Fossil SCM

Merge the all the latest trunk enhancements into the http1-1-chunked branch.

drh 2026-07-25 08:44 UTC http1-1-chunked merge
Commit a5f61586b7493c3d5298a4a16edf269c2fa09967f483d58b7e924b2c15e0fba4
+1 -1
--- auto.def
+++ auto.def
@@ -36,11 +36,11 @@
3636
}
3737
3838
# Update the minimum required SQLite version number here, and also
3939
# in src/main.c near the sqlite3_libversion_number() call. Take care
4040
# that both places agree!
41
-define MINIMUM_SQLITE_VERSION "3.49.0"
41
+define MINIMUM_SQLITE_VERSION "3.54.0"
4242
4343
# This is useful for people wanting Fossil to use an external SQLite library
4444
# to compare the one they have against the minimum required
4545
if {[opt-bool print-minimum-sqlite-version]} {
4646
puts [get-define MINIMUM_SQLITE_VERSION]
4747
--- auto.def
+++ auto.def
@@ -36,11 +36,11 @@
36 }
37
38 # Update the minimum required SQLite version number here, and also
39 # in src/main.c near the sqlite3_libversion_number() call. Take care
40 # that both places agree!
41 define MINIMUM_SQLITE_VERSION "3.49.0"
42
43 # This is useful for people wanting Fossil to use an external SQLite library
44 # to compare the one they have against the minimum required
45 if {[opt-bool print-minimum-sqlite-version]} {
46 puts [get-define MINIMUM_SQLITE_VERSION]
47
--- auto.def
+++ auto.def
@@ -36,11 +36,11 @@
36 }
37
38 # Update the minimum required SQLite version number here, and also
39 # in src/main.c near the sqlite3_libversion_number() call. Take care
40 # that both places agree!
41 define MINIMUM_SQLITE_VERSION "3.54.0"
42
43 # This is useful for people wanting Fossil to use an external SQLite library
44 # to compare the one they have against the minimum required
45 if {[opt-bool print-minimum-sqlite-version]} {
46 puts [get-define MINIMUM_SQLITE_VERSION]
47
+8 -1
--- extsrc/qrf.h
+++ extsrc/qrf.h
@@ -55,10 +55,12 @@
5555
char *(*xRender)(void*,sqlite3_value*); /* Render a value */
5656
int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
5757
void *pRenderArg; /* First argument to the xRender callback */
5858
void *pWriteArg; /* First argument to the xWrite callback */
5959
char **pzOutput; /* Storage location for output string */
60
+ /* The following are available in iVersion 2 and later */
61
+ unsigned char bRowCount; /* Show the number of rows at end of each query */
6062
/* Additional fields may be added in the future */
6163
};
6264
6365
/*
6466
** Interfaces
@@ -83,11 +85,11 @@
8385
#define QRF_STYLE_Column 2 /* One record per line in neat columns */
8486
#define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
8587
#define QRF_STYLE_Csv 4 /* Comma-separated-value */
8688
#define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
8789
#define QRF_STYLE_Explain 6 /* EXPLAIN output */
88
-#define QRF_STYLE_Html 7 /* Generate an XHTML table */
90
+#define QRF_STYLE_Html 7 /* Generate HTML-style <tr><td> output */
8991
#define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
9092
#define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
9193
#define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
9294
#define QRF_STYLE_Line 11 /* One column per line. */
9395
#define QRF_STYLE_List 12 /* One record per line with a separator */
@@ -143,10 +145,15 @@
143145
#define QRF_SW_On 2 /* This setting is forced on */
144146
#define QRF_Auto 0 /* Alternate spelling for QRF_*_Auto */
145147
#define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
146148
#define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
147149
150
+/*
151
+** Additional value allowed for bTitles
152
+*/
153
+#define QRF_Always 3 /* Always show titles, even if no rows */
154
+
148155
/*
149156
** Possible alignment values alignment settings
150157
**
151158
** Horizontal Vertial
152159
** ---------- -------- */
153160
--- extsrc/qrf.h
+++ extsrc/qrf.h
@@ -55,10 +55,12 @@
55 char *(*xRender)(void*,sqlite3_value*); /* Render a value */
56 int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
57 void *pRenderArg; /* First argument to the xRender callback */
58 void *pWriteArg; /* First argument to the xWrite callback */
59 char **pzOutput; /* Storage location for output string */
 
 
60 /* Additional fields may be added in the future */
61 };
62
63 /*
64 ** Interfaces
@@ -83,11 +85,11 @@
83 #define QRF_STYLE_Column 2 /* One record per line in neat columns */
84 #define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
85 #define QRF_STYLE_Csv 4 /* Comma-separated-value */
86 #define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
87 #define QRF_STYLE_Explain 6 /* EXPLAIN output */
88 #define QRF_STYLE_Html 7 /* Generate an XHTML table */
89 #define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
90 #define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
91 #define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
92 #define QRF_STYLE_Line 11 /* One column per line. */
93 #define QRF_STYLE_List 12 /* One record per line with a separator */
@@ -143,10 +145,15 @@
143 #define QRF_SW_On 2 /* This setting is forced on */
144 #define QRF_Auto 0 /* Alternate spelling for QRF_*_Auto */
145 #define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
146 #define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
147
 
 
 
 
 
148 /*
149 ** Possible alignment values alignment settings
150 **
151 ** Horizontal Vertial
152 ** ---------- -------- */
153
--- extsrc/qrf.h
+++ extsrc/qrf.h
@@ -55,10 +55,12 @@
55 char *(*xRender)(void*,sqlite3_value*); /* Render a value */
56 int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
57 void *pRenderArg; /* First argument to the xRender callback */
58 void *pWriteArg; /* First argument to the xWrite callback */
59 char **pzOutput; /* Storage location for output string */
60 /* The following are available in iVersion 2 and later */
61 unsigned char bRowCount; /* Show the number of rows at end of each query */
62 /* Additional fields may be added in the future */
63 };
64
65 /*
66 ** Interfaces
@@ -83,11 +85,11 @@
85 #define QRF_STYLE_Column 2 /* One record per line in neat columns */
86 #define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
87 #define QRF_STYLE_Csv 4 /* Comma-separated-value */
88 #define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
89 #define QRF_STYLE_Explain 6 /* EXPLAIN output */
90 #define QRF_STYLE_Html 7 /* Generate HTML-style <tr><td> output */
91 #define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
92 #define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
93 #define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
94 #define QRF_STYLE_Line 11 /* One column per line. */
95 #define QRF_STYLE_List 12 /* One record per line with a separator */
@@ -143,10 +145,15 @@
145 #define QRF_SW_On 2 /* This setting is forced on */
146 #define QRF_Auto 0 /* Alternate spelling for QRF_*_Auto */
147 #define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
148 #define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
149
150 /*
151 ** Additional value allowed for bTitles
152 */
153 #define QRF_Always 3 /* Always show titles, even if no rows */
154
155 /*
156 ** Possible alignment values alignment settings
157 **
158 ** Horizontal Vertial
159 ** ---------- -------- */
160
+532 -139
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -23,10 +23,11 @@
2323
** ext/misc/shathree.c
2424
** ext/misc/sqlar.c
2525
** ext/misc/sqlite3_stdio.c
2626
** ext/misc/sqlite3_stdio.h
2727
** ext/misc/stmtrand.c
28
+** ext/misc/strdup.c
2829
** ext/misc/uint.c
2930
** ext/misc/vfstrace.c
3031
** ext/misc/windirent.h
3132
** ext/misc/zipfile.c
3233
** ext/qrf/qrf.c
@@ -205,28 +206,38 @@
205206
# define shell_add_history(X) add_history(X)
206207
# define shell_read_history(X) read_history(X)
207208
# define shell_write_history(X) write_history(X)
208209
# define shell_stifle_history(X) stifle_history(X)
209210
# define shell_readline(X) readline(X)
211
+# define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */
210212
211213
#elif HAVE_LINENOISE
212214
213215
# include "linenoise.h"
214216
# define shell_add_history(X) linenoiseHistoryAdd(X)
215217
# define shell_read_history(X) linenoiseHistoryLoad(X)
216218
# define shell_write_history(X) linenoiseHistorySave(X)
217219
# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
218220
# define shell_readline(X) linenoise(X)
221
+# define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */
219222
220223
#else
221224
222225
# define shell_read_history(X)
223226
# define shell_write_history(X)
224227
# define shell_stifle_history(X)
228
+# define SHELL_CMDLINE_EDIT_AVAILABLE 0 /* command-line editing not available */
229
+#endif
225230
226
-# define SHELL_USE_LOCAL_GETLINE 1
227
-#endif
231
+/*
232
+** Global variable shellCmdLineEdit determines whether or not command-line
233
+** editing is enabled. It defaults to 1 if the CLI is linked against a
234
+** command-line editing library (linenoise, readline, or editline) and
235
+** to 0 if no command-line editing library is available. The
236
+** "--cmdline-edit off" command-line option will change this value to 0.
237
+*/
238
+static int shellCmdLineEdit = SHELL_CMDLINE_EDIT_AVAILABLE;
228239
229240
#ifndef deliberate_fall_through
230241
/* Quiet some compilers about some of our intentional code. */
231242
# if defined(GCC_VERSION) && GCC_VERSION>=7000000
232243
# define deliberate_fall_through __attribute__((fallthrough));
@@ -733,10 +744,12 @@
733744
char *(*xRender)(void*,sqlite3_value*); /* Render a value */
734745
int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
735746
void *pRenderArg; /* First argument to the xRender callback */
736747
void *pWriteArg; /* First argument to the xWrite callback */
737748
char **pzOutput; /* Storage location for output string */
749
+ /* The following are available in iVersion 2 and later */
750
+ unsigned char bRowCount; /* Show the number of rows at end of each query */
738751
/* Additional fields may be added in the future */
739752
};
740753
741754
/*
742755
** Interfaces
@@ -761,11 +774,11 @@
761774
#define QRF_STYLE_Column 2 /* One record per line in neat columns */
762775
#define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
763776
#define QRF_STYLE_Csv 4 /* Comma-separated-value */
764777
#define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
765778
#define QRF_STYLE_Explain 6 /* EXPLAIN output */
766
-#define QRF_STYLE_Html 7 /* Generate an XHTML table */
779
+#define QRF_STYLE_Html 7 /* Generate HTML-style <tr><td> output */
767780
#define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
768781
#define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
769782
#define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
770783
#define QRF_STYLE_Line 11 /* One column per line. */
771784
#define QRF_STYLE_List 12 /* One record per line with a separator */
@@ -821,10 +834,15 @@
821834
#define QRF_SW_On 2 /* This setting is forced on */
822835
#define QRF_Auto 0 /* Alternate spelling for QRF_*_Auto */
823836
#define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
824837
#define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
825838
839
+/*
840
+** Additional value allowed for bTitles
841
+*/
842
+#define QRF_Always 3 /* Always show titles, even if no rows */
843
+
826844
/*
827845
** Possible alignment values alignment settings
828846
**
829847
** Horizontal Vertial
830848
** ---------- -------- */
@@ -2527,10 +2545,14 @@
25272545
/* Doubled horizontal lines: */
25282546
#define DBL_24 "\342\225\220" /* U+2550 === */
25292547
#define DBL_123 "\342\225\236" /* U+255e |= */
25302548
#define DBL_134 "\342\225\241" /* U+2561 =| */
25312549
#define DBL_1234 "\342\225\252" /* U+256a =|= */
2550
+#define DBL_12 "\342\225\230" /* U+2558 `= */
2551
+#define DBL_14 "\342\225\233" /* U+255b =' */
2552
+#define DBL_124 "\342\225\247" /* U+2567 ='= */
2553
+
25322554
25332555
/* Draw horizontal line N characters long using unicode box
25342556
** characters
25352557
*/
25362558
static void qrfBoxLine(sqlite3_str *pOut, int N, int bDbl){
@@ -2549,16 +2571,16 @@
25492571
25502572
/*
25512573
** Draw a horizontal separator for a QRF_STYLE_Box table.
25522574
*/
25532575
static void qrfBoxSeparator(
2554
- sqlite3_str *pOut,
2555
- qrfColData *p,
2556
- const char *zSep1,
2557
- const char *zSep2,
2558
- const char *zSep3,
2559
- int bDbl
2576
+ sqlite3_str *pOut, /* Output to this sqlite3_str */
2577
+ qrfColData *p, /* Columnar data */
2578
+ const char *zSep1, /* Left margin */
2579
+ const char *zSep2, /* Column separator */
2580
+ const char *zSep3, /* Right margin */
2581
+ int bDbl /* True for double-lines */
25602582
){
25612583
int i;
25622584
if( p->nCol>0 ){
25632585
int useBorder = p->p->spec.bBorder!=QRF_No;
25642586
if( useBorder ){
@@ -2573,10 +2595,36 @@
25732595
sqlite3_str_appendall(pOut, zSep3);
25742596
}
25752597
}
25762598
sqlite3_str_append(pOut, "\n", 1);
25772599
}
2600
+
2601
+/*
2602
+** Draw a horizontal separator for a QRF_STYLE_Column table.
2603
+** This style of separator is only used for separating the title
2604
+** from the content.
2605
+*/
2606
+static void qrfColumnSeparator(
2607
+ sqlite3_str *pOut, /* Output to this sqlite3_str */
2608
+ qrfColData *p, /* Columnar data */
2609
+ const char *colSep, /* Column separator text */
2610
+ int szColSep, /* Size of zColSep in bytes */
2611
+ const char *rowSep, /* Row separator text */
2612
+ int szRowSep /* Size of zRowSep in bytes */
2613
+){
2614
+ int j;
2615
+ int nColumn = p->nCol;
2616
+ for(j=0; j<nColumn; j++){
2617
+ sqlite3_str_appendchar(pOut, p->a[j].w, '-');
2618
+ if( j<nColumn-1 ){
2619
+ sqlite3_str_append(pOut, colSep, szColSep);
2620
+ }else{
2621
+ qrfRTrim(pOut);
2622
+ sqlite3_str_append(pOut, rowSep, szRowSep);
2623
+ }
2624
+ }
2625
+}
25782626
25792627
/*
25802628
** Load into pData the default alignment for the body of a table.
25812629
*/
25822630
static void qrfLoadAlignment(qrfColData *pData, Qrf *p){
@@ -2831,11 +2879,25 @@
28312879
sqlite3_str *pStr; /* Temporary rendering */
28322880
qrfColData data; /* Columnar layout data */
28332881
int bRTrim; /* Trim trailing space */
28342882
28352883
rc = sqlite3_step(p->pStmt);
2836
- if( rc!=SQLITE_ROW || nColumn==0 ){
2884
+ if( nColumn==0 ){
2885
+ return; /* Not a query. No results every shown. */
2886
+ }
2887
+ if( rc==SQLITE_DONE && nColumn>0 ){
2888
+ /* Empty query */
2889
+ if( p->spec.bTitles==QRF_Always ){
2890
+ /* fall through into the columnar logic below */
2891
+ }else{
2892
+ if( p->spec.bRowCount==QRF_Yes ){
2893
+ sqlite3_str_appendf(p->pOut, "(0 rows)\n");
2894
+ qrfWrite(p);
2895
+ }
2896
+ return; /* No output, other than the row count */
2897
+ }
2898
+ }else if( rc!=SQLITE_ROW ){
28372899
return; /* No output */
28382900
}
28392901
28402902
/* Initialize the data container */
28412903
memset(&data, 0, sizeof(data));
@@ -2848,12 +2910,12 @@
28482910
}
28492911
memset(data.a, 0, nColumn*sizeof(struct qrfPerCol) );
28502912
if( qrfColDataEnlarge(&data) ) return;
28512913
assert( data.az!=0 );
28522914
2853
- /* Load the column header names and all cell content into data */
2854
- if( p->spec.bTitles==QRF_Yes ){
2915
+ /* Load the column header names into data */
2916
+ if( p->spec.bTitles>=QRF_Yes ){
28552917
unsigned char saved_eText = p->spec.eText;
28562918
p->spec.eText = p->spec.eTitle;
28572919
memset(data.abNum, 0, nColumn);
28582920
for(i=0; i<nColumn; i++){
28592921
const char *z = (const char*)sqlite3_column_name(p->pStmt,i);
@@ -2874,13 +2936,14 @@
28742936
data.n++;
28752937
if( w>data.a[i].mxW ) data.a[i].mxW = w;
28762938
if( nNL ) data.bMultiRow = 1;
28772939
}
28782940
p->spec.eText = saved_eText;
2879
- p->nRow++;
28802941
}
2881
- do{
2942
+
2943
+ /* Load query results into data */
2944
+ while( rc==SQLITE_ROW && p->iErr==SQLITE_OK ){
28822945
if( data.n+nColumn > data.nAlloc ){
28832946
if( qrfColDataEnlarge(&data) ) return;
28842947
}
28852948
for(i=0; i<nColumn; i++){
28862949
char *z;
@@ -2897,11 +2960,12 @@
28972960
data.n++;
28982961
if( w>data.a[i].mxW ) data.a[i].mxW = w;
28992962
if( nNL ) data.bMultiRow = 1;
29002963
}
29012964
p->nRow++;
2902
- }while( sqlite3_step(p->pStmt)==SQLITE_ROW && p->iErr==SQLITE_OK );
2965
+ rc = sqlite3_step(p->pStmt);
2966
+ }
29032967
if( p->iErr ){
29042968
qrfColDataFree(&data);
29052969
return;
29062970
}
29072971
@@ -3105,11 +3169,11 @@
31053169
/* Draw either (1) the separator between the title line and the body
31063170
** of the table, or (2) separators between individual rows of the table
31073171
** body. isTitleDataSeparator will be true if we are doing (1).
31083172
*/
31093173
if( (i==0 || data.bMultiRow) && i+nColumn<data.n ){
3110
- int isTitleDataSeparator = (i==0 && p->spec.bTitles==QRF_Yes);
3174
+ int isTitleDataSeparator = (i==0 && p->spec.bTitles>=QRF_Yes);
31113175
if( isTitleDataSeparator ){
31123176
qrfLoadAlignment(&data, p);
31133177
}
31143178
switch( p->spec.eStyle ){
31153179
case QRF_STYLE_Table: {
@@ -3132,19 +3196,12 @@
31323196
}
31333197
break;
31343198
}
31353199
case QRF_STYLE_Column: {
31363200
if( isTitleDataSeparator ){
3137
- for(j=0; j<nColumn; j++){
3138
- sqlite3_str_appendchar(p->pOut, data.a[j].w, '-');
3139
- if( j<nColumn-1 ){
3140
- sqlite3_str_append(p->pOut, colSep, szColSep);
3141
- }else{
3142
- qrfRTrim(p->pOut);
3143
- sqlite3_str_append(p->pOut, rowSep, szRowSep);
3144
- }
3145
- }
3201
+ qrfColumnSeparator(p->pOut, &data, colSep, szColSep,
3202
+ rowSep, szRowSep);
31463203
}else if( data.bMultiRow ){
31473204
qrfRTrim(p->pOut);
31483205
sqlite3_str_append(p->pOut, "\n", 1);
31493206
}
31503207
break;
@@ -3152,20 +3209,39 @@
31523209
}
31533210
}
31543211
}
31553212
31563213
/* Draw the line across the bottom of the table */
3157
- if( p->spec.bBorder!=QRF_No ){
3214
+ if( p->spec.bBorder!=QRF_No || p->nRow==0 ){
31583215
switch( p->spec.eStyle ){
31593216
case QRF_STYLE_Box:
3160
- qrfBoxSeparator(p->pOut, &data, BOX_R12, BOX_124, BOX_R14, 0);
3217
+ if( p->nRow>0 ){
3218
+ qrfBoxSeparator(p->pOut, &data, BOX_R12, BOX_124, BOX_R14, 0);
3219
+ }else{
3220
+ qrfBoxSeparator(p->pOut, &data, DBL_12, DBL_124, DBL_14, 1);
3221
+ }
31613222
break;
31623223
case QRF_STYLE_Table:
31633224
qrfRowSeparator(p->pOut, &data, '+');
31643225
break;
3226
+ case QRF_STYLE_Markdown:
3227
+ if( p->nRow==0 ){
3228
+ qrfRowSeparator(p->pOut, &data, '|');
3229
+ }
3230
+ break;
3231
+ case QRF_STYLE_Column:
3232
+ if( p->nRow==0 ){
3233
+ qrfColumnSeparator(p->pOut, &data, colSep, szColSep,
3234
+ rowSep, szRowSep);
3235
+ }
3236
+ break;
31653237
}
31663238
}
3239
+ if( p->spec.bRowCount==QRF_Yes ){
3240
+ sqlite3_int64 n = p->nRow;
3241
+ sqlite3_str_appendf(p->pOut, "(%lld row%s)\n", n, n==1 ? "" : "s");
3242
+ }
31673243
qrfWrite(p);
31683244
31693245
qrfColDataFree(&data);
31703246
return;
31713247
}
@@ -3412,10 +3488,49 @@
34123488
sqlite3_str_append(p->pOut, ":", 1);
34133489
qrfRenderValue(p, p->pOut, i);
34143490
}
34153491
qrfWrite(p);
34163492
}
3493
+
3494
+/*
3495
+** Render a title row (a row containing column names) if the spec
3496
+** calls for one and if it makes sense for the eStyle. Title rows
3497
+** do not make sense for some eStyles, such as QRF_STYLE_Off,
3498
+** QRF_STYLE_Count, QRF_STYLE_Json, and similar.
3499
+*/
3500
+static void qrfSimpleTitle(Qrf *p){
3501
+ assert( p->nRow==0 );
3502
+ assert( p->spec.bTitles>=QRF_Yes );
3503
+ switch( p->spec.eStyle ){
3504
+ case QRF_STYLE_Html: {
3505
+ int i;
3506
+ sqlite3_str_append(p->pOut, "<tr>", 4);
3507
+ for(i=0; i<p->nCol; i++){
3508
+ const char *zCName = sqlite3_column_name(p->pStmt, i);
3509
+ sqlite3_str_append(p->pOut, "\n<th>", 5);
3510
+ qrfEncodeText(p, p->pOut, zCName);
3511
+ }
3512
+ sqlite3_str_append(p->pOut, "\n</tr>\n", 7);
3513
+ break;
3514
+ }
3515
+ case QRF_STYLE_Quote:
3516
+ case QRF_STYLE_List: {
3517
+ int i;
3518
+ int saved_eText = p->spec.eText;
3519
+ p->spec.eText = p->spec.eTitle;
3520
+ for(i=0; i<p->nCol; i++){
3521
+ const char *zCName = sqlite3_column_name(p->pStmt, i);
3522
+ if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
3523
+ qrfEncodeText(p, p->pOut, zCName);
3524
+ }
3525
+ sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
3526
+ qrfWrite(p);
3527
+ p->spec.eText = saved_eText;
3528
+ break;
3529
+ }
3530
+ }
3531
+}
34173532
34183533
/*
34193534
** Render a single row of output for non-columnar styles - any
34203535
** style that lets us render row by row as the content is received
34213536
** from the query.
@@ -3445,25 +3560,19 @@
34453560
}
34463561
qrfOneJsonRow(p);
34473562
break;
34483563
}
34493564
case QRF_STYLE_Html: {
3450
- if( p->nRow==0 && p->spec.bTitles==QRF_Yes ){
3451
- sqlite3_str_append(p->pOut, "<TR>", 4);
3452
- for(i=0; i<p->nCol; i++){
3453
- const char *zCName = sqlite3_column_name(p->pStmt, i);
3454
- sqlite3_str_append(p->pOut, "\n<TH>", 5);
3455
- qrfEncodeText(p, p->pOut, zCName);
3456
- }
3457
- sqlite3_str_append(p->pOut, "\n</TR>\n", 7);
3458
- }
3459
- sqlite3_str_append(p->pOut, "<TR>", 4);
3460
- for(i=0; i<p->nCol; i++){
3461
- sqlite3_str_append(p->pOut, "\n<TD>", 5);
3565
+ if( p->nRow==0 && p->spec.bTitles>=QRF_Yes ){
3566
+ qrfSimpleTitle(p);
3567
+ }
3568
+ sqlite3_str_append(p->pOut, "<tr>", 4);
3569
+ for(i=0; i<p->nCol; i++){
3570
+ sqlite3_str_append(p->pOut, "\n<td>", 5);
34623571
qrfRenderValue(p, p->pOut, i);
34633572
}
3464
- sqlite3_str_append(p->pOut, "\n</TR>\n", 7);
3573
+ sqlite3_str_append(p->pOut, "\n</tr>\n", 7);
34653574
qrfWrite(p);
34663575
break;
34673576
}
34683577
case QRF_STYLE_Insert: {
34693578
unsigned int mxIns = p->spec.nMultiInsert;
@@ -3476,11 +3585,11 @@
34763585
if( qrf_need_quote(p->spec.zTableName) ){
34773586
sqlite3_str_appendf(p->pOut,"INSERT INTO \"%w\"",p->spec.zTableName);
34783587
}else{
34793588
sqlite3_str_appendf(p->pOut,"INSERT INTO %s",p->spec.zTableName);
34803589
}
3481
- if( p->spec.bTitles==QRF_Yes ){
3590
+ if( p->spec.bTitles>=QRF_Yes ){
34823591
for(i=0; i<p->nCol; i++){
34833592
const char *zCName = sqlite3_column_name(p->pStmt, i);
34843593
if( qrf_need_quote(zCName) ){
34853594
sqlite3_str_appendf(p->pOut, "%c\"%w\"",
34863595
i==0 ? '(' : ',', zCName);
@@ -3576,21 +3685,12 @@
35763685
if( zEqpLine[0]=='-' ) qrfEqpRender(p, 0);
35773686
qrfEqpAppend(p, iEqpId, iParentId, zEqpLine);
35783687
break;
35793688
}
35803689
default: { /* QRF_STYLE_List */
3581
- if( p->nRow==0 && p->spec.bTitles==QRF_Yes ){
3582
- int saved_eText = p->spec.eText;
3583
- p->spec.eText = p->spec.eTitle;
3584
- for(i=0; i<p->nCol; i++){
3585
- const char *zCName = sqlite3_column_name(p->pStmt, i);
3586
- if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
3587
- qrfEncodeText(p, p->pOut, zCName);
3588
- }
3589
- sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
3590
- qrfWrite(p);
3591
- p->spec.eText = saved_eText;
3690
+ if( p->nRow==0 && p->spec.bTitles>=QRF_Yes ){
3691
+ qrfSimpleTitle(p);
35923692
}
35933693
for(i=0; i<p->nCol; i++){
35943694
if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
35953695
qrfRenderValue(p, p->pOut, i);
35963696
}
@@ -3612,11 +3712,11 @@
36123712
char **pzErr /* Write errors here */
36133713
){
36143714
size_t sz; /* Size of pSpec[], based on pSpec->iVersion */
36153715
memset(p, 0, sizeof(*p));
36163716
p->pzErr = pzErr;
3617
- if( pSpec->iVersion>1 ){
3717
+ if( pSpec->iVersion>2 ){
36183718
qrfError(p, SQLITE_ERROR,
36193719
"unusable sqlite3_qrf_spec.iVersion (%d)",
36203720
pSpec->iVersion);
36213721
return;
36223722
}
@@ -3640,10 +3740,13 @@
36403740
if( p->spec.eStyle>QRF_STYLE_Table ) p->spec.eStyle = QRF_Auto;
36413741
if( p->spec.eEsc>QRF_ESC_Symbol ) p->spec.eEsc = QRF_Auto;
36423742
if( p->spec.eText>QRF_TEXT_Relaxed ) p->spec.eText = QRF_Auto;
36433743
if( p->spec.eTitle>QRF_TEXT_Relaxed ) p->spec.eTitle = QRF_Auto;
36443744
if( p->spec.eBlob>QRF_BLOB_Size ) p->spec.eBlob = QRF_Auto;
3745
+ if( pSpec->iVersion<=1 ){
3746
+ p->spec.bRowCount = 0;
3747
+ }
36453748
qrf_reinit:
36463749
switch( p->spec.eStyle ){
36473750
case QRF_Auto: {
36483751
switch( sqlite3_stmt_isexplain(pStmt) ){
36493752
case 0: p->spec.eStyle = QRF_STYLE_Box; break;
@@ -3898,10 +4001,34 @@
38984001
default: {
38994002
/* Non-columnar modes where the output can occur after each row
39004003
** of result is received */
39014004
while( qrf.iErr==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
39024005
qrfOneSimpleRow(&qrf);
4006
+ }
4007
+ if( qrf.nCol>0 && qrf.nRow==0 && qrf.spec.bTitles==QRF_Always ){
4008
+ qrfSimpleTitle(&qrf);
4009
+ }
4010
+ if( qrf.nCol>0 && qrf.spec.bRowCount==QRF_Yes ){
4011
+ const char *zPlural = qrf.nRow==1 ? "" : "s";
4012
+ switch( qrf.spec.eStyle ){
4013
+ case QRF_STYLE_Line:
4014
+ if( qrf.nRow>0 ) sqlite3_str_append(qrf.pOut, "\n", 1);
4015
+ /* Fall through */
4016
+ case QRF_STYLE_Csv:
4017
+ case QRF_STYLE_List:
4018
+ case QRF_STYLE_Quote:
4019
+ sqlite3_str_appendf(qrf.pOut,"(%lld row%s)\n",qrf.nRow,zPlural);
4020
+ break;
4021
+ case QRF_STYLE_Html:
4022
+ sqlite3_str_appendf(qrf.pOut,"<!-- %lld row%s -->\n",
4023
+ qrf.nRow, zPlural);
4024
+ break;
4025
+ case QRF_STYLE_Insert:
4026
+ sqlite3_str_appendf(qrf.pOut,"/* %lld row%s inserted */\n",
4027
+ qrf.nRow, zPlural);
4028
+ break;
4029
+ }
39034030
}
39044031
break;
39054032
}
39064033
}
39074034
qrfResetStmt(&qrf);
@@ -5839,10 +5966,13 @@
58395966
}
58405967
58415968
/*
58425969
** Allocate a new Decimal object initialized to the text in zIn[].
58435970
** Return NULL if any kind of error occurs.
5971
+**
5972
+** Note that zIn[] is not necessarily zero-terminated. Always
5973
+** respect the boundary imposed by the n argument.
58445974
*/
58455975
static Decimal *decimalNewFromText(const char *zIn, int n){
58465976
Decimal *p = 0;
58475977
int i;
58485978
int iExp = 0;
@@ -5856,15 +5986,15 @@
58565986
p->isNull = 0;
58575987
p->nDigit = 0;
58585988
p->nFrac = 0;
58595989
p->a = sqlite3_malloc64( n+1 );
58605990
if( p->a==0 ) goto new_from_text_failed;
5861
- for(i=0; IsSpace(zIn[i]); i++){}
5862
- if( zIn[i]=='-' ){
5991
+ for(i=0; i<n && IsSpace(zIn[i]); i++){}
5992
+ if( i<n && zIn[i]=='-' ){
58635993
p->sign = 1;
58645994
i++;
5865
- }else if( zIn[i]=='+' ){
5995
+ }else if( i<n && zIn[i]=='+' ){
58665996
i++;
58675997
}
58685998
while( i<n && zIn[i]=='0' ) i++;
58695999
while( i<n ){
58706000
char c = zIn[i];
@@ -6091,11 +6221,11 @@
60916221
if( p->a[N]>=5 ){
60926222
/* If all leading digits are 9, increase the number of digits
60936223
** by adding a new 0 to the front */
60946224
for(i=0; i<N && p->a[i]==9; i++){}
60956225
if( i==N ){
6096
- decimal_expand(p, p->nDigit+1, 0);
6226
+ decimal_expand(p, p->nDigit+1, p->nFrac);
60976227
if( p->oom ) return;
60986228
}
60996229
61006230
/* Do the rounding */
61016231
p->a[N-1]++;
@@ -6249,10 +6379,11 @@
62496379
int nAddSig;
62506380
int nAddFrac;
62516381
signed char *a;
62526382
if( p==0 ) return;
62536383
nAddFrac = nFrac - p->nFrac;
6384
+ assert( nAddFrac>=0 );
62546385
nAddSig = (nDigit - p->nDigit) - nAddFrac;
62556386
if( nAddFrac==0 && nAddSig==0 ) return;
62566387
if( nDigit+1>SQLITE_DECIMAL_MAX_DIGIT ){ p->oom = 1; return; }
62576388
a = sqlite3_realloc64(p->a, nDigit+1);
62586389
if( a==0 ){
@@ -8256,10 +8387,20 @@
82568387
if( r==(double)x ) return r;
82578388
if( r<(double)x ) x--;
82588389
return (double)x;
82598390
}
82608391
#endif
8392
+
8393
+/* Convert a floating point value to its closest integer. Do so in
8394
+** a way that avoids 'outside the range of representable values' warnings
8395
+** from UBSAN.
8396
+*/
8397
+static sqlite3_int64 seriesRealToI64(double r){
8398
+ if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
8399
+ if( r>+9223372036854774784.0 ) return LARGEST_INT64;
8400
+ return (sqlite3_int64)r;
8401
+}
82618402
82628403
/*
82638404
** This method is called to "rewind" the series_cursor object back
82648405
** to the first row of output. This method is always called at least
82658406
** once prior to any call to seriesColumn() or seriesRowid() or
@@ -8379,11 +8520,11 @@
83798520
double r = sqlite3_value_double(argv[iArg++]);
83808521
if( r==seriesCeil(r)
83818522
&& r>=(double)SMALLEST_INT64
83828523
&& r<=(double)LARGEST_INT64
83838524
){
8384
- iMin = iMax = (sqlite3_int64)r;
8525
+ iMin = iMax = seriesRealToI64(r);
83858526
}else{
83868527
goto series_no_rows;
83878528
}
83888529
}else{
83898530
iMin = iMax = sqlite3_value_int64(argv[iArg++]);
@@ -8395,14 +8536,11 @@
83958536
if( r<=(double)SMALLEST_INT64 ){
83968537
iMin = SMALLEST_INT64;
83978538
}else if( r>(double)LARGEST_INT64 ){
83988539
goto series_no_rows;
83998540
}else{
8400
- iMin = (sqlite3_int64)seriesCeil(r);
8401
- if( iMin<0 && r>0.0 ){
8402
- iMin = LARGEST_INT64;
8403
- }
8541
+ iMin = seriesRealToI64(seriesCeil(r));
84048542
if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
84058543
if( iMin==LARGEST_INT64 ) goto series_no_rows;
84068544
iMin++;
84078545
}
84088546
}
@@ -8423,14 +8561,12 @@
84238561
if( r>=(double)LARGEST_INT64 ){
84248562
iMax = LARGEST_INT64;
84258563
}else if( r<=(double)SMALLEST_INT64 ){
84268564
goto series_no_rows;
84278565
}else{
8428
- iMax = (sqlite3_int64)seriesFloor(r);
8429
- if( iMax<0 && r>0.0 ){
8430
- iMax = LARGEST_INT64;
8431
- }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8566
+ iMax = seriesRealToI64(seriesFloor(r));
8567
+ if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
84328568
if( iMax==SMALLEST_INT64 ) goto series_no_rows;
84338569
iMax--;
84348570
}
84358571
}
84368572
}else{
@@ -10593,11 +10729,15 @@
1059310729
sqlite3_result_error_nomem(ctx);
1059410730
return SQLITE_NOMEM;
1059510731
}
1059610732
}
1059710733
10598
- sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
10734
+ if( n>0 ){
10735
+ sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
10736
+ }else{
10737
+ sqlite3_result_null(ctx);
10738
+ }
1059910739
if( aBuf!=aStatic ) sqlite3_free(aBuf);
1060010740
#endif
1060110741
}else{
1060210742
readFileContents(ctx, pCur->zPath);
1060310743
}
@@ -14457,11 +14597,11 @@
1445714597
eocd.nEntry = (u16)p->nEntry;
1445814598
eocd.nEntryTotal = (u16)p->nEntry;
1445914599
eocd.nSize = p->cds.n;
1446014600
eocd.iOffset = p->body.n;
1446114601
14462
- nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
14602
+ nZip = (i64)p->body.n + (i64)p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
1446314603
aZip = (u8*)sqlite3_malloc64(nZip);
1446414604
if( aZip==0 ){
1446514605
sqlite3_result_error_nomem(pCtx);
1446614606
}else{
1446714607
memcpy(aZip, p->body.a, p->body.n);
@@ -17584,16 +17724,19 @@
1758417724
}
1758517725
iRet++;
1758617726
}
1758717727
}
1758817728
else if( c=='[' ){
17589
- while( z[iRet++]!=']' && z[iRet] );
17729
+ while( z[iRet] && z[iRet++]!=']' ){}
1759017730
}
1759117731
else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
1759217732
while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
1759317733
iRet++;
1759417734
}
17735
+ }
17736
+ else if( c==0 ){
17737
+ iRet = 0;
1759517738
}
1759617739
1759717740
return iRet;
1759817741
}
1759917742
@@ -18030,10 +18173,27 @@
1803018173
intckFinalize(p, pStmt);
1803118174
1803218175
if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
1803318176
return zRet;
1803418177
}
18178
+
18179
+/*
18180
+** Register or unregister special SQL functions implemented by intck.
18181
+**
18182
+** Normally the custom SQL functions used by intck are only available
18183
+** in between sqlite3_intck_open() and sqlite3_intck_close(). However,
18184
+** for testing and debugging, it is sometimes useful to make those
18185
+** functions available generally. This routine provides as a separate
18186
+** interface in order to provide that capability.
18187
+*/
18188
+int sqlite3_intck_register(sqlite3 *db, int bCreate){
18189
+ int rc;
18190
+ rc = sqlite3_create_function(db, "parse_create_index",
18191
+ 2, SQLITE_UTF8, 0, bCreate ? intckParseCreateIndexFunc : 0, 0, 0
18192
+ );
18193
+ return rc;
18194
+}
1803518195
1803618196
/*
1803718197
** Open a new integrity-check object.
1803818198
*/
1803918199
int sqlite3_intck_open(
@@ -18052,13 +18212,11 @@
1805218212
}else{
1805318213
memset(pNew, 0, sizeof(*pNew));
1805418214
pNew->db = db;
1805518215
pNew->zDb = (const char*)&pNew[1];
1805618216
memcpy(&pNew[1], zDb, nDb+1);
18057
- rc = sqlite3_create_function(db, "parse_create_index",
18058
- 2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0
18059
- );
18217
+ rc = sqlite3_intck_register(db, 1);
1806018218
if( rc!=SQLITE_OK ){
1806118219
sqlite3_intck_close(pNew);
1806218220
pNew = 0;
1806318221
}
1806418222
}
@@ -18071,13 +18229,11 @@
1807118229
** Free the integrity-check object.
1807218230
*/
1807318231
void sqlite3_intck_close(sqlite3_intck *p){
1807418232
if( p ){
1807518233
sqlite3_finalize(p->pCheck);
18076
- sqlite3_create_function(
18077
- p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0
18078
- );
18234
+ sqlite3_intck_register(p->db, 0);
1807918235
sqlite3_free(p->zObj);
1808018236
sqlite3_free(p->zKey);
1808118237
sqlite3_free(p->zTestSql);
1808218238
sqlite3_free(p->zErr);
1808318239
sqlite3_free(p->zMessage);
@@ -20355,16 +20511,128 @@
2035520511
){
2035620512
int rc = SQLITE_OK;
2035720513
SQLITE_EXTENSION_INIT2(pApi);
2035820514
(void)pzErrMsg; /* Unused parameter */
2035920515
rc = sqlite3_create_function(db, "diskused", 1,
20360
- SQLITE_UTF8|SQLITE_INNOCUOUS,
20516
+ SQLITE_UTF8|SQLITE_DIRECTONLY,
2036120517
0, diskusedFunc, 0, 0);
2036220518
return rc;
2036320519
}
2036420520
2036520521
/************************* End ext/misc/diskused.c ********************/
20522
+/************************* Begin ext/misc/strdup.c ******************/
20523
+/*
20524
+** 2026-07-04
20525
+**
20526
+** The author disclaims copyright to this source code. In place of
20527
+** a legal notice, here is a blessing:
20528
+**
20529
+** May you do good and not evil.
20530
+** May you find forgiveness for yourself and forgive others.
20531
+** May you share freely, never taking more than you give.
20532
+**
20533
+******************************************************************************
20534
+**
20535
+** Since this module was written (coincidentally) on the 250th anniversary
20536
+** of the signing of the Declaration of Independence of The United States,
20537
+** it seems fitting to quote from that document:
20538
+**
20539
+** We hold these truths to be self-evident, that all men are created
20540
+** equal, that they are endowed by their Creator with certain unalienable
20541
+** Rights, that among these are Life, Liberty and the pursuit of Happiness
20542
+** - That to secure these rights, Governments are instituted among Men,
20543
+** deriving their just powers from the consent of the governed,....
20544
+**
20545
+** Two core ideas that (1) rights come from God and not from government,
20546
+** and that (2) there should not be special privileged classes of people
20547
+** were radical thoughts then, and are indeed disputed even today. Many
20548
+** people still hold that human rights derive from the beneficence of
20549
+** government and that certain classes of people have special rights and
20550
+** privileges not available to all. Yet, were it not for the crazy ideas
20551
+** espoused in the original Declaration of Independence, this software
20552
+** project, and indeed most of modern technology, would not exist.
20553
+**
20554
+** Therefore let us give thanks for the bold leadership and vision
20555
+** demonstrated by the authors of the American Revolution, 250 years ago
20556
+** this day.
20557
+**
20558
+******************************************************************************
20559
+**
20560
+** Implementation of the strdup() SQL function. strdup() makes a copy
20561
+** of its argument (a string or a BLOB) into memory obtained directly
20562
+** from system malloc() (not from sqlite3_malloc()) and sized exactly
20563
+** to hold the string or BLOB. This is intended for testing purposes,
20564
+** particularly testing with ASAN. This function serves no practical
20565
+** purpose beyond testing and not not intended for production use.
20566
+**
20567
+** NULL, BLOB, and TEXT values come through as NULL, BLOB, and TEXT,
20568
+** respectively. Numeric values are rendered as strings and come out
20569
+** as text.
20570
+*/
20571
+/* #include "sqlite3ext.h" */
20572
+SQLITE_EXTENSION_INIT1
20573
+#include <assert.h>
20574
+#include <string.h>
20575
+#include <stdlib.h>
20576
+
20577
+/*
20578
+** Make a copy of a string or BLOB in memory obtained from malloc().
20579
+*/
20580
+static void strdupfunc(
20581
+ sqlite3_context *context,
20582
+ int argc,
20583
+ sqlite3_value **argv
20584
+){
20585
+ const unsigned char *zIn;
20586
+ int nIn;
20587
+ unsigned char *zOut;
20588
+
20589
+ assert( argc==1 );
20590
+ if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
20591
+ if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
20592
+ zIn = (const unsigned char*)sqlite3_value_blob(argv[0]);
20593
+ nIn = sqlite3_value_bytes(argv[0]);
20594
+ zOut = malloc( nIn==0 ? 1 : nIn );
20595
+ if( zOut==0 ){
20596
+ sqlite3_result_error_nomem(context);
20597
+ return;
20598
+ }
20599
+ if( nIn>0 ) memcpy(zOut, zIn, nIn);
20600
+ sqlite3_result_blob(context, zOut, nIn, free);
20601
+ }else{
20602
+ zIn = (const unsigned char*)sqlite3_value_text(argv[0]);
20603
+ if( zIn==0 ) return;
20604
+ nIn = (int)strlen((char*)zIn);
20605
+ zOut = malloc( nIn+1 );
20606
+ if( zOut==0 ){
20607
+ sqlite3_result_error_nomem(context);
20608
+ return;
20609
+ }
20610
+ memcpy(zOut, zIn, nIn);
20611
+ zOut[nIn] = 0;
20612
+ sqlite3_result_text64(context, (char*)zOut, nIn, free,
20613
+ SQLITE_UTF8_ZT);
20614
+ }
20615
+}
20616
+
20617
+#ifdef _WIN32
20618
+
20619
+#endif
20620
+int sqlite3_strdup_init(
20621
+ sqlite3 *db,
20622
+ char **pzErrMsg,
20623
+ const sqlite3_api_routines *pApi
20624
+){
20625
+ int rc = SQLITE_OK;
20626
+ SQLITE_EXTENSION_INIT2(pApi);
20627
+ (void)pzErrMsg; /* Unused parameter */
20628
+ rc = sqlite3_create_function(db, "strdup", 1, SQLITE_UTF8,
20629
+ 0, strdupfunc, 0, 0);
20630
+ return rc;
20631
+}
20632
+
20633
+/************************* End ext/misc/strdup.c ********************/
2036620634
2036720635
#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
2036820636
#define SQLITE_SHELL_HAVE_RECOVER 1
2036920637
#else
2037020638
#define SQLITE_SHELL_HAVE_RECOVER 0
@@ -24581,10 +24849,20 @@
2458124849
#endif
2458224850
#ifdef SQLITE_SHELL_EXTSRC
2458324851
# include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
2458424852
#endif
2458524853
24854
+/*
24855
+** Set the SQLITE_SHELL_EDITION to a YYYYMMDD date string and the
24856
+** code will attempt to use defaults for the prompt and for the
24857
+** initial output mode (and maybe other feature) that were for
24858
+** the most recent version not newer than the specified date.
24859
+*/
24860
+#ifndef SQLITE_SHELL_EDITION
24861
+# define SQLITE_SHELL_EDITION 99991231 /* Use the latest if unspecified */
24862
+#endif
24863
+
2458624864
#if defined(SQLITE_ENABLE_SESSION)
2458724865
/*
2458824866
** State information for a single open session
2458924867
*/
2459024868
typedef struct OpenSession OpenSession;
@@ -24828,11 +25106,11 @@
2482825106
unsigned char eHdr; /* Default header encoding. */
2482925107
unsigned char eBlob; /* Default blob encoding. */
2483025108
unsigned char bHdr; /* Show headers by default. 0: n/a, 1: no 2: yes */
2483125109
unsigned char eStyle; /* Underlying QRF style */
2483225110
unsigned char eCx; /* 0: other, 1: line, 2: columnar */
24833
- unsigned char mFlg; /* Flags. 1=border-off 2=split-column */
25111
+ unsigned char mFlg; /* Flags. 1=border-off 2=split-column 4=rowcount */
2483425112
};
2483525113
2483625114
/* String constants used by built-in modes */
2483725115
static const char *aModeStr[] =
2483825116
/* 0 1 2 3 4 5 6 7 8 */
@@ -24841,45 +25119,45 @@
2484125119
/* 9 10 11 12 13 */
2484225120
2484325121
static const ModeInfo aModeInfo[] = {
2484425122
/* zName eCSep eRSep eNull eText eHdr eBlob bHdr eStyle eCx mFlg */
2484525123
{ "ascii", 7, 6, 9, 1, 1, 0, 1, 12, 0, 0 },
24846
- { "box", 0, 0, 9, 1, 1, 0, 2, 1, 2, 0 },
25124
+ { "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 },
2484725125
{ "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 },
24848
- { "column", 0, 0, 9, 1, 1, 0, 2, 2, 2, 0 },
25126
+ { "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 },
2484925127
{ "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 },
2485025128
{ "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
24851
- { "html", 0, 0, 9, 4, 4, 0, 2, 7, 0, 0 },
25129
+ { "html", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 },
2485225130
{ "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 },
2485325131
{ "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 },
2485425132
{ "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 },
2485525133
{ "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 },
2485625134
{ "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 },
2485725135
{ "list", 2, 1, 9, 1, 1, 0, 1, 12, 0, 0 },
24858
- { "markdown", 0, 0, 9, 1, 1, 0, 2, 13, 2, 0 },
25136
+ { "markdown", 0, 0, 9, 1, 1, 0, 3, 13, 2, 0 },
2485925137
{ "off", 0, 0, 0, 0, 0, 0, 0, 14, 0, 0 },
24860
- { "psql", 0, 0, 9, 1, 1, 0, 2, 19, 2, 1 },
24861
- { "qbox", 0, 0, 10, 2, 1, 0, 2, 1, 2, 0 },
25138
+ { "psql", 0, 0, 9, 1, 1, 0, 3, 19, 2, 5 },
25139
+ { "qbox", 0, 0, 10, 2, 1, 0, 3, 1, 2, 0 },
2486225140
{ "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 },
2486325141
{ "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 },
24864
- { "table", 0, 0, 9, 1, 1, 0, 2, 19, 2, 0 },
25142
+ { "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 },
2486525143
{ "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 },
2486625144
{ "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 },
24867
- { "www", 0, 0, 9, 4, 4, 0, 2, 7, 0, 0 }
24868
-}; /* | / / | / / | | \
24869
- ** | / / | / / | | \_ 2: columnar
24870
- ** Index into aModeStr[] | / / | | 1: line
24871
- ** | / / | | 0: other
24872
- ** | / / | \
24873
- ** text encoding |/ | show | \
24874
- ** v-------------------' | hdrs? | The QRF style
24875
- ** 0: n/a blob | v-----'
24876
- ** 1: plain v----------' 0: n/a
24877
- ** 2: sql 0: auto 1: no
24878
- ** 3: csv 1: as-text 2: yes
24879
- ** 4: html 2: sql
24880
- ** 5: c 3: hex
25145
+ { "www", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 }
25146
+}; /* | / / | / / | | / \____
25147
+ ** | / / | / / | | / |
25148
+ ** Index into aModeStr[] | / / | | 2: columnar |
25149
+ ** | / / | | 1: line |
25150
+ ** | / / | | 0: other |
25151
+ ** text encoding |/ | show | | |
25152
+ ** v-------------------' | hdrs? | The QRF style |
25153
+ ** 0: n/a blob | v-----' /
25154
+ ** 1: plain v----------' 0: n/a _________/
25155
+ ** 2: sql 0: auto 1: no |
25156
+ ** 3: csv 1: as-text 2: yes 1: border-off
25157
+ ** 4: html 2: sql 3: always 2: split-column
25158
+ ** 5: c 3: hex 4: rowcount
2488125159
** 6: json 4: c
2488225160
** 5: json
2488325161
** 6: size
2488425162
******************************************************************/
2488525163
@@ -25162,11 +25440,11 @@
2516225440
*/
2516325441
static char *local_getline(char *zLine, FILE *in){
2516425442
int nLine = zLine==0 ? 0 : 100;
2516525443
int n = 0;
2516625444
25167
- while( 1 ){
25445
+ while( seenInterrupt<2 ){
2516825446
if( n+100>nLine ){
2516925447
if( nLine>=1073741773 ){
2517025448
free(zLine);
2517125449
return 0;
2517225450
}
@@ -25226,11 +25504,13 @@
2522625504
# define SQLITE_PS_APPDEF shellPromptAppDef
2522725505
static const char *shellPromptAppDef(int c){
2522825506
switch( c ){
2522925507
/* The default main prompt string */
2523025508
case 1:
25231
-#if defined(SQLITE_PS1)
25509
+#if SQLITE_SHELL_EDITION<20260423
25510
+ return "sqlite> "; /* Legacy prompt for backwards compatibility */
25511
+#elif defined(SQLITE_PS1)
2523225512
return SQLITE_PS1;
2523325513
#else
2523425514
if( shellNoColor() ){
2523525515
return "/A-/v /f-> ";
2523625516
}else{
@@ -25238,11 +25518,13 @@
2523825518
}
2523925519
#endif
2524025520
2524125521
/* The default continuation prompt string */
2524225522
case 2:
25243
-#if defined(SQLITE_PS2)
25523
+#if SQLITE_SHELL_EDITION<20260423
25524
+ return " ...> "; /* Legacy continuation prompt */
25525
+#elif defined(SQLITE_PS2)
2524425526
return SQLITE_PS2;
2524525527
#else
2524625528
if( shellNoColor() ){
2524725529
return "/B/C-> ";
2524825530
}else{
@@ -25711,30 +25993,33 @@
2571125993
zResult = local_getline(zPrior, in);
2571225994
}else{
2571325995
const char *zBase = prompt_string(p, bContinue!=0);
2571425996
char *zPrompt = expand_prompt(p, zAll, zBase);
2571525997
shell_check_oom(zPrompt);
25716
-#if SHELL_USE_LOCAL_GETLINE
25717
- sputz(stdout, zPrompt);
25718
- fflush(stdout);
25719
- do{
25720
- zResult = local_getline(zPrior, stdin);
25721
- zPrior = 0;
25722
- /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
25723
- if( zResult==0 ) sqlite3_sleep(50);
25724
- }while( zResult==0 && seenInterrupt>0 );
25725
-#else
25726
- free(zPrior);
25727
- zResult = shell_readline(zPrompt);
25728
- while( zResult==0 ){
25729
- /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
25730
- sqlite3_sleep(50);
25731
- if( seenInterrupt==0 ) break;
25732
- zResult = shell_readline("");
25733
- }
25734
- if( zResult && *zResult ) shell_add_history(zResult);
25735
-#endif
25998
+#if SHELL_CMDLINE_EDIT_AVAILABLE
25999
+ if( shellCmdLineEdit ){
26000
+ free(zPrior);
26001
+ zResult = shell_readline(zPrompt);
26002
+ while( zResult==0 ){
26003
+ /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
26004
+ sqlite3_sleep(50);
26005
+ if( seenInterrupt==0 ) break;
26006
+ zResult = shell_readline("");
26007
+ }
26008
+ if( zResult && *zResult ) shell_add_history(zResult);
26009
+ }else
26010
+#endif
26011
+ {
26012
+ sputz(stdout, zPrompt);
26013
+ fflush(stdout);
26014
+ do{
26015
+ zResult = local_getline(zPrior, stdin);
26016
+ zPrior = 0;
26017
+ /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
26018
+ if( zResult==0 ) sqlite3_sleep(50);
26019
+ }while( zResult==0 && seenInterrupt>0 );
26020
+ }
2573626021
sqlite3_free(zPrompt);
2573726022
}
2573826023
return zResult;
2573926024
}
2574026025
#endif /* !SQLITE_SHELL_FIDDLE */
@@ -26307,11 +26592,11 @@
2630726592
free(p->spec.zColumnSep);
2630826593
free(p->spec.zRowSep);
2630926594
free(p->spec.zTableName);
2631026595
free(p->spec.zNull);
2631126596
memset(p, 0, sizeof(*p));
26312
- p->spec.iVersion = 1;
26597
+ p->spec.iVersion = 2;
2631326598
p->autoExplain = autoExplain;
2631426599
}
2631526600
2631626601
/*
2631726602
** Duplicate Mode pSrc into pDest. pDest is assumed to be
@@ -26432,10 +26717,15 @@
2643226717
pM->spec.bSplitColumn = QRF_Yes;
2643326718
pM->bAutoScreenWidth = 1;
2643426719
}else{
2643526720
pM->spec.bSplitColumn = QRF_No;
2643626721
}
26722
+ if( pI->mFlg & 0x04 ){
26723
+ pM->spec.bRowCount = QRF_Yes;
26724
+ }else{
26725
+ pM->spec.bRowCount = QRF_No;
26726
+ }
2643726727
}else if( eMode>=MODE_USER && eMode-MODE_USER<p->nSavedModes ){
2643826728
modeFree(&p->mode);
2643926729
modeDup(&p->mode, &p->aSavedModes[eMode-MODE_USER].mode);
2644026730
}else if( eMode==MODE_BATCH ){
2644126731
u8 mFlags = p->mode.mFlags;
@@ -26461,13 +26751,15 @@
2646126751
/*
2646226752
** Set the mode to the default. It assumed that the mode has
2646326753
** already been freed and zeroed prior to calling this routine.
2646426754
*/
2646526755
static void modeDefault(ShellState *p){
26466
- p->mode.spec.iVersion = 1;
26756
+ p->mode.spec.iVersion = 2;
2646726757
p->mode.autoExplain = 1;
26468
- if( stdin_is_interactive || stdout_is_console ){
26758
+ if( (stdin_is_interactive || stdout_is_console)
26759
+ && SQLITE_SHELL_EDITION>=20260409
26760
+ ){
2646926761
modeChange(p, MODE_TTY);
2647026762
}else{
2647126763
modeChange(p, MODE_BATCH);
2647226764
}
2647326765
}
@@ -28827,10 +29119,11 @@
2882729119
" --quote ARG Enable/disable quoting of text. ARG can be\n"
2882829120
" \"off\", \"on\", \"sql\", \"relaxed\", \"csv\", \"html\",\n"
2882929121
" \"tcl\", or \"json\". \"off\" means show the text as-is.\n"
2883029122
" \"on\" is an alias for \"sql\".\n"
2883129123
" --reset Changes all mode settings back to their default.\n"
29124
+" --rowcount BOOLEAN Show \"(N rows)\" at the end of query results.\n"
2883229125
" --rowsep STRING Use STRING as the row separator\n"
2883329126
" --sw|--screenwidth N Declare the screen width of the output device\n"
2883429127
" to be N characters. An attempt may be made to\n"
2883529128
" wrap output text to fit within this limit. Zero\n"
2883629129
" means \"no limit\". Or N can be \"auto\" to set the\n"
@@ -28838,11 +29131,11 @@
2883829131
" --tablename NAME Set the name of the table for \"insert\" mode.\n"
2883929132
" --tag NAME Save mode to the left as NAME.\n"
2884029133
" --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON.\n"
2884129134
" --title ARG Whether or not to show column headers, and if so\n"
2884229135
" how to encode them. ARG can be \"off\", \"on\",\n"
28843
-" \"sql\", \"csv\", \"html\", \"tcl\", or \"json\".\n"
29136
+" \"always\", \"sql\", \"csv\", \"html\", \"tcl\", or \"json\".\n"
2884429137
" --titlelimit N Limit the length of column titles to N characters.\n"
2884529138
" -v|--verbose Verbose output\n"
2884629139
" --widths LIST Set the columns widths for columnar modes. The\n"
2884729140
" argument is a list of integers, one for each\n"
2884829141
" column. A \"0\" width means use a dynamic width\n"
@@ -29544,10 +29837,11 @@
2954429837
sqlite3_base85_init(p->db, 0, 0);
2954529838
sqlite3_regexp_init(p->db, 0, 0);
2954629839
sqlite3_ieee_init(p->db, 0, 0);
2954729840
sqlite3_series_init(p->db, 0, 0);
2954829841
sqlite3_diskused_init(p->db, 0, 0);
29842
+ sqlite3_strdup_init(p->db, 0, 0);
2954929843
#ifndef SQLITE_SHELL_FIDDLE
2955029844
sqlite3_fileio_init(p->db, 0, 0);
2955129845
sqlite3_completion_init(p->db, 0, 0);
2955229846
#endif
2955329847
#ifdef SQLITE_HAVE_ZLIB
@@ -32998,14 +33292,16 @@
3299833292
/*
3299933293
** This function computes what to show the user about the configured
3300033294
** titles (or column-names). Output is an integer between 0 and 3:
3300133295
**
3300233296
** 0: The titles do not matter. Never show anything.
33003
-** 1: Show "--titles off"
33004
-** 2: Show "--titles on"
33005
-** 3: Show "--title VALUE" where VALUE is an encoding method
33297
+** 1: Show "--title off"
33298
+** 2: Show "--title on"
33299
+** 3: Show "--title always"
33300
+** 4: Show "--title VALUE" where VALUE is an encoding method
3300633301
** to use, one of: plain sql csv html tcl json
33302
+** 5: Show "--title VALUE" as in 3, followed by "--title always"
3300733303
**
3300833304
** Inputs are:
3300933305
**
3301033306
** spec.bTitles (bT) Whether or not to show the titles
3301133307
** spec.eTitle (eT) The actual encoding to be used for titles
@@ -33038,11 +33334,27 @@
3303833334
if( eT!=eH ) v >>= 32; /* Encoding disagree in upper 4-bytes */
3303933335
if( bT!=bH ) v >>= 16; /* ON/OFF disagree in upper 2-byte pairs */
3304033336
if( bT<2 ) v >>= 8; /* ON in even bytes, OFF in odd bytes (1st byte 0) */
3304133337
if( !bAll ) v >>= 4; /* bAll values are in the lower half-byte */
3304233338
33043
- return v & 3; /* Return the selected truth-table entry */
33339
+ v &= 3;
33340
+ /* At this point v means:
33341
+ ** 0: The titles do not matter. Never show anything.
33342
+ ** 1: Show "--title off"
33343
+ ** 2: Show "--title on"
33344
+ ** 3: Show "--title VALUE" where VALUE is an encoding method
33345
+ ** to use, one of: plain sql csv html tcl json
33346
+ ** If bTitles is QRF_Always, convert 2->3, 3->5. If bTitles is not
33347
+ ** QRF_Always, convert 3->4.
33348
+ */
33349
+ if( p->mode.spec.bTitles==QRF_Always ){
33350
+ if( v==3 ) v = 5;
33351
+ if( v==2 ) v = 3;
33352
+ }else{
33353
+ if( v==3 ) v = 4;
33354
+ }
33355
+ return v;
3304433356
}
3304533357
3304633358
/*
3304733359
** DOT-COMMAND: .mode
3304833360
**
@@ -33086,10 +33398,11 @@
3308633398
** --quote ARG Enable/disable quoting of text. ARG can be
3308733399
** "off", "on", "sql", "relaxed", "csv", "html",
3308833400
** "tcl", or "json". "off" means show the text as-is.
3308933401
** "on" is an alias for "sql".
3309033402
** --reset Changes all mode settings back to their default.
33403
+** --rowcount BOOLEAN Show "(N rows)" at the end of query results.
3309133404
** --rowsep STRING Use STRING as the row separator
3309233405
** --sw|--screenwidth N Declare the screen width of the output device
3309333406
** to be N characters. An attempt may be made to
3309433407
** wrap output text to fit within this limit. Zero
3309533408
** means "no limit". Or N can be "auto" to set the
@@ -33097,11 +33410,11 @@
3309733410
** --tablename NAME Set the name of the table for "insert" mode.
3309833411
** --tag NAME Save mode to the left as NAME.
3309933412
** --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON.
3310033413
** --title ARG Whether or not to show column headers, and if so
3310133414
** how to encode them. ARG can be "off", "on",
33102
-** "sql", "csv", "html", "tcl", or "json".
33415
+** "always", "sql", "csv", "html", "tcl", or "json".
3310333416
** --titlelimit N Limit the length of column titles to N characters.
3310433417
** -v|--verbose Verbose output
3310533418
** --widths LIST Set the columns widths for columnar modes. The
3310633419
** argument is a list of integers, one for each
3310733420
** column. A "0" width means use a dynamic width
@@ -33325,10 +33638,17 @@
3332533638
chng = 1;
3332633639
}else if( optionMatch(z,"reset") ){
3332733640
int saved_eMode = p->mode.eMode;
3332833641
modeFree(&p->mode);
3332933642
modeChange(p, saved_eMode);
33643
+ }else if( optionMatch(z,"rowcount") ){
33644
+ if( i+1>=nArg ){
33645
+ dotCmdError(p, i, "missing argument", 0);
33646
+ return 1;
33647
+ }
33648
+ p->mode.spec.bRowCount = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
33649
+ chng = 1;
3333033650
}else if( optionMatch(z,"screenwidth") || optionMatch(z,"sw") ){
3333133651
if( (++i)>=nArg ){
3333233652
dotCmdError(p, i-1, "missing argument", 0);
3333333653
return 1;
3333433654
}
@@ -33378,25 +33698,63 @@
3337833698
return 1;
3337933699
}
3338033700
p->mode.spec.bTextJsonb = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
3338133701
chng = 1;
3338233702
}else if( optionMatch(z,"titles") || optionMatch(z,"title") ){
33703
+ /* The --titles option controls two fields of the
33704
+ ** sqlite3_qrf_spec object: eTitle and bTitles.
33705
+ **
33706
+ ** --titles eTitle bTitles
33707
+ ** -------- --------------- ---------------------
33708
+ ** "off" (unchanged) QRF_Off
33709
+ ** "on" (unchanged) QRF_On
33710
+ ** "always" (unchanged) QRF_Always
33711
+ ** "auto", (default) (default)
33712
+ ** "plain" QRF_TEXT_Plain QRF_Always or QRF_On
33713
+ ** "sql" QRF_TEXT_Sql QRF_Always or QRF_On
33714
+ ** "csv" QRF_TEXT_Csv QRF_Always or QRF_On
33715
+ ** "html" QRF_TEXT_Html QRF_Always or QRF_On
33716
+ ** "tcl" QRF_TEXT_Tcl QRF_Always or QRF_On
33717
+ ** "json" QRF_TEXT_Json QRF_Always or QRF_On
33718
+ **
33719
+ ** This mapping is different from the -title option to the "format"
33720
+ ** method of the TCL interface. In this mapping:
33721
+ **
33722
+ ** * "off", "on", and "always" affect only bTitles and leave
33723
+ ** eTitle unchanged
33724
+ **
33725
+ ** * "auto" sets both bTitles and eTitle to the default value
33726
+ ** in aModeInfo[] according to the current --style.
33727
+ **
33728
+ ** * "plain" through "json" set eTitle but leave bTitles
33729
+ ** unchanged if it is not QRF_Off. If bTitles is QRF_Off,
33730
+ ** then it is changed QRF_Always.
33731
+ */
3338333732
char *zErr = 0;
3338433733
if( i+1>=nArg ){
3338533734
dotCmdError(p, i, "missing argument", 0);
3338633735
return 1;
3338733736
}
3338833737
k = pickStr(azArg[++i],&zErr,
33389
- "off","on","plain","sql","csv","html","tcl","json","");
33390
- /* 0 1 2 3 4 5 6 7 */
33738
+ "off","on","always","auto","plain","sql","csv","html","tcl","json","");
33739
+ /* 0 1 2 3 4 5 6 7 8 9 */
3339133740
if( k<0 ){
3339233741
dotCmdError(p, i, "bad --titles value","%z", zErr);
3339333742
return 1;
3339433743
}
33395
- p->mode.spec.bTitles = k>=1 ? QRF_Yes : QRF_No;
3339633744
p->mode.mFlags &= ~MFLG_HDR;
33397
- p->mode.spec.eTitle = k>1 ? k-1 : aModeInfo[p->mode.eMode].eHdr;
33745
+ if( k<=2 ){
33746
+ p->mode.spec.bTitles = QRF_No+k;
33747
+ }else if( k==3 ){
33748
+ p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
33749
+ p->mode.spec.bTitles = aModeInfo[p->mode.eMode].bHdr;
33750
+ }else{
33751
+ p->mode.spec.eTitle = (k-4)+QRF_TEXT_Plain;
33752
+ if( p->mode.spec.bTitles==QRF_No ){
33753
+ p->mode.spec.bTitles = QRF_Always;
33754
+ }
33755
+ }
3339833756
chng = 1;
3339933757
}else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
3340033758
int nWidth = 0;
3340133759
short int *aWidth;
3340233760
const char *zW;
@@ -33547,10 +33905,16 @@
3354733905
if( bAll
3354833906
|| (pI->eText!=p->mode.spec.eText && (pI->eText>1 || p->mode.spec.eText>1))
3354933907
){
3355033908
sqlite3_str_appendf(pDesc," --quote %s",qrfQuoteNames[p->mode.spec.eText]);
3355133909
}
33910
+ if( bAll
33911
+ || ((p->mode.spec.bRowCount==QRF_Yes) != ((pI->mFlg&4)!=0))
33912
+ ){
33913
+ sqlite3_str_appendf(pDesc," --rowcount %s",
33914
+ p->mode.spec.bRowCount==QRF_Yes ? "on" : "off");
33915
+ }
3355233916
zSetting = aModeStr[pI->eRSep];
3355333917
if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zRowSep)!=0) ){
3355433918
sqlite3_str_appendf(pDesc, " --rowsep ");
3355533919
append_c_string(pDesc, p->mode.spec.zRowSep);
3355633920
}
@@ -33576,14 +33940,19 @@
3357633940
if( k==1 ){
3357733941
sqlite3_str_appendall(pDesc, " --titles off");
3357833942
}else if( k==2 ){
3357933943
sqlite3_str_appendall(pDesc, " --titles on");
3358033944
}else if( k==3 ){
33945
+ sqlite3_str_appendall(pDesc, " --titles always");
33946
+ }else if( k>=4 ){
3358133947
static const char *azTitle[] =
3358233948
{ "plain", "sql", "csv", "html", "tcl", "json"};
3358333949
sqlite3_str_appendf(pDesc, " --titles %s",
3358433950
azTitle[p->mode.spec.eTitle-1]);
33951
+ if( k==5 ){
33952
+ sqlite3_str_appendf(pDesc, " --titles always");
33953
+ }
3358533954
}
3358633955
if( p->mode.spec.nWidth>0 && (bAll || pI->eCx==2) ){
3358733956
int ii;
3358833957
const char *zSep = " --widths ";
3358933958
for(ii=0; ii<p->mode.spec.nWidth; ii++){
@@ -34901,15 +35270,19 @@
3490135270
}
3490235271
}else
3490335272
3490435273
if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
3490535274
if( nArg==2 ){
34906
- p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
35275
+ if( cli_strcmp(azArg[1],"always")==0 ){
35276
+ p->mode.spec.bTitles = QRF_Always;
35277
+ }else{
35278
+ p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
35279
+ }
3490735280
p->mode.mFlags |= MFLG_HDR;
3490835281
p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
3490935282
}else{
34910
- eputz("Usage: .headers on|off\n");
35283
+ eputz("Usage: .headers off|on|always\n");
3491135284
rc = 1;
3491235285
}
3491335286
}else
3491435287
3491535288
if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
@@ -35113,13 +35486,21 @@
3511335486
sqlite3_str_free(pSql);
3511435487
}else
3511535488
3511635489
if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
3511735490
i64 iArg = 0;
35491
+ open_db(p, 0);
3511835492
if( nArg==2 ){
3511935493
iArg = integerValue(azArg[1]);
35120
- if( iArg==0 ) iArg = -1;
35494
+ if( iArg==0 ){
35495
+ if( cli_strcmp(azArg[1],"register")==0 ){
35496
+ sqlite3_intck_register(p->db, 1);
35497
+ rc = 0;
35498
+ goto meta_command_exit;
35499
+ }
35500
+ iArg = -1;
35501
+ }
3512135502
}
3512235503
if( (nArg!=1 && nArg!=2) || iArg<0 ){
3512335504
cli_printf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n");
3512435505
rc = 1;
3512535506
goto meta_command_exit;
@@ -35167,10 +35548,11 @@
3516735548
{ "attached", SQLITE_LIMIT_ATTACHED },
3516835549
{ "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
3516935550
{ "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
3517035551
{ "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
3517135552
{ "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
35553
+ { "schema", SQLITE_LIMIT_SCHEMA },
3517235554
};
3517335555
int i, n2;
3517435556
open_db(p, 0);
3517535557
if( nArg==1 ){
3517635558
for(i=0; i<ArraySize(aLimit); i++){
@@ -36493,11 +36875,12 @@
3649336875
azBool[(p->mode.mFlags & MFLG_ECHO)!=0]);
3649436876
cli_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->mode.autoEQP&3]);
3649536877
cli_printf(p->out, "%12.12s: %s\n","explain",
3649636878
p->mode.autoExplain ? "auto" : "off");
3649736879
cli_printf(p->out, "%12.12s: %s\n","headers",
36498
- azBool[p->mode.spec.bTitles==QRF_Yes]);
36880
+ p->mode.spec.bTitles==QRF_Always ? "always" :
36881
+ azBool[p->mode.spec.bTitles==QRF_Yes]);
3649936882
if( p->mode.spec.eStyle==QRF_STYLE_Column
3650036883
|| p->mode.spec.eStyle==QRF_STYLE_Box
3650136884
|| p->mode.spec.eStyle==QRF_STYLE_Table
3650236885
|| p->mode.spec.eStyle==QRF_STYLE_Markdown
3650336886
){
@@ -37860,10 +38243,11 @@
3786038243
" -ascii set '.mode ascii'\n"
3786138244
" -bail stop after hitting an error\n"
3786238245
" -batch force batch I/O\n"
3786338246
" -box set '.mode box'\n"
3786438247
" -cmd COMMAND run \"COMMAND\" before reading stdin\n"
38248
+ " -cmdline-edit BOOL enable or disable command-line editing\n"
3786538249
" -column set '.mode column'\n"
3786638250
" -csv set '.mode csv -limits off'\n"
3786738251
#if !defined(SQLITE_OMIT_DESERIALIZE)
3786838252
" -deserialize open the database using sqlite3_deserialize()\n"
3786938253
#endif
@@ -38130,10 +38514,13 @@
3813038514
stdout_is_console = 1;
3813138515
data.wasm.zDefaultDbName = "/fiddle.sqlite3";
3813238516
#else
3813338517
stdin_is_interactive = isatty(0);
3813438518
stdout_is_console = isatty(1);
38519
+ if( !stdin_is_interactive || !stdout_is_console ){
38520
+ shellCmdLineEdit = 0;
38521
+ }
3813538522
#endif
3813638523
atexit(abnormalExit);
3813738524
#ifdef SQLITE_DEBUG
3813838525
mem_main_enter = sqlite3_memory_used();
3813938526
#endif
@@ -38377,10 +38764,12 @@
3837738764
}else if( cli_strcmp(z,"-safe")==0 ){
3837838765
/* no-op - catch this on the second pass */
3837938766
}else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
3838038767
/* skip over the argument */
3838138768
i++;
38769
+ }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
38770
+ shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i));
3838238771
}else if( cli_strcmp(z,"-test-argv")==0 ){
3838338772
/* Undocumented test option. Print the values in argv[] and exit.
3838438773
** Use this to verify that any translation of the argv[], for example
3838538774
** on Windows that receives wargv[] from the OS and must convert
3838638775
** to UTF8 prior to calling this routine. */
@@ -38567,11 +38956,11 @@
3856738956
cmdline_option_value(argc,argv,++i));
3856838957
}else if( cli_strcmp(z,"-nullvalue")==0 ){
3856938958
modeSetStr(&data.mode.spec.zNull,
3857038959
cmdline_option_value(argc,argv,++i));
3857138960
}else if( cli_strcmp(z,"-header")==0 ){
38572
- data.mode.spec.bTitles = QRF_Yes;
38961
+ data.mode.spec.bTitles = QRF_Always;
3857338962
data.mode.mFlags |= MFLG_HDR;
3857438963
}else if( cli_strcmp(z,"-noheader")==0 ){
3857538964
data.mode.spec.bTitles = QRF_No;
3857638965
data.mode.mFlags |= MFLG_HDR;
3857738966
}else if( cli_strcmp(z,"-echo")==0 ){
@@ -38639,10 +39028,12 @@
3863939028
i++;
3864039029
#ifdef SQLITE_ENABLE_MULTIPLEX
3864139030
}else if( cli_strcmp(z,"-multiplex")==0 ){
3864239031
i++;
3864339032
#endif
39033
+ }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
39034
+ i+=2;
3864439035
}else if( cli_strcmp(z,"-help")==0 ){
3864539036
usage(1);
3864639037
}else if( cli_strcmp(z,"-cmd")==0 ){
3864739038
/* Run commands that follow -cmd first and separately from commands
3864839039
** that simply appear on the command-line. This seems goofy. It would
@@ -38668,12 +39059,14 @@
3866839059
rc = 1;
3866939060
goto shell_main_exit;
3867039061
}
3867139062
open_db(&data, OPEN_DB_ZIPFILE);
3867239063
if( z[2] ){
39064
+ char *zSaved = argv[i];
3867339065
argv[i] = &z[2];
3867439066
arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
39067
+ argv[i] = zSaved;
3867539068
}else{
3867639069
arDotCommand(&data, 1, argv+i, argc-i);
3867739070
}
3867839071
readStdin = 0;
3867939072
stdin_is_interactive = 0;
3868039073
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -23,10 +23,11 @@
23 ** ext/misc/shathree.c
24 ** ext/misc/sqlar.c
25 ** ext/misc/sqlite3_stdio.c
26 ** ext/misc/sqlite3_stdio.h
27 ** ext/misc/stmtrand.c
 
28 ** ext/misc/uint.c
29 ** ext/misc/vfstrace.c
30 ** ext/misc/windirent.h
31 ** ext/misc/zipfile.c
32 ** ext/qrf/qrf.c
@@ -205,28 +206,38 @@
205 # define shell_add_history(X) add_history(X)
206 # define shell_read_history(X) read_history(X)
207 # define shell_write_history(X) write_history(X)
208 # define shell_stifle_history(X) stifle_history(X)
209 # define shell_readline(X) readline(X)
 
210
211 #elif HAVE_LINENOISE
212
213 # include "linenoise.h"
214 # define shell_add_history(X) linenoiseHistoryAdd(X)
215 # define shell_read_history(X) linenoiseHistoryLoad(X)
216 # define shell_write_history(X) linenoiseHistorySave(X)
217 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
218 # define shell_readline(X) linenoise(X)
 
219
220 #else
221
222 # define shell_read_history(X)
223 # define shell_write_history(X)
224 # define shell_stifle_history(X)
 
 
225
226 # define SHELL_USE_LOCAL_GETLINE 1
227 #endif
 
 
 
 
 
 
228
229 #ifndef deliberate_fall_through
230 /* Quiet some compilers about some of our intentional code. */
231 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
232 # define deliberate_fall_through __attribute__((fallthrough));
@@ -733,10 +744,12 @@
733 char *(*xRender)(void*,sqlite3_value*); /* Render a value */
734 int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
735 void *pRenderArg; /* First argument to the xRender callback */
736 void *pWriteArg; /* First argument to the xWrite callback */
737 char **pzOutput; /* Storage location for output string */
 
 
738 /* Additional fields may be added in the future */
739 };
740
741 /*
742 ** Interfaces
@@ -761,11 +774,11 @@
761 #define QRF_STYLE_Column 2 /* One record per line in neat columns */
762 #define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
763 #define QRF_STYLE_Csv 4 /* Comma-separated-value */
764 #define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
765 #define QRF_STYLE_Explain 6 /* EXPLAIN output */
766 #define QRF_STYLE_Html 7 /* Generate an XHTML table */
767 #define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
768 #define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
769 #define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
770 #define QRF_STYLE_Line 11 /* One column per line. */
771 #define QRF_STYLE_List 12 /* One record per line with a separator */
@@ -821,10 +834,15 @@
821 #define QRF_SW_On 2 /* This setting is forced on */
822 #define QRF_Auto 0 /* Alternate spelling for QRF_*_Auto */
823 #define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
824 #define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
825
 
 
 
 
 
826 /*
827 ** Possible alignment values alignment settings
828 **
829 ** Horizontal Vertial
830 ** ---------- -------- */
@@ -2527,10 +2545,14 @@
2527 /* Doubled horizontal lines: */
2528 #define DBL_24 "\342\225\220" /* U+2550 === */
2529 #define DBL_123 "\342\225\236" /* U+255e |= */
2530 #define DBL_134 "\342\225\241" /* U+2561 =| */
2531 #define DBL_1234 "\342\225\252" /* U+256a =|= */
 
 
 
 
2532
2533 /* Draw horizontal line N characters long using unicode box
2534 ** characters
2535 */
2536 static void qrfBoxLine(sqlite3_str *pOut, int N, int bDbl){
@@ -2549,16 +2571,16 @@
2549
2550 /*
2551 ** Draw a horizontal separator for a QRF_STYLE_Box table.
2552 */
2553 static void qrfBoxSeparator(
2554 sqlite3_str *pOut,
2555 qrfColData *p,
2556 const char *zSep1,
2557 const char *zSep2,
2558 const char *zSep3,
2559 int bDbl
2560 ){
2561 int i;
2562 if( p->nCol>0 ){
2563 int useBorder = p->p->spec.bBorder!=QRF_No;
2564 if( useBorder ){
@@ -2573,10 +2595,36 @@
2573 sqlite3_str_appendall(pOut, zSep3);
2574 }
2575 }
2576 sqlite3_str_append(pOut, "\n", 1);
2577 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2578
2579 /*
2580 ** Load into pData the default alignment for the body of a table.
2581 */
2582 static void qrfLoadAlignment(qrfColData *pData, Qrf *p){
@@ -2831,11 +2879,25 @@
2831 sqlite3_str *pStr; /* Temporary rendering */
2832 qrfColData data; /* Columnar layout data */
2833 int bRTrim; /* Trim trailing space */
2834
2835 rc = sqlite3_step(p->pStmt);
2836 if( rc!=SQLITE_ROW || nColumn==0 ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2837 return; /* No output */
2838 }
2839
2840 /* Initialize the data container */
2841 memset(&data, 0, sizeof(data));
@@ -2848,12 +2910,12 @@
2848 }
2849 memset(data.a, 0, nColumn*sizeof(struct qrfPerCol) );
2850 if( qrfColDataEnlarge(&data) ) return;
2851 assert( data.az!=0 );
2852
2853 /* Load the column header names and all cell content into data */
2854 if( p->spec.bTitles==QRF_Yes ){
2855 unsigned char saved_eText = p->spec.eText;
2856 p->spec.eText = p->spec.eTitle;
2857 memset(data.abNum, 0, nColumn);
2858 for(i=0; i<nColumn; i++){
2859 const char *z = (const char*)sqlite3_column_name(p->pStmt,i);
@@ -2874,13 +2936,14 @@
2874 data.n++;
2875 if( w>data.a[i].mxW ) data.a[i].mxW = w;
2876 if( nNL ) data.bMultiRow = 1;
2877 }
2878 p->spec.eText = saved_eText;
2879 p->nRow++;
2880 }
2881 do{
 
 
2882 if( data.n+nColumn > data.nAlloc ){
2883 if( qrfColDataEnlarge(&data) ) return;
2884 }
2885 for(i=0; i<nColumn; i++){
2886 char *z;
@@ -2897,11 +2960,12 @@
2897 data.n++;
2898 if( w>data.a[i].mxW ) data.a[i].mxW = w;
2899 if( nNL ) data.bMultiRow = 1;
2900 }
2901 p->nRow++;
2902 }while( sqlite3_step(p->pStmt)==SQLITE_ROW && p->iErr==SQLITE_OK );
 
2903 if( p->iErr ){
2904 qrfColDataFree(&data);
2905 return;
2906 }
2907
@@ -3105,11 +3169,11 @@
3105 /* Draw either (1) the separator between the title line and the body
3106 ** of the table, or (2) separators between individual rows of the table
3107 ** body. isTitleDataSeparator will be true if we are doing (1).
3108 */
3109 if( (i==0 || data.bMultiRow) && i+nColumn<data.n ){
3110 int isTitleDataSeparator = (i==0 && p->spec.bTitles==QRF_Yes);
3111 if( isTitleDataSeparator ){
3112 qrfLoadAlignment(&data, p);
3113 }
3114 switch( p->spec.eStyle ){
3115 case QRF_STYLE_Table: {
@@ -3132,19 +3196,12 @@
3132 }
3133 break;
3134 }
3135 case QRF_STYLE_Column: {
3136 if( isTitleDataSeparator ){
3137 for(j=0; j<nColumn; j++){
3138 sqlite3_str_appendchar(p->pOut, data.a[j].w, '-');
3139 if( j<nColumn-1 ){
3140 sqlite3_str_append(p->pOut, colSep, szColSep);
3141 }else{
3142 qrfRTrim(p->pOut);
3143 sqlite3_str_append(p->pOut, rowSep, szRowSep);
3144 }
3145 }
3146 }else if( data.bMultiRow ){
3147 qrfRTrim(p->pOut);
3148 sqlite3_str_append(p->pOut, "\n", 1);
3149 }
3150 break;
@@ -3152,20 +3209,39 @@
3152 }
3153 }
3154 }
3155
3156 /* Draw the line across the bottom of the table */
3157 if( p->spec.bBorder!=QRF_No ){
3158 switch( p->spec.eStyle ){
3159 case QRF_STYLE_Box:
3160 qrfBoxSeparator(p->pOut, &data, BOX_R12, BOX_124, BOX_R14, 0);
 
 
 
 
3161 break;
3162 case QRF_STYLE_Table:
3163 qrfRowSeparator(p->pOut, &data, '+');
3164 break;
 
 
 
 
 
 
 
 
 
 
 
3165 }
3166 }
 
 
 
 
3167 qrfWrite(p);
3168
3169 qrfColDataFree(&data);
3170 return;
3171 }
@@ -3412,10 +3488,49 @@
3412 sqlite3_str_append(p->pOut, ":", 1);
3413 qrfRenderValue(p, p->pOut, i);
3414 }
3415 qrfWrite(p);
3416 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3417
3418 /*
3419 ** Render a single row of output for non-columnar styles - any
3420 ** style that lets us render row by row as the content is received
3421 ** from the query.
@@ -3445,25 +3560,19 @@
3445 }
3446 qrfOneJsonRow(p);
3447 break;
3448 }
3449 case QRF_STYLE_Html: {
3450 if( p->nRow==0 && p->spec.bTitles==QRF_Yes ){
3451 sqlite3_str_append(p->pOut, "<TR>", 4);
3452 for(i=0; i<p->nCol; i++){
3453 const char *zCName = sqlite3_column_name(p->pStmt, i);
3454 sqlite3_str_append(p->pOut, "\n<TH>", 5);
3455 qrfEncodeText(p, p->pOut, zCName);
3456 }
3457 sqlite3_str_append(p->pOut, "\n</TR>\n", 7);
3458 }
3459 sqlite3_str_append(p->pOut, "<TR>", 4);
3460 for(i=0; i<p->nCol; i++){
3461 sqlite3_str_append(p->pOut, "\n<TD>", 5);
3462 qrfRenderValue(p, p->pOut, i);
3463 }
3464 sqlite3_str_append(p->pOut, "\n</TR>\n", 7);
3465 qrfWrite(p);
3466 break;
3467 }
3468 case QRF_STYLE_Insert: {
3469 unsigned int mxIns = p->spec.nMultiInsert;
@@ -3476,11 +3585,11 @@
3476 if( qrf_need_quote(p->spec.zTableName) ){
3477 sqlite3_str_appendf(p->pOut,"INSERT INTO \"%w\"",p->spec.zTableName);
3478 }else{
3479 sqlite3_str_appendf(p->pOut,"INSERT INTO %s",p->spec.zTableName);
3480 }
3481 if( p->spec.bTitles==QRF_Yes ){
3482 for(i=0; i<p->nCol; i++){
3483 const char *zCName = sqlite3_column_name(p->pStmt, i);
3484 if( qrf_need_quote(zCName) ){
3485 sqlite3_str_appendf(p->pOut, "%c\"%w\"",
3486 i==0 ? '(' : ',', zCName);
@@ -3576,21 +3685,12 @@
3576 if( zEqpLine[0]=='-' ) qrfEqpRender(p, 0);
3577 qrfEqpAppend(p, iEqpId, iParentId, zEqpLine);
3578 break;
3579 }
3580 default: { /* QRF_STYLE_List */
3581 if( p->nRow==0 && p->spec.bTitles==QRF_Yes ){
3582 int saved_eText = p->spec.eText;
3583 p->spec.eText = p->spec.eTitle;
3584 for(i=0; i<p->nCol; i++){
3585 const char *zCName = sqlite3_column_name(p->pStmt, i);
3586 if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
3587 qrfEncodeText(p, p->pOut, zCName);
3588 }
3589 sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
3590 qrfWrite(p);
3591 p->spec.eText = saved_eText;
3592 }
3593 for(i=0; i<p->nCol; i++){
3594 if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
3595 qrfRenderValue(p, p->pOut, i);
3596 }
@@ -3612,11 +3712,11 @@
3612 char **pzErr /* Write errors here */
3613 ){
3614 size_t sz; /* Size of pSpec[], based on pSpec->iVersion */
3615 memset(p, 0, sizeof(*p));
3616 p->pzErr = pzErr;
3617 if( pSpec->iVersion>1 ){
3618 qrfError(p, SQLITE_ERROR,
3619 "unusable sqlite3_qrf_spec.iVersion (%d)",
3620 pSpec->iVersion);
3621 return;
3622 }
@@ -3640,10 +3740,13 @@
3640 if( p->spec.eStyle>QRF_STYLE_Table ) p->spec.eStyle = QRF_Auto;
3641 if( p->spec.eEsc>QRF_ESC_Symbol ) p->spec.eEsc = QRF_Auto;
3642 if( p->spec.eText>QRF_TEXT_Relaxed ) p->spec.eText = QRF_Auto;
3643 if( p->spec.eTitle>QRF_TEXT_Relaxed ) p->spec.eTitle = QRF_Auto;
3644 if( p->spec.eBlob>QRF_BLOB_Size ) p->spec.eBlob = QRF_Auto;
 
 
 
3645 qrf_reinit:
3646 switch( p->spec.eStyle ){
3647 case QRF_Auto: {
3648 switch( sqlite3_stmt_isexplain(pStmt) ){
3649 case 0: p->spec.eStyle = QRF_STYLE_Box; break;
@@ -3898,10 +4001,34 @@
3898 default: {
3899 /* Non-columnar modes where the output can occur after each row
3900 ** of result is received */
3901 while( qrf.iErr==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
3902 qrfOneSimpleRow(&qrf);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3903 }
3904 break;
3905 }
3906 }
3907 qrfResetStmt(&qrf);
@@ -5839,10 +5966,13 @@
5839 }
5840
5841 /*
5842 ** Allocate a new Decimal object initialized to the text in zIn[].
5843 ** Return NULL if any kind of error occurs.
 
 
 
5844 */
5845 static Decimal *decimalNewFromText(const char *zIn, int n){
5846 Decimal *p = 0;
5847 int i;
5848 int iExp = 0;
@@ -5856,15 +5986,15 @@
5856 p->isNull = 0;
5857 p->nDigit = 0;
5858 p->nFrac = 0;
5859 p->a = sqlite3_malloc64( n+1 );
5860 if( p->a==0 ) goto new_from_text_failed;
5861 for(i=0; IsSpace(zIn[i]); i++){}
5862 if( zIn[i]=='-' ){
5863 p->sign = 1;
5864 i++;
5865 }else if( zIn[i]=='+' ){
5866 i++;
5867 }
5868 while( i<n && zIn[i]=='0' ) i++;
5869 while( i<n ){
5870 char c = zIn[i];
@@ -6091,11 +6221,11 @@
6091 if( p->a[N]>=5 ){
6092 /* If all leading digits are 9, increase the number of digits
6093 ** by adding a new 0 to the front */
6094 for(i=0; i<N && p->a[i]==9; i++){}
6095 if( i==N ){
6096 decimal_expand(p, p->nDigit+1, 0);
6097 if( p->oom ) return;
6098 }
6099
6100 /* Do the rounding */
6101 p->a[N-1]++;
@@ -6249,10 +6379,11 @@
6249 int nAddSig;
6250 int nAddFrac;
6251 signed char *a;
6252 if( p==0 ) return;
6253 nAddFrac = nFrac - p->nFrac;
 
6254 nAddSig = (nDigit - p->nDigit) - nAddFrac;
6255 if( nAddFrac==0 && nAddSig==0 ) return;
6256 if( nDigit+1>SQLITE_DECIMAL_MAX_DIGIT ){ p->oom = 1; return; }
6257 a = sqlite3_realloc64(p->a, nDigit+1);
6258 if( a==0 ){
@@ -8256,10 +8387,20 @@
8256 if( r==(double)x ) return r;
8257 if( r<(double)x ) x--;
8258 return (double)x;
8259 }
8260 #endif
 
 
 
 
 
 
 
 
 
 
8261
8262 /*
8263 ** This method is called to "rewind" the series_cursor object back
8264 ** to the first row of output. This method is always called at least
8265 ** once prior to any call to seriesColumn() or seriesRowid() or
@@ -8379,11 +8520,11 @@
8379 double r = sqlite3_value_double(argv[iArg++]);
8380 if( r==seriesCeil(r)
8381 && r>=(double)SMALLEST_INT64
8382 && r<=(double)LARGEST_INT64
8383 ){
8384 iMin = iMax = (sqlite3_int64)r;
8385 }else{
8386 goto series_no_rows;
8387 }
8388 }else{
8389 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
@@ -8395,14 +8536,11 @@
8395 if( r<=(double)SMALLEST_INT64 ){
8396 iMin = SMALLEST_INT64;
8397 }else if( r>(double)LARGEST_INT64 ){
8398 goto series_no_rows;
8399 }else{
8400 iMin = (sqlite3_int64)seriesCeil(r);
8401 if( iMin<0 && r>0.0 ){
8402 iMin = LARGEST_INT64;
8403 }
8404 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8405 if( iMin==LARGEST_INT64 ) goto series_no_rows;
8406 iMin++;
8407 }
8408 }
@@ -8423,14 +8561,12 @@
8423 if( r>=(double)LARGEST_INT64 ){
8424 iMax = LARGEST_INT64;
8425 }else if( r<=(double)SMALLEST_INT64 ){
8426 goto series_no_rows;
8427 }else{
8428 iMax = (sqlite3_int64)seriesFloor(r);
8429 if( iMax<0 && r>0.0 ){
8430 iMax = LARGEST_INT64;
8431 }else if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
8432 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
8433 iMax--;
8434 }
8435 }
8436 }else{
@@ -10593,11 +10729,15 @@
10593 sqlite3_result_error_nomem(ctx);
10594 return SQLITE_NOMEM;
10595 }
10596 }
10597
10598 sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
 
 
 
 
10599 if( aBuf!=aStatic ) sqlite3_free(aBuf);
10600 #endif
10601 }else{
10602 readFileContents(ctx, pCur->zPath);
10603 }
@@ -14457,11 +14597,11 @@
14457 eocd.nEntry = (u16)p->nEntry;
14458 eocd.nEntryTotal = (u16)p->nEntry;
14459 eocd.nSize = p->cds.n;
14460 eocd.iOffset = p->body.n;
14461
14462 nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
14463 aZip = (u8*)sqlite3_malloc64(nZip);
14464 if( aZip==0 ){
14465 sqlite3_result_error_nomem(pCtx);
14466 }else{
14467 memcpy(aZip, p->body.a, p->body.n);
@@ -17584,16 +17724,19 @@
17584 }
17585 iRet++;
17586 }
17587 }
17588 else if( c=='[' ){
17589 while( z[iRet++]!=']' && z[iRet] );
17590 }
17591 else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
17592 while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
17593 iRet++;
17594 }
 
 
 
17595 }
17596
17597 return iRet;
17598 }
17599
@@ -18030,10 +18173,27 @@
18030 intckFinalize(p, pStmt);
18031
18032 if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
18033 return zRet;
18034 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18035
18036 /*
18037 ** Open a new integrity-check object.
18038 */
18039 int sqlite3_intck_open(
@@ -18052,13 +18212,11 @@
18052 }else{
18053 memset(pNew, 0, sizeof(*pNew));
18054 pNew->db = db;
18055 pNew->zDb = (const char*)&pNew[1];
18056 memcpy(&pNew[1], zDb, nDb+1);
18057 rc = sqlite3_create_function(db, "parse_create_index",
18058 2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0
18059 );
18060 if( rc!=SQLITE_OK ){
18061 sqlite3_intck_close(pNew);
18062 pNew = 0;
18063 }
18064 }
@@ -18071,13 +18229,11 @@
18071 ** Free the integrity-check object.
18072 */
18073 void sqlite3_intck_close(sqlite3_intck *p){
18074 if( p ){
18075 sqlite3_finalize(p->pCheck);
18076 sqlite3_create_function(
18077 p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0
18078 );
18079 sqlite3_free(p->zObj);
18080 sqlite3_free(p->zKey);
18081 sqlite3_free(p->zTestSql);
18082 sqlite3_free(p->zErr);
18083 sqlite3_free(p->zMessage);
@@ -20355,16 +20511,128 @@
20355 ){
20356 int rc = SQLITE_OK;
20357 SQLITE_EXTENSION_INIT2(pApi);
20358 (void)pzErrMsg; /* Unused parameter */
20359 rc = sqlite3_create_function(db, "diskused", 1,
20360 SQLITE_UTF8|SQLITE_INNOCUOUS,
20361 0, diskusedFunc, 0, 0);
20362 return rc;
20363 }
20364
20365 /************************* End ext/misc/diskused.c ********************/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20366
20367 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
20368 #define SQLITE_SHELL_HAVE_RECOVER 1
20369 #else
20370 #define SQLITE_SHELL_HAVE_RECOVER 0
@@ -24581,10 +24849,20 @@
24581 #endif
24582 #ifdef SQLITE_SHELL_EXTSRC
24583 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
24584 #endif
24585
 
 
 
 
 
 
 
 
 
 
24586 #if defined(SQLITE_ENABLE_SESSION)
24587 /*
24588 ** State information for a single open session
24589 */
24590 typedef struct OpenSession OpenSession;
@@ -24828,11 +25106,11 @@
24828 unsigned char eHdr; /* Default header encoding. */
24829 unsigned char eBlob; /* Default blob encoding. */
24830 unsigned char bHdr; /* Show headers by default. 0: n/a, 1: no 2: yes */
24831 unsigned char eStyle; /* Underlying QRF style */
24832 unsigned char eCx; /* 0: other, 1: line, 2: columnar */
24833 unsigned char mFlg; /* Flags. 1=border-off 2=split-column */
24834 };
24835
24836 /* String constants used by built-in modes */
24837 static const char *aModeStr[] =
24838 /* 0 1 2 3 4 5 6 7 8 */
@@ -24841,45 +25119,45 @@
24841 /* 9 10 11 12 13 */
24842
24843 static const ModeInfo aModeInfo[] = {
24844 /* zName eCSep eRSep eNull eText eHdr eBlob bHdr eStyle eCx mFlg */
24845 { "ascii", 7, 6, 9, 1, 1, 0, 1, 12, 0, 0 },
24846 { "box", 0, 0, 9, 1, 1, 0, 2, 1, 2, 0 },
24847 { "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 },
24848 { "column", 0, 0, 9, 1, 1, 0, 2, 2, 2, 0 },
24849 { "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 },
24850 { "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
24851 { "html", 0, 0, 9, 4, 4, 0, 2, 7, 0, 0 },
24852 { "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 },
24853 { "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 },
24854 { "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 },
24855 { "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 },
24856 { "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 },
24857 { "list", 2, 1, 9, 1, 1, 0, 1, 12, 0, 0 },
24858 { "markdown", 0, 0, 9, 1, 1, 0, 2, 13, 2, 0 },
24859 { "off", 0, 0, 0, 0, 0, 0, 0, 14, 0, 0 },
24860 { "psql", 0, 0, 9, 1, 1, 0, 2, 19, 2, 1 },
24861 { "qbox", 0, 0, 10, 2, 1, 0, 2, 1, 2, 0 },
24862 { "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 },
24863 { "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 },
24864 { "table", 0, 0, 9, 1, 1, 0, 2, 19, 2, 0 },
24865 { "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 },
24866 { "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 },
24867 { "www", 0, 0, 9, 4, 4, 0, 2, 7, 0, 0 }
24868 }; /* | / / | / / | | \
24869 ** | / / | / / | | \_ 2: columnar
24870 ** Index into aModeStr[] | / / | | 1: line
24871 ** | / / | | 0: other
24872 ** | / / | \
24873 ** text encoding |/ | show | \
24874 ** v-------------------' | hdrs? | The QRF style
24875 ** 0: n/a blob | v-----'
24876 ** 1: plain v----------' 0: n/a
24877 ** 2: sql 0: auto 1: no
24878 ** 3: csv 1: as-text 2: yes
24879 ** 4: html 2: sql
24880 ** 5: c 3: hex
24881 ** 6: json 4: c
24882 ** 5: json
24883 ** 6: size
24884 ******************************************************************/
24885
@@ -25162,11 +25440,11 @@
25162 */
25163 static char *local_getline(char *zLine, FILE *in){
25164 int nLine = zLine==0 ? 0 : 100;
25165 int n = 0;
25166
25167 while( 1 ){
25168 if( n+100>nLine ){
25169 if( nLine>=1073741773 ){
25170 free(zLine);
25171 return 0;
25172 }
@@ -25226,11 +25504,13 @@
25226 # define SQLITE_PS_APPDEF shellPromptAppDef
25227 static const char *shellPromptAppDef(int c){
25228 switch( c ){
25229 /* The default main prompt string */
25230 case 1:
25231 #if defined(SQLITE_PS1)
 
 
25232 return SQLITE_PS1;
25233 #else
25234 if( shellNoColor() ){
25235 return "/A-/v /f-> ";
25236 }else{
@@ -25238,11 +25518,13 @@
25238 }
25239 #endif
25240
25241 /* The default continuation prompt string */
25242 case 2:
25243 #if defined(SQLITE_PS2)
 
 
25244 return SQLITE_PS2;
25245 #else
25246 if( shellNoColor() ){
25247 return "/B/C-> ";
25248 }else{
@@ -25711,30 +25993,33 @@
25711 zResult = local_getline(zPrior, in);
25712 }else{
25713 const char *zBase = prompt_string(p, bContinue!=0);
25714 char *zPrompt = expand_prompt(p, zAll, zBase);
25715 shell_check_oom(zPrompt);
25716 #if SHELL_USE_LOCAL_GETLINE
25717 sputz(stdout, zPrompt);
25718 fflush(stdout);
25719 do{
25720 zResult = local_getline(zPrior, stdin);
25721 zPrior = 0;
25722 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
25723 if( zResult==0 ) sqlite3_sleep(50);
25724 }while( zResult==0 && seenInterrupt>0 );
25725 #else
25726 free(zPrior);
25727 zResult = shell_readline(zPrompt);
25728 while( zResult==0 ){
25729 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
25730 sqlite3_sleep(50);
25731 if( seenInterrupt==0 ) break;
25732 zResult = shell_readline("");
25733 }
25734 if( zResult && *zResult ) shell_add_history(zResult);
25735 #endif
 
 
 
25736 sqlite3_free(zPrompt);
25737 }
25738 return zResult;
25739 }
25740 #endif /* !SQLITE_SHELL_FIDDLE */
@@ -26307,11 +26592,11 @@
26307 free(p->spec.zColumnSep);
26308 free(p->spec.zRowSep);
26309 free(p->spec.zTableName);
26310 free(p->spec.zNull);
26311 memset(p, 0, sizeof(*p));
26312 p->spec.iVersion = 1;
26313 p->autoExplain = autoExplain;
26314 }
26315
26316 /*
26317 ** Duplicate Mode pSrc into pDest. pDest is assumed to be
@@ -26432,10 +26717,15 @@
26432 pM->spec.bSplitColumn = QRF_Yes;
26433 pM->bAutoScreenWidth = 1;
26434 }else{
26435 pM->spec.bSplitColumn = QRF_No;
26436 }
 
 
 
 
 
26437 }else if( eMode>=MODE_USER && eMode-MODE_USER<p->nSavedModes ){
26438 modeFree(&p->mode);
26439 modeDup(&p->mode, &p->aSavedModes[eMode-MODE_USER].mode);
26440 }else if( eMode==MODE_BATCH ){
26441 u8 mFlags = p->mode.mFlags;
@@ -26461,13 +26751,15 @@
26461 /*
26462 ** Set the mode to the default. It assumed that the mode has
26463 ** already been freed and zeroed prior to calling this routine.
26464 */
26465 static void modeDefault(ShellState *p){
26466 p->mode.spec.iVersion = 1;
26467 p->mode.autoExplain = 1;
26468 if( stdin_is_interactive || stdout_is_console ){
 
 
26469 modeChange(p, MODE_TTY);
26470 }else{
26471 modeChange(p, MODE_BATCH);
26472 }
26473 }
@@ -28827,10 +29119,11 @@
28827 " --quote ARG Enable/disable quoting of text. ARG can be\n"
28828 " \"off\", \"on\", \"sql\", \"relaxed\", \"csv\", \"html\",\n"
28829 " \"tcl\", or \"json\". \"off\" means show the text as-is.\n"
28830 " \"on\" is an alias for \"sql\".\n"
28831 " --reset Changes all mode settings back to their default.\n"
 
28832 " --rowsep STRING Use STRING as the row separator\n"
28833 " --sw|--screenwidth N Declare the screen width of the output device\n"
28834 " to be N characters. An attempt may be made to\n"
28835 " wrap output text to fit within this limit. Zero\n"
28836 " means \"no limit\". Or N can be \"auto\" to set the\n"
@@ -28838,11 +29131,11 @@
28838 " --tablename NAME Set the name of the table for \"insert\" mode.\n"
28839 " --tag NAME Save mode to the left as NAME.\n"
28840 " --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON.\n"
28841 " --title ARG Whether or not to show column headers, and if so\n"
28842 " how to encode them. ARG can be \"off\", \"on\",\n"
28843 " \"sql\", \"csv\", \"html\", \"tcl\", or \"json\".\n"
28844 " --titlelimit N Limit the length of column titles to N characters.\n"
28845 " -v|--verbose Verbose output\n"
28846 " --widths LIST Set the columns widths for columnar modes. The\n"
28847 " argument is a list of integers, one for each\n"
28848 " column. A \"0\" width means use a dynamic width\n"
@@ -29544,10 +29837,11 @@
29544 sqlite3_base85_init(p->db, 0, 0);
29545 sqlite3_regexp_init(p->db, 0, 0);
29546 sqlite3_ieee_init(p->db, 0, 0);
29547 sqlite3_series_init(p->db, 0, 0);
29548 sqlite3_diskused_init(p->db, 0, 0);
 
29549 #ifndef SQLITE_SHELL_FIDDLE
29550 sqlite3_fileio_init(p->db, 0, 0);
29551 sqlite3_completion_init(p->db, 0, 0);
29552 #endif
29553 #ifdef SQLITE_HAVE_ZLIB
@@ -32998,14 +33292,16 @@
32998 /*
32999 ** This function computes what to show the user about the configured
33000 ** titles (or column-names). Output is an integer between 0 and 3:
33001 **
33002 ** 0: The titles do not matter. Never show anything.
33003 ** 1: Show "--titles off"
33004 ** 2: Show "--titles on"
33005 ** 3: Show "--title VALUE" where VALUE is an encoding method
 
33006 ** to use, one of: plain sql csv html tcl json
 
33007 **
33008 ** Inputs are:
33009 **
33010 ** spec.bTitles (bT) Whether or not to show the titles
33011 ** spec.eTitle (eT) The actual encoding to be used for titles
@@ -33038,11 +33334,27 @@
33038 if( eT!=eH ) v >>= 32; /* Encoding disagree in upper 4-bytes */
33039 if( bT!=bH ) v >>= 16; /* ON/OFF disagree in upper 2-byte pairs */
33040 if( bT<2 ) v >>= 8; /* ON in even bytes, OFF in odd bytes (1st byte 0) */
33041 if( !bAll ) v >>= 4; /* bAll values are in the lower half-byte */
33042
33043 return v & 3; /* Return the selected truth-table entry */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33044 }
33045
33046 /*
33047 ** DOT-COMMAND: .mode
33048 **
@@ -33086,10 +33398,11 @@
33086 ** --quote ARG Enable/disable quoting of text. ARG can be
33087 ** "off", "on", "sql", "relaxed", "csv", "html",
33088 ** "tcl", or "json". "off" means show the text as-is.
33089 ** "on" is an alias for "sql".
33090 ** --reset Changes all mode settings back to their default.
 
33091 ** --rowsep STRING Use STRING as the row separator
33092 ** --sw|--screenwidth N Declare the screen width of the output device
33093 ** to be N characters. An attempt may be made to
33094 ** wrap output text to fit within this limit. Zero
33095 ** means "no limit". Or N can be "auto" to set the
@@ -33097,11 +33410,11 @@
33097 ** --tablename NAME Set the name of the table for "insert" mode.
33098 ** --tag NAME Save mode to the left as NAME.
33099 ** --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON.
33100 ** --title ARG Whether or not to show column headers, and if so
33101 ** how to encode them. ARG can be "off", "on",
33102 ** "sql", "csv", "html", "tcl", or "json".
33103 ** --titlelimit N Limit the length of column titles to N characters.
33104 ** -v|--verbose Verbose output
33105 ** --widths LIST Set the columns widths for columnar modes. The
33106 ** argument is a list of integers, one for each
33107 ** column. A "0" width means use a dynamic width
@@ -33325,10 +33638,17 @@
33325 chng = 1;
33326 }else if( optionMatch(z,"reset") ){
33327 int saved_eMode = p->mode.eMode;
33328 modeFree(&p->mode);
33329 modeChange(p, saved_eMode);
 
 
 
 
 
 
 
33330 }else if( optionMatch(z,"screenwidth") || optionMatch(z,"sw") ){
33331 if( (++i)>=nArg ){
33332 dotCmdError(p, i-1, "missing argument", 0);
33333 return 1;
33334 }
@@ -33378,25 +33698,63 @@
33378 return 1;
33379 }
33380 p->mode.spec.bTextJsonb = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
33381 chng = 1;
33382 }else if( optionMatch(z,"titles") || optionMatch(z,"title") ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33383 char *zErr = 0;
33384 if( i+1>=nArg ){
33385 dotCmdError(p, i, "missing argument", 0);
33386 return 1;
33387 }
33388 k = pickStr(azArg[++i],&zErr,
33389 "off","on","plain","sql","csv","html","tcl","json","");
33390 /* 0 1 2 3 4 5 6 7 */
33391 if( k<0 ){
33392 dotCmdError(p, i, "bad --titles value","%z", zErr);
33393 return 1;
33394 }
33395 p->mode.spec.bTitles = k>=1 ? QRF_Yes : QRF_No;
33396 p->mode.mFlags &= ~MFLG_HDR;
33397 p->mode.spec.eTitle = k>1 ? k-1 : aModeInfo[p->mode.eMode].eHdr;
 
 
 
 
 
 
 
 
 
 
33398 chng = 1;
33399 }else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
33400 int nWidth = 0;
33401 short int *aWidth;
33402 const char *zW;
@@ -33547,10 +33905,16 @@
33547 if( bAll
33548 || (pI->eText!=p->mode.spec.eText && (pI->eText>1 || p->mode.spec.eText>1))
33549 ){
33550 sqlite3_str_appendf(pDesc," --quote %s",qrfQuoteNames[p->mode.spec.eText]);
33551 }
 
 
 
 
 
 
33552 zSetting = aModeStr[pI->eRSep];
33553 if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zRowSep)!=0) ){
33554 sqlite3_str_appendf(pDesc, " --rowsep ");
33555 append_c_string(pDesc, p->mode.spec.zRowSep);
33556 }
@@ -33576,14 +33940,19 @@
33576 if( k==1 ){
33577 sqlite3_str_appendall(pDesc, " --titles off");
33578 }else if( k==2 ){
33579 sqlite3_str_appendall(pDesc, " --titles on");
33580 }else if( k==3 ){
 
 
33581 static const char *azTitle[] =
33582 { "plain", "sql", "csv", "html", "tcl", "json"};
33583 sqlite3_str_appendf(pDesc, " --titles %s",
33584 azTitle[p->mode.spec.eTitle-1]);
 
 
 
33585 }
33586 if( p->mode.spec.nWidth>0 && (bAll || pI->eCx==2) ){
33587 int ii;
33588 const char *zSep = " --widths ";
33589 for(ii=0; ii<p->mode.spec.nWidth; ii++){
@@ -34901,15 +35270,19 @@
34901 }
34902 }else
34903
34904 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
34905 if( nArg==2 ){
34906 p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
 
 
 
 
34907 p->mode.mFlags |= MFLG_HDR;
34908 p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
34909 }else{
34910 eputz("Usage: .headers on|off\n");
34911 rc = 1;
34912 }
34913 }else
34914
34915 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
@@ -35113,13 +35486,21 @@
35113 sqlite3_str_free(pSql);
35114 }else
35115
35116 if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
35117 i64 iArg = 0;
 
35118 if( nArg==2 ){
35119 iArg = integerValue(azArg[1]);
35120 if( iArg==0 ) iArg = -1;
 
 
 
 
 
 
 
35121 }
35122 if( (nArg!=1 && nArg!=2) || iArg<0 ){
35123 cli_printf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n");
35124 rc = 1;
35125 goto meta_command_exit;
@@ -35167,10 +35548,11 @@
35167 { "attached", SQLITE_LIMIT_ATTACHED },
35168 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
35169 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
35170 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
35171 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
 
35172 };
35173 int i, n2;
35174 open_db(p, 0);
35175 if( nArg==1 ){
35176 for(i=0; i<ArraySize(aLimit); i++){
@@ -36493,11 +36875,12 @@
36493 azBool[(p->mode.mFlags & MFLG_ECHO)!=0]);
36494 cli_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->mode.autoEQP&3]);
36495 cli_printf(p->out, "%12.12s: %s\n","explain",
36496 p->mode.autoExplain ? "auto" : "off");
36497 cli_printf(p->out, "%12.12s: %s\n","headers",
36498 azBool[p->mode.spec.bTitles==QRF_Yes]);
 
36499 if( p->mode.spec.eStyle==QRF_STYLE_Column
36500 || p->mode.spec.eStyle==QRF_STYLE_Box
36501 || p->mode.spec.eStyle==QRF_STYLE_Table
36502 || p->mode.spec.eStyle==QRF_STYLE_Markdown
36503 ){
@@ -37860,10 +38243,11 @@
37860 " -ascii set '.mode ascii'\n"
37861 " -bail stop after hitting an error\n"
37862 " -batch force batch I/O\n"
37863 " -box set '.mode box'\n"
37864 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
 
37865 " -column set '.mode column'\n"
37866 " -csv set '.mode csv -limits off'\n"
37867 #if !defined(SQLITE_OMIT_DESERIALIZE)
37868 " -deserialize open the database using sqlite3_deserialize()\n"
37869 #endif
@@ -38130,10 +38514,13 @@
38130 stdout_is_console = 1;
38131 data.wasm.zDefaultDbName = "/fiddle.sqlite3";
38132 #else
38133 stdin_is_interactive = isatty(0);
38134 stdout_is_console = isatty(1);
 
 
 
38135 #endif
38136 atexit(abnormalExit);
38137 #ifdef SQLITE_DEBUG
38138 mem_main_enter = sqlite3_memory_used();
38139 #endif
@@ -38377,10 +38764,12 @@
38377 }else if( cli_strcmp(z,"-safe")==0 ){
38378 /* no-op - catch this on the second pass */
38379 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
38380 /* skip over the argument */
38381 i++;
 
 
38382 }else if( cli_strcmp(z,"-test-argv")==0 ){
38383 /* Undocumented test option. Print the values in argv[] and exit.
38384 ** Use this to verify that any translation of the argv[], for example
38385 ** on Windows that receives wargv[] from the OS and must convert
38386 ** to UTF8 prior to calling this routine. */
@@ -38567,11 +38956,11 @@
38567 cmdline_option_value(argc,argv,++i));
38568 }else if( cli_strcmp(z,"-nullvalue")==0 ){
38569 modeSetStr(&data.mode.spec.zNull,
38570 cmdline_option_value(argc,argv,++i));
38571 }else if( cli_strcmp(z,"-header")==0 ){
38572 data.mode.spec.bTitles = QRF_Yes;
38573 data.mode.mFlags |= MFLG_HDR;
38574 }else if( cli_strcmp(z,"-noheader")==0 ){
38575 data.mode.spec.bTitles = QRF_No;
38576 data.mode.mFlags |= MFLG_HDR;
38577 }else if( cli_strcmp(z,"-echo")==0 ){
@@ -38639,10 +39028,12 @@
38639 i++;
38640 #ifdef SQLITE_ENABLE_MULTIPLEX
38641 }else if( cli_strcmp(z,"-multiplex")==0 ){
38642 i++;
38643 #endif
 
 
38644 }else if( cli_strcmp(z,"-help")==0 ){
38645 usage(1);
38646 }else if( cli_strcmp(z,"-cmd")==0 ){
38647 /* Run commands that follow -cmd first and separately from commands
38648 ** that simply appear on the command-line. This seems goofy. It would
@@ -38668,12 +39059,14 @@
38668 rc = 1;
38669 goto shell_main_exit;
38670 }
38671 open_db(&data, OPEN_DB_ZIPFILE);
38672 if( z[2] ){
 
38673 argv[i] = &z[2];
38674 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
 
38675 }else{
38676 arDotCommand(&data, 1, argv+i, argc-i);
38677 }
38678 readStdin = 0;
38679 stdin_is_interactive = 0;
38680
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -23,10 +23,11 @@
23 ** ext/misc/shathree.c
24 ** ext/misc/sqlar.c
25 ** ext/misc/sqlite3_stdio.c
26 ** ext/misc/sqlite3_stdio.h
27 ** ext/misc/stmtrand.c
28 ** ext/misc/strdup.c
29 ** ext/misc/uint.c
30 ** ext/misc/vfstrace.c
31 ** ext/misc/windirent.h
32 ** ext/misc/zipfile.c
33 ** ext/qrf/qrf.c
@@ -205,28 +206,38 @@
206 # define shell_add_history(X) add_history(X)
207 # define shell_read_history(X) read_history(X)
208 # define shell_write_history(X) write_history(X)
209 # define shell_stifle_history(X) stifle_history(X)
210 # define shell_readline(X) readline(X)
211 # define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */
212
213 #elif HAVE_LINENOISE
214
215 # include "linenoise.h"
216 # define shell_add_history(X) linenoiseHistoryAdd(X)
217 # define shell_read_history(X) linenoiseHistoryLoad(X)
218 # define shell_write_history(X) linenoiseHistorySave(X)
219 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
220 # define shell_readline(X) linenoise(X)
221 # define SHELL_CMDLINE_EDIT_AVAILABLE 1 /* command-line editing available */
222
223 #else
224
225 # define shell_read_history(X)
226 # define shell_write_history(X)
227 # define shell_stifle_history(X)
228 # define SHELL_CMDLINE_EDIT_AVAILABLE 0 /* command-line editing not available */
229 #endif
230
231 /*
232 ** Global variable shellCmdLineEdit determines whether or not command-line
233 ** editing is enabled. It defaults to 1 if the CLI is linked against a
234 ** command-line editing library (linenoise, readline, or editline) and
235 ** to 0 if no command-line editing library is available. The
236 ** "--cmdline-edit off" command-line option will change this value to 0.
237 */
238 static int shellCmdLineEdit = SHELL_CMDLINE_EDIT_AVAILABLE;
239
240 #ifndef deliberate_fall_through
241 /* Quiet some compilers about some of our intentional code. */
242 # if defined(GCC_VERSION) && GCC_VERSION>=7000000
243 # define deliberate_fall_through __attribute__((fallthrough));
@@ -733,10 +744,12 @@
744 char *(*xRender)(void*,sqlite3_value*); /* Render a value */
745 int (*xWrite)(void*,const char*,sqlite3_int64); /* Write output */
746 void *pRenderArg; /* First argument to the xRender callback */
747 void *pWriteArg; /* First argument to the xWrite callback */
748 char **pzOutput; /* Storage location for output string */
749 /* The following are available in iVersion 2 and later */
750 unsigned char bRowCount; /* Show the number of rows at end of each query */
751 /* Additional fields may be added in the future */
752 };
753
754 /*
755 ** Interfaces
@@ -761,11 +774,11 @@
774 #define QRF_STYLE_Column 2 /* One record per line in neat columns */
775 #define QRF_STYLE_Count 3 /* Output only a count of the rows of output */
776 #define QRF_STYLE_Csv 4 /* Comma-separated-value */
777 #define QRF_STYLE_Eqp 5 /* Format EXPLAIN QUERY PLAN output */
778 #define QRF_STYLE_Explain 6 /* EXPLAIN output */
779 #define QRF_STYLE_Html 7 /* Generate HTML-style <tr><td> output */
780 #define QRF_STYLE_Insert 8 /* Generate SQL "insert" statements */
781 #define QRF_STYLE_Json 9 /* Output is a list of JSON objects */
782 #define QRF_STYLE_JObject 10 /* Independent JSON objects for each row */
783 #define QRF_STYLE_Line 11 /* One column per line. */
784 #define QRF_STYLE_List 12 /* One record per line with a separator */
@@ -821,10 +834,15 @@
834 #define QRF_SW_On 2 /* This setting is forced on */
835 #define QRF_Auto 0 /* Alternate spelling for QRF_*_Auto */
836 #define QRF_No 1 /* Alternate spelling for QRF_SW_Off */
837 #define QRF_Yes 2 /* Alternate spelling for QRF_SW_On */
838
839 /*
840 ** Additional value allowed for bTitles
841 */
842 #define QRF_Always 3 /* Always show titles, even if no rows */
843
844 /*
845 ** Possible alignment values alignment settings
846 **
847 ** Horizontal Vertial
848 ** ---------- -------- */
@@ -2527,10 +2545,14 @@
2545 /* Doubled horizontal lines: */
2546 #define DBL_24 "\342\225\220" /* U+2550 === */
2547 #define DBL_123 "\342\225\236" /* U+255e |= */
2548 #define DBL_134 "\342\225\241" /* U+2561 =| */
2549 #define DBL_1234 "\342\225\252" /* U+256a =|= */
2550 #define DBL_12 "\342\225\230" /* U+2558 `= */
2551 #define DBL_14 "\342\225\233" /* U+255b =' */
2552 #define DBL_124 "\342\225\247" /* U+2567 ='= */
2553
2554
2555 /* Draw horizontal line N characters long using unicode box
2556 ** characters
2557 */
2558 static void qrfBoxLine(sqlite3_str *pOut, int N, int bDbl){
@@ -2549,16 +2571,16 @@
2571
2572 /*
2573 ** Draw a horizontal separator for a QRF_STYLE_Box table.
2574 */
2575 static void qrfBoxSeparator(
2576 sqlite3_str *pOut, /* Output to this sqlite3_str */
2577 qrfColData *p, /* Columnar data */
2578 const char *zSep1, /* Left margin */
2579 const char *zSep2, /* Column separator */
2580 const char *zSep3, /* Right margin */
2581 int bDbl /* True for double-lines */
2582 ){
2583 int i;
2584 if( p->nCol>0 ){
2585 int useBorder = p->p->spec.bBorder!=QRF_No;
2586 if( useBorder ){
@@ -2573,10 +2595,36 @@
2595 sqlite3_str_appendall(pOut, zSep3);
2596 }
2597 }
2598 sqlite3_str_append(pOut, "\n", 1);
2599 }
2600
2601 /*
2602 ** Draw a horizontal separator for a QRF_STYLE_Column table.
2603 ** This style of separator is only used for separating the title
2604 ** from the content.
2605 */
2606 static void qrfColumnSeparator(
2607 sqlite3_str *pOut, /* Output to this sqlite3_str */
2608 qrfColData *p, /* Columnar data */
2609 const char *colSep, /* Column separator text */
2610 int szColSep, /* Size of zColSep in bytes */
2611 const char *rowSep, /* Row separator text */
2612 int szRowSep /* Size of zRowSep in bytes */
2613 ){
2614 int j;
2615 int nColumn = p->nCol;
2616 for(j=0; j<nColumn; j++){
2617 sqlite3_str_appendchar(pOut, p->a[j].w, '-');
2618 if( j<nColumn-1 ){
2619 sqlite3_str_append(pOut, colSep, szColSep);
2620 }else{
2621 qrfRTrim(pOut);
2622 sqlite3_str_append(pOut, rowSep, szRowSep);
2623 }
2624 }
2625 }
2626
2627 /*
2628 ** Load into pData the default alignment for the body of a table.
2629 */
2630 static void qrfLoadAlignment(qrfColData *pData, Qrf *p){
@@ -2831,11 +2879,25 @@
2879 sqlite3_str *pStr; /* Temporary rendering */
2880 qrfColData data; /* Columnar layout data */
2881 int bRTrim; /* Trim trailing space */
2882
2883 rc = sqlite3_step(p->pStmt);
2884 if( nColumn==0 ){
2885 return; /* Not a query. No results every shown. */
2886 }
2887 if( rc==SQLITE_DONE && nColumn>0 ){
2888 /* Empty query */
2889 if( p->spec.bTitles==QRF_Always ){
2890 /* fall through into the columnar logic below */
2891 }else{
2892 if( p->spec.bRowCount==QRF_Yes ){
2893 sqlite3_str_appendf(p->pOut, "(0 rows)\n");
2894 qrfWrite(p);
2895 }
2896 return; /* No output, other than the row count */
2897 }
2898 }else if( rc!=SQLITE_ROW ){
2899 return; /* No output */
2900 }
2901
2902 /* Initialize the data container */
2903 memset(&data, 0, sizeof(data));
@@ -2848,12 +2910,12 @@
2910 }
2911 memset(data.a, 0, nColumn*sizeof(struct qrfPerCol) );
2912 if( qrfColDataEnlarge(&data) ) return;
2913 assert( data.az!=0 );
2914
2915 /* Load the column header names into data */
2916 if( p->spec.bTitles>=QRF_Yes ){
2917 unsigned char saved_eText = p->spec.eText;
2918 p->spec.eText = p->spec.eTitle;
2919 memset(data.abNum, 0, nColumn);
2920 for(i=0; i<nColumn; i++){
2921 const char *z = (const char*)sqlite3_column_name(p->pStmt,i);
@@ -2874,13 +2936,14 @@
2936 data.n++;
2937 if( w>data.a[i].mxW ) data.a[i].mxW = w;
2938 if( nNL ) data.bMultiRow = 1;
2939 }
2940 p->spec.eText = saved_eText;
 
2941 }
2942
2943 /* Load query results into data */
2944 while( rc==SQLITE_ROW && p->iErr==SQLITE_OK ){
2945 if( data.n+nColumn > data.nAlloc ){
2946 if( qrfColDataEnlarge(&data) ) return;
2947 }
2948 for(i=0; i<nColumn; i++){
2949 char *z;
@@ -2897,11 +2960,12 @@
2960 data.n++;
2961 if( w>data.a[i].mxW ) data.a[i].mxW = w;
2962 if( nNL ) data.bMultiRow = 1;
2963 }
2964 p->nRow++;
2965 rc = sqlite3_step(p->pStmt);
2966 }
2967 if( p->iErr ){
2968 qrfColDataFree(&data);
2969 return;
2970 }
2971
@@ -3105,11 +3169,11 @@
3169 /* Draw either (1) the separator between the title line and the body
3170 ** of the table, or (2) separators between individual rows of the table
3171 ** body. isTitleDataSeparator will be true if we are doing (1).
3172 */
3173 if( (i==0 || data.bMultiRow) && i+nColumn<data.n ){
3174 int isTitleDataSeparator = (i==0 && p->spec.bTitles>=QRF_Yes);
3175 if( isTitleDataSeparator ){
3176 qrfLoadAlignment(&data, p);
3177 }
3178 switch( p->spec.eStyle ){
3179 case QRF_STYLE_Table: {
@@ -3132,19 +3196,12 @@
3196 }
3197 break;
3198 }
3199 case QRF_STYLE_Column: {
3200 if( isTitleDataSeparator ){
3201 qrfColumnSeparator(p->pOut, &data, colSep, szColSep,
3202 rowSep, szRowSep);
 
 
 
 
 
 
 
3203 }else if( data.bMultiRow ){
3204 qrfRTrim(p->pOut);
3205 sqlite3_str_append(p->pOut, "\n", 1);
3206 }
3207 break;
@@ -3152,20 +3209,39 @@
3209 }
3210 }
3211 }
3212
3213 /* Draw the line across the bottom of the table */
3214 if( p->spec.bBorder!=QRF_No || p->nRow==0 ){
3215 switch( p->spec.eStyle ){
3216 case QRF_STYLE_Box:
3217 if( p->nRow>0 ){
3218 qrfBoxSeparator(p->pOut, &data, BOX_R12, BOX_124, BOX_R14, 0);
3219 }else{
3220 qrfBoxSeparator(p->pOut, &data, DBL_12, DBL_124, DBL_14, 1);
3221 }
3222 break;
3223 case QRF_STYLE_Table:
3224 qrfRowSeparator(p->pOut, &data, '+');
3225 break;
3226 case QRF_STYLE_Markdown:
3227 if( p->nRow==0 ){
3228 qrfRowSeparator(p->pOut, &data, '|');
3229 }
3230 break;
3231 case QRF_STYLE_Column:
3232 if( p->nRow==0 ){
3233 qrfColumnSeparator(p->pOut, &data, colSep, szColSep,
3234 rowSep, szRowSep);
3235 }
3236 break;
3237 }
3238 }
3239 if( p->spec.bRowCount==QRF_Yes ){
3240 sqlite3_int64 n = p->nRow;
3241 sqlite3_str_appendf(p->pOut, "(%lld row%s)\n", n, n==1 ? "" : "s");
3242 }
3243 qrfWrite(p);
3244
3245 qrfColDataFree(&data);
3246 return;
3247 }
@@ -3412,10 +3488,49 @@
3488 sqlite3_str_append(p->pOut, ":", 1);
3489 qrfRenderValue(p, p->pOut, i);
3490 }
3491 qrfWrite(p);
3492 }
3493
3494 /*
3495 ** Render a title row (a row containing column names) if the spec
3496 ** calls for one and if it makes sense for the eStyle. Title rows
3497 ** do not make sense for some eStyles, such as QRF_STYLE_Off,
3498 ** QRF_STYLE_Count, QRF_STYLE_Json, and similar.
3499 */
3500 static void qrfSimpleTitle(Qrf *p){
3501 assert( p->nRow==0 );
3502 assert( p->spec.bTitles>=QRF_Yes );
3503 switch( p->spec.eStyle ){
3504 case QRF_STYLE_Html: {
3505 int i;
3506 sqlite3_str_append(p->pOut, "<tr>", 4);
3507 for(i=0; i<p->nCol; i++){
3508 const char *zCName = sqlite3_column_name(p->pStmt, i);
3509 sqlite3_str_append(p->pOut, "\n<th>", 5);
3510 qrfEncodeText(p, p->pOut, zCName);
3511 }
3512 sqlite3_str_append(p->pOut, "\n</tr>\n", 7);
3513 break;
3514 }
3515 case QRF_STYLE_Quote:
3516 case QRF_STYLE_List: {
3517 int i;
3518 int saved_eText = p->spec.eText;
3519 p->spec.eText = p->spec.eTitle;
3520 for(i=0; i<p->nCol; i++){
3521 const char *zCName = sqlite3_column_name(p->pStmt, i);
3522 if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
3523 qrfEncodeText(p, p->pOut, zCName);
3524 }
3525 sqlite3_str_appendall(p->pOut, p->spec.zRowSep);
3526 qrfWrite(p);
3527 p->spec.eText = saved_eText;
3528 break;
3529 }
3530 }
3531 }
3532
3533 /*
3534 ** Render a single row of output for non-columnar styles - any
3535 ** style that lets us render row by row as the content is received
3536 ** from the query.
@@ -3445,25 +3560,19 @@
3560 }
3561 qrfOneJsonRow(p);
3562 break;
3563 }
3564 case QRF_STYLE_Html: {
3565 if( p->nRow==0 && p->spec.bTitles>=QRF_Yes ){
3566 qrfSimpleTitle(p);
3567 }
3568 sqlite3_str_append(p->pOut, "<tr>", 4);
3569 for(i=0; i<p->nCol; i++){
3570 sqlite3_str_append(p->pOut, "\n<td>", 5);
 
 
 
 
 
 
3571 qrfRenderValue(p, p->pOut, i);
3572 }
3573 sqlite3_str_append(p->pOut, "\n</tr>\n", 7);
3574 qrfWrite(p);
3575 break;
3576 }
3577 case QRF_STYLE_Insert: {
3578 unsigned int mxIns = p->spec.nMultiInsert;
@@ -3476,11 +3585,11 @@
3585 if( qrf_need_quote(p->spec.zTableName) ){
3586 sqlite3_str_appendf(p->pOut,"INSERT INTO \"%w\"",p->spec.zTableName);
3587 }else{
3588 sqlite3_str_appendf(p->pOut,"INSERT INTO %s",p->spec.zTableName);
3589 }
3590 if( p->spec.bTitles>=QRF_Yes ){
3591 for(i=0; i<p->nCol; i++){
3592 const char *zCName = sqlite3_column_name(p->pStmt, i);
3593 if( qrf_need_quote(zCName) ){
3594 sqlite3_str_appendf(p->pOut, "%c\"%w\"",
3595 i==0 ? '(' : ',', zCName);
@@ -3576,21 +3685,12 @@
3685 if( zEqpLine[0]=='-' ) qrfEqpRender(p, 0);
3686 qrfEqpAppend(p, iEqpId, iParentId, zEqpLine);
3687 break;
3688 }
3689 default: { /* QRF_STYLE_List */
3690 if( p->nRow==0 && p->spec.bTitles>=QRF_Yes ){
3691 qrfSimpleTitle(p);
 
 
 
 
 
 
 
 
 
3692 }
3693 for(i=0; i<p->nCol; i++){
3694 if( i>0 ) sqlite3_str_appendall(p->pOut, p->spec.zColumnSep);
3695 qrfRenderValue(p, p->pOut, i);
3696 }
@@ -3612,11 +3712,11 @@
3712 char **pzErr /* Write errors here */
3713 ){
3714 size_t sz; /* Size of pSpec[], based on pSpec->iVersion */
3715 memset(p, 0, sizeof(*p));
3716 p->pzErr = pzErr;
3717 if( pSpec->iVersion>2 ){
3718 qrfError(p, SQLITE_ERROR,
3719 "unusable sqlite3_qrf_spec.iVersion (%d)",
3720 pSpec->iVersion);
3721 return;
3722 }
@@ -3640,10 +3740,13 @@
3740 if( p->spec.eStyle>QRF_STYLE_Table ) p->spec.eStyle = QRF_Auto;
3741 if( p->spec.eEsc>QRF_ESC_Symbol ) p->spec.eEsc = QRF_Auto;
3742 if( p->spec.eText>QRF_TEXT_Relaxed ) p->spec.eText = QRF_Auto;
3743 if( p->spec.eTitle>QRF_TEXT_Relaxed ) p->spec.eTitle = QRF_Auto;
3744 if( p->spec.eBlob>QRF_BLOB_Size ) p->spec.eBlob = QRF_Auto;
3745 if( pSpec->iVersion<=1 ){
3746 p->spec.bRowCount = 0;
3747 }
3748 qrf_reinit:
3749 switch( p->spec.eStyle ){
3750 case QRF_Auto: {
3751 switch( sqlite3_stmt_isexplain(pStmt) ){
3752 case 0: p->spec.eStyle = QRF_STYLE_Box; break;
@@ -3898,10 +4001,34 @@
4001 default: {
4002 /* Non-columnar modes where the output can occur after each row
4003 ** of result is received */
4004 while( qrf.iErr==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
4005 qrfOneSimpleRow(&qrf);
4006 }
4007 if( qrf.nCol>0 && qrf.nRow==0 && qrf.spec.bTitles==QRF_Always ){
4008 qrfSimpleTitle(&qrf);
4009 }
4010 if( qrf.nCol>0 && qrf.spec.bRowCount==QRF_Yes ){
4011 const char *zPlural = qrf.nRow==1 ? "" : "s";
4012 switch( qrf.spec.eStyle ){
4013 case QRF_STYLE_Line:
4014 if( qrf.nRow>0 ) sqlite3_str_append(qrf.pOut, "\n", 1);
4015 /* Fall through */
4016 case QRF_STYLE_Csv:
4017 case QRF_STYLE_List:
4018 case QRF_STYLE_Quote:
4019 sqlite3_str_appendf(qrf.pOut,"(%lld row%s)\n",qrf.nRow,zPlural);
4020 break;
4021 case QRF_STYLE_Html:
4022 sqlite3_str_appendf(qrf.pOut,"<!-- %lld row%s -->\n",
4023 qrf.nRow, zPlural);
4024 break;
4025 case QRF_STYLE_Insert:
4026 sqlite3_str_appendf(qrf.pOut,"/* %lld row%s inserted */\n",
4027 qrf.nRow, zPlural);
4028 break;
4029 }
4030 }
4031 break;
4032 }
4033 }
4034 qrfResetStmt(&qrf);
@@ -5839,10 +5966,13 @@
5966 }
5967
5968 /*
5969 ** Allocate a new Decimal object initialized to the text in zIn[].
5970 ** Return NULL if any kind of error occurs.
5971 **
5972 ** Note that zIn[] is not necessarily zero-terminated. Always
5973 ** respect the boundary imposed by the n argument.
5974 */
5975 static Decimal *decimalNewFromText(const char *zIn, int n){
5976 Decimal *p = 0;
5977 int i;
5978 int iExp = 0;
@@ -5856,15 +5986,15 @@
5986 p->isNull = 0;
5987 p->nDigit = 0;
5988 p->nFrac = 0;
5989 p->a = sqlite3_malloc64( n+1 );
5990 if( p->a==0 ) goto new_from_text_failed;
5991 for(i=0; i<n && IsSpace(zIn[i]); i++){}
5992 if( i<n && zIn[i]=='-' ){
5993 p->sign = 1;
5994 i++;
5995 }else if( i<n && zIn[i]=='+' ){
5996 i++;
5997 }
5998 while( i<n && zIn[i]=='0' ) i++;
5999 while( i<n ){
6000 char c = zIn[i];
@@ -6091,11 +6221,11 @@
6221 if( p->a[N]>=5 ){
6222 /* If all leading digits are 9, increase the number of digits
6223 ** by adding a new 0 to the front */
6224 for(i=0; i<N && p->a[i]==9; i++){}
6225 if( i==N ){
6226 decimal_expand(p, p->nDigit+1, p->nFrac);
6227 if( p->oom ) return;
6228 }
6229
6230 /* Do the rounding */
6231 p->a[N-1]++;
@@ -6249,10 +6379,11 @@
6379 int nAddSig;
6380 int nAddFrac;
6381 signed char *a;
6382 if( p==0 ) return;
6383 nAddFrac = nFrac - p->nFrac;
6384 assert( nAddFrac>=0 );
6385 nAddSig = (nDigit - p->nDigit) - nAddFrac;
6386 if( nAddFrac==0 && nAddSig==0 ) return;
6387 if( nDigit+1>SQLITE_DECIMAL_MAX_DIGIT ){ p->oom = 1; return; }
6388 a = sqlite3_realloc64(p->a, nDigit+1);
6389 if( a==0 ){
@@ -8256,10 +8387,20 @@
8387 if( r==(double)x ) return r;
8388 if( r<(double)x ) x--;
8389 return (double)x;
8390 }
8391 #endif
8392
8393 /* Convert a floating point value to its closest integer. Do so in
8394 ** a way that avoids 'outside the range of representable values' warnings
8395 ** from UBSAN.
8396 */
8397 static sqlite3_int64 seriesRealToI64(double r){
8398 if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
8399 if( r>+9223372036854774784.0 ) return LARGEST_INT64;
8400 return (sqlite3_int64)r;
8401 }
8402
8403 /*
8404 ** This method is called to "rewind" the series_cursor object back
8405 ** to the first row of output. This method is always called at least
8406 ** once prior to any call to seriesColumn() or seriesRowid() or
@@ -8379,11 +8520,11 @@
8520 double r = sqlite3_value_double(argv[iArg++]);
8521 if( r==seriesCeil(r)
8522 && r>=(double)SMALLEST_INT64
8523 && r<=(double)LARGEST_INT64
8524 ){
8525 iMin = iMax = seriesRealToI64(r);
8526 }else{
8527 goto series_no_rows;
8528 }
8529 }else{
8530 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
@@ -8395,14 +8536,11 @@
8536 if( r<=(double)SMALLEST_INT64 ){
8537 iMin = SMALLEST_INT64;
8538 }else if( r>(double)LARGEST_INT64 ){
8539 goto series_no_rows;
8540 }else{
8541 iMin = seriesRealToI64(seriesCeil(r));
 
 
 
8542 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
8543 if( iMin==LARGEST_INT64 ) goto series_no_rows;
8544 iMin++;
8545 }
8546 }
@@ -8423,14 +8561,12 @@
8561 if( r>=(double)LARGEST_INT64 ){
8562 iMax = LARGEST_INT64;
8563 }else if( r<=(double)SMALLEST_INT64 ){
8564 goto series_no_rows;
8565 }else{
8566 iMax = seriesRealToI64(seriesFloor(r));
8567 if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
 
 
8568 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
8569 iMax--;
8570 }
8571 }
8572 }else{
@@ -10593,11 +10729,15 @@
10729 sqlite3_result_error_nomem(ctx);
10730 return SQLITE_NOMEM;
10731 }
10732 }
10733
10734 if( n>0 ){
10735 sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
10736 }else{
10737 sqlite3_result_null(ctx);
10738 }
10739 if( aBuf!=aStatic ) sqlite3_free(aBuf);
10740 #endif
10741 }else{
10742 readFileContents(ctx, pCur->zPath);
10743 }
@@ -14457,11 +14597,11 @@
14597 eocd.nEntry = (u16)p->nEntry;
14598 eocd.nEntryTotal = (u16)p->nEntry;
14599 eocd.nSize = p->cds.n;
14600 eocd.iOffset = p->body.n;
14601
14602 nZip = (i64)p->body.n + (i64)p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
14603 aZip = (u8*)sqlite3_malloc64(nZip);
14604 if( aZip==0 ){
14605 sqlite3_result_error_nomem(pCtx);
14606 }else{
14607 memcpy(aZip, p->body.a, p->body.n);
@@ -17584,16 +17724,19 @@
17724 }
17725 iRet++;
17726 }
17727 }
17728 else if( c=='[' ){
17729 while( z[iRet] && z[iRet++]!=']' ){}
17730 }
17731 else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){
17732 while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){
17733 iRet++;
17734 }
17735 }
17736 else if( c==0 ){
17737 iRet = 0;
17738 }
17739
17740 return iRet;
17741 }
17742
@@ -18030,10 +18173,27 @@
18173 intckFinalize(p, pStmt);
18174
18175 if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1");
18176 return zRet;
18177 }
18178
18179 /*
18180 ** Register or unregister special SQL functions implemented by intck.
18181 **
18182 ** Normally the custom SQL functions used by intck are only available
18183 ** in between sqlite3_intck_open() and sqlite3_intck_close(). However,
18184 ** for testing and debugging, it is sometimes useful to make those
18185 ** functions available generally. This routine provides as a separate
18186 ** interface in order to provide that capability.
18187 */
18188 int sqlite3_intck_register(sqlite3 *db, int bCreate){
18189 int rc;
18190 rc = sqlite3_create_function(db, "parse_create_index",
18191 2, SQLITE_UTF8, 0, bCreate ? intckParseCreateIndexFunc : 0, 0, 0
18192 );
18193 return rc;
18194 }
18195
18196 /*
18197 ** Open a new integrity-check object.
18198 */
18199 int sqlite3_intck_open(
@@ -18052,13 +18212,11 @@
18212 }else{
18213 memset(pNew, 0, sizeof(*pNew));
18214 pNew->db = db;
18215 pNew->zDb = (const char*)&pNew[1];
18216 memcpy(&pNew[1], zDb, nDb+1);
18217 rc = sqlite3_intck_register(db, 1);
 
 
18218 if( rc!=SQLITE_OK ){
18219 sqlite3_intck_close(pNew);
18220 pNew = 0;
18221 }
18222 }
@@ -18071,13 +18229,11 @@
18229 ** Free the integrity-check object.
18230 */
18231 void sqlite3_intck_close(sqlite3_intck *p){
18232 if( p ){
18233 sqlite3_finalize(p->pCheck);
18234 sqlite3_intck_register(p->db, 0);
 
 
18235 sqlite3_free(p->zObj);
18236 sqlite3_free(p->zKey);
18237 sqlite3_free(p->zTestSql);
18238 sqlite3_free(p->zErr);
18239 sqlite3_free(p->zMessage);
@@ -20355,16 +20511,128 @@
20511 ){
20512 int rc = SQLITE_OK;
20513 SQLITE_EXTENSION_INIT2(pApi);
20514 (void)pzErrMsg; /* Unused parameter */
20515 rc = sqlite3_create_function(db, "diskused", 1,
20516 SQLITE_UTF8|SQLITE_DIRECTONLY,
20517 0, diskusedFunc, 0, 0);
20518 return rc;
20519 }
20520
20521 /************************* End ext/misc/diskused.c ********************/
20522 /************************* Begin ext/misc/strdup.c ******************/
20523 /*
20524 ** 2026-07-04
20525 **
20526 ** The author disclaims copyright to this source code. In place of
20527 ** a legal notice, here is a blessing:
20528 **
20529 ** May you do good and not evil.
20530 ** May you find forgiveness for yourself and forgive others.
20531 ** May you share freely, never taking more than you give.
20532 **
20533 ******************************************************************************
20534 **
20535 ** Since this module was written (coincidentally) on the 250th anniversary
20536 ** of the signing of the Declaration of Independence of The United States,
20537 ** it seems fitting to quote from that document:
20538 **
20539 ** We hold these truths to be self-evident, that all men are created
20540 ** equal, that they are endowed by their Creator with certain unalienable
20541 ** Rights, that among these are Life, Liberty and the pursuit of Happiness
20542 ** - That to secure these rights, Governments are instituted among Men,
20543 ** deriving their just powers from the consent of the governed,....
20544 **
20545 ** Two core ideas that (1) rights come from God and not from government,
20546 ** and that (2) there should not be special privileged classes of people
20547 ** were radical thoughts then, and are indeed disputed even today. Many
20548 ** people still hold that human rights derive from the beneficence of
20549 ** government and that certain classes of people have special rights and
20550 ** privileges not available to all. Yet, were it not for the crazy ideas
20551 ** espoused in the original Declaration of Independence, this software
20552 ** project, and indeed most of modern technology, would not exist.
20553 **
20554 ** Therefore let us give thanks for the bold leadership and vision
20555 ** demonstrated by the authors of the American Revolution, 250 years ago
20556 ** this day.
20557 **
20558 ******************************************************************************
20559 **
20560 ** Implementation of the strdup() SQL function. strdup() makes a copy
20561 ** of its argument (a string or a BLOB) into memory obtained directly
20562 ** from system malloc() (not from sqlite3_malloc()) and sized exactly
20563 ** to hold the string or BLOB. This is intended for testing purposes,
20564 ** particularly testing with ASAN. This function serves no practical
20565 ** purpose beyond testing and not not intended for production use.
20566 **
20567 ** NULL, BLOB, and TEXT values come through as NULL, BLOB, and TEXT,
20568 ** respectively. Numeric values are rendered as strings and come out
20569 ** as text.
20570 */
20571 /* #include "sqlite3ext.h" */
20572 SQLITE_EXTENSION_INIT1
20573 #include <assert.h>
20574 #include <string.h>
20575 #include <stdlib.h>
20576
20577 /*
20578 ** Make a copy of a string or BLOB in memory obtained from malloc().
20579 */
20580 static void strdupfunc(
20581 sqlite3_context *context,
20582 int argc,
20583 sqlite3_value **argv
20584 ){
20585 const unsigned char *zIn;
20586 int nIn;
20587 unsigned char *zOut;
20588
20589 assert( argc==1 );
20590 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
20591 if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
20592 zIn = (const unsigned char*)sqlite3_value_blob(argv[0]);
20593 nIn = sqlite3_value_bytes(argv[0]);
20594 zOut = malloc( nIn==0 ? 1 : nIn );
20595 if( zOut==0 ){
20596 sqlite3_result_error_nomem(context);
20597 return;
20598 }
20599 if( nIn>0 ) memcpy(zOut, zIn, nIn);
20600 sqlite3_result_blob(context, zOut, nIn, free);
20601 }else{
20602 zIn = (const unsigned char*)sqlite3_value_text(argv[0]);
20603 if( zIn==0 ) return;
20604 nIn = (int)strlen((char*)zIn);
20605 zOut = malloc( nIn+1 );
20606 if( zOut==0 ){
20607 sqlite3_result_error_nomem(context);
20608 return;
20609 }
20610 memcpy(zOut, zIn, nIn);
20611 zOut[nIn] = 0;
20612 sqlite3_result_text64(context, (char*)zOut, nIn, free,
20613 SQLITE_UTF8_ZT);
20614 }
20615 }
20616
20617 #ifdef _WIN32
20618
20619 #endif
20620 int sqlite3_strdup_init(
20621 sqlite3 *db,
20622 char **pzErrMsg,
20623 const sqlite3_api_routines *pApi
20624 ){
20625 int rc = SQLITE_OK;
20626 SQLITE_EXTENSION_INIT2(pApi);
20627 (void)pzErrMsg; /* Unused parameter */
20628 rc = sqlite3_create_function(db, "strdup", 1, SQLITE_UTF8,
20629 0, strdupfunc, 0, 0);
20630 return rc;
20631 }
20632
20633 /************************* End ext/misc/strdup.c ********************/
20634
20635 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
20636 #define SQLITE_SHELL_HAVE_RECOVER 1
20637 #else
20638 #define SQLITE_SHELL_HAVE_RECOVER 0
@@ -24581,10 +24849,20 @@
24849 #endif
24850 #ifdef SQLITE_SHELL_EXTSRC
24851 # include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC)
24852 #endif
24853
24854 /*
24855 ** Set the SQLITE_SHELL_EDITION to a YYYYMMDD date string and the
24856 ** code will attempt to use defaults for the prompt and for the
24857 ** initial output mode (and maybe other feature) that were for
24858 ** the most recent version not newer than the specified date.
24859 */
24860 #ifndef SQLITE_SHELL_EDITION
24861 # define SQLITE_SHELL_EDITION 99991231 /* Use the latest if unspecified */
24862 #endif
24863
24864 #if defined(SQLITE_ENABLE_SESSION)
24865 /*
24866 ** State information for a single open session
24867 */
24868 typedef struct OpenSession OpenSession;
@@ -24828,11 +25106,11 @@
25106 unsigned char eHdr; /* Default header encoding. */
25107 unsigned char eBlob; /* Default blob encoding. */
25108 unsigned char bHdr; /* Show headers by default. 0: n/a, 1: no 2: yes */
25109 unsigned char eStyle; /* Underlying QRF style */
25110 unsigned char eCx; /* 0: other, 1: line, 2: columnar */
25111 unsigned char mFlg; /* Flags. 1=border-off 2=split-column 4=rowcount */
25112 };
25113
25114 /* String constants used by built-in modes */
25115 static const char *aModeStr[] =
25116 /* 0 1 2 3 4 5 6 7 8 */
@@ -24841,45 +25119,45 @@
25119 /* 9 10 11 12 13 */
25120
25121 static const ModeInfo aModeInfo[] = {
25122 /* zName eCSep eRSep eNull eText eHdr eBlob bHdr eStyle eCx mFlg */
25123 { "ascii", 7, 6, 9, 1, 1, 0, 1, 12, 0, 0 },
25124 { "box", 0, 0, 9, 1, 1, 0, 3, 1, 2, 0 },
25125 { "c", 4, 1, 10, 5, 5, 4, 1, 12, 0, 0 },
25126 { "column", 0, 0, 9, 1, 1, 0, 3, 2, 2, 0 },
25127 { "count", 0, 0, 0, 0, 0, 0, 0, 3, 0, 0 },
25128 { "csv", 4, 5, 9, 3, 3, 0, 1, 12, 0, 0 },
25129 { "html", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 },
25130 { "insert", 0, 0, 10, 2, 2, 0, 1, 8, 0, 0 },
25131 { "jatom", 4, 1, 11, 6, 6, 0, 1, 12, 0, 0 },
25132 { "jobject", 0, 1, 11, 6, 6, 0, 0, 10, 0, 0 },
25133 { "json", 0, 0, 11, 6, 6, 0, 0, 9, 0, 0 },
25134 { "line", 13, 1, 9, 1, 1, 0, 0, 11, 1, 0 },
25135 { "list", 2, 1, 9, 1, 1, 0, 1, 12, 0, 0 },
25136 { "markdown", 0, 0, 9, 1, 1, 0, 3, 13, 2, 0 },
25137 { "off", 0, 0, 0, 0, 0, 0, 0, 14, 0, 0 },
25138 { "psql", 0, 0, 9, 1, 1, 0, 3, 19, 2, 5 },
25139 { "qbox", 0, 0, 10, 2, 1, 0, 3, 1, 2, 0 },
25140 { "quote", 4, 1, 10, 2, 2, 0, 1, 12, 0, 0 },
25141 { "split", 0, 0, 9, 1, 1, 0, 1, 2, 2, 2 },
25142 { "table", 0, 0, 9, 1, 1, 0, 3, 19, 2, 0 },
25143 { "tabs", 8, 1, 9, 3, 3, 0, 1, 12, 0, 0 },
25144 { "tcl", 3, 1, 12, 5, 5, 4, 1, 12, 0, 0 },
25145 { "www", 0, 0, 9, 4, 4, 0, 3, 7, 0, 0 }
25146 }; /* | / / | / / | | / \____
25147 ** | / / | / / | | / |
25148 ** Index into aModeStr[] | / / | | 2: columnar |
25149 ** | / / | | 1: line |
25150 ** | / / | | 0: other |
25151 ** text encoding |/ | show | | |
25152 ** v-------------------' | hdrs? | The QRF style |
25153 ** 0: n/a blob | v-----' /
25154 ** 1: plain v----------' 0: n/a _________/
25155 ** 2: sql 0: auto 1: no |
25156 ** 3: csv 1: as-text 2: yes 1: border-off
25157 ** 4: html 2: sql 3: always 2: split-column
25158 ** 5: c 3: hex 4: rowcount
25159 ** 6: json 4: c
25160 ** 5: json
25161 ** 6: size
25162 ******************************************************************/
25163
@@ -25162,11 +25440,11 @@
25440 */
25441 static char *local_getline(char *zLine, FILE *in){
25442 int nLine = zLine==0 ? 0 : 100;
25443 int n = 0;
25444
25445 while( seenInterrupt<2 ){
25446 if( n+100>nLine ){
25447 if( nLine>=1073741773 ){
25448 free(zLine);
25449 return 0;
25450 }
@@ -25226,11 +25504,13 @@
25504 # define SQLITE_PS_APPDEF shellPromptAppDef
25505 static const char *shellPromptAppDef(int c){
25506 switch( c ){
25507 /* The default main prompt string */
25508 case 1:
25509 #if SQLITE_SHELL_EDITION<20260423
25510 return "sqlite> "; /* Legacy prompt for backwards compatibility */
25511 #elif defined(SQLITE_PS1)
25512 return SQLITE_PS1;
25513 #else
25514 if( shellNoColor() ){
25515 return "/A-/v /f-> ";
25516 }else{
@@ -25238,11 +25518,13 @@
25518 }
25519 #endif
25520
25521 /* The default continuation prompt string */
25522 case 2:
25523 #if SQLITE_SHELL_EDITION<20260423
25524 return " ...> "; /* Legacy continuation prompt */
25525 #elif defined(SQLITE_PS2)
25526 return SQLITE_PS2;
25527 #else
25528 if( shellNoColor() ){
25529 return "/B/C-> ";
25530 }else{
@@ -25711,30 +25993,33 @@
25993 zResult = local_getline(zPrior, in);
25994 }else{
25995 const char *zBase = prompt_string(p, bContinue!=0);
25996 char *zPrompt = expand_prompt(p, zAll, zBase);
25997 shell_check_oom(zPrompt);
25998 #if SHELL_CMDLINE_EDIT_AVAILABLE
25999 if( shellCmdLineEdit ){
26000 free(zPrior);
26001 zResult = shell_readline(zPrompt);
26002 while( zResult==0 ){
26003 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
26004 sqlite3_sleep(50);
26005 if( seenInterrupt==0 ) break;
26006 zResult = shell_readline("");
26007 }
26008 if( zResult && *zResult ) shell_add_history(zResult);
26009 }else
26010 #endif
26011 {
26012 sputz(stdout, zPrompt);
26013 fflush(stdout);
26014 do{
26015 zResult = local_getline(zPrior, stdin);
26016 zPrior = 0;
26017 /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */
26018 if( zResult==0 ) sqlite3_sleep(50);
26019 }while( zResult==0 && seenInterrupt>0 );
26020 }
26021 sqlite3_free(zPrompt);
26022 }
26023 return zResult;
26024 }
26025 #endif /* !SQLITE_SHELL_FIDDLE */
@@ -26307,11 +26592,11 @@
26592 free(p->spec.zColumnSep);
26593 free(p->spec.zRowSep);
26594 free(p->spec.zTableName);
26595 free(p->spec.zNull);
26596 memset(p, 0, sizeof(*p));
26597 p->spec.iVersion = 2;
26598 p->autoExplain = autoExplain;
26599 }
26600
26601 /*
26602 ** Duplicate Mode pSrc into pDest. pDest is assumed to be
@@ -26432,10 +26717,15 @@
26717 pM->spec.bSplitColumn = QRF_Yes;
26718 pM->bAutoScreenWidth = 1;
26719 }else{
26720 pM->spec.bSplitColumn = QRF_No;
26721 }
26722 if( pI->mFlg & 0x04 ){
26723 pM->spec.bRowCount = QRF_Yes;
26724 }else{
26725 pM->spec.bRowCount = QRF_No;
26726 }
26727 }else if( eMode>=MODE_USER && eMode-MODE_USER<p->nSavedModes ){
26728 modeFree(&p->mode);
26729 modeDup(&p->mode, &p->aSavedModes[eMode-MODE_USER].mode);
26730 }else if( eMode==MODE_BATCH ){
26731 u8 mFlags = p->mode.mFlags;
@@ -26461,13 +26751,15 @@
26751 /*
26752 ** Set the mode to the default. It assumed that the mode has
26753 ** already been freed and zeroed prior to calling this routine.
26754 */
26755 static void modeDefault(ShellState *p){
26756 p->mode.spec.iVersion = 2;
26757 p->mode.autoExplain = 1;
26758 if( (stdin_is_interactive || stdout_is_console)
26759 && SQLITE_SHELL_EDITION>=20260409
26760 ){
26761 modeChange(p, MODE_TTY);
26762 }else{
26763 modeChange(p, MODE_BATCH);
26764 }
26765 }
@@ -28827,10 +29119,11 @@
29119 " --quote ARG Enable/disable quoting of text. ARG can be\n"
29120 " \"off\", \"on\", \"sql\", \"relaxed\", \"csv\", \"html\",\n"
29121 " \"tcl\", or \"json\". \"off\" means show the text as-is.\n"
29122 " \"on\" is an alias for \"sql\".\n"
29123 " --reset Changes all mode settings back to their default.\n"
29124 " --rowcount BOOLEAN Show \"(N rows)\" at the end of query results.\n"
29125 " --rowsep STRING Use STRING as the row separator\n"
29126 " --sw|--screenwidth N Declare the screen width of the output device\n"
29127 " to be N characters. An attempt may be made to\n"
29128 " wrap output text to fit within this limit. Zero\n"
29129 " means \"no limit\". Or N can be \"auto\" to set the\n"
@@ -28838,11 +29131,11 @@
29131 " --tablename NAME Set the name of the table for \"insert\" mode.\n"
29132 " --tag NAME Save mode to the left as NAME.\n"
29133 " --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON.\n"
29134 " --title ARG Whether or not to show column headers, and if so\n"
29135 " how to encode them. ARG can be \"off\", \"on\",\n"
29136 " \"always\", \"sql\", \"csv\", \"html\", \"tcl\", or \"json\".\n"
29137 " --titlelimit N Limit the length of column titles to N characters.\n"
29138 " -v|--verbose Verbose output\n"
29139 " --widths LIST Set the columns widths for columnar modes. The\n"
29140 " argument is a list of integers, one for each\n"
29141 " column. A \"0\" width means use a dynamic width\n"
@@ -29544,10 +29837,11 @@
29837 sqlite3_base85_init(p->db, 0, 0);
29838 sqlite3_regexp_init(p->db, 0, 0);
29839 sqlite3_ieee_init(p->db, 0, 0);
29840 sqlite3_series_init(p->db, 0, 0);
29841 sqlite3_diskused_init(p->db, 0, 0);
29842 sqlite3_strdup_init(p->db, 0, 0);
29843 #ifndef SQLITE_SHELL_FIDDLE
29844 sqlite3_fileio_init(p->db, 0, 0);
29845 sqlite3_completion_init(p->db, 0, 0);
29846 #endif
29847 #ifdef SQLITE_HAVE_ZLIB
@@ -32998,14 +33292,16 @@
33292 /*
33293 ** This function computes what to show the user about the configured
33294 ** titles (or column-names). Output is an integer between 0 and 3:
33295 **
33296 ** 0: The titles do not matter. Never show anything.
33297 ** 1: Show "--title off"
33298 ** 2: Show "--title on"
33299 ** 3: Show "--title always"
33300 ** 4: Show "--title VALUE" where VALUE is an encoding method
33301 ** to use, one of: plain sql csv html tcl json
33302 ** 5: Show "--title VALUE" as in 3, followed by "--title always"
33303 **
33304 ** Inputs are:
33305 **
33306 ** spec.bTitles (bT) Whether or not to show the titles
33307 ** spec.eTitle (eT) The actual encoding to be used for titles
@@ -33038,11 +33334,27 @@
33334 if( eT!=eH ) v >>= 32; /* Encoding disagree in upper 4-bytes */
33335 if( bT!=bH ) v >>= 16; /* ON/OFF disagree in upper 2-byte pairs */
33336 if( bT<2 ) v >>= 8; /* ON in even bytes, OFF in odd bytes (1st byte 0) */
33337 if( !bAll ) v >>= 4; /* bAll values are in the lower half-byte */
33338
33339 v &= 3;
33340 /* At this point v means:
33341 ** 0: The titles do not matter. Never show anything.
33342 ** 1: Show "--title off"
33343 ** 2: Show "--title on"
33344 ** 3: Show "--title VALUE" where VALUE is an encoding method
33345 ** to use, one of: plain sql csv html tcl json
33346 ** If bTitles is QRF_Always, convert 2->3, 3->5. If bTitles is not
33347 ** QRF_Always, convert 3->4.
33348 */
33349 if( p->mode.spec.bTitles==QRF_Always ){
33350 if( v==3 ) v = 5;
33351 if( v==2 ) v = 3;
33352 }else{
33353 if( v==3 ) v = 4;
33354 }
33355 return v;
33356 }
33357
33358 /*
33359 ** DOT-COMMAND: .mode
33360 **
@@ -33086,10 +33398,11 @@
33398 ** --quote ARG Enable/disable quoting of text. ARG can be
33399 ** "off", "on", "sql", "relaxed", "csv", "html",
33400 ** "tcl", or "json". "off" means show the text as-is.
33401 ** "on" is an alias for "sql".
33402 ** --reset Changes all mode settings back to their default.
33403 ** --rowcount BOOLEAN Show "(N rows)" at the end of query results.
33404 ** --rowsep STRING Use STRING as the row separator
33405 ** --sw|--screenwidth N Declare the screen width of the output device
33406 ** to be N characters. An attempt may be made to
33407 ** wrap output text to fit within this limit. Zero
33408 ** means "no limit". Or N can be "auto" to set the
@@ -33097,11 +33410,11 @@
33410 ** --tablename NAME Set the name of the table for "insert" mode.
33411 ** --tag NAME Save mode to the left as NAME.
33412 ** --textjsonb BOOLEAN If enabled, JSONB text is displayed as text JSON.
33413 ** --title ARG Whether or not to show column headers, and if so
33414 ** how to encode them. ARG can be "off", "on",
33415 ** "always", "sql", "csv", "html", "tcl", or "json".
33416 ** --titlelimit N Limit the length of column titles to N characters.
33417 ** -v|--verbose Verbose output
33418 ** --widths LIST Set the columns widths for columnar modes. The
33419 ** argument is a list of integers, one for each
33420 ** column. A "0" width means use a dynamic width
@@ -33325,10 +33638,17 @@
33638 chng = 1;
33639 }else if( optionMatch(z,"reset") ){
33640 int saved_eMode = p->mode.eMode;
33641 modeFree(&p->mode);
33642 modeChange(p, saved_eMode);
33643 }else if( optionMatch(z,"rowcount") ){
33644 if( i+1>=nArg ){
33645 dotCmdError(p, i, "missing argument", 0);
33646 return 1;
33647 }
33648 p->mode.spec.bRowCount = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
33649 chng = 1;
33650 }else if( optionMatch(z,"screenwidth") || optionMatch(z,"sw") ){
33651 if( (++i)>=nArg ){
33652 dotCmdError(p, i-1, "missing argument", 0);
33653 return 1;
33654 }
@@ -33378,25 +33698,63 @@
33698 return 1;
33699 }
33700 p->mode.spec.bTextJsonb = booleanValue(azArg[++i]) ? QRF_Yes : QRF_No;
33701 chng = 1;
33702 }else if( optionMatch(z,"titles") || optionMatch(z,"title") ){
33703 /* The --titles option controls two fields of the
33704 ** sqlite3_qrf_spec object: eTitle and bTitles.
33705 **
33706 ** --titles eTitle bTitles
33707 ** -------- --------------- ---------------------
33708 ** "off" (unchanged) QRF_Off
33709 ** "on" (unchanged) QRF_On
33710 ** "always" (unchanged) QRF_Always
33711 ** "auto", (default) (default)
33712 ** "plain" QRF_TEXT_Plain QRF_Always or QRF_On
33713 ** "sql" QRF_TEXT_Sql QRF_Always or QRF_On
33714 ** "csv" QRF_TEXT_Csv QRF_Always or QRF_On
33715 ** "html" QRF_TEXT_Html QRF_Always or QRF_On
33716 ** "tcl" QRF_TEXT_Tcl QRF_Always or QRF_On
33717 ** "json" QRF_TEXT_Json QRF_Always or QRF_On
33718 **
33719 ** This mapping is different from the -title option to the "format"
33720 ** method of the TCL interface. In this mapping:
33721 **
33722 ** * "off", "on", and "always" affect only bTitles and leave
33723 ** eTitle unchanged
33724 **
33725 ** * "auto" sets both bTitles and eTitle to the default value
33726 ** in aModeInfo[] according to the current --style.
33727 **
33728 ** * "plain" through "json" set eTitle but leave bTitles
33729 ** unchanged if it is not QRF_Off. If bTitles is QRF_Off,
33730 ** then it is changed QRF_Always.
33731 */
33732 char *zErr = 0;
33733 if( i+1>=nArg ){
33734 dotCmdError(p, i, "missing argument", 0);
33735 return 1;
33736 }
33737 k = pickStr(azArg[++i],&zErr,
33738 "off","on","always","auto","plain","sql","csv","html","tcl","json","");
33739 /* 0 1 2 3 4 5 6 7 8 9 */
33740 if( k<0 ){
33741 dotCmdError(p, i, "bad --titles value","%z", zErr);
33742 return 1;
33743 }
 
33744 p->mode.mFlags &= ~MFLG_HDR;
33745 if( k<=2 ){
33746 p->mode.spec.bTitles = QRF_No+k;
33747 }else if( k==3 ){
33748 p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
33749 p->mode.spec.bTitles = aModeInfo[p->mode.eMode].bHdr;
33750 }else{
33751 p->mode.spec.eTitle = (k-4)+QRF_TEXT_Plain;
33752 if( p->mode.spec.bTitles==QRF_No ){
33753 p->mode.spec.bTitles = QRF_Always;
33754 }
33755 }
33756 chng = 1;
33757 }else if( optionMatch(z,"widths") || optionMatch(z,"width") ){
33758 int nWidth = 0;
33759 short int *aWidth;
33760 const char *zW;
@@ -33547,10 +33905,16 @@
33905 if( bAll
33906 || (pI->eText!=p->mode.spec.eText && (pI->eText>1 || p->mode.spec.eText>1))
33907 ){
33908 sqlite3_str_appendf(pDesc," --quote %s",qrfQuoteNames[p->mode.spec.eText]);
33909 }
33910 if( bAll
33911 || ((p->mode.spec.bRowCount==QRF_Yes) != ((pI->mFlg&4)!=0))
33912 ){
33913 sqlite3_str_appendf(pDesc," --rowcount %s",
33914 p->mode.spec.bRowCount==QRF_Yes ? "on" : "off");
33915 }
33916 zSetting = aModeStr[pI->eRSep];
33917 if( bAll || (zSetting && cli_strcmp(zSetting,p->mode.spec.zRowSep)!=0) ){
33918 sqlite3_str_appendf(pDesc, " --rowsep ");
33919 append_c_string(pDesc, p->mode.spec.zRowSep);
33920 }
@@ -33576,14 +33940,19 @@
33940 if( k==1 ){
33941 sqlite3_str_appendall(pDesc, " --titles off");
33942 }else if( k==2 ){
33943 sqlite3_str_appendall(pDesc, " --titles on");
33944 }else if( k==3 ){
33945 sqlite3_str_appendall(pDesc, " --titles always");
33946 }else if( k>=4 ){
33947 static const char *azTitle[] =
33948 { "plain", "sql", "csv", "html", "tcl", "json"};
33949 sqlite3_str_appendf(pDesc, " --titles %s",
33950 azTitle[p->mode.spec.eTitle-1]);
33951 if( k==5 ){
33952 sqlite3_str_appendf(pDesc, " --titles always");
33953 }
33954 }
33955 if( p->mode.spec.nWidth>0 && (bAll || pI->eCx==2) ){
33956 int ii;
33957 const char *zSep = " --widths ";
33958 for(ii=0; ii<p->mode.spec.nWidth; ii++){
@@ -34901,15 +35270,19 @@
35270 }
35271 }else
35272
35273 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){
35274 if( nArg==2 ){
35275 if( cli_strcmp(azArg[1],"always")==0 ){
35276 p->mode.spec.bTitles = QRF_Always;
35277 }else{
35278 p->mode.spec.bTitles = booleanValue(azArg[1]) ? QRF_Yes : QRF_No;
35279 }
35280 p->mode.mFlags |= MFLG_HDR;
35281 p->mode.spec.eTitle = aModeInfo[p->mode.eMode].eHdr;
35282 }else{
35283 eputz("Usage: .headers off|on|always\n");
35284 rc = 1;
35285 }
35286 }else
35287
35288 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){
@@ -35113,13 +35486,21 @@
35486 sqlite3_str_free(pSql);
35487 }else
35488
35489 if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){
35490 i64 iArg = 0;
35491 open_db(p, 0);
35492 if( nArg==2 ){
35493 iArg = integerValue(azArg[1]);
35494 if( iArg==0 ){
35495 if( cli_strcmp(azArg[1],"register")==0 ){
35496 sqlite3_intck_register(p->db, 1);
35497 rc = 0;
35498 goto meta_command_exit;
35499 }
35500 iArg = -1;
35501 }
35502 }
35503 if( (nArg!=1 && nArg!=2) || iArg<0 ){
35504 cli_printf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n");
35505 rc = 1;
35506 goto meta_command_exit;
@@ -35167,10 +35548,11 @@
35548 { "attached", SQLITE_LIMIT_ATTACHED },
35549 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
35550 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
35551 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
35552 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
35553 { "schema", SQLITE_LIMIT_SCHEMA },
35554 };
35555 int i, n2;
35556 open_db(p, 0);
35557 if( nArg==1 ){
35558 for(i=0; i<ArraySize(aLimit); i++){
@@ -36493,11 +36875,12 @@
36875 azBool[(p->mode.mFlags & MFLG_ECHO)!=0]);
36876 cli_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->mode.autoEQP&3]);
36877 cli_printf(p->out, "%12.12s: %s\n","explain",
36878 p->mode.autoExplain ? "auto" : "off");
36879 cli_printf(p->out, "%12.12s: %s\n","headers",
36880 p->mode.spec.bTitles==QRF_Always ? "always" :
36881 azBool[p->mode.spec.bTitles==QRF_Yes]);
36882 if( p->mode.spec.eStyle==QRF_STYLE_Column
36883 || p->mode.spec.eStyle==QRF_STYLE_Box
36884 || p->mode.spec.eStyle==QRF_STYLE_Table
36885 || p->mode.spec.eStyle==QRF_STYLE_Markdown
36886 ){
@@ -37860,10 +38243,11 @@
38243 " -ascii set '.mode ascii'\n"
38244 " -bail stop after hitting an error\n"
38245 " -batch force batch I/O\n"
38246 " -box set '.mode box'\n"
38247 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
38248 " -cmdline-edit BOOL enable or disable command-line editing\n"
38249 " -column set '.mode column'\n"
38250 " -csv set '.mode csv -limits off'\n"
38251 #if !defined(SQLITE_OMIT_DESERIALIZE)
38252 " -deserialize open the database using sqlite3_deserialize()\n"
38253 #endif
@@ -38130,10 +38514,13 @@
38514 stdout_is_console = 1;
38515 data.wasm.zDefaultDbName = "/fiddle.sqlite3";
38516 #else
38517 stdin_is_interactive = isatty(0);
38518 stdout_is_console = isatty(1);
38519 if( !stdin_is_interactive || !stdout_is_console ){
38520 shellCmdLineEdit = 0;
38521 }
38522 #endif
38523 atexit(abnormalExit);
38524 #ifdef SQLITE_DEBUG
38525 mem_main_enter = sqlite3_memory_used();
38526 #endif
@@ -38377,10 +38764,12 @@
38764 }else if( cli_strcmp(z,"-safe")==0 ){
38765 /* no-op - catch this on the second pass */
38766 }else if( cli_strcmp(z,"-escape")==0 && i+1<argc ){
38767 /* skip over the argument */
38768 i++;
38769 }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
38770 shellCmdLineEdit = booleanValue(cmdline_option_value(argc,argv,++i));
38771 }else if( cli_strcmp(z,"-test-argv")==0 ){
38772 /* Undocumented test option. Print the values in argv[] and exit.
38773 ** Use this to verify that any translation of the argv[], for example
38774 ** on Windows that receives wargv[] from the OS and must convert
38775 ** to UTF8 prior to calling this routine. */
@@ -38567,11 +38956,11 @@
38956 cmdline_option_value(argc,argv,++i));
38957 }else if( cli_strcmp(z,"-nullvalue")==0 ){
38958 modeSetStr(&data.mode.spec.zNull,
38959 cmdline_option_value(argc,argv,++i));
38960 }else if( cli_strcmp(z,"-header")==0 ){
38961 data.mode.spec.bTitles = QRF_Always;
38962 data.mode.mFlags |= MFLG_HDR;
38963 }else if( cli_strcmp(z,"-noheader")==0 ){
38964 data.mode.spec.bTitles = QRF_No;
38965 data.mode.mFlags |= MFLG_HDR;
38966 }else if( cli_strcmp(z,"-echo")==0 ){
@@ -38639,10 +39028,12 @@
39028 i++;
39029 #ifdef SQLITE_ENABLE_MULTIPLEX
39030 }else if( cli_strcmp(z,"-multiplex")==0 ){
39031 i++;
39032 #endif
39033 }else if( cli_strcmp(z,"-cmdline-edit")==0 ){
39034 i+=2;
39035 }else if( cli_strcmp(z,"-help")==0 ){
39036 usage(1);
39037 }else if( cli_strcmp(z,"-cmd")==0 ){
39038 /* Run commands that follow -cmd first and separately from commands
39039 ** that simply appear on the command-line. This seems goofy. It would
@@ -38668,12 +39059,14 @@
39059 rc = 1;
39060 goto shell_main_exit;
39061 }
39062 open_db(&data, OPEN_DB_ZIPFILE);
39063 if( z[2] ){
39064 char *zSaved = argv[i];
39065 argv[i] = &z[2];
39066 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
39067 argv[i] = zSaved;
39068 }else{
39069 arDotCommand(&data, 1, argv+i, argc-i);
39070 }
39071 readStdin = 0;
39072 stdin_is_interactive = 0;
39073
+1369 -689
--- 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
-** 3f3fb9b638f59ad982beafb7c117f24ddd3d with changes in files:
21
+** 2f1f4f73535386549c12694dc57cfe555eec 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.54.0"
471471
#define SQLITE_VERSION_NUMBER 3054000
472
-#define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
472
+#define SQLITE_SOURCE_ID "2026-07-24 16:28:47 2f1f4f73535386549c12694dc57cfe555eec689ae6824c6241aaf8d5befcd74d"
473473
#define SQLITE_SCM_BRANCH "trunk"
474474
#define SQLITE_SCM_TAGS ""
475
-#define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
475
+#define SQLITE_SCM_DATETIME "2026-07-24T16:28:47.830Z"
476476
477477
/*
478478
** CAPI3REF: Run-Time Library Version Numbers
479479
** KEYWORDS: sqlite3_version sqlite3_sourceid
480480
**
@@ -3732,11 +3732,11 @@
37323732
** authorizer will fail with an error message explaining that
37333733
** access is denied.
37343734
**
37353735
** ^The first parameter to the authorizer callback is a copy of the third
37363736
** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3737
-** to the callback is an integer [SQLITE_COPY | action code] that specifies
3737
+** to the callback is an integer [SQLITE_READ | action code] that specifies
37383738
** the particular action to be authorized. ^The third through sixth parameters
37393739
** to the callback are either NULL pointers or zero-terminated strings
37403740
** that contain additional details about the action to be authorized.
37413741
** Applications must always be prepared to encounter a NULL pointer in any
37423742
** of the third through the sixth parameters of the authorization callback.
@@ -3775,25 +3775,37 @@
37753775
** ^(Only a single authorizer can be in place on a database connection
37763776
** at a time. Each call to sqlite3_set_authorizer overrides the
37773777
** previous call.)^ ^Disable the authorizer by installing a NULL callback.
37783778
** The authorizer is disabled by default.
37793779
**
3780
-** The authorizer callback must not do anything that will modify
3780
+** <h3>Limitations And Caveats</h3><ul>
3781
+**
3782
+** <li>The authorizer callback must not do anything that will modify
37813783
** the database connection that invoked the authorizer callback.
37823784
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
37833785
** database connections for the meaning of "modify" in this paragraph.
37843786
**
3785
-** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3787
+** <li>^When [sqlite3_prepare_v2()] is used to prepare a statement, the
37863788
** statement might be re-prepared during [sqlite3_step()] due to a
37873789
** schema change. Hence, the application should ensure that the
37883790
** correct authorizer callback remains in place during the [sqlite3_step()].
37893791
**
3790
-** ^Note that the authorizer callback is invoked only during
3792
+** <li>^The authorizer callback is invoked only during
37913793
** [sqlite3_prepare()] or its variants. Authorization is not
37923794
** performed during statement evaluation in [sqlite3_step()], unless
37933795
** as stated in the previous paragraph, sqlite3_step() invokes
37943796
** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3797
+**
3798
+** <li>Authorizer callbacks for the expressions of a
3799
+** [generated column] are invoked when the schema is parsed (and specifically
3800
+** when the [CREATE TABLE] statement that contains the generated column is
3801
+** parsed) not when the generated column is used in a DML statement.
3802
+** This is deliberate, as one of the purposes of generated columns
3803
+** is to give schema designers the ability to provide gated access
3804
+** to privileged columns and/or functions.
3805
+**
3806
+** </ul>
37953807
*/
37963808
SQLITE_API int sqlite3_set_authorizer(
37973809
sqlite3*,
37983810
int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
37993811
void *pUserData
@@ -3864,12 +3876,17 @@
38643876
#define SQLITE_ANALYZE 28 /* Table Name NULL */
38653877
#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
38663878
#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
38673879
#define SQLITE_FUNCTION 31 /* NULL Function Name */
38683880
#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3869
-#define SQLITE_COPY 0 /* No longer used */
38703881
#define SQLITE_RECURSIVE 33 /* NULL NULL */
3882
+
3883
+/*
3884
+** Note: The SQLITE_COPY macro (with value 0) used to be one of the
3885
+** action codes above. That macro has now been repurposed as a possible
3886
+** value to the 3rd argument to sqlite3_result_str().
3887
+*/
38713888
38723889
/*
38733890
** CAPI3REF: Deprecated Tracing And Profiling Functions
38743891
** DEPRECATED
38753892
**
@@ -4734,10 +4751,14 @@
47344751
** nesting depth for separate triggers.</dd>)^
47354752
**
47364753
** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
47374754
** <dd>The maximum number of auxiliary worker threads that a single
47384755
** [prepared statement] may start.</dd>)^
4756
+**
4757
+** [[SQLITE_LIMIT_SCHEMA]] ^(<dt>SQLITE_LIMIT_SCHEMA</dt>
4758
+** <dd>The maximum number of objects (tables, indexes, triggers, and views)
4759
+** defined by the database schema.</dd>)^
47394760
** </dl>
47404761
*/
47414762
#define SQLITE_LIMIT_LENGTH 0
47424763
#define SQLITE_LIMIT_SQL_LENGTH 1
47434764
#define SQLITE_LIMIT_COLUMN 2
@@ -4749,10 +4770,11 @@
47494770
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
47504771
#define SQLITE_LIMIT_VARIABLE_NUMBER 9
47514772
#define SQLITE_LIMIT_TRIGGER_DEPTH 10
47524773
#define SQLITE_LIMIT_WORKER_THREADS 11
47534774
#define SQLITE_LIMIT_PARSER_DEPTH 12
4775
+#define SQLITE_LIMIT_SCHEMA 13
47544776
47554777
/*
47564778
** CAPI3REF: Prepare Flags
47574779
**
47584780
** These constants define various flags that can be passed into the
@@ -4860,10 +4882,12 @@
48604882
** there is a small performance advantage to passing an nByte parameter that
48614883
** is the number of bytes in the input string <i>including</i>
48624884
** the nul-terminator.
48634885
** Note that nByte measures the length of the input in bytes, not
48644886
** characters, even for the UTF-16 interfaces.
4887
+** For the sqlite3_prepare16() and sqlite3_prepare16_v2() interfaces,
4888
+** the nByte value must be even or undefined behavior can result.
48654889
**
48664890
** ^If pzTail is not NULL then *pzTail is made to point to the first byte
48674891
** past the end of the first SQL statement in zSql. These routines only
48684892
** compile the first statement in zSql, so *pzTail is left pointing to
48694893
** what remains uncompiled.
@@ -5606,11 +5630,11 @@
56065630
** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
56075631
** can be obtained by calling [sqlite3_reset()] on the
56085632
** [prepared statement]. ^In the "v2" interface,
56095633
** the more specific error code is returned directly by sqlite3_step().
56105634
**
5611
-** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5635
+** [SQLITE_MISUSE] means that this routine was called inappropriately.
56125636
** Perhaps it was called on a [prepared statement] that has
56135637
** already been [sqlite3_finalize | finalized] or on one that had
56145638
** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
56155639
** be the case that the same database connection is being used by two or
56165640
** more threads at the same moment in time.
@@ -6779,11 +6803,15 @@
67796803
** to by the second parameter and which is N bytes long where N is the
67806804
** third parameter.
67816805
**
67826806
** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
67836807
** interfaces set the result of the application-defined function to be
6784
-** a BLOB containing all zero bytes and N bytes in size.
6808
+** a BLOB containing all zero bytes and N bytes in size. The
6809
+** zeroblob64(C,N) interface returns a [result code], which is normally
6810
+** [SQLITE_OK] but might be some other value if the requested operation
6811
+** could not be complete, for example if insufficient memory is available
6812
+** or if the value of N is out of range.
67856813
**
67866814
** ^The sqlite3_result_double() interface sets the result from
67876815
** an application-defined function to be a floating point value specified
67886816
** by its 2nd argument.
67896817
**
@@ -9117,12 +9145,12 @@
91179145
** The lifecycle of an sqlite3_str object is as follows:
91189146
** <ol>
91199147
** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
91209148
** <li> ^Text is appended to the sqlite3_str object using various
91219149
** methods, such as [sqlite3_str_appendf()].
9122
-** <li> ^The sqlite3_str object is destroyed and the string it created
9123
-** is returned using the [sqlite3_str_finish()] interface.
9150
+** <li> The sqlite3_str object is destroyed and the string it created
9151
+** is returned using [sqlite3_str_finish()] or [sqlite3_result_str()].
91249152
** </ol>
91259153
*/
91269154
typedef struct sqlite3_str sqlite3_str;
91279155
91289156
/*
@@ -9170,10 +9198,44 @@
91709198
** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)).
91719199
*/
91729200
SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
91739201
SQLITE_API void sqlite3_str_free(sqlite3_str*);
91749202
9203
+/*
9204
+** CAPI3REF: Return A Dynamic String From an SQL Function
9205
+**
9206
+** The [sqlite3_result_str(C,S,F)] interface causes the
9207
+** [sqlite3_str|dynamic string] S to become the return value for the
9208
+** application-defined function or virtual table that uses
9209
+** [sqlite3_context] C. The F flag can be one of [SQLITE_COPY]
9210
+** or [SQLITE_XFER] or [SQLITE_FINISH].
9211
+**
9212
+** If the dynamic string is invalid or incomplete due to an out-of-memory
9213
+** or string-too-large error, then this routine transfers that error
9214
+** over to the SQL function.
9215
+**
9216
+** If the F argument is SQLITE_COPY, then a copy of the dynamic string
9217
+** content is made and the dynamic string object is unchanged.
9218
+** If the F argument is SQLITE_XFER, then ownership of the content
9219
+** in the dynamic is transferred to the SQL function (via a pointer copy
9220
+** rather than a string copy) and the dynamic string is reset to an
9221
+** empty string. The SQLITE_FINISH value for F works like SQLITE_RESET
9222
+** except that it also invokes the [sqlite3_str_free(S)] destructor
9223
+** on the dynamic string object.
9224
+*/
9225
+SQLITE_API void sqlite3_result_str(sqlite3_context*, sqlite3_str*, int);
9226
+
9227
+/*
9228
+** CAPI3REF: Control Flags For sqlite3_result_str()
9229
+**
9230
+** The following integers can be used as the third "F" argument
9231
+** to [sqlite3_result_str(C,S,F)].
9232
+*/
9233
+#define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */
9234
+#define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */
9235
+#define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */
9236
+
91759237
/*
91769238
** CAPI3REF: Add Content To A Dynamic String
91779239
** METHOD: sqlite3_str
91789240
**
91799241
** These interfaces add or remove content to an sqlite3_str object
@@ -14978,10 +15040,37 @@
1497815040
*/
1497915041
#ifndef SQLITE_MAX_TRIGGER_DEPTH
1498015042
# define SQLITE_MAX_TRIGGER_DEPTH 1000
1498115043
#endif
1498215044
15045
+/*
15046
+** Maximum number of objects defined by a single database schema.
15047
+** Objects include:
15048
+**
15049
+** * tables (including the sqlite_schema table)
15050
+** * virtual tables
15051
+** * named indexes
15052
+** * indexes created automatically by UNIQUE and PRIMARY KEY constraints
15053
+** * triggers
15054
+** * views
15055
+**
15056
+** The total of all of the above is the number of objects in the schema,
15057
+** and that number may not exceed this value.
15058
+**
15059
+** The maximum number of objects is restricted to forestall theoretical
15060
+** signed integer overflow attacks using databases with billions of
15061
+** schema objects. Such attacks are "theoretical" because memory and
15062
+** disk space constraints would be reached long before billions of schema
15063
+** objects could be created. Even so, it seems good to have a well defined
15064
+** upper limit on the complexity of the schema, for defense in depth.
15065
+** No real-world application should ever get anywhere close to hitting
15066
+** this limit.
15067
+*/
15068
+#ifndef SQLITE_MAX_SCHEMA
15069
+# define SQLITE_MAX_SCHEMA 10000000
15070
+#endif
15071
+
1498315072
/************** End of sqliteLimit.h *****************************************/
1498415073
/************** Continuing where we left off in sqliteInt.h ******************/
1498515074
1498615075
/* Disable nuisance warnings on Borland compilers */
1498715076
#if defined(__BORLANDC__)
@@ -15236,11 +15325,13 @@
1523615325
** bitmask tests, testcase() can be used to make sure each bit
1523715326
** is significant and used at least once. On switch statements
1523815327
** where multiple cases go to the same block of code, testcase()
1523915328
** can insure that all cases are evaluated.
1524015329
*/
15241
-#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
15330
+#if defined(SQLITE_MUTATION_TEST)
15331
+# define testcase(X)
15332
+#elif defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
1524215333
# ifndef SQLITE_AMALGAMATION
1524315334
extern unsigned int sqlite3CoverageCounter;
1524415335
# endif
1524515336
# define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
1524615337
#else
@@ -17190,11 +17281,11 @@
1719017281
SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
1719117282
#endif
1719217283
1719317284
SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
1719417285
SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
17195
-SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
17286
+SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree*, Btree*);
1719617287
1719717288
SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
1719817289
1719917290
/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
1720017291
** of the flags shown below.
@@ -17267,16 +17358,23 @@
1726717358
** The design of the _RANGE hint is aid b-tree implementations that try
1726817359
** to prefetch content from remote machines - to provide those
1726917360
** implementations with limits on what needs to be prefetched and thereby
1727017361
** reduce network bandwidth.
1727117362
**
17363
+** BTREE_HINT_TABLECURSOR (arguments: BtCursor*)
17364
+**
17365
+** This hint is invoked on a non-covering index cursor soon after it
17366
+** is opened. The only argument is a pointer to the table cursor used to
17367
+** obtain non-covered fields from the database.
17368
+**
1727217369
** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
1727317370
** standard SQLite. The other hints are provided for extensions that use
1727417371
** the SQLite parser and code generator but substitute their own storage
1727517372
** engine.
1727617373
*/
1727717374
#define BTREE_HINT_RANGE 0 /* Range constraints on queries */
17375
+#define BTREE_HINT_TABLECURSOR 1 /* Table csr associated with this index csr */
1727817376
1727917377
/*
1728017378
** Values that may be OR'd together to form the argument to the
1728117379
** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
1728217380
**
@@ -17332,10 +17430,13 @@
1733217430
#endif
1733317431
SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
1733417432
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
1733517433
#ifdef SQLITE_ENABLE_CURSOR_HINTS
1733617434
SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
17435
+ #ifdef SQLITE_DEBUG
17436
+SQLITE_PRIVATE BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor*);
17437
+ #endif
1733717438
#endif
1733817439
1733917440
SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
1734017441
SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
1734117442
BtCursor*,
@@ -18573,11 +18674,11 @@
1857318674
1857418675
/*
1857518676
** The number of different kinds of things that can be limited
1857618677
** using the sqlite3_limit() interface.
1857718678
*/
18578
-#define SQLITE_N_LIMIT (SQLITE_LIMIT_PARSER_DEPTH+1)
18679
+#define SQLITE_N_LIMIT (SQLITE_LIMIT_SCHEMA+1)
1857918680
1858018681
/*
1858118682
** Lookaside malloc is a set of fixed-size buffers that can be used
1858218683
** to satisfy small transient memory allocation requests for objects
1858318684
** associated with a particular database connection. The use of
@@ -20940,16 +21041,16 @@
2094021041
bft bHasExists :1; /* Has a correlated "EXISTS (SELECT ....)" expression */
2094121042
bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */
2094221043
bft bHasWith :1; /* True if statement contains WITH */
2094321044
bft okConstFactor:1; /* OK to factor out constants */
2094421045
bft checkSchema :1; /* Causes schema cookie check after an error */
21046
+ bft usesAinc :1; /* True if pAinc is valid */
2094521047
int nRangeReg; /* Size of the temporary register block */
2094621048
int iRangeReg; /* First register in temporary register block */
2094721049
int nErr; /* Number of errors seen */
2094821050
int nTab; /* Number of previously allocated VDBE cursors */
2094921051
int nMem; /* Number of memory cells used so far */
20950
- int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
2095121052
int iSelfTab; /* Table associated with an index on expr, or negative
2095221053
** of the base register during check-constraint eval */
2095321054
int nNestSel; /* Number of nested SELECT statements and/or VIEWs */
2095421055
int nLabel; /* The *negative* of the number of labels used */
2095521056
int nLabelAlloc; /* Number of slots in aLabel */
@@ -20964,13 +21065,11 @@
2096421065
#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2096521066
u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */
2096621067
#endif
2096721068
#ifndef SQLITE_OMIT_SHARED_CACHE
2096821069
int nTableLock; /* Number of locks in aTableLock */
20969
- TableLock *aTableLock; /* Required table locks for shared-cache mode */
2097021070
#endif
20971
- AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
2097221071
Parse *pToplevel; /* Parse structure for main program (or NULL) */
2097321072
Table *pTriggerTab; /* Table triggers are being coded for */
2097421073
TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
2097521074
ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */
2097621075
@@ -20995,10 +21094,17 @@
2099521094
} cr;
2099621095
struct { /* These fields available to all other statements */
2099721096
Returning *pReturning; /* The RETURNING clause */
2099821097
} d;
2099921098
} u1;
21099
+ AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters. Only
21100
+ ** valid if Parse.usesAinc is true */
21101
+#ifndef SQLITE_OMIT_SHARED_CACHE
21102
+ TableLock *aTableLock; /* Required table locks for shared-cache mode. Only
21103
+ ** valid if Parse.nTableLock>0 */
21104
+#endif
21105
+
2100021106
2100121107
/************************************************************************
2100221108
** Above is constant between recursions. Below is reset before and after
2100321109
** each recursion. The boundary between these two regions is determined
2100421110
** using offsetof(Parse,sLastToken) so the sLastToken field must be the
@@ -21942,10 +22048,11 @@
2194222048
#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
2194322049
SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
2194422050
#endif
2194522051
#if defined(SQLITE_TEST)
2194622052
SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
22053
+SQLITE_PRIVATE const char *sqlite3TestPtrToText(void*);
2194722054
#endif
2194822055
2194922056
#if defined(SQLITE_DEBUG)
2195022057
SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
2195122058
SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
@@ -22166,10 +22273,11 @@
2216622273
SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
2216722274
SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
2216822275
SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
2216922276
SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
2217022277
SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**);
22278
+SQLITE_PRIVATE int sqlite3IndexBloomable(const Index*,int);
2217122279
SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
2217222280
Expr*, int, int, u8);
2217322281
SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
2217422282
SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
2217522283
SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
@@ -22528,10 +22636,11 @@
2252822636
SQLITE_PRIVATE const unsigned char *sqlite3aEQb;
2252922637
SQLITE_PRIVATE const unsigned char *sqlite3aGTb;
2253022638
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
2253122639
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
2253222640
SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
22641
+SQLITE_PRIVATE const sqlite3_str sqlite3OomStr;
2253322642
#ifndef SQLITE_OMIT_WSD
2253422643
SQLITE_PRIVATE int sqlite3PendingByte;
2253522644
#endif
2253622645
#endif /* SQLITE_AMALGAMATION */
2253722646
#ifdef VDBE_PROFILE
@@ -22630,11 +22739,10 @@
2263022739
SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
2263122740
SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, i64);
2263222741
SQLITE_PRIVATE int sqlite3StrAccumEnlargeIfNeeded(StrAccum*, i64);
2263322742
SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
2263422743
SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);
22635
-SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
2263622744
SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
2263722745
SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
2263822746
SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
2263922747
SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
2264022748
@@ -23578,10 +23686,13 @@
2357823686
"MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
2357923687
#endif
2358023688
#ifdef SQLITE_MAX_PAGE_SIZE
2358123689
"MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
2358223690
#endif
23691
+#ifdef SQLITE_MAX_SCHEMA
23692
+ "MAX_SCHEMA=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA),
23693
+#endif
2358323694
#ifdef SQLITE_MAX_SCHEMA_RETRY
2358423695
"MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
2358523696
#endif
2358623697
#ifdef SQLITE_MAX_SQL_LENGTH
2358723698
"MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
@@ -24228,10 +24339,20 @@
2422824339
** Hash table for global functions - functions common to all
2422924340
** database connections. After initialization, this table is
2423024341
** read-only.
2423124342
*/
2423224343
SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
24344
+
24345
+/*
24346
+** This singleton is an sqlite3_str object that is returned if
24347
+** sqlite3_malloc() fails to provide space for a real one. This
24348
+** sqlite3_str object accepts no new text and always returns
24349
+** an SQLITE_NOMEM error.
24350
+*/
24351
+SQLITE_PRIVATE const sqlite3_str sqlite3OomStr = {
24352
+ 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
24353
+};
2423324354
2423424355
#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
2423524356
/*
2423624357
** Counter used for coverage testing. Does not come into play for
2423724358
** release builds.
@@ -26297,10 +26418,53 @@
2629726418
clearYMD_HMS_TZ(p);
2629826419
rc = 0;
2629926420
p->nFloor = 0;
2630026421
}
2630126422
break;
26423
+ }
26424
+ case 'e': {
26425
+ /*
26426
+ ** end of day
26427
+ ** end of month
26428
+ ** end of year
26429
+ **
26430
+ ** Move the date forwards to the last millisecond of the current
26431
+ ** day, month or year.
26432
+ */
26433
+ if( sqlite3_strnicmp(z, "end of ", 7)!=0 ){
26434
+ break;
26435
+ }
26436
+ if( !p->validJD && !p->validYMD && !p->validHMS ) break;
26437
+ z += 7;
26438
+ computeYMD(p);
26439
+ p->validHMS = 1;
26440
+ p->h = 23;
26441
+ p->m = 59;
26442
+ p->s = 59.999;
26443
+ p->rawS = 0;
26444
+ p->tz = 0;
26445
+ p->validJD = 0;
26446
+ if( sqlite3_stricmp(z,"month")==0 ){
26447
+ p->D = 1;
26448
+ p->M++;
26449
+ if( p->M>12 ){
26450
+ p->Y++;
26451
+ p->M = 1;
26452
+ }
26453
+ computeFloor(p);
26454
+ computeJD(p);
26455
+ p->iJD -= (p->nFloor+1)*86400000;
26456
+ clearYMD_HMS_TZ(p);
26457
+ rc = 0;
26458
+ }else if( sqlite3_stricmp(z,"year")==0 ){
26459
+ p->M = 12;
26460
+ p->D = 31;
26461
+ rc = 0;
26462
+ }else if( sqlite3_stricmp(z,"day")==0 ){
26463
+ rc = 0;
26464
+ }
26465
+ break;
2630226466
}
2630326467
case 'f': {
2630426468
/*
2630526469
** floor
2630626470
**
@@ -26400,34 +26564,44 @@
2640026564
break;
2640126565
}
2640226566
case 'w': {
2640326567
/*
2640426568
** weekday N
26569
+ ** weekday -N
2640526570
**
26406
- ** Move the date to the same time on the next occurrence of
26407
- ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
26408
- ** date is already on the appropriate weekday, this is a no-op.
26571
+ ** Move the date forward (for N>=0) or backward (for N<=-0) to the
26572
+ ** same time on the next/previous occurrence of weekday abs(N)
26573
+ ** where 0==Sunday, 1==Monday, and so forth. If the date is already
26574
+ ** on the appropriate weekday, this is a no-op.
2640926575
*/
2641026576
if( sqlite3_strnicmp(z, "weekday ", 8)==0
26411
- && sqlite3AtoF(&z[8], &r)>0
26412
- && r>=0.0 && r<7.0 && (n=(int)r)==r ){
26577
+ && sqlite3AtoF(&z[8], &r)>0
26578
+ && r>=-6.0 && r<=6.0
26579
+ && sqlite3RealSameAsInt(r,(i64)(n=(int)r))
26580
+ ){
2641326581
sqlite3_int64 Z;
2641426582
computeYMD_HMS(p);
2641526583
p->tz = 0;
2641626584
p->validJD = 0;
2641726585
computeJD(p);
2641826586
Z = ((p->iJD + 129600000)/86400000) % 7;
26419
- if( Z>n ) Z -= 7;
26420
- p->iJD += (n - Z)*86400000;
26587
+ if( n<0 ) n = -n;
26588
+ if( Z!=n ){
26589
+ if( Z>n ) Z -= 7;
26590
+ p->iJD += (n - Z)*86400000;
26591
+ if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000;
26592
+ }
2642126593
clearYMD_HMS_TZ(p);
2642226594
rc = 0;
2642326595
}
2642426596
break;
2642526597
}
2642626598
case 's': {
2642726599
/*
26428
- ** start of TTTTT
26600
+ ** start of day
26601
+ ** start of month
26602
+ ** start of year
2642926603
**
2643026604
** Move the date backwards to the beginning of the current day,
2643126605
** or month or year.
2643226606
**
2643326607
** subsecond
@@ -26947,42 +27121,42 @@
2694727121
){
2694827122
DateTime x;
2694927123
size_t i,j;
2695027124
sqlite3 *db;
2695127125
const char *zFmt;
26952
- sqlite3_str sRes;
27126
+ sqlite3_str *pRes;
2695327127
2695427128
2695527129
if( argc==0 ) return;
2695627130
zFmt = (const char*)sqlite3_value_text(argv[0]);
2695727131
if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
2695827132
db = sqlite3_context_db_handle(context);
26959
- sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
27133
+ pRes = sqlite3_str_new(db);
2696027134
2696127135
computeJD(&x);
2696227136
computeYMD_HMS(&x);
2696327137
for(i=j=0; zFmt[i]; i++){
2696427138
char cf;
2696527139
if( zFmt[i]!='%' ) continue;
26966
- if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
27140
+ if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j));
2696727141
i++;
2696827142
j = i + 1;
2696927143
cf = zFmt[i];
2697027144
switch( cf ){
2697127145
case 'd': /* Fall thru */
2697227146
case 'e': {
26973
- sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D);
27147
+ sqlite3_str_appendf(pRes, cf=='d' ? "%02d" : "%2d", x.D);
2697427148
break;
2697527149
}
2697627150
case 'f': { /* Fractional seconds. (Non-standard) */
2697727151
double s = x.s;
2697827152
if( NEVER(s>59.999) ) s = 59.999;
26979
- sqlite3_str_appendf(&sRes, "%06.3f", s);
27153
+ sqlite3_str_appendf(pRes, "%06.3f", s);
2698027154
break;
2698127155
}
2698227156
case 'F': {
26983
- sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
27157
+ sqlite3_str_appendf(pRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
2698427158
break;
2698527159
}
2698627160
case 'G': /* Fall thru */
2698727161
case 'g': {
2698827162
DateTime y = x;
@@ -26990,85 +27164,85 @@
2699027164
/* Move y so that it is the Thursday in the same week as x */
2699127165
y.iJD += (3 - daysAfterMonday(&x))*86400000;
2699227166
y.validYMD = 0;
2699327167
computeYMD(&y);
2699427168
if( cf=='g' ){
26995
- sqlite3_str_appendf(&sRes, "%02d", y.Y%100);
27169
+ sqlite3_str_appendf(pRes, "%02d", y.Y%100);
2699627170
}else{
26997
- sqlite3_str_appendf(&sRes, "%04d", y.Y);
27171
+ sqlite3_str_appendf(pRes, "%04d", y.Y);
2699827172
}
2699927173
break;
2700027174
}
2700127175
case 'H':
2700227176
case 'k': {
27003
- sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h);
27177
+ sqlite3_str_appendf(pRes, cf=='H' ? "%02d" : "%2d", x.h);
2700427178
break;
2700527179
}
2700627180
case 'I': /* Fall thru */
2700727181
case 'l': {
2700827182
int h = x.h;
2700927183
if( h>12 ) h -= 12;
2701027184
if( h==0 ) h = 12;
27011
- sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h);
27185
+ sqlite3_str_appendf(pRes, cf=='I' ? "%02d" : "%2d", h);
2701227186
break;
2701327187
}
2701427188
case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */
27015
- sqlite3_str_appendf(&sRes,"%03d",daysAfterJan01(&x)+1);
27189
+ sqlite3_str_appendf(pRes,"%03d",daysAfterJan01(&x)+1);
2701627190
break;
2701727191
}
2701827192
case 'J': { /* Julian day number. (Non-standard) */
27019
- sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0);
27193
+ sqlite3_str_appendf(pRes,"%.16g",x.iJD/86400000.0);
2702027194
break;
2702127195
}
2702227196
case 'm': {
27023
- sqlite3_str_appendf(&sRes,"%02d",x.M);
27197
+ sqlite3_str_appendf(pRes,"%02d",x.M);
2702427198
break;
2702527199
}
2702627200
case 'M': {
27027
- sqlite3_str_appendf(&sRes,"%02d",x.m);
27201
+ sqlite3_str_appendf(pRes,"%02d",x.m);
2702827202
break;
2702927203
}
2703027204
case 'p': /* Fall thru */
2703127205
case 'P': {
2703227206
if( x.h>=12 ){
27033
- sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2);
27207
+ sqlite3_str_append(pRes, cf=='p' ? "PM" : "pm", 2);
2703427208
}else{
27035
- sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2);
27209
+ sqlite3_str_append(pRes, cf=='p' ? "AM" : "am", 2);
2703627210
}
2703727211
break;
2703827212
}
2703927213
case 'R': {
27040
- sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m);
27214
+ sqlite3_str_appendf(pRes, "%02d:%02d", x.h, x.m);
2704127215
break;
2704227216
}
2704327217
case 's': {
2704427218
if( x.useSubsec ){
27045
- sqlite3_str_appendf(&sRes,"%.3f",
27219
+ sqlite3_str_appendf(pRes,"%.3f",
2704627220
(x.iJD - 21086676*(i64)10000000)/1000.0);
2704727221
}else{
2704827222
i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
27049
- sqlite3_str_appendf(&sRes,"%lld",iS);
27223
+ sqlite3_str_appendf(pRes,"%lld",iS);
2705027224
}
2705127225
break;
2705227226
}
2705327227
case 'S': {
27054
- sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
27228
+ sqlite3_str_appendf(pRes,"%02d",(int)x.s);
2705527229
break;
2705627230
}
2705727231
case 'T': {
27058
- sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
27232
+ sqlite3_str_appendf(pRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
2705927233
break;
2706027234
}
2706127235
case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */
2706227236
case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */
2706327237
char c = (char)daysAfterSunday(&x) + '0';
2706427238
if( c=='0' && cf=='u' ) c = '7';
27065
- sqlite3_str_appendchar(&sRes, 1, c);
27239
+ sqlite3_str_appendchar(pRes, 1, c);
2706627240
break;
2706727241
}
2706827242
case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */
27069
- sqlite3_str_appendf(&sRes,"%02d",
27243
+ sqlite3_str_appendf(pRes,"%02d",
2707027244
(daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7);
2707127245
break;
2707227246
}
2707327247
case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */
2707427248
DateTime y = x;
@@ -27075,34 +27249,34 @@
2707527249
/* Adjust y so that is the Thursday in the same week as x */
2707627250
assert( y.validJD );
2707727251
y.iJD += (3 - daysAfterMonday(&x))*86400000;
2707827252
y.validYMD = 0;
2707927253
computeYMD(&y);
27080
- sqlite3_str_appendf(&sRes,"%02d", daysAfterJan01(&y)/7+1);
27254
+ sqlite3_str_appendf(pRes,"%02d", daysAfterJan01(&y)/7+1);
2708127255
break;
2708227256
}
2708327257
case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */
27084
- sqlite3_str_appendf(&sRes,"%02d",
27258
+ sqlite3_str_appendf(pRes,"%02d",
2708527259
(daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7);
2708627260
break;
2708727261
}
2708827262
case 'Y': {
27089
- sqlite3_str_appendf(&sRes,"%04d",x.Y);
27263
+ sqlite3_str_appendf(pRes,"%04d",x.Y);
2709027264
break;
2709127265
}
2709227266
case '%': {
27093
- sqlite3_str_appendchar(&sRes, 1, '%');
27267
+ sqlite3_str_appendchar(pRes, 1, '%');
2709427268
break;
2709527269
}
2709627270
default: {
27097
- sqlite3_str_reset(&sRes);
27271
+ sqlite3_str_free(pRes);
2709827272
return;
2709927273
}
2710027274
}
2710127275
}
27102
- if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
27103
- sqlite3ResultStrAccum(context, &sRes);
27276
+ if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j));
27277
+ sqlite3_result_str(context, pRes, SQLITE_FINISH);
2710427278
}
2710527279
2710627280
/*
2710727281
** current_time()
2710827282
**
@@ -27234,11 +27408,11 @@
2723427408
clearYMD_HMS_TZ(&d1);
2723527409
computeYMD_HMS(&d1);
2723627410
sqlite3StrAccumInit(&sRes, 0, 0, 0, 100);
2723727411
sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f",
2723827412
sign, Y, M, d1.D-1, d1.h, d1.m, d1.s);
27239
- sqlite3ResultStrAccum(context, &sRes);
27413
+ sqlite3_result_str(context, &sRes, SQLITE_XFER);
2724027414
}
2724127415
2724227416
2724327417
/*
2724427418
** current_timestamp()
@@ -27662,11 +27836,11 @@
2766227836
if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
2766327837
rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
2766427838
}else{
2766527839
double r;
2766627840
rc = pVfs->xCurrentTime(pVfs, &r);
27667
- *pTimeOut = (sqlite3_int64)(r*86400000.0);
27841
+ *pTimeOut = sqlite3RealToI64(r*86400000.0);
2766827842
}
2766927843
return rc;
2767027844
}
2767127845
2767227846
SQLITE_PRIVATE int sqlite3OsOpenMalloc(
@@ -32612,10 +32786,14 @@
3261232786
*/
3261332787
#ifndef SQLITE_PRINTF_PRECISION_LIMIT
3261432788
# define SQLITE_FP_PRECISION_LIMIT 100000000
3261532789
#endif
3261632790
32791
+/* Forward reference */
32792
+static void sqlite3StrAppend64(sqlite3_str *p, const char *z, i64 N);
32793
+static void sqlite3StrAppendchar64(sqlite3_str *p, i64 N, char c);
32794
+
3261732795
/*
3261832796
** Render a string given by "fmt" into the StrAccum object.
3261932797
*/
3262032798
SQLITE_API void sqlite3_str_vappendf(
3262132799
sqlite3_str *pAccum, /* Accumulate results here */
@@ -32622,14 +32800,14 @@
3262232800
const char *fmt, /* Format string */
3262332801
va_list ap /* arguments */
3262432802
){
3262532803
int c; /* Next character in the format string */
3262632804
char *bufpt; /* Pointer to the conversion buffer */
32627
- int precision; /* Precision of the current field */
32628
- int length; /* Length of the field */
32805
+ i64 precision; /* Precision of the current field */
32806
+ i64 length; /* Length of the field */
3262932807
int idx; /* A general purpose loop counter */
32630
- int width; /* Width of the current field */
32808
+ i64 width; /* Width of the current field */
3263132809
etByte flag_leftjustify; /* True if "-" flag is present */
3263232810
etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
3263332811
etByte flag_alternateform; /* True if "#" flag is present */
3263432812
etByte flag_altform2; /* True if "!" flag is present */
3263532813
etByte flag_zeropad; /* True if field width constant starts with zero */
@@ -32673,11 +32851,11 @@
3267332851
fmt = strchr(fmt, '%');
3267432852
if( fmt==0 ){
3267532853
fmt = bufpt + strlen(bufpt);
3267632854
}
3267732855
#endif
32678
- sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
32856
+ sqlite3StrAppend64(pAccum, bufpt, fmt - bufpt);
3267932857
if( *fmt==0 ) break;
3268032858
}
3268132859
if( (c=(*++fmt))==0 ){
3268232860
sqlite3_str_append(pAccum, "%", 1);
3268332861
break;
@@ -32919,26 +33097,27 @@
3291933097
do{ /* Convert to ascii */
3292033098
*(--bufpt) = cset[longvalue%base];
3292133099
longvalue = longvalue/base;
3292233100
}while( longvalue>0 );
3292333101
}
32924
- length = (int)(&zOut[nOut-1]-bufpt);
33102
+ length = &zOut[nOut-1] - bufpt;
3292533103
if( precision>length ){ /* zero pad */
32926
- int nn = precision-length;
33104
+ i64 nn = precision-length;
3292733105
bufpt -= nn;
3292833106
memset(bufpt,'0',nn);
3292933107
length = precision;
3293033108
}
3293133109
if( cThousand ){
32932
- int nn = (length - 1)/3; /* Number of "," to insert */
32933
- int ix = (length - 1)%3 + 1;
33110
+ i64 nn = (length - 1)/3; /* Number of "," to insert */
33111
+ i64 ix = (length - 1)%3 + 1;
33112
+ int ii;
3293433113
bufpt -= nn;
32935
- for(idx=0; nn>0; idx++){
32936
- bufpt[idx] = bufpt[idx+nn];
33114
+ for(ii=0; nn>0; ii++){
33115
+ bufpt[ii] = bufpt[ii+nn];
3293733116
ix--;
3293833117
if( ix==0 ){
32939
- bufpt[++idx] = cThousand;
33118
+ bufpt[++ii] = cThousand;
3294033119
nn--;
3294133120
ix = 3;
3294233121
}
3294333122
}
3294433123
}
@@ -32947,11 +33126,11 @@
3294733126
const char *pre;
3294833127
char x;
3294933128
pre = &aPrefix[infop->prefix];
3295033129
for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
3295133130
}
32952
- length = (int)(&zOut[nOut-1]-bufpt);
33131
+ length = &zOut[nOut-1] - bufpt;
3295333132
break;
3295433133
case etFLOAT:
3295533134
case etEXP:
3295633135
case etGENERIC: {
3295733136
FpDecode s;
@@ -32979,12 +33158,17 @@
3297933158
iRound = precision+1;
3298033159
}
3298133160
sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 20 : 16);
3298233161
if( s.isSpecial ){
3298333162
if( s.isSpecial==2 ){
32984
- bufpt = flag_zeropad ? "null" : "NaN";
32985
- length = sqlite3Strlen30(bufpt);
33163
+ if( flag_zeropad ){
33164
+ bufpt = "null";
33165
+ length = 4;
33166
+ }else{
33167
+ bufpt = "NaN";
33168
+ length = 3;
33169
+ }
3298633170
break;
3298733171
}else if( flag_zeropad ){
3298833172
s.z[0] = '9';
3298933173
s.iDP = 1000;
3299033174
s.n = 1;
@@ -32996,11 +33180,11 @@
3299633180
}else if( flag_prefix ){
3299733181
buf[0] = flag_prefix;
3299833182
}else{
3299933183
bufpt++;
3300033184
}
33001
- length = sqlite3Strlen30(bufpt);
33185
+ length = strlen(bufpt);
3300233186
break;
3300333187
}
3300433188
}
3300533189
if( s.sign=='-' ){
3300633190
if( flag_alternateform
@@ -33152,11 +33336,11 @@
3315233336
}
3315333337
*(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
3315433338
*(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
3315533339
}
3315633340
33157
- length = (int)(bufpt-zOut);
33341
+ length = bufpt - zOut;
3315833342
assert( length <= szBufNeeded );
3315933343
if( length<width ){
3316033344
i64 nPad = width - length;
3316133345
if( flag_leftjustify ){
3316233346
memset(bufpt, ' ', nPad);
@@ -33172,10 +33356,11 @@
3317233356
}
3317333357
3317433358
if( zExtra==0 ){
3317533359
/* The result is being rendered directory into pAccum. This
3317633360
** is the common and fast case */
33361
+ assert( pAccum->nChar + length < SMXV(pAccum->nChar) );
3317733362
pAccum->nChar += length;
3317833363
zOut[length] = 0;
3317933364
continue;
3318033365
}else{
3318133366
/* We were unable to render directly into pAccum because we
@@ -33218,14 +33403,14 @@
3321833403
}
3321933404
if( precision>1 ){
3322033405
i64 nPrior = 1;
3322133406
width -= precision-1;
3322233407
if( width>1 && !flag_leftjustify ){
33223
- sqlite3_str_appendchar(pAccum, width-1, ' ');
33408
+ sqlite3StrAppendchar64(pAccum, width-1, ' ');
3322433409
width = 0;
3322533410
}
33226
- sqlite3_str_append(pAccum, buf, length);
33411
+ sqlite3StrAppend64(pAccum, buf, length);
3322733412
precision--;
3322833413
while( precision > 1 ){
3322933414
i64 nCopyBytes;
3323033415
if( nPrior > precision-1 ) nPrior = precision - 1;
3323133416
nCopyBytes = length*nPrior;
@@ -33277,21 +33462,21 @@
3327733462
** precision characters */
3327833463
unsigned char *z = (unsigned char*)bufpt;
3327933464
while( precision-- > 0 && z[0] ){
3328033465
SQLITE_SKIP_UTF8(z);
3328133466
}
33282
- length = (int)(z - (unsigned char*)bufpt);
33467
+ length = z - (unsigned char*)bufpt;
3328333468
}else{
3328433469
for(length=0; length<precision && bufpt[length]; length++){}
3328533470
}
3328633471
}else{
33287
- length = 0x7fffffff & (int)strlen(bufpt);
33472
+ length = strlen(bufpt);
3328833473
}
3328933474
adjust_width_for_utf8:
3329033475
if( flag_altform2 && width>0 ){
3329133476
/* Adjust width to account for extra bytes in UTF-8 characters */
33292
- int ii = length - 1;
33477
+ i64 ii = length - 1;
3329333478
while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
3329433479
}
3329533480
break;
3329633481
case etESCAPE_j: /* %j: JSON string literal w/o "..." */
3329733482
case etESCAPE_J: { /* %J: Generate a JSON string literal */
@@ -33322,11 +33507,11 @@
3332233507
while( (escarg[px]&0xc0)==0x80 ) px++;
3332333508
}
3332433509
}
3332533510
for(i=j=0; i<px; i++){
3332633511
if( (ch = ((u8*)escarg)[i])<=0x1f || ch=='"' || ch=='\\' ){
33327
- if( j<i ) sqlite3_str_append(pAccum, &escarg[j], i-j);
33512
+ if( j<i ) sqlite3StrAppend64(pAccum, &escarg[j], i-j);
3332833513
j = i+1;
3332933514
if( ch==0 ) break;
3333033515
sqlite3_str_appendchar(pAccum, 1, '\\');
3333133516
if( ch>0x1f ){
3333233517
sqlite3_str_appendchar(pAccum, 1, ch);
@@ -33338,11 +33523,11 @@
3333833523
sqlite3_str_appendchar(pAccum, 1, aHex[ch>>4]);
3333933524
sqlite3_str_appendchar(pAccum, 1, aHex[ch&0xf]);
3334033525
}
3334133526
}
3334233527
}
33343
- if( j<i ) sqlite3_str_append(pAccum, &escarg[j], i-j);
33528
+ if( j<i ) sqlite3StrAppend64(pAccum, &escarg[j], i-j);
3334433529
if( xtype==etESCAPE_J ) sqlite3_str_append(pAccum, "\"", 1);
3334533530
}
3334633531
if( width>0 && sqlite3_str_errcode(pAccum)==SQLITE_OK ){
3334733532
sqlite3_int64 n = sqlite3_str_length(pAccum) - iStart;
3334833533
sqlite3_int64 len = n;
@@ -33354,11 +33539,11 @@
3335433539
}
3335533540
}
3335633541
if( width>len ){
3335733542
sqlite3_int64 sp = width-len;
3335833543
assert( sp>0 && sp<0x7fffffff );
33359
- sqlite3_str_appendchar(pAccum, (int)sp, ' ');
33544
+ sqlite3StrAppendchar64(pAccum, (int)sp, ' ');
3336033545
if( !flag_leftjustify
3336133546
&& n>0
3336233547
&& sqlite3_str_errcode(pAccum)==0
3336333548
){
3336433549
zz = sqlite3_str_value(pAccum);
@@ -33546,15 +33731,15 @@
3354633731
** indicating that width and precision should be expressed in characters,
3354733732
** then the values have been translated prior to reaching this point.
3354833733
*/
3354933734
width -= length;
3355033735
if( width>0 ){
33551
- if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
33552
- sqlite3_str_append(pAccum, bufpt, length);
33553
- if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
33736
+ if( !flag_leftjustify ) sqlite3StrAppendchar64(pAccum, width, ' ');
33737
+ sqlite3StrAppend64(pAccum, bufpt, length);
33738
+ if( flag_leftjustify ) sqlite3StrAppendchar64(pAccum, width, ' ');
3355433739
}else{
33555
- sqlite3_str_append(pAccum, bufpt, length);
33740
+ sqlite3StrAppend64(pAccum, bufpt, length);
3355633741
}
3355733742
3355833743
if( zExtra ){
3355933744
sqlite3DbFree(pAccum->db, zExtra);
3356033745
zExtra = 0;
@@ -33670,10 +33855,17 @@
3367033855
if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
3367133856
return;
3367233857
}
3367333858
while( (N--)>0 ) p->zText[p->nChar++] = c;
3367433859
}
33860
+static void sqlite3StrAppendchar64(sqlite3_str *p, i64 N, char c){
33861
+ testcase( p->nChar + N > 0x7fffffff );
33862
+ if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
33863
+ return;
33864
+ }
33865
+ while( (N--)>0 ) p->zText[p->nChar++] = c;
33866
+}
3367533867
3367633868
/*
3367733869
** The StrAccum "p" is not large enough to accept N new bytes of z[].
3367833870
** So enlarge if first, then do the append.
3367933871
**
@@ -33681,10 +33873,11 @@
3368133873
** work (enlarging the buffer) using tail recursion, so that the
3368233874
** sqlite3_str_append() routine can use fast calling semantics.
3368333875
*/
3368433876
static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
3368533877
N = sqlite3StrAccumEnlarge(p, N);
33878
+ assert( z!=0 || N==0 );
3368633879
if( N>0 ){
3368733880
memcpy(&p->zText[p->nChar], z, N);
3368833881
p->nChar += N;
3368933882
}
3369033883
}
@@ -33704,10 +33897,24 @@
3370433897
assert( p->zText );
3370533898
p->nChar += N;
3370633899
memcpy(&p->zText[p->nChar-N], z, N);
3370733900
}
3370833901
}
33902
+static void sqlite3StrAppend64(sqlite3_str *p, const char *z, i64 N){
33903
+ assert( z!=0 || N==0 );
33904
+ assert( p->zText!=0 || p->nChar==0 || p->accError );
33905
+ assert( N>=0 );
33906
+ assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
33907
+ if( p->nChar+N >= (i64)p->nAlloc ){
33908
+ enlargeAndAppend(p,z,N);
33909
+ }else if( N ){
33910
+ assert( p->zText );
33911
+ p->nChar += N;
33912
+ memcpy(&p->zText[p->nChar-N], z, N);
33913
+ }
33914
+}
33915
+
3370933916
3371033917
/*
3371133918
** Append the complete text of zero-terminated string z[] to the p string.
3371233919
*/
3371333920
SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
@@ -33741,41 +33948,15 @@
3374133948
}
3374233949
}
3374333950
return p->zText;
3374433951
}
3374533952
33746
-/*
33747
-** Use the content of the StrAccum passed as the second argument
33748
-** as the result of an SQL function.
33749
-*/
33750
-SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
33751
- if( p->accError ){
33752
- sqlite3_result_error_code(pCtx, p->accError);
33753
- sqlite3_str_reset(p);
33754
- }else if( isMalloced(p) ){
33755
- sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
33756
- }else{
33757
- sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
33758
- sqlite3_str_reset(p);
33759
- }
33760
-}
33761
-
33762
-/*
33763
-** This singleton is an sqlite3_str object that is returned if
33764
-** sqlite3_malloc() fails to provide space for a real one. This
33765
-** sqlite3_str object accepts no new text and always returns
33766
-** an SQLITE_NOMEM error.
33767
-*/
33768
-static sqlite3_str sqlite3OomStr = {
33769
- 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
33770
-};
33771
-
3377233953
/* Finalize a string created using sqlite3_str_new().
3377333954
*/
3377433955
SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
3377533956
char *z;
33776
- if( p!=0 && p!=&sqlite3OomStr ){
33957
+ if( p!=0 && p!=(sqlite3_str*)&sqlite3OomStr ){
3377733958
z = sqlite3StrAccumFinish(p);
3377833959
sqlite3_free(p);
3377933960
}else{
3378033961
z = 0;
3378133962
}
@@ -33812,10 +33993,12 @@
3381233993
*/
3381333994
SQLITE_API void sqlite3_str_reset(StrAccum *p){
3381433995
if( isMalloced(p) ){
3381533996
sqlite3DbFree(p->db, p->zText);
3381633997
p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
33998
+ }else if( p==(sqlite3_str*)&sqlite3OomStr ){
33999
+ return;
3381734000
}
3381834001
p->nAlloc = 0;
3381934002
p->nChar = 0;
3382034003
p->zText = 0;
3382134004
}
@@ -33823,11 +34006,11 @@
3382334006
/*
3382434007
** Destroy a dynamically allocate sqlite3_str object and all
3382534008
** of its content, all in one call.
3382634009
*/
3382734010
SQLITE_API void sqlite3_str_free(sqlite3_str *p){
33828
- if( p!=0 && p!=&sqlite3OomStr ){
34011
+ if( p!=0 && p!=(sqlite3_str*)&sqlite3OomStr ){
3382934012
sqlite3_str_reset(p);
3383034013
sqlite3_free(p);
3383134014
}
3383234015
}
3383334016
@@ -33860,11 +34043,11 @@
3386034043
sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
3386134044
if( p ){
3386234045
sqlite3StrAccumInit(p, 0, 0, 0,
3386334046
db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
3386434047
}else{
33865
- p = &sqlite3OomStr;
34048
+ p = (sqlite3_str*)&sqlite3OomStr;
3386634049
}
3386734050
return p;
3386834051
}
3386934052
3387034053
/*
@@ -37500,11 +37683,11 @@
3750037683
return mState;
3750137684
}
3750237685
}
3750337686
return 0xfffffff0 | mState;
3750437687
#else
37505
- return sqlite3Atoi64(z, pResult, strlen(z), SQLITE_UTF8)==0;
37688
+ return sqlite3Atoi64(zIn, pResult, strlen(zIn), SQLITE_UTF8)==0;
3750637689
#endif /* SQLITE_OMIT_FLOATING_POINT */
3750737690
}
3750837691
3750937692
/*
3751037693
** Digit pairs used to convert a U64 or I64 into text, two digits
@@ -39731,20 +39914,21 @@
3973139914
i = 0;
3973239915
j = 0;
3973339916
while( 1 ){
3973439917
c = kvvfsHexValue[aIn[i]];
3973539918
if( c<0 ){
39736
- int n = 0;
39737
- int mult = 1;
39919
+ sqlite3_int64 n = 0;
39920
+ sqlite3_int64 mult = 1;
3973839921
c = aIn[i];
3973939922
if( c==0 ) break;
3974039923
while( c>='a' && c<='z' ){
3974139924
n += (c - 'a')*mult;
39925
+ if( n>nOut ) return -1 /* oversized/malformed input */;
3974239926
mult *= 26;
3974339927
c = aIn[++i];
3974439928
}
39745
- if( j+n>nOut ) return -1;
39929
+ if( j+n>nOut ) return -1 /* oversized/malformed input */;
3974639930
memset(&aOut[j], 0, n);
3974739931
j += n;
3974839932
if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
3974939933
}else if( j<nOut ){
3975039934
aOut[j] = c<<4;
@@ -39773,22 +39957,28 @@
3977339957
static void kvvfsDecodeJournal(
3977439958
KVVfsFile *pFile, /* Store decoding in pFile->aJrnl */
3977539959
const char *zTxt, /* Text encoding. Zero-terminated */
3977639960
int nTxt /* Bytes in zTxt, excluding zero terminator */
3977739961
){
39778
- unsigned int n = 0;
39779
- int c, i, mult;
39962
+ unsigned int n = 0, mult;
39963
+ int c, i;
3978039964
i = 0;
3978139965
mult = 1;
39782
- while( (c = zTxt[i++])>='a' && c<='z' ){
39783
- n += (zTxt[i] - 'a')*mult;
39966
+ sqlite3_free(pFile->aJrnl);
39967
+ pFile->aJrnl = 0;
39968
+ pFile->nJrnl = 0;
39969
+ while( (c = zTxt[i])>='a' && c<='z' ){
39970
+ n += (c - 'a')*mult;
3978439971
mult *= 26;
39972
+ ++i;
3978539973
}
39786
- sqlite3_free(pFile->aJrnl);
39974
+ if( ' '!=zTxt[i++] ){
39975
+ /* Malformed input */
39976
+ return;
39977
+ }
3978739978
pFile->aJrnl = sqlite3_malloc64( n );
3978839979
if( pFile->aJrnl==0 ){
39789
- pFile->nJrnl = 0;
3979039980
return;
3979139981
}
3979239982
pFile->nJrnl = n;
3979339983
n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl);
3979439984
if( n<pFile->nJrnl ){
@@ -39824,13 +40014,11 @@
3982440014
3982540015
SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass,
3982640016
pFile->isJournal ? "journal" : "db"));
3982740017
sqlite3_free(pFile->aJrnl);
3982840018
sqlite3_free(pFile->aData);
39829
-#ifdef SQLITE_WASM
3983040019
memset(pFile, 0, sizeof(*pFile));
39831
-#endif
3983240020
return SQLITE_OK;
3983340021
}
3983440022
3983540023
/*
3983640024
** Read from the -journal file.
@@ -39856,10 +40044,11 @@
3985640044
if( aTxt==0 ) return SQLITE_NOMEM;
3985740045
rc = sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, "jrnl",
3985840046
aTxt, szTxt+1);
3985940047
if( rc>=0 ){
3986040048
kvvfsDecodeJournal(pFile, aTxt, szTxt);
40049
+ rc = 0;
3986140050
}
3986240051
sqlite3_free(aTxt);
3986340052
if( rc ) return rc;
3986440053
if( pFile->aJrnl==0 ) return SQLITE_IOERR;
3986540054
}
@@ -40180,11 +40369,11 @@
4018040369
}
4018140370
if( !pFile->zClass ){
4018240371
#ifdef SQLITE_WASM
4018340372
if( strlen(zName) >= (KVRECORD_KEY_SZ
4018440373
- 6 /* "kvvfs-" */
40185
- - 11 /* "-##########" */) ){
40374
+ - 11 /* "-NNNNNNNNNNN" */) ){
4018640375
return SQLITE_CANTOPEN;
4018740376
}
4018840377
#else
4018940378
if( 0!=strcmp(zName, "local") && 0!=strcmp(zName, "session") ){
4019040379
/* Historical naming restriction which journaling depends on. */
@@ -45946,11 +46135,10 @@
4594646135
i64 nNew /* Required mapping size */
4594746136
){
4594846137
const char *zErr = "mmap";
4594946138
int h = pFd->h; /* File descriptor open on db file */
4595046139
u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
45951
- i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
4595246140
u8 *pNew = 0; /* Location of new mapping */
4595346141
int flags = PROT_READ; /* Flags to pass to mmap() */
4595446142
4595546143
assert( pFd->nFetchOut==0 );
4595646144
assert( nNew>pFd->mmapSize );
@@ -45964,25 +46152,16 @@
4596446152
#endif
4596546153
4596646154
if( pOrig ){
4596746155
#if HAVE_MREMAP
4596846156
i64 nReuse = pFd->mmapSize;
46157
+ pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
46158
+ zErr = "mremap";
4596946159
#else
4597046160
const int szSyspage = osGetpagesize();
4597146161
i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
45972
-#endif
4597346162
u8 *pReq = &pOrig[nReuse];
45974
-
45975
- /* Unmap any pages of the existing mapping that cannot be reused. */
45976
- if( nReuse!=nOrig ){
45977
- osMunmap(pReq, nOrig-nReuse);
45978
- }
45979
-
45980
-#if HAVE_MREMAP
45981
- pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
45982
- zErr = "mremap";
45983
-#else
4598446163
pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4598546164
if( pNew!=MAP_FAILED ){
4598646165
if( pNew!=pReq ){
4598746166
osMunmap(pNew, nNew - nReuse);
4598846167
pNew = 0;
@@ -46613,40 +46792,33 @@
4661346792
verifyDbFile(pNew);
4661446793
}
4661546794
return rc;
4661646795
}
4661746796
46618
-/*
46619
-** Directories to consider for temp files.
46620
-*/
46621
-static const char *azTempDirs[] = {
46622
- 0,
46623
- 0,
46624
- "/var/tmp",
46625
- "/usr/tmp",
46626
- "/tmp",
46627
- "."
46628
-};
46629
-
46630
-/*
46631
-** Initialize first two members of azTempDirs[] array.
46632
-*/
46633
-static void unixTempFileInit(void){
46634
- azTempDirs[0] = getenv("SQLITE_TMPDIR");
46635
- azTempDirs[1] = getenv("TMPDIR");
46636
-}
46637
-
4663846797
/*
4663946798
** Return the name of a directory in which to put temporary files.
4664046799
** If no suitable temporary file directory can be found, return NULL.
46800
+**
46801
+** The return value might be a string obtained from getenv() and so
46802
+** the return value should not be used after any call to setenv() or
46803
+** putenv() as that value might have been freed.
4664146804
*/
4664246805
static const char *unixTempFileDir(void){
46643
- unsigned int i = 0;
46806
+ unsigned int i;
4664446807
struct stat buf;
46645
- const char *zDir = sqlite3_temp_directory;
46808
+ const char *zDir;
4664646809
46647
- while(1){
46810
+ for(i=0; i<7; i++){
46811
+ switch( i ){
46812
+ case 0: zDir = sqlite3_temp_directory; break;
46813
+ case 1: zDir = getenv("SQLITE_TMPDIR"); break;
46814
+ case 2: zDir = getenv("TMPDIR"); break;
46815
+ case 3: zDir = "/var/tmp"; break;
46816
+ case 4: zDir = "/usr/tmp"; break;
46817
+ case 5: zDir = "/tmp"; break;
46818
+ default: zDir = "."; break;
46819
+ }
4664846820
if( zDir!=0
4664946821
#if OS_VXWORKS
4665046822
&& zDir[0]=='/'
4665146823
#endif
4665246824
&& osStat(zDir, &buf)==0
@@ -46653,12 +46825,10 @@
4665346825
&& S_ISDIR(buf.st_mode)
4665446826
&& osAccess(zDir, 03)==0
4665546827
){
4665646828
return zDir;
4665746829
}
46658
- if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
46659
- zDir = azTempDirs[i++];
4666046830
}
4666146831
return 0;
4666246832
}
4666346833
4666446834
/*
@@ -48937,13 +49107,10 @@
4893749107
** DMS UNIX_SHM_BASE+8 128
4893849108
*/
4893949109
assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
4894049110
#endif
4894149111
48942
- /* Initialize temp file dir array. */
48943
- unixTempFileInit();
48944
-
4894549112
return SQLITE_OK;
4894649113
}
4894749114
4894849115
/*
4894949116
** Shutdown the operating system interface.
@@ -52221,11 +52388,11 @@
5222152388
# define sqlite3_win_test_unc_locking 0
5222252389
#endif
5222352390
5222452391
/*
5222552392
** Return true if the string passed as the only argument is likely
52226
-** to be a UNC path. Return false if note.
52393
+** to be a UNC path. Return false if not.
5222752394
**
5222852395
** Return true if:
5222952396
**
5223052397
** (1) The name begins with "\\"
5223152398
** (2) But does not begin with "\\?\C:\" where C can be any alphabetic
@@ -55070,26 +55237,27 @@
5507055237
int iDb;
5507155238
Btree *pBt;
5507255239
sqlite3_int64 sz;
5507355240
int szPage = 0;
5507455241
sqlite3_stmt *pStmt = 0;
55075
- unsigned char *pOut;
55242
+ unsigned char *pOut = 0;
5507655243
char *zSql;
5507755244
int rc;
5507855245
5507955246
#ifdef SQLITE_ENABLE_API_ARMOR
5508055247
if( !sqlite3SafetyCheckOk(db) ){
5508155248
(void)SQLITE_MISUSE_BKPT;
5508255249
return 0;
5508355250
}
5508455251
#endif
55252
+ sqlite3_mutex_enter(db->mutex);
5508555253
5508655254
if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
5508755255
p = memdbFromDbSchema(db, zSchema);
5508855256
iDb = sqlite3FindDbName(db, zSchema);
5508955257
if( piSize ) *piSize = -1;
55090
- if( iDb<0 ) return 0;
55258
+ if( iDb<0 ) goto serialize_out;
5509155259
if( p ){
5509255260
MemStore *pStore = p->pStore;
5509355261
assert( pStore->pMutex==0 );
5509455262
if( piSize ) *piSize = pStore->sz;
5509555263
if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
@@ -55096,23 +55264,21 @@
5509655264
pOut = pStore->aData;
5509755265
}else{
5509855266
pOut = sqlite3_malloc64( pStore->sz );
5509955267
if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
5510055268
}
55101
- return pOut;
55269
+ goto serialize_out;
5510255270
}
5510355271
pBt = db->aDb[iDb].pBt;
55104
- if( pBt==0 ) return 0;
55272
+ if( pBt==0 ) goto serialize_out;
5510555273
szPage = sqlite3BtreeGetPageSize(pBt);
5510655274
zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
5510755275
rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
5510855276
sqlite3_free(zSql);
55109
- if( rc ) return 0;
55277
+ if( rc ) goto serialize_out;
5511055278
rc = sqlite3_step(pStmt);
55111
- if( rc!=SQLITE_ROW ){
55112
- pOut = 0;
55113
- }else{
55279
+ if( rc==SQLITE_ROW ){
5511455280
sz = sqlite3_column_int64(pStmt, 0)*szPage;
5511555281
if( sz==0 ){
5511655282
sqlite3_reset(pStmt);
5511755283
sqlite3_exec(db, "BEGIN IMMEDIATE; COMMIT;", 0, 0, 0);
5511855284
rc = sqlite3_step(pStmt);
@@ -55142,10 +55308,13 @@
5514255308
}
5514355309
}
5514455310
}
5514555311
}
5514655312
sqlite3_finalize(pStmt);
55313
+
55314
+ serialize_out:
55315
+ sqlite3_mutex_leave(db->mutex);
5514755316
return pOut;
5514855317
}
5514955318
5515055319
/* Convert zSchema to a MemDB and initialize its content.
5515155320
*/
@@ -59917,10 +60086,45 @@
5991760086
static void freeSuperJournal(char *zSuper){
5991860087
if( zSuper ){
5991960088
sqlite3_free(&zSuper[-4]);
5992060089
}
5992160090
}
60091
+
60092
+/*
60093
+** Check if zSuper is a valid super-journal name. There are two valid
60094
+** formats:
60095
+**
60096
+** + The 3rd and 4th last bytes of the filename are ".9", and the
60097
+** following 2 bytes are hex digits. This is a file created in 8.3
60098
+** filenames mode.
60099
+**
60100
+** + The 3rd last byte of the filename is "9" and the filename
60101
+** contains the string "-mj" starting at the 12th last byte.
60102
+** All bytes following the "-mj" are hex digits.
60103
+**
60104
+** If the filename matches either of these patterns, return non-zero.
60105
+** Otherwise, return zero.
60106
+*/
60107
+static int pagerIsSuperJrnlName(const char *zSuper){
60108
+ const int nSuper = sqlite3Strlen30(zSuper);
60109
+ int ii;
60110
+
60111
+#ifdef SQLITE_ENABLE_8_3_NAMES
60112
+ if( nSuper<4 ) return 0;
60113
+ if( zSuper[nSuper-3]!='9' ) return 0;
60114
+ if( sqlite3Isxdigit(zSuper[nSuper-2])==0 ) return 0;
60115
+ if( sqlite3Isxdigit(zSuper[nSuper-1])==0 ) return 0;
60116
+ if( zSuper[nSuper-4]=='.' ) return 1;
60117
+#endif
60118
+ if( nSuper<12 ) return 0;
60119
+ if( memcmp(&zSuper[nSuper-12], "-mj", 3) ) return 0;
60120
+ if( zSuper[nSuper-3]!='9' ) return 0;
60121
+ for(ii=nSuper-9; ii<nSuper; ii++){
60122
+ if( sqlite3Isxdigit(zSuper[ii])==0 ) return 0;
60123
+ }
60124
+ return 1;
60125
+}
5992260126
5992360127
/*
5992460128
** Parameter pJrnl is a file-handle open on a journal file. This function
5992560129
** attempts to read a super-journal file name from the end of the journal
5992660130
** file. If successful, it sets output parameter (*pzSuper) to point to a
@@ -59955,32 +60159,34 @@
5995560159
|| len>=nSuper
5995660160
|| len>szJ-16
5995760161
|| len==0
5995860162
|| SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
5995960163
|| SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
59960
- || memcmp(aMagic, aJournalMagic, 8)
5996160164
){
5996260165
return rc;
5996360166
}
5996460167
5996560168
zOut = (char*)sqlite3MallocZero(4 + len + 2);
5996660169
if( !zOut ){
59967
- rc = SQLITE_NOMEM_BKPT;
60170
+ rc = memcmp(aMagic,aJournalMagic,8) ? SQLITE_OK : SQLITE_NOMEM_BKPT;
5996860171
}else{
5996960172
zOut = &zOut[4];
5997060173
if( SQLITE_OK==(rc = sqlite3OsRead(pJrnl, zOut, len, szJ-16-len)) ){
5997160174
u32 u; /* Unsigned loop counter */
5997260175
/* See if the checksum matches the super-journal name */
5997360176
for(u=0; u<len; u++){
5997460177
cksum -= zOut[u];
5997560178
}
5997660179
}
59977
- if( rc!=SQLITE_OK || cksum ){
59978
- /* If the checksum doesn't add up, then one or more of the disk sectors
59979
- ** containing the super-journal filename is corrupted. This means
59980
- ** definitely roll back, so just return SQLITE_OK and report a (nul)
59981
- ** super-journal filename. */
60180
+ if( rc!=SQLITE_OK /* Couldn't read the name */
60181
+ || !pagerIsSuperJrnlName(zOut) /* Name is not valid */
60182
+ || cksum /* checksum is incorrect */
60183
+ || memcmp(aMagic, aJournalMagic, 8)!=0 /* Bad magic number */
60184
+ ){
60185
+ /* If any validity checks fail, that means the super-journal filename
60186
+ ** is corrupted, so rollback. Return SQLITE_K and a NULL super-journal
60187
+ ** name */
5998260188
freeSuperJournal(zOut);
5998360189
zOut = 0;
5998460190
}
5998560191
}
5998660192
@@ -60359,10 +60565,11 @@
6035960565
i64 jrnlSize; /* Size of journal file on disk */
6036060566
u32 cksum = 0; /* Checksum of string zSuper */
6036160567
6036260568
assert( pPager->setSuper==0 );
6036360569
assert( !pagerUseWal(pPager) );
60570
+ assert( zSuper==0 || pagerIsSuperJrnlName(zSuper) );
6036460571
6036560572
if( !zSuper
6036660573
|| pPager->journalMode==PAGER_JOURNALMODE_MEMORY
6036760574
|| !isOpen(pPager->jfd)
6036860575
){
@@ -61189,10 +61396,23 @@
6118961396
sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
6119061397
char *zSuperJournal = 0; /* Contents of super-journal file */
6119161398
i64 nSuperJournal; /* Size of super-journal file */
6119261399
char *zJournal; /* Pointer to one journal within MJ file */
6119361400
char *zFree = 0; /* Free this buffer */
61401
+ int bSeen = 0; /* If super-journal contains pPager->zJournal */
61402
+
61403
+ /* Check if this looks like a real super-journal name. If it does not,
61404
+ ** return SQLITE_OK without attempting to delete it. This is to limit
61405
+ ** the degree to which a crafted journal file can be used to cause
61406
+ ** SQLite to delete arbitrary files.
61407
+ **
61408
+ ** This test never fails, becaue the super journal name is checked
61409
+ ** by readSuperJournal().
61410
+ */
61411
+ if( NEVER(pagerIsSuperJrnlName(zSuper)==0) ){
61412
+ return SQLITE_OK;
61413
+ }
6119461414
6119561415
/* Allocate space for both the pJournal and pSuper file descriptors.
6119661416
** If successful, open the super-journal file for reading.
6119761417
*/
6119861418
pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
@@ -61228,51 +61448,60 @@
6122861448
zSuperJournal[nSuperJournal] = 0;
6122961449
zSuperJournal[nSuperJournal+1] = 0;
6123061450
6123161451
zJournal = zSuperJournal;
6123261452
while( (zJournal-zSuperJournal)<nSuperJournal ){
61233
- int exists;
61234
- rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
61235
- if( rc!=SQLITE_OK ){
61236
- goto delsuper_out;
61237
- }
61238
- if( exists ){
61239
- char *zSuperPtr = 0;
61240
-
61241
- /* One of the journals pointed to by the super-journal exists.
61242
- ** Open it and check if it points at the super-journal. If
61243
- ** so, return without deleting the super-journal file.
61244
- ** NB: zJournal is really a MAIN_JOURNAL. But call it a
61245
- ** SUPER_JOURNAL here so that the VFS will not send the zJournal
61246
- ** name into sqlite3_database_file_object().
61247
- */
61248
- int c;
61249
- int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
61250
- rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
61251
- if( rc!=SQLITE_OK ){
61252
- goto delsuper_out;
61253
- }
61254
-
61255
- rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr);
61256
- sqlite3OsClose(pJournal);
61257
- if( rc!=SQLITE_OK ){
61258
- assert( zSuperPtr==0 );
61259
- goto delsuper_out;
61260
- }
61261
-
61262
- c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0;
61263
- freeSuperJournal(zSuperPtr);
61264
- if( c ){
61265
- /* We have a match. Do not delete the super-journal file. */
61266
- goto delsuper_out;
61453
+ if( strcmp(zJournal, pPager->zJournal)==0 ){
61454
+ bSeen = 1;
61455
+ }else{
61456
+ int exists;
61457
+ rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
61458
+ if( rc!=SQLITE_OK ){
61459
+ goto delsuper_out;
61460
+ }
61461
+ if( exists ){
61462
+ char *zSuperPtr = 0;
61463
+
61464
+ /* One of the journals pointed to by the super-journal exists.
61465
+ ** Open it and check if it points at the super-journal. If
61466
+ ** so, return without deleting the super-journal file.
61467
+ ** NB: zJournal is really a MAIN_JOURNAL. But call it a
61468
+ ** SUPER_JOURNAL here so that the VFS will not send the zJournal
61469
+ ** name into sqlite3_database_file_object().
61470
+ */
61471
+ int c;
61472
+ int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
61473
+ rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
61474
+ if( rc!=SQLITE_OK ){
61475
+ goto delsuper_out;
61476
+ }
61477
+
61478
+ rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr);
61479
+ sqlite3OsClose(pJournal);
61480
+ if( rc!=SQLITE_OK ){
61481
+ assert( zSuperPtr==0 );
61482
+ goto delsuper_out;
61483
+ }
61484
+
61485
+ c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0;
61486
+ freeSuperJournal(zSuperPtr);
61487
+ if( c ){
61488
+ /* We have a match. Do not delete the super-journal file. */
61489
+ goto delsuper_out;
61490
+ }
6126761491
}
6126861492
}
6126961493
zJournal += (sqlite3Strlen30(zJournal)+1);
6127061494
}
6127161495
6127261496
sqlite3OsClose(pSuper);
61273
- rc = sqlite3OsDelete(pVfs, zSuper, 0);
61497
+ if( bSeen ){
61498
+ /* Only delete the super-journal if bSeen is true - indicating that
61499
+ ** the super-journal contained a pointer to this database's journal
61500
+ ** file. */
61501
+ rc = sqlite3OsDelete(pVfs, zSuper, 0);
61502
+ }
6127461503
6127561504
delsuper_out:
6127661505
sqlite3_free(zFree);
6127761506
if( pSuper ){
6127861507
sqlite3OsClose(pSuper);
@@ -71674,10 +71903,13 @@
7167471903
int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
7167571904
** Error code if eState==CURSOR_FAULT */
7167671905
Btree *pBtree; /* The Btree to which this cursor belongs */
7167771906
Pgno *aOverflow; /* Cache of overflow page locations */
7167871907
void *pKey; /* Saved key that was cursor last known position */
71908
+#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
71909
+ BtCursor *pCursorHintTableCursor;
71910
+#endif
7167971911
/* All fields above are zeroed when the cursor is allocated. See
7168071912
** sqlite3BtreeCursorZero(). Fields that follow must be manually
7168171913
** initialized. */
7168271914
#define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
7168371915
BtShared *pBt; /* The BtShared this cursor points to */
@@ -71850,10 +72082,13 @@
7185072082
int v2; /* Value for third %d substitution in zPfx */
7185172083
StrAccum errMsg; /* Accumulate the error message text here */
7185272084
u32 *heap; /* Min-heap used for analyzing cell coverage */
7185372085
sqlite3 *db; /* Database connection running the check */
7185472086
i64 nRow; /* Number of rows visited in current tree */
72087
+#ifdef SQLITE_DEBUG
72088
+ u32 mxHeap; /* Maximum number of entries in the Min-heap */
72089
+#endif
7185572090
};
7185672091
7185772092
/*
7185872093
** Routines to read or write a two- and four-byte big-endian integer values.
7185972094
*/
@@ -73178,28 +73413,45 @@
7317873413
** parameter. See the definitions of the BTREE_HINT_* macros for details.
7317973414
*/
7318073415
SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
7318173416
/* Used only by system that substitute their own storage engine */
7318273417
#ifdef SQLITE_DEBUG
73183
- if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){
73184
- va_list ap;
73418
+ va_list ap;
73419
+ va_start(ap, eHintType);
73420
+ if( eHintType==BTREE_HINT_RANGE ){
7318573421
Expr *pExpr;
7318673422
Walker w;
7318773423
memset(&w, 0, sizeof(w));
7318873424
w.xExprCallback = sqlite3CursorRangeHintExprCheck;
73189
- va_start(ap, eHintType);
7319073425
pExpr = va_arg(ap, Expr*);
7319173426
w.u.aMem = va_arg(ap, Mem*);
73192
- va_end(ap);
7319373427
assert( pExpr!=0 );
7319473428
assert( w.u.aMem!=0 );
7319573429
sqlite3WalkExpr(&w, pExpr);
73430
+ }else if( ALWAYS(eHintType==BTREE_HINT_TABLECURSOR) ){
73431
+ BtCursor *pCsr = va_arg(ap, BtCursor*);
73432
+ assert( pCur->pCursorHintTableCursor==0
73433
+ || pCur->pCursorHintTableCursor==pCsr
73434
+ );
73435
+ assert( pCsr->pKeyInfo==0 || CORRUPT_DB );
73436
+ pCur->pCursorHintTableCursor = pCsr;
7319673437
}
73438
+ va_end(ap);
7319773439
#endif /* SQLITE_DEBUG */
7319873440
}
7319973441
#endif /* SQLITE_ENABLE_CURSOR_HINTS */
7320073442
73443
+#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
73444
+/*
73445
+** Return the pointer configured via the BTREE_HINT_TABLECURSOR hint on
73446
+** cursor pCsr. This is used from OP_DeferredSeek to assert() that the
73447
+** index cursor has been correctly configured with the table cursor.
73448
+*/
73449
+SQLITE_PRIVATE BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor *pCsr){
73450
+ return pCsr->pCursorHintTableCursor;
73451
+}
73452
+#endif
7320173453
7320273454
/*
7320373455
** Provide flag hints to the cursor.
7320473456
*/
7320573457
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
@@ -74321,12 +74573,19 @@
7432174573
/* Freeblock off the end of the page */
7432274574
return SQLITE_CORRUPT_PAGE(pPage);
7432374575
}
7432474576
next = get2byte(&data[pc]);
7432574577
size = get2byte(&data[pc+2]);
74578
+ if( size<4 && sqlite3FaultSim(422)==SQLITE_OK ){
74579
+ /* Minimum freeblock size is 4. Enable fault-sim 422 to disable this
74580
+ ** check to reach interesting error stats. However, disabling this
74581
+ ** check can cause assertion faults due to min-heap overflow. All
74582
+ ** fault-sims are for testing use only, but this one especially so. */
74583
+ return SQLITE_CORRUPT_PAGE(pPage);
74584
+ }
7432674585
nFree = nFree + size;
74327
- if( next<=pc+size+3 ) break;
74586
+ if( next<pc+size+4 ) break;
7432874587
pc = next;
7432974588
}
7433074589
if( next>0 ){
7433174590
/* Freeblock not in ascending order */
7433274591
return SQLITE_CORRUPT_PAGE(pPage);
@@ -78157,18 +78416,18 @@
7815778416
nCell = pCell[0];
7815878417
if( nCell<=pPage->max1bytePayload ){
7815978418
/* This branch runs if the record-size field of the cell is a
7816078419
** single byte varint and the record fits entirely on the main
7816178420
** b-tree page. */
78162
- testcase( pCell+nCell+1==pPage->aDataEnd );
78421
+ if( pCell + nCell >= pPage->aDataEnd ) return 99;
7816378422
c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
7816478423
}else if( !(pCell[1] & 0x80)
7816578424
&& (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
7816678425
){
7816778426
/* The record-size field is a 2 byte varint and the record
7816878427
** fits entirely on the main b-tree page. */
78169
- testcase( pCell+nCell+2==pPage->aDataEnd );
78428
+ if( pCell + nCell >= pPage->aDataEnd ) return 99;
7817078429
c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
7817178430
}else{
7817278431
/* If the record extends into overflow pages, do not attempt
7817378432
** the optimization. */
7817478433
c = 99;
@@ -78326,18 +78585,21 @@
7832678585
nCell = pCell[0];
7832778586
if( nCell<=pPage->max1bytePayload ){
7832878587
/* This branch runs if the record-size field of the cell is a
7832978588
** single byte varint and the record fits entirely on the main
7833078589
** b-tree page. */
78331
- testcase( pCell+nCell+1==pPage->aDataEnd );
78590
+ if( pCell + nCell >= pPage->aDataEnd ){
78591
+ rc = SQLITE_CORRUPT_PAGE(pPage);
78592
+ goto moveto_index_finish;
78593
+ }
7833278594
c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
7833378595
}else if( !(pCell[1] & 0x80)
7833478596
&& (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
78597
+ && pCell + nCell < pPage->aDataEnd
7833578598
){
7833678599
/* The record-size field is a 2 byte varint and the record
7833778600
** fits entirely on the main b-tree page. */
78338
- testcase( pCell+nCell+2==pPage->aDataEnd );
7833978601
c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
7834078602
}else{
7834178603
/* The record flows over onto one or more overflow pages. In
7834278604
** this case the whole cell needs to be parsed, a buffer allocated
7834378605
** and accessPayload() used to retrieve the record into the
@@ -83203,10 +83465,11 @@
8320383465
checkAppendMsg(pCheck, "Child page depth differs");
8320483466
depth = d2;
8320583467
}
8320683468
}else{
8320783469
/* Populate the coverage-checking heap for leaf pages */
83470
+ assert( heap!=0 && heap[0] < pCheck->mxHeap );
8320883471
btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
8320983472
}
8321083473
}
8321183474
*piMinKey = maxKey;
8321283475
@@ -83222,10 +83485,11 @@
8322283485
heap[0] = 0;
8322383486
for(i=nCell-1; i>=0; i--){
8322483487
u32 size;
8322583488
pc = get2byteAligned(&data[cellStart+i*2]);
8322683489
size = pPage->xCellSize(pPage, &data[pc]);
83490
+ assert( heap!=0 && heap[0] < pCheck->mxHeap );
8322783491
btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
8322883492
}
8322983493
}
8323083494
assert( heap!=0 );
8323183495
/* Add the freeblocks to the min-heap
@@ -83238,10 +83502,11 @@
8323883502
while( i>0 ){
8323983503
int size, j;
8324083504
assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
8324183505
size = get2byte(&data[i+2]);
8324283506
assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
83507
+ assert( heap!=0 && heap[0] < pCheck->mxHeap );
8324383508
btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
8324483509
/* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
8324583510
** big-endian integer which is the offset in the b-tree page of the next
8324683511
** freeblock in the chain, or zero if the freeblock is the last on the
8324783512
** chain. */
@@ -83372,10 +83637,13 @@
8337283637
if( !sCheck.aPgRef ){
8337383638
checkOom(&sCheck);
8337483639
goto integrity_ck_cleanup;
8337583640
}
8337683641
sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
83642
+#ifdef SQLITE_DEBUG
83643
+ sCheck.mxHeap = pBt->pageSize/4 - 1;
83644
+#endif
8337783645
if( sCheck.heap==0 ){
8337883646
checkOom(&sCheck);
8337983647
goto integrity_ck_cleanup;
8338083648
}
8338183649
@@ -83796,17 +84064,18 @@
8379684064
/*
8379784065
** Structure allocated for each backup operation.
8379884066
*/
8379984067
struct sqlite3_backup {
8380084068
sqlite3* pDestDb; /* Destination database handle */
83801
- Db *pDest; /* Destination db file */
84069
+ char *zDestDb;
84070
+ Btree *pDest; /* Destination b-tree file */
8380284071
u32 iDestSchema; /* Original schema cookie in destination */
8380384072
int bDestLocked; /* True once a write-transaction is open on pDest */
8380484073
8380584074
Pgno iNext; /* Page number of the next source page to copy */
8380684075
sqlite3* pSrcDb; /* Source database handle */
83807
- Db *pSrc; /* Source db file */
84076
+ Btree *pSrc; /* Source b-tree file */
8380884077
8380984078
int rc; /* Backup process error code */
8381084079
8381184080
/* These two variables are set by every call to backup_step(). They are
8381284081
** read by calls to backup_remaining() and backup_pagecount().
@@ -83855,13 +84124,15 @@
8385584124
**
8385684125
** If the "temp" database is requested, it may need to be opened by this
8385784126
** function. If an error occurs while doing so, return 0 and write an
8385884127
** error message to pErrorDb.
8385984128
*/
83860
-static Db *findDatabase(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
83861
- int i = sqlite3FindDbName(pDb, zDb);
84129
+static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
84130
+ int i;
8386284131
84132
+ assert( pDb!=0 );
84133
+ i = sqlite3FindDbName(pDb, zDb);
8386384134
if( i==1 ){
8386484135
Parse sParse;
8386584136
int rc = 0;
8386684137
sqlite3ParseObjectInit(&sParse,pDb);
8386784138
if( sqlite3OpenTempDatabase(&sParse) ){
@@ -83878,21 +84149,19 @@
8387884149
if( i<0 ){
8387984150
sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
8388084151
return 0;
8388184152
}
8388284153
83883
- return &pDb->aDb[i];
84154
+ return pDb->aDb[i].pBt;
8388484155
}
8388584156
8388684157
/*
8388784158
** Attempt to set the page size of the destination to match the page size
8388884159
** of the source.
8388984160
*/
83890
-static int setDestPgsz(sqlite3_backup *p){
83891
- return sqlite3BtreeSetPageSize(p->pDest->pBt,
83892
- sqlite3BtreeGetPageSize(p->pSrc->pBt), 0, 0
83893
- );
84161
+static int setDestPgsz(Btree *pDest, Btree *pSrc){
84162
+ return sqlite3BtreeSetPageSize(pDest, sqlite3BtreeGetPageSize(pSrc), 0, 0);
8389484163
}
8389584164
8389684165
/*
8389784166
** Check that there is no open read-transaction on the b-tree passed as the
8389884167
** second argument. If there is not, return SQLITE_OK. Otherwise, if there
@@ -83945,31 +84214,41 @@
8394584214
sqlite3ErrorWithMsg(
8394684215
pDestDb, SQLITE_ERROR, "source and destination must be distinct"
8394784216
);
8394884217
p = 0;
8394984218
}else {
84219
+ int nDest = sqlite3Strlen30(zDestDb);
84220
+
8395084221
/* Allocate space for a new sqlite3_backup object...
8395184222
** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
8395284223
** call to sqlite3_backup_init() and is destroyed by a call to
8395384224
** sqlite3_backup_finish(). */
83954
- p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
84225
+ p = (sqlite3_backup*)sqlite3MallocZero(sizeof(sqlite3_backup)+nDest+1);
8395584226
if( !p ){
8395684227
sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
84228
+ }else{
84229
+ p->zDestDb = (char*)&p[1];
84230
+ memcpy(p->zDestDb, zDestDb, nDest);
8395784231
}
8395884232
}
8395984233
8396084234
/* If the allocation succeeded, populate the new object. */
8396184235
if( p ){
83962
- p->pSrc = findDatabase(pDestDb, pSrcDb, zSrcDb);
83963
- p->pDest = findDatabase(pDestDb, pDestDb, zDestDb);
84236
+ /* Do not store the pointer to the destination b-tree at this point.
84237
+ ** This is because there is nothing preventing it from being detached
84238
+ ** or otherwise freed before the first call to sqlite3_backup_step()
84239
+ ** on this object. The source b-tree does not have this problem, as
84240
+ ** incrementing Btree.nBackup (see below) effectively locks the object. */
84241
+ Btree *pDest = findBtree(pDestDb, pDestDb, zDestDb);
84242
+ p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
8396484243
p->pDestDb = pDestDb;
8396584244
p->pSrcDb = pSrcDb;
8396684245
p->iNext = 1;
8396784246
p->isAttached = 0;
8396884247
83969
- if( 0==p->pSrc || 0==p->pDest
83970
- || checkReadTransaction(pDestDb, p->pDest->pBt)!=SQLITE_OK
84248
+ if( 0==p->pSrc || 0==pDest
84249
+ || checkReadTransaction(pDestDb, pDest)!=SQLITE_OK
8397184250
){
8397284251
/* One (or both) of the named databases did not exist or an OOM
8397384252
** error was hit. Or there is a transaction open on the destination
8397484253
** database. The error has already been written into the pDestDb
8397584254
** handle. All that is left to do here is free the sqlite3_backup
@@ -83977,11 +84256,11 @@
8397784256
sqlite3_free(p);
8397884257
p = 0;
8397984258
}
8398084259
}
8398184260
if( p ){
83982
- p->pSrc->pBt->nBackup++;
84261
+ p->pSrc->nBackup++;
8398384262
}
8398484263
8398584264
sqlite3_mutex_leave(pDestDb->mutex);
8398684265
sqlite3_mutex_leave(pSrcDb->mutex);
8398784266
return p;
@@ -84005,22 +84284,22 @@
8400584284
sqlite3_backup *p, /* Backup handle */
8400684285
Pgno iSrcPg, /* Source database page to backup */
8400784286
const u8 *zSrcData, /* Source database page data */
8400884287
int bUpdate /* True for an update, false otherwise */
8400984288
){
84010
- Pager * const pDestPager = sqlite3BtreePager(p->pDest->pBt);
84011
- const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc->pBt);
84012
- int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest->pBt);
84289
+ Pager * const pDestPager = sqlite3BtreePager(p->pDest);
84290
+ const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
84291
+ int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
8401384292
const int nCopy = MIN(nSrcPgsz, nDestPgsz);
8401484293
const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
8401584294
int rc = SQLITE_OK;
8401684295
i64 iOff;
8401784296
84018
- assert( sqlite3BtreeGetReserveNoMutex(p->pSrc->pBt)>=0 );
84297
+ assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
8401984298
assert( p->bDestLocked );
8402084299
assert( !isFatalError(p->rc) );
84021
- assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt->pBt) );
84300
+ assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
8402284301
assert( zSrcData );
8402384302
assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 );
8402484303
8402584304
/* This loop runs once for each destination page spanned by the source
8402684305
** page. For each iteration, variable iOff is set to the byte offset
@@ -84027,11 +84306,11 @@
8402784306
** of the destination page.
8402884307
*/
8402984308
for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
8403084309
DbPage *pDestPg = 0;
8403184310
Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
84032
- if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt->pBt) ) continue;
84311
+ if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
8403384312
if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
8403484313
&& SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
8403584314
){
8403684315
const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
8403784316
u8 *zDestData = sqlite3PagerGetData(pDestPg);
@@ -84045,11 +84324,11 @@
8404584324
** "MUST BE FIRST" for this purpose.
8404684325
*/
8404784326
memcpy(zOut, zIn, nCopy);
8404884327
((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
8404984328
if( iOff==0 && bUpdate==0 ){
84050
- sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc->pBt));
84329
+ sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
8405184330
}
8405284331
}
8405384332
sqlite3PagerUnref(pDestPg);
8405484333
}
8405584334
@@ -84077,12 +84356,12 @@
8407784356
** Register this backup object with the associated source pager for
8407884357
** callbacks when pages are changed or the cache invalidated.
8407984358
*/
8408084359
static void attachBackupObject(sqlite3_backup *p){
8408184360
sqlite3_backup **pp;
84082
- assert( sqlite3BtreeHoldsMutex(p->pSrc->pBt) );
84083
- pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc->pBt));
84361
+ assert( sqlite3BtreeHoldsMutex(p->pSrc) );
84362
+ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
8408484363
p->pNext = *pp;
8408584364
*pp = p;
8408684365
p->isAttached = 1;
8408784366
}
8408884367
@@ -84089,93 +84368,103 @@
8408984368
/*
8409084369
** Copy nPage pages from the source b-tree to the destination.
8409184370
*/
8409284371
SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
8409384372
int rc;
84094
- int destMode; /* Destination journal mode */
84373
+ int destMode = 0; /* Destination journal mode */
8409584374
int pgszSrc = 0; /* Source page size */
8409684375
int pgszDest = 0; /* Destination page size */
84097
- Btree *pDest;
84098
- Btree *pSrc;
8409984376
8410084377
#ifdef SQLITE_ENABLE_API_ARMOR
8410184378
if( p==0 ) return SQLITE_MISUSE_BKPT;
8410284379
#endif
84103
- assert( p->pDest );
84104
- assert( p->pSrc );
84105
- pDest = p->pDest->pBt;
84106
- pSrc = p->pSrc->pBt;
8410784380
sqlite3_mutex_enter(p->pSrcDb->mutex);
84108
- sqlite3BtreeEnter(pSrc);
84381
+ sqlite3BtreeEnter(p->pSrc);
8410984382
if( p->pDestDb ){
8411084383
sqlite3_mutex_enter(p->pDestDb->mutex);
8411184384
}
8411284385
8411384386
rc = p->rc;
8411484387
if( !isFatalError(rc) ){
84115
- Pager * const pSrcPager = sqlite3BtreePager(pSrc); /* Source pager */
84116
- Pager * const pDestPager = sqlite3BtreePager(pDest); /* Dest pager */
84388
+ Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
84389
+ Btree * pDest = 0; /* Dest btree */
84390
+ Pager * pDestPager = 0; /* Dest pager */
8411784391
int ii; /* Iterator variable */
8411884392
int nSrcPage = -1; /* Size of source db in pages */
8411984393
int bCloseTrans = 0; /* True if src db requires unlocking */
8412084394
8412184395
/* If the source pager is currently in a write-transaction, return
8412284396
** SQLITE_BUSY immediately.
8412384397
*/
84124
- if( p->pDestDb && pSrc->pBt->inTransaction==TRANS_WRITE ){
84398
+ if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
8412584399
rc = SQLITE_BUSY;
8412684400
}else{
8412784401
rc = SQLITE_OK;
8412884402
}
84403
+
8412984404
8413084405
/* If there is no open read-transaction on the source database, open
8413184406
** one now. If a transaction is opened here, then it will be closed
8413284407
** before this function exits.
8413384408
*/
84134
- if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(pSrc) ){
84135
- rc = sqlite3BtreeBeginTrans(pSrc, 0, 0);
84409
+ if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
84410
+ rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
8413684411
bCloseTrans = 1;
8413784412
}
84413
+
84414
+ /* Locate the destination btree and pager. */
84415
+ if( (pDest = p->pDest)==0 ){
84416
+ pDest = findBtree(p->pDestDb, p->pDestDb, p->zDestDb);
84417
+ }
84418
+ if( pDest==0 ){
84419
+ rc = SQLITE_ERROR;
84420
+ }else{
84421
+ pDestPager = sqlite3BtreePager(pDest);
84422
+ }
8413884423
8413984424
/* If the destination database has not yet been locked (i.e. if this
8414084425
** is the first call to backup_step() for the current backup operation),
8414184426
** try to set its page size to the same as the source database. This
8414284427
** is especially important on ZipVFS systems, as in that case it is
8414384428
** not possible to create a database file that uses one page size by
8414484429
** writing to it with another. */
84145
- if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
84430
+ if( p->bDestLocked==0 && rc==SQLITE_OK
84431
+ && setDestPgsz(pDest, p->pSrc)==SQLITE_NOMEM
84432
+ ){
8414684433
rc = SQLITE_NOMEM;
8414784434
}
8414884435
8414984436
/* Lock the destination database, if it is not locked already. */
8415084437
if( SQLITE_OK==rc && p->bDestLocked==0
8415184438
&& SQLITE_OK==(rc = sqlite3BtreeBeginTrans(pDest, 2,
8415284439
(int*)&p->iDestSchema))
8415384440
){
8415484441
p->bDestLocked = 1;
84442
+ p->pDest = pDest;
8415584443
}
8415684444
8415784445
/* Do not allow backup if the destination database is in WAL mode
8415884446
** and the page sizes are different between source and destination */
84159
- pgszSrc = sqlite3BtreeGetPageSize(pSrc);
84160
- pgszDest = sqlite3BtreeGetPageSize(pDest);
84161
- destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(pDest));
84162
- if( SQLITE_OK==rc
84163
- && (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
84164
- && pgszSrc!=pgszDest
84165
- ){
84166
- rc = SQLITE_READONLY;
84447
+ if( rc==SQLITE_OK ){
84448
+ pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
84449
+ pgszDest = sqlite3BtreeGetPageSize(p->pDest);
84450
+ destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
84451
+ if( (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
84452
+ && pgszSrc!=pgszDest
84453
+ ){
84454
+ rc = SQLITE_READONLY;
84455
+ }
8416784456
}
8416884457
8416984458
/* Now that there is a read-lock on the source database, query the
8417084459
** source pager for the number of pages in the database.
8417184460
*/
84172
- nSrcPage = (int)sqlite3BtreeLastPage(pSrc);
84461
+ nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
8417384462
assert( nSrcPage>=0 );
8417484463
for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
8417584464
const Pgno iSrcPg = p->iNext; /* Source page number */
84176
- if( iSrcPg!=PENDING_BYTE_PAGE(pSrc->pBt) ){
84465
+ if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
8417784466
DbPage *pSrcPg; /* Source page object */
8417884467
rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
8417984468
if( rc==SQLITE_OK ){
8418084469
rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
8418184470
sqlite3PagerUnref(pSrcPg);
@@ -84198,22 +84487,22 @@
8419884487
** the case where the source and destination databases have the
8419984488
** same schema version.
8420084489
*/
8420184490
if( rc==SQLITE_DONE ){
8420284491
if( nSrcPage==0 ){
84203
- rc = sqlite3BtreeNewDb(pDest);
84492
+ rc = sqlite3BtreeNewDb(p->pDest);
8420484493
nSrcPage = 1;
8420584494
}
8420684495
if( rc==SQLITE_OK || rc==SQLITE_DONE ){
84207
- rc = sqlite3BtreeUpdateMeta(pDest,1,p->iDestSchema+1);
84496
+ rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
8420884497
}
8420984498
if( rc==SQLITE_OK ){
8421084499
if( p->pDestDb ){
8421184500
sqlite3ResetAllSchemasOfConnection(p->pDestDb);
8421284501
}
8421384502
if( destMode==PAGER_JOURNALMODE_WAL ){
84214
- rc = sqlite3BtreeSetVersion(pDest, 2);
84503
+ rc = sqlite3BtreeSetVersion(p->pDest, 2);
8421584504
}
8421684505
}
8421784506
if( rc==SQLITE_OK ){
8421884507
int nDestTruncate;
8421984508
/* Set nDestTruncate to the final number of pages in the destination
@@ -84226,16 +84515,16 @@
8422684515
** sqlite3PagerTruncateImage() here so that any pages in the
8422784516
** destination file that lie beyond the nDestTruncate page mark are
8422884517
** journalled by PagerCommitPhaseOne() before they are destroyed
8422984518
** by the file truncation.
8423084519
*/
84231
- assert( pgszSrc==sqlite3BtreeGetPageSize(pSrc) );
84232
- assert( pgszDest==sqlite3BtreeGetPageSize(pDest) );
84520
+ assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
84521
+ assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
8423384522
if( pgszSrc<pgszDest ){
8423484523
int ratio = pgszDest/pgszSrc;
8423584524
nDestTruncate = (nSrcPage+ratio-1)/ratio;
84236
- if( nDestTruncate==(int)PENDING_BYTE_PAGE(pDest->pBt) ){
84525
+ if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
8423784526
nDestTruncate--;
8423884527
}
8423984528
}else{
8424084529
nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
8424184530
}
@@ -84259,11 +84548,11 @@
8425984548
i64 iEnd;
8426084549
8426184550
assert( pFile );
8426284551
assert( nDestTruncate==0
8426384552
|| (i64)nDestTruncate*(i64)pgszDest >= iSize || (
84264
- nDestTruncate==(int)(PENDING_BYTE_PAGE(pDest->pBt)-1)
84553
+ nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
8426584554
&& iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
8426684555
));
8426784556
8426884557
/* This block ensures that all data required to recreate the original
8426984558
** database has been stored in the journal for pDestPager and the
@@ -84271,11 +84560,11 @@
8427184560
** the database file in any way, knowing that if a power failure
8427284561
** occurs, the original database will be reconstructed from the
8427384562
** journal file. */
8427484563
sqlite3PagerPagecount(pDestPager, &nDstPage);
8427584564
for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
84276
- if( iPg!=PENDING_BYTE_PAGE(pDest->pBt) ){
84565
+ if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
8427784566
DbPage *pPg;
8427884567
rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
8427984568
if( rc==SQLITE_OK ){
8428084569
rc = sqlite3PagerWrite(pPg);
8428184570
sqlite3PagerUnref(pPg);
@@ -84315,11 +84604,11 @@
8431584604
rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
8431684605
}
8431784606
8431884607
/* Finish committing the transaction to the destination database. */
8431984608
if( SQLITE_OK==rc
84320
- && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(pDest, 0))
84609
+ && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
8432184610
){
8432284611
rc = SQLITE_DONE;
8432384612
}
8432484613
}
8432584614
}
@@ -84329,12 +84618,12 @@
8432984618
** no need to check the return values of the btree methods here, as
8433084619
** "committing" a read-only transaction cannot fail.
8433184620
*/
8433284621
if( bCloseTrans ){
8433384622
TESTONLY( int rc2 );
84334
- TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(pSrc, 0);
84335
- TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(pSrc, 0);
84623
+ TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
84624
+ TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
8433684625
assert( rc2==SQLITE_OK );
8433784626
}
8433884627
8433984628
if( rc==SQLITE_IOERR_NOMEM ){
8434084629
rc = SQLITE_NOMEM_BKPT;
@@ -84342,11 +84631,11 @@
8434284631
p->rc = rc;
8434384632
}
8434484633
if( p->pDestDb ){
8434584634
sqlite3_mutex_leave(p->pDestDb->mutex);
8434684635
}
84347
- sqlite3BtreeLeave(pSrc);
84636
+ sqlite3BtreeLeave(p->pSrc);
8434884637
sqlite3_mutex_leave(p->pSrcDb->mutex);
8434984638
return rc;
8435084639
}
8435184640
8435284641
/*
@@ -84359,41 +84648,43 @@
8435984648
8436084649
/* Enter the mutexes */
8436184650
if( p==0 ) return SQLITE_OK;
8436284651
pSrcDb = p->pSrcDb;
8436384652
sqlite3_mutex_enter(pSrcDb->mutex);
84364
- sqlite3BtreeEnter(p->pSrc->pBt);
84653
+ sqlite3BtreeEnter(p->pSrc);
8436584654
if( p->pDestDb ){
8436684655
sqlite3_mutex_enter(p->pDestDb->mutex);
8436784656
}
8436884657
8436984658
/* Detach this backup from the source pager. */
8437084659
if( p->pDestDb ){
84371
- p->pSrc->pBt->nBackup--;
84660
+ p->pSrc->nBackup--;
8437284661
}
8437384662
if( p->isAttached ){
84374
- pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc->pBt));
84663
+ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
8437584664
assert( pp!=0 );
8437684665
while( *pp!=p ){
8437784666
pp = &(*pp)->pNext;
8437884667
assert( pp!=0 );
8437984668
}
8438084669
*pp = p->pNext;
8438184670
}
8438284671
8438384672
/* If a transaction is still open on the Btree, roll it back. */
84384
- sqlite3BtreeRollback(p->pDest->pBt, SQLITE_OK, 0);
84673
+ if( p->pDest ){
84674
+ sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
84675
+ }
8438584676
8438684677
/* Set the error code of the destination database handle. */
8438784678
rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
8438884679
if( p->pDestDb ){
8438984680
sqlite3Error(p->pDestDb, rc);
8439084681
8439184682
/* Exit the mutexes and free the backup context structure. */
8439284683
sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
8439384684
}
84394
- sqlite3BtreeLeave(p->pSrc->pBt);
84685
+ sqlite3BtreeLeave(p->pSrc);
8439584686
if( p->pDestDb ){
8439684687
/* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
8439784688
** call to sqlite3_backup_init() and is destroyed by a call to
8439884689
** sqlite3_backup_finish(). */
8439984690
sqlite3_free(p);
@@ -84447,11 +84738,11 @@
8444784738
Pgno iPage,
8444884739
const u8 *aData
8444984740
){
8445084741
assert( p!=0 );
8445184742
do{
84452
- assert( sqlite3_mutex_held(p->pSrc->pBt->pBt->mutex) );
84743
+ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
8445384744
if( !isFatalError(p->rc) && iPage<p->iNext ){
8445484745
/* The backup process p has already copied page iPage. But now it
8445584746
** has been modified by a transaction on the source pager. Copy
8445684747
** the new data into the backup.
8445784748
*/
@@ -84483,11 +84774,11 @@
8448384774
** called.
8448484775
*/
8448584776
SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
8448684777
sqlite3_backup *p; /* Iterator variable */
8448784778
for(p=pBackup; p; p=p->pNext){
84488
- assert( sqlite3_mutex_held(p->pSrc->pBt->pBt->mutex) );
84779
+ assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
8448984780
p->iNext = 1;
8449084781
}
8449184782
}
8449284783
8449384784
#ifndef SQLITE_OMIT_VACUUM
@@ -84501,12 +84792,10 @@
8450184792
*/
8450284793
SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
8450384794
int rc;
8450484795
sqlite3_file *pFd; /* File descriptor for database pTo */
8450584796
sqlite3_backup b;
84506
- Db dbDest;
84507
- Db dbSrc;
8450884797
sqlite3BtreeEnter(pTo);
8450984798
sqlite3BtreeEnter(pFrom);
8451084799
8451184800
assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
8451284801
pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
@@ -84521,17 +84810,13 @@
8452184810
** to 0. This is used by the implementations of sqlite3_backup_step()
8452284811
** and sqlite3_backup_finish() to detect that they are being called
8452384812
** from this function, not directly by the user.
8452484813
*/
8452584814
memset(&b, 0, sizeof(b));
84526
- memset(&dbDest, 0, sizeof(dbDest));
84527
- memset(&dbSrc, 0, sizeof(dbSrc));
84528
- dbDest.pBt = pTo;
84529
- dbSrc.pBt = pFrom;
8453084815
b.pSrcDb = pFrom->db;
84531
- b.pSrc = &dbSrc;
84532
- b.pDest = &dbDest;
84816
+ b.pSrc = pFrom;
84817
+ b.pDest = pTo;
8453384818
b.iNext = 1;
8453484819
8453584820
/* 0x7FFFFFFF is the hard limit for the number of pages in a database
8453684821
** file. By passing this as the number of pages to copy to
8453784822
** sqlite3_backup_step(), we can guarantee that the copy finishes
@@ -84543,11 +84828,11 @@
8454384828
8454484829
rc = sqlite3_backup_finish(&b);
8454584830
if( rc==SQLITE_OK ){
8454684831
pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
8454784832
}else{
84548
- sqlite3PagerClearCache(sqlite3BtreePager(pTo));
84833
+ sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
8454984834
}
8455084835
8455184836
assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
8455284837
copy_finished:
8455384838
sqlite3BtreeLeave(pFrom);
@@ -86859,11 +87144,10 @@
8685987144
p->pParse = pParse;
8686087145
pParse->pVdbe = p;
8686187146
assert( pParse->aLabel==0 );
8686287147
assert( pParse->nLabel==0 );
8686387148
assert( p->nOpAlloc==0 );
86864
- assert( pParse->szOpAlloc==0 );
8686587149
sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
8686687150
return p;
8686787151
}
8686887152
8686987153
/*
@@ -87009,12 +87293,11 @@
8700987293
8701087294
assert( nOp<=(int)(1024/sizeof(Op)) );
8701187295
assert( nNew>=(v->nOpAlloc+nOp) );
8701287296
pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
8701387297
if( pNew ){
87014
- p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
87015
- v->nOpAlloc = p->szOpAlloc/sizeof(Op);
87298
+ v->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
8701687299
v->aOp = pNew;
8701787300
}
8701887301
return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
8701987302
}
8702087303
@@ -87445,11 +87728,11 @@
8744587728
** Resolve label "x" to be the address of the next instruction to
8744687729
** be inserted. The parameter "x" must have been obtained from
8744787730
** a prior call to sqlite3VdbeMakeLabel().
8744887731
*/
8744987732
static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
87450
- int nNewSize = 10 - p->nLabel;
87733
+ int nNewSize = 25 - p->nLabel;
8745187734
p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
8745287735
nNewSize*sizeof(p->aLabel[0]));
8745387736
if( p->aLabel==0 ){
8745487737
p->nLabelAlloc = 0;
8745587738
}else{
@@ -89513,11 +89796,11 @@
8951389796
** of the prepared statement.
8951489797
*/
8951589798
n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
8951689799
x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
8951789800
assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
89518
- x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
89801
+ x.nFree = ROUNDDOWN8((p->nOpAlloc-p->nOp)*sizeof(Op)); /* Bytes unused mem */
8951989802
assert( x.nFree>=0 );
8952089803
assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
8952189804
8952289805
resolveP2Values(p, &nArg);
8952389806
p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
@@ -92662,12 +92945,18 @@
9266292945
** that sqlite3_prepare() generates. For example, if new functions or
9266392946
** collating sequences are registered or if an authorizer function is
9266492947
** added or changed.
9266592948
*/
9266692949
SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
92667
- Vdbe *p = (Vdbe*)pStmt;
92668
- return p==0 || p->expired;
92950
+ int iRet = 1;
92951
+ if( pStmt ){
92952
+ Vdbe *p = (Vdbe*)pStmt;
92953
+ sqlite3_mutex_enter(p->db->mutex);
92954
+ iRet = p->expired;
92955
+ sqlite3_mutex_leave(p->db->mutex);
92956
+ }
92957
+ return iRet;
9266992958
}
9267092959
#endif
9267192960
9267292961
/*
9267392962
** Check on a Vdbe to make sure it has not been finalized. Log
@@ -93009,19 +93298,22 @@
9300993298
sqlite3ValueFree(pOld);
9301093299
}
9301193300
9301293301
9301393302
/**************************** sqlite3_result_ *******************************
93014
-** The following routines are used by user-defined functions to specify
93015
-** the function result.
93016
-**
93017
-** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
93018
-** result as a string or blob. Appropriate errors are set if the string/blob
93019
-** is too big or if an OOM occurs.
93020
-**
93021
-** The invokeValueDestructor(P,X) routine invokes destructor function X()
93022
-** on value P if P is not going to be used and need to be destroyed.
93303
+** The following routines are used by application-defined SQL functions to
93304
+** specify the function return value. There are many variations on
93305
+** sqlite3_result_xxxx() for different types of return values.
93306
+**
93307
+** The setStrOrError() function is a helper function that invokes
93308
+** sqlite3VdbeMemSetStr() to store the result as a string or blob.
93309
+** Appropriate errors are set if the string/blob is too big or if
93310
+** an OOM occurs.
93311
+**
93312
+** The invokeValueDestructor(P,X) helper function invokes the destructor
93313
+** function X() on value P if P is not going to be used and need to
93314
+** be destroyed.
9302393315
*/
9302493316
static void setResultStrOrError(
9302593317
sqlite3_context *pCtx, /* Function context */
9302693318
const char *z, /* String pointer */
9302793319
int n, /* Bytes in string, or negative */
@@ -93330,11 +93622,11 @@
9333093622
setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
9333193623
SQLITE_STATIC);
9333293624
}
9333393625
}
9333493626
93335
-/* Force an SQLITE_TOOBIG error. */
93627
+/* Cause the SQL function to raise an SQLITE_TOOBIG error. */
9333693628
SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
9333793629
#ifdef SQLITE_ENABLE_API_ARMOR
9333893630
if( pCtx==0 ) return;
9333993631
#endif
9334093632
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
@@ -93341,20 +93633,78 @@
9334193633
pCtx->isError = SQLITE_TOOBIG;
9334293634
sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
9334393635
SQLITE_UTF8, SQLITE_STATIC);
9334493636
}
9334593637
93346
-/* An SQLITE_NOMEM error. */
93638
+/* Cause the SQL function to raise an SQLITE_NOMEM error. */
9334793639
SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
9334893640
#ifdef SQLITE_ENABLE_API_ARMOR
9334993641
if( pCtx==0 ) return;
9335093642
#endif
9335193643
assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
9335293644
sqlite3VdbeMemSetNull(pCtx->pOut);
9335393645
pCtx->isError = SQLITE_NOMEM_BKPT;
9335493646
sqlite3OomFault(pCtx->pOut->db);
9335593647
}
93648
+
93649
+/* Make the return value of the SQL function or virtual table pCtx
93650
+** be the content of the sqlite3_str object pStr. The eOwn flag
93651
+** determines ownership of the sqlite3_str object and its content.
93652
+**
93653
+** eOwn Ownership transfer
93654
+** ------------- ------------------------------------------------
93655
+**
93656
+** SQLITE_COPY The SQL function returns a copy the sqlite3_str
93657
+** content and leaves the sqlite3_str object itself
93658
+** unchanged.
93659
+**
93660
+** SQLITE_XFER The content of the sqlite3_str is transferred to
93661
+** the SQL function and the SQL function takes
93662
+** responsibility for freeing that content when it is
93663
+** no longer needed. The sqlite3_str object is reset
93664
+** to an empty string.
93665
+**
93666
+** SQLITE_FINISH Like SQLITE_XFER except that the pStr is also
93667
+** freed using sqlite3_str_free().
93668
+*/
93669
+SQLITE_API void sqlite3_result_str(sqlite3_context *pCtx, sqlite3_str *pStr, int eOwn){
93670
+#ifdef SQLITE_ENABLE_API_ARMOR
93671
+ if( pCtx==0 ) return;
93672
+ if( pStr==0 ) return;
93673
+#endif
93674
+ testcase( pStr==(sqlite3_str*)&sqlite3OomStr );
93675
+ if( pStr->accError==0 ){
93676
+ if( pStr->nChar==0 ){
93677
+ setResultStrOrError(pCtx, "", 0, SQLITE_UTF8_ZT, SQLITE_STATIC);
93678
+ sqlite3_str_reset(pStr);
93679
+ }else{
93680
+ const char *zText = sqlite3_str_value(pStr);
93681
+ /* Only internal code has the ability to capture a pointer to
93682
+ ** an sqlite3_str object that uses static buffer. And none of
93683
+ ** those internal use cases every invoke the sqlite3_result_str()
93684
+ ** interface on a static-buffer sqlite3_str. Should this change
93685
+ ** in the future, the following assert() will let us know. */
93686
+ assert( isMalloced(pStr) );
93687
+ if( eOwn==SQLITE_COPY ){
93688
+ setResultStrOrError(pCtx, zText, pStr->nChar,
93689
+ SQLITE_UTF8, SQLITE_TRANSIENT);
93690
+ }else{
93691
+ setResultStrOrError(pCtx, zText, pStr->nChar,
93692
+ SQLITE_UTF8_ZT, SQLITE_DYNAMIC);
93693
+ sqlite3StrAccumInit(pStr, pStr->db, 0, 0, pStr->mxAlloc);
93694
+ }
93695
+ }
93696
+ }else if( pStr->accError==SQLITE_NOMEM ){
93697
+ sqlite3_result_error_nomem(pCtx);
93698
+ }else{
93699
+ assert( pStr->accError==SQLITE_TOOBIG );
93700
+ sqlite3_result_error_toobig(pCtx);
93701
+ }
93702
+ if( eOwn==SQLITE_FINISH ){
93703
+ sqlite3_str_free(pStr);
93704
+ }
93705
+}
9335693706
9335793707
#ifndef SQLITE_UNTESTABLE
9335893708
/* Force the INT64 value currently stored as the result to be
9335993709
** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
9336093710
** test-control.
@@ -96241,10 +96591,14 @@
9624196591
}
9624296592
9624396593
/*
9624496594
** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
9624596595
** with pOp->p3. Return the hash.
96596
+**
96597
+** IMPORTANT RESTRICTION (tag-202607231411): This hash is only valid if the
96598
+** collating sequence for TEXT is BINARY. Hence, Bloom filters that use this
96599
+** hash will not work for look-ups that use any other collating sequence.
9624696600
*/
9624796601
static u64 filterHash(const Mem *aMem, const Op *pOp){
9624896602
int i, mx;
9624996603
u64 h = 0;
9625096604
@@ -96253,15 +96607,32 @@
9625396607
const Mem *p = &aMem[i];
9625496608
if( p->flags & (MEM_Int|MEM_IntReal) ){
9625596609
h += p->u.i;
9625696610
}else if( p->flags & MEM_Real ){
9625796611
h += sqlite3VdbeIntValue(p);
96258
- }else if( p->flags & (MEM_Str|MEM_Blob) ){
96259
- /* All strings have the same hash and all blobs have the same hash,
96260
- ** though, at least, those hashes are different from each other and
96261
- ** from NULL. */
96262
- h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
96612
+ }else if( p->flags & MEM_Str ){
96613
+ u64 x;
96614
+ h += p->n;
96615
+ if( p->n >= sizeof(x) ){
96616
+ memcpy(&x, p->z, sizeof(x));
96617
+ h += x;
96618
+ memcpy(&x, p->z + p->n - sizeof(x), sizeof(x));
96619
+ h += x;
96620
+ }else{
96621
+ x = 0;
96622
+ memcpy(&x, p->z, p->n);
96623
+ h += x;
96624
+ }
96625
+ }else if( p->flags & MEM_Blob ){
96626
+ int n = p->n;
96627
+ u64 x = 0;
96628
+ if( n ){
96629
+ memcpy(&x, p->z, MIN(n, sizeof(x)));
96630
+ h += x;
96631
+ }
96632
+ h += n;
96633
+ if( p->flags & MEM_Zero ) h += p->u.nZero;
9626396634
}
9626496635
}
9626596636
return h;
9626696637
}
9626796638
@@ -101084,11 +101455,11 @@
101084101455
*/
101085101456
case OP_SeekRowid: { /* jump0, in3, ncycle */
101086101457
VdbeCursor *pC;
101087101458
BtCursor *pCrsr;
101088101459
int res;
101089
- u64 iKey;
101460
+ i64 iKey;
101090101461
101091101462
pIn3 = &aMem[pOp->p3];
101092101463
testcase( pIn3->flags & MEM_Int );
101093101464
testcase( pIn3->flags & MEM_IntReal );
101094101465
testcase( pIn3->flags & MEM_Real );
@@ -101098,13 +101469,23 @@
101098101469
** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
101099101470
** into an integer without loss of information. Take care to avoid
101100101471
** changing the datatype of pIn3, however, as it is used by other
101101101472
** parts of the prepared statement. */
101102101473
Mem x = pIn3[0];
101103
- applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
101104
- if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
101105
- iKey = x.u.i;
101474
+ if( x.flags & MEM_Str ){
101475
+ applyNumericAffinity(&x, 1);
101476
+ }
101477
+ if( x.flags & MEM_Int ){
101478
+ iKey = x.u.i;
101479
+ }else
101480
+ if( (x.flags & MEM_Real)==0
101481
+ || x.u.r < -9223372036854775808.0
101482
+ || x.u.r > 9223372036854775807.0
101483
+ || (double)(iKey = sqlite3RealToI64(x.u.r))!=x.u.r
101484
+ ){
101485
+ goto jump_to_p2;
101486
+ }
101106101487
goto notExistsWithKey;
101107101488
}
101108101489
/* Fall through into OP_NotExists */
101109101490
/* no break */ deliberate_fall_through
101110101491
case OP_NotExists: /* jump, in3, ncycle */
@@ -102342,10 +102723,15 @@
102342102723
pTabCur = p->apCsr[pOp->p3];
102343102724
assert( pTabCur!=0 );
102344102725
assert( pTabCur->eCurType==CURTYPE_BTREE );
102345102726
assert( pTabCur->uc.pCursor!=0 );
102346102727
assert( pTabCur->isTable );
102728
+#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
102729
+ assert(
102730
+ sqlite3BtreeCursorHintTblCsr(pC->uc.pCursor)==pTabCur->uc.pCursor
102731
+ );
102732
+#endif
102347102733
pTabCur->nullRow = 0;
102348102734
pTabCur->movetoTarget = rowid;
102349102735
pTabCur->deferredMoveto = 1;
102350102736
pTabCur->cacheStatus = CACHE_STALE;
102351102737
assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
@@ -104724,27 +105110,41 @@
104724105110
p->aCounter[SQLITE_STMTSTATUS_RUN]++;
104725105111
goto jump_to_p2;
104726105112
}
104727105113
104728105114
#ifdef SQLITE_ENABLE_CURSOR_HINTS
104729
-/* Opcode: CursorHint P1 * * P4 *
105115
+/* Opcode: CursorHint P1 * P3 P4 *
104730105116
**
104731
-** Provide a hint to cursor P1 that it only needs to return rows that
104732
-** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
104733
-** to values currently held in registers. TK_COLUMN terms in the P4
105117
+** Provide a hint to cursor P1.
105118
+**
105119
+** If P4 is of type P4_EXPR, then the hint is that the cursor need only return
105120
+** rows that satisfy the Expr in P4. TK_REGISTER terms in the P4 expression
105121
+** refer to values currently held in registers. TK_COLUMN terms in the P4
104734105122
** expression refer to columns in the b-tree to which cursor P1 is pointing.
105123
+** P3 is ignore in this case.
105124
+**
105125
+** Or, if P4 is P4_NOTUSED, then the hint is that cursor P1 is an index cursor
105126
+** used to drive table cursor P3. In other words, that this VM may execute
105127
+** OP_DeferredSeek instructions to lazily position P3 based on current
105128
+** position of P1.
104735105129
*/
104736105130
case OP_CursorHint: {
104737105131
VdbeCursor *pC;
105132
+ pC = p->apCsr[pOp->p1];
104738105133
104739105134
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
104740
- assert( pOp->p4type==P4_EXPR );
104741
- pC = p->apCsr[pOp->p1];
105135
+
104742105136
if( pC ){
104743105137
assert( pC->eCurType==CURTYPE_BTREE );
104744
- sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
104745
- pOp->p4.pExpr, aMem);
105138
+ if( pOp->p4type==P4_EXPR ){
105139
+ sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
105140
+ pOp->p4.pExpr, aMem);
105141
+ }else if( p->apCsr[pOp->p3] ){
105142
+ sqlite3BtreeCursorHint(
105143
+ pC->uc.pCursor, BTREE_HINT_TABLECURSOR, p->apCsr[pOp->p3]->uc.pCursor
105144
+ );
105145
+ }
104746105146
}
104747105147
break;
104748105148
}
104749105149
#endif /* SQLITE_ENABLE_CURSOR_HINTS */
104750105150
@@ -110329,13 +110729,15 @@
110329110729
if( pFJMatch ){
110330110730
assert( pExpr->op==TK_FUNCTION );
110331110731
assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 );
110332110732
assert( pExpr->x.pList==pFJMatch );
110333110733
assert( pFJMatch->nExpr>0 );
110334
- pExpr = pFJMatch->a[0].pExpr;
110335
- }
110336
- if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
110734
+ for(i=0; i<pFJMatch->nExpr; i++){
110735
+ assert( pFJMatch->a[i].pExpr->op==TK_COLUMN );
110736
+ sqlite3AuthRead(pParse,pFJMatch->a[i].pExpr,pSchema,pNC->pSrcList);
110737
+ }
110738
+ }else if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
110337110739
sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
110338110740
}
110339110741
}
110340110742
#endif
110341110743
/* Increment the nRef value on all name contexts from TopNC up to
@@ -110447,15 +110849,24 @@
110447110849
static SQLITE_NOINLINE void resolveSetExprSubtypeArg(ExprList *pList){
110448110850
int nn, ii;
110449110851
nn = pList ? pList->nExpr : 0;
110450110852
for(ii=0; ii<nn; ii++){
110451110853
Expr *pExpr = pList->a[ii].pExpr;
110452
- ExprSetProperty(pExpr, EP_SubtArg);
110453
- if( pExpr->op==TK_SELECT ){
110454
- assert( ExprUseXSelect(pExpr) );
110455
- assert( pExpr->x.pSelect!=0 );
110456
- resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList);
110854
+ while( 1 /*exit-by-break*/ ){
110855
+ ExprSetProperty(pExpr, EP_SubtArg);
110856
+ if( pExpr->op==TK_SELECT ){
110857
+ assert( ExprUseXSelect(pExpr) );
110858
+ assert( pExpr->x.pSelect!=0 );
110859
+ resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList);
110860
+ break;
110861
+ }
110862
+ if( pExpr->op==TK_UPLUS ){
110863
+ pExpr = pExpr->pLeft;
110864
+ assert( pExpr!=0 );
110865
+ }else{
110866
+ break;
110867
+ }
110457110868
}
110458110869
}
110459110870
}
110460110871
110461110872
/*
@@ -115538,10 +115949,12 @@
115538115949
}else{
115539115950
VdbeComment((v, "RHS of IN operator"));
115540115951
}
115541115952
#endif
115542115953
pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
115954
+ assert( pKeyInfo!=0 || pParse->nErr );
115955
+ if( pKeyInfo==0 ) return;
115543115956
115544115957
if( ExprUseXSelect(pExpr) ){
115545115958
/* Case 1: expr IN (SELECT ...)
115546115959
**
115547115960
** Generate code to write the results of the select into the temporary
@@ -115562,21 +115975,35 @@
115562115975
int rc;
115563115976
int addrBloom = 0;
115564115977
sqlite3SelectDestInit(&dest, SRT_Set, iTab);
115565115978
dest.zAffSdst = exprINAffinity(pParse, pExpr);
115566115979
pSelect->iLimit = 0;
115980
+ assert( pEList!=0 );
115981
+ assert( pEList->nExpr>0 );
115982
+ assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
115983
+ for(i=0; i<nVal; i++){
115984
+ Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
115985
+ CollSeq *pColl;
115986
+ pKeyInfo->aColl[i] = pColl = sqlite3BinaryCompareCollSeq(
115987
+ pParse, p, pEList->a[i].pExpr
115988
+ );
115989
+ if( !sqlite3IsBinary(pColl) ){
115990
+ allowBloom = 0; /* tag-202607231411 */
115991
+ }
115992
+ }
115567115993
if( addrOnce
115568115994
&& allowBloom
115569115995
&& OptimizationEnabled(pParse->db, SQLITE_BloomFilter)
115570115996
){
115571115997
int regBloom = ++pParse->nMem;
115572115998
addrBloom = sqlite3VdbeAddOp2(v, OP_Blob, 10000, regBloom);
115573115999
VdbeComment((v, "Bloom filter"));
115574116000
dest.iSDParm2 = regBloom;
116001
+ sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
116002
+ pKeyInfo = 0;
115575116003
}
115576116004
testcase( pSelect->selFlags & SF_Distinct );
115577
- testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
115578116005
pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
115579116006
rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
115580116007
sqlite3SelectDelete(pParse->db, pCopy);
115581116008
sqlite3DbFree(pParse->db, dest.zAffSdst);
115582116009
if( addrBloom ){
@@ -115590,20 +116017,10 @@
115590116017
}
115591116018
if( rc ){
115592116019
sqlite3KeyInfoUnref(pKeyInfo);
115593116020
return;
115594116021
}
115595
- assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
115596
- assert( pEList!=0 );
115597
- assert( pEList->nExpr>0 );
115598
- assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
115599
- for(i=0; i<nVal; i++){
115600
- Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
115601
- pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
115602
- pParse, p, pEList->a[i].pExpr
115603
- );
115604
- }
115605116022
}
115606116023
}else if( ALWAYS(pExpr->x.pList!=0) ){
115607116024
/* Case 2: expr IN (exprlist)
115608116025
**
115609116026
** For each expression, build an index key from the evaluation and
@@ -115620,14 +116037,13 @@
115620116037
if( affinity<=SQLITE_AFF_NONE ){
115621116038
affinity = SQLITE_AFF_BLOB;
115622116039
}else if( affinity==SQLITE_AFF_REAL ){
115623116040
affinity = SQLITE_AFF_NUMERIC;
115624116041
}
115625
- if( pKeyInfo ){
115626
- assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
115627
- pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
115628
- }
116042
+ assert( pKeyInfo!=0 );
116043
+ assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
116044
+ pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
115629116045
115630116046
/* Loop through each expression in <exprlist>. */
115631116047
r1 = sqlite3GetTempReg(pParse);
115632116048
r2 = sqlite3GetTempReg(pParse);
115633116049
for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
@@ -116580,11 +116996,11 @@
116580116996
if( pExpr->op!=TK_FUNCTION ){
116581116997
return WRC_Prune;
116582116998
}
116583116999
assert( ExprUseXList(pExpr) );
116584117000
db = pWalker->pParse->db;
116585
- n = ALWAYS(pExpr->x.pList) ? pExpr->x.pList->nExpr : 0;
117001
+ n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
116586117002
pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
116587117003
if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
116588117004
pWalker->eCode = 1;
116589117005
return WRC_Abort;
116590117006
}
@@ -117229,11 +117645,16 @@
117229117645
#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
117230117646
if( pDef==0 && pParse->explain ){
117231117647
pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
117232117648
}
117233117649
#endif
117234
- if( pDef==0 || pDef->xFinalize!=0 ){
117650
+ if( pDef==0
117651
+ || pDef->xFinalize!=0
117652
+ || ((pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 &&
117653
+ !pParse->nested &&
117654
+ (db->mDbFlags & DBFLAG_InternalFunc)==0)
117655
+ ){
117235117656
sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
117236117657
break;
117237117658
}
117238117659
if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
117239117660
assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
@@ -121984,19 +122405,41 @@
121984122405
121985122406
121986122407
/*
121987122408
** Argument z points into the body of a constraint - specifically the
121988122409
** second token of the constraint definition. For a named constraint,
121989
-** z points to the first token past the CONSTRAINT keyword. For an
122410
+** z points to the second token of the constraint definition. For an
121990122411
** unnamed NOT NULL constraint, z points to the first byte past the NOT
121991122412
** keyword.
122413
+**
122414
+** Argument eTok may be the token value of the first token of the constraint
122415
+** (e.g. TK_CHECK or TK_REFERENCES) or zero. If it is either TK_REFERENCES
122416
+** or TK_FOREIGN, special parsing is enabled to find the end of the foreign-key
122417
+** constraint definition.
121992122418
**
121993122419
** Return the number of bytes until the end of the constraint.
121994122420
*/
121995
-static int getConstraint(const u8 *z){
122421
+static int getConstraint(const u8 *z, int eTok){
121996122422
int iOff = 0;
121997122423
int t = 0;
122424
+
122425
+#ifndef SQLITE_OMIT_FOREIGN_KEY
122426
+ if( eTok==TK_FOREIGN ){
122427
+ /* For a FOREIGN KEY constraint, use getConstraint() to parse everything
122428
+ ** up to the REFERENCES keyword. Then getConstraintToken() to consume
122429
+ ** the TK_REFERENCES token itself. Then fall through to the special
122430
+ ** handling for TK_REFERENCES below. */
122431
+ iOff = getConstraint(z, 0);
122432
+ iOff += getConstraintToken(&z[iOff], &eTok);
122433
+ }
122434
+
122435
+ if( eTok==TK_REFERENCES ){
122436
+ /* REFERENCES is followed by a table name. Gobble this up here in
122437
+ ** case the table name is a fallback token like TK_GENERATED. */
122438
+ iOff += getConstraintToken(&z[iOff], &t);
122439
+ }
122440
+#endif
121998122441
121999122442
/* Now, the current constraint proceeds until the next occurence of one
122000122443
** of the following tokens:
122001122444
**
122002122445
** CONSTRAINT, PRIMARY, NOT, UNIQUE, CHECK, DEFAULT,
@@ -122165,24 +122608,24 @@
122165122608
|| t==TK_COMMA || t==TK_RP || t==TK_GENERATED || t==TK_AS
122166122609
){
122167122610
t = TK_CHECK;
122168122611
}else{
122169122612
iOff += nTok;
122170
- iOff += getConstraint(&zSql[iOff]);
122613
+ iOff += getConstraint(&zSql[iOff], t);
122171122614
}
122172122615
122173122616
if( cmp==0 || (iNotNull>=0 && t==TK_NOT) ){
122174
- if( t!=TK_NOT && t!=TK_CHECK ){
122617
+ if( t!=TK_NOT && t!=TK_CHECK && t!=TK_REFERENCES && t!=TK_FOREIGN ){
122175122618
errorMPrintf(ctx, "constraint may not be dropped: %s", zCons);
122176122619
return;
122177122620
}
122178122621
iEnd = iOff;
122179122622
break;
122180122623
}
122181122624
122182122625
}else if( t==TK_NOT && iNotNull==ii ){
122183
- iEnd = iOff + getConstraint(&zSql[iOff]);
122626
+ iEnd = iOff + getConstraint(&zSql[iOff], 0);
122184122627
break;
122185122628
}else if( t==TK_RP || t==TK_ILLEGAL ){
122186122629
iEnd = -1;
122187122630
break;
122188122631
}else if( t==TK_COMMA ){
@@ -122236,13 +122679,12 @@
122236122679
const u8 *zSql = sqlite3_value_text(argv[0]);
122237122680
const char *zCons = (const char*)sqlite3_value_text(argv[1]);
122238122681
int iCol = sqlite3_value_int(argv[2]);
122239122682
int iOff = 0;
122240122683
int ii;
122241
- char *zNew = 0;
122684
+ sqlite3_str *pNew;
122242122685
int t = 0;
122243
- sqlite3 *db;
122244122686
UNUSED_PARAMETER(NotUsed);
122245122687
122246122688
if( skipCreateTable(ctx, zSql, &iOff) ) return;
122247122689
122248122690
for(ii=0; ii<=iCol || (iCol<0 && t!=TK_RP); ii++){
@@ -122258,17 +122700,15 @@
122258122700
}
122259122701
}
122260122702
122261122703
iOff += getWhitespace(&zSql[iOff]);
122262122704
122263
- db = sqlite3_context_db_handle(ctx);
122264
- if( iCol<0 ){
122265
- zNew = sqlite3MPrintf(db, "%.*s, %s%s", iOff, zSql, zCons, &zSql[iOff]);
122266
- }else{
122267
- zNew = sqlite3MPrintf(db, "%.*s %s%s", iOff, zSql, zCons, &zSql[iOff]);
122268
- }
122269
- sqlite3_result_text(ctx, zNew, -1, SQLITE_DYNAMIC);
122705
+ pNew = sqlite3_str_new(sqlite3_context_db_handle(ctx));
122706
+ sqlite3_str_append(pNew, (const char*)zSql, iOff);
122707
+ if( iCol<0 ) sqlite3_str_append(pNew, ",", 1);
122708
+ sqlite3_str_appendf(pNew, " %s%s", zCons, &zSql[iOff]);
122709
+ sqlite3_result_str(ctx, pNew, SQLITE_FINISH);
122270122710
}
122271122711
122272122712
/*
122273122713
** Find a column named pCol in table pTab. If successful, set output
122274122714
** parameter *piCol to the index of the column in the table and return
@@ -123524,11 +123964,11 @@
123524123964
sqlite3_str_appendf(&sStat, " %llu", iVal);
123525123965
#ifdef SQLITE_ENABLE_STAT4
123526123966
assert( p->current.anEq[i] || p->nRow==0 );
123527123967
#endif
123528123968
}
123529
- sqlite3ResultStrAccum(context, &sStat);
123969
+ sqlite3_result_str(context, &sStat, SQLITE_XFER);
123530123970
}
123531123971
#ifdef SQLITE_ENABLE_STAT4
123532123972
else if( eCall==STAT_GET_ROWID ){
123533123973
if( p->iGet<0 ){
123534123974
samplePushPrevious(p, 0);
@@ -123561,11 +124001,11 @@
123561124001
sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
123562124002
for(i=0; i<p->nCol; i++){
123563124003
sqlite3_str_appendf(&sStat, "%llu ", (u64)aCnt[i]);
123564124004
}
123565124005
if( sStat.nChar ) sStat.nChar--;
123566
- sqlite3ResultStrAccum(context, &sStat);
124006
+ sqlite3_result_str(context, &sStat, SQLITE_XFER);
123567124007
}
123568124008
#endif /* SQLITE_ENABLE_STAT4 */
123569124009
#ifndef SQLITE_DEBUG
123570124010
UNUSED_PARAMETER( argc );
123571124011
#endif
@@ -125649,10 +126089,11 @@
125649126089
}
125650126090
}
125651126091
125652126092
assert( pToplevel->nTableLock < 0x7fff0000 );
125653126093
nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
126094
+ if( pToplevel->nTableLock==0 ) pToplevel->aTableLock = 0;
125654126095
pToplevel->aTableLock =
125655126096
sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
125656126097
if( pToplevel->aTableLock ){
125657126098
p = &pToplevel->aTableLock[pToplevel->nTableLock++];
125658126099
p->iDb = iDb;
@@ -125815,11 +126256,11 @@
125815126256
if( pParse->nTableLock ) codeTableLocks(pParse);
125816126257
#endif
125817126258
125818126259
/* Initialize any AUTOINCREMENT data structures required.
125819126260
*/
125820
- if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
126261
+ if( pParse->usesAinc ) sqlite3AutoincrementBegin(pParse);
125821126262
125822126263
/* Code constant expressions that were factored out of inner loops.
125823126264
*/
125824126265
if( pParse->pConstExpr ){
125825126266
ExprList *pEL = pParse->pConstExpr;
@@ -125848,11 +126289,11 @@
125848126289
assert( v!=0 || pParse->nErr );
125849126290
assert( db->mallocFailed==0 || pParse->nErr );
125850126291
if( pParse->nErr==0 ){
125851126292
/* A minimum of one cursor is required if autoincrement is used
125852126293
* See ticket [a696379c1f08866] */
125853
- assert( pParse->pAinc==0 || pParse->nTab>0 );
126294
+ assert( pParse->usesAinc==0 || pParse->nTab>0 );
125854126295
sqlite3VdbeMakeReady(v, pParse);
125855126296
pParse->rc = SQLITE_DONE;
125856126297
}else{
125857126298
pParse->rc = SQLITE_ERROR;
125858126299
}
@@ -127812,10 +128253,27 @@
127812128253
pIdx->aSortOrder = (u8*)zExtra;
127813128254
pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */
127814128255
pIdx->isResized = 1;
127815128256
return SQLITE_OK;
127816128257
}
128258
+
128259
+/*
128260
+** Return true if the index pIdx can support a Bloom filter on its
128261
+** first N columns. Specifically, return true if all of the first N
128262
+** columns have the BINARY collating sequence or no collating sequence
128263
+** at all, and return false if there are any non-BINARY collating
128264
+** seqeuences on any of the first N columns. tag-202607231411
128265
+*/
128266
+SQLITE_PRIVATE int sqlite3IndexBloomable(const Index *pIdx, int N){
128267
+ int i;
128268
+ assert( pIdx!=0 );
128269
+ assert( N <= pIdx->nColumn );
128270
+ for(i=0; i<N; i++){
128271
+ if( sqlite3StrICmp(pIdx->azColl[i],"BINARY")!=0 ) return 0;
128272
+ }
128273
+ return 1;
128274
+}
127817128275
127818128276
/*
127819128277
** Estimate the total row width for a table.
127820128278
*/
127821128279
static void estimateTableWidth(Table *pTab){
@@ -128164,18 +128622,15 @@
128164128622
128165128623
#ifndef SQLITE_OMIT_VIRTUALTABLE
128166128624
/*
128167128625
** Return true if zName is a shadow table name in the current database
128168128626
** connection.
128169
-**
128170
-** zName is temporarily modified while this routine is running, but is
128171
-** restored to its original value prior to this routine returning.
128172128627
*/
128173128628
SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
128174128629
const char *zTail; /* Pointer to the last "_" in zName */
128175128630
Table *pTab; /* Table that zName is a shadow of */
128176
- char *zCopy;
128631
+ char *zCopy; /* Transient copy of zName after last "_" */
128177128632
zTail = strrchr(zName, '_');
128178128633
if( zTail==0 ) return 0;
128179128634
zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
128180128635
pTab = zCopy ? sqlite3FindTable(db, zCopy, 0) : 0;
128181128636
sqlite3DbFree(db, zCopy);
@@ -129683,12 +130138,13 @@
129683130138
}
129684130139
}
129685130140
if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
129686130141
if( !ifNotExist ){
129687130142
sqlite3ErrorMsg(pParse, "index %s already exists", zName);
130143
+ }else if( db->init.busy ){
130144
+ sqlite3ErrorMsg(pParse,""); /* corruptSchema() will do the error */
129688130145
}else{
129689
- assert( !db->init.busy );
129690130146
sqlite3CodeVerifySchema(pParse, iDb);
129691130147
sqlite3ForceNotReadOnly(pParse);
129692130148
}
129693130149
goto exit_create_index;
129694130150
}
@@ -133318,32 +133774,20 @@
133318133774
sqlite3_value **argv
133319133775
){
133320133776
PrintfArguments x;
133321133777
StrAccum str;
133322133778
const char *zFormat;
133323
- int n;
133324133779
sqlite3 *db = sqlite3_context_db_handle(context);
133325133780
133326133781
if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
133327133782
x.nArg = argc-1;
133328133783
x.nUsed = 0;
133329133784
x.apArg = argv+1;
133330133785
sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
133331133786
str.printfFlags = SQLITE_PRINTF_SQLFUNC;
133332133787
sqlite3_str_appendf(&str, zFormat, &x);
133333
- if( str.accError==SQLITE_OK ){
133334
- n = str.nChar;
133335
- sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
133336
- SQLITE_DYNAMIC);
133337
- }else{
133338
- if( str.accError==SQLITE_NOMEM ){
133339
- sqlite3_result_error_nomem(context);
133340
- }else{
133341
- sqlite3_result_error_toobig(context);
133342
- }
133343
- sqlite3_str_reset(&str);
133344
- }
133788
+ sqlite3_result_str(context, &str, SQLITE_XFER);
133345133789
}
133346133790
}
133347133791
133348133792
/*
133349133793
** Implementation of the substr() function.
@@ -134286,16 +134730,11 @@
134286134730
sqlite3 *db = sqlite3_context_db_handle(context);
134287134731
assert( argc==1 );
134288134732
UNUSED_PARAMETER(argc);
134289134733
sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
134290134734
sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context)));
134291
- sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
134292
- SQLITE_DYNAMIC);
134293
- if( str.accError!=SQLITE_OK ){
134294
- sqlite3_result_null(context);
134295
- sqlite3_result_error_code(context, str.accError);
134296
- }
134735
+ sqlite3_result_str(context, &str, SQLITE_XFER);
134297134736
}
134298134737
134299134738
/*
134300134739
** The unicode() function. Return the integer unicode code-point value
134301134740
** for the first character of the input string.
@@ -135324,32 +135763,22 @@
135324135763
#endif /* SQLITE_OMIT_WINDOWFUNC */
135325135764
static void groupConcatFinalize(sqlite3_context *context){
135326135765
GroupConcatCtx *pGCC
135327135766
= (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
135328135767
if( pGCC ){
135329
- sqlite3ResultStrAccum(context, &pGCC->str);
135768
+ sqlite3_result_str(context, &pGCC->str, SQLITE_XFER);
135330135769
#ifndef SQLITE_OMIT_WINDOWFUNC
135331135770
sqlite3_free(pGCC->pnSepLengths);
135332135771
#endif
135333135772
}
135334135773
}
135335135774
#ifndef SQLITE_OMIT_WINDOWFUNC
135336135775
static void groupConcatValue(sqlite3_context *context){
135337135776
GroupConcatCtx *pGCC
135338135777
= (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
135339
- if( pGCC ){
135340
- StrAccum *pAccum = &pGCC->str;
135341
- if( pAccum->accError==SQLITE_TOOBIG ){
135342
- sqlite3_result_error_toobig(context);
135343
- }else if( pAccum->accError==SQLITE_NOMEM ){
135344
- sqlite3_result_error_nomem(context);
135345
- }else if( pGCC->nAccum>0 && pAccum->nChar==0 ){
135346
- sqlite3_result_text(context, "", 1, SQLITE_STATIC);
135347
- }else{
135348
- const char *zText = sqlite3_str_value(pAccum);
135349
- sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
135350
- }
135778
+ if( pGCC && pGCC->nAccum>0 ){
135779
+ sqlite3_result_str(context, &pGCC->str, SQLITE_COPY);
135351135780
}
135352135781
}
135353135782
#else
135354135783
# define groupConcatValue 0
135355135784
#endif /* SQLITE_OMIT_WINDOWFUNC */
@@ -135976,17 +136405,21 @@
135976136405
static void percentSort(
135977136406
double *a, /* Array to sort */
135978136407
unsigned int n, /* Number of elements in array a[] */
135979136408
int iReq /* Element caller cares about (or -ve) */
135980136409
){
135981
- int iLt; /* Entries before a[iLt] are less than rPivot */
135982
- int iGt; /* Entries at or after a[iGt] are greater than rPivot */
136410
+ int iLt; /* Entries before a[iLt] are less than or equal to rPivot */
136411
+ int iGt; /* Entries a[iGt] and after are greater or equal to rPivot */
135983136412
int i; /* Loop counter */
135984136413
double rPivot; /* The pivot value */
135985136414
135986136415
assert( n>=2 );
135987136416
do{
136417
+ /* Put the first, middle, and last elements in sorted order.
136418
+ ** After doing so, return immediately if the array contains
136419
+ ** three or fewer elements as there is nothing more to do.
136420
+ */
135988136421
if( a[0]>a[n-1] ){
135989136422
SWAP_DOUBLE(a[0],a[n-1])
135990136423
}
135991136424
if( n==2 ) return;
135992136425
iGt = n-1;
@@ -135995,10 +136428,15 @@
135995136428
SWAP_DOUBLE(a[0],a[i])
135996136429
}else if( a[i]>a[iGt] ){
135997136430
SWAP_DOUBLE(a[i],a[iGt])
135998136431
}
135999136432
if( n==3 ) return;
136433
+
136434
+ /* Take the value of the middle element as the pivot. Shuffle
136435
+ ** values around so that all elements less than the pivot come
136436
+ ** before all elements greater than the pivot.
136437
+ */
136000136438
rPivot = a[i];
136001136439
iLt = i = 1;
136002136440
do{
136003136441
if( a[i]<rPivot ){
136004136442
if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
@@ -136012,12 +136450,16 @@
136012136450
}else{
136013136451
i++;
136014136452
}
136015136453
}while( i<iGt );
136016136454
136455
+ assert( iLt>0 && iLt<iGt && iGt<n );
136456
+ testcase( iGt>iLt+1 );
136017136457
assert( a[iLt]==rPivot );
136018
- assert( iGt>iLt );
136458
+ assert( a[iLt-1]<=rPivot );
136459
+ assert( a[iGt]>=rPivot );
136460
+ assert( a[iLt+1]>=rPivot );
136019136461
136020136462
if( iReq>=0 ){
136021136463
/* In this case, the only elements that the caller requires sorted into
136022136464
** the correct positions are elements a[iReq] and a[iReq+1]. At this
136023136465
** point we know that element a[iLt] is in the correct position and
@@ -136190,12 +136632,11 @@
136190136632
sqlite3_str_appendall(pStr, ",\"journal\":");
136191136633
rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr);
136192136634
if( rc ) sqlite3_str_append(pStr, "null", 4);
136193136635
}
136194136636
sqlite3_str_append(pStr, "}", 1);
136195
- sqlite3_result_text(context, sqlite3_str_finish(pStr), -1,
136196
- sqlite3_free);
136637
+ sqlite3_result_str(context, pStr, SQLITE_FINISH);
136197136638
}
136198136639
sqlite3BtreeLeave(pBtree);
136199136640
}else{
136200136641
sqlite3_result_text(context, "{}", 2, SQLITE_STATIC);
136201136642
}
@@ -136307,12 +136748,12 @@
136307136748
}else{
136308136749
sqlite3_str_appendf(pResult, ", NULL");
136309136750
}
136310136751
}
136311136752
}
136312
- sqlite3_result_text(ctx, sqlite3_str_finish(pResult), -1, sqlite3_free);
136313136753
}
136754
+ sqlite3_result_str(ctx, pResult, SQLITE_FINISH);
136314136755
sqlite3_free_filename(zFile);
136315136756
sqlite3_free(zErr);
136316136757
}
136317136758
#endif /* SQLITE_DEBUG */
136318136759
@@ -136405,11 +136846,11 @@
136405136846
VFUNCTION(random, 0, 0, 0, randomFunc ),
136406136847
VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
136407136848
FUNCTION(nullif, 2, 0, 1, nullifFunc ),
136408136849
DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
136409136850
DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
136410
- FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
136851
+ SFUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
136411136852
FUNCTION(unistr, 1, 0, 0, unistrFunc ),
136412136853
FUNCTION(quote, 1, 0, 0, quoteFunc ),
136413136854
FUNCTION(unistr_quote, 1, 1, 0, quoteFunc ),
136414136855
VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
136415136856
VFUNCTION(changes, 0, 0, 0, changes ),
@@ -138454,19 +138895,23 @@
138454138895
pParse->nErr++;
138455138896
pParse->rc = SQLITE_CORRUPT_SEQUENCE;
138456138897
return 0;
138457138898
}
138458138899
138900
+ if( pToplevel->usesAinc==0 ){
138901
+ pToplevel->pAinc = 0;
138902
+ }
138459138903
pInfo = pToplevel->pAinc;
138460138904
while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
138461138905
if( pInfo==0 ){
138462138906
pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
138463138907
sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
138464138908
testcase( pParse->earlyCleanup );
138465138909
if( pParse->db->mallocFailed ) return 0;
138466138910
pInfo->pNext = pToplevel->pAinc;
138467138911
pToplevel->pAinc = pInfo;
138912
+ pToplevel->usesAinc = 1;
138468138913
pInfo->pTab = pTab;
138469138914
pInfo->iDb = iDb;
138470138915
pToplevel->nMem++; /* Register to hold name of table */
138471138916
pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
138472138917
pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
@@ -138491,10 +138936,11 @@
138491138936
** only called from the top-level */
138492138937
assert( pParse->pTriggerTab==0 );
138493138938
assert( sqlite3IsToplevel(pParse) );
138494138939
138495138940
assert( v ); /* We failed long ago if this is not so */
138941
+ assert( pParse->usesAinc );
138496138942
for(p = pParse->pAinc; p; p = p->pNext){
138497138943
static const int iLn = VDBE_OFFSET_LINENO(2);
138498138944
static const VdbeOpList autoInc[] = {
138499138945
/* 0 */ {OP_Null, 0, 0, 0},
138500138946
/* 1 */ {OP_Rewind, 0, 10, 0},
@@ -138558,10 +139004,11 @@
138558139004
AutoincInfo *p;
138559139005
Vdbe *v = pParse->pVdbe;
138560139006
sqlite3 *db = pParse->db;
138561139007
138562139008
assert( v );
139009
+ assert( pParse->usesAinc );
138563139010
for(p = pParse->pAinc; p; p = p->pNext){
138564139011
static const int iLn = VDBE_OFFSET_LINENO(2);
138565139012
static const VdbeOpList autoIncEnd[] = {
138566139013
/* 0 */ {OP_NotNull, 0, 2, 0},
138567139014
/* 1 */ {OP_NewRowid, 0, 0, 0},
@@ -138590,11 +139037,11 @@
138590139037
aOp[3].p5 = OPFLAG_APPEND;
138591139038
sqlite3ReleaseTempReg(pParse, iRec);
138592139039
}
138593139040
}
138594139041
SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
138595
- if( pParse->pAinc ) autoIncrementEnd(pParse);
139042
+ if( pParse->usesAinc ) autoIncrementEnd(pParse);
138596139043
}
138597139044
#else
138598139045
/*
138599139046
** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
138600139047
** above are all no-ops
@@ -140244,10 +140691,26 @@
140244140691
pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
140245140692
regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
140246140693
}else{
140247140694
pTrigger = 0;
140248140695
regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
140696
+ }
140697
+ if( regTrigCnt ){
140698
+ /* At this point regTrigCnt is non-zero if there are DELETE triggers
140699
+ ** or FK triggers. But we only care about these things if there is
140700
+ ** a chance that a row will be deleted by an ON CONFLICT REPLACE
140701
+ ** constraint. So zero regTrigCnt if no such constraint can be found. */
140702
+ if( overrideError!=OE_Replace ){
140703
+ if( overrideError!=OE_Default ){
140704
+ regTrigCnt = 0;
140705
+ }else if( pkChng==0 || pPk || pTab->keyConf!=OE_Replace ){
140706
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
140707
+ if( pIdx->onError==OE_Replace ) break;
140708
+ }
140709
+ if( pIdx==0 ) regTrigCnt = 0;
140710
+ }
140711
+ }
140249140712
}
140250140713
if( regTrigCnt ){
140251140714
/* Replace triggers might exist. Allocate the counter and
140252140715
** initialize it to zero. */
140253140716
regTrigCnt = ++pParse->nMem;
@@ -140296,13 +140759,17 @@
140296140759
** the UNIQUE constraints have run.
140297140760
*/
140298140761
if( onError==OE_Replace /* IPK rule is REPLACE */
140299140762
&& onError!=overrideError /* Rules for other constraints are different */
140300140763
&& pTab->pIndex /* There exist other constraints */
140301
- && !upsertIpkDelay /* IPK check already deferred by UPSERT */
140302140764
){
140303
- ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
140765
+ if( upsertIpkDelay ){
140766
+ ipkTop = upsertIpkDelay + 1;
140767
+ upsertIpkDelay = 0;
140768
+ }else{
140769
+ ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
140770
+ }
140304140771
VdbeComment((v, "defer IPK REPLACE until last"));
140305140772
}
140306140773
140307140774
if( isUpdate ){
140308140775
/* pkChng!=0 does not mean that the rowid has changed, only that
@@ -140392,15 +140859,15 @@
140392140859
sqlite3VdbeGoto(v, ignoreDest);
140393140860
break;
140394140861
}
140395140862
}
140396140863
sqlite3VdbeResolveLabel(v, addrRowidOk);
140397
- if( pUpsert && pUpsertClause!=pUpsert ){
140398
- upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
140399
- }else if( ipkTop ){
140864
+ if( ipkTop ){
140400140865
ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
140401140866
sqlite3VdbeJumpHere(v, ipkTop-1);
140867
+ }else if( pUpsert && pUpsertClause!=pUpsert ){
140868
+ upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
140402140869
}
140403140870
}
140404140871
140405140872
/* Test all UNIQUE constraints by creating entries for each UNIQUE
140406140873
** index and making sure that duplicate entries do not already exist.
@@ -140416,10 +140883,11 @@
140416140883
int regIdx; /* Range of registers holding content for pIdx */
140417140884
int regR; /* Range of registers holding conflicting PK */
140418140885
int iThisCur; /* Cursor for this UNIQUE index */
140419140886
int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
140420140887
int addrConflictCk; /* First opcode in the conflict check logic */
140888
+ int nConflictCk; /* Number of opcodes in conflict check logic */
140421140889
140422140890
if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
140423140891
if( pUpsert ){
140424140892
pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
140425140893
if( upsertIpkDelay && pUpsertClause==pUpsert ){
@@ -140591,10 +141059,15 @@
140591141059
VdbeCoverageIf(v, op==OP_Ne);
140592141060
}
140593141061
}
140594141062
}
140595141063
}
141064
+
141065
+ nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
141066
+ assert( nConflictCk>0 || db->mallocFailed );
141067
+ testcase( nConflictCk<=0 );
141068
+ testcase( nConflictCk>1 );
140596141069
140597141070
/* Generate code that executes if the new index entry is not unique */
140598141071
assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
140599141072
|| onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
140600141073
switch( onError ){
@@ -140617,17 +141090,11 @@
140617141090
testcase( onError==OE_Ignore );
140618141091
sqlite3VdbeGoto(v, ignoreDest);
140619141092
break;
140620141093
}
140621141094
default: {
140622
- int nConflictCk; /* Number of opcodes in conflict check logic */
140623
-
140624141095
assert( onError==OE_Replace );
140625
- nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
140626
- assert( nConflictCk>0 || db->mallocFailed );
140627
- testcase( nConflictCk<=0 );
140628
- testcase( nConflictCk>1 );
140629141096
if( regTrigCnt ){
140630141097
sqlite3MultiWrite(pParse);
140631141098
nReplaceTrig++;
140632141099
}
140633141100
if( pTrigger && isUpdate ){
@@ -140637,62 +141104,62 @@
140637141104
regR, nPkField, 0, OE_Replace,
140638141105
(pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
140639141106
if( pTrigger && isUpdate ){
140640141107
sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
140641141108
}
140642
- if( regTrigCnt ){
140643
- int addrBypass; /* Jump destination to bypass recheck logic */
140644
-
140645
- sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
140646
- addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
140647
- VdbeComment((v, "bypass recheck"));
140648
-
140649
- /* Here we insert code that will be invoked after all constraint
140650
- ** checks have run, if and only if one or more replace triggers
140651
- ** fired. */
140652
- sqlite3VdbeResolveLabel(v, lblRecheckOk);
140653
- lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
140654
- if( pIdx->pPartIdxWhere ){
140655
- /* Bypass the recheck if this partial index is not defined
140656
- ** for the current row */
140657
- sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
140658
- VdbeCoverage(v);
140659
- }
140660
- /* Copy the constraint check code from above, except change
140661
- ** the constraint-ok jump destination to be the address of
140662
- ** the next retest block */
140663
- while( nConflictCk>0 ){
140664
- VdbeOp x; /* Conflict check opcode to copy */
140665
- /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
140666
- ** Hence, make a complete copy of the opcode, rather than using
140667
- ** a pointer to the opcode. */
140668
- x = *sqlite3VdbeGetOp(v, addrConflictCk);
140669
- if( x.opcode!=OP_IdxRowid ){
140670
- int p2; /* New P2 value for copied conflict check opcode */
140671
- const char *zP4;
140672
- if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
140673
- p2 = lblRecheckOk;
140674
- }else{
140675
- p2 = x.p2;
140676
- }
140677
- zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
140678
- sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
140679
- sqlite3VdbeChangeP5(v, x.p5);
140680
- VdbeCoverageIf(v, p2!=x.p2);
140681
- }
140682
- nConflictCk--;
140683
- addrConflictCk++;
140684
- }
140685
- /* If the retest fails, issue an abort */
140686
- sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
140687
-
140688
- sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
140689
- }
140690141109
seenReplace = 1;
140691141110
break;
140692141111
}
140693141112
}
141113
+ if( regTrigCnt ){
141114
+ int addrBypass; /* Jump destination to bypass recheck logic */
141115
+
141116
+ sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
141117
+ addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
141118
+ VdbeComment((v, "bypass recheck"));
141119
+
141120
+ /* Here we insert code that will be invoked after all constraint
141121
+ ** checks have run, if and only if one or more replace triggers
141122
+ ** fired. */
141123
+ sqlite3VdbeResolveLabel(v, lblRecheckOk);
141124
+ lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
141125
+ if( pIdx->pPartIdxWhere ){
141126
+ /* Bypass the recheck if this partial index is not defined
141127
+ ** for the current row */
141128
+ sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
141129
+ VdbeCoverage(v);
141130
+ }
141131
+ /* Copy the constraint check code from above, except change
141132
+ ** the constraint-ok jump destination to be the address of
141133
+ ** the next retest block */
141134
+ while( nConflictCk>0 ){
141135
+ VdbeOp x; /* Conflict check opcode to copy */
141136
+ /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
141137
+ ** Hence, make a complete copy of the opcode, rather than using
141138
+ ** a pointer to the opcode. */
141139
+ x = *sqlite3VdbeGetOp(v, addrConflictCk);
141140
+ if( x.opcode!=OP_IdxRowid ){
141141
+ int p2; /* New P2 value for copied conflict check opcode */
141142
+ const char *zP4;
141143
+ if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
141144
+ p2 = lblRecheckOk;
141145
+ }else{
141146
+ p2 = x.p2;
141147
+ }
141148
+ zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
141149
+ sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
141150
+ sqlite3VdbeChangeP5(v, x.p5);
141151
+ VdbeCoverageIf(v, p2!=x.p2);
141152
+ }
141153
+ nConflictCk--;
141154
+ addrConflictCk++;
141155
+ }
141156
+ /* If the retest fails, issue an abort */
141157
+ sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
141158
+
141159
+ sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
141160
+ }
140694141161
sqlite3VdbeResolveLabel(v, addrUniqueOk);
140695141162
if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
140696141163
if( pUpsertClause
140697141164
&& upsertIpkReturn
140698141165
&& sqlite3UpsertNextIsIPK(pUpsertClause)
@@ -140726,12 +141193,12 @@
140726141193
VdbeCoverage(v);
140727141194
sqlite3RowidConstraint(pParse, OE_Abort, pTab);
140728141195
}else{
140729141196
sqlite3VdbeGoto(v, addrRecheck);
140730141197
}
140731
- sqlite3VdbeResolveLabel(v, lblRecheckOk);
140732141198
}
141199
+ if( regTrigCnt ) sqlite3VdbeResolveLabel(v, lblRecheckOk);
140733141200
140734141201
/* Generate the table record */
140735141202
if( HasRowid(pTab) ){
140736141203
int regRec = aRegIdx[ix];
140737141204
sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
@@ -142023,10 +142490,11 @@
142023142490
void (*str_free)(sqlite3_str*);
142024142491
int (*carray_bind)(sqlite3_stmt*,int,void*,int,int,void(*)(void*));
142025142492
int (*carray_bind_v2)(sqlite3_stmt*,int,void*,int,int,void(*)(void*),void*);
142026142493
/* Version 3.54.0 and later */
142027142494
sqlite3_int64 (*incomplete)(const char*);
142495
+ void (*result_str)(sqlite3_context*,sqlite3_str*,int);
142028142496
};
142029142497
142030142498
/*
142031142499
** This is the function signature used for all extension entry points. It
142032142500
** is also defined in the file "loadext.c".
@@ -142368,10 +142836,11 @@
142368142836
#define sqlite3_str_free sqlite3_api->str_free
142369142837
#define sqlite3_carray_bind sqlite3_api->carray_bind
142370142838
#define sqlite3_carray_bind_v2 sqlite3_api->carray_bind_v2
142371142839
/* Version 3.54.0 and later */
142372142840
#define sqlite3_incomplete sqlite3_api->incomplete
142841
+#define sqlite3_result_str sqlite3_api->result_str
142373142842
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
142374142843
142375142844
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
142376142845
/* This case when the file really is being compiled as a loadable
142377142846
** extension */
@@ -142905,11 +143374,13 @@
142905143374
sqlite3_carray_bind_v2,
142906143375
#else
142907143376
0,
142908143377
0,
142909143378
#endif
142910
- sqlite3_incomplete
143379
+ /* Version 3.54.0 and later */
143380
+ sqlite3_incomplete,
143381
+ sqlite3_result_str
142911143382
};
142912143383
142913143384
/* True if x is the directory separator character
142914143385
*/
142915143386
#if SQLITE_OS_WIN
@@ -147203,10 +147674,11 @@
147203147674
corruptSchema(pData, argv, 0);
147204147675
return 1;
147205147676
}
147206147677
147207147678
assert( iDb>=0 && iDb<db->nDb );
147679
+ assert( db->aDb[iDb].pSchema!=0 );
147208147680
if( argv[3]==0 ){
147209147681
corruptSchema(pData, argv, 0);
147210147682
}else if( argv[4]
147211147683
&& 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
147212147684
&& 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
@@ -147277,10 +147749,20 @@
147277147749
){
147278147750
if( sqlite3Config.bExtraSchemaChecks ){
147279147751
corruptSchema(pData, argv, "invalid rootpage");
147280147752
}
147281147753
}
147754
+ }
147755
+ if( pData->pzErrMsg[0]==0 ){
147756
+ Schema *pX = db->aDb[iDb].pSchema;
147757
+ if( pX->tblHash.count + pX->idxHash.count + pX->trigHash.count
147758
+ > (u32)db->aLimit[SQLITE_LIMIT_SCHEMA]
147759
+ ){
147760
+ *pData->pzErrMsg = sqlite3MPrintf(db, "too many schema objects");
147761
+ pData->rc = SQLITE_ERROR;
147762
+ return 1;
147763
+ }
147282147764
}
147283147765
return 0;
147284147766
}
147285147767
147286147768
/*
@@ -147674,11 +148156,11 @@
147674148156
sqlite3 *db = pParse->db;
147675148157
assert( db!=0 );
147676148158
assert( db->pParse==pParse );
147677148159
assert( pParse->nested==0 );
147678148160
#ifndef SQLITE_OMIT_SHARED_CACHE
147679
- if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
148161
+ if( pParse->nTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
147680148162
#endif
147681148163
while( pParse->pCleanup ){
147682148164
ParseCleanup *pCleanup = pParse->pCleanup;
147683148165
pParse->pCleanup = pCleanup->pNext;
147684148166
pCleanup->xCleanup(db, pCleanup->pPtr);
@@ -147758,10 +148240,11 @@
147758148240
**
147759148241
** Caution: Do not confuse this routine with sqlite3ParseObjectInit() which
147760148242
** is generated by Lemon.
147761148243
*/
147762148244
SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
148245
+ assert( db!=0 );
147763148246
memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
147764148247
memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
147765148248
assert( db->pParse!=pParse );
147766148249
pParse->pOuterParse = db->pParse;
147767148250
db->pParse = pParse;
@@ -148157,11 +148640,11 @@
148157148640
int nBytes, /* Length of zSql in bytes. */
148158148641
sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148159148642
const void **pzTail /* OUT: End of parsed string */
148160148643
){
148161148644
int rc;
148162
- rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
148645
+ rc = sqlite3Prepare16(db,zSql,nBytes&~1,0,ppStmt,pzTail);
148163148646
assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148164148647
return rc;
148165148648
}
148166148649
SQLITE_API int sqlite3_prepare16_v2(
148167148650
sqlite3 *db, /* Database handle. */
@@ -148169,11 +148652,11 @@
148169148652
int nBytes, /* Length of zSql in bytes. */
148170148653
sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148171148654
const void **pzTail /* OUT: End of parsed string */
148172148655
){
148173148656
int rc;
148174
- rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
148657
+ rc = sqlite3Prepare16(db,zSql,nBytes&~1,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
148175148658
assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148176148659
return rc;
148177148660
}
148178148661
SQLITE_API int sqlite3_prepare16_v3(
148179148662
sqlite3 *db, /* Database handle. */
@@ -148182,11 +148665,11 @@
148182148665
unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
148183148666
sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148184148667
const void **pzTail /* OUT: End of parsed string */
148185148668
){
148186148669
int rc;
148187
- rc = sqlite3Prepare16(db,zSql,nBytes,
148670
+ rc = sqlite3Prepare16(db,zSql,nBytes&~1,
148188148671
SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
148189148672
ppStmt,pzTail);
148190148673
assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148191148674
return rc;
148192148675
}
@@ -148855,11 +149338,11 @@
148855149338
pRight->u3.pOn = 0;
148856149339
pRight->fg.isOn = 1;
148857149340
p->selFlags |= SF_OnToWhere;
148858149341
}
148859149342
148860
- if( IsVirtual(pRightTab) && joinType==EP_OuterON && pRight->u1.pFuncArg ){
149343
+ if( pRight->fg.isTabFunc && joinType==EP_OuterON && pRight->u1.pFuncArg ){
148861149344
p->selFlags |= SF_OnToWhere;
148862149345
}
148863149346
}
148864149347
return 0;
148865149348
}
@@ -149321,10 +149804,52 @@
149321149804
}
149322149805
pSort->nDefer = (u8)nDefer;
149323149806
*ppExtra = pExtra;
149324149807
}
149325149808
#endif
149809
+
149810
+#ifdef SQLITE_DEBUG
149811
+/*
149812
+** This is a byte-code validation check that only runs when SQLITE_DEBUG
149813
+** is defined. This routine looks backwards through the bytecode
149814
+** for the definition of cursor with index iCur. It extracts the KeyInfo from
149815
+** that cursor (it must be an index cursor) and verifies that the cursor
149816
+** does not use any collating seqeuences other than BINARY for its first
149817
+** nCol columns.
149818
+**
149819
+** This routine is used inside of an assert(). So it should return true
149820
+** on success and false if the invariant is not satisfied.
149821
+**
149822
+** tag-202607231411
149823
+*/
149824
+static int sqlite3CursorBloomable(Parse *pParse, int iCur, int nCol){
149825
+ int i,k;
149826
+ Vdbe *v = pParse->pVdbe;
149827
+ if( pParse->nErr ) return 1;
149828
+ assert( v );
149829
+ for(k=sqlite3VdbeCurrentAddr(v)-1; k>0; k--){
149830
+ const VdbeOp *pOp = sqlite3VdbeGetOp(v, k);
149831
+ const KeyInfo *pKeyInfo;
149832
+ if( pOp->p1!=iCur ) continue;
149833
+ if( pOp->opcode!=OP_OpenRead
149834
+ && pOp->opcode!=OP_OpenWrite
149835
+ && pOp->opcode!=OP_OpenEphemeral
149836
+ ){
149837
+ continue;
149838
+ }
149839
+ assert( pOp->p4type==P4_KEYINFO );
149840
+ pKeyInfo = (const KeyInfo*)pOp->p4.pKeyInfo;
149841
+ assert( pKeyInfo!=0 );
149842
+ for(i=0; i<nCol; i++){
149843
+ assert( sqlite3IsBinary(pKeyInfo->aColl[i]) );
149844
+ }
149845
+ return 1;
149846
+ }
149847
+ return 0;
149848
+}
149849
+#endif /* SQLITE_DEBUG */
149850
+
149326149851
149327149852
/*
149328149853
** This routine generates the code for the inside of the inner loop
149329149854
** of a SELECT.
149330149855
**
@@ -149592,10 +150117,11 @@
149592150117
assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
149593150118
sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
149594150119
r1, pDest->zAffSdst, nResultCol);
149595150120
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
149596150121
if( pDest->iSDParm2 ){
150122
+ assert( sqlite3CursorBloomable(pParse,iParm,nResultCol) );
149597150123
sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
149598150124
regResult, nResultCol);
149599150125
ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
149600150126
}
149601150127
sqlite3ReleaseTempReg(pParse, r1);
@@ -151401,10 +151927,11 @@
151401151927
sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
151402151928
r1, pDest->zAffSdst, pIn->nSdst);
151403151929
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
151404151930
pIn->iSdst, pIn->nSdst);
151405151931
if( pDest->iSDParm2>0 ){
151932
+ assert( sqlite3CursorBloomable(pParse, pDest->iSDParm, pIn->nSdst) );
151406151933
sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
151407151934
pIn->iSdst, pIn->nSdst);
151408151935
ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
151409151936
}
151410151937
sqlite3ReleaseTempReg(pParse, r1);
@@ -155350,11 +155877,12 @@
155350155877
assert( ExprUseXList(pExpr) );
155351155878
if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
155352155879
if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
155353155880
if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
155354155881
pFrom = p->pSrc->a;
155355
- if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */
155882
+ if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */
155883
+ if( (p->selFlags & SF_Correlated)!=0 ) return 0; /* Not a correlated subq */
155356155884
pSub = pFrom->u4.pSubq->pSelect;
155357155885
if( pSub->pPrior==0 ) return 0; /* Must be a compound */
155358155886
if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
155359155887
do{
155360155888
if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
@@ -157581,12 +158109,13 @@
157581158109
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
157582158110
if( !IN_RENAME_OBJECT ){
157583158111
if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
157584158112
if( !noErr ){
157585158113
sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
158114
+ }else if( db->init.busy ){
158115
+ sqlite3ErrorMsg(pParse,""); /* Err msg generated by corruptSchema() */
157586158116
}else{
157587
- assert( !db->init.busy );
157588158117
sqlite3CodeVerifySchema(pParse, iDb);
157589158118
VVA_ONLY( pParse->ifNotExists = 1; )
157590158119
}
157591158120
goto trigger_cleanup;
157592158121
}
@@ -161225,10 +161754,11 @@
161225161754
SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){
161226161755
HashElem *pThis, *pNext;
161227161756
#ifdef SQLITE_ENABLE_API_ARMOR
161228161757
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161229161758
#endif
161759
+ sqlite3_mutex_enter(db->mutex);
161230161760
for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
161231161761
Module *pMod = (Module*)sqliteHashData(pThis);
161232161762
pNext = sqliteHashNext(pThis);
161233161763
if( azNames ){
161234161764
int ii;
@@ -161235,10 +161765,11 @@
161235161765
for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
161236161766
if( azNames[ii]!=0 ) continue;
161237161767
}
161238161768
createModule(db, pMod->zName, 0, 0, 0);
161239161769
}
161770
+ sqlite3_mutex_leave(db->mutex);
161240161771
return SQLITE_OK;
161241161772
}
161242161773
161243161774
/*
161244161775
** Decrement the reference count on a Module object. Destroy the
@@ -161803,10 +162334,12 @@
161803162334
char *zErr = 0;
161804162335
rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
161805162336
if( rc!=SQLITE_OK ){
161806162337
sqlite3ErrorMsg(pParse, "%s", zErr);
161807162338
pParse->rc = rc;
162339
+ }else{
162340
+ sqlite3MarkAllShadowTablesOf(db, pTab);
161808162341
}
161809162342
sqlite3DbFree(db, zErr);
161810162343
}
161811162344
161812162345
return rc;
@@ -163082,14 +163615,11 @@
163082163615
SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
163083163616
SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
163084163617
SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
163085163618
SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
163086163619
SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
163087
-
163088
-
163089
-
163090
-
163620
+SQLITE_PRIVATE int sqlite3WhereLoopBloomable(const WhereLoop*);
163091163621
163092163622
/*
163093163623
** Bitmasks for the operators on WhereTerm objects. These are all
163094163624
** operators that are of interest to the query planner. An
163095163625
** OR-ed combination of these values can be used when searching for
@@ -164554,10 +165084,11 @@
164554165084
testcase( pTerm->wtFlags & TERM_VIRTUAL );
164555165085
regRowid = sqlite3GetTempReg(pParse);
164556165086
regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
164557165087
sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
164558165088
VdbeCoverage(pParse->pVdbe);
165089
+ assert( sqlite3WhereLoopBloomable(pLoop) );
164559165090
sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
164560165091
addrNxt, regRowid, 1);
164561165092
VdbeCoverage(pParse->pVdbe);
164562165093
}else{
164563165094
u16 nEq = pLoop->u.btree.nEq;
@@ -164567,10 +165098,11 @@
164567165098
assert( pLoop->wsFlags & WHERE_INDEXED );
164568165099
assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
164569165100
r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
164570165101
codeApplyAffinity(pParse, r1, nEq, zStartAff);
164571165102
sqlite3DbFree(pParse->db, zStartAff);
165103
+ assert( sqlite3WhereLoopBloomable(pLoop) );
164572165104
sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
164573165105
addrNxt, r1, nEq);
164574165106
VdbeCoverage(pParse->pVdbe);
164575165107
}
164576165108
pLevel->regFilter = 0;
@@ -165170,10 +165702,11 @@
165170165702
if( regBignull ){
165171165703
sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
165172165704
VdbeComment((v, "NULL-scan pass ctr"));
165173165705
}
165174165706
if( pLevel->regFilter ){
165707
+ assert( sqlite3WhereLoopBloomable(pLoop) );
165175165708
sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
165176165709
regBase, nEq);
165177165710
VdbeCoverage(v);
165178165711
filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
165179165712
}
@@ -165907,12 +166440,14 @@
165907166440
jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
165908166441
VdbeCoverage(v);
165909166442
VdbeComment((v, "match against %s", pTab->zName));
165910166443
sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r);
165911166444
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
165912
- sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
165913
- sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
166445
+ if( pRJ->regBloom ){
166446
+ sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
166447
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
166448
+ }
165914166449
sqlite3VdbeJumpHere(v, jmp1);
165915166450
sqlite3ReleaseTempRange(pParse, r, nPk+1);
165916166451
}
165917166452
165918166453
/* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -166060,11 +166595,11 @@
166060166595
WHERE_RIGHT_JOIN, 0);
166061166596
if( pSubWInfo ){
166062166597
int iCur = pLevel->iTabCur;
166063166598
int r = ++pParse->nMem;
166064166599
int nPk;
166065
- int jmp;
166600
+ int jmp = 0;
166066166601
int addrCont = sqlite3WhereContinueLabel(pSubWInfo);
166067166602
Table *pTab = pTabItem->pSTab;
166068166603
if( HasRowid(pTab) ){
166069166604
sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
166070166605
nPk = 1;
@@ -166076,15 +166611,17 @@
166076166611
for(iPk=0; iPk<nPk; iPk++){
166077166612
int iCol = pPk->aiColumn[iPk];
166078166613
sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
166079166614
}
166080166615
}
166081
- jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
166082
- VdbeCoverage(v);
166616
+ if( pRJ->regBloom ){
166617
+ jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
166618
+ VdbeCoverage(v);
166619
+ }
166083166620
sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
166084166621
VdbeCoverage(v);
166085
- sqlite3VdbeJumpHere(v, jmp);
166622
+ if( jmp ) sqlite3VdbeJumpHere(v, jmp);
166086166623
sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
166087166624
sqlite3WhereEnd(pSubWInfo);
166088166625
}
166089166626
sqlite3ExprDelete(pParse->db, pSubWhere);
166090166627
ExplainQueryPlanPop(pParse);
@@ -167001,33 +167538,62 @@
167001167538
}
167002167539
}
167003167540
}
167004167541
}
167005167542
167006
- /* At this point, okToChngToIN is true if original pTerm satisfies
167007
- ** case 1. In that case, construct a new virtual term that is
167008
- ** pTerm converted into an IN operator.
167543
+ /* At this point, okToChngToIN is true if original pTerm is a
167544
+ ** candidate to satisfy case 1, though we are not yet certain that
167545
+ ** the collating sequences are all compatible. Try to construct a
167546
+ ** new virtual term that is pTerm converted from an OR operator
167547
+ ** into an IN operator.
167548
+ **
167549
+ ** During construction, verify that the collating sequences on all
167550
+ ** subterms of the OR are compatible. Omit the construction of the
167551
+ ** new IN operator if there are any collating sequence mismatches.
167009167552
*/
167010167553
if( okToChngToIN ){
167011167554
Expr *pDup; /* A transient duplicate expression */
167012167555
ExprList *pList = 0; /* The RHS of the IN operator */
167013167556
Expr *pLeft = 0; /* The LHS of the IN operator */
167557
+ CollSeq *pCollSeq = 0; /* Collating sequence to use */
167014167558
Expr *pNew; /* The complete IN operator */
167015167559
167016167560
for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
167561
+ Expr *pThis;
167017167562
if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
167018167563
assert( pOrTerm->eOperator & WO_EQ );
167019167564
assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
167020167565
assert( pOrTerm->leftCursor==iCursor );
167021167566
assert( pOrTerm->u.x.leftColumn==iColumn );
167022
- pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
167567
+ pThis = pOrTerm->pExpr;
167568
+ pDup = sqlite3ExprDup(db, pThis->pRight, 0);
167023167569
pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
167024
- pLeft = pOrTerm->pExpr->pLeft;
167570
+ if( pLeft==0 ){
167571
+ pLeft = pThis->pLeft;
167572
+ pCollSeq = sqlite3ExprCompareCollSeq(pParse, pThis);
167573
+ }else{
167574
+ assert( 0==sqlite3ExprCompare(pParse,
167575
+ sqlite3ExprSkipCollate(pThis->pLeft),
167576
+ sqlite3ExprSkipCollate(pLeft), -1) );
167577
+ if( pCollSeq!=sqlite3ExprCompareCollSeq(pParse, pThis) ){
167578
+ pLeft = 0; /* Collating sequence mismatch */
167579
+ break;
167580
+ }
167581
+ }
167025167582
}
167026
- assert( pLeft!=0 );
167027
- pDup = sqlite3ExprDup(db, pLeft, 0);
167028
- pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
167583
+ if( pLeft==0 ){
167584
+ pNew = 0; /* Collating sequence mismatch */
167585
+ }else{
167586
+ pDup = sqlite3ExprDup(db, pLeft, 0);
167587
+ if( sqlite3ExprCollSeq(pParse, pDup)!=pCollSeq
167588
+ && ALWAYS(pCollSeq!=0)
167589
+ ){
167590
+ assert( pCollSeq->zName!=0 );
167591
+ pDup = sqlite3ExprAddCollateString(pParse, pDup, pCollSeq->zName);
167592
+ }
167593
+ pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
167594
+ }
167029167595
if( pNew ){
167030167596
int idxNew;
167031167597
transferJoinMarkings(pNew, pExpr);
167032167598
assert( ExprUseXList(pNew) );
167033167599
pNew->x.pList = pList;
@@ -168006,10 +168572,14 @@
168006168572
Expr *pColRef;
168007168573
Expr *pTerm;
168008168574
if( pItem->fg.isTabFunc==0 ) return;
168009168575
pTab = pItem->pSTab;
168010168576
assert( pTab!=0 );
168577
+ if( !IsVirtual(pTab) ){
168578
+ sqlite3ErrorMsg(pParse, "'%s' is not a function", pItem->zName);
168579
+ return;
168580
+ }
168011168581
pArgs = pItem->u1.pFuncArg;
168012168582
if( pArgs==0 ) return;
168013168583
for(j=k=0; j<pArgs->nExpr; j++){
168014168584
Expr *pRhs;
168015168585
u32 joinType;
@@ -168039,10 +168609,20 @@
168039168609
}
168040168610
sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
168041168611
whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
168042168612
}
168043168613
}
168614
+
168615
+/*
168616
+** Return true if the WhereLoop pLoop can be use a Bloom filter.
168617
+** tag-202607231411
168618
+*/
168619
+SQLITE_PRIVATE int sqlite3WhereLoopBloomable(const WhereLoop *pLoop){
168620
+ if( pLoop->wsFlags & WHERE_IPK ) return 1;
168621
+ if( NEVER((pLoop->wsFlags & WHERE_INDEXED)==0) ) return 0;
168622
+ return sqlite3IndexBloomable(pLoop->u.btree.pIndex, pLoop->u.btree.nEq);
168623
+}
168044168624
168045168625
/************** End of whereexpr.c *******************************************/
168046168626
/************** Begin file where.c *******************************************/
168047168627
/*
168048168628
** 2001 September 15
@@ -169051,11 +169631,11 @@
169051169631
WhereLoop *pLoop; /* The Loop object */
169052169632
char *zNotUsed; /* Extra space on the end of pIdx */
169053169633
Bitmask idxCols; /* Bitmap of columns used for indexing */
169054169634
Bitmask extraCols; /* Bitmap of additional columns */
169055169635
u8 sentWarning = 0; /* True if a warning has been issued */
169056
- u8 useBloomFilter = 0; /* True to also add a Bloom filter */
169636
+ u8 useBloomFilter = 1; /* True to also add a Bloom filter */
169057169637
Expr *pPartial = 0; /* Partial Index Expression */
169058169638
int iContinue = 0; /* Jump here to skip excluded rows */
169059169639
SrcList *pTabList; /* The complete FROM clause */
169060169640
SrcItem *pSrc; /* The FROM clause term to get the next index */
169061169641
int addrCounter = 0; /* Address where integer counter is initialized */
@@ -169178,22 +169758,17 @@
169178169758
Expr *pX = pTerm->pExpr;
169179169759
idxCols |= cMask;
169180169760
pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
169181169761
pColl = sqlite3ExprCompareCollSeq(pParse, pX);
169182169762
assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
169763
+ if( !sqlite3IsBinary(pColl) ){
169764
+ /* Disallow the use of a Bloom filter if any non-BINARY collating
169765
+ ** sequence is involved. tag-202607231411 */
169766
+ useBloomFilter = 0;
169767
+ }
169183169768
pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
169184169769
n++;
169185
- if( ALWAYS(pX->pLeft!=0)
169186
- && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
169187
- ){
169188
- /* TUNING: only use a Bloom filter on an automatic index
169189
- ** if one or more key columns has the ability to hold numeric
169190
- ** values, since strings all have the same hash in the Bloom
169191
- ** filter implementation and hence a Bloom filter on a text column
169192
- ** is not usually helpful. */
169193
- useBloomFilter = 1;
169194
- }
169195169770
}
169196169771
}
169197169772
}
169198169773
assert( (u32)n==pLoop->u.btree.nEq );
169199169774
@@ -169259,10 +169834,11 @@
169259169834
regRecord = sqlite3GetTempReg(pParse);
169260169835
regBase = sqlite3GenerateIndexKey(
169261169836
pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
169262169837
);
169263169838
if( pLevel->regFilter ){
169839
+ assert( sqlite3WhereLoopBloomable(pLoop) );
169264169840
sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
169265169841
regBase, pLoop->u.btree.nEq);
169266169842
}
169267169843
sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
169268169844
sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
@@ -169374,10 +169950,11 @@
169374169950
if( sz<10000 ){
169375169951
sz = 10000;
169376169952
}else if( sz>10000000 ){
169377169953
sz = 10000000;
169378169954
}
169955
+ assert( sqlite3WhereLoopBloomable(pLoop) );
169379169956
sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
169380169957
169381169958
addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
169382169959
pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
169383169960
for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
@@ -169396,10 +169973,11 @@
169396169973
}else{
169397169974
Index *pIdx = pLoop->u.btree.pIndex;
169398169975
int n = pLoop->u.btree.nEq;
169399169976
int r1 = sqlite3GetTempRange(pParse, n);
169400169977
int jj;
169978
+ assert( pIdx!=0 );
169401169979
for(jj=0; jj<n; jj++){
169402169980
assert( pIdx->pTable==pItem->pSTab );
169403169981
sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
169404169982
}
169405169983
sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
@@ -173052,11 +173630,11 @@
173052173630
}
173053173631
#ifndef SQLITE_OMIT_VIRTUALTABLE
173054173632
if( IsVirtual(pItem->pSTab) ){
173055173633
SrcItem *p;
173056173634
for(p=&pItem[1]; p<pEnd; p++){
173057
- if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
173635
+ if( (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
173058173636
mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
173059173637
}
173060173638
}
173061173639
rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
173062173640
}else
@@ -174682,23 +175260,21 @@
174682175260
Table *pTab = pItem->pSTab;
174683175261
if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
174684175262
pTab->tabFlags |= TF_MaybeReanalyze;
174685175263
if( i>=1
174686175264
&& (pLoop->wsFlags & reqFlags)==reqFlags
174687
- /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
174688
- && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
175265
+ && sqlite3WhereLoopBloomable(pLoop)
175266
+ && nSearch > pTab->nRowLogEst
174689175267
){
174690
- if( nSearch > pTab->nRowLogEst ){
174691
- testcase( pItem->fg.jointype & JT_LEFT );
174692
- pLoop->wsFlags |= WHERE_BLOOMFILTER;
174693
- pLoop->wsFlags &= ~WHERE_IDX_ONLY;
174694
- WHERETRACE(0xffffffff, (
174695
- "-> use Bloom-filter on loop %c because there are ~%.1e "
174696
- "lookups into %s which has only ~%.1e rows\n",
174697
- pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
174698
- (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
174699
- }
175268
+ testcase( pItem->fg.jointype & JT_LEFT );
175269
+ pLoop->wsFlags |= WHERE_BLOOMFILTER;
175270
+ pLoop->wsFlags &= ~WHERE_IDX_ONLY;
175271
+ WHERETRACE(0xffffffff, (
175272
+ "-> use Bloom-filter on loop %c because there are ~%.1e "
175273
+ "lookups into %s which has only ~%.1e rows\n",
175274
+ pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
175275
+ (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
174700175276
}
174701175277
nSearch += pLoop->nOut;
174702175278
}
174703175279
}
174704175280
@@ -175432,26 +176008,31 @@
175432176008
}
175433176009
sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
175434176010
(u8*)&colUsed, P4_INT64);
175435176011
}
175436176012
#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
176013
+#ifdef SQLITE_ENABLE_CURSOR_HINTS
176014
+ if( HasRowid(pTab) ){
176015
+ sqlite3VdbeAddOp3(v, OP_CursorHint, iIndexCur, 0, pTabItem->iCursor);
176016
+ }
176017
+#endif
175437176018
}
175438176019
}
175439176020
if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
175440176021
if( (pTabItem->fg.jointype & JT_RIGHT)!=0
175441176022
&& (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
175442176023
){
175443176024
WhereRightJoin *pRJ = pLevel->pRJ;
176025
+ int bBloomable = 0;
175444176026
pRJ->iMatch = pParse->nTab++;
175445
- pRJ->regBloom = ++pParse->nMem;
175446
- sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
175447176027
pRJ->regReturn = ++pParse->nMem;
175448176028
sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
175449176029
assert( pTab==pTabItem->pSTab );
175450176030
if( HasRowid(pTab) ){
175451176031
KeyInfo *pInfo;
175452176032
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
176033
+ bBloomable = 1;
175453176034
pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
175454176035
if( pInfo ){
175455176036
pInfo->aColl[0] = 0;
175456176037
pInfo->aSortFlags[0] = 0;
175457176038
sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
@@ -175458,10 +176039,17 @@
175458176039
}
175459176040
}else{
175460176041
Index *pPk = sqlite3PrimaryKeyIndex(pTab);
175461176042
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
175462176043
sqlite3VdbeSetP4KeyInfo(pParse, pPk);
176044
+ bBloomable = sqlite3IndexBloomable(pPk,pPk->nKeyCol);
176045
+ }
176046
+ if( bBloomable ){
176047
+ pRJ->regBloom = ++pParse->nMem;
176048
+ sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
176049
+ }else{
176050
+ pRJ->regBloom = 0;
175463176051
}
175464176052
pLoop->wsFlags &= ~WHERE_IDX_ONLY;
175465176053
/* The nature of RIGHT JOIN processing is such that it messes up
175466176054
** the output order. So omit any ORDER BY/GROUP BY elimination
175467176055
** optimizations. We need to do an actual sort for RIGHT JOIN. */
@@ -176155,11 +176743,11 @@
176155176743
case SQLITE_INTEGER:
176156176744
iVal = sqlite3_value_int64(apArg[1]);
176157176745
break;
176158176746
case SQLITE_FLOAT: {
176159176747
double fVal = sqlite3_value_double(apArg[1]);
176160
- if( ((i64)fVal)!=fVal ) goto error_out;
176748
+ if( sqlite3RealToI64(fVal)!=fVal ) goto error_out;
176161176749
iVal = (i64)fVal;
176162176750
break;
176163176751
}
176164176752
default:
176165176753
goto error_out;
@@ -186803,67 +187391,64 @@
186803187391
SQLITE_API char *sqlite3_data_directory = 0;
186804187392
186805187393
/*
186806187394
** Initialize SQLite.
186807187395
**
186808
-** This routine must be called to initialize the memory allocation,
186809
-** VFS, and mutex subsystems prior to doing any serious work with
186810
-** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
187396
+** The sqlite3_initialize() routine must be called to initialize the
187397
+** memory allocation, VFS, and mutex subsystems prior to doing any
187398
+** serious work. As long as you do not compile with SQLITE_OMIT_AUTOINIT
186811187399
** this routine will be called automatically by key routines such as
186812187400
** sqlite3_open().
186813187401
**
186814187402
** This routine is a no-op except on its very first call for the process,
186815
-** or for the first call after a call to sqlite3_shutdown.
187403
+** or for the first call after a call to sqlite3_shutdown. Most calls
187404
+** to sqlite3_initialize() are, in fact, no-ops. For that reason, the
187405
+** routine is broken into two pieces:
186816187406
**
186817
-** The first thread to call this routine runs the initialization to
186818
-** completion. If subsequent threads call this routine before the first
187407
+** sqlite3Initialize() Does the actual work of initialization
187408
+**
187409
+** sqlite3_initialize() Checks to see if initialization is needed
187410
+** and invokes sqlite3Initialize() if it is.
187411
+**
187412
+** The sqlite3_initialize() interface is called frequently, but
187413
+** sqlite3Initialize() runs rarely. The function is broken up this way
187414
+** to avoid wasting CPU cycles with unnecessary stack setup for local
187415
+** variables in cases where it is not needed.
187416
+**
187417
+** The first thread to call sqlite3_initialize() runs the initialization to
187418
+** completion. If subsequent threads call sqlite3_initialize() before the first
186819187419
** thread has finished the initialization process, then the subsequent
186820187420
** threads must block until the first thread finishes with the initialization.
186821187421
**
186822187422
** The first thread might call this routine recursively. Recursive
186823187423
** calls to this routine should not block, of course. Otherwise the
186824187424
** initialization process would never complete.
186825187425
**
186826
-** Let X be the first thread to enter this routine. Let Y be some other
186827
-** thread. Then while the initial invocation of this routine by X is
186828
-** incomplete, it is required that:
187426
+** Let X be the first thread to enter sqlite3_initialize(). Let Y be some
187427
+** other thread. While the initial invocation of sqlite3_initialize() by X
187428
+** is incomplete, it is required that:
186829187429
**
186830
-** * Calls to this routine from Y must block until the outer-most
187430
+** * Calls to sqlite3_initialize() from Y must block until the outer-most
186831187431
** call by X completes.
186832187432
**
186833
-** * Recursive calls to this routine from thread X return immediately
186834
-** without blocking.
187433
+** * Recursive calls to sqlite3_initialize() from thread X return
187434
+** immediately without blocking.
186835187435
*/
186836
-SQLITE_API int sqlite3_initialize(void){
186837
- MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
186838
- int rc; /* Result code */
187436
+static SQLITE_NOINLINE int sqlite3Initialize(void){
187437
+ MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
187438
+ int rc; /* Result code */
186839187439
#ifdef SQLITE_EXTRA_INIT
186840
- int bRunExtraInit = 0; /* Extra initialization needed */
186841
-#endif
186842
-
186843
-#ifdef SQLITE_OMIT_WSD
186844
- rc = sqlite3_wsd_init(4096, 24);
186845
- if( rc!=SQLITE_OK ){
186846
- return rc;
186847
- }
187440
+ int bRunExtraInit = 0; /* Extra initialization needed */
186848187441
#endif
186849187442
186850187443
/* If the following assert() fails on some obscure processor/compiler
186851
- ** combination, the work-around is to set the correct pointer
186852
- ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
187444
+ ** combination to warn that SQLite has been mis-compiled. If you hit
187445
+ ** this assert(), that means you need to recompile with the
187446
+ ** -DSQLITE_PTRSIZE=n compile-time option to set the correct pointer size.
187447
+ */
186853187448
assert( SQLITE_PTRSIZE==sizeof(char*) );
186854187449
186855
- /* If SQLite is already completely initialized, then this call
186856
- ** to sqlite3_initialize() should be a no-op. But the initialization
186857
- ** must be complete. So isInit must not be set until the very end
186858
- ** of this routine.
186859
- */
186860
- if( sqlite3GlobalConfig.isInit ){
186861
- sqlite3MemoryBarrier();
186862
- return SQLITE_OK;
186863
- }
186864
-
186865187450
/* Make sure the mutex subsystem is initialized. If unable to
186866187451
** initialize the mutex subsystem, return early with the error.
186867187452
** If the system is so sick that we are unable to allocate a mutex,
186868187453
** there is not much SQLite is going to be able to do.
186869187454
**
@@ -187003,10 +187588,30 @@
187003187588
int SQLITE_EXTRA_INIT(const char*);
187004187589
rc = SQLITE_EXTRA_INIT(0);
187005187590
}
187006187591
#endif
187007187592
return rc;
187593
+}
187594
+SQLITE_API int sqlite3_initialize(void){
187595
+ /* If this build does not support writable static data (WSD) natively
187596
+ ** then we have to invoke the (application-supplied) WSD initialization
187597
+ ** routine before doing anything else. */
187598
+#ifdef SQLITE_OMIT_WSD
187599
+ rc = sqlite3_wsd_init(4096, 24);
187600
+ if( rc!=SQLITE_OK ){
187601
+ return rc;
187602
+ }
187603
+#endif
187604
+
187605
+ if( sqlite3GlobalConfig.isInit ){
187606
+ /* SQLite has already been initialized. Fast early-out. */
187607
+ sqlite3MemoryBarrier();
187608
+ return SQLITE_OK;
187609
+ }else{
187610
+ /* Invoke sqlite3Initialize() to do the actual work. */
187611
+ return sqlite3Initialize();
187612
+ }
187008187613
}
187009187614
187010187615
/*
187011187616
** Undo the effects of sqlite3_initialize(). Must not be called while
187012187617
** there are outstanding database connections or memory allocations or
@@ -187755,17 +188360,21 @@
187755188360
187756188361
/*
187757188362
** Return the ROWID of the most recent insert
187758188363
*/
187759188364
SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
188365
+ i64 iRet;
187760188366
#ifdef SQLITE_ENABLE_API_ARMOR
187761188367
if( !sqlite3SafetyCheckOk(db) ){
187762188368
(void)SQLITE_MISUSE_BKPT;
187763188369
return 0;
187764188370
}
187765188371
#endif
187766
- return db->lastRowid;
188372
+ sqlite3_mutex_enter(db->mutex);
188373
+ iRet = db->lastRowid;
188374
+ sqlite3_mutex_leave(db->mutex);
188375
+ return iRet;
187767188376
}
187768188377
187769188378
/*
187770188379
** Set the value returned by the sqlite3_last_insert_rowid() API function.
187771188380
*/
@@ -187784,33 +188393,41 @@
187784188393
/*
187785188394
** Return the number of changes in the most recently executed DML
187786188395
** statement.
187787188396
*/
187788188397
SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3 *db){
188398
+ i64 iRet;
187789188399
#ifdef SQLITE_ENABLE_API_ARMOR
187790188400
if( !sqlite3SafetyCheckOk(db) ){
187791188401
(void)SQLITE_MISUSE_BKPT;
187792188402
return 0;
187793188403
}
187794188404
#endif
187795
- return db->nChange;
188405
+ sqlite3_mutex_enter(db->mutex);
188406
+ iRet = db->nChange;
188407
+ sqlite3_mutex_leave(db->mutex);
188408
+ return iRet;
187796188409
}
187797188410
SQLITE_API int sqlite3_changes(sqlite3 *db){
187798188411
return (int)sqlite3_changes64(db);
187799188412
}
187800188413
187801188414
/*
187802188415
** Return the number of changes since the database handle was opened.
187803188416
*/
187804188417
SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
188418
+ i64 iRet;
187805188419
#ifdef SQLITE_ENABLE_API_ARMOR
187806188420
if( !sqlite3SafetyCheckOk(db) ){
187807188421
(void)SQLITE_MISUSE_BKPT;
187808188422
return 0;
187809188423
}
187810188424
#endif
187811
- return db->nTotalChange;
188425
+ sqlite3_mutex_enter(db->mutex);
188426
+ iRet = db->nTotalChange;
188427
+ sqlite3_mutex_leave(db->mutex);
188428
+ return iRet;
187812188429
}
187813188430
SQLITE_API int sqlite3_total_changes(sqlite3 *db){
187814188431
return (int)sqlite3_total_changes64(db);
187815188432
}
187816188433
@@ -188489,10 +189106,11 @@
188489189106
*/
188490189107
SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
188491189108
#ifdef SQLITE_ENABLE_API_ARMOR
188492189109
if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
188493189110
#endif
189111
+ sqlite3_mutex_enter(db->mutex);
188494189112
if( ms>0 ){
188495189113
sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
188496189114
(void*)db);
188497189115
db->busyTimeout = ms;
188498189116
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
@@ -188499,10 +189117,11 @@
188499189117
db->setlkTimeout = ms;
188500189118
#endif
188501189119
}else{
188502189120
sqlite3_busy_handler(db, 0, 0);
188503189121
}
189122
+ sqlite3_mutex_leave(db->mutex);
188504189123
return SQLITE_OK;
188505189124
}
188506189125
188507189126
/*
188508189127
** Set the setlk timeout value.
@@ -189404,13 +190023,15 @@
189404190023
/*
189405190024
** Return the byte offset of the most recent error
189406190025
*/
189407190026
SQLITE_API int sqlite3_error_offset(sqlite3 *db){
189408190027
int iOffset = -1;
189409
- if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
190028
+ if( db && sqlite3SafetyCheckSickOrOk(db) ){
189410190029
sqlite3_mutex_enter(db->mutex);
189411
- iOffset = db->errByteOffset;
190030
+ if( db->errCode ){
190031
+ iOffset = db->errByteOffset;
190032
+ }
189412190033
sqlite3_mutex_leave(db->mutex);
189413190034
}
189414190035
return iOffset;
189415190036
}
189416190037
@@ -189460,29 +190081,47 @@
189460190081
/*
189461190082
** Return the most recent error code generated by an SQLite routine. If NULL is
189462190083
** passed to this function, we assume a malloc() failed during sqlite3_open().
189463190084
*/
189464190085
SQLITE_API int sqlite3_errcode(sqlite3 *db){
189465
- if( db && !sqlite3SafetyCheckSickOrOk(db) ){
190086
+ int iRet;
190087
+ if( !db ) return SQLITE_NOMEM_BKPT;
190088
+ if( !sqlite3SafetyCheckSickOrOk(db) ){
189466190089
return SQLITE_MISUSE_BKPT;
189467190090
}
189468
- if( !db || db->mallocFailed ){
189469
- return SQLITE_NOMEM_BKPT;
190091
+ sqlite3_mutex_enter(db->mutex);
190092
+ if( db->mallocFailed ){
190093
+ iRet = SQLITE_NOMEM_BKPT;
190094
+ }else{
190095
+ iRet = db->errCode & db->errMask;
189470190096
}
189471
- return db->errCode & db->errMask;
190097
+ sqlite3_mutex_leave(db->mutex);
190098
+ return iRet;
189472190099
}
189473190100
SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
189474
- if( db && !sqlite3SafetyCheckSickOrOk(db) ){
190101
+ int iRet;
190102
+ if( !db ) return SQLITE_NOMEM_BKPT;
190103
+ if( !sqlite3SafetyCheckSickOrOk(db) ){
189475190104
return SQLITE_MISUSE_BKPT;
189476190105
}
189477
- if( !db || db->mallocFailed ){
189478
- return SQLITE_NOMEM_BKPT;
190106
+ sqlite3_mutex_enter(db->mutex);
190107
+ if( db->mallocFailed ){
190108
+ iRet = SQLITE_NOMEM_BKPT;
190109
+ }else{
190110
+ iRet = db->errCode;
189479190111
}
189480
- return db->errCode;
190112
+ sqlite3_mutex_leave(db->mutex);
190113
+ return iRet;
189481190114
}
189482190115
SQLITE_API int sqlite3_system_errno(sqlite3 *db){
189483
- return db ? db->iSysErrno : 0;
190116
+ int iRet = 0;
190117
+ if( db ){
190118
+ sqlite3_mutex_enter(db->mutex);
190119
+ iRet = db->iSysErrno;
190120
+ sqlite3_mutex_leave(db->mutex);
190121
+ }
190122
+ return iRet;
189484190123
}
189485190124
189486190125
/*
189487190126
** Return a string that describes the kind of error specified in the
189488190127
** argument. For now, this simply calls the internal sqlite3ErrStr()
@@ -189585,10 +190224,11 @@
189585190224
SQLITE_MAX_LIKE_PATTERN_LENGTH,
189586190225
SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
189587190226
SQLITE_MAX_TRIGGER_DEPTH,
189588190227
SQLITE_MAX_WORKER_THREADS,
189589190228
SQLITE_MAX_PARSER_DEPTH,
190229
+ SQLITE_MAX_SCHEMA,
189590190230
};
189591190231
189592190232
/*
189593190233
** Make sure the hard limits are set to reasonable values
189594190234
*/
@@ -189667,25 +190307,28 @@
189667190307
assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
189668190308
SQLITE_MAX_LIKE_PATTERN_LENGTH );
189669190309
assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
189670190310
assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
189671190311
assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
189672
- assert( SQLITE_LIMIT_PARSER_DEPTH==(SQLITE_N_LIMIT-1) );
190312
+ assert( aHardLimit[SQLITE_LIMIT_SCHEMA]==SQLITE_MAX_SCHEMA );
190313
+ assert( SQLITE_LIMIT_SCHEMA==(SQLITE_N_LIMIT-1) );
189673190314
189674190315
189675190316
if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
189676190317
return -1;
189677190318
}
190319
+ sqlite3_mutex_enter(db->mutex);
189678190320
oldLimit = db->aLimit[limitId];
189679190321
if( newLimit>=0 ){ /* IMP: R-52476-28732 */
189680190322
if( newLimit>aHardLimit[limitId] ){
189681190323
newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
189682190324
}else if( newLimit<SQLITE_MIN_LENGTH && limitId==SQLITE_LIMIT_LENGTH ){
189683190325
newLimit = SQLITE_MIN_LENGTH;
189684190326
}
189685190327
db->aLimit[limitId] = newLimit;
189686190328
}
190329
+ sqlite3_mutex_leave(db->mutex);
189687190330
return oldLimit; /* IMP: R-53341-35419 */
189688190331
}
189689190332
189690190333
/*
189691190334
** This function is used to parse both URIs and non-URI filenames passed by the
@@ -189724,22 +190367,22 @@
189724190367
int rc = SQLITE_OK;
189725190368
unsigned int flags = *pFlags;
189726190369
const char *zVfs = zDefaultVfs;
189727190370
char *zFile;
189728190371
char c;
189729
- int nUri = sqlite3Strlen30(zUri);
190372
+ i64 nUri = strlen(zUri);
189730190373
189731190374
assert( *pzErrMsg==0 );
189732190375
189733190376
if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
189734190377
|| AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
189735190378
&& nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
189736190379
){
189737190380
char *zOpt;
189738190381
int eState; /* Parser state when parsing URI */
189739
- int iIn; /* Input character index */
189740
- int iOut = 0; /* Output character index */
190382
+ i64 iIn; /* Input character index */
190383
+ i64 iOut = 0; /* Output character index */
189741190384
u64 nByte = nUri+8; /* Bytes of space to allocate */
189742190385
189743190386
/* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
189744190387
** method that there may be extra parameters following the file-name. */
189745190388
flags |= SQLITE_OPEN_URI;
@@ -189769,11 +190412,11 @@
189769190412
if( zUri[5]=='/' && zUri[6]=='/' ){
189770190413
iIn = 7;
189771190414
while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
189772190415
if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
189773190416
*pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
189774
- iIn-7, &zUri[7]);
190417
+ (int)(iIn-7), &zUri[7]);
189775190418
rc = SQLITE_ERROR;
189776190419
goto parse_uri_out;
189777190420
}
189778190421
}
189779190422
#endif
@@ -189844,15 +190487,15 @@
189844190487
189845190488
/* Check if there were any options specified that should be interpreted
189846190489
** here. Options that are interpreted here include "vfs" and those that
189847190490
** correspond to flags that may be passed to the sqlite3_open_v2()
189848190491
** method. */
189849
- zOpt = &zFile[sqlite3Strlen30(zFile)+1];
190492
+ zOpt = &zFile[strlen(zFile)+1];
189850190493
while( zOpt[0] ){
189851
- int nOpt = sqlite3Strlen30(zOpt);
190494
+ i64 nOpt = strlen(zOpt);
189852190495
char *zVal = &zOpt[nOpt+1];
189853
- int nVal = sqlite3Strlen30(zVal);
190496
+ i64 nVal = strlen(zVal);
189854190497
189855190498
if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
189856190499
zVfs = zVal;
189857190500
}else{
189858190501
struct OpenMode {
@@ -189894,11 +190537,11 @@
189894190537
if( aMode ){
189895190538
int i;
189896190539
int mode = 0;
189897190540
for(i=0; aMode[i].z; i++){
189898190541
const char *z = aMode[i].z;
189899
- if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
190542
+ if( nVal==(i64)strlen(z) && 0==memcmp(zVal, z, nVal) ){
189900190543
mode = aMode[i].mode;
189901190544
break;
189902190545
}
189903190546
}
189904190547
if( mode==0 ){
@@ -190579,17 +191222,21 @@
190579191222
** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
190580191223
** by default. Autocommit is disabled by a BEGIN statement and reenabled
190581191224
** by the next COMMIT or ROLLBACK.
190582191225
*/
190583191226
SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
191227
+ int iRet;
190584191228
#ifdef SQLITE_ENABLE_API_ARMOR
190585191229
if( !sqlite3SafetyCheckOk(db) ){
190586191230
(void)SQLITE_MISUSE_BKPT;
190587191231
return 0;
190588191232
}
190589191233
#endif
190590
- return db->autoCommit;
191234
+ sqlite3_mutex_enter(db->mutex);
191235
+ iRet = db->autoCommit;
191236
+ sqlite3_mutex_leave(db->mutex);
191237
+ return iRet;
190591191238
}
190592191239
190593191240
/*
190594191241
** The following routines are substitutes for constants SQLITE_CORRUPT,
190595191242
** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
@@ -191610,21 +192257,23 @@
191610192257
/*
191611192258
** Return the name of the N-th database schema. Return NULL if N is out
191612192259
** of range.
191613192260
*/
191614192261
SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N){
192262
+ const char *zRet = 0;
191615192263
#ifdef SQLITE_ENABLE_API_ARMOR
191616192264
if( !sqlite3SafetyCheckOk(db) ){
191617192265
(void)SQLITE_MISUSE_BKPT;
191618192266
return 0;
191619192267
}
191620192268
#endif
191621
- if( N<0 || N>=db->nDb ){
191622
- return 0;
191623
- }else{
191624
- return db->aDb[N].zDbSName;
192269
+ sqlite3_mutex_enter(db->mutex);
192270
+ if( N>=0 && N<db->nDb ){
192271
+ zRet = db->aDb[N].zDbSName;
191625192272
}
192273
+ sqlite3_mutex_leave(db->mutex);
192274
+ return zRet;
191626192275
}
191627192276
191628192277
/*
191629192278
** Return the filename of the database associated with a database
191630192279
** connection.
@@ -197602,10 +198251,11 @@
197602198251
}else{
197603198252
int nDistance;
197604198253
char *p1;
197605198254
char *p2;
197606198255
char *aOut;
198256
+ i64 nAlloc = (i64)nPoslist*2 + FTS3_BUFFER_PADDING;
197607198257
197608198258
if( nMaxUndeferred>iPrev ){
197609198259
p1 = aPoslist;
197610198260
p2 = pPhrase->doclist.pList;
197611198261
nDistance = nMaxUndeferred - iPrev;
@@ -197613,11 +198263,11 @@
197613198263
p1 = pPhrase->doclist.pList;
197614198264
p2 = aPoslist;
197615198265
nDistance = iPrev - nMaxUndeferred;
197616198266
}
197617198267
197618
- aOut = (char *)sqlite3Fts3MallocZero(((i64)nPoslist)+FTS3_BUFFER_PADDING);
198268
+ aOut = (char *)sqlite3Fts3MallocZero(nAlloc);
197619198269
if( !aOut ){
197620198270
sqlite3_free(aPoslist);
197621198271
return SQLITE_NOMEM;
197622198272
}
197623198273
@@ -207898,11 +208548,11 @@
207898208548
if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
207899208549
sqlite3_reset(pSelect);
207900208550
return FTS_CORRUPT_VTAB;
207901208551
}
207902208552
207903
- pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
208553
+ pWriter->nLeafEst = (int)(((iEnd - iStart)+1)/FTS_MAX_APPENDABLE_HEIGHT);
207904208554
pWriter->iStart = iStart;
207905208555
pWriter->iEnd = iEnd;
207906208556
pWriter->iAbsLevel = iAbsLevel;
207907208557
pWriter->iIdx = iIdx;
207908208558
@@ -210015,12 +210665,12 @@
210015210665
210016210666
/* If there is insufficient space allocated at StrBuffer.z, use realloc()
210017210667
** to grow the buffer until so that it is big enough to accommodate the
210018210668
** appended data.
210019210669
*/
210020
- if( pStr->n+nAppend+1>=pStr->nAlloc ){
210021
- sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
210670
+ if( (i64)pStr->n+(i64)nAppend+1>=(i64)pStr->nAlloc ){
210671
+ i64 nAlloc = pStr->nAlloc+(i64)nAppend+100;
210022210672
char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
210023210673
if( !zNew ){
210024210674
return SQLITE_NOMEM;
210025210675
}
210026210676
pStr->z = zNew;
@@ -213118,11 +213768,11 @@
213118213768
/*
213119213769
** Expand pParse->aBlob so that it holds at least N bytes.
213120213770
**
213121213771
** Return the number of errors.
213122213772
*/
213123
-static int jsonBlobExpand(JsonParse *pParse, u32 N){
213773
+static int jsonBlobExpand(JsonParse *pParse, u64 N){
213124213774
u8 *aNew;
213125213775
u64 t;
213126213776
assert( N>pParse->nBlobAlloc );
213127213777
if( pParse->nBlobAlloc==0 ){
213128213778
t = 100;
@@ -213146,11 +213796,11 @@
213146213796
**
213147213797
** Return true on success. Return false on OOM.
213148213798
*/
213149213799
static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){
213150213800
u8 *aOld;
213151
- u32 nSize;
213801
+ u64 nSize;
213152213802
assert( !pParse->bReadOnly );
213153213803
if( pParse->oom ) return 0;
213154213804
if( pParse->nBlobAlloc>0 ) return 1;
213155213805
aOld = pParse->aBlob;
213156213806
nSize = pParse->nBlob + nExtra;
@@ -213167,11 +213817,11 @@
213167213817
*/
213168213818
static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte(
213169213819
JsonParse *pParse,
213170213820
u8 c
213171213821
){
213172
- jsonBlobExpand(pParse, pParse->nBlob+1);
213822
+ jsonBlobExpand(pParse, (u64)pParse->nBlob+1);
213173213823
if( pParse->oom==0 ){
213174213824
assert( pParse->nBlob+1<=pParse->nBlobAlloc );
213175213825
pParse->aBlob[pParse->nBlob++] = c;
213176213826
}
213177213827
}
@@ -213194,11 +213844,11 @@
213194213844
JsonParse *pParse,
213195213845
u8 eType,
213196213846
u64 szPayload,
213197213847
const void *aPayload
213198213848
){
213199
- if( jsonBlobExpand(pParse, pParse->nBlob+szPayload+9) ) return;
213849
+ if( jsonBlobExpand(pParse, (u64)pParse->nBlob+(u64)szPayload+9) ) return;
213200213850
jsonBlobAppendNode(pParse, eType, szPayload, aPayload);
213201213851
}
213202213852
213203213853
213204213854
/* Append a node type byte together with the payload size and
@@ -213284,11 +213934,11 @@
213284213934
}else{
213285213935
nNeeded = 4;
213286213936
}
213287213937
delta = nNeeded - nExtra;
213288213938
if( delta ){
213289
- u32 newSize = pParse->nBlob + delta;
213939
+ u64 newSize = (u64)pParse->nBlob + delta;
213290213940
if( delta>0 ){
213291213941
if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){
213292213942
return 0; /* OOM error. Error state recorded in pParse->oom. */
213293213943
}
213294213944
a = &pParse->aBlob[i];
@@ -214220,11 +214870,12 @@
214220214870
u32 k = 0;
214221214871
const char *zIn = (const char*)&pParse->aBlob[i+n];
214222214872
if( sz==0 ) goto malformed_jsonb;
214223214873
if( zIn[0]=='-' ){
214224214874
jsonAppendChar(pOut, '-');
214225
- k++;
214875
+ if( sz<=1 ) goto malformed_jsonb;
214876
+ k = 1;
214226214877
}
214227214878
if( zIn[k]=='.' ){
214228214879
jsonAppendChar(pOut, '0');
214229214880
}
214230214881
for(; k<sz; k++){
@@ -214631,11 +215282,11 @@
214631215282
){
214632215283
return;
214633215284
}
214634215285
if( d!=0 ){
214635215286
if( pParse->nBlob + d > pParse->nBlobAlloc ){
214636
- jsonBlobExpand(pParse, pParse->nBlob+d);
215287
+ jsonBlobExpand(pParse, (u64)pParse->nBlob+d);
214637215288
if( pParse->oom ) return;
214638215289
}
214639215290
memmove(&pParse->aBlob[iDel+nIns],
214640215291
&pParse->aBlob[iDel+nDel],
214641215292
pParse->nBlob - (iDel+nDel));
@@ -215418,12 +216069,11 @@
215418216069
jsonBlobAppendNode(pParse, JSONB_TEXTRAW, nJson, zJson);
215419216070
}
215420216071
break;
215421216072
}
215422216073
case SQLITE_FLOAT: {
215423
- double r = sqlite3_value_double(pArg);
215424
- if( NEVER(sqlite3IsNaN(r)) ){
216074
+ if( NEVER(sqlite3IsNaN(sqlite3_value_double(pArg))) ){
215425216075
jsonBlobAppendNode(pParse, JSONB_NULL, 0, 0);
215426216076
}else{
215427216077
int n = sqlite3_value_bytes(pArg);
215428216078
const char *z = (const char*)sqlite3_value_text(pArg);
215429216079
if( z==0 ) return 1;
@@ -217184,11 +217834,13 @@
217184217834
*/
217185217835
static int jsonSkipLabel(JsonEachCursor *p){
217186217836
if( p->eType==JSONB_OBJECT ){
217187217837
u32 sz = 0;
217188217838
u32 n = jsonbPayloadSize(&p->sParse, p->i, &sz);
217189
- return p->i + n + sz;
217839
+ sz += p->i + n;
217840
+ if( sz >= p->sParse.nBlob ) sz = p->i;
217841
+ return sz;
217190217842
}else{
217191217843
return p->i;
217192217844
}
217193217845
}
217194217846
@@ -218016,11 +218668,11 @@
218016218668
int mxLevel; /* iLevel value for root of the tree */
218017218669
RtreeSearchPoint *aPoint; /* Priority queue for search points */
218018218670
sqlite3_stmt *pReadAux; /* Statement to read aux-data */
218019218671
RtreeSearchPoint sPoint; /* Cached next search point */
218020218672
RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
218021
- u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
218673
+ u32 anQueue[RTREE_MAX_DEPTH+2]; /* Number of queued entries by iLevel */
218022218674
};
218023218675
218024218676
/* Return the Rtree of a RtreeCursor */
218025218677
#define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
218026218678
@@ -218499,11 +219151,11 @@
218499219151
** are the leaves, and so on. If the depth as specified on the root node
218500219152
** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
218501219153
*/
218502219154
if( rc==SQLITE_OK && pNode && iNode==1 ){
218503219155
pRtree->iDepth = readInt16(pNode->zData);
218504
- if( pRtree->iDepth>RTREE_MAX_DEPTH ){
219156
+ if( pRtree->iDepth>=RTREE_MAX_DEPTH ){
218505219157
rc = SQLITE_CORRUPT_VTAB;
218506219158
RTREE_IS_CORRUPT(pRtree);
218507219159
}
218508219160
}
218509219161
@@ -226154,31 +226806,31 @@
226154226806
int lenSrc, /* Length of the source file */
226155226807
const char *zDelta, /* Delta to apply to the pattern */
226156226808
int lenDelta, /* Length of the delta */
226157226809
char *zOut /* Write the output into this preallocated buffer */
226158226810
){
226159
- unsigned int limit;
226160
- unsigned int total = 0;
226811
+ sqlite3_uint64 limit;
226812
+ sqlite3_uint64 total = 0;
226161226813
#if RBU_ENABLE_DELTA_CKSUM
226162226814
char *zOrigOut = zOut;
226163226815
#endif
226164226816
226165226817
limit = rbuDeltaGetInt(&zDelta, &lenDelta);
226166226818
if( lenDelta<=0 || *zDelta!='\n' ){
226167226819
/* ERROR: size integer not terminated by "\n" */
226168226820
return -1;
226169226821
}
226170
- zDelta++; lenDelta--;
226171
- while( *zDelta && lenDelta>0 ){
226822
+ zDelta++; lenDelta--; /* Skip the \n */
226823
+ while( lenDelta>0 && zDelta[0] ){
226172226824
unsigned int cnt, ofst;
226173226825
cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
226174226826
if( lenDelta<=0 ) return -1;
226175226827
switch( zDelta[0] ){
226176226828
case '@': {
226177226829
zDelta++; lenDelta--;
226178226830
ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
226179
- if( lenDelta>0 || zDelta[0]!=',' ){
226831
+ if( lenDelta>0 && zDelta[0]!=',' ){
226180226832
/* ERROR: copy command not terminated by ',' */
226181226833
return -1;
226182226834
}
226183226835
zDelta++; lenDelta--;
226184226836
total += cnt;
@@ -226199,11 +226851,11 @@
226199226851
total += cnt;
226200226852
if( total>limit ){
226201226853
/* ERROR: insert command gives an output larger than predicted */
226202226854
return -1;
226203226855
}
226204
- if( (i64)cnt>(i64)lenDelta ){
226856
+ if( cnt>lenDelta ){
226205226857
/* ERROR: insert count exceeds size of delta */
226206226858
return -1;
226207226859
}
226208226860
memcpy(zOut, zDelta, cnt);
226209226861
zOut += cnt;
@@ -228212,17 +228864,17 @@
228212228864
char *zWhere = rbuObjIterGetWhere(p, pIter);
228213228865
char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
228214228866
char *zUpdate = 0;
228215228867
228216228868
pUp->zMask = (char*)&pUp[1];
228217
- memcpy(pUp->zMask, zMask, pIter->nTblCol);
228218228869
pUp->pNext = pIter->pRbuUpdate;
228219228870
pIter->pRbuUpdate = pUp;
228220228871
228221228872
if( zSet ){
228222228873
const char *zPrefix = "";
228223
-
228874
+ assert( p->rc==SQLITE_OK );
228875
+ memcpy(pUp->zMask, zMask, pIter->nTblCol);
228224228876
if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
228225228877
zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
228226228878
zPrefix, pIter->zTbl, zSet, zWhere
228227228879
);
228228228880
p->rc = prepareFreeAndCollectError(
@@ -228308,10 +228960,13 @@
228308228960
pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
228309228961
break;
228310228962
228311228963
case RBU_STATE_ROW:
228312228964
pRet->nRow = sqlite3_column_int(pStmt, 1);
228965
+ if( pRet->nRow<0 ){
228966
+ rc = SQLITE_CORRUPT;
228967
+ }
228313228968
break;
228314228969
228315228970
case RBU_STATE_PROGRESS:
228316228971
pRet->nProgress = sqlite3_column_int64(pStmt, 1);
228317228972
break;
@@ -234473,11 +235128,11 @@
234473235128
SessionBuffer *p,
234474235129
const char *zStr,
234475235130
int *pRc
234476235131
){
234477235132
int nStr = sqlite3Strlen30(zStr);
234478
- if( 0==sessionBufferGrow(p, nStr+1, pRc) ){
235133
+ if( 0==sessionBufferGrow(p, (i64)nStr+1, pRc) ){
234479235134
memcpy(&p->aBuf[p->nBuf], zStr, nStr);
234480235135
p->nBuf += nStr;
234481235136
p->aBuf[p->nBuf] = 0x00;
234482235137
}
234483235138
}
@@ -239557,11 +240212,16 @@
239557240212
int nRec;
239558240213
int rc = SQLITE_OK;
239559240214
239560240215
pIter->in.bNoDiscard = 1;
239561240216
while( SQLITE_ROW==(sessionChangesetNext(pIter, &aRec, &nRec, 0)) ){
239562
- rc = sessionOneChangeIterToHash(pGrp, pIter, bRebase);
240217
+ if( bRebase && pIter->bPatchset ){
240218
+ /* A patchset may not be used as a rebase */
240219
+ rc = SQLITE_ERROR;
240220
+ }else{
240221
+ rc = sessionOneChangeIterToHash(pGrp, pIter, bRebase);
240222
+ }
239563240223
if( rc!=SQLITE_OK ) break;
239564240224
}
239565240225
239566240226
if( rc==SQLITE_OK ) rc = pIter->rc;
239567240227
return rc;
@@ -239875,18 +240535,21 @@
239875240535
int nCol, /* Number of columns in each record */
239876240536
u8 *a1, int n1, /* Record 1 */
239877240537
u8 *a2, int n2, /* Record 2 */
239878240538
int *pRc /* IN/OUT: error code */
239879240539
){
239880
- sessionBufferGrow(pBuf, n1+n2, pRc);
240540
+ u8 *a1Eof = &a1[n1];
240541
+ u8 *a2Eof = &a2[n2];
240542
+
240543
+ sessionBufferGrow(pBuf, (i64)n1+n2, pRc);
239881240544
if( *pRc==SQLITE_OK ){
239882240545
int i;
239883240546
u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
239884240547
for(i=0; i<nCol; i++){
239885
- int nn1 = sessionSerialLen(a1);
239886
- int nn2 = sessionSerialLen(a2);
239887
- if( *a1==0 || *a1==0xFF ){
240548
+ int nn1 = (a1<a1Eof ? sessionSerialLen(a1) : 0);
240549
+ int nn2 = (a2<a2Eof ? sessionSerialLen(a2) : 0);
240550
+ if( nn1==0 || (nn2>0 && (*a1==0 || *a1==0xFF)) ){
239888240551
memcpy(pOut, a2, nn2);
239889240552
pOut += nn2;
239890240553
}else{
239891240554
memcpy(pOut, a1, nn1);
239892240555
pOut += nn1;
@@ -239924,24 +240587,25 @@
239924240587
sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
239925240588
u8 *aRec, int nRec, /* Local change */
239926240589
u8 *aChange, int nChange, /* Record to rebase against */
239927240590
int *pRc /* IN/OUT: Return Code */
239928240591
){
239929
- sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
240592
+ sessionBufferGrow(pBuf, (i64)2+nRec+nChange, pRc);
239930240593
if( *pRc==SQLITE_OK ){
239931240594
int bData = 0;
239932240595
u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
239933240596
int i;
239934240597
u8 *a1 = aRec;
239935240598
u8 *a2 = aChange;
240599
+ u8 *a2Eof = &a2[nChange];
239936240600
239937240601
*pOut++ = SQLITE_UPDATE;
239938240602
*pOut++ = pIter->bIndirect;
239939240603
for(i=0; i<pIter->nCol; i++){
239940240604
int n1 = sessionSerialLen(a1);
239941
- int n2 = sessionSerialLen(a2);
239942
- if( pIter->abPK[i] || a2[0]==0 ){
240605
+ int n2 = (a2>=a2Eof) ? 0 : sessionSerialLen(a2);
240606
+ if( n2<=0 || pIter->abPK[i] || a2[0]==0 ){
239943240607
if( !pIter->abPK[i] && a1[0] ) bData = 1;
239944240608
memcpy(pOut, a1, n1);
239945240609
pOut += n1;
239946240610
}else if( a2[0]!=0xFF && a1[0] ){
239947240611
bData = 1;
@@ -240138,12 +240802,12 @@
240138240802
*/
240139240803
SQLITE_API int sqlite3rebaser_configure(
240140240804
sqlite3_rebaser *p,
240141240805
int nRebase, const void *pRebase
240142240806
){
240143
- sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
240144240807
int rc; /* Return code */
240808
+ sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
240145240809
rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
240146240810
if( rc==SQLITE_OK ){
240147240811
rc = sessionChangesetToHash(pIter, &p->grp, 1);
240148240812
}
240149240813
sqlite3changeset_finalize(pIter);
@@ -250965,10 +251629,11 @@
250965251629
i64 szData = (sizeof(Fts5Data) + 7) & ~7;
250966251630
i64 nAlloc = szData + nByte + FTS5_DATA_PADDING;
250967251631
pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
250968251632
if( pRet ){
250969251633
pRet->nn = nByte;
251634
+ pRet->szLeaf = 0;
250970251635
aOut = pRet->p = (u8*)pRet + szData;
250971251636
}else{
250972251637
rc = SQLITE_NOMEM;
250973251638
}
250974251639
@@ -250977,14 +251642,12 @@
250977251642
}
250978251643
if( rc!=SQLITE_OK ){
250979251644
sqlite3_free(pRet);
250980251645
pRet = 0;
250981251646
}else{
250982
- /* TODO1: Fix this */
250983251647
pRet->p[nByte] = 0x00;
250984251648
pRet->p[nByte+1] = 0x00;
250985
- pRet->szLeaf = fts5GetU16(&pRet->p[2]);
250986251649
}
250987251650
}
250988251651
p->rc = rc;
250989251652
p->nRead++;
250990251653
}
@@ -251001,13 +251664,21 @@
251001251664
*/
251002251665
static void fts5DataRelease(Fts5Data *pData){
251003251666
sqlite3_free(pData);
251004251667
}
251005251668
251669
+/*
251670
+** Read a leaf-page record. This is similar to fts5DataRead(), except that
251671
+** it fills in the Fts5Data.szLeaf value before returning.
251672
+*/
251006251673
static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
251007251674
Fts5Data *pRet = fts5DataRead(p, iRowid);
251008251675
if( pRet ){
251676
+ assert( pRet->szLeaf==0 );
251677
+ if( pRet->nn>=4 ){
251678
+ pRet->szLeaf = fts5GetU16(&pRet->p[2]);
251679
+ }
251009251680
if( pRet->szLeaf<4 || pRet->szLeaf>pRet->nn ){
251010251681
FTS5_CORRUPT_ROWID(p, iRowid);
251011251682
fts5DataRelease(pRet);
251012251683
pRet = 0;
251013251684
}
@@ -252914,10 +253585,14 @@
252914253585
const u8 *a = pIter->pLeaf->p;
252915253586
int iTermOff = 0;
252916253587
252917253588
pIter->iPgidxOff = pIter->pLeaf->szLeaf;
252918253589
pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff);
253590
+ if( iTermOff > pIter->pLeaf->szLeaf ){
253591
+ p->rc = FTS5_CORRUPT;
253592
+ return;
253593
+ }
252919253594
pIter->iLeafOffset = iTermOff;
252920253595
fts5SegIterLoadTerm(p, pIter, 0);
252921253596
fts5SegIterLoadNPos(p, pIter);
252922253597
if( bDlidx ) fts5SegIterLoadDlidx(p, pIter);
252923253598
@@ -255240,19 +255915,19 @@
255240255915
for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
255241255916
i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
255242255917
int iNext = 0;
255243255918
u8 *aPg = 0;
255244255919
255245
- pLeaf = fts5DataRead(p, iRowid);
255920
+ pLeaf = fts5LeafRead(p, iRowid);
255246255921
if( pLeaf==0 ) break;
255247255922
aPg = pLeaf->p;
255248255923
255249255924
iNext = fts5GetU16(&aPg[0]);
255250255925
if( iNext!=0 ){
255251255926
*pbLastInDoclist = 0;
255252255927
}
255253
- if( iNext==0 && pLeaf->szLeaf!=pLeaf->nn ){
255928
+ if( iNext==0 && pLeaf->szLeaf<pLeaf->nn ){
255254255929
fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
255255255930
}
255256255931
255257255932
if( iNext==0 ){
255258255933
/* The page contains no terms or rowids. Replace it with an empty
@@ -255535,19 +256210,19 @@
255535256210
255536256211
assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
255537256212
/* The entry being removed may be the only position list in
255538256213
** its doclist. */
255539256214
for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
255540
- Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
256215
+ Fts5Data *pPg = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
255541256216
int bEmpty = (pPg && pPg->nn==4);
255542256217
fts5DataRelease(pPg);
255543256218
if( bEmpty==0 ) break;
255544256219
}
255545256220
255546256221
if( iPgno==pSeg->iTermLeafPgno ){
255547256222
i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
255548
- Fts5Data *pTerm = fts5DataRead(p, iId);
256223
+ Fts5Data *pTerm = fts5LeafRead(p, iId);
255549256224
if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
255550256225
u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
255551256226
int nTermIdx = pTerm->nn - pTerm->szLeaf;
255552256227
int iTermIdx = 0;
255553256228
i64 iTermOff = 0;
@@ -258495,11 +259170,11 @@
258495259170
int i;
258496259171
258497259172
/* Now check that the iter.nEmpty leaves following the current leaf
258498259173
** (a) exist and (b) contain no terms. */
258499259174
for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
258500
- Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
259175
+ Fts5Data *pLeaf = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
258501259176
if( pLeaf ){
258502259177
if( !fts5LeafIsTermless(pLeaf)
258503259178
|| (i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf))
258504259179
){
258505259180
FTS5_CORRUPT_ROWID(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
@@ -258623,13 +259298,17 @@
258623259298
iRowidOff = fts5LeafFirstRowidOff(pLeaf);
258624259299
if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
258625259300
FTS5_CORRUPT_ROWID(p, iRow);
258626259301
}else{
258627259302
iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
258628
- res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
258629
- if( res==0 ) res = nTerm - nIdxTerm;
258630
- if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow);
259303
+ if( (i64)iOff+(i64)nTerm>(i64)pLeaf->szLeaf ){
259304
+ FTS5_CORRUPT_ROWID(p, iRow);
259305
+ }else{
259306
+ res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
259307
+ if( res==0 ) res = nTerm - nIdxTerm;
259308
+ if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow);
259309
+ }
258631259310
}
258632259311
258633259312
fts5IntegrityCheckPgidx(p, iRow, pLeaf);
258634259313
}
258635259314
fts5DataRelease(pLeaf);
@@ -262347,23 +263026,27 @@
262347263026
Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
262348263027
Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
262349263028
262350263029
if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
262351263030
Fts5Sorter *pSorter = pCsr->pSorter;
262352
- int n;
262353
- if( pSorter ){
262354
- int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
262355
- n = pSorter->aIdx[iPhrase] - i1;
262356
- pIter->a = &pSorter->aPoslist[i1];
263031
+ if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
263032
+ rc = SQLITE_RANGE;
262357263033
}else{
262358
- rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
262359
- }
262360
- if( rc==SQLITE_OK ){
262361
- assert( pIter->a || n==0 );
262362
- pIter->b = (pIter->a ? &pIter->a[n] : 0);
262363
- *piCol = 0;
262364
- fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
263034
+ int n;
263035
+ if( pSorter ){
263036
+ int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
263037
+ n = pSorter->aIdx[iPhrase] - i1;
263038
+ pIter->a = &pSorter->aPoslist[i1];
263039
+ }else{
263040
+ rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
263041
+ }
263042
+ if( rc==SQLITE_OK ){
263043
+ assert( pIter->a || n==0 );
263044
+ pIter->b = (pIter->a ? &pIter->a[n] : 0);
263045
+ *piCol = 0;
263046
+ fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
263047
+ }
262365263048
}
262366263049
}else{
262367263050
int n;
262368263051
rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
262369263052
if( rc==SQLITE_OK ){
@@ -263267,11 +263950,11 @@
263267263950
int nArg, /* Number of args */
263268263951
sqlite3_value **apUnused /* Function arguments */
263269263952
){
263270263953
assert( nArg==0 );
263271263954
UNUSED_PARAM2(nArg, apUnused);
263272
- sqlite3_result_text(pCtx, "fts5: 2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06", -1, SQLITE_TRANSIENT);
263955
+ sqlite3_result_text(pCtx, "fts5: 2026-07-24 16:28:47 2f1f4f73535386549c12694dc57cfe555eec689ae6824c6241aaf8d5befcd74d", -1, SQLITE_TRANSIENT);
263273263956
}
263274263957
263275263958
/*
263276263959
** Implementation of fts5_locale(LOCALE, TEXT) function.
263277263960
**
@@ -263909,38 +264592,35 @@
263909264592
263910264593
if( bCreate ){
263911264594
if( pConfig->eContent==FTS5_CONTENT_NORMAL
263912264595
|| pConfig->eContent==FTS5_CONTENT_UNINDEXED
263913264596
){
263914
- int nDefn = 32 + pConfig->nCol*10;
263915
- char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 20);
263916
- if( zDefn==0 ){
263917
- rc = SQLITE_NOMEM;
263918
- }else{
263919
- int i;
263920
- int iOff;
263921
- sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
263922
- iOff = (int)strlen(zDefn);
263923
- for(i=0; i<pConfig->nCol; i++){
263924
- if( pConfig->eContent==FTS5_CONTENT_NORMAL
263925
- || pConfig->abUnindexed[i]
263926
- ){
263927
- sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
263928
- iOff += (int)strlen(&zDefn[iOff]);
263929
- }
263930
- }
263931
- if( pConfig->bLocale ){
263932
- for(i=0; i<pConfig->nCol; i++){
263933
- if( pConfig->abUnindexed[i]==0 ){
263934
- sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", l%d", i);
263935
- iOff += (int)strlen(&zDefn[iOff]);
263936
- }
263937
- }
263938
- }
263939
- rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
263940
- }
263941
- sqlite3_free(zDefn);
264597
+ int i = 0;
264598
+ char *zDefn = 0;
264599
+ sqlite3_str *pDefn = sqlite3_str_new(pConfig->db);
264600
+
264601
+ sqlite3_str_appendf(pDefn, "id INTEGER PRIMARY KEY");
264602
+ for(i=0; i<pConfig->nCol; i++){
264603
+ if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->abUnindexed[i] ){
264604
+ sqlite3_str_appendf(pDefn, ", c%d", i);
264605
+ }
264606
+ }
264607
+ if( pConfig->bLocale ){
264608
+ for(i=0; i<pConfig->nCol; i++){
264609
+ if( pConfig->abUnindexed[i]==0 ){
264610
+ sqlite3_str_appendf(pDefn, ", l%d", i);
264611
+ }
264612
+ }
264613
+ }
264614
+ zDefn = sqlite3_str_finish(pDefn);
264615
+
264616
+ if( zDefn ){
264617
+ rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
264618
+ sqlite3_free(zDefn);
264619
+ }else{
264620
+ rc = SQLITE_NOMEM;
264621
+ }
263942264622
}
263943264623
263944264624
if( rc==SQLITE_OK && pConfig->bColumnsize ){
263945264625
const char *zCols = "id INTEGER PRIMARY KEY, sz BLOB";
263946264626
if( pConfig->bContentlessDelete ){
263947264627
--- 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 ** 3f3fb9b638f59ad982beafb7c117f24ddd3d 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.54.0"
471 #define SQLITE_VERSION_NUMBER 3054000
472 #define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
473 #define SQLITE_SCM_BRANCH "trunk"
474 #define SQLITE_SCM_TAGS ""
475 #define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
476
477 /*
478 ** CAPI3REF: Run-Time Library Version Numbers
479 ** KEYWORDS: sqlite3_version sqlite3_sourceid
480 **
@@ -3732,11 +3732,11 @@
3732 ** authorizer will fail with an error message explaining that
3733 ** access is denied.
3734 **
3735 ** ^The first parameter to the authorizer callback is a copy of the third
3736 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3737 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
3738 ** the particular action to be authorized. ^The third through sixth parameters
3739 ** to the callback are either NULL pointers or zero-terminated strings
3740 ** that contain additional details about the action to be authorized.
3741 ** Applications must always be prepared to encounter a NULL pointer in any
3742 ** of the third through the sixth parameters of the authorization callback.
@@ -3775,25 +3775,37 @@
3775 ** ^(Only a single authorizer can be in place on a database connection
3776 ** at a time. Each call to sqlite3_set_authorizer overrides the
3777 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3778 ** The authorizer is disabled by default.
3779 **
3780 ** The authorizer callback must not do anything that will modify
 
 
3781 ** the database connection that invoked the authorizer callback.
3782 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3783 ** database connections for the meaning of "modify" in this paragraph.
3784 **
3785 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3786 ** statement might be re-prepared during [sqlite3_step()] due to a
3787 ** schema change. Hence, the application should ensure that the
3788 ** correct authorizer callback remains in place during the [sqlite3_step()].
3789 **
3790 ** ^Note that the authorizer callback is invoked only during
3791 ** [sqlite3_prepare()] or its variants. Authorization is not
3792 ** performed during statement evaluation in [sqlite3_step()], unless
3793 ** as stated in the previous paragraph, sqlite3_step() invokes
3794 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
 
 
 
 
 
 
 
 
 
 
3795 */
3796 SQLITE_API int sqlite3_set_authorizer(
3797 sqlite3*,
3798 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3799 void *pUserData
@@ -3864,12 +3876,17 @@
3864 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3865 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3866 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3867 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3868 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3869 #define SQLITE_COPY 0 /* No longer used */
3870 #define SQLITE_RECURSIVE 33 /* NULL NULL */
 
 
 
 
 
 
3871
3872 /*
3873 ** CAPI3REF: Deprecated Tracing And Profiling Functions
3874 ** DEPRECATED
3875 **
@@ -4734,10 +4751,14 @@
4734 ** nesting depth for separate triggers.</dd>)^
4735 **
4736 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4737 ** <dd>The maximum number of auxiliary worker threads that a single
4738 ** [prepared statement] may start.</dd>)^
 
 
 
 
4739 ** </dl>
4740 */
4741 #define SQLITE_LIMIT_LENGTH 0
4742 #define SQLITE_LIMIT_SQL_LENGTH 1
4743 #define SQLITE_LIMIT_COLUMN 2
@@ -4749,10 +4770,11 @@
4749 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
4750 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
4751 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
4752 #define SQLITE_LIMIT_WORKER_THREADS 11
4753 #define SQLITE_LIMIT_PARSER_DEPTH 12
 
4754
4755 /*
4756 ** CAPI3REF: Prepare Flags
4757 **
4758 ** These constants define various flags that can be passed into the
@@ -4860,10 +4882,12 @@
4860 ** there is a small performance advantage to passing an nByte parameter that
4861 ** is the number of bytes in the input string <i>including</i>
4862 ** the nul-terminator.
4863 ** Note that nByte measures the length of the input in bytes, not
4864 ** characters, even for the UTF-16 interfaces.
 
 
4865 **
4866 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4867 ** past the end of the first SQL statement in zSql. These routines only
4868 ** compile the first statement in zSql, so *pzTail is left pointing to
4869 ** what remains uncompiled.
@@ -5606,11 +5630,11 @@
5606 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5607 ** can be obtained by calling [sqlite3_reset()] on the
5608 ** [prepared statement]. ^In the "v2" interface,
5609 ** the more specific error code is returned directly by sqlite3_step().
5610 **
5611 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5612 ** Perhaps it was called on a [prepared statement] that has
5613 ** already been [sqlite3_finalize | finalized] or on one that had
5614 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5615 ** be the case that the same database connection is being used by two or
5616 ** more threads at the same moment in time.
@@ -6779,11 +6803,15 @@
6779 ** to by the second parameter and which is N bytes long where N is the
6780 ** third parameter.
6781 **
6782 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6783 ** interfaces set the result of the application-defined function to be
6784 ** a BLOB containing all zero bytes and N bytes in size.
 
 
 
 
6785 **
6786 ** ^The sqlite3_result_double() interface sets the result from
6787 ** an application-defined function to be a floating point value specified
6788 ** by its 2nd argument.
6789 **
@@ -9117,12 +9145,12 @@
9117 ** The lifecycle of an sqlite3_str object is as follows:
9118 ** <ol>
9119 ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
9120 ** <li> ^Text is appended to the sqlite3_str object using various
9121 ** methods, such as [sqlite3_str_appendf()].
9122 ** <li> ^The sqlite3_str object is destroyed and the string it created
9123 ** is returned using the [sqlite3_str_finish()] interface.
9124 ** </ol>
9125 */
9126 typedef struct sqlite3_str sqlite3_str;
9127
9128 /*
@@ -9170,10 +9198,44 @@
9170 ** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)).
9171 */
9172 SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
9173 SQLITE_API void sqlite3_str_free(sqlite3_str*);
9174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9175 /*
9176 ** CAPI3REF: Add Content To A Dynamic String
9177 ** METHOD: sqlite3_str
9178 **
9179 ** These interfaces add or remove content to an sqlite3_str object
@@ -14978,10 +15040,37 @@
14978 */
14979 #ifndef SQLITE_MAX_TRIGGER_DEPTH
14980 # define SQLITE_MAX_TRIGGER_DEPTH 1000
14981 #endif
14982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14983 /************** End of sqliteLimit.h *****************************************/
14984 /************** Continuing where we left off in sqliteInt.h ******************/
14985
14986 /* Disable nuisance warnings on Borland compilers */
14987 #if defined(__BORLANDC__)
@@ -15236,11 +15325,13 @@
15236 ** bitmask tests, testcase() can be used to make sure each bit
15237 ** is significant and used at least once. On switch statements
15238 ** where multiple cases go to the same block of code, testcase()
15239 ** can insure that all cases are evaluated.
15240 */
15241 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
 
 
15242 # ifndef SQLITE_AMALGAMATION
15243 extern unsigned int sqlite3CoverageCounter;
15244 # endif
15245 # define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
15246 #else
@@ -17190,11 +17281,11 @@
17190 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
17191 #endif
17192
17193 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
17194 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
17195 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
17196
17197 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
17198
17199 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
17200 ** of the flags shown below.
@@ -17267,16 +17358,23 @@
17267 ** The design of the _RANGE hint is aid b-tree implementations that try
17268 ** to prefetch content from remote machines - to provide those
17269 ** implementations with limits on what needs to be prefetched and thereby
17270 ** reduce network bandwidth.
17271 **
 
 
 
 
 
 
17272 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
17273 ** standard SQLite. The other hints are provided for extensions that use
17274 ** the SQLite parser and code generator but substitute their own storage
17275 ** engine.
17276 */
17277 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
 
17278
17279 /*
17280 ** Values that may be OR'd together to form the argument to the
17281 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
17282 **
@@ -17332,10 +17430,13 @@
17332 #endif
17333 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
17334 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
17335 #ifdef SQLITE_ENABLE_CURSOR_HINTS
17336 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
 
 
 
17337 #endif
17338
17339 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
17340 SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
17341 BtCursor*,
@@ -18573,11 +18674,11 @@
18573
18574 /*
18575 ** The number of different kinds of things that can be limited
18576 ** using the sqlite3_limit() interface.
18577 */
18578 #define SQLITE_N_LIMIT (SQLITE_LIMIT_PARSER_DEPTH+1)
18579
18580 /*
18581 ** Lookaside malloc is a set of fixed-size buffers that can be used
18582 ** to satisfy small transient memory allocation requests for objects
18583 ** associated with a particular database connection. The use of
@@ -20940,16 +21041,16 @@
20940 bft bHasExists :1; /* Has a correlated "EXISTS (SELECT ....)" expression */
20941 bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */
20942 bft bHasWith :1; /* True if statement contains WITH */
20943 bft okConstFactor:1; /* OK to factor out constants */
20944 bft checkSchema :1; /* Causes schema cookie check after an error */
 
20945 int nRangeReg; /* Size of the temporary register block */
20946 int iRangeReg; /* First register in temporary register block */
20947 int nErr; /* Number of errors seen */
20948 int nTab; /* Number of previously allocated VDBE cursors */
20949 int nMem; /* Number of memory cells used so far */
20950 int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
20951 int iSelfTab; /* Table associated with an index on expr, or negative
20952 ** of the base register during check-constraint eval */
20953 int nNestSel; /* Number of nested SELECT statements and/or VIEWs */
20954 int nLabel; /* The *negative* of the number of labels used */
20955 int nLabelAlloc; /* Number of slots in aLabel */
@@ -20964,13 +21065,11 @@
20964 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
20965 u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */
20966 #endif
20967 #ifndef SQLITE_OMIT_SHARED_CACHE
20968 int nTableLock; /* Number of locks in aTableLock */
20969 TableLock *aTableLock; /* Required table locks for shared-cache mode */
20970 #endif
20971 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
20972 Parse *pToplevel; /* Parse structure for main program (or NULL) */
20973 Table *pTriggerTab; /* Table triggers are being coded for */
20974 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
20975 ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */
20976
@@ -20995,10 +21094,17 @@
20995 } cr;
20996 struct { /* These fields available to all other statements */
20997 Returning *pReturning; /* The RETURNING clause */
20998 } d;
20999 } u1;
 
 
 
 
 
 
 
21000
21001 /************************************************************************
21002 ** Above is constant between recursions. Below is reset before and after
21003 ** each recursion. The boundary between these two regions is determined
21004 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
@@ -21942,10 +22048,11 @@
21942 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
21943 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
21944 #endif
21945 #if defined(SQLITE_TEST)
21946 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
 
21947 #endif
21948
21949 #if defined(SQLITE_DEBUG)
21950 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
21951 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
@@ -22166,10 +22273,11 @@
22166 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
22167 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
22168 SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
22169 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
22170 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**);
 
22171 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
22172 Expr*, int, int, u8);
22173 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
22174 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
22175 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
@@ -22528,10 +22636,11 @@
22528 SQLITE_PRIVATE const unsigned char *sqlite3aEQb;
22529 SQLITE_PRIVATE const unsigned char *sqlite3aGTb;
22530 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
22531 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
22532 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 
22533 #ifndef SQLITE_OMIT_WSD
22534 SQLITE_PRIVATE int sqlite3PendingByte;
22535 #endif
22536 #endif /* SQLITE_AMALGAMATION */
22537 #ifdef VDBE_PROFILE
@@ -22630,11 +22739,10 @@
22630 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
22631 SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, i64);
22632 SQLITE_PRIVATE int sqlite3StrAccumEnlargeIfNeeded(StrAccum*, i64);
22633 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
22634 SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);
22635 SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*);
22636 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
22637 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
22638 SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
22639 SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
22640
@@ -23578,10 +23686,13 @@
23578 "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
23579 #endif
23580 #ifdef SQLITE_MAX_PAGE_SIZE
23581 "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
23582 #endif
 
 
 
23583 #ifdef SQLITE_MAX_SCHEMA_RETRY
23584 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
23585 #endif
23586 #ifdef SQLITE_MAX_SQL_LENGTH
23587 "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
@@ -24228,10 +24339,20 @@
24228 ** Hash table for global functions - functions common to all
24229 ** database connections. After initialization, this table is
24230 ** read-only.
24231 */
24232 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 
 
 
 
 
 
 
 
 
 
24233
24234 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
24235 /*
24236 ** Counter used for coverage testing. Does not come into play for
24237 ** release builds.
@@ -26297,10 +26418,53 @@
26297 clearYMD_HMS_TZ(p);
26298 rc = 0;
26299 p->nFloor = 0;
26300 }
26301 break;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26302 }
26303 case 'f': {
26304 /*
26305 ** floor
26306 **
@@ -26400,34 +26564,44 @@
26400 break;
26401 }
26402 case 'w': {
26403 /*
26404 ** weekday N
 
26405 **
26406 ** Move the date to the same time on the next occurrence of
26407 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
26408 ** date is already on the appropriate weekday, this is a no-op.
 
26409 */
26410 if( sqlite3_strnicmp(z, "weekday ", 8)==0
26411 && sqlite3AtoF(&z[8], &r)>0
26412 && r>=0.0 && r<7.0 && (n=(int)r)==r ){
 
 
26413 sqlite3_int64 Z;
26414 computeYMD_HMS(p);
26415 p->tz = 0;
26416 p->validJD = 0;
26417 computeJD(p);
26418 Z = ((p->iJD + 129600000)/86400000) % 7;
26419 if( Z>n ) Z -= 7;
26420 p->iJD += (n - Z)*86400000;
 
 
 
 
26421 clearYMD_HMS_TZ(p);
26422 rc = 0;
26423 }
26424 break;
26425 }
26426 case 's': {
26427 /*
26428 ** start of TTTTT
 
 
26429 **
26430 ** Move the date backwards to the beginning of the current day,
26431 ** or month or year.
26432 **
26433 ** subsecond
@@ -26947,42 +27121,42 @@
26947 ){
26948 DateTime x;
26949 size_t i,j;
26950 sqlite3 *db;
26951 const char *zFmt;
26952 sqlite3_str sRes;
26953
26954
26955 if( argc==0 ) return;
26956 zFmt = (const char*)sqlite3_value_text(argv[0]);
26957 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
26958 db = sqlite3_context_db_handle(context);
26959 sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
26960
26961 computeJD(&x);
26962 computeYMD_HMS(&x);
26963 for(i=j=0; zFmt[i]; i++){
26964 char cf;
26965 if( zFmt[i]!='%' ) continue;
26966 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
26967 i++;
26968 j = i + 1;
26969 cf = zFmt[i];
26970 switch( cf ){
26971 case 'd': /* Fall thru */
26972 case 'e': {
26973 sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D);
26974 break;
26975 }
26976 case 'f': { /* Fractional seconds. (Non-standard) */
26977 double s = x.s;
26978 if( NEVER(s>59.999) ) s = 59.999;
26979 sqlite3_str_appendf(&sRes, "%06.3f", s);
26980 break;
26981 }
26982 case 'F': {
26983 sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
26984 break;
26985 }
26986 case 'G': /* Fall thru */
26987 case 'g': {
26988 DateTime y = x;
@@ -26990,85 +27164,85 @@
26990 /* Move y so that it is the Thursday in the same week as x */
26991 y.iJD += (3 - daysAfterMonday(&x))*86400000;
26992 y.validYMD = 0;
26993 computeYMD(&y);
26994 if( cf=='g' ){
26995 sqlite3_str_appendf(&sRes, "%02d", y.Y%100);
26996 }else{
26997 sqlite3_str_appendf(&sRes, "%04d", y.Y);
26998 }
26999 break;
27000 }
27001 case 'H':
27002 case 'k': {
27003 sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h);
27004 break;
27005 }
27006 case 'I': /* Fall thru */
27007 case 'l': {
27008 int h = x.h;
27009 if( h>12 ) h -= 12;
27010 if( h==0 ) h = 12;
27011 sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h);
27012 break;
27013 }
27014 case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */
27015 sqlite3_str_appendf(&sRes,"%03d",daysAfterJan01(&x)+1);
27016 break;
27017 }
27018 case 'J': { /* Julian day number. (Non-standard) */
27019 sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0);
27020 break;
27021 }
27022 case 'm': {
27023 sqlite3_str_appendf(&sRes,"%02d",x.M);
27024 break;
27025 }
27026 case 'M': {
27027 sqlite3_str_appendf(&sRes,"%02d",x.m);
27028 break;
27029 }
27030 case 'p': /* Fall thru */
27031 case 'P': {
27032 if( x.h>=12 ){
27033 sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2);
27034 }else{
27035 sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2);
27036 }
27037 break;
27038 }
27039 case 'R': {
27040 sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m);
27041 break;
27042 }
27043 case 's': {
27044 if( x.useSubsec ){
27045 sqlite3_str_appendf(&sRes,"%.3f",
27046 (x.iJD - 21086676*(i64)10000000)/1000.0);
27047 }else{
27048 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
27049 sqlite3_str_appendf(&sRes,"%lld",iS);
27050 }
27051 break;
27052 }
27053 case 'S': {
27054 sqlite3_str_appendf(&sRes,"%02d",(int)x.s);
27055 break;
27056 }
27057 case 'T': {
27058 sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
27059 break;
27060 }
27061 case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */
27062 case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */
27063 char c = (char)daysAfterSunday(&x) + '0';
27064 if( c=='0' && cf=='u' ) c = '7';
27065 sqlite3_str_appendchar(&sRes, 1, c);
27066 break;
27067 }
27068 case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */
27069 sqlite3_str_appendf(&sRes,"%02d",
27070 (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7);
27071 break;
27072 }
27073 case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */
27074 DateTime y = x;
@@ -27075,34 +27249,34 @@
27075 /* Adjust y so that is the Thursday in the same week as x */
27076 assert( y.validJD );
27077 y.iJD += (3 - daysAfterMonday(&x))*86400000;
27078 y.validYMD = 0;
27079 computeYMD(&y);
27080 sqlite3_str_appendf(&sRes,"%02d", daysAfterJan01(&y)/7+1);
27081 break;
27082 }
27083 case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */
27084 sqlite3_str_appendf(&sRes,"%02d",
27085 (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7);
27086 break;
27087 }
27088 case 'Y': {
27089 sqlite3_str_appendf(&sRes,"%04d",x.Y);
27090 break;
27091 }
27092 case '%': {
27093 sqlite3_str_appendchar(&sRes, 1, '%');
27094 break;
27095 }
27096 default: {
27097 sqlite3_str_reset(&sRes);
27098 return;
27099 }
27100 }
27101 }
27102 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
27103 sqlite3ResultStrAccum(context, &sRes);
27104 }
27105
27106 /*
27107 ** current_time()
27108 **
@@ -27234,11 +27408,11 @@
27234 clearYMD_HMS_TZ(&d1);
27235 computeYMD_HMS(&d1);
27236 sqlite3StrAccumInit(&sRes, 0, 0, 0, 100);
27237 sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f",
27238 sign, Y, M, d1.D-1, d1.h, d1.m, d1.s);
27239 sqlite3ResultStrAccum(context, &sRes);
27240 }
27241
27242
27243 /*
27244 ** current_timestamp()
@@ -27662,11 +27836,11 @@
27662 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
27663 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
27664 }else{
27665 double r;
27666 rc = pVfs->xCurrentTime(pVfs, &r);
27667 *pTimeOut = (sqlite3_int64)(r*86400000.0);
27668 }
27669 return rc;
27670 }
27671
27672 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
@@ -32612,10 +32786,14 @@
32612 */
32613 #ifndef SQLITE_PRINTF_PRECISION_LIMIT
32614 # define SQLITE_FP_PRECISION_LIMIT 100000000
32615 #endif
32616
 
 
 
 
32617 /*
32618 ** Render a string given by "fmt" into the StrAccum object.
32619 */
32620 SQLITE_API void sqlite3_str_vappendf(
32621 sqlite3_str *pAccum, /* Accumulate results here */
@@ -32622,14 +32800,14 @@
32622 const char *fmt, /* Format string */
32623 va_list ap /* arguments */
32624 ){
32625 int c; /* Next character in the format string */
32626 char *bufpt; /* Pointer to the conversion buffer */
32627 int precision; /* Precision of the current field */
32628 int length; /* Length of the field */
32629 int idx; /* A general purpose loop counter */
32630 int width; /* Width of the current field */
32631 etByte flag_leftjustify; /* True if "-" flag is present */
32632 etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
32633 etByte flag_alternateform; /* True if "#" flag is present */
32634 etByte flag_altform2; /* True if "!" flag is present */
32635 etByte flag_zeropad; /* True if field width constant starts with zero */
@@ -32673,11 +32851,11 @@
32673 fmt = strchr(fmt, '%');
32674 if( fmt==0 ){
32675 fmt = bufpt + strlen(bufpt);
32676 }
32677 #endif
32678 sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
32679 if( *fmt==0 ) break;
32680 }
32681 if( (c=(*++fmt))==0 ){
32682 sqlite3_str_append(pAccum, "%", 1);
32683 break;
@@ -32919,26 +33097,27 @@
32919 do{ /* Convert to ascii */
32920 *(--bufpt) = cset[longvalue%base];
32921 longvalue = longvalue/base;
32922 }while( longvalue>0 );
32923 }
32924 length = (int)(&zOut[nOut-1]-bufpt);
32925 if( precision>length ){ /* zero pad */
32926 int nn = precision-length;
32927 bufpt -= nn;
32928 memset(bufpt,'0',nn);
32929 length = precision;
32930 }
32931 if( cThousand ){
32932 int nn = (length - 1)/3; /* Number of "," to insert */
32933 int ix = (length - 1)%3 + 1;
 
32934 bufpt -= nn;
32935 for(idx=0; nn>0; idx++){
32936 bufpt[idx] = bufpt[idx+nn];
32937 ix--;
32938 if( ix==0 ){
32939 bufpt[++idx] = cThousand;
32940 nn--;
32941 ix = 3;
32942 }
32943 }
32944 }
@@ -32947,11 +33126,11 @@
32947 const char *pre;
32948 char x;
32949 pre = &aPrefix[infop->prefix];
32950 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
32951 }
32952 length = (int)(&zOut[nOut-1]-bufpt);
32953 break;
32954 case etFLOAT:
32955 case etEXP:
32956 case etGENERIC: {
32957 FpDecode s;
@@ -32979,12 +33158,17 @@
32979 iRound = precision+1;
32980 }
32981 sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 20 : 16);
32982 if( s.isSpecial ){
32983 if( s.isSpecial==2 ){
32984 bufpt = flag_zeropad ? "null" : "NaN";
32985 length = sqlite3Strlen30(bufpt);
 
 
 
 
 
32986 break;
32987 }else if( flag_zeropad ){
32988 s.z[0] = '9';
32989 s.iDP = 1000;
32990 s.n = 1;
@@ -32996,11 +33180,11 @@
32996 }else if( flag_prefix ){
32997 buf[0] = flag_prefix;
32998 }else{
32999 bufpt++;
33000 }
33001 length = sqlite3Strlen30(bufpt);
33002 break;
33003 }
33004 }
33005 if( s.sign=='-' ){
33006 if( flag_alternateform
@@ -33152,11 +33336,11 @@
33152 }
33153 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
33154 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
33155 }
33156
33157 length = (int)(bufpt-zOut);
33158 assert( length <= szBufNeeded );
33159 if( length<width ){
33160 i64 nPad = width - length;
33161 if( flag_leftjustify ){
33162 memset(bufpt, ' ', nPad);
@@ -33172,10 +33356,11 @@
33172 }
33173
33174 if( zExtra==0 ){
33175 /* The result is being rendered directory into pAccum. This
33176 ** is the common and fast case */
 
33177 pAccum->nChar += length;
33178 zOut[length] = 0;
33179 continue;
33180 }else{
33181 /* We were unable to render directly into pAccum because we
@@ -33218,14 +33403,14 @@
33218 }
33219 if( precision>1 ){
33220 i64 nPrior = 1;
33221 width -= precision-1;
33222 if( width>1 && !flag_leftjustify ){
33223 sqlite3_str_appendchar(pAccum, width-1, ' ');
33224 width = 0;
33225 }
33226 sqlite3_str_append(pAccum, buf, length);
33227 precision--;
33228 while( precision > 1 ){
33229 i64 nCopyBytes;
33230 if( nPrior > precision-1 ) nPrior = precision - 1;
33231 nCopyBytes = length*nPrior;
@@ -33277,21 +33462,21 @@
33277 ** precision characters */
33278 unsigned char *z = (unsigned char*)bufpt;
33279 while( precision-- > 0 && z[0] ){
33280 SQLITE_SKIP_UTF8(z);
33281 }
33282 length = (int)(z - (unsigned char*)bufpt);
33283 }else{
33284 for(length=0; length<precision && bufpt[length]; length++){}
33285 }
33286 }else{
33287 length = 0x7fffffff & (int)strlen(bufpt);
33288 }
33289 adjust_width_for_utf8:
33290 if( flag_altform2 && width>0 ){
33291 /* Adjust width to account for extra bytes in UTF-8 characters */
33292 int ii = length - 1;
33293 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
33294 }
33295 break;
33296 case etESCAPE_j: /* %j: JSON string literal w/o "..." */
33297 case etESCAPE_J: { /* %J: Generate a JSON string literal */
@@ -33322,11 +33507,11 @@
33322 while( (escarg[px]&0xc0)==0x80 ) px++;
33323 }
33324 }
33325 for(i=j=0; i<px; i++){
33326 if( (ch = ((u8*)escarg)[i])<=0x1f || ch=='"' || ch=='\\' ){
33327 if( j<i ) sqlite3_str_append(pAccum, &escarg[j], i-j);
33328 j = i+1;
33329 if( ch==0 ) break;
33330 sqlite3_str_appendchar(pAccum, 1, '\\');
33331 if( ch>0x1f ){
33332 sqlite3_str_appendchar(pAccum, 1, ch);
@@ -33338,11 +33523,11 @@
33338 sqlite3_str_appendchar(pAccum, 1, aHex[ch>>4]);
33339 sqlite3_str_appendchar(pAccum, 1, aHex[ch&0xf]);
33340 }
33341 }
33342 }
33343 if( j<i ) sqlite3_str_append(pAccum, &escarg[j], i-j);
33344 if( xtype==etESCAPE_J ) sqlite3_str_append(pAccum, "\"", 1);
33345 }
33346 if( width>0 && sqlite3_str_errcode(pAccum)==SQLITE_OK ){
33347 sqlite3_int64 n = sqlite3_str_length(pAccum) - iStart;
33348 sqlite3_int64 len = n;
@@ -33354,11 +33539,11 @@
33354 }
33355 }
33356 if( width>len ){
33357 sqlite3_int64 sp = width-len;
33358 assert( sp>0 && sp<0x7fffffff );
33359 sqlite3_str_appendchar(pAccum, (int)sp, ' ');
33360 if( !flag_leftjustify
33361 && n>0
33362 && sqlite3_str_errcode(pAccum)==0
33363 ){
33364 zz = sqlite3_str_value(pAccum);
@@ -33546,15 +33731,15 @@
33546 ** indicating that width and precision should be expressed in characters,
33547 ** then the values have been translated prior to reaching this point.
33548 */
33549 width -= length;
33550 if( width>0 ){
33551 if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
33552 sqlite3_str_append(pAccum, bufpt, length);
33553 if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
33554 }else{
33555 sqlite3_str_append(pAccum, bufpt, length);
33556 }
33557
33558 if( zExtra ){
33559 sqlite3DbFree(pAccum->db, zExtra);
33560 zExtra = 0;
@@ -33670,10 +33855,17 @@
33670 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
33671 return;
33672 }
33673 while( (N--)>0 ) p->zText[p->nChar++] = c;
33674 }
 
 
 
 
 
 
 
33675
33676 /*
33677 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
33678 ** So enlarge if first, then do the append.
33679 **
@@ -33681,10 +33873,11 @@
33681 ** work (enlarging the buffer) using tail recursion, so that the
33682 ** sqlite3_str_append() routine can use fast calling semantics.
33683 */
33684 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
33685 N = sqlite3StrAccumEnlarge(p, N);
 
33686 if( N>0 ){
33687 memcpy(&p->zText[p->nChar], z, N);
33688 p->nChar += N;
33689 }
33690 }
@@ -33704,10 +33897,24 @@
33704 assert( p->zText );
33705 p->nChar += N;
33706 memcpy(&p->zText[p->nChar-N], z, N);
33707 }
33708 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33709
33710 /*
33711 ** Append the complete text of zero-terminated string z[] to the p string.
33712 */
33713 SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
@@ -33741,41 +33948,15 @@
33741 }
33742 }
33743 return p->zText;
33744 }
33745
33746 /*
33747 ** Use the content of the StrAccum passed as the second argument
33748 ** as the result of an SQL function.
33749 */
33750 SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
33751 if( p->accError ){
33752 sqlite3_result_error_code(pCtx, p->accError);
33753 sqlite3_str_reset(p);
33754 }else if( isMalloced(p) ){
33755 sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
33756 }else{
33757 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
33758 sqlite3_str_reset(p);
33759 }
33760 }
33761
33762 /*
33763 ** This singleton is an sqlite3_str object that is returned if
33764 ** sqlite3_malloc() fails to provide space for a real one. This
33765 ** sqlite3_str object accepts no new text and always returns
33766 ** an SQLITE_NOMEM error.
33767 */
33768 static sqlite3_str sqlite3OomStr = {
33769 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
33770 };
33771
33772 /* Finalize a string created using sqlite3_str_new().
33773 */
33774 SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
33775 char *z;
33776 if( p!=0 && p!=&sqlite3OomStr ){
33777 z = sqlite3StrAccumFinish(p);
33778 sqlite3_free(p);
33779 }else{
33780 z = 0;
33781 }
@@ -33812,10 +33993,12 @@
33812 */
33813 SQLITE_API void sqlite3_str_reset(StrAccum *p){
33814 if( isMalloced(p) ){
33815 sqlite3DbFree(p->db, p->zText);
33816 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
 
 
33817 }
33818 p->nAlloc = 0;
33819 p->nChar = 0;
33820 p->zText = 0;
33821 }
@@ -33823,11 +34006,11 @@
33823 /*
33824 ** Destroy a dynamically allocate sqlite3_str object and all
33825 ** of its content, all in one call.
33826 */
33827 SQLITE_API void sqlite3_str_free(sqlite3_str *p){
33828 if( p!=0 && p!=&sqlite3OomStr ){
33829 sqlite3_str_reset(p);
33830 sqlite3_free(p);
33831 }
33832 }
33833
@@ -33860,11 +34043,11 @@
33860 sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
33861 if( p ){
33862 sqlite3StrAccumInit(p, 0, 0, 0,
33863 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
33864 }else{
33865 p = &sqlite3OomStr;
33866 }
33867 return p;
33868 }
33869
33870 /*
@@ -37500,11 +37683,11 @@
37500 return mState;
37501 }
37502 }
37503 return 0xfffffff0 | mState;
37504 #else
37505 return sqlite3Atoi64(z, pResult, strlen(z), SQLITE_UTF8)==0;
37506 #endif /* SQLITE_OMIT_FLOATING_POINT */
37507 }
37508
37509 /*
37510 ** Digit pairs used to convert a U64 or I64 into text, two digits
@@ -39731,20 +39914,21 @@
39731 i = 0;
39732 j = 0;
39733 while( 1 ){
39734 c = kvvfsHexValue[aIn[i]];
39735 if( c<0 ){
39736 int n = 0;
39737 int mult = 1;
39738 c = aIn[i];
39739 if( c==0 ) break;
39740 while( c>='a' && c<='z' ){
39741 n += (c - 'a')*mult;
 
39742 mult *= 26;
39743 c = aIn[++i];
39744 }
39745 if( j+n>nOut ) return -1;
39746 memset(&aOut[j], 0, n);
39747 j += n;
39748 if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
39749 }else if( j<nOut ){
39750 aOut[j] = c<<4;
@@ -39773,22 +39957,28 @@
39773 static void kvvfsDecodeJournal(
39774 KVVfsFile *pFile, /* Store decoding in pFile->aJrnl */
39775 const char *zTxt, /* Text encoding. Zero-terminated */
39776 int nTxt /* Bytes in zTxt, excluding zero terminator */
39777 ){
39778 unsigned int n = 0;
39779 int c, i, mult;
39780 i = 0;
39781 mult = 1;
39782 while( (c = zTxt[i++])>='a' && c<='z' ){
39783 n += (zTxt[i] - 'a')*mult;
 
 
 
39784 mult *= 26;
 
39785 }
39786 sqlite3_free(pFile->aJrnl);
 
 
 
39787 pFile->aJrnl = sqlite3_malloc64( n );
39788 if( pFile->aJrnl==0 ){
39789 pFile->nJrnl = 0;
39790 return;
39791 }
39792 pFile->nJrnl = n;
39793 n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl);
39794 if( n<pFile->nJrnl ){
@@ -39824,13 +40014,11 @@
39824
39825 SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass,
39826 pFile->isJournal ? "journal" : "db"));
39827 sqlite3_free(pFile->aJrnl);
39828 sqlite3_free(pFile->aData);
39829 #ifdef SQLITE_WASM
39830 memset(pFile, 0, sizeof(*pFile));
39831 #endif
39832 return SQLITE_OK;
39833 }
39834
39835 /*
39836 ** Read from the -journal file.
@@ -39856,10 +40044,11 @@
39856 if( aTxt==0 ) return SQLITE_NOMEM;
39857 rc = sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, "jrnl",
39858 aTxt, szTxt+1);
39859 if( rc>=0 ){
39860 kvvfsDecodeJournal(pFile, aTxt, szTxt);
 
39861 }
39862 sqlite3_free(aTxt);
39863 if( rc ) return rc;
39864 if( pFile->aJrnl==0 ) return SQLITE_IOERR;
39865 }
@@ -40180,11 +40369,11 @@
40180 }
40181 if( !pFile->zClass ){
40182 #ifdef SQLITE_WASM
40183 if( strlen(zName) >= (KVRECORD_KEY_SZ
40184 - 6 /* "kvvfs-" */
40185 - 11 /* "-##########" */) ){
40186 return SQLITE_CANTOPEN;
40187 }
40188 #else
40189 if( 0!=strcmp(zName, "local") && 0!=strcmp(zName, "session") ){
40190 /* Historical naming restriction which journaling depends on. */
@@ -45946,11 +46135,10 @@
45946 i64 nNew /* Required mapping size */
45947 ){
45948 const char *zErr = "mmap";
45949 int h = pFd->h; /* File descriptor open on db file */
45950 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
45951 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
45952 u8 *pNew = 0; /* Location of new mapping */
45953 int flags = PROT_READ; /* Flags to pass to mmap() */
45954
45955 assert( pFd->nFetchOut==0 );
45956 assert( nNew>pFd->mmapSize );
@@ -45964,25 +46152,16 @@
45964 #endif
45965
45966 if( pOrig ){
45967 #if HAVE_MREMAP
45968 i64 nReuse = pFd->mmapSize;
 
 
45969 #else
45970 const int szSyspage = osGetpagesize();
45971 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
45972 #endif
45973 u8 *pReq = &pOrig[nReuse];
45974
45975 /* Unmap any pages of the existing mapping that cannot be reused. */
45976 if( nReuse!=nOrig ){
45977 osMunmap(pReq, nOrig-nReuse);
45978 }
45979
45980 #if HAVE_MREMAP
45981 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
45982 zErr = "mremap";
45983 #else
45984 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
45985 if( pNew!=MAP_FAILED ){
45986 if( pNew!=pReq ){
45987 osMunmap(pNew, nNew - nReuse);
45988 pNew = 0;
@@ -46613,40 +46792,33 @@
46613 verifyDbFile(pNew);
46614 }
46615 return rc;
46616 }
46617
46618 /*
46619 ** Directories to consider for temp files.
46620 */
46621 static const char *azTempDirs[] = {
46622 0,
46623 0,
46624 "/var/tmp",
46625 "/usr/tmp",
46626 "/tmp",
46627 "."
46628 };
46629
46630 /*
46631 ** Initialize first two members of azTempDirs[] array.
46632 */
46633 static void unixTempFileInit(void){
46634 azTempDirs[0] = getenv("SQLITE_TMPDIR");
46635 azTempDirs[1] = getenv("TMPDIR");
46636 }
46637
46638 /*
46639 ** Return the name of a directory in which to put temporary files.
46640 ** If no suitable temporary file directory can be found, return NULL.
 
 
 
 
46641 */
46642 static const char *unixTempFileDir(void){
46643 unsigned int i = 0;
46644 struct stat buf;
46645 const char *zDir = sqlite3_temp_directory;
46646
46647 while(1){
 
 
 
 
 
 
 
 
 
46648 if( zDir!=0
46649 #if OS_VXWORKS
46650 && zDir[0]=='/'
46651 #endif
46652 && osStat(zDir, &buf)==0
@@ -46653,12 +46825,10 @@
46653 && S_ISDIR(buf.st_mode)
46654 && osAccess(zDir, 03)==0
46655 ){
46656 return zDir;
46657 }
46658 if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break;
46659 zDir = azTempDirs[i++];
46660 }
46661 return 0;
46662 }
46663
46664 /*
@@ -48937,13 +49107,10 @@
48937 ** DMS UNIX_SHM_BASE+8 128
48938 */
48939 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
48940 #endif
48941
48942 /* Initialize temp file dir array. */
48943 unixTempFileInit();
48944
48945 return SQLITE_OK;
48946 }
48947
48948 /*
48949 ** Shutdown the operating system interface.
@@ -52221,11 +52388,11 @@
52221 # define sqlite3_win_test_unc_locking 0
52222 #endif
52223
52224 /*
52225 ** Return true if the string passed as the only argument is likely
52226 ** to be a UNC path. Return false if note.
52227 **
52228 ** Return true if:
52229 **
52230 ** (1) The name begins with "\\"
52231 ** (2) But does not begin with "\\?\C:\" where C can be any alphabetic
@@ -55070,26 +55237,27 @@
55070 int iDb;
55071 Btree *pBt;
55072 sqlite3_int64 sz;
55073 int szPage = 0;
55074 sqlite3_stmt *pStmt = 0;
55075 unsigned char *pOut;
55076 char *zSql;
55077 int rc;
55078
55079 #ifdef SQLITE_ENABLE_API_ARMOR
55080 if( !sqlite3SafetyCheckOk(db) ){
55081 (void)SQLITE_MISUSE_BKPT;
55082 return 0;
55083 }
55084 #endif
 
55085
55086 if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
55087 p = memdbFromDbSchema(db, zSchema);
55088 iDb = sqlite3FindDbName(db, zSchema);
55089 if( piSize ) *piSize = -1;
55090 if( iDb<0 ) return 0;
55091 if( p ){
55092 MemStore *pStore = p->pStore;
55093 assert( pStore->pMutex==0 );
55094 if( piSize ) *piSize = pStore->sz;
55095 if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
@@ -55096,23 +55264,21 @@
55096 pOut = pStore->aData;
55097 }else{
55098 pOut = sqlite3_malloc64( pStore->sz );
55099 if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
55100 }
55101 return pOut;
55102 }
55103 pBt = db->aDb[iDb].pBt;
55104 if( pBt==0 ) return 0;
55105 szPage = sqlite3BtreeGetPageSize(pBt);
55106 zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
55107 rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
55108 sqlite3_free(zSql);
55109 if( rc ) return 0;
55110 rc = sqlite3_step(pStmt);
55111 if( rc!=SQLITE_ROW ){
55112 pOut = 0;
55113 }else{
55114 sz = sqlite3_column_int64(pStmt, 0)*szPage;
55115 if( sz==0 ){
55116 sqlite3_reset(pStmt);
55117 sqlite3_exec(db, "BEGIN IMMEDIATE; COMMIT;", 0, 0, 0);
55118 rc = sqlite3_step(pStmt);
@@ -55142,10 +55308,13 @@
55142 }
55143 }
55144 }
55145 }
55146 sqlite3_finalize(pStmt);
 
 
 
55147 return pOut;
55148 }
55149
55150 /* Convert zSchema to a MemDB and initialize its content.
55151 */
@@ -59917,10 +60086,45 @@
59917 static void freeSuperJournal(char *zSuper){
59918 if( zSuper ){
59919 sqlite3_free(&zSuper[-4]);
59920 }
59921 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59922
59923 /*
59924 ** Parameter pJrnl is a file-handle open on a journal file. This function
59925 ** attempts to read a super-journal file name from the end of the journal
59926 ** file. If successful, it sets output parameter (*pzSuper) to point to a
@@ -59955,32 +60159,34 @@
59955 || len>=nSuper
59956 || len>szJ-16
59957 || len==0
59958 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
59959 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
59960 || memcmp(aMagic, aJournalMagic, 8)
59961 ){
59962 return rc;
59963 }
59964
59965 zOut = (char*)sqlite3MallocZero(4 + len + 2);
59966 if( !zOut ){
59967 rc = SQLITE_NOMEM_BKPT;
59968 }else{
59969 zOut = &zOut[4];
59970 if( SQLITE_OK==(rc = sqlite3OsRead(pJrnl, zOut, len, szJ-16-len)) ){
59971 u32 u; /* Unsigned loop counter */
59972 /* See if the checksum matches the super-journal name */
59973 for(u=0; u<len; u++){
59974 cksum -= zOut[u];
59975 }
59976 }
59977 if( rc!=SQLITE_OK || cksum ){
59978 /* If the checksum doesn't add up, then one or more of the disk sectors
59979 ** containing the super-journal filename is corrupted. This means
59980 ** definitely roll back, so just return SQLITE_OK and report a (nul)
59981 ** super-journal filename. */
 
 
 
59982 freeSuperJournal(zOut);
59983 zOut = 0;
59984 }
59985 }
59986
@@ -60359,10 +60565,11 @@
60359 i64 jrnlSize; /* Size of journal file on disk */
60360 u32 cksum = 0; /* Checksum of string zSuper */
60361
60362 assert( pPager->setSuper==0 );
60363 assert( !pagerUseWal(pPager) );
 
60364
60365 if( !zSuper
60366 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
60367 || !isOpen(pPager->jfd)
60368 ){
@@ -61189,10 +61396,23 @@
61189 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
61190 char *zSuperJournal = 0; /* Contents of super-journal file */
61191 i64 nSuperJournal; /* Size of super-journal file */
61192 char *zJournal; /* Pointer to one journal within MJ file */
61193 char *zFree = 0; /* Free this buffer */
 
 
 
 
 
 
 
 
 
 
 
 
 
61194
61195 /* Allocate space for both the pJournal and pSuper file descriptors.
61196 ** If successful, open the super-journal file for reading.
61197 */
61198 pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
@@ -61228,51 +61448,60 @@
61228 zSuperJournal[nSuperJournal] = 0;
61229 zSuperJournal[nSuperJournal+1] = 0;
61230
61231 zJournal = zSuperJournal;
61232 while( (zJournal-zSuperJournal)<nSuperJournal ){
61233 int exists;
61234 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
61235 if( rc!=SQLITE_OK ){
61236 goto delsuper_out;
61237 }
61238 if( exists ){
61239 char *zSuperPtr = 0;
61240
61241 /* One of the journals pointed to by the super-journal exists.
61242 ** Open it and check if it points at the super-journal. If
61243 ** so, return without deleting the super-journal file.
61244 ** NB: zJournal is really a MAIN_JOURNAL. But call it a
61245 ** SUPER_JOURNAL here so that the VFS will not send the zJournal
61246 ** name into sqlite3_database_file_object().
61247 */
61248 int c;
61249 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
61250 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
61251 if( rc!=SQLITE_OK ){
61252 goto delsuper_out;
61253 }
61254
61255 rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr);
61256 sqlite3OsClose(pJournal);
61257 if( rc!=SQLITE_OK ){
61258 assert( zSuperPtr==0 );
61259 goto delsuper_out;
61260 }
61261
61262 c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0;
61263 freeSuperJournal(zSuperPtr);
61264 if( c ){
61265 /* We have a match. Do not delete the super-journal file. */
61266 goto delsuper_out;
 
 
 
 
61267 }
61268 }
61269 zJournal += (sqlite3Strlen30(zJournal)+1);
61270 }
61271
61272 sqlite3OsClose(pSuper);
61273 rc = sqlite3OsDelete(pVfs, zSuper, 0);
 
 
 
 
 
61274
61275 delsuper_out:
61276 sqlite3_free(zFree);
61277 if( pSuper ){
61278 sqlite3OsClose(pSuper);
@@ -71674,10 +71903,13 @@
71674 int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
71675 ** Error code if eState==CURSOR_FAULT */
71676 Btree *pBtree; /* The Btree to which this cursor belongs */
71677 Pgno *aOverflow; /* Cache of overflow page locations */
71678 void *pKey; /* Saved key that was cursor last known position */
 
 
 
71679 /* All fields above are zeroed when the cursor is allocated. See
71680 ** sqlite3BtreeCursorZero(). Fields that follow must be manually
71681 ** initialized. */
71682 #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
71683 BtShared *pBt; /* The BtShared this cursor points to */
@@ -71850,10 +72082,13 @@
71850 int v2; /* Value for third %d substitution in zPfx */
71851 StrAccum errMsg; /* Accumulate the error message text here */
71852 u32 *heap; /* Min-heap used for analyzing cell coverage */
71853 sqlite3 *db; /* Database connection running the check */
71854 i64 nRow; /* Number of rows visited in current tree */
 
 
 
71855 };
71856
71857 /*
71858 ** Routines to read or write a two- and four-byte big-endian integer values.
71859 */
@@ -73178,28 +73413,45 @@
73178 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
73179 */
73180 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
73181 /* Used only by system that substitute their own storage engine */
73182 #ifdef SQLITE_DEBUG
73183 if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){
73184 va_list ap;
 
73185 Expr *pExpr;
73186 Walker w;
73187 memset(&w, 0, sizeof(w));
73188 w.xExprCallback = sqlite3CursorRangeHintExprCheck;
73189 va_start(ap, eHintType);
73190 pExpr = va_arg(ap, Expr*);
73191 w.u.aMem = va_arg(ap, Mem*);
73192 va_end(ap);
73193 assert( pExpr!=0 );
73194 assert( w.u.aMem!=0 );
73195 sqlite3WalkExpr(&w, pExpr);
 
 
 
 
 
 
 
73196 }
 
73197 #endif /* SQLITE_DEBUG */
73198 }
73199 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
73200
 
 
 
 
 
 
 
 
 
 
73201
73202 /*
73203 ** Provide flag hints to the cursor.
73204 */
73205 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
@@ -74321,12 +74573,19 @@
74321 /* Freeblock off the end of the page */
74322 return SQLITE_CORRUPT_PAGE(pPage);
74323 }
74324 next = get2byte(&data[pc]);
74325 size = get2byte(&data[pc+2]);
 
 
 
 
 
 
 
74326 nFree = nFree + size;
74327 if( next<=pc+size+3 ) break;
74328 pc = next;
74329 }
74330 if( next>0 ){
74331 /* Freeblock not in ascending order */
74332 return SQLITE_CORRUPT_PAGE(pPage);
@@ -78157,18 +78416,18 @@
78157 nCell = pCell[0];
78158 if( nCell<=pPage->max1bytePayload ){
78159 /* This branch runs if the record-size field of the cell is a
78160 ** single byte varint and the record fits entirely on the main
78161 ** b-tree page. */
78162 testcase( pCell+nCell+1==pPage->aDataEnd );
78163 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
78164 }else if( !(pCell[1] & 0x80)
78165 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
78166 ){
78167 /* The record-size field is a 2 byte varint and the record
78168 ** fits entirely on the main b-tree page. */
78169 testcase( pCell+nCell+2==pPage->aDataEnd );
78170 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
78171 }else{
78172 /* If the record extends into overflow pages, do not attempt
78173 ** the optimization. */
78174 c = 99;
@@ -78326,18 +78585,21 @@
78326 nCell = pCell[0];
78327 if( nCell<=pPage->max1bytePayload ){
78328 /* This branch runs if the record-size field of the cell is a
78329 ** single byte varint and the record fits entirely on the main
78330 ** b-tree page. */
78331 testcase( pCell+nCell+1==pPage->aDataEnd );
 
 
 
78332 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
78333 }else if( !(pCell[1] & 0x80)
78334 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
 
78335 ){
78336 /* The record-size field is a 2 byte varint and the record
78337 ** fits entirely on the main b-tree page. */
78338 testcase( pCell+nCell+2==pPage->aDataEnd );
78339 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
78340 }else{
78341 /* The record flows over onto one or more overflow pages. In
78342 ** this case the whole cell needs to be parsed, a buffer allocated
78343 ** and accessPayload() used to retrieve the record into the
@@ -83203,10 +83465,11 @@
83203 checkAppendMsg(pCheck, "Child page depth differs");
83204 depth = d2;
83205 }
83206 }else{
83207 /* Populate the coverage-checking heap for leaf pages */
 
83208 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
83209 }
83210 }
83211 *piMinKey = maxKey;
83212
@@ -83222,10 +83485,11 @@
83222 heap[0] = 0;
83223 for(i=nCell-1; i>=0; i--){
83224 u32 size;
83225 pc = get2byteAligned(&data[cellStart+i*2]);
83226 size = pPage->xCellSize(pPage, &data[pc]);
 
83227 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
83228 }
83229 }
83230 assert( heap!=0 );
83231 /* Add the freeblocks to the min-heap
@@ -83238,10 +83502,11 @@
83238 while( i>0 ){
83239 int size, j;
83240 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
83241 size = get2byte(&data[i+2]);
83242 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
 
83243 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
83244 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
83245 ** big-endian integer which is the offset in the b-tree page of the next
83246 ** freeblock in the chain, or zero if the freeblock is the last on the
83247 ** chain. */
@@ -83372,10 +83637,13 @@
83372 if( !sCheck.aPgRef ){
83373 checkOom(&sCheck);
83374 goto integrity_ck_cleanup;
83375 }
83376 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
 
 
 
83377 if( sCheck.heap==0 ){
83378 checkOom(&sCheck);
83379 goto integrity_ck_cleanup;
83380 }
83381
@@ -83796,17 +84064,18 @@
83796 /*
83797 ** Structure allocated for each backup operation.
83798 */
83799 struct sqlite3_backup {
83800 sqlite3* pDestDb; /* Destination database handle */
83801 Db *pDest; /* Destination db file */
 
83802 u32 iDestSchema; /* Original schema cookie in destination */
83803 int bDestLocked; /* True once a write-transaction is open on pDest */
83804
83805 Pgno iNext; /* Page number of the next source page to copy */
83806 sqlite3* pSrcDb; /* Source database handle */
83807 Db *pSrc; /* Source db file */
83808
83809 int rc; /* Backup process error code */
83810
83811 /* These two variables are set by every call to backup_step(). They are
83812 ** read by calls to backup_remaining() and backup_pagecount().
@@ -83855,13 +84124,15 @@
83855 **
83856 ** If the "temp" database is requested, it may need to be opened by this
83857 ** function. If an error occurs while doing so, return 0 and write an
83858 ** error message to pErrorDb.
83859 */
83860 static Db *findDatabase(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
83861 int i = sqlite3FindDbName(pDb, zDb);
83862
 
 
83863 if( i==1 ){
83864 Parse sParse;
83865 int rc = 0;
83866 sqlite3ParseObjectInit(&sParse,pDb);
83867 if( sqlite3OpenTempDatabase(&sParse) ){
@@ -83878,21 +84149,19 @@
83878 if( i<0 ){
83879 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
83880 return 0;
83881 }
83882
83883 return &pDb->aDb[i];
83884 }
83885
83886 /*
83887 ** Attempt to set the page size of the destination to match the page size
83888 ** of the source.
83889 */
83890 static int setDestPgsz(sqlite3_backup *p){
83891 return sqlite3BtreeSetPageSize(p->pDest->pBt,
83892 sqlite3BtreeGetPageSize(p->pSrc->pBt), 0, 0
83893 );
83894 }
83895
83896 /*
83897 ** Check that there is no open read-transaction on the b-tree passed as the
83898 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
@@ -83945,31 +84214,41 @@
83945 sqlite3ErrorWithMsg(
83946 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
83947 );
83948 p = 0;
83949 }else {
 
 
83950 /* Allocate space for a new sqlite3_backup object...
83951 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
83952 ** call to sqlite3_backup_init() and is destroyed by a call to
83953 ** sqlite3_backup_finish(). */
83954 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
83955 if( !p ){
83956 sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
 
 
 
83957 }
83958 }
83959
83960 /* If the allocation succeeded, populate the new object. */
83961 if( p ){
83962 p->pSrc = findDatabase(pDestDb, pSrcDb, zSrcDb);
83963 p->pDest = findDatabase(pDestDb, pDestDb, zDestDb);
 
 
 
 
 
83964 p->pDestDb = pDestDb;
83965 p->pSrcDb = pSrcDb;
83966 p->iNext = 1;
83967 p->isAttached = 0;
83968
83969 if( 0==p->pSrc || 0==p->pDest
83970 || checkReadTransaction(pDestDb, p->pDest->pBt)!=SQLITE_OK
83971 ){
83972 /* One (or both) of the named databases did not exist or an OOM
83973 ** error was hit. Or there is a transaction open on the destination
83974 ** database. The error has already been written into the pDestDb
83975 ** handle. All that is left to do here is free the sqlite3_backup
@@ -83977,11 +84256,11 @@
83977 sqlite3_free(p);
83978 p = 0;
83979 }
83980 }
83981 if( p ){
83982 p->pSrc->pBt->nBackup++;
83983 }
83984
83985 sqlite3_mutex_leave(pDestDb->mutex);
83986 sqlite3_mutex_leave(pSrcDb->mutex);
83987 return p;
@@ -84005,22 +84284,22 @@
84005 sqlite3_backup *p, /* Backup handle */
84006 Pgno iSrcPg, /* Source database page to backup */
84007 const u8 *zSrcData, /* Source database page data */
84008 int bUpdate /* True for an update, false otherwise */
84009 ){
84010 Pager * const pDestPager = sqlite3BtreePager(p->pDest->pBt);
84011 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc->pBt);
84012 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest->pBt);
84013 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
84014 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
84015 int rc = SQLITE_OK;
84016 i64 iOff;
84017
84018 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc->pBt)>=0 );
84019 assert( p->bDestLocked );
84020 assert( !isFatalError(p->rc) );
84021 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt->pBt) );
84022 assert( zSrcData );
84023 assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 );
84024
84025 /* This loop runs once for each destination page spanned by the source
84026 ** page. For each iteration, variable iOff is set to the byte offset
@@ -84027,11 +84306,11 @@
84027 ** of the destination page.
84028 */
84029 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
84030 DbPage *pDestPg = 0;
84031 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
84032 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt->pBt) ) continue;
84033 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
84034 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
84035 ){
84036 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
84037 u8 *zDestData = sqlite3PagerGetData(pDestPg);
@@ -84045,11 +84324,11 @@
84045 ** "MUST BE FIRST" for this purpose.
84046 */
84047 memcpy(zOut, zIn, nCopy);
84048 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
84049 if( iOff==0 && bUpdate==0 ){
84050 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc->pBt));
84051 }
84052 }
84053 sqlite3PagerUnref(pDestPg);
84054 }
84055
@@ -84077,12 +84356,12 @@
84077 ** Register this backup object with the associated source pager for
84078 ** callbacks when pages are changed or the cache invalidated.
84079 */
84080 static void attachBackupObject(sqlite3_backup *p){
84081 sqlite3_backup **pp;
84082 assert( sqlite3BtreeHoldsMutex(p->pSrc->pBt) );
84083 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc->pBt));
84084 p->pNext = *pp;
84085 *pp = p;
84086 p->isAttached = 1;
84087 }
84088
@@ -84089,93 +84368,103 @@
84089 /*
84090 ** Copy nPage pages from the source b-tree to the destination.
84091 */
84092 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
84093 int rc;
84094 int destMode; /* Destination journal mode */
84095 int pgszSrc = 0; /* Source page size */
84096 int pgszDest = 0; /* Destination page size */
84097 Btree *pDest;
84098 Btree *pSrc;
84099
84100 #ifdef SQLITE_ENABLE_API_ARMOR
84101 if( p==0 ) return SQLITE_MISUSE_BKPT;
84102 #endif
84103 assert( p->pDest );
84104 assert( p->pSrc );
84105 pDest = p->pDest->pBt;
84106 pSrc = p->pSrc->pBt;
84107 sqlite3_mutex_enter(p->pSrcDb->mutex);
84108 sqlite3BtreeEnter(pSrc);
84109 if( p->pDestDb ){
84110 sqlite3_mutex_enter(p->pDestDb->mutex);
84111 }
84112
84113 rc = p->rc;
84114 if( !isFatalError(rc) ){
84115 Pager * const pSrcPager = sqlite3BtreePager(pSrc); /* Source pager */
84116 Pager * const pDestPager = sqlite3BtreePager(pDest); /* Dest pager */
 
84117 int ii; /* Iterator variable */
84118 int nSrcPage = -1; /* Size of source db in pages */
84119 int bCloseTrans = 0; /* True if src db requires unlocking */
84120
84121 /* If the source pager is currently in a write-transaction, return
84122 ** SQLITE_BUSY immediately.
84123 */
84124 if( p->pDestDb && pSrc->pBt->inTransaction==TRANS_WRITE ){
84125 rc = SQLITE_BUSY;
84126 }else{
84127 rc = SQLITE_OK;
84128 }
 
84129
84130 /* If there is no open read-transaction on the source database, open
84131 ** one now. If a transaction is opened here, then it will be closed
84132 ** before this function exits.
84133 */
84134 if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(pSrc) ){
84135 rc = sqlite3BtreeBeginTrans(pSrc, 0, 0);
84136 bCloseTrans = 1;
84137 }
 
 
 
 
 
 
 
 
 
 
84138
84139 /* If the destination database has not yet been locked (i.e. if this
84140 ** is the first call to backup_step() for the current backup operation),
84141 ** try to set its page size to the same as the source database. This
84142 ** is especially important on ZipVFS systems, as in that case it is
84143 ** not possible to create a database file that uses one page size by
84144 ** writing to it with another. */
84145 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
 
 
84146 rc = SQLITE_NOMEM;
84147 }
84148
84149 /* Lock the destination database, if it is not locked already. */
84150 if( SQLITE_OK==rc && p->bDestLocked==0
84151 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(pDest, 2,
84152 (int*)&p->iDestSchema))
84153 ){
84154 p->bDestLocked = 1;
 
84155 }
84156
84157 /* Do not allow backup if the destination database is in WAL mode
84158 ** and the page sizes are different between source and destination */
84159 pgszSrc = sqlite3BtreeGetPageSize(pSrc);
84160 pgszDest = sqlite3BtreeGetPageSize(pDest);
84161 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(pDest));
84162 if( SQLITE_OK==rc
84163 && (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
84164 && pgszSrc!=pgszDest
84165 ){
84166 rc = SQLITE_READONLY;
 
84167 }
84168
84169 /* Now that there is a read-lock on the source database, query the
84170 ** source pager for the number of pages in the database.
84171 */
84172 nSrcPage = (int)sqlite3BtreeLastPage(pSrc);
84173 assert( nSrcPage>=0 );
84174 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
84175 const Pgno iSrcPg = p->iNext; /* Source page number */
84176 if( iSrcPg!=PENDING_BYTE_PAGE(pSrc->pBt) ){
84177 DbPage *pSrcPg; /* Source page object */
84178 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
84179 if( rc==SQLITE_OK ){
84180 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
84181 sqlite3PagerUnref(pSrcPg);
@@ -84198,22 +84487,22 @@
84198 ** the case where the source and destination databases have the
84199 ** same schema version.
84200 */
84201 if( rc==SQLITE_DONE ){
84202 if( nSrcPage==0 ){
84203 rc = sqlite3BtreeNewDb(pDest);
84204 nSrcPage = 1;
84205 }
84206 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
84207 rc = sqlite3BtreeUpdateMeta(pDest,1,p->iDestSchema+1);
84208 }
84209 if( rc==SQLITE_OK ){
84210 if( p->pDestDb ){
84211 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
84212 }
84213 if( destMode==PAGER_JOURNALMODE_WAL ){
84214 rc = sqlite3BtreeSetVersion(pDest, 2);
84215 }
84216 }
84217 if( rc==SQLITE_OK ){
84218 int nDestTruncate;
84219 /* Set nDestTruncate to the final number of pages in the destination
@@ -84226,16 +84515,16 @@
84226 ** sqlite3PagerTruncateImage() here so that any pages in the
84227 ** destination file that lie beyond the nDestTruncate page mark are
84228 ** journalled by PagerCommitPhaseOne() before they are destroyed
84229 ** by the file truncation.
84230 */
84231 assert( pgszSrc==sqlite3BtreeGetPageSize(pSrc) );
84232 assert( pgszDest==sqlite3BtreeGetPageSize(pDest) );
84233 if( pgszSrc<pgszDest ){
84234 int ratio = pgszDest/pgszSrc;
84235 nDestTruncate = (nSrcPage+ratio-1)/ratio;
84236 if( nDestTruncate==(int)PENDING_BYTE_PAGE(pDest->pBt) ){
84237 nDestTruncate--;
84238 }
84239 }else{
84240 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
84241 }
@@ -84259,11 +84548,11 @@
84259 i64 iEnd;
84260
84261 assert( pFile );
84262 assert( nDestTruncate==0
84263 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
84264 nDestTruncate==(int)(PENDING_BYTE_PAGE(pDest->pBt)-1)
84265 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
84266 ));
84267
84268 /* This block ensures that all data required to recreate the original
84269 ** database has been stored in the journal for pDestPager and the
@@ -84271,11 +84560,11 @@
84271 ** the database file in any way, knowing that if a power failure
84272 ** occurs, the original database will be reconstructed from the
84273 ** journal file. */
84274 sqlite3PagerPagecount(pDestPager, &nDstPage);
84275 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
84276 if( iPg!=PENDING_BYTE_PAGE(pDest->pBt) ){
84277 DbPage *pPg;
84278 rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
84279 if( rc==SQLITE_OK ){
84280 rc = sqlite3PagerWrite(pPg);
84281 sqlite3PagerUnref(pPg);
@@ -84315,11 +84604,11 @@
84315 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
84316 }
84317
84318 /* Finish committing the transaction to the destination database. */
84319 if( SQLITE_OK==rc
84320 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(pDest, 0))
84321 ){
84322 rc = SQLITE_DONE;
84323 }
84324 }
84325 }
@@ -84329,12 +84618,12 @@
84329 ** no need to check the return values of the btree methods here, as
84330 ** "committing" a read-only transaction cannot fail.
84331 */
84332 if( bCloseTrans ){
84333 TESTONLY( int rc2 );
84334 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(pSrc, 0);
84335 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(pSrc, 0);
84336 assert( rc2==SQLITE_OK );
84337 }
84338
84339 if( rc==SQLITE_IOERR_NOMEM ){
84340 rc = SQLITE_NOMEM_BKPT;
@@ -84342,11 +84631,11 @@
84342 p->rc = rc;
84343 }
84344 if( p->pDestDb ){
84345 sqlite3_mutex_leave(p->pDestDb->mutex);
84346 }
84347 sqlite3BtreeLeave(pSrc);
84348 sqlite3_mutex_leave(p->pSrcDb->mutex);
84349 return rc;
84350 }
84351
84352 /*
@@ -84359,41 +84648,43 @@
84359
84360 /* Enter the mutexes */
84361 if( p==0 ) return SQLITE_OK;
84362 pSrcDb = p->pSrcDb;
84363 sqlite3_mutex_enter(pSrcDb->mutex);
84364 sqlite3BtreeEnter(p->pSrc->pBt);
84365 if( p->pDestDb ){
84366 sqlite3_mutex_enter(p->pDestDb->mutex);
84367 }
84368
84369 /* Detach this backup from the source pager. */
84370 if( p->pDestDb ){
84371 p->pSrc->pBt->nBackup--;
84372 }
84373 if( p->isAttached ){
84374 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc->pBt));
84375 assert( pp!=0 );
84376 while( *pp!=p ){
84377 pp = &(*pp)->pNext;
84378 assert( pp!=0 );
84379 }
84380 *pp = p->pNext;
84381 }
84382
84383 /* If a transaction is still open on the Btree, roll it back. */
84384 sqlite3BtreeRollback(p->pDest->pBt, SQLITE_OK, 0);
 
 
84385
84386 /* Set the error code of the destination database handle. */
84387 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
84388 if( p->pDestDb ){
84389 sqlite3Error(p->pDestDb, rc);
84390
84391 /* Exit the mutexes and free the backup context structure. */
84392 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
84393 }
84394 sqlite3BtreeLeave(p->pSrc->pBt);
84395 if( p->pDestDb ){
84396 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
84397 ** call to sqlite3_backup_init() and is destroyed by a call to
84398 ** sqlite3_backup_finish(). */
84399 sqlite3_free(p);
@@ -84447,11 +84738,11 @@
84447 Pgno iPage,
84448 const u8 *aData
84449 ){
84450 assert( p!=0 );
84451 do{
84452 assert( sqlite3_mutex_held(p->pSrc->pBt->pBt->mutex) );
84453 if( !isFatalError(p->rc) && iPage<p->iNext ){
84454 /* The backup process p has already copied page iPage. But now it
84455 ** has been modified by a transaction on the source pager. Copy
84456 ** the new data into the backup.
84457 */
@@ -84483,11 +84774,11 @@
84483 ** called.
84484 */
84485 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
84486 sqlite3_backup *p; /* Iterator variable */
84487 for(p=pBackup; p; p=p->pNext){
84488 assert( sqlite3_mutex_held(p->pSrc->pBt->pBt->mutex) );
84489 p->iNext = 1;
84490 }
84491 }
84492
84493 #ifndef SQLITE_OMIT_VACUUM
@@ -84501,12 +84792,10 @@
84501 */
84502 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
84503 int rc;
84504 sqlite3_file *pFd; /* File descriptor for database pTo */
84505 sqlite3_backup b;
84506 Db dbDest;
84507 Db dbSrc;
84508 sqlite3BtreeEnter(pTo);
84509 sqlite3BtreeEnter(pFrom);
84510
84511 assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
84512 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
@@ -84521,17 +84810,13 @@
84521 ** to 0. This is used by the implementations of sqlite3_backup_step()
84522 ** and sqlite3_backup_finish() to detect that they are being called
84523 ** from this function, not directly by the user.
84524 */
84525 memset(&b, 0, sizeof(b));
84526 memset(&dbDest, 0, sizeof(dbDest));
84527 memset(&dbSrc, 0, sizeof(dbSrc));
84528 dbDest.pBt = pTo;
84529 dbSrc.pBt = pFrom;
84530 b.pSrcDb = pFrom->db;
84531 b.pSrc = &dbSrc;
84532 b.pDest = &dbDest;
84533 b.iNext = 1;
84534
84535 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
84536 ** file. By passing this as the number of pages to copy to
84537 ** sqlite3_backup_step(), we can guarantee that the copy finishes
@@ -84543,11 +84828,11 @@
84543
84544 rc = sqlite3_backup_finish(&b);
84545 if( rc==SQLITE_OK ){
84546 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
84547 }else{
84548 sqlite3PagerClearCache(sqlite3BtreePager(pTo));
84549 }
84550
84551 assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
84552 copy_finished:
84553 sqlite3BtreeLeave(pFrom);
@@ -86859,11 +87144,10 @@
86859 p->pParse = pParse;
86860 pParse->pVdbe = p;
86861 assert( pParse->aLabel==0 );
86862 assert( pParse->nLabel==0 );
86863 assert( p->nOpAlloc==0 );
86864 assert( pParse->szOpAlloc==0 );
86865 sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
86866 return p;
86867 }
86868
86869 /*
@@ -87009,12 +87293,11 @@
87009
87010 assert( nOp<=(int)(1024/sizeof(Op)) );
87011 assert( nNew>=(v->nOpAlloc+nOp) );
87012 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
87013 if( pNew ){
87014 p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
87015 v->nOpAlloc = p->szOpAlloc/sizeof(Op);
87016 v->aOp = pNew;
87017 }
87018 return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
87019 }
87020
@@ -87445,11 +87728,11 @@
87445 ** Resolve label "x" to be the address of the next instruction to
87446 ** be inserted. The parameter "x" must have been obtained from
87447 ** a prior call to sqlite3VdbeMakeLabel().
87448 */
87449 static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
87450 int nNewSize = 10 - p->nLabel;
87451 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
87452 nNewSize*sizeof(p->aLabel[0]));
87453 if( p->aLabel==0 ){
87454 p->nLabelAlloc = 0;
87455 }else{
@@ -89513,11 +89796,11 @@
89513 ** of the prepared statement.
89514 */
89515 n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
89516 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
89517 assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
89518 x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
89519 assert( x.nFree>=0 );
89520 assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
89521
89522 resolveP2Values(p, &nArg);
89523 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
@@ -92662,12 +92945,18 @@
92662 ** that sqlite3_prepare() generates. For example, if new functions or
92663 ** collating sequences are registered or if an authorizer function is
92664 ** added or changed.
92665 */
92666 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
92667 Vdbe *p = (Vdbe*)pStmt;
92668 return p==0 || p->expired;
 
 
 
 
 
 
92669 }
92670 #endif
92671
92672 /*
92673 ** Check on a Vdbe to make sure it has not been finalized. Log
@@ -93009,19 +93298,22 @@
93009 sqlite3ValueFree(pOld);
93010 }
93011
93012
93013 /**************************** sqlite3_result_ *******************************
93014 ** The following routines are used by user-defined functions to specify
93015 ** the function result.
93016 **
93017 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
93018 ** result as a string or blob. Appropriate errors are set if the string/blob
93019 ** is too big or if an OOM occurs.
93020 **
93021 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
93022 ** on value P if P is not going to be used and need to be destroyed.
 
 
 
93023 */
93024 static void setResultStrOrError(
93025 sqlite3_context *pCtx, /* Function context */
93026 const char *z, /* String pointer */
93027 int n, /* Bytes in string, or negative */
@@ -93330,11 +93622,11 @@
93330 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
93331 SQLITE_STATIC);
93332 }
93333 }
93334
93335 /* Force an SQLITE_TOOBIG error. */
93336 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
93337 #ifdef SQLITE_ENABLE_API_ARMOR
93338 if( pCtx==0 ) return;
93339 #endif
93340 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
@@ -93341,20 +93633,78 @@
93341 pCtx->isError = SQLITE_TOOBIG;
93342 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
93343 SQLITE_UTF8, SQLITE_STATIC);
93344 }
93345
93346 /* An SQLITE_NOMEM error. */
93347 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
93348 #ifdef SQLITE_ENABLE_API_ARMOR
93349 if( pCtx==0 ) return;
93350 #endif
93351 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
93352 sqlite3VdbeMemSetNull(pCtx->pOut);
93353 pCtx->isError = SQLITE_NOMEM_BKPT;
93354 sqlite3OomFault(pCtx->pOut->db);
93355 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93356
93357 #ifndef SQLITE_UNTESTABLE
93358 /* Force the INT64 value currently stored as the result to be
93359 ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
93360 ** test-control.
@@ -96241,10 +96591,14 @@
96241 }
96242
96243 /*
96244 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
96245 ** with pOp->p3. Return the hash.
 
 
 
 
96246 */
96247 static u64 filterHash(const Mem *aMem, const Op *pOp){
96248 int i, mx;
96249 u64 h = 0;
96250
@@ -96253,15 +96607,32 @@
96253 const Mem *p = &aMem[i];
96254 if( p->flags & (MEM_Int|MEM_IntReal) ){
96255 h += p->u.i;
96256 }else if( p->flags & MEM_Real ){
96257 h += sqlite3VdbeIntValue(p);
96258 }else if( p->flags & (MEM_Str|MEM_Blob) ){
96259 /* All strings have the same hash and all blobs have the same hash,
96260 ** though, at least, those hashes are different from each other and
96261 ** from NULL. */
96262 h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96263 }
96264 }
96265 return h;
96266 }
96267
@@ -101084,11 +101455,11 @@
101084 */
101085 case OP_SeekRowid: { /* jump0, in3, ncycle */
101086 VdbeCursor *pC;
101087 BtCursor *pCrsr;
101088 int res;
101089 u64 iKey;
101090
101091 pIn3 = &aMem[pOp->p3];
101092 testcase( pIn3->flags & MEM_Int );
101093 testcase( pIn3->flags & MEM_IntReal );
101094 testcase( pIn3->flags & MEM_Real );
@@ -101098,13 +101469,23 @@
101098 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
101099 ** into an integer without loss of information. Take care to avoid
101100 ** changing the datatype of pIn3, however, as it is used by other
101101 ** parts of the prepared statement. */
101102 Mem x = pIn3[0];
101103 applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
101104 if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
101105 iKey = x.u.i;
 
 
 
 
 
 
 
 
 
 
101106 goto notExistsWithKey;
101107 }
101108 /* Fall through into OP_NotExists */
101109 /* no break */ deliberate_fall_through
101110 case OP_NotExists: /* jump, in3, ncycle */
@@ -102342,10 +102723,15 @@
102342 pTabCur = p->apCsr[pOp->p3];
102343 assert( pTabCur!=0 );
102344 assert( pTabCur->eCurType==CURTYPE_BTREE );
102345 assert( pTabCur->uc.pCursor!=0 );
102346 assert( pTabCur->isTable );
 
 
 
 
 
102347 pTabCur->nullRow = 0;
102348 pTabCur->movetoTarget = rowid;
102349 pTabCur->deferredMoveto = 1;
102350 pTabCur->cacheStatus = CACHE_STALE;
102351 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
@@ -104724,27 +105110,41 @@
104724 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
104725 goto jump_to_p2;
104726 }
104727
104728 #ifdef SQLITE_ENABLE_CURSOR_HINTS
104729 /* Opcode: CursorHint P1 * * P4 *
104730 **
104731 ** Provide a hint to cursor P1 that it only needs to return rows that
104732 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
104733 ** to values currently held in registers. TK_COLUMN terms in the P4
 
 
104734 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
 
 
 
 
 
 
104735 */
104736 case OP_CursorHint: {
104737 VdbeCursor *pC;
 
104738
104739 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
104740 assert( pOp->p4type==P4_EXPR );
104741 pC = p->apCsr[pOp->p1];
104742 if( pC ){
104743 assert( pC->eCurType==CURTYPE_BTREE );
104744 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
104745 pOp->p4.pExpr, aMem);
 
 
 
 
 
 
104746 }
104747 break;
104748 }
104749 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
104750
@@ -110329,13 +110729,15 @@
110329 if( pFJMatch ){
110330 assert( pExpr->op==TK_FUNCTION );
110331 assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 );
110332 assert( pExpr->x.pList==pFJMatch );
110333 assert( pFJMatch->nExpr>0 );
110334 pExpr = pFJMatch->a[0].pExpr;
110335 }
110336 if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
 
 
110337 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
110338 }
110339 }
110340 #endif
110341 /* Increment the nRef value on all name contexts from TopNC up to
@@ -110447,15 +110849,24 @@
110447 static SQLITE_NOINLINE void resolveSetExprSubtypeArg(ExprList *pList){
110448 int nn, ii;
110449 nn = pList ? pList->nExpr : 0;
110450 for(ii=0; ii<nn; ii++){
110451 Expr *pExpr = pList->a[ii].pExpr;
110452 ExprSetProperty(pExpr, EP_SubtArg);
110453 if( pExpr->op==TK_SELECT ){
110454 assert( ExprUseXSelect(pExpr) );
110455 assert( pExpr->x.pSelect!=0 );
110456 resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList);
 
 
 
 
 
 
 
 
 
110457 }
110458 }
110459 }
110460
110461 /*
@@ -115538,10 +115949,12 @@
115538 }else{
115539 VdbeComment((v, "RHS of IN operator"));
115540 }
115541 #endif
115542 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
 
 
115543
115544 if( ExprUseXSelect(pExpr) ){
115545 /* Case 1: expr IN (SELECT ...)
115546 **
115547 ** Generate code to write the results of the select into the temporary
@@ -115562,21 +115975,35 @@
115562 int rc;
115563 int addrBloom = 0;
115564 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
115565 dest.zAffSdst = exprINAffinity(pParse, pExpr);
115566 pSelect->iLimit = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
115567 if( addrOnce
115568 && allowBloom
115569 && OptimizationEnabled(pParse->db, SQLITE_BloomFilter)
115570 ){
115571 int regBloom = ++pParse->nMem;
115572 addrBloom = sqlite3VdbeAddOp2(v, OP_Blob, 10000, regBloom);
115573 VdbeComment((v, "Bloom filter"));
115574 dest.iSDParm2 = regBloom;
 
 
115575 }
115576 testcase( pSelect->selFlags & SF_Distinct );
115577 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
115578 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
115579 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
115580 sqlite3SelectDelete(pParse->db, pCopy);
115581 sqlite3DbFree(pParse->db, dest.zAffSdst);
115582 if( addrBloom ){
@@ -115590,20 +116017,10 @@
115590 }
115591 if( rc ){
115592 sqlite3KeyInfoUnref(pKeyInfo);
115593 return;
115594 }
115595 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
115596 assert( pEList!=0 );
115597 assert( pEList->nExpr>0 );
115598 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
115599 for(i=0; i<nVal; i++){
115600 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
115601 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
115602 pParse, p, pEList->a[i].pExpr
115603 );
115604 }
115605 }
115606 }else if( ALWAYS(pExpr->x.pList!=0) ){
115607 /* Case 2: expr IN (exprlist)
115608 **
115609 ** For each expression, build an index key from the evaluation and
@@ -115620,14 +116037,13 @@
115620 if( affinity<=SQLITE_AFF_NONE ){
115621 affinity = SQLITE_AFF_BLOB;
115622 }else if( affinity==SQLITE_AFF_REAL ){
115623 affinity = SQLITE_AFF_NUMERIC;
115624 }
115625 if( pKeyInfo ){
115626 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
115627 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
115628 }
115629
115630 /* Loop through each expression in <exprlist>. */
115631 r1 = sqlite3GetTempReg(pParse);
115632 r2 = sqlite3GetTempReg(pParse);
115633 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
@@ -116580,11 +116996,11 @@
116580 if( pExpr->op!=TK_FUNCTION ){
116581 return WRC_Prune;
116582 }
116583 assert( ExprUseXList(pExpr) );
116584 db = pWalker->pParse->db;
116585 n = ALWAYS(pExpr->x.pList) ? pExpr->x.pList->nExpr : 0;
116586 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
116587 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
116588 pWalker->eCode = 1;
116589 return WRC_Abort;
116590 }
@@ -117229,11 +117645,16 @@
117229 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
117230 if( pDef==0 && pParse->explain ){
117231 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
117232 }
117233 #endif
117234 if( pDef==0 || pDef->xFinalize!=0 ){
 
 
 
 
 
117235 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
117236 break;
117237 }
117238 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
117239 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
@@ -121984,19 +122405,41 @@
121984
121985
121986 /*
121987 ** Argument z points into the body of a constraint - specifically the
121988 ** second token of the constraint definition. For a named constraint,
121989 ** z points to the first token past the CONSTRAINT keyword. For an
121990 ** unnamed NOT NULL constraint, z points to the first byte past the NOT
121991 ** keyword.
 
 
 
 
 
121992 **
121993 ** Return the number of bytes until the end of the constraint.
121994 */
121995 static int getConstraint(const u8 *z){
121996 int iOff = 0;
121997 int t = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121998
121999 /* Now, the current constraint proceeds until the next occurence of one
122000 ** of the following tokens:
122001 **
122002 ** CONSTRAINT, PRIMARY, NOT, UNIQUE, CHECK, DEFAULT,
@@ -122165,24 +122608,24 @@
122165 || t==TK_COMMA || t==TK_RP || t==TK_GENERATED || t==TK_AS
122166 ){
122167 t = TK_CHECK;
122168 }else{
122169 iOff += nTok;
122170 iOff += getConstraint(&zSql[iOff]);
122171 }
122172
122173 if( cmp==0 || (iNotNull>=0 && t==TK_NOT) ){
122174 if( t!=TK_NOT && t!=TK_CHECK ){
122175 errorMPrintf(ctx, "constraint may not be dropped: %s", zCons);
122176 return;
122177 }
122178 iEnd = iOff;
122179 break;
122180 }
122181
122182 }else if( t==TK_NOT && iNotNull==ii ){
122183 iEnd = iOff + getConstraint(&zSql[iOff]);
122184 break;
122185 }else if( t==TK_RP || t==TK_ILLEGAL ){
122186 iEnd = -1;
122187 break;
122188 }else if( t==TK_COMMA ){
@@ -122236,13 +122679,12 @@
122236 const u8 *zSql = sqlite3_value_text(argv[0]);
122237 const char *zCons = (const char*)sqlite3_value_text(argv[1]);
122238 int iCol = sqlite3_value_int(argv[2]);
122239 int iOff = 0;
122240 int ii;
122241 char *zNew = 0;
122242 int t = 0;
122243 sqlite3 *db;
122244 UNUSED_PARAMETER(NotUsed);
122245
122246 if( skipCreateTable(ctx, zSql, &iOff) ) return;
122247
122248 for(ii=0; ii<=iCol || (iCol<0 && t!=TK_RP); ii++){
@@ -122258,17 +122700,15 @@
122258 }
122259 }
122260
122261 iOff += getWhitespace(&zSql[iOff]);
122262
122263 db = sqlite3_context_db_handle(ctx);
122264 if( iCol<0 ){
122265 zNew = sqlite3MPrintf(db, "%.*s, %s%s", iOff, zSql, zCons, &zSql[iOff]);
122266 }else{
122267 zNew = sqlite3MPrintf(db, "%.*s %s%s", iOff, zSql, zCons, &zSql[iOff]);
122268 }
122269 sqlite3_result_text(ctx, zNew, -1, SQLITE_DYNAMIC);
122270 }
122271
122272 /*
122273 ** Find a column named pCol in table pTab. If successful, set output
122274 ** parameter *piCol to the index of the column in the table and return
@@ -123524,11 +123964,11 @@
123524 sqlite3_str_appendf(&sStat, " %llu", iVal);
123525 #ifdef SQLITE_ENABLE_STAT4
123526 assert( p->current.anEq[i] || p->nRow==0 );
123527 #endif
123528 }
123529 sqlite3ResultStrAccum(context, &sStat);
123530 }
123531 #ifdef SQLITE_ENABLE_STAT4
123532 else if( eCall==STAT_GET_ROWID ){
123533 if( p->iGet<0 ){
123534 samplePushPrevious(p, 0);
@@ -123561,11 +124001,11 @@
123561 sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
123562 for(i=0; i<p->nCol; i++){
123563 sqlite3_str_appendf(&sStat, "%llu ", (u64)aCnt[i]);
123564 }
123565 if( sStat.nChar ) sStat.nChar--;
123566 sqlite3ResultStrAccum(context, &sStat);
123567 }
123568 #endif /* SQLITE_ENABLE_STAT4 */
123569 #ifndef SQLITE_DEBUG
123570 UNUSED_PARAMETER( argc );
123571 #endif
@@ -125649,10 +126089,11 @@
125649 }
125650 }
125651
125652 assert( pToplevel->nTableLock < 0x7fff0000 );
125653 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
 
125654 pToplevel->aTableLock =
125655 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
125656 if( pToplevel->aTableLock ){
125657 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
125658 p->iDb = iDb;
@@ -125815,11 +126256,11 @@
125815 if( pParse->nTableLock ) codeTableLocks(pParse);
125816 #endif
125817
125818 /* Initialize any AUTOINCREMENT data structures required.
125819 */
125820 if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
125821
125822 /* Code constant expressions that were factored out of inner loops.
125823 */
125824 if( pParse->pConstExpr ){
125825 ExprList *pEL = pParse->pConstExpr;
@@ -125848,11 +126289,11 @@
125848 assert( v!=0 || pParse->nErr );
125849 assert( db->mallocFailed==0 || pParse->nErr );
125850 if( pParse->nErr==0 ){
125851 /* A minimum of one cursor is required if autoincrement is used
125852 * See ticket [a696379c1f08866] */
125853 assert( pParse->pAinc==0 || pParse->nTab>0 );
125854 sqlite3VdbeMakeReady(v, pParse);
125855 pParse->rc = SQLITE_DONE;
125856 }else{
125857 pParse->rc = SQLITE_ERROR;
125858 }
@@ -127812,10 +128253,27 @@
127812 pIdx->aSortOrder = (u8*)zExtra;
127813 pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */
127814 pIdx->isResized = 1;
127815 return SQLITE_OK;
127816 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127817
127818 /*
127819 ** Estimate the total row width for a table.
127820 */
127821 static void estimateTableWidth(Table *pTab){
@@ -128164,18 +128622,15 @@
128164
128165 #ifndef SQLITE_OMIT_VIRTUALTABLE
128166 /*
128167 ** Return true if zName is a shadow table name in the current database
128168 ** connection.
128169 **
128170 ** zName is temporarily modified while this routine is running, but is
128171 ** restored to its original value prior to this routine returning.
128172 */
128173 SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
128174 const char *zTail; /* Pointer to the last "_" in zName */
128175 Table *pTab; /* Table that zName is a shadow of */
128176 char *zCopy;
128177 zTail = strrchr(zName, '_');
128178 if( zTail==0 ) return 0;
128179 zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
128180 pTab = zCopy ? sqlite3FindTable(db, zCopy, 0) : 0;
128181 sqlite3DbFree(db, zCopy);
@@ -129683,12 +130138,13 @@
129683 }
129684 }
129685 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
129686 if( !ifNotExist ){
129687 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
 
 
129688 }else{
129689 assert( !db->init.busy );
129690 sqlite3CodeVerifySchema(pParse, iDb);
129691 sqlite3ForceNotReadOnly(pParse);
129692 }
129693 goto exit_create_index;
129694 }
@@ -133318,32 +133774,20 @@
133318 sqlite3_value **argv
133319 ){
133320 PrintfArguments x;
133321 StrAccum str;
133322 const char *zFormat;
133323 int n;
133324 sqlite3 *db = sqlite3_context_db_handle(context);
133325
133326 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
133327 x.nArg = argc-1;
133328 x.nUsed = 0;
133329 x.apArg = argv+1;
133330 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
133331 str.printfFlags = SQLITE_PRINTF_SQLFUNC;
133332 sqlite3_str_appendf(&str, zFormat, &x);
133333 if( str.accError==SQLITE_OK ){
133334 n = str.nChar;
133335 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
133336 SQLITE_DYNAMIC);
133337 }else{
133338 if( str.accError==SQLITE_NOMEM ){
133339 sqlite3_result_error_nomem(context);
133340 }else{
133341 sqlite3_result_error_toobig(context);
133342 }
133343 sqlite3_str_reset(&str);
133344 }
133345 }
133346 }
133347
133348 /*
133349 ** Implementation of the substr() function.
@@ -134286,16 +134730,11 @@
134286 sqlite3 *db = sqlite3_context_db_handle(context);
134287 assert( argc==1 );
134288 UNUSED_PARAMETER(argc);
134289 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
134290 sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context)));
134291 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
134292 SQLITE_DYNAMIC);
134293 if( str.accError!=SQLITE_OK ){
134294 sqlite3_result_null(context);
134295 sqlite3_result_error_code(context, str.accError);
134296 }
134297 }
134298
134299 /*
134300 ** The unicode() function. Return the integer unicode code-point value
134301 ** for the first character of the input string.
@@ -135324,32 +135763,22 @@
135324 #endif /* SQLITE_OMIT_WINDOWFUNC */
135325 static void groupConcatFinalize(sqlite3_context *context){
135326 GroupConcatCtx *pGCC
135327 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
135328 if( pGCC ){
135329 sqlite3ResultStrAccum(context, &pGCC->str);
135330 #ifndef SQLITE_OMIT_WINDOWFUNC
135331 sqlite3_free(pGCC->pnSepLengths);
135332 #endif
135333 }
135334 }
135335 #ifndef SQLITE_OMIT_WINDOWFUNC
135336 static void groupConcatValue(sqlite3_context *context){
135337 GroupConcatCtx *pGCC
135338 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
135339 if( pGCC ){
135340 StrAccum *pAccum = &pGCC->str;
135341 if( pAccum->accError==SQLITE_TOOBIG ){
135342 sqlite3_result_error_toobig(context);
135343 }else if( pAccum->accError==SQLITE_NOMEM ){
135344 sqlite3_result_error_nomem(context);
135345 }else if( pGCC->nAccum>0 && pAccum->nChar==0 ){
135346 sqlite3_result_text(context, "", 1, SQLITE_STATIC);
135347 }else{
135348 const char *zText = sqlite3_str_value(pAccum);
135349 sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
135350 }
135351 }
135352 }
135353 #else
135354 # define groupConcatValue 0
135355 #endif /* SQLITE_OMIT_WINDOWFUNC */
@@ -135976,17 +136405,21 @@
135976 static void percentSort(
135977 double *a, /* Array to sort */
135978 unsigned int n, /* Number of elements in array a[] */
135979 int iReq /* Element caller cares about (or -ve) */
135980 ){
135981 int iLt; /* Entries before a[iLt] are less than rPivot */
135982 int iGt; /* Entries at or after a[iGt] are greater than rPivot */
135983 int i; /* Loop counter */
135984 double rPivot; /* The pivot value */
135985
135986 assert( n>=2 );
135987 do{
 
 
 
 
135988 if( a[0]>a[n-1] ){
135989 SWAP_DOUBLE(a[0],a[n-1])
135990 }
135991 if( n==2 ) return;
135992 iGt = n-1;
@@ -135995,10 +136428,15 @@
135995 SWAP_DOUBLE(a[0],a[i])
135996 }else if( a[i]>a[iGt] ){
135997 SWAP_DOUBLE(a[i],a[iGt])
135998 }
135999 if( n==3 ) return;
 
 
 
 
 
136000 rPivot = a[i];
136001 iLt = i = 1;
136002 do{
136003 if( a[i]<rPivot ){
136004 if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
@@ -136012,12 +136450,16 @@
136012 }else{
136013 i++;
136014 }
136015 }while( i<iGt );
136016
 
 
136017 assert( a[iLt]==rPivot );
136018 assert( iGt>iLt );
 
 
136019
136020 if( iReq>=0 ){
136021 /* In this case, the only elements that the caller requires sorted into
136022 ** the correct positions are elements a[iReq] and a[iReq+1]. At this
136023 ** point we know that element a[iLt] is in the correct position and
@@ -136190,12 +136632,11 @@
136190 sqlite3_str_appendall(pStr, ",\"journal\":");
136191 rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr);
136192 if( rc ) sqlite3_str_append(pStr, "null", 4);
136193 }
136194 sqlite3_str_append(pStr, "}", 1);
136195 sqlite3_result_text(context, sqlite3_str_finish(pStr), -1,
136196 sqlite3_free);
136197 }
136198 sqlite3BtreeLeave(pBtree);
136199 }else{
136200 sqlite3_result_text(context, "{}", 2, SQLITE_STATIC);
136201 }
@@ -136307,12 +136748,12 @@
136307 }else{
136308 sqlite3_str_appendf(pResult, ", NULL");
136309 }
136310 }
136311 }
136312 sqlite3_result_text(ctx, sqlite3_str_finish(pResult), -1, sqlite3_free);
136313 }
 
136314 sqlite3_free_filename(zFile);
136315 sqlite3_free(zErr);
136316 }
136317 #endif /* SQLITE_DEBUG */
136318
@@ -136405,11 +136846,11 @@
136405 VFUNCTION(random, 0, 0, 0, randomFunc ),
136406 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
136407 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
136408 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
136409 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
136410 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
136411 FUNCTION(unistr, 1, 0, 0, unistrFunc ),
136412 FUNCTION(quote, 1, 0, 0, quoteFunc ),
136413 FUNCTION(unistr_quote, 1, 1, 0, quoteFunc ),
136414 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
136415 VFUNCTION(changes, 0, 0, 0, changes ),
@@ -138454,19 +138895,23 @@
138454 pParse->nErr++;
138455 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
138456 return 0;
138457 }
138458
 
 
 
138459 pInfo = pToplevel->pAinc;
138460 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
138461 if( pInfo==0 ){
138462 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
138463 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
138464 testcase( pParse->earlyCleanup );
138465 if( pParse->db->mallocFailed ) return 0;
138466 pInfo->pNext = pToplevel->pAinc;
138467 pToplevel->pAinc = pInfo;
 
138468 pInfo->pTab = pTab;
138469 pInfo->iDb = iDb;
138470 pToplevel->nMem++; /* Register to hold name of table */
138471 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
138472 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
@@ -138491,10 +138936,11 @@
138491 ** only called from the top-level */
138492 assert( pParse->pTriggerTab==0 );
138493 assert( sqlite3IsToplevel(pParse) );
138494
138495 assert( v ); /* We failed long ago if this is not so */
 
138496 for(p = pParse->pAinc; p; p = p->pNext){
138497 static const int iLn = VDBE_OFFSET_LINENO(2);
138498 static const VdbeOpList autoInc[] = {
138499 /* 0 */ {OP_Null, 0, 0, 0},
138500 /* 1 */ {OP_Rewind, 0, 10, 0},
@@ -138558,10 +139004,11 @@
138558 AutoincInfo *p;
138559 Vdbe *v = pParse->pVdbe;
138560 sqlite3 *db = pParse->db;
138561
138562 assert( v );
 
138563 for(p = pParse->pAinc; p; p = p->pNext){
138564 static const int iLn = VDBE_OFFSET_LINENO(2);
138565 static const VdbeOpList autoIncEnd[] = {
138566 /* 0 */ {OP_NotNull, 0, 2, 0},
138567 /* 1 */ {OP_NewRowid, 0, 0, 0},
@@ -138590,11 +139037,11 @@
138590 aOp[3].p5 = OPFLAG_APPEND;
138591 sqlite3ReleaseTempReg(pParse, iRec);
138592 }
138593 }
138594 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
138595 if( pParse->pAinc ) autoIncrementEnd(pParse);
138596 }
138597 #else
138598 /*
138599 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
138600 ** above are all no-ops
@@ -140244,10 +140691,26 @@
140244 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
140245 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
140246 }else{
140247 pTrigger = 0;
140248 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140249 }
140250 if( regTrigCnt ){
140251 /* Replace triggers might exist. Allocate the counter and
140252 ** initialize it to zero. */
140253 regTrigCnt = ++pParse->nMem;
@@ -140296,13 +140759,17 @@
140296 ** the UNIQUE constraints have run.
140297 */
140298 if( onError==OE_Replace /* IPK rule is REPLACE */
140299 && onError!=overrideError /* Rules for other constraints are different */
140300 && pTab->pIndex /* There exist other constraints */
140301 && !upsertIpkDelay /* IPK check already deferred by UPSERT */
140302 ){
140303 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
 
 
 
 
 
140304 VdbeComment((v, "defer IPK REPLACE until last"));
140305 }
140306
140307 if( isUpdate ){
140308 /* pkChng!=0 does not mean that the rowid has changed, only that
@@ -140392,15 +140859,15 @@
140392 sqlite3VdbeGoto(v, ignoreDest);
140393 break;
140394 }
140395 }
140396 sqlite3VdbeResolveLabel(v, addrRowidOk);
140397 if( pUpsert && pUpsertClause!=pUpsert ){
140398 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
140399 }else if( ipkTop ){
140400 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
140401 sqlite3VdbeJumpHere(v, ipkTop-1);
 
 
140402 }
140403 }
140404
140405 /* Test all UNIQUE constraints by creating entries for each UNIQUE
140406 ** index and making sure that duplicate entries do not already exist.
@@ -140416,10 +140883,11 @@
140416 int regIdx; /* Range of registers holding content for pIdx */
140417 int regR; /* Range of registers holding conflicting PK */
140418 int iThisCur; /* Cursor for this UNIQUE index */
140419 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
140420 int addrConflictCk; /* First opcode in the conflict check logic */
 
140421
140422 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
140423 if( pUpsert ){
140424 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
140425 if( upsertIpkDelay && pUpsertClause==pUpsert ){
@@ -140591,10 +141059,15 @@
140591 VdbeCoverageIf(v, op==OP_Ne);
140592 }
140593 }
140594 }
140595 }
 
 
 
 
 
140596
140597 /* Generate code that executes if the new index entry is not unique */
140598 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
140599 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
140600 switch( onError ){
@@ -140617,17 +141090,11 @@
140617 testcase( onError==OE_Ignore );
140618 sqlite3VdbeGoto(v, ignoreDest);
140619 break;
140620 }
140621 default: {
140622 int nConflictCk; /* Number of opcodes in conflict check logic */
140623
140624 assert( onError==OE_Replace );
140625 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
140626 assert( nConflictCk>0 || db->mallocFailed );
140627 testcase( nConflictCk<=0 );
140628 testcase( nConflictCk>1 );
140629 if( regTrigCnt ){
140630 sqlite3MultiWrite(pParse);
140631 nReplaceTrig++;
140632 }
140633 if( pTrigger && isUpdate ){
@@ -140637,62 +141104,62 @@
140637 regR, nPkField, 0, OE_Replace,
140638 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
140639 if( pTrigger && isUpdate ){
140640 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
140641 }
140642 if( regTrigCnt ){
140643 int addrBypass; /* Jump destination to bypass recheck logic */
140644
140645 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
140646 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
140647 VdbeComment((v, "bypass recheck"));
140648
140649 /* Here we insert code that will be invoked after all constraint
140650 ** checks have run, if and only if one or more replace triggers
140651 ** fired. */
140652 sqlite3VdbeResolveLabel(v, lblRecheckOk);
140653 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
140654 if( pIdx->pPartIdxWhere ){
140655 /* Bypass the recheck if this partial index is not defined
140656 ** for the current row */
140657 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
140658 VdbeCoverage(v);
140659 }
140660 /* Copy the constraint check code from above, except change
140661 ** the constraint-ok jump destination to be the address of
140662 ** the next retest block */
140663 while( nConflictCk>0 ){
140664 VdbeOp x; /* Conflict check opcode to copy */
140665 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
140666 ** Hence, make a complete copy of the opcode, rather than using
140667 ** a pointer to the opcode. */
140668 x = *sqlite3VdbeGetOp(v, addrConflictCk);
140669 if( x.opcode!=OP_IdxRowid ){
140670 int p2; /* New P2 value for copied conflict check opcode */
140671 const char *zP4;
140672 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
140673 p2 = lblRecheckOk;
140674 }else{
140675 p2 = x.p2;
140676 }
140677 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
140678 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
140679 sqlite3VdbeChangeP5(v, x.p5);
140680 VdbeCoverageIf(v, p2!=x.p2);
140681 }
140682 nConflictCk--;
140683 addrConflictCk++;
140684 }
140685 /* If the retest fails, issue an abort */
140686 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
140687
140688 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
140689 }
140690 seenReplace = 1;
140691 break;
140692 }
140693 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140694 sqlite3VdbeResolveLabel(v, addrUniqueOk);
140695 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
140696 if( pUpsertClause
140697 && upsertIpkReturn
140698 && sqlite3UpsertNextIsIPK(pUpsertClause)
@@ -140726,12 +141193,12 @@
140726 VdbeCoverage(v);
140727 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
140728 }else{
140729 sqlite3VdbeGoto(v, addrRecheck);
140730 }
140731 sqlite3VdbeResolveLabel(v, lblRecheckOk);
140732 }
 
140733
140734 /* Generate the table record */
140735 if( HasRowid(pTab) ){
140736 int regRec = aRegIdx[ix];
140737 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
@@ -142023,10 +142490,11 @@
142023 void (*str_free)(sqlite3_str*);
142024 int (*carray_bind)(sqlite3_stmt*,int,void*,int,int,void(*)(void*));
142025 int (*carray_bind_v2)(sqlite3_stmt*,int,void*,int,int,void(*)(void*),void*);
142026 /* Version 3.54.0 and later */
142027 sqlite3_int64 (*incomplete)(const char*);
 
142028 };
142029
142030 /*
142031 ** This is the function signature used for all extension entry points. It
142032 ** is also defined in the file "loadext.c".
@@ -142368,10 +142836,11 @@
142368 #define sqlite3_str_free sqlite3_api->str_free
142369 #define sqlite3_carray_bind sqlite3_api->carray_bind
142370 #define sqlite3_carray_bind_v2 sqlite3_api->carray_bind_v2
142371 /* Version 3.54.0 and later */
142372 #define sqlite3_incomplete sqlite3_api->incomplete
 
142373 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
142374
142375 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
142376 /* This case when the file really is being compiled as a loadable
142377 ** extension */
@@ -142905,11 +143374,13 @@
142905 sqlite3_carray_bind_v2,
142906 #else
142907 0,
142908 0,
142909 #endif
142910 sqlite3_incomplete
 
 
142911 };
142912
142913 /* True if x is the directory separator character
142914 */
142915 #if SQLITE_OS_WIN
@@ -147203,10 +147674,11 @@
147203 corruptSchema(pData, argv, 0);
147204 return 1;
147205 }
147206
147207 assert( iDb>=0 && iDb<db->nDb );
 
147208 if( argv[3]==0 ){
147209 corruptSchema(pData, argv, 0);
147210 }else if( argv[4]
147211 && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
147212 && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
@@ -147277,10 +147749,20 @@
147277 ){
147278 if( sqlite3Config.bExtraSchemaChecks ){
147279 corruptSchema(pData, argv, "invalid rootpage");
147280 }
147281 }
 
 
 
 
 
 
 
 
 
 
147282 }
147283 return 0;
147284 }
147285
147286 /*
@@ -147674,11 +148156,11 @@
147674 sqlite3 *db = pParse->db;
147675 assert( db!=0 );
147676 assert( db->pParse==pParse );
147677 assert( pParse->nested==0 );
147678 #ifndef SQLITE_OMIT_SHARED_CACHE
147679 if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
147680 #endif
147681 while( pParse->pCleanup ){
147682 ParseCleanup *pCleanup = pParse->pCleanup;
147683 pParse->pCleanup = pCleanup->pNext;
147684 pCleanup->xCleanup(db, pCleanup->pPtr);
@@ -147758,10 +148240,11 @@
147758 **
147759 ** Caution: Do not confuse this routine with sqlite3ParseObjectInit() which
147760 ** is generated by Lemon.
147761 */
147762 SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
 
147763 memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
147764 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
147765 assert( db->pParse!=pParse );
147766 pParse->pOuterParse = db->pParse;
147767 db->pParse = pParse;
@@ -148157,11 +148640,11 @@
148157 int nBytes, /* Length of zSql in bytes. */
148158 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148159 const void **pzTail /* OUT: End of parsed string */
148160 ){
148161 int rc;
148162 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
148163 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148164 return rc;
148165 }
148166 SQLITE_API int sqlite3_prepare16_v2(
148167 sqlite3 *db, /* Database handle. */
@@ -148169,11 +148652,11 @@
148169 int nBytes, /* Length of zSql in bytes. */
148170 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148171 const void **pzTail /* OUT: End of parsed string */
148172 ){
148173 int rc;
148174 rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
148175 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148176 return rc;
148177 }
148178 SQLITE_API int sqlite3_prepare16_v3(
148179 sqlite3 *db, /* Database handle. */
@@ -148182,11 +148665,11 @@
148182 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
148183 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148184 const void **pzTail /* OUT: End of parsed string */
148185 ){
148186 int rc;
148187 rc = sqlite3Prepare16(db,zSql,nBytes,
148188 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
148189 ppStmt,pzTail);
148190 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148191 return rc;
148192 }
@@ -148855,11 +149338,11 @@
148855 pRight->u3.pOn = 0;
148856 pRight->fg.isOn = 1;
148857 p->selFlags |= SF_OnToWhere;
148858 }
148859
148860 if( IsVirtual(pRightTab) && joinType==EP_OuterON && pRight->u1.pFuncArg ){
148861 p->selFlags |= SF_OnToWhere;
148862 }
148863 }
148864 return 0;
148865 }
@@ -149321,10 +149804,52 @@
149321 }
149322 pSort->nDefer = (u8)nDefer;
149323 *ppExtra = pExtra;
149324 }
149325 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149326
149327 /*
149328 ** This routine generates the code for the inside of the inner loop
149329 ** of a SELECT.
149330 **
@@ -149592,10 +150117,11 @@
149592 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
149593 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
149594 r1, pDest->zAffSdst, nResultCol);
149595 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
149596 if( pDest->iSDParm2 ){
 
149597 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
149598 regResult, nResultCol);
149599 ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
149600 }
149601 sqlite3ReleaseTempReg(pParse, r1);
@@ -151401,10 +151927,11 @@
151401 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
151402 r1, pDest->zAffSdst, pIn->nSdst);
151403 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
151404 pIn->iSdst, pIn->nSdst);
151405 if( pDest->iSDParm2>0 ){
 
151406 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
151407 pIn->iSdst, pIn->nSdst);
151408 ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
151409 }
151410 sqlite3ReleaseTempReg(pParse, r1);
@@ -155350,11 +155877,12 @@
155350 assert( ExprUseXList(pExpr) );
155351 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
155352 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
155353 if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
155354 pFrom = p->pSrc->a;
155355 if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */
 
155356 pSub = pFrom->u4.pSubq->pSelect;
155357 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
155358 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
155359 do{
155360 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
@@ -157581,12 +158109,13 @@
157581 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
157582 if( !IN_RENAME_OBJECT ){
157583 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
157584 if( !noErr ){
157585 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
 
 
157586 }else{
157587 assert( !db->init.busy );
157588 sqlite3CodeVerifySchema(pParse, iDb);
157589 VVA_ONLY( pParse->ifNotExists = 1; )
157590 }
157591 goto trigger_cleanup;
157592 }
@@ -161225,10 +161754,11 @@
161225 SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){
161226 HashElem *pThis, *pNext;
161227 #ifdef SQLITE_ENABLE_API_ARMOR
161228 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161229 #endif
 
161230 for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
161231 Module *pMod = (Module*)sqliteHashData(pThis);
161232 pNext = sqliteHashNext(pThis);
161233 if( azNames ){
161234 int ii;
@@ -161235,10 +161765,11 @@
161235 for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
161236 if( azNames[ii]!=0 ) continue;
161237 }
161238 createModule(db, pMod->zName, 0, 0, 0);
161239 }
 
161240 return SQLITE_OK;
161241 }
161242
161243 /*
161244 ** Decrement the reference count on a Module object. Destroy the
@@ -161803,10 +162334,12 @@
161803 char *zErr = 0;
161804 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
161805 if( rc!=SQLITE_OK ){
161806 sqlite3ErrorMsg(pParse, "%s", zErr);
161807 pParse->rc = rc;
 
 
161808 }
161809 sqlite3DbFree(db, zErr);
161810 }
161811
161812 return rc;
@@ -163082,14 +163615,11 @@
163082 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
163083 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
163084 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
163085 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
163086 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
163087
163088
163089
163090
163091
163092 /*
163093 ** Bitmasks for the operators on WhereTerm objects. These are all
163094 ** operators that are of interest to the query planner. An
163095 ** OR-ed combination of these values can be used when searching for
@@ -164554,10 +165084,11 @@
164554 testcase( pTerm->wtFlags & TERM_VIRTUAL );
164555 regRowid = sqlite3GetTempReg(pParse);
164556 regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
164557 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
164558 VdbeCoverage(pParse->pVdbe);
 
164559 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
164560 addrNxt, regRowid, 1);
164561 VdbeCoverage(pParse->pVdbe);
164562 }else{
164563 u16 nEq = pLoop->u.btree.nEq;
@@ -164567,10 +165098,11 @@
164567 assert( pLoop->wsFlags & WHERE_INDEXED );
164568 assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
164569 r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
164570 codeApplyAffinity(pParse, r1, nEq, zStartAff);
164571 sqlite3DbFree(pParse->db, zStartAff);
 
164572 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
164573 addrNxt, r1, nEq);
164574 VdbeCoverage(pParse->pVdbe);
164575 }
164576 pLevel->regFilter = 0;
@@ -165170,10 +165702,11 @@
165170 if( regBignull ){
165171 sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
165172 VdbeComment((v, "NULL-scan pass ctr"));
165173 }
165174 if( pLevel->regFilter ){
 
165175 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
165176 regBase, nEq);
165177 VdbeCoverage(v);
165178 filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
165179 }
@@ -165907,12 +166440,14 @@
165907 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
165908 VdbeCoverage(v);
165909 VdbeComment((v, "match against %s", pTab->zName));
165910 sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r);
165911 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
165912 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
165913 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
 
 
165914 sqlite3VdbeJumpHere(v, jmp1);
165915 sqlite3ReleaseTempRange(pParse, r, nPk+1);
165916 }
165917
165918 /* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -166060,11 +166595,11 @@
166060 WHERE_RIGHT_JOIN, 0);
166061 if( pSubWInfo ){
166062 int iCur = pLevel->iTabCur;
166063 int r = ++pParse->nMem;
166064 int nPk;
166065 int jmp;
166066 int addrCont = sqlite3WhereContinueLabel(pSubWInfo);
166067 Table *pTab = pTabItem->pSTab;
166068 if( HasRowid(pTab) ){
166069 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
166070 nPk = 1;
@@ -166076,15 +166611,17 @@
166076 for(iPk=0; iPk<nPk; iPk++){
166077 int iCol = pPk->aiColumn[iPk];
166078 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
166079 }
166080 }
166081 jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
166082 VdbeCoverage(v);
 
 
166083 sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
166084 VdbeCoverage(v);
166085 sqlite3VdbeJumpHere(v, jmp);
166086 sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
166087 sqlite3WhereEnd(pSubWInfo);
166088 }
166089 sqlite3ExprDelete(pParse->db, pSubWhere);
166090 ExplainQueryPlanPop(pParse);
@@ -167001,33 +167538,62 @@
167001 }
167002 }
167003 }
167004 }
167005
167006 /* At this point, okToChngToIN is true if original pTerm satisfies
167007 ** case 1. In that case, construct a new virtual term that is
167008 ** pTerm converted into an IN operator.
 
 
 
 
 
 
167009 */
167010 if( okToChngToIN ){
167011 Expr *pDup; /* A transient duplicate expression */
167012 ExprList *pList = 0; /* The RHS of the IN operator */
167013 Expr *pLeft = 0; /* The LHS of the IN operator */
 
167014 Expr *pNew; /* The complete IN operator */
167015
167016 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
 
167017 if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
167018 assert( pOrTerm->eOperator & WO_EQ );
167019 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
167020 assert( pOrTerm->leftCursor==iCursor );
167021 assert( pOrTerm->u.x.leftColumn==iColumn );
167022 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
 
167023 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
167024 pLeft = pOrTerm->pExpr->pLeft;
 
 
 
 
 
 
 
 
 
 
 
167025 }
167026 assert( pLeft!=0 );
167027 pDup = sqlite3ExprDup(db, pLeft, 0);
167028 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
 
 
 
 
 
 
 
 
 
167029 if( pNew ){
167030 int idxNew;
167031 transferJoinMarkings(pNew, pExpr);
167032 assert( ExprUseXList(pNew) );
167033 pNew->x.pList = pList;
@@ -168006,10 +168572,14 @@
168006 Expr *pColRef;
168007 Expr *pTerm;
168008 if( pItem->fg.isTabFunc==0 ) return;
168009 pTab = pItem->pSTab;
168010 assert( pTab!=0 );
 
 
 
 
168011 pArgs = pItem->u1.pFuncArg;
168012 if( pArgs==0 ) return;
168013 for(j=k=0; j<pArgs->nExpr; j++){
168014 Expr *pRhs;
168015 u32 joinType;
@@ -168039,10 +168609,20 @@
168039 }
168040 sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
168041 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
168042 }
168043 }
 
 
 
 
 
 
 
 
 
 
168044
168045 /************** End of whereexpr.c *******************************************/
168046 /************** Begin file where.c *******************************************/
168047 /*
168048 ** 2001 September 15
@@ -169051,11 +169631,11 @@
169051 WhereLoop *pLoop; /* The Loop object */
169052 char *zNotUsed; /* Extra space on the end of pIdx */
169053 Bitmask idxCols; /* Bitmap of columns used for indexing */
169054 Bitmask extraCols; /* Bitmap of additional columns */
169055 u8 sentWarning = 0; /* True if a warning has been issued */
169056 u8 useBloomFilter = 0; /* True to also add a Bloom filter */
169057 Expr *pPartial = 0; /* Partial Index Expression */
169058 int iContinue = 0; /* Jump here to skip excluded rows */
169059 SrcList *pTabList; /* The complete FROM clause */
169060 SrcItem *pSrc; /* The FROM clause term to get the next index */
169061 int addrCounter = 0; /* Address where integer counter is initialized */
@@ -169178,22 +169758,17 @@
169178 Expr *pX = pTerm->pExpr;
169179 idxCols |= cMask;
169180 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
169181 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
169182 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
 
 
 
 
 
169183 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
169184 n++;
169185 if( ALWAYS(pX->pLeft!=0)
169186 && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
169187 ){
169188 /* TUNING: only use a Bloom filter on an automatic index
169189 ** if one or more key columns has the ability to hold numeric
169190 ** values, since strings all have the same hash in the Bloom
169191 ** filter implementation and hence a Bloom filter on a text column
169192 ** is not usually helpful. */
169193 useBloomFilter = 1;
169194 }
169195 }
169196 }
169197 }
169198 assert( (u32)n==pLoop->u.btree.nEq );
169199
@@ -169259,10 +169834,11 @@
169259 regRecord = sqlite3GetTempReg(pParse);
169260 regBase = sqlite3GenerateIndexKey(
169261 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
169262 );
169263 if( pLevel->regFilter ){
 
169264 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
169265 regBase, pLoop->u.btree.nEq);
169266 }
169267 sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
169268 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
@@ -169374,10 +169950,11 @@
169374 if( sz<10000 ){
169375 sz = 10000;
169376 }else if( sz>10000000 ){
169377 sz = 10000000;
169378 }
 
169379 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
169380
169381 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
169382 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
169383 for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
@@ -169396,10 +169973,11 @@
169396 }else{
169397 Index *pIdx = pLoop->u.btree.pIndex;
169398 int n = pLoop->u.btree.nEq;
169399 int r1 = sqlite3GetTempRange(pParse, n);
169400 int jj;
 
169401 for(jj=0; jj<n; jj++){
169402 assert( pIdx->pTable==pItem->pSTab );
169403 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
169404 }
169405 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
@@ -173052,11 +173630,11 @@
173052 }
173053 #ifndef SQLITE_OMIT_VIRTUALTABLE
173054 if( IsVirtual(pItem->pSTab) ){
173055 SrcItem *p;
173056 for(p=&pItem[1]; p<pEnd; p++){
173057 if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
173058 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
173059 }
173060 }
173061 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
173062 }else
@@ -174682,23 +175260,21 @@
174682 Table *pTab = pItem->pSTab;
174683 if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
174684 pTab->tabFlags |= TF_MaybeReanalyze;
174685 if( i>=1
174686 && (pLoop->wsFlags & reqFlags)==reqFlags
174687 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
174688 && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
174689 ){
174690 if( nSearch > pTab->nRowLogEst ){
174691 testcase( pItem->fg.jointype & JT_LEFT );
174692 pLoop->wsFlags |= WHERE_BLOOMFILTER;
174693 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
174694 WHERETRACE(0xffffffff, (
174695 "-> use Bloom-filter on loop %c because there are ~%.1e "
174696 "lookups into %s which has only ~%.1e rows\n",
174697 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
174698 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
174699 }
174700 }
174701 nSearch += pLoop->nOut;
174702 }
174703 }
174704
@@ -175432,26 +176008,31 @@
175432 }
175433 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
175434 (u8*)&colUsed, P4_INT64);
175435 }
175436 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
 
 
 
 
 
175437 }
175438 }
175439 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
175440 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
175441 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
175442 ){
175443 WhereRightJoin *pRJ = pLevel->pRJ;
 
175444 pRJ->iMatch = pParse->nTab++;
175445 pRJ->regBloom = ++pParse->nMem;
175446 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
175447 pRJ->regReturn = ++pParse->nMem;
175448 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
175449 assert( pTab==pTabItem->pSTab );
175450 if( HasRowid(pTab) ){
175451 KeyInfo *pInfo;
175452 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
 
175453 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
175454 if( pInfo ){
175455 pInfo->aColl[0] = 0;
175456 pInfo->aSortFlags[0] = 0;
175457 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
@@ -175458,10 +176039,17 @@
175458 }
175459 }else{
175460 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
175461 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
175462 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
 
 
 
 
 
 
 
175463 }
175464 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
175465 /* The nature of RIGHT JOIN processing is such that it messes up
175466 ** the output order. So omit any ORDER BY/GROUP BY elimination
175467 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
@@ -176155,11 +176743,11 @@
176155 case SQLITE_INTEGER:
176156 iVal = sqlite3_value_int64(apArg[1]);
176157 break;
176158 case SQLITE_FLOAT: {
176159 double fVal = sqlite3_value_double(apArg[1]);
176160 if( ((i64)fVal)!=fVal ) goto error_out;
176161 iVal = (i64)fVal;
176162 break;
176163 }
176164 default:
176165 goto error_out;
@@ -186803,67 +187391,64 @@
186803 SQLITE_API char *sqlite3_data_directory = 0;
186804
186805 /*
186806 ** Initialize SQLite.
186807 **
186808 ** This routine must be called to initialize the memory allocation,
186809 ** VFS, and mutex subsystems prior to doing any serious work with
186810 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
186811 ** this routine will be called automatically by key routines such as
186812 ** sqlite3_open().
186813 **
186814 ** This routine is a no-op except on its very first call for the process,
186815 ** or for the first call after a call to sqlite3_shutdown.
 
 
186816 **
186817 ** The first thread to call this routine runs the initialization to
186818 ** completion. If subsequent threads call this routine before the first
 
 
 
 
 
 
 
 
 
 
186819 ** thread has finished the initialization process, then the subsequent
186820 ** threads must block until the first thread finishes with the initialization.
186821 **
186822 ** The first thread might call this routine recursively. Recursive
186823 ** calls to this routine should not block, of course. Otherwise the
186824 ** initialization process would never complete.
186825 **
186826 ** Let X be the first thread to enter this routine. Let Y be some other
186827 ** thread. Then while the initial invocation of this routine by X is
186828 ** incomplete, it is required that:
186829 **
186830 ** * Calls to this routine from Y must block until the outer-most
186831 ** call by X completes.
186832 **
186833 ** * Recursive calls to this routine from thread X return immediately
186834 ** without blocking.
186835 */
186836 SQLITE_API int sqlite3_initialize(void){
186837 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
186838 int rc; /* Result code */
186839 #ifdef SQLITE_EXTRA_INIT
186840 int bRunExtraInit = 0; /* Extra initialization needed */
186841 #endif
186842
186843 #ifdef SQLITE_OMIT_WSD
186844 rc = sqlite3_wsd_init(4096, 24);
186845 if( rc!=SQLITE_OK ){
186846 return rc;
186847 }
186848 #endif
186849
186850 /* If the following assert() fails on some obscure processor/compiler
186851 ** combination, the work-around is to set the correct pointer
186852 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
 
 
186853 assert( SQLITE_PTRSIZE==sizeof(char*) );
186854
186855 /* If SQLite is already completely initialized, then this call
186856 ** to sqlite3_initialize() should be a no-op. But the initialization
186857 ** must be complete. So isInit must not be set until the very end
186858 ** of this routine.
186859 */
186860 if( sqlite3GlobalConfig.isInit ){
186861 sqlite3MemoryBarrier();
186862 return SQLITE_OK;
186863 }
186864
186865 /* Make sure the mutex subsystem is initialized. If unable to
186866 ** initialize the mutex subsystem, return early with the error.
186867 ** If the system is so sick that we are unable to allocate a mutex,
186868 ** there is not much SQLite is going to be able to do.
186869 **
@@ -187003,10 +187588,30 @@
187003 int SQLITE_EXTRA_INIT(const char*);
187004 rc = SQLITE_EXTRA_INIT(0);
187005 }
187006 #endif
187007 return rc;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187008 }
187009
187010 /*
187011 ** Undo the effects of sqlite3_initialize(). Must not be called while
187012 ** there are outstanding database connections or memory allocations or
@@ -187755,17 +188360,21 @@
187755
187756 /*
187757 ** Return the ROWID of the most recent insert
187758 */
187759 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
 
187760 #ifdef SQLITE_ENABLE_API_ARMOR
187761 if( !sqlite3SafetyCheckOk(db) ){
187762 (void)SQLITE_MISUSE_BKPT;
187763 return 0;
187764 }
187765 #endif
187766 return db->lastRowid;
 
 
 
187767 }
187768
187769 /*
187770 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
187771 */
@@ -187784,33 +188393,41 @@
187784 /*
187785 ** Return the number of changes in the most recently executed DML
187786 ** statement.
187787 */
187788 SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3 *db){
 
187789 #ifdef SQLITE_ENABLE_API_ARMOR
187790 if( !sqlite3SafetyCheckOk(db) ){
187791 (void)SQLITE_MISUSE_BKPT;
187792 return 0;
187793 }
187794 #endif
187795 return db->nChange;
 
 
 
187796 }
187797 SQLITE_API int sqlite3_changes(sqlite3 *db){
187798 return (int)sqlite3_changes64(db);
187799 }
187800
187801 /*
187802 ** Return the number of changes since the database handle was opened.
187803 */
187804 SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
 
187805 #ifdef SQLITE_ENABLE_API_ARMOR
187806 if( !sqlite3SafetyCheckOk(db) ){
187807 (void)SQLITE_MISUSE_BKPT;
187808 return 0;
187809 }
187810 #endif
187811 return db->nTotalChange;
 
 
 
187812 }
187813 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
187814 return (int)sqlite3_total_changes64(db);
187815 }
187816
@@ -188489,10 +189106,11 @@
188489 */
188490 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
188491 #ifdef SQLITE_ENABLE_API_ARMOR
188492 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
188493 #endif
 
188494 if( ms>0 ){
188495 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
188496 (void*)db);
188497 db->busyTimeout = ms;
188498 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
@@ -188499,10 +189117,11 @@
188499 db->setlkTimeout = ms;
188500 #endif
188501 }else{
188502 sqlite3_busy_handler(db, 0, 0);
188503 }
 
188504 return SQLITE_OK;
188505 }
188506
188507 /*
188508 ** Set the setlk timeout value.
@@ -189404,13 +190023,15 @@
189404 /*
189405 ** Return the byte offset of the most recent error
189406 */
189407 SQLITE_API int sqlite3_error_offset(sqlite3 *db){
189408 int iOffset = -1;
189409 if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
189410 sqlite3_mutex_enter(db->mutex);
189411 iOffset = db->errByteOffset;
 
 
189412 sqlite3_mutex_leave(db->mutex);
189413 }
189414 return iOffset;
189415 }
189416
@@ -189460,29 +190081,47 @@
189460 /*
189461 ** Return the most recent error code generated by an SQLite routine. If NULL is
189462 ** passed to this function, we assume a malloc() failed during sqlite3_open().
189463 */
189464 SQLITE_API int sqlite3_errcode(sqlite3 *db){
189465 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
 
 
189466 return SQLITE_MISUSE_BKPT;
189467 }
189468 if( !db || db->mallocFailed ){
189469 return SQLITE_NOMEM_BKPT;
 
 
 
189470 }
189471 return db->errCode & db->errMask;
 
189472 }
189473 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
189474 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
 
 
189475 return SQLITE_MISUSE_BKPT;
189476 }
189477 if( !db || db->mallocFailed ){
189478 return SQLITE_NOMEM_BKPT;
 
 
 
189479 }
189480 return db->errCode;
 
189481 }
189482 SQLITE_API int sqlite3_system_errno(sqlite3 *db){
189483 return db ? db->iSysErrno : 0;
 
 
 
 
 
 
189484 }
189485
189486 /*
189487 ** Return a string that describes the kind of error specified in the
189488 ** argument. For now, this simply calls the internal sqlite3ErrStr()
@@ -189585,10 +190224,11 @@
189585 SQLITE_MAX_LIKE_PATTERN_LENGTH,
189586 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
189587 SQLITE_MAX_TRIGGER_DEPTH,
189588 SQLITE_MAX_WORKER_THREADS,
189589 SQLITE_MAX_PARSER_DEPTH,
 
189590 };
189591
189592 /*
189593 ** Make sure the hard limits are set to reasonable values
189594 */
@@ -189667,25 +190307,28 @@
189667 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
189668 SQLITE_MAX_LIKE_PATTERN_LENGTH );
189669 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
189670 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
189671 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
189672 assert( SQLITE_LIMIT_PARSER_DEPTH==(SQLITE_N_LIMIT-1) );
 
189673
189674
189675 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
189676 return -1;
189677 }
 
189678 oldLimit = db->aLimit[limitId];
189679 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
189680 if( newLimit>aHardLimit[limitId] ){
189681 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
189682 }else if( newLimit<SQLITE_MIN_LENGTH && limitId==SQLITE_LIMIT_LENGTH ){
189683 newLimit = SQLITE_MIN_LENGTH;
189684 }
189685 db->aLimit[limitId] = newLimit;
189686 }
 
189687 return oldLimit; /* IMP: R-53341-35419 */
189688 }
189689
189690 /*
189691 ** This function is used to parse both URIs and non-URI filenames passed by the
@@ -189724,22 +190367,22 @@
189724 int rc = SQLITE_OK;
189725 unsigned int flags = *pFlags;
189726 const char *zVfs = zDefaultVfs;
189727 char *zFile;
189728 char c;
189729 int nUri = sqlite3Strlen30(zUri);
189730
189731 assert( *pzErrMsg==0 );
189732
189733 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
189734 || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
189735 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
189736 ){
189737 char *zOpt;
189738 int eState; /* Parser state when parsing URI */
189739 int iIn; /* Input character index */
189740 int iOut = 0; /* Output character index */
189741 u64 nByte = nUri+8; /* Bytes of space to allocate */
189742
189743 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
189744 ** method that there may be extra parameters following the file-name. */
189745 flags |= SQLITE_OPEN_URI;
@@ -189769,11 +190412,11 @@
189769 if( zUri[5]=='/' && zUri[6]=='/' ){
189770 iIn = 7;
189771 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
189772 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
189773 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
189774 iIn-7, &zUri[7]);
189775 rc = SQLITE_ERROR;
189776 goto parse_uri_out;
189777 }
189778 }
189779 #endif
@@ -189844,15 +190487,15 @@
189844
189845 /* Check if there were any options specified that should be interpreted
189846 ** here. Options that are interpreted here include "vfs" and those that
189847 ** correspond to flags that may be passed to the sqlite3_open_v2()
189848 ** method. */
189849 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
189850 while( zOpt[0] ){
189851 int nOpt = sqlite3Strlen30(zOpt);
189852 char *zVal = &zOpt[nOpt+1];
189853 int nVal = sqlite3Strlen30(zVal);
189854
189855 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
189856 zVfs = zVal;
189857 }else{
189858 struct OpenMode {
@@ -189894,11 +190537,11 @@
189894 if( aMode ){
189895 int i;
189896 int mode = 0;
189897 for(i=0; aMode[i].z; i++){
189898 const char *z = aMode[i].z;
189899 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
189900 mode = aMode[i].mode;
189901 break;
189902 }
189903 }
189904 if( mode==0 ){
@@ -190579,17 +191222,21 @@
190579 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
190580 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
190581 ** by the next COMMIT or ROLLBACK.
190582 */
190583 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
 
190584 #ifdef SQLITE_ENABLE_API_ARMOR
190585 if( !sqlite3SafetyCheckOk(db) ){
190586 (void)SQLITE_MISUSE_BKPT;
190587 return 0;
190588 }
190589 #endif
190590 return db->autoCommit;
 
 
 
190591 }
190592
190593 /*
190594 ** The following routines are substitutes for constants SQLITE_CORRUPT,
190595 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
@@ -191610,21 +192257,23 @@
191610 /*
191611 ** Return the name of the N-th database schema. Return NULL if N is out
191612 ** of range.
191613 */
191614 SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N){
 
191615 #ifdef SQLITE_ENABLE_API_ARMOR
191616 if( !sqlite3SafetyCheckOk(db) ){
191617 (void)SQLITE_MISUSE_BKPT;
191618 return 0;
191619 }
191620 #endif
191621 if( N<0 || N>=db->nDb ){
191622 return 0;
191623 }else{
191624 return db->aDb[N].zDbSName;
191625 }
 
 
191626 }
191627
191628 /*
191629 ** Return the filename of the database associated with a database
191630 ** connection.
@@ -197602,10 +198251,11 @@
197602 }else{
197603 int nDistance;
197604 char *p1;
197605 char *p2;
197606 char *aOut;
 
197607
197608 if( nMaxUndeferred>iPrev ){
197609 p1 = aPoslist;
197610 p2 = pPhrase->doclist.pList;
197611 nDistance = nMaxUndeferred - iPrev;
@@ -197613,11 +198263,11 @@
197613 p1 = pPhrase->doclist.pList;
197614 p2 = aPoslist;
197615 nDistance = iPrev - nMaxUndeferred;
197616 }
197617
197618 aOut = (char *)sqlite3Fts3MallocZero(((i64)nPoslist)+FTS3_BUFFER_PADDING);
197619 if( !aOut ){
197620 sqlite3_free(aPoslist);
197621 return SQLITE_NOMEM;
197622 }
197623
@@ -207898,11 +208548,11 @@
207898 if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
207899 sqlite3_reset(pSelect);
207900 return FTS_CORRUPT_VTAB;
207901 }
207902
207903 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
207904 pWriter->iStart = iStart;
207905 pWriter->iEnd = iEnd;
207906 pWriter->iAbsLevel = iAbsLevel;
207907 pWriter->iIdx = iIdx;
207908
@@ -210015,12 +210665,12 @@
210015
210016 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
210017 ** to grow the buffer until so that it is big enough to accommodate the
210018 ** appended data.
210019 */
210020 if( pStr->n+nAppend+1>=pStr->nAlloc ){
210021 sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
210022 char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
210023 if( !zNew ){
210024 return SQLITE_NOMEM;
210025 }
210026 pStr->z = zNew;
@@ -213118,11 +213768,11 @@
213118 /*
213119 ** Expand pParse->aBlob so that it holds at least N bytes.
213120 **
213121 ** Return the number of errors.
213122 */
213123 static int jsonBlobExpand(JsonParse *pParse, u32 N){
213124 u8 *aNew;
213125 u64 t;
213126 assert( N>pParse->nBlobAlloc );
213127 if( pParse->nBlobAlloc==0 ){
213128 t = 100;
@@ -213146,11 +213796,11 @@
213146 **
213147 ** Return true on success. Return false on OOM.
213148 */
213149 static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){
213150 u8 *aOld;
213151 u32 nSize;
213152 assert( !pParse->bReadOnly );
213153 if( pParse->oom ) return 0;
213154 if( pParse->nBlobAlloc>0 ) return 1;
213155 aOld = pParse->aBlob;
213156 nSize = pParse->nBlob + nExtra;
@@ -213167,11 +213817,11 @@
213167 */
213168 static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte(
213169 JsonParse *pParse,
213170 u8 c
213171 ){
213172 jsonBlobExpand(pParse, pParse->nBlob+1);
213173 if( pParse->oom==0 ){
213174 assert( pParse->nBlob+1<=pParse->nBlobAlloc );
213175 pParse->aBlob[pParse->nBlob++] = c;
213176 }
213177 }
@@ -213194,11 +213844,11 @@
213194 JsonParse *pParse,
213195 u8 eType,
213196 u64 szPayload,
213197 const void *aPayload
213198 ){
213199 if( jsonBlobExpand(pParse, pParse->nBlob+szPayload+9) ) return;
213200 jsonBlobAppendNode(pParse, eType, szPayload, aPayload);
213201 }
213202
213203
213204 /* Append a node type byte together with the payload size and
@@ -213284,11 +213934,11 @@
213284 }else{
213285 nNeeded = 4;
213286 }
213287 delta = nNeeded - nExtra;
213288 if( delta ){
213289 u32 newSize = pParse->nBlob + delta;
213290 if( delta>0 ){
213291 if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){
213292 return 0; /* OOM error. Error state recorded in pParse->oom. */
213293 }
213294 a = &pParse->aBlob[i];
@@ -214220,11 +214870,12 @@
214220 u32 k = 0;
214221 const char *zIn = (const char*)&pParse->aBlob[i+n];
214222 if( sz==0 ) goto malformed_jsonb;
214223 if( zIn[0]=='-' ){
214224 jsonAppendChar(pOut, '-');
214225 k++;
 
214226 }
214227 if( zIn[k]=='.' ){
214228 jsonAppendChar(pOut, '0');
214229 }
214230 for(; k<sz; k++){
@@ -214631,11 +215282,11 @@
214631 ){
214632 return;
214633 }
214634 if( d!=0 ){
214635 if( pParse->nBlob + d > pParse->nBlobAlloc ){
214636 jsonBlobExpand(pParse, pParse->nBlob+d);
214637 if( pParse->oom ) return;
214638 }
214639 memmove(&pParse->aBlob[iDel+nIns],
214640 &pParse->aBlob[iDel+nDel],
214641 pParse->nBlob - (iDel+nDel));
@@ -215418,12 +216069,11 @@
215418 jsonBlobAppendNode(pParse, JSONB_TEXTRAW, nJson, zJson);
215419 }
215420 break;
215421 }
215422 case SQLITE_FLOAT: {
215423 double r = sqlite3_value_double(pArg);
215424 if( NEVER(sqlite3IsNaN(r)) ){
215425 jsonBlobAppendNode(pParse, JSONB_NULL, 0, 0);
215426 }else{
215427 int n = sqlite3_value_bytes(pArg);
215428 const char *z = (const char*)sqlite3_value_text(pArg);
215429 if( z==0 ) return 1;
@@ -217184,11 +217834,13 @@
217184 */
217185 static int jsonSkipLabel(JsonEachCursor *p){
217186 if( p->eType==JSONB_OBJECT ){
217187 u32 sz = 0;
217188 u32 n = jsonbPayloadSize(&p->sParse, p->i, &sz);
217189 return p->i + n + sz;
 
 
217190 }else{
217191 return p->i;
217192 }
217193 }
217194
@@ -218016,11 +218668,11 @@
218016 int mxLevel; /* iLevel value for root of the tree */
218017 RtreeSearchPoint *aPoint; /* Priority queue for search points */
218018 sqlite3_stmt *pReadAux; /* Statement to read aux-data */
218019 RtreeSearchPoint sPoint; /* Cached next search point */
218020 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
218021 u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
218022 };
218023
218024 /* Return the Rtree of a RtreeCursor */
218025 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
218026
@@ -218499,11 +219151,11 @@
218499 ** are the leaves, and so on. If the depth as specified on the root node
218500 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
218501 */
218502 if( rc==SQLITE_OK && pNode && iNode==1 ){
218503 pRtree->iDepth = readInt16(pNode->zData);
218504 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
218505 rc = SQLITE_CORRUPT_VTAB;
218506 RTREE_IS_CORRUPT(pRtree);
218507 }
218508 }
218509
@@ -226154,31 +226806,31 @@
226154 int lenSrc, /* Length of the source file */
226155 const char *zDelta, /* Delta to apply to the pattern */
226156 int lenDelta, /* Length of the delta */
226157 char *zOut /* Write the output into this preallocated buffer */
226158 ){
226159 unsigned int limit;
226160 unsigned int total = 0;
226161 #if RBU_ENABLE_DELTA_CKSUM
226162 char *zOrigOut = zOut;
226163 #endif
226164
226165 limit = rbuDeltaGetInt(&zDelta, &lenDelta);
226166 if( lenDelta<=0 || *zDelta!='\n' ){
226167 /* ERROR: size integer not terminated by "\n" */
226168 return -1;
226169 }
226170 zDelta++; lenDelta--;
226171 while( *zDelta && lenDelta>0 ){
226172 unsigned int cnt, ofst;
226173 cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
226174 if( lenDelta<=0 ) return -1;
226175 switch( zDelta[0] ){
226176 case '@': {
226177 zDelta++; lenDelta--;
226178 ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
226179 if( lenDelta>0 || zDelta[0]!=',' ){
226180 /* ERROR: copy command not terminated by ',' */
226181 return -1;
226182 }
226183 zDelta++; lenDelta--;
226184 total += cnt;
@@ -226199,11 +226851,11 @@
226199 total += cnt;
226200 if( total>limit ){
226201 /* ERROR: insert command gives an output larger than predicted */
226202 return -1;
226203 }
226204 if( (i64)cnt>(i64)lenDelta ){
226205 /* ERROR: insert count exceeds size of delta */
226206 return -1;
226207 }
226208 memcpy(zOut, zDelta, cnt);
226209 zOut += cnt;
@@ -228212,17 +228864,17 @@
228212 char *zWhere = rbuObjIterGetWhere(p, pIter);
228213 char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
228214 char *zUpdate = 0;
228215
228216 pUp->zMask = (char*)&pUp[1];
228217 memcpy(pUp->zMask, zMask, pIter->nTblCol);
228218 pUp->pNext = pIter->pRbuUpdate;
228219 pIter->pRbuUpdate = pUp;
228220
228221 if( zSet ){
228222 const char *zPrefix = "";
228223
 
228224 if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
228225 zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
228226 zPrefix, pIter->zTbl, zSet, zWhere
228227 );
228228 p->rc = prepareFreeAndCollectError(
@@ -228308,10 +228960,13 @@
228308 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
228309 break;
228310
228311 case RBU_STATE_ROW:
228312 pRet->nRow = sqlite3_column_int(pStmt, 1);
 
 
 
228313 break;
228314
228315 case RBU_STATE_PROGRESS:
228316 pRet->nProgress = sqlite3_column_int64(pStmt, 1);
228317 break;
@@ -234473,11 +235128,11 @@
234473 SessionBuffer *p,
234474 const char *zStr,
234475 int *pRc
234476 ){
234477 int nStr = sqlite3Strlen30(zStr);
234478 if( 0==sessionBufferGrow(p, nStr+1, pRc) ){
234479 memcpy(&p->aBuf[p->nBuf], zStr, nStr);
234480 p->nBuf += nStr;
234481 p->aBuf[p->nBuf] = 0x00;
234482 }
234483 }
@@ -239557,11 +240212,16 @@
239557 int nRec;
239558 int rc = SQLITE_OK;
239559
239560 pIter->in.bNoDiscard = 1;
239561 while( SQLITE_ROW==(sessionChangesetNext(pIter, &aRec, &nRec, 0)) ){
239562 rc = sessionOneChangeIterToHash(pGrp, pIter, bRebase);
 
 
 
 
 
239563 if( rc!=SQLITE_OK ) break;
239564 }
239565
239566 if( rc==SQLITE_OK ) rc = pIter->rc;
239567 return rc;
@@ -239875,18 +240535,21 @@
239875 int nCol, /* Number of columns in each record */
239876 u8 *a1, int n1, /* Record 1 */
239877 u8 *a2, int n2, /* Record 2 */
239878 int *pRc /* IN/OUT: error code */
239879 ){
239880 sessionBufferGrow(pBuf, n1+n2, pRc);
 
 
 
239881 if( *pRc==SQLITE_OK ){
239882 int i;
239883 u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
239884 for(i=0; i<nCol; i++){
239885 int nn1 = sessionSerialLen(a1);
239886 int nn2 = sessionSerialLen(a2);
239887 if( *a1==0 || *a1==0xFF ){
239888 memcpy(pOut, a2, nn2);
239889 pOut += nn2;
239890 }else{
239891 memcpy(pOut, a1, nn1);
239892 pOut += nn1;
@@ -239924,24 +240587,25 @@
239924 sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
239925 u8 *aRec, int nRec, /* Local change */
239926 u8 *aChange, int nChange, /* Record to rebase against */
239927 int *pRc /* IN/OUT: Return Code */
239928 ){
239929 sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
239930 if( *pRc==SQLITE_OK ){
239931 int bData = 0;
239932 u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
239933 int i;
239934 u8 *a1 = aRec;
239935 u8 *a2 = aChange;
 
239936
239937 *pOut++ = SQLITE_UPDATE;
239938 *pOut++ = pIter->bIndirect;
239939 for(i=0; i<pIter->nCol; i++){
239940 int n1 = sessionSerialLen(a1);
239941 int n2 = sessionSerialLen(a2);
239942 if( pIter->abPK[i] || a2[0]==0 ){
239943 if( !pIter->abPK[i] && a1[0] ) bData = 1;
239944 memcpy(pOut, a1, n1);
239945 pOut += n1;
239946 }else if( a2[0]!=0xFF && a1[0] ){
239947 bData = 1;
@@ -240138,12 +240802,12 @@
240138 */
240139 SQLITE_API int sqlite3rebaser_configure(
240140 sqlite3_rebaser *p,
240141 int nRebase, const void *pRebase
240142 ){
240143 sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
240144 int rc; /* Return code */
 
240145 rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
240146 if( rc==SQLITE_OK ){
240147 rc = sessionChangesetToHash(pIter, &p->grp, 1);
240148 }
240149 sqlite3changeset_finalize(pIter);
@@ -250965,10 +251629,11 @@
250965 i64 szData = (sizeof(Fts5Data) + 7) & ~7;
250966 i64 nAlloc = szData + nByte + FTS5_DATA_PADDING;
250967 pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
250968 if( pRet ){
250969 pRet->nn = nByte;
 
250970 aOut = pRet->p = (u8*)pRet + szData;
250971 }else{
250972 rc = SQLITE_NOMEM;
250973 }
250974
@@ -250977,14 +251642,12 @@
250977 }
250978 if( rc!=SQLITE_OK ){
250979 sqlite3_free(pRet);
250980 pRet = 0;
250981 }else{
250982 /* TODO1: Fix this */
250983 pRet->p[nByte] = 0x00;
250984 pRet->p[nByte+1] = 0x00;
250985 pRet->szLeaf = fts5GetU16(&pRet->p[2]);
250986 }
250987 }
250988 p->rc = rc;
250989 p->nRead++;
250990 }
@@ -251001,13 +251664,21 @@
251001 */
251002 static void fts5DataRelease(Fts5Data *pData){
251003 sqlite3_free(pData);
251004 }
251005
 
 
 
 
251006 static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
251007 Fts5Data *pRet = fts5DataRead(p, iRowid);
251008 if( pRet ){
 
 
 
 
251009 if( pRet->szLeaf<4 || pRet->szLeaf>pRet->nn ){
251010 FTS5_CORRUPT_ROWID(p, iRowid);
251011 fts5DataRelease(pRet);
251012 pRet = 0;
251013 }
@@ -252914,10 +253585,14 @@
252914 const u8 *a = pIter->pLeaf->p;
252915 int iTermOff = 0;
252916
252917 pIter->iPgidxOff = pIter->pLeaf->szLeaf;
252918 pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff);
 
 
 
 
252919 pIter->iLeafOffset = iTermOff;
252920 fts5SegIterLoadTerm(p, pIter, 0);
252921 fts5SegIterLoadNPos(p, pIter);
252922 if( bDlidx ) fts5SegIterLoadDlidx(p, pIter);
252923
@@ -255240,19 +255915,19 @@
255240 for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
255241 i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
255242 int iNext = 0;
255243 u8 *aPg = 0;
255244
255245 pLeaf = fts5DataRead(p, iRowid);
255246 if( pLeaf==0 ) break;
255247 aPg = pLeaf->p;
255248
255249 iNext = fts5GetU16(&aPg[0]);
255250 if( iNext!=0 ){
255251 *pbLastInDoclist = 0;
255252 }
255253 if( iNext==0 && pLeaf->szLeaf!=pLeaf->nn ){
255254 fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
255255 }
255256
255257 if( iNext==0 ){
255258 /* The page contains no terms or rowids. Replace it with an empty
@@ -255535,19 +256210,19 @@
255535
255536 assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
255537 /* The entry being removed may be the only position list in
255538 ** its doclist. */
255539 for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
255540 Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
255541 int bEmpty = (pPg && pPg->nn==4);
255542 fts5DataRelease(pPg);
255543 if( bEmpty==0 ) break;
255544 }
255545
255546 if( iPgno==pSeg->iTermLeafPgno ){
255547 i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
255548 Fts5Data *pTerm = fts5DataRead(p, iId);
255549 if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
255550 u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
255551 int nTermIdx = pTerm->nn - pTerm->szLeaf;
255552 int iTermIdx = 0;
255553 i64 iTermOff = 0;
@@ -258495,11 +259170,11 @@
258495 int i;
258496
258497 /* Now check that the iter.nEmpty leaves following the current leaf
258498 ** (a) exist and (b) contain no terms. */
258499 for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
258500 Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
258501 if( pLeaf ){
258502 if( !fts5LeafIsTermless(pLeaf)
258503 || (i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf))
258504 ){
258505 FTS5_CORRUPT_ROWID(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
@@ -258623,13 +259298,17 @@
258623 iRowidOff = fts5LeafFirstRowidOff(pLeaf);
258624 if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
258625 FTS5_CORRUPT_ROWID(p, iRow);
258626 }else{
258627 iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
258628 res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
258629 if( res==0 ) res = nTerm - nIdxTerm;
258630 if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow);
 
 
 
 
258631 }
258632
258633 fts5IntegrityCheckPgidx(p, iRow, pLeaf);
258634 }
258635 fts5DataRelease(pLeaf);
@@ -262347,23 +263026,27 @@
262347 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
262348 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
262349
262350 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
262351 Fts5Sorter *pSorter = pCsr->pSorter;
262352 int n;
262353 if( pSorter ){
262354 int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
262355 n = pSorter->aIdx[iPhrase] - i1;
262356 pIter->a = &pSorter->aPoslist[i1];
262357 }else{
262358 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
262359 }
262360 if( rc==SQLITE_OK ){
262361 assert( pIter->a || n==0 );
262362 pIter->b = (pIter->a ? &pIter->a[n] : 0);
262363 *piCol = 0;
262364 fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
 
 
 
 
 
 
 
262365 }
262366 }else{
262367 int n;
262368 rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
262369 if( rc==SQLITE_OK ){
@@ -263267,11 +263950,11 @@
263267 int nArg, /* Number of args */
263268 sqlite3_value **apUnused /* Function arguments */
263269 ){
263270 assert( nArg==0 );
263271 UNUSED_PARAM2(nArg, apUnused);
263272 sqlite3_result_text(pCtx, "fts5: 2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06", -1, SQLITE_TRANSIENT);
263273 }
263274
263275 /*
263276 ** Implementation of fts5_locale(LOCALE, TEXT) function.
263277 **
@@ -263909,38 +264592,35 @@
263909
263910 if( bCreate ){
263911 if( pConfig->eContent==FTS5_CONTENT_NORMAL
263912 || pConfig->eContent==FTS5_CONTENT_UNINDEXED
263913 ){
263914 int nDefn = 32 + pConfig->nCol*10;
263915 char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 20);
263916 if( zDefn==0 ){
263917 rc = SQLITE_NOMEM;
263918 }else{
263919 int i;
263920 int iOff;
263921 sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
263922 iOff = (int)strlen(zDefn);
263923 for(i=0; i<pConfig->nCol; i++){
263924 if( pConfig->eContent==FTS5_CONTENT_NORMAL
263925 || pConfig->abUnindexed[i]
263926 ){
263927 sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
263928 iOff += (int)strlen(&zDefn[iOff]);
263929 }
263930 }
263931 if( pConfig->bLocale ){
263932 for(i=0; i<pConfig->nCol; i++){
263933 if( pConfig->abUnindexed[i]==0 ){
263934 sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", l%d", i);
263935 iOff += (int)strlen(&zDefn[iOff]);
263936 }
263937 }
263938 }
263939 rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
263940 }
263941 sqlite3_free(zDefn);
263942 }
263943
263944 if( rc==SQLITE_OK && pConfig->bColumnsize ){
263945 const char *zCols = "id INTEGER PRIMARY KEY, sz BLOB";
263946 if( pConfig->bContentlessDelete ){
263947
--- 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 ** 2f1f4f73535386549c12694dc57cfe555eec 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.54.0"
471 #define SQLITE_VERSION_NUMBER 3054000
472 #define SQLITE_SOURCE_ID "2026-07-24 16:28:47 2f1f4f73535386549c12694dc57cfe555eec689ae6824c6241aaf8d5befcd74d"
473 #define SQLITE_SCM_BRANCH "trunk"
474 #define SQLITE_SCM_TAGS ""
475 #define SQLITE_SCM_DATETIME "2026-07-24T16:28:47.830Z"
476
477 /*
478 ** CAPI3REF: Run-Time Library Version Numbers
479 ** KEYWORDS: sqlite3_version sqlite3_sourceid
480 **
@@ -3732,11 +3732,11 @@
3732 ** authorizer will fail with an error message explaining that
3733 ** access is denied.
3734 **
3735 ** ^The first parameter to the authorizer callback is a copy of the third
3736 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3737 ** to the callback is an integer [SQLITE_READ | action code] that specifies
3738 ** the particular action to be authorized. ^The third through sixth parameters
3739 ** to the callback are either NULL pointers or zero-terminated strings
3740 ** that contain additional details about the action to be authorized.
3741 ** Applications must always be prepared to encounter a NULL pointer in any
3742 ** of the third through the sixth parameters of the authorization callback.
@@ -3775,25 +3775,37 @@
3775 ** ^(Only a single authorizer can be in place on a database connection
3776 ** at a time. Each call to sqlite3_set_authorizer overrides the
3777 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3778 ** The authorizer is disabled by default.
3779 **
3780 ** <h3>Limitations And Caveats</h3><ul>
3781 **
3782 ** <li>The authorizer callback must not do anything that will modify
3783 ** the database connection that invoked the authorizer callback.
3784 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3785 ** database connections for the meaning of "modify" in this paragraph.
3786 **
3787 ** <li>^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3788 ** statement might be re-prepared during [sqlite3_step()] due to a
3789 ** schema change. Hence, the application should ensure that the
3790 ** correct authorizer callback remains in place during the [sqlite3_step()].
3791 **
3792 ** <li>^The authorizer callback is invoked only during
3793 ** [sqlite3_prepare()] or its variants. Authorization is not
3794 ** performed during statement evaluation in [sqlite3_step()], unless
3795 ** as stated in the previous paragraph, sqlite3_step() invokes
3796 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3797 **
3798 ** <li>Authorizer callbacks for the expressions of a
3799 ** [generated column] are invoked when the schema is parsed (and specifically
3800 ** when the [CREATE TABLE] statement that contains the generated column is
3801 ** parsed) not when the generated column is used in a DML statement.
3802 ** This is deliberate, as one of the purposes of generated columns
3803 ** is to give schema designers the ability to provide gated access
3804 ** to privileged columns and/or functions.
3805 **
3806 ** </ul>
3807 */
3808 SQLITE_API int sqlite3_set_authorizer(
3809 sqlite3*,
3810 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3811 void *pUserData
@@ -3864,12 +3876,17 @@
3876 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3877 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3878 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3879 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3880 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
 
3881 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3882
3883 /*
3884 ** Note: The SQLITE_COPY macro (with value 0) used to be one of the
3885 ** action codes above. That macro has now been repurposed as a possible
3886 ** value to the 3rd argument to sqlite3_result_str().
3887 */
3888
3889 /*
3890 ** CAPI3REF: Deprecated Tracing And Profiling Functions
3891 ** DEPRECATED
3892 **
@@ -4734,10 +4751,14 @@
4751 ** nesting depth for separate triggers.</dd>)^
4752 **
4753 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4754 ** <dd>The maximum number of auxiliary worker threads that a single
4755 ** [prepared statement] may start.</dd>)^
4756 **
4757 ** [[SQLITE_LIMIT_SCHEMA]] ^(<dt>SQLITE_LIMIT_SCHEMA</dt>
4758 ** <dd>The maximum number of objects (tables, indexes, triggers, and views)
4759 ** defined by the database schema.</dd>)^
4760 ** </dl>
4761 */
4762 #define SQLITE_LIMIT_LENGTH 0
4763 #define SQLITE_LIMIT_SQL_LENGTH 1
4764 #define SQLITE_LIMIT_COLUMN 2
@@ -4749,10 +4770,11 @@
4770 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
4771 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
4772 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
4773 #define SQLITE_LIMIT_WORKER_THREADS 11
4774 #define SQLITE_LIMIT_PARSER_DEPTH 12
4775 #define SQLITE_LIMIT_SCHEMA 13
4776
4777 /*
4778 ** CAPI3REF: Prepare Flags
4779 **
4780 ** These constants define various flags that can be passed into the
@@ -4860,10 +4882,12 @@
4882 ** there is a small performance advantage to passing an nByte parameter that
4883 ** is the number of bytes in the input string <i>including</i>
4884 ** the nul-terminator.
4885 ** Note that nByte measures the length of the input in bytes, not
4886 ** characters, even for the UTF-16 interfaces.
4887 ** For the sqlite3_prepare16() and sqlite3_prepare16_v2() interfaces,
4888 ** the nByte value must be even or undefined behavior can result.
4889 **
4890 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4891 ** past the end of the first SQL statement in zSql. These routines only
4892 ** compile the first statement in zSql, so *pzTail is left pointing to
4893 ** what remains uncompiled.
@@ -5606,11 +5630,11 @@
5630 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5631 ** can be obtained by calling [sqlite3_reset()] on the
5632 ** [prepared statement]. ^In the "v2" interface,
5633 ** the more specific error code is returned directly by sqlite3_step().
5634 **
5635 ** [SQLITE_MISUSE] means that this routine was called inappropriately.
5636 ** Perhaps it was called on a [prepared statement] that has
5637 ** already been [sqlite3_finalize | finalized] or on one that had
5638 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5639 ** be the case that the same database connection is being used by two or
5640 ** more threads at the same moment in time.
@@ -6779,11 +6803,15 @@
6803 ** to by the second parameter and which is N bytes long where N is the
6804 ** third parameter.
6805 **
6806 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6807 ** interfaces set the result of the application-defined function to be
6808 ** a BLOB containing all zero bytes and N bytes in size. The
6809 ** zeroblob64(C,N) interface returns a [result code], which is normally
6810 ** [SQLITE_OK] but might be some other value if the requested operation
6811 ** could not be complete, for example if insufficient memory is available
6812 ** or if the value of N is out of range.
6813 **
6814 ** ^The sqlite3_result_double() interface sets the result from
6815 ** an application-defined function to be a floating point value specified
6816 ** by its 2nd argument.
6817 **
@@ -9117,12 +9145,12 @@
9145 ** The lifecycle of an sqlite3_str object is as follows:
9146 ** <ol>
9147 ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
9148 ** <li> ^Text is appended to the sqlite3_str object using various
9149 ** methods, such as [sqlite3_str_appendf()].
9150 ** <li> The sqlite3_str object is destroyed and the string it created
9151 ** is returned using [sqlite3_str_finish()] or [sqlite3_result_str()].
9152 ** </ol>
9153 */
9154 typedef struct sqlite3_str sqlite3_str;
9155
9156 /*
@@ -9170,10 +9198,44 @@
9198 ** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)).
9199 */
9200 SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
9201 SQLITE_API void sqlite3_str_free(sqlite3_str*);
9202
9203 /*
9204 ** CAPI3REF: Return A Dynamic String From an SQL Function
9205 **
9206 ** The [sqlite3_result_str(C,S,F)] interface causes the
9207 ** [sqlite3_str|dynamic string] S to become the return value for the
9208 ** application-defined function or virtual table that uses
9209 ** [sqlite3_context] C. The F flag can be one of [SQLITE_COPY]
9210 ** or [SQLITE_XFER] or [SQLITE_FINISH].
9211 **
9212 ** If the dynamic string is invalid or incomplete due to an out-of-memory
9213 ** or string-too-large error, then this routine transfers that error
9214 ** over to the SQL function.
9215 **
9216 ** If the F argument is SQLITE_COPY, then a copy of the dynamic string
9217 ** content is made and the dynamic string object is unchanged.
9218 ** If the F argument is SQLITE_XFER, then ownership of the content
9219 ** in the dynamic is transferred to the SQL function (via a pointer copy
9220 ** rather than a string copy) and the dynamic string is reset to an
9221 ** empty string. The SQLITE_FINISH value for F works like SQLITE_RESET
9222 ** except that it also invokes the [sqlite3_str_free(S)] destructor
9223 ** on the dynamic string object.
9224 */
9225 SQLITE_API void sqlite3_result_str(sqlite3_context*, sqlite3_str*, int);
9226
9227 /*
9228 ** CAPI3REF: Control Flags For sqlite3_result_str()
9229 **
9230 ** The following integers can be used as the third "F" argument
9231 ** to [sqlite3_result_str(C,S,F)].
9232 */
9233 #define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */
9234 #define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */
9235 #define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */
9236
9237 /*
9238 ** CAPI3REF: Add Content To A Dynamic String
9239 ** METHOD: sqlite3_str
9240 **
9241 ** These interfaces add or remove content to an sqlite3_str object
@@ -14978,10 +15040,37 @@
15040 */
15041 #ifndef SQLITE_MAX_TRIGGER_DEPTH
15042 # define SQLITE_MAX_TRIGGER_DEPTH 1000
15043 #endif
15044
15045 /*
15046 ** Maximum number of objects defined by a single database schema.
15047 ** Objects include:
15048 **
15049 ** * tables (including the sqlite_schema table)
15050 ** * virtual tables
15051 ** * named indexes
15052 ** * indexes created automatically by UNIQUE and PRIMARY KEY constraints
15053 ** * triggers
15054 ** * views
15055 **
15056 ** The total of all of the above is the number of objects in the schema,
15057 ** and that number may not exceed this value.
15058 **
15059 ** The maximum number of objects is restricted to forestall theoretical
15060 ** signed integer overflow attacks using databases with billions of
15061 ** schema objects. Such attacks are "theoretical" because memory and
15062 ** disk space constraints would be reached long before billions of schema
15063 ** objects could be created. Even so, it seems good to have a well defined
15064 ** upper limit on the complexity of the schema, for defense in depth.
15065 ** No real-world application should ever get anywhere close to hitting
15066 ** this limit.
15067 */
15068 #ifndef SQLITE_MAX_SCHEMA
15069 # define SQLITE_MAX_SCHEMA 10000000
15070 #endif
15071
15072 /************** End of sqliteLimit.h *****************************************/
15073 /************** Continuing where we left off in sqliteInt.h ******************/
15074
15075 /* Disable nuisance warnings on Borland compilers */
15076 #if defined(__BORLANDC__)
@@ -15236,11 +15325,13 @@
15325 ** bitmask tests, testcase() can be used to make sure each bit
15326 ** is significant and used at least once. On switch statements
15327 ** where multiple cases go to the same block of code, testcase()
15328 ** can insure that all cases are evaluated.
15329 */
15330 #if defined(SQLITE_MUTATION_TEST)
15331 # define testcase(X)
15332 #elif defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
15333 # ifndef SQLITE_AMALGAMATION
15334 extern unsigned int sqlite3CoverageCounter;
15335 # endif
15336 # define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__; }
15337 #else
@@ -17190,11 +17281,11 @@
17281 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
17282 #endif
17283
17284 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
17285 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
17286 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree*, Btree*);
17287
17288 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
17289
17290 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
17291 ** of the flags shown below.
@@ -17267,16 +17358,23 @@
17358 ** The design of the _RANGE hint is aid b-tree implementations that try
17359 ** to prefetch content from remote machines - to provide those
17360 ** implementations with limits on what needs to be prefetched and thereby
17361 ** reduce network bandwidth.
17362 **
17363 ** BTREE_HINT_TABLECURSOR (arguments: BtCursor*)
17364 **
17365 ** This hint is invoked on a non-covering index cursor soon after it
17366 ** is opened. The only argument is a pointer to the table cursor used to
17367 ** obtain non-covered fields from the database.
17368 **
17369 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
17370 ** standard SQLite. The other hints are provided for extensions that use
17371 ** the SQLite parser and code generator but substitute their own storage
17372 ** engine.
17373 */
17374 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
17375 #define BTREE_HINT_TABLECURSOR 1 /* Table csr associated with this index csr */
17376
17377 /*
17378 ** Values that may be OR'd together to form the argument to the
17379 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
17380 **
@@ -17332,10 +17430,13 @@
17430 #endif
17431 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
17432 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
17433 #ifdef SQLITE_ENABLE_CURSOR_HINTS
17434 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
17435 #ifdef SQLITE_DEBUG
17436 SQLITE_PRIVATE BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor*);
17437 #endif
17438 #endif
17439
17440 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
17441 SQLITE_PRIVATE int sqlite3BtreeTableMoveto(
17442 BtCursor*,
@@ -18573,11 +18674,11 @@
18674
18675 /*
18676 ** The number of different kinds of things that can be limited
18677 ** using the sqlite3_limit() interface.
18678 */
18679 #define SQLITE_N_LIMIT (SQLITE_LIMIT_SCHEMA+1)
18680
18681 /*
18682 ** Lookaside malloc is a set of fixed-size buffers that can be used
18683 ** to satisfy small transient memory allocation requests for objects
18684 ** associated with a particular database connection. The use of
@@ -20940,16 +21041,16 @@
21041 bft bHasExists :1; /* Has a correlated "EXISTS (SELECT ....)" expression */
21042 bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */
21043 bft bHasWith :1; /* True if statement contains WITH */
21044 bft okConstFactor:1; /* OK to factor out constants */
21045 bft checkSchema :1; /* Causes schema cookie check after an error */
21046 bft usesAinc :1; /* True if pAinc is valid */
21047 int nRangeReg; /* Size of the temporary register block */
21048 int iRangeReg; /* First register in temporary register block */
21049 int nErr; /* Number of errors seen */
21050 int nTab; /* Number of previously allocated VDBE cursors */
21051 int nMem; /* Number of memory cells used so far */
 
21052 int iSelfTab; /* Table associated with an index on expr, or negative
21053 ** of the base register during check-constraint eval */
21054 int nNestSel; /* Number of nested SELECT statements and/or VIEWs */
21055 int nLabel; /* The *negative* of the number of labels used */
21056 int nLabelAlloc; /* Number of slots in aLabel */
@@ -20964,13 +21065,11 @@
21065 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
21066 u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */
21067 #endif
21068 #ifndef SQLITE_OMIT_SHARED_CACHE
21069 int nTableLock; /* Number of locks in aTableLock */
 
21070 #endif
 
21071 Parse *pToplevel; /* Parse structure for main program (or NULL) */
21072 Table *pTriggerTab; /* Table triggers are being coded for */
21073 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
21074 ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */
21075
@@ -20995,10 +21094,17 @@
21094 } cr;
21095 struct { /* These fields available to all other statements */
21096 Returning *pReturning; /* The RETURNING clause */
21097 } d;
21098 } u1;
21099 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters. Only
21100 ** valid if Parse.usesAinc is true */
21101 #ifndef SQLITE_OMIT_SHARED_CACHE
21102 TableLock *aTableLock; /* Required table locks for shared-cache mode. Only
21103 ** valid if Parse.nTableLock>0 */
21104 #endif
21105
21106
21107 /************************************************************************
21108 ** Above is constant between recursions. Below is reset before and after
21109 ** each recursion. The boundary between these two regions is determined
21110 ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
@@ -21942,10 +22048,11 @@
22048 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
22049 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
22050 #endif
22051 #if defined(SQLITE_TEST)
22052 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
22053 SQLITE_PRIVATE const char *sqlite3TestPtrToText(void*);
22054 #endif
22055
22056 #if defined(SQLITE_DEBUG)
22057 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...);
22058 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
@@ -22166,10 +22273,11 @@
22273 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
22274 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
22275 SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);
22276 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
22277 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**);
22278 SQLITE_PRIVATE int sqlite3IndexBloomable(const Index*,int);
22279 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
22280 Expr*, int, int, u8);
22281 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
22282 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
22283 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
@@ -22528,10 +22636,11 @@
22636 SQLITE_PRIVATE const unsigned char *sqlite3aEQb;
22637 SQLITE_PRIVATE const unsigned char *sqlite3aGTb;
22638 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
22639 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
22640 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
22641 SQLITE_PRIVATE const sqlite3_str sqlite3OomStr;
22642 #ifndef SQLITE_OMIT_WSD
22643 SQLITE_PRIVATE int sqlite3PendingByte;
22644 #endif
22645 #endif /* SQLITE_AMALGAMATION */
22646 #ifdef VDBE_PROFILE
@@ -22630,11 +22739,10 @@
22739 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
22740 SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, i64);
22741 SQLITE_PRIVATE int sqlite3StrAccumEnlargeIfNeeded(StrAccum*, i64);
22742 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
22743 SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8);
 
22744 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
22745 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
22746 SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*);
22747 SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*);
22748
@@ -23578,10 +23686,13 @@
23686 "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
23687 #endif
23688 #ifdef SQLITE_MAX_PAGE_SIZE
23689 "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
23690 #endif
23691 #ifdef SQLITE_MAX_SCHEMA
23692 "MAX_SCHEMA=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA),
23693 #endif
23694 #ifdef SQLITE_MAX_SCHEMA_RETRY
23695 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
23696 #endif
23697 #ifdef SQLITE_MAX_SQL_LENGTH
23698 "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
@@ -24228,10 +24339,20 @@
24339 ** Hash table for global functions - functions common to all
24340 ** database connections. After initialization, this table is
24341 ** read-only.
24342 */
24343 SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
24344
24345 /*
24346 ** This singleton is an sqlite3_str object that is returned if
24347 ** sqlite3_malloc() fails to provide space for a real one. This
24348 ** sqlite3_str object accepts no new text and always returns
24349 ** an SQLITE_NOMEM error.
24350 */
24351 SQLITE_PRIVATE const sqlite3_str sqlite3OomStr = {
24352 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
24353 };
24354
24355 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
24356 /*
24357 ** Counter used for coverage testing. Does not come into play for
24358 ** release builds.
@@ -26297,10 +26418,53 @@
26418 clearYMD_HMS_TZ(p);
26419 rc = 0;
26420 p->nFloor = 0;
26421 }
26422 break;
26423 }
26424 case 'e': {
26425 /*
26426 ** end of day
26427 ** end of month
26428 ** end of year
26429 **
26430 ** Move the date forwards to the last millisecond of the current
26431 ** day, month or year.
26432 */
26433 if( sqlite3_strnicmp(z, "end of ", 7)!=0 ){
26434 break;
26435 }
26436 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
26437 z += 7;
26438 computeYMD(p);
26439 p->validHMS = 1;
26440 p->h = 23;
26441 p->m = 59;
26442 p->s = 59.999;
26443 p->rawS = 0;
26444 p->tz = 0;
26445 p->validJD = 0;
26446 if( sqlite3_stricmp(z,"month")==0 ){
26447 p->D = 1;
26448 p->M++;
26449 if( p->M>12 ){
26450 p->Y++;
26451 p->M = 1;
26452 }
26453 computeFloor(p);
26454 computeJD(p);
26455 p->iJD -= (p->nFloor+1)*86400000;
26456 clearYMD_HMS_TZ(p);
26457 rc = 0;
26458 }else if( sqlite3_stricmp(z,"year")==0 ){
26459 p->M = 12;
26460 p->D = 31;
26461 rc = 0;
26462 }else if( sqlite3_stricmp(z,"day")==0 ){
26463 rc = 0;
26464 }
26465 break;
26466 }
26467 case 'f': {
26468 /*
26469 ** floor
26470 **
@@ -26400,34 +26564,44 @@
26564 break;
26565 }
26566 case 'w': {
26567 /*
26568 ** weekday N
26569 ** weekday -N
26570 **
26571 ** Move the date forward (for N>=0) or backward (for N<=-0) to the
26572 ** same time on the next/previous occurrence of weekday abs(N)
26573 ** where 0==Sunday, 1==Monday, and so forth. If the date is already
26574 ** on the appropriate weekday, this is a no-op.
26575 */
26576 if( sqlite3_strnicmp(z, "weekday ", 8)==0
26577 && sqlite3AtoF(&z[8], &r)>0
26578 && r>=-6.0 && r<=6.0
26579 && sqlite3RealSameAsInt(r,(i64)(n=(int)r))
26580 ){
26581 sqlite3_int64 Z;
26582 computeYMD_HMS(p);
26583 p->tz = 0;
26584 p->validJD = 0;
26585 computeJD(p);
26586 Z = ((p->iJD + 129600000)/86400000) % 7;
26587 if( n<0 ) n = -n;
26588 if( Z!=n ){
26589 if( Z>n ) Z -= 7;
26590 p->iJD += (n - Z)*86400000;
26591 if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000;
26592 }
26593 clearYMD_HMS_TZ(p);
26594 rc = 0;
26595 }
26596 break;
26597 }
26598 case 's': {
26599 /*
26600 ** start of day
26601 ** start of month
26602 ** start of year
26603 **
26604 ** Move the date backwards to the beginning of the current day,
26605 ** or month or year.
26606 **
26607 ** subsecond
@@ -26947,42 +27121,42 @@
27121 ){
27122 DateTime x;
27123 size_t i,j;
27124 sqlite3 *db;
27125 const char *zFmt;
27126 sqlite3_str *pRes;
27127
27128
27129 if( argc==0 ) return;
27130 zFmt = (const char*)sqlite3_value_text(argv[0]);
27131 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
27132 db = sqlite3_context_db_handle(context);
27133 pRes = sqlite3_str_new(db);
27134
27135 computeJD(&x);
27136 computeYMD_HMS(&x);
27137 for(i=j=0; zFmt[i]; i++){
27138 char cf;
27139 if( zFmt[i]!='%' ) continue;
27140 if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j));
27141 i++;
27142 j = i + 1;
27143 cf = zFmt[i];
27144 switch( cf ){
27145 case 'd': /* Fall thru */
27146 case 'e': {
27147 sqlite3_str_appendf(pRes, cf=='d' ? "%02d" : "%2d", x.D);
27148 break;
27149 }
27150 case 'f': { /* Fractional seconds. (Non-standard) */
27151 double s = x.s;
27152 if( NEVER(s>59.999) ) s = 59.999;
27153 sqlite3_str_appendf(pRes, "%06.3f", s);
27154 break;
27155 }
27156 case 'F': {
27157 sqlite3_str_appendf(pRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
27158 break;
27159 }
27160 case 'G': /* Fall thru */
27161 case 'g': {
27162 DateTime y = x;
@@ -26990,85 +27164,85 @@
27164 /* Move y so that it is the Thursday in the same week as x */
27165 y.iJD += (3 - daysAfterMonday(&x))*86400000;
27166 y.validYMD = 0;
27167 computeYMD(&y);
27168 if( cf=='g' ){
27169 sqlite3_str_appendf(pRes, "%02d", y.Y%100);
27170 }else{
27171 sqlite3_str_appendf(pRes, "%04d", y.Y);
27172 }
27173 break;
27174 }
27175 case 'H':
27176 case 'k': {
27177 sqlite3_str_appendf(pRes, cf=='H' ? "%02d" : "%2d", x.h);
27178 break;
27179 }
27180 case 'I': /* Fall thru */
27181 case 'l': {
27182 int h = x.h;
27183 if( h>12 ) h -= 12;
27184 if( h==0 ) h = 12;
27185 sqlite3_str_appendf(pRes, cf=='I' ? "%02d" : "%2d", h);
27186 break;
27187 }
27188 case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */
27189 sqlite3_str_appendf(pRes,"%03d",daysAfterJan01(&x)+1);
27190 break;
27191 }
27192 case 'J': { /* Julian day number. (Non-standard) */
27193 sqlite3_str_appendf(pRes,"%.16g",x.iJD/86400000.0);
27194 break;
27195 }
27196 case 'm': {
27197 sqlite3_str_appendf(pRes,"%02d",x.M);
27198 break;
27199 }
27200 case 'M': {
27201 sqlite3_str_appendf(pRes,"%02d",x.m);
27202 break;
27203 }
27204 case 'p': /* Fall thru */
27205 case 'P': {
27206 if( x.h>=12 ){
27207 sqlite3_str_append(pRes, cf=='p' ? "PM" : "pm", 2);
27208 }else{
27209 sqlite3_str_append(pRes, cf=='p' ? "AM" : "am", 2);
27210 }
27211 break;
27212 }
27213 case 'R': {
27214 sqlite3_str_appendf(pRes, "%02d:%02d", x.h, x.m);
27215 break;
27216 }
27217 case 's': {
27218 if( x.useSubsec ){
27219 sqlite3_str_appendf(pRes,"%.3f",
27220 (x.iJD - 21086676*(i64)10000000)/1000.0);
27221 }else{
27222 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
27223 sqlite3_str_appendf(pRes,"%lld",iS);
27224 }
27225 break;
27226 }
27227 case 'S': {
27228 sqlite3_str_appendf(pRes,"%02d",(int)x.s);
27229 break;
27230 }
27231 case 'T': {
27232 sqlite3_str_appendf(pRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
27233 break;
27234 }
27235 case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */
27236 case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */
27237 char c = (char)daysAfterSunday(&x) + '0';
27238 if( c=='0' && cf=='u' ) c = '7';
27239 sqlite3_str_appendchar(pRes, 1, c);
27240 break;
27241 }
27242 case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */
27243 sqlite3_str_appendf(pRes,"%02d",
27244 (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7);
27245 break;
27246 }
27247 case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */
27248 DateTime y = x;
@@ -27075,34 +27249,34 @@
27249 /* Adjust y so that is the Thursday in the same week as x */
27250 assert( y.validJD );
27251 y.iJD += (3 - daysAfterMonday(&x))*86400000;
27252 y.validYMD = 0;
27253 computeYMD(&y);
27254 sqlite3_str_appendf(pRes,"%02d", daysAfterJan01(&y)/7+1);
27255 break;
27256 }
27257 case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */
27258 sqlite3_str_appendf(pRes,"%02d",
27259 (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7);
27260 break;
27261 }
27262 case 'Y': {
27263 sqlite3_str_appendf(pRes,"%04d",x.Y);
27264 break;
27265 }
27266 case '%': {
27267 sqlite3_str_appendchar(pRes, 1, '%');
27268 break;
27269 }
27270 default: {
27271 sqlite3_str_free(pRes);
27272 return;
27273 }
27274 }
27275 }
27276 if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j));
27277 sqlite3_result_str(context, pRes, SQLITE_FINISH);
27278 }
27279
27280 /*
27281 ** current_time()
27282 **
@@ -27234,11 +27408,11 @@
27408 clearYMD_HMS_TZ(&d1);
27409 computeYMD_HMS(&d1);
27410 sqlite3StrAccumInit(&sRes, 0, 0, 0, 100);
27411 sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f",
27412 sign, Y, M, d1.D-1, d1.h, d1.m, d1.s);
27413 sqlite3_result_str(context, &sRes, SQLITE_XFER);
27414 }
27415
27416
27417 /*
27418 ** current_timestamp()
@@ -27662,11 +27836,11 @@
27836 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
27837 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
27838 }else{
27839 double r;
27840 rc = pVfs->xCurrentTime(pVfs, &r);
27841 *pTimeOut = sqlite3RealToI64(r*86400000.0);
27842 }
27843 return rc;
27844 }
27845
27846 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
@@ -32612,10 +32786,14 @@
32786 */
32787 #ifndef SQLITE_PRINTF_PRECISION_LIMIT
32788 # define SQLITE_FP_PRECISION_LIMIT 100000000
32789 #endif
32790
32791 /* Forward reference */
32792 static void sqlite3StrAppend64(sqlite3_str *p, const char *z, i64 N);
32793 static void sqlite3StrAppendchar64(sqlite3_str *p, i64 N, char c);
32794
32795 /*
32796 ** Render a string given by "fmt" into the StrAccum object.
32797 */
32798 SQLITE_API void sqlite3_str_vappendf(
32799 sqlite3_str *pAccum, /* Accumulate results here */
@@ -32622,14 +32800,14 @@
32800 const char *fmt, /* Format string */
32801 va_list ap /* arguments */
32802 ){
32803 int c; /* Next character in the format string */
32804 char *bufpt; /* Pointer to the conversion buffer */
32805 i64 precision; /* Precision of the current field */
32806 i64 length; /* Length of the field */
32807 int idx; /* A general purpose loop counter */
32808 i64 width; /* Width of the current field */
32809 etByte flag_leftjustify; /* True if "-" flag is present */
32810 etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
32811 etByte flag_alternateform; /* True if "#" flag is present */
32812 etByte flag_altform2; /* True if "!" flag is present */
32813 etByte flag_zeropad; /* True if field width constant starts with zero */
@@ -32673,11 +32851,11 @@
32851 fmt = strchr(fmt, '%');
32852 if( fmt==0 ){
32853 fmt = bufpt + strlen(bufpt);
32854 }
32855 #endif
32856 sqlite3StrAppend64(pAccum, bufpt, fmt - bufpt);
32857 if( *fmt==0 ) break;
32858 }
32859 if( (c=(*++fmt))==0 ){
32860 sqlite3_str_append(pAccum, "%", 1);
32861 break;
@@ -32919,26 +33097,27 @@
33097 do{ /* Convert to ascii */
33098 *(--bufpt) = cset[longvalue%base];
33099 longvalue = longvalue/base;
33100 }while( longvalue>0 );
33101 }
33102 length = &zOut[nOut-1] - bufpt;
33103 if( precision>length ){ /* zero pad */
33104 i64 nn = precision-length;
33105 bufpt -= nn;
33106 memset(bufpt,'0',nn);
33107 length = precision;
33108 }
33109 if( cThousand ){
33110 i64 nn = (length - 1)/3; /* Number of "," to insert */
33111 i64 ix = (length - 1)%3 + 1;
33112 int ii;
33113 bufpt -= nn;
33114 for(ii=0; nn>0; ii++){
33115 bufpt[ii] = bufpt[ii+nn];
33116 ix--;
33117 if( ix==0 ){
33118 bufpt[++ii] = cThousand;
33119 nn--;
33120 ix = 3;
33121 }
33122 }
33123 }
@@ -32947,11 +33126,11 @@
33126 const char *pre;
33127 char x;
33128 pre = &aPrefix[infop->prefix];
33129 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
33130 }
33131 length = &zOut[nOut-1] - bufpt;
33132 break;
33133 case etFLOAT:
33134 case etEXP:
33135 case etGENERIC: {
33136 FpDecode s;
@@ -32979,12 +33158,17 @@
33158 iRound = precision+1;
33159 }
33160 sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 20 : 16);
33161 if( s.isSpecial ){
33162 if( s.isSpecial==2 ){
33163 if( flag_zeropad ){
33164 bufpt = "null";
33165 length = 4;
33166 }else{
33167 bufpt = "NaN";
33168 length = 3;
33169 }
33170 break;
33171 }else if( flag_zeropad ){
33172 s.z[0] = '9';
33173 s.iDP = 1000;
33174 s.n = 1;
@@ -32996,11 +33180,11 @@
33180 }else if( flag_prefix ){
33181 buf[0] = flag_prefix;
33182 }else{
33183 bufpt++;
33184 }
33185 length = strlen(bufpt);
33186 break;
33187 }
33188 }
33189 if( s.sign=='-' ){
33190 if( flag_alternateform
@@ -33152,11 +33336,11 @@
33336 }
33337 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
33338 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
33339 }
33340
33341 length = bufpt - zOut;
33342 assert( length <= szBufNeeded );
33343 if( length<width ){
33344 i64 nPad = width - length;
33345 if( flag_leftjustify ){
33346 memset(bufpt, ' ', nPad);
@@ -33172,10 +33356,11 @@
33356 }
33357
33358 if( zExtra==0 ){
33359 /* The result is being rendered directory into pAccum. This
33360 ** is the common and fast case */
33361 assert( pAccum->nChar + length < SMXV(pAccum->nChar) );
33362 pAccum->nChar += length;
33363 zOut[length] = 0;
33364 continue;
33365 }else{
33366 /* We were unable to render directly into pAccum because we
@@ -33218,14 +33403,14 @@
33403 }
33404 if( precision>1 ){
33405 i64 nPrior = 1;
33406 width -= precision-1;
33407 if( width>1 && !flag_leftjustify ){
33408 sqlite3StrAppendchar64(pAccum, width-1, ' ');
33409 width = 0;
33410 }
33411 sqlite3StrAppend64(pAccum, buf, length);
33412 precision--;
33413 while( precision > 1 ){
33414 i64 nCopyBytes;
33415 if( nPrior > precision-1 ) nPrior = precision - 1;
33416 nCopyBytes = length*nPrior;
@@ -33277,21 +33462,21 @@
33462 ** precision characters */
33463 unsigned char *z = (unsigned char*)bufpt;
33464 while( precision-- > 0 && z[0] ){
33465 SQLITE_SKIP_UTF8(z);
33466 }
33467 length = z - (unsigned char*)bufpt;
33468 }else{
33469 for(length=0; length<precision && bufpt[length]; length++){}
33470 }
33471 }else{
33472 length = strlen(bufpt);
33473 }
33474 adjust_width_for_utf8:
33475 if( flag_altform2 && width>0 ){
33476 /* Adjust width to account for extra bytes in UTF-8 characters */
33477 i64 ii = length - 1;
33478 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
33479 }
33480 break;
33481 case etESCAPE_j: /* %j: JSON string literal w/o "..." */
33482 case etESCAPE_J: { /* %J: Generate a JSON string literal */
@@ -33322,11 +33507,11 @@
33507 while( (escarg[px]&0xc0)==0x80 ) px++;
33508 }
33509 }
33510 for(i=j=0; i<px; i++){
33511 if( (ch = ((u8*)escarg)[i])<=0x1f || ch=='"' || ch=='\\' ){
33512 if( j<i ) sqlite3StrAppend64(pAccum, &escarg[j], i-j);
33513 j = i+1;
33514 if( ch==0 ) break;
33515 sqlite3_str_appendchar(pAccum, 1, '\\');
33516 if( ch>0x1f ){
33517 sqlite3_str_appendchar(pAccum, 1, ch);
@@ -33338,11 +33523,11 @@
33523 sqlite3_str_appendchar(pAccum, 1, aHex[ch>>4]);
33524 sqlite3_str_appendchar(pAccum, 1, aHex[ch&0xf]);
33525 }
33526 }
33527 }
33528 if( j<i ) sqlite3StrAppend64(pAccum, &escarg[j], i-j);
33529 if( xtype==etESCAPE_J ) sqlite3_str_append(pAccum, "\"", 1);
33530 }
33531 if( width>0 && sqlite3_str_errcode(pAccum)==SQLITE_OK ){
33532 sqlite3_int64 n = sqlite3_str_length(pAccum) - iStart;
33533 sqlite3_int64 len = n;
@@ -33354,11 +33539,11 @@
33539 }
33540 }
33541 if( width>len ){
33542 sqlite3_int64 sp = width-len;
33543 assert( sp>0 && sp<0x7fffffff );
33544 sqlite3StrAppendchar64(pAccum, (int)sp, ' ');
33545 if( !flag_leftjustify
33546 && n>0
33547 && sqlite3_str_errcode(pAccum)==0
33548 ){
33549 zz = sqlite3_str_value(pAccum);
@@ -33546,15 +33731,15 @@
33731 ** indicating that width and precision should be expressed in characters,
33732 ** then the values have been translated prior to reaching this point.
33733 */
33734 width -= length;
33735 if( width>0 ){
33736 if( !flag_leftjustify ) sqlite3StrAppendchar64(pAccum, width, ' ');
33737 sqlite3StrAppend64(pAccum, bufpt, length);
33738 if( flag_leftjustify ) sqlite3StrAppendchar64(pAccum, width, ' ');
33739 }else{
33740 sqlite3StrAppend64(pAccum, bufpt, length);
33741 }
33742
33743 if( zExtra ){
33744 sqlite3DbFree(pAccum->db, zExtra);
33745 zExtra = 0;
@@ -33670,10 +33855,17 @@
33855 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
33856 return;
33857 }
33858 while( (N--)>0 ) p->zText[p->nChar++] = c;
33859 }
33860 static void sqlite3StrAppendchar64(sqlite3_str *p, i64 N, char c){
33861 testcase( p->nChar + N > 0x7fffffff );
33862 if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
33863 return;
33864 }
33865 while( (N--)>0 ) p->zText[p->nChar++] = c;
33866 }
33867
33868 /*
33869 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
33870 ** So enlarge if first, then do the append.
33871 **
@@ -33681,10 +33873,11 @@
33873 ** work (enlarging the buffer) using tail recursion, so that the
33874 ** sqlite3_str_append() routine can use fast calling semantics.
33875 */
33876 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
33877 N = sqlite3StrAccumEnlarge(p, N);
33878 assert( z!=0 || N==0 );
33879 if( N>0 ){
33880 memcpy(&p->zText[p->nChar], z, N);
33881 p->nChar += N;
33882 }
33883 }
@@ -33704,10 +33897,24 @@
33897 assert( p->zText );
33898 p->nChar += N;
33899 memcpy(&p->zText[p->nChar-N], z, N);
33900 }
33901 }
33902 static void sqlite3StrAppend64(sqlite3_str *p, const char *z, i64 N){
33903 assert( z!=0 || N==0 );
33904 assert( p->zText!=0 || p->nChar==0 || p->accError );
33905 assert( N>=0 );
33906 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
33907 if( p->nChar+N >= (i64)p->nAlloc ){
33908 enlargeAndAppend(p,z,N);
33909 }else if( N ){
33910 assert( p->zText );
33911 p->nChar += N;
33912 memcpy(&p->zText[p->nChar-N], z, N);
33913 }
33914 }
33915
33916
33917 /*
33918 ** Append the complete text of zero-terminated string z[] to the p string.
33919 */
33920 SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
@@ -33741,41 +33948,15 @@
33948 }
33949 }
33950 return p->zText;
33951 }
33952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33953 /* Finalize a string created using sqlite3_str_new().
33954 */
33955 SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
33956 char *z;
33957 if( p!=0 && p!=(sqlite3_str*)&sqlite3OomStr ){
33958 z = sqlite3StrAccumFinish(p);
33959 sqlite3_free(p);
33960 }else{
33961 z = 0;
33962 }
@@ -33812,10 +33993,12 @@
33993 */
33994 SQLITE_API void sqlite3_str_reset(StrAccum *p){
33995 if( isMalloced(p) ){
33996 sqlite3DbFree(p->db, p->zText);
33997 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
33998 }else if( p==(sqlite3_str*)&sqlite3OomStr ){
33999 return;
34000 }
34001 p->nAlloc = 0;
34002 p->nChar = 0;
34003 p->zText = 0;
34004 }
@@ -33823,11 +34006,11 @@
34006 /*
34007 ** Destroy a dynamically allocate sqlite3_str object and all
34008 ** of its content, all in one call.
34009 */
34010 SQLITE_API void sqlite3_str_free(sqlite3_str *p){
34011 if( p!=0 && p!=(sqlite3_str*)&sqlite3OomStr ){
34012 sqlite3_str_reset(p);
34013 sqlite3_free(p);
34014 }
34015 }
34016
@@ -33860,11 +34043,11 @@
34043 sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
34044 if( p ){
34045 sqlite3StrAccumInit(p, 0, 0, 0,
34046 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
34047 }else{
34048 p = (sqlite3_str*)&sqlite3OomStr;
34049 }
34050 return p;
34051 }
34052
34053 /*
@@ -37500,11 +37683,11 @@
37683 return mState;
37684 }
37685 }
37686 return 0xfffffff0 | mState;
37687 #else
37688 return sqlite3Atoi64(zIn, pResult, strlen(zIn), SQLITE_UTF8)==0;
37689 #endif /* SQLITE_OMIT_FLOATING_POINT */
37690 }
37691
37692 /*
37693 ** Digit pairs used to convert a U64 or I64 into text, two digits
@@ -39731,20 +39914,21 @@
39914 i = 0;
39915 j = 0;
39916 while( 1 ){
39917 c = kvvfsHexValue[aIn[i]];
39918 if( c<0 ){
39919 sqlite3_int64 n = 0;
39920 sqlite3_int64 mult = 1;
39921 c = aIn[i];
39922 if( c==0 ) break;
39923 while( c>='a' && c<='z' ){
39924 n += (c - 'a')*mult;
39925 if( n>nOut ) return -1 /* oversized/malformed input */;
39926 mult *= 26;
39927 c = aIn[++i];
39928 }
39929 if( j+n>nOut ) return -1 /* oversized/malformed input */;
39930 memset(&aOut[j], 0, n);
39931 j += n;
39932 if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */
39933 }else if( j<nOut ){
39934 aOut[j] = c<<4;
@@ -39773,22 +39957,28 @@
39957 static void kvvfsDecodeJournal(
39958 KVVfsFile *pFile, /* Store decoding in pFile->aJrnl */
39959 const char *zTxt, /* Text encoding. Zero-terminated */
39960 int nTxt /* Bytes in zTxt, excluding zero terminator */
39961 ){
39962 unsigned int n = 0, mult;
39963 int c, i;
39964 i = 0;
39965 mult = 1;
39966 sqlite3_free(pFile->aJrnl);
39967 pFile->aJrnl = 0;
39968 pFile->nJrnl = 0;
39969 while( (c = zTxt[i])>='a' && c<='z' ){
39970 n += (c - 'a')*mult;
39971 mult *= 26;
39972 ++i;
39973 }
39974 if( ' '!=zTxt[i++] ){
39975 /* Malformed input */
39976 return;
39977 }
39978 pFile->aJrnl = sqlite3_malloc64( n );
39979 if( pFile->aJrnl==0 ){
 
39980 return;
39981 }
39982 pFile->nJrnl = n;
39983 n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl);
39984 if( n<pFile->nJrnl ){
@@ -39824,13 +40014,11 @@
40014
40015 SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass,
40016 pFile->isJournal ? "journal" : "db"));
40017 sqlite3_free(pFile->aJrnl);
40018 sqlite3_free(pFile->aData);
 
40019 memset(pFile, 0, sizeof(*pFile));
 
40020 return SQLITE_OK;
40021 }
40022
40023 /*
40024 ** Read from the -journal file.
@@ -39856,10 +40044,11 @@
40044 if( aTxt==0 ) return SQLITE_NOMEM;
40045 rc = sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, "jrnl",
40046 aTxt, szTxt+1);
40047 if( rc>=0 ){
40048 kvvfsDecodeJournal(pFile, aTxt, szTxt);
40049 rc = 0;
40050 }
40051 sqlite3_free(aTxt);
40052 if( rc ) return rc;
40053 if( pFile->aJrnl==0 ) return SQLITE_IOERR;
40054 }
@@ -40180,11 +40369,11 @@
40369 }
40370 if( !pFile->zClass ){
40371 #ifdef SQLITE_WASM
40372 if( strlen(zName) >= (KVRECORD_KEY_SZ
40373 - 6 /* "kvvfs-" */
40374 - 11 /* "-NNNNNNNNNNN" */) ){
40375 return SQLITE_CANTOPEN;
40376 }
40377 #else
40378 if( 0!=strcmp(zName, "local") && 0!=strcmp(zName, "session") ){
40379 /* Historical naming restriction which journaling depends on. */
@@ -45946,11 +46135,10 @@
46135 i64 nNew /* Required mapping size */
46136 ){
46137 const char *zErr = "mmap";
46138 int h = pFd->h; /* File descriptor open on db file */
46139 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
 
46140 u8 *pNew = 0; /* Location of new mapping */
46141 int flags = PROT_READ; /* Flags to pass to mmap() */
46142
46143 assert( pFd->nFetchOut==0 );
46144 assert( nNew>pFd->mmapSize );
@@ -45964,25 +46152,16 @@
46152 #endif
46153
46154 if( pOrig ){
46155 #if HAVE_MREMAP
46156 i64 nReuse = pFd->mmapSize;
46157 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
46158 zErr = "mremap";
46159 #else
46160 const int szSyspage = osGetpagesize();
46161 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
 
46162 u8 *pReq = &pOrig[nReuse];
 
 
 
 
 
 
 
 
 
 
46163 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
46164 if( pNew!=MAP_FAILED ){
46165 if( pNew!=pReq ){
46166 osMunmap(pNew, nNew - nReuse);
46167 pNew = 0;
@@ -46613,40 +46792,33 @@
46792 verifyDbFile(pNew);
46793 }
46794 return rc;
46795 }
46796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46797 /*
46798 ** Return the name of a directory in which to put temporary files.
46799 ** If no suitable temporary file directory can be found, return NULL.
46800 **
46801 ** The return value might be a string obtained from getenv() and so
46802 ** the return value should not be used after any call to setenv() or
46803 ** putenv() as that value might have been freed.
46804 */
46805 static const char *unixTempFileDir(void){
46806 unsigned int i;
46807 struct stat buf;
46808 const char *zDir;
46809
46810 for(i=0; i<7; i++){
46811 switch( i ){
46812 case 0: zDir = sqlite3_temp_directory; break;
46813 case 1: zDir = getenv("SQLITE_TMPDIR"); break;
46814 case 2: zDir = getenv("TMPDIR"); break;
46815 case 3: zDir = "/var/tmp"; break;
46816 case 4: zDir = "/usr/tmp"; break;
46817 case 5: zDir = "/tmp"; break;
46818 default: zDir = "."; break;
46819 }
46820 if( zDir!=0
46821 #if OS_VXWORKS
46822 && zDir[0]=='/'
46823 #endif
46824 && osStat(zDir, &buf)==0
@@ -46653,12 +46825,10 @@
46825 && S_ISDIR(buf.st_mode)
46826 && osAccess(zDir, 03)==0
46827 ){
46828 return zDir;
46829 }
 
 
46830 }
46831 return 0;
46832 }
46833
46834 /*
@@ -48937,13 +49107,10 @@
49107 ** DMS UNIX_SHM_BASE+8 128
49108 */
49109 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
49110 #endif
49111
 
 
 
49112 return SQLITE_OK;
49113 }
49114
49115 /*
49116 ** Shutdown the operating system interface.
@@ -52221,11 +52388,11 @@
52388 # define sqlite3_win_test_unc_locking 0
52389 #endif
52390
52391 /*
52392 ** Return true if the string passed as the only argument is likely
52393 ** to be a UNC path. Return false if not.
52394 **
52395 ** Return true if:
52396 **
52397 ** (1) The name begins with "\\"
52398 ** (2) But does not begin with "\\?\C:\" where C can be any alphabetic
@@ -55070,26 +55237,27 @@
55237 int iDb;
55238 Btree *pBt;
55239 sqlite3_int64 sz;
55240 int szPage = 0;
55241 sqlite3_stmt *pStmt = 0;
55242 unsigned char *pOut = 0;
55243 char *zSql;
55244 int rc;
55245
55246 #ifdef SQLITE_ENABLE_API_ARMOR
55247 if( !sqlite3SafetyCheckOk(db) ){
55248 (void)SQLITE_MISUSE_BKPT;
55249 return 0;
55250 }
55251 #endif
55252 sqlite3_mutex_enter(db->mutex);
55253
55254 if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
55255 p = memdbFromDbSchema(db, zSchema);
55256 iDb = sqlite3FindDbName(db, zSchema);
55257 if( piSize ) *piSize = -1;
55258 if( iDb<0 ) goto serialize_out;
55259 if( p ){
55260 MemStore *pStore = p->pStore;
55261 assert( pStore->pMutex==0 );
55262 if( piSize ) *piSize = pStore->sz;
55263 if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
@@ -55096,23 +55264,21 @@
55264 pOut = pStore->aData;
55265 }else{
55266 pOut = sqlite3_malloc64( pStore->sz );
55267 if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
55268 }
55269 goto serialize_out;
55270 }
55271 pBt = db->aDb[iDb].pBt;
55272 if( pBt==0 ) goto serialize_out;
55273 szPage = sqlite3BtreeGetPageSize(pBt);
55274 zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
55275 rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
55276 sqlite3_free(zSql);
55277 if( rc ) goto serialize_out;
55278 rc = sqlite3_step(pStmt);
55279 if( rc==SQLITE_ROW ){
 
 
55280 sz = sqlite3_column_int64(pStmt, 0)*szPage;
55281 if( sz==0 ){
55282 sqlite3_reset(pStmt);
55283 sqlite3_exec(db, "BEGIN IMMEDIATE; COMMIT;", 0, 0, 0);
55284 rc = sqlite3_step(pStmt);
@@ -55142,10 +55308,13 @@
55308 }
55309 }
55310 }
55311 }
55312 sqlite3_finalize(pStmt);
55313
55314 serialize_out:
55315 sqlite3_mutex_leave(db->mutex);
55316 return pOut;
55317 }
55318
55319 /* Convert zSchema to a MemDB and initialize its content.
55320 */
@@ -59917,10 +60086,45 @@
60086 static void freeSuperJournal(char *zSuper){
60087 if( zSuper ){
60088 sqlite3_free(&zSuper[-4]);
60089 }
60090 }
60091
60092 /*
60093 ** Check if zSuper is a valid super-journal name. There are two valid
60094 ** formats:
60095 **
60096 ** + The 3rd and 4th last bytes of the filename are ".9", and the
60097 ** following 2 bytes are hex digits. This is a file created in 8.3
60098 ** filenames mode.
60099 **
60100 ** + The 3rd last byte of the filename is "9" and the filename
60101 ** contains the string "-mj" starting at the 12th last byte.
60102 ** All bytes following the "-mj" are hex digits.
60103 **
60104 ** If the filename matches either of these patterns, return non-zero.
60105 ** Otherwise, return zero.
60106 */
60107 static int pagerIsSuperJrnlName(const char *zSuper){
60108 const int nSuper = sqlite3Strlen30(zSuper);
60109 int ii;
60110
60111 #ifdef SQLITE_ENABLE_8_3_NAMES
60112 if( nSuper<4 ) return 0;
60113 if( zSuper[nSuper-3]!='9' ) return 0;
60114 if( sqlite3Isxdigit(zSuper[nSuper-2])==0 ) return 0;
60115 if( sqlite3Isxdigit(zSuper[nSuper-1])==0 ) return 0;
60116 if( zSuper[nSuper-4]=='.' ) return 1;
60117 #endif
60118 if( nSuper<12 ) return 0;
60119 if( memcmp(&zSuper[nSuper-12], "-mj", 3) ) return 0;
60120 if( zSuper[nSuper-3]!='9' ) return 0;
60121 for(ii=nSuper-9; ii<nSuper; ii++){
60122 if( sqlite3Isxdigit(zSuper[ii])==0 ) return 0;
60123 }
60124 return 1;
60125 }
60126
60127 /*
60128 ** Parameter pJrnl is a file-handle open on a journal file. This function
60129 ** attempts to read a super-journal file name from the end of the journal
60130 ** file. If successful, it sets output parameter (*pzSuper) to point to a
@@ -59955,32 +60159,34 @@
60159 || len>=nSuper
60160 || len>szJ-16
60161 || len==0
60162 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
60163 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
 
60164 ){
60165 return rc;
60166 }
60167
60168 zOut = (char*)sqlite3MallocZero(4 + len + 2);
60169 if( !zOut ){
60170 rc = memcmp(aMagic,aJournalMagic,8) ? SQLITE_OK : SQLITE_NOMEM_BKPT;
60171 }else{
60172 zOut = &zOut[4];
60173 if( SQLITE_OK==(rc = sqlite3OsRead(pJrnl, zOut, len, szJ-16-len)) ){
60174 u32 u; /* Unsigned loop counter */
60175 /* See if the checksum matches the super-journal name */
60176 for(u=0; u<len; u++){
60177 cksum -= zOut[u];
60178 }
60179 }
60180 if( rc!=SQLITE_OK /* Couldn't read the name */
60181 || !pagerIsSuperJrnlName(zOut) /* Name is not valid */
60182 || cksum /* checksum is incorrect */
60183 || memcmp(aMagic, aJournalMagic, 8)!=0 /* Bad magic number */
60184 ){
60185 /* If any validity checks fail, that means the super-journal filename
60186 ** is corrupted, so rollback. Return SQLITE_K and a NULL super-journal
60187 ** name */
60188 freeSuperJournal(zOut);
60189 zOut = 0;
60190 }
60191 }
60192
@@ -60359,10 +60565,11 @@
60565 i64 jrnlSize; /* Size of journal file on disk */
60566 u32 cksum = 0; /* Checksum of string zSuper */
60567
60568 assert( pPager->setSuper==0 );
60569 assert( !pagerUseWal(pPager) );
60570 assert( zSuper==0 || pagerIsSuperJrnlName(zSuper) );
60571
60572 if( !zSuper
60573 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
60574 || !isOpen(pPager->jfd)
60575 ){
@@ -61189,10 +61396,23 @@
61396 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
61397 char *zSuperJournal = 0; /* Contents of super-journal file */
61398 i64 nSuperJournal; /* Size of super-journal file */
61399 char *zJournal; /* Pointer to one journal within MJ file */
61400 char *zFree = 0; /* Free this buffer */
61401 int bSeen = 0; /* If super-journal contains pPager->zJournal */
61402
61403 /* Check if this looks like a real super-journal name. If it does not,
61404 ** return SQLITE_OK without attempting to delete it. This is to limit
61405 ** the degree to which a crafted journal file can be used to cause
61406 ** SQLite to delete arbitrary files.
61407 **
61408 ** This test never fails, becaue the super journal name is checked
61409 ** by readSuperJournal().
61410 */
61411 if( NEVER(pagerIsSuperJrnlName(zSuper)==0) ){
61412 return SQLITE_OK;
61413 }
61414
61415 /* Allocate space for both the pJournal and pSuper file descriptors.
61416 ** If successful, open the super-journal file for reading.
61417 */
61418 pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
@@ -61228,51 +61448,60 @@
61448 zSuperJournal[nSuperJournal] = 0;
61449 zSuperJournal[nSuperJournal+1] = 0;
61450
61451 zJournal = zSuperJournal;
61452 while( (zJournal-zSuperJournal)<nSuperJournal ){
61453 if( strcmp(zJournal, pPager->zJournal)==0 ){
61454 bSeen = 1;
61455 }else{
61456 int exists;
61457 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
61458 if( rc!=SQLITE_OK ){
61459 goto delsuper_out;
61460 }
61461 if( exists ){
61462 char *zSuperPtr = 0;
61463
61464 /* One of the journals pointed to by the super-journal exists.
61465 ** Open it and check if it points at the super-journal. If
61466 ** so, return without deleting the super-journal file.
61467 ** NB: zJournal is really a MAIN_JOURNAL. But call it a
61468 ** SUPER_JOURNAL here so that the VFS will not send the zJournal
61469 ** name into sqlite3_database_file_object().
61470 */
61471 int c;
61472 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
61473 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
61474 if( rc!=SQLITE_OK ){
61475 goto delsuper_out;
61476 }
61477
61478 rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr);
61479 sqlite3OsClose(pJournal);
61480 if( rc!=SQLITE_OK ){
61481 assert( zSuperPtr==0 );
61482 goto delsuper_out;
61483 }
61484
61485 c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0;
61486 freeSuperJournal(zSuperPtr);
61487 if( c ){
61488 /* We have a match. Do not delete the super-journal file. */
61489 goto delsuper_out;
61490 }
61491 }
61492 }
61493 zJournal += (sqlite3Strlen30(zJournal)+1);
61494 }
61495
61496 sqlite3OsClose(pSuper);
61497 if( bSeen ){
61498 /* Only delete the super-journal if bSeen is true - indicating that
61499 ** the super-journal contained a pointer to this database's journal
61500 ** file. */
61501 rc = sqlite3OsDelete(pVfs, zSuper, 0);
61502 }
61503
61504 delsuper_out:
61505 sqlite3_free(zFree);
61506 if( pSuper ){
61507 sqlite3OsClose(pSuper);
@@ -71674,10 +71903,13 @@
71903 int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
71904 ** Error code if eState==CURSOR_FAULT */
71905 Btree *pBtree; /* The Btree to which this cursor belongs */
71906 Pgno *aOverflow; /* Cache of overflow page locations */
71907 void *pKey; /* Saved key that was cursor last known position */
71908 #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
71909 BtCursor *pCursorHintTableCursor;
71910 #endif
71911 /* All fields above are zeroed when the cursor is allocated. See
71912 ** sqlite3BtreeCursorZero(). Fields that follow must be manually
71913 ** initialized. */
71914 #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
71915 BtShared *pBt; /* The BtShared this cursor points to */
@@ -71850,10 +72082,13 @@
72082 int v2; /* Value for third %d substitution in zPfx */
72083 StrAccum errMsg; /* Accumulate the error message text here */
72084 u32 *heap; /* Min-heap used for analyzing cell coverage */
72085 sqlite3 *db; /* Database connection running the check */
72086 i64 nRow; /* Number of rows visited in current tree */
72087 #ifdef SQLITE_DEBUG
72088 u32 mxHeap; /* Maximum number of entries in the Min-heap */
72089 #endif
72090 };
72091
72092 /*
72093 ** Routines to read or write a two- and four-byte big-endian integer values.
72094 */
@@ -73178,28 +73413,45 @@
73413 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
73414 */
73415 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
73416 /* Used only by system that substitute their own storage engine */
73417 #ifdef SQLITE_DEBUG
73418 va_list ap;
73419 va_start(ap, eHintType);
73420 if( eHintType==BTREE_HINT_RANGE ){
73421 Expr *pExpr;
73422 Walker w;
73423 memset(&w, 0, sizeof(w));
73424 w.xExprCallback = sqlite3CursorRangeHintExprCheck;
 
73425 pExpr = va_arg(ap, Expr*);
73426 w.u.aMem = va_arg(ap, Mem*);
 
73427 assert( pExpr!=0 );
73428 assert( w.u.aMem!=0 );
73429 sqlite3WalkExpr(&w, pExpr);
73430 }else if( ALWAYS(eHintType==BTREE_HINT_TABLECURSOR) ){
73431 BtCursor *pCsr = va_arg(ap, BtCursor*);
73432 assert( pCur->pCursorHintTableCursor==0
73433 || pCur->pCursorHintTableCursor==pCsr
73434 );
73435 assert( pCsr->pKeyInfo==0 || CORRUPT_DB );
73436 pCur->pCursorHintTableCursor = pCsr;
73437 }
73438 va_end(ap);
73439 #endif /* SQLITE_DEBUG */
73440 }
73441 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
73442
73443 #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
73444 /*
73445 ** Return the pointer configured via the BTREE_HINT_TABLECURSOR hint on
73446 ** cursor pCsr. This is used from OP_DeferredSeek to assert() that the
73447 ** index cursor has been correctly configured with the table cursor.
73448 */
73449 SQLITE_PRIVATE BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor *pCsr){
73450 return pCsr->pCursorHintTableCursor;
73451 }
73452 #endif
73453
73454 /*
73455 ** Provide flag hints to the cursor.
73456 */
73457 SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
@@ -74321,12 +74573,19 @@
74573 /* Freeblock off the end of the page */
74574 return SQLITE_CORRUPT_PAGE(pPage);
74575 }
74576 next = get2byte(&data[pc]);
74577 size = get2byte(&data[pc+2]);
74578 if( size<4 && sqlite3FaultSim(422)==SQLITE_OK ){
74579 /* Minimum freeblock size is 4. Enable fault-sim 422 to disable this
74580 ** check to reach interesting error stats. However, disabling this
74581 ** check can cause assertion faults due to min-heap overflow. All
74582 ** fault-sims are for testing use only, but this one especially so. */
74583 return SQLITE_CORRUPT_PAGE(pPage);
74584 }
74585 nFree = nFree + size;
74586 if( next<pc+size+4 ) break;
74587 pc = next;
74588 }
74589 if( next>0 ){
74590 /* Freeblock not in ascending order */
74591 return SQLITE_CORRUPT_PAGE(pPage);
@@ -78157,18 +78416,18 @@
78416 nCell = pCell[0];
78417 if( nCell<=pPage->max1bytePayload ){
78418 /* This branch runs if the record-size field of the cell is a
78419 ** single byte varint and the record fits entirely on the main
78420 ** b-tree page. */
78421 if( pCell + nCell >= pPage->aDataEnd ) return 99;
78422 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
78423 }else if( !(pCell[1] & 0x80)
78424 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
78425 ){
78426 /* The record-size field is a 2 byte varint and the record
78427 ** fits entirely on the main b-tree page. */
78428 if( pCell + nCell >= pPage->aDataEnd ) return 99;
78429 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
78430 }else{
78431 /* If the record extends into overflow pages, do not attempt
78432 ** the optimization. */
78433 c = 99;
@@ -78326,18 +78585,21 @@
78585 nCell = pCell[0];
78586 if( nCell<=pPage->max1bytePayload ){
78587 /* This branch runs if the record-size field of the cell is a
78588 ** single byte varint and the record fits entirely on the main
78589 ** b-tree page. */
78590 if( pCell + nCell >= pPage->aDataEnd ){
78591 rc = SQLITE_CORRUPT_PAGE(pPage);
78592 goto moveto_index_finish;
78593 }
78594 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
78595 }else if( !(pCell[1] & 0x80)
78596 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
78597 && pCell + nCell < pPage->aDataEnd
78598 ){
78599 /* The record-size field is a 2 byte varint and the record
78600 ** fits entirely on the main b-tree page. */
 
78601 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
78602 }else{
78603 /* The record flows over onto one or more overflow pages. In
78604 ** this case the whole cell needs to be parsed, a buffer allocated
78605 ** and accessPayload() used to retrieve the record into the
@@ -83203,10 +83465,11 @@
83465 checkAppendMsg(pCheck, "Child page depth differs");
83466 depth = d2;
83467 }
83468 }else{
83469 /* Populate the coverage-checking heap for leaf pages */
83470 assert( heap!=0 && heap[0] < pCheck->mxHeap );
83471 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
83472 }
83473 }
83474 *piMinKey = maxKey;
83475
@@ -83222,10 +83485,11 @@
83485 heap[0] = 0;
83486 for(i=nCell-1; i>=0; i--){
83487 u32 size;
83488 pc = get2byteAligned(&data[cellStart+i*2]);
83489 size = pPage->xCellSize(pPage, &data[pc]);
83490 assert( heap!=0 && heap[0] < pCheck->mxHeap );
83491 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
83492 }
83493 }
83494 assert( heap!=0 );
83495 /* Add the freeblocks to the min-heap
@@ -83238,10 +83502,11 @@
83502 while( i>0 ){
83503 int size, j;
83504 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
83505 size = get2byte(&data[i+2]);
83506 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
83507 assert( heap!=0 && heap[0] < pCheck->mxHeap );
83508 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
83509 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
83510 ** big-endian integer which is the offset in the b-tree page of the next
83511 ** freeblock in the chain, or zero if the freeblock is the last on the
83512 ** chain. */
@@ -83372,10 +83637,13 @@
83637 if( !sCheck.aPgRef ){
83638 checkOom(&sCheck);
83639 goto integrity_ck_cleanup;
83640 }
83641 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
83642 #ifdef SQLITE_DEBUG
83643 sCheck.mxHeap = pBt->pageSize/4 - 1;
83644 #endif
83645 if( sCheck.heap==0 ){
83646 checkOom(&sCheck);
83647 goto integrity_ck_cleanup;
83648 }
83649
@@ -83796,17 +84064,18 @@
84064 /*
84065 ** Structure allocated for each backup operation.
84066 */
84067 struct sqlite3_backup {
84068 sqlite3* pDestDb; /* Destination database handle */
84069 char *zDestDb;
84070 Btree *pDest; /* Destination b-tree file */
84071 u32 iDestSchema; /* Original schema cookie in destination */
84072 int bDestLocked; /* True once a write-transaction is open on pDest */
84073
84074 Pgno iNext; /* Page number of the next source page to copy */
84075 sqlite3* pSrcDb; /* Source database handle */
84076 Btree *pSrc; /* Source b-tree file */
84077
84078 int rc; /* Backup process error code */
84079
84080 /* These two variables are set by every call to backup_step(). They are
84081 ** read by calls to backup_remaining() and backup_pagecount().
@@ -83855,13 +84124,15 @@
84124 **
84125 ** If the "temp" database is requested, it may need to be opened by this
84126 ** function. If an error occurs while doing so, return 0 and write an
84127 ** error message to pErrorDb.
84128 */
84129 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
84130 int i;
84131
84132 assert( pDb!=0 );
84133 i = sqlite3FindDbName(pDb, zDb);
84134 if( i==1 ){
84135 Parse sParse;
84136 int rc = 0;
84137 sqlite3ParseObjectInit(&sParse,pDb);
84138 if( sqlite3OpenTempDatabase(&sParse) ){
@@ -83878,21 +84149,19 @@
84149 if( i<0 ){
84150 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
84151 return 0;
84152 }
84153
84154 return pDb->aDb[i].pBt;
84155 }
84156
84157 /*
84158 ** Attempt to set the page size of the destination to match the page size
84159 ** of the source.
84160 */
84161 static int setDestPgsz(Btree *pDest, Btree *pSrc){
84162 return sqlite3BtreeSetPageSize(pDest, sqlite3BtreeGetPageSize(pSrc), 0, 0);
 
 
84163 }
84164
84165 /*
84166 ** Check that there is no open read-transaction on the b-tree passed as the
84167 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
@@ -83945,31 +84214,41 @@
84214 sqlite3ErrorWithMsg(
84215 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
84216 );
84217 p = 0;
84218 }else {
84219 int nDest = sqlite3Strlen30(zDestDb);
84220
84221 /* Allocate space for a new sqlite3_backup object...
84222 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
84223 ** call to sqlite3_backup_init() and is destroyed by a call to
84224 ** sqlite3_backup_finish(). */
84225 p = (sqlite3_backup*)sqlite3MallocZero(sizeof(sqlite3_backup)+nDest+1);
84226 if( !p ){
84227 sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
84228 }else{
84229 p->zDestDb = (char*)&p[1];
84230 memcpy(p->zDestDb, zDestDb, nDest);
84231 }
84232 }
84233
84234 /* If the allocation succeeded, populate the new object. */
84235 if( p ){
84236 /* Do not store the pointer to the destination b-tree at this point.
84237 ** This is because there is nothing preventing it from being detached
84238 ** or otherwise freed before the first call to sqlite3_backup_step()
84239 ** on this object. The source b-tree does not have this problem, as
84240 ** incrementing Btree.nBackup (see below) effectively locks the object. */
84241 Btree *pDest = findBtree(pDestDb, pDestDb, zDestDb);
84242 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
84243 p->pDestDb = pDestDb;
84244 p->pSrcDb = pSrcDb;
84245 p->iNext = 1;
84246 p->isAttached = 0;
84247
84248 if( 0==p->pSrc || 0==pDest
84249 || checkReadTransaction(pDestDb, pDest)!=SQLITE_OK
84250 ){
84251 /* One (or both) of the named databases did not exist or an OOM
84252 ** error was hit. Or there is a transaction open on the destination
84253 ** database. The error has already been written into the pDestDb
84254 ** handle. All that is left to do here is free the sqlite3_backup
@@ -83977,11 +84256,11 @@
84256 sqlite3_free(p);
84257 p = 0;
84258 }
84259 }
84260 if( p ){
84261 p->pSrc->nBackup++;
84262 }
84263
84264 sqlite3_mutex_leave(pDestDb->mutex);
84265 sqlite3_mutex_leave(pSrcDb->mutex);
84266 return p;
@@ -84005,22 +84284,22 @@
84284 sqlite3_backup *p, /* Backup handle */
84285 Pgno iSrcPg, /* Source database page to backup */
84286 const u8 *zSrcData, /* Source database page data */
84287 int bUpdate /* True for an update, false otherwise */
84288 ){
84289 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
84290 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
84291 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
84292 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
84293 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
84294 int rc = SQLITE_OK;
84295 i64 iOff;
84296
84297 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
84298 assert( p->bDestLocked );
84299 assert( !isFatalError(p->rc) );
84300 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
84301 assert( zSrcData );
84302 assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 );
84303
84304 /* This loop runs once for each destination page spanned by the source
84305 ** page. For each iteration, variable iOff is set to the byte offset
@@ -84027,11 +84306,11 @@
84306 ** of the destination page.
84307 */
84308 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
84309 DbPage *pDestPg = 0;
84310 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
84311 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
84312 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
84313 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
84314 ){
84315 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
84316 u8 *zDestData = sqlite3PagerGetData(pDestPg);
@@ -84045,11 +84324,11 @@
84324 ** "MUST BE FIRST" for this purpose.
84325 */
84326 memcpy(zOut, zIn, nCopy);
84327 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
84328 if( iOff==0 && bUpdate==0 ){
84329 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
84330 }
84331 }
84332 sqlite3PagerUnref(pDestPg);
84333 }
84334
@@ -84077,12 +84356,12 @@
84356 ** Register this backup object with the associated source pager for
84357 ** callbacks when pages are changed or the cache invalidated.
84358 */
84359 static void attachBackupObject(sqlite3_backup *p){
84360 sqlite3_backup **pp;
84361 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
84362 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
84363 p->pNext = *pp;
84364 *pp = p;
84365 p->isAttached = 1;
84366 }
84367
@@ -84089,93 +84368,103 @@
84368 /*
84369 ** Copy nPage pages from the source b-tree to the destination.
84370 */
84371 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
84372 int rc;
84373 int destMode = 0; /* Destination journal mode */
84374 int pgszSrc = 0; /* Source page size */
84375 int pgszDest = 0; /* Destination page size */
 
 
84376
84377 #ifdef SQLITE_ENABLE_API_ARMOR
84378 if( p==0 ) return SQLITE_MISUSE_BKPT;
84379 #endif
 
 
 
 
84380 sqlite3_mutex_enter(p->pSrcDb->mutex);
84381 sqlite3BtreeEnter(p->pSrc);
84382 if( p->pDestDb ){
84383 sqlite3_mutex_enter(p->pDestDb->mutex);
84384 }
84385
84386 rc = p->rc;
84387 if( !isFatalError(rc) ){
84388 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
84389 Btree * pDest = 0; /* Dest btree */
84390 Pager * pDestPager = 0; /* Dest pager */
84391 int ii; /* Iterator variable */
84392 int nSrcPage = -1; /* Size of source db in pages */
84393 int bCloseTrans = 0; /* True if src db requires unlocking */
84394
84395 /* If the source pager is currently in a write-transaction, return
84396 ** SQLITE_BUSY immediately.
84397 */
84398 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
84399 rc = SQLITE_BUSY;
84400 }else{
84401 rc = SQLITE_OK;
84402 }
84403
84404
84405 /* If there is no open read-transaction on the source database, open
84406 ** one now. If a transaction is opened here, then it will be closed
84407 ** before this function exits.
84408 */
84409 if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
84410 rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
84411 bCloseTrans = 1;
84412 }
84413
84414 /* Locate the destination btree and pager. */
84415 if( (pDest = p->pDest)==0 ){
84416 pDest = findBtree(p->pDestDb, p->pDestDb, p->zDestDb);
84417 }
84418 if( pDest==0 ){
84419 rc = SQLITE_ERROR;
84420 }else{
84421 pDestPager = sqlite3BtreePager(pDest);
84422 }
84423
84424 /* If the destination database has not yet been locked (i.e. if this
84425 ** is the first call to backup_step() for the current backup operation),
84426 ** try to set its page size to the same as the source database. This
84427 ** is especially important on ZipVFS systems, as in that case it is
84428 ** not possible to create a database file that uses one page size by
84429 ** writing to it with another. */
84430 if( p->bDestLocked==0 && rc==SQLITE_OK
84431 && setDestPgsz(pDest, p->pSrc)==SQLITE_NOMEM
84432 ){
84433 rc = SQLITE_NOMEM;
84434 }
84435
84436 /* Lock the destination database, if it is not locked already. */
84437 if( SQLITE_OK==rc && p->bDestLocked==0
84438 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(pDest, 2,
84439 (int*)&p->iDestSchema))
84440 ){
84441 p->bDestLocked = 1;
84442 p->pDest = pDest;
84443 }
84444
84445 /* Do not allow backup if the destination database is in WAL mode
84446 ** and the page sizes are different between source and destination */
84447 if( rc==SQLITE_OK ){
84448 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
84449 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
84450 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
84451 if( (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
84452 && pgszSrc!=pgszDest
84453 ){
84454 rc = SQLITE_READONLY;
84455 }
84456 }
84457
84458 /* Now that there is a read-lock on the source database, query the
84459 ** source pager for the number of pages in the database.
84460 */
84461 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
84462 assert( nSrcPage>=0 );
84463 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
84464 const Pgno iSrcPg = p->iNext; /* Source page number */
84465 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
84466 DbPage *pSrcPg; /* Source page object */
84467 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
84468 if( rc==SQLITE_OK ){
84469 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
84470 sqlite3PagerUnref(pSrcPg);
@@ -84198,22 +84487,22 @@
84487 ** the case where the source and destination databases have the
84488 ** same schema version.
84489 */
84490 if( rc==SQLITE_DONE ){
84491 if( nSrcPage==0 ){
84492 rc = sqlite3BtreeNewDb(p->pDest);
84493 nSrcPage = 1;
84494 }
84495 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
84496 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
84497 }
84498 if( rc==SQLITE_OK ){
84499 if( p->pDestDb ){
84500 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
84501 }
84502 if( destMode==PAGER_JOURNALMODE_WAL ){
84503 rc = sqlite3BtreeSetVersion(p->pDest, 2);
84504 }
84505 }
84506 if( rc==SQLITE_OK ){
84507 int nDestTruncate;
84508 /* Set nDestTruncate to the final number of pages in the destination
@@ -84226,16 +84515,16 @@
84515 ** sqlite3PagerTruncateImage() here so that any pages in the
84516 ** destination file that lie beyond the nDestTruncate page mark are
84517 ** journalled by PagerCommitPhaseOne() before they are destroyed
84518 ** by the file truncation.
84519 */
84520 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
84521 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
84522 if( pgszSrc<pgszDest ){
84523 int ratio = pgszDest/pgszSrc;
84524 nDestTruncate = (nSrcPage+ratio-1)/ratio;
84525 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
84526 nDestTruncate--;
84527 }
84528 }else{
84529 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
84530 }
@@ -84259,11 +84548,11 @@
84548 i64 iEnd;
84549
84550 assert( pFile );
84551 assert( nDestTruncate==0
84552 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
84553 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
84554 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
84555 ));
84556
84557 /* This block ensures that all data required to recreate the original
84558 ** database has been stored in the journal for pDestPager and the
@@ -84271,11 +84560,11 @@
84560 ** the database file in any way, knowing that if a power failure
84561 ** occurs, the original database will be reconstructed from the
84562 ** journal file. */
84563 sqlite3PagerPagecount(pDestPager, &nDstPage);
84564 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
84565 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
84566 DbPage *pPg;
84567 rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
84568 if( rc==SQLITE_OK ){
84569 rc = sqlite3PagerWrite(pPg);
84570 sqlite3PagerUnref(pPg);
@@ -84315,11 +84604,11 @@
84604 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
84605 }
84606
84607 /* Finish committing the transaction to the destination database. */
84608 if( SQLITE_OK==rc
84609 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
84610 ){
84611 rc = SQLITE_DONE;
84612 }
84613 }
84614 }
@@ -84329,12 +84618,12 @@
84618 ** no need to check the return values of the btree methods here, as
84619 ** "committing" a read-only transaction cannot fail.
84620 */
84621 if( bCloseTrans ){
84622 TESTONLY( int rc2 );
84623 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
84624 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
84625 assert( rc2==SQLITE_OK );
84626 }
84627
84628 if( rc==SQLITE_IOERR_NOMEM ){
84629 rc = SQLITE_NOMEM_BKPT;
@@ -84342,11 +84631,11 @@
84631 p->rc = rc;
84632 }
84633 if( p->pDestDb ){
84634 sqlite3_mutex_leave(p->pDestDb->mutex);
84635 }
84636 sqlite3BtreeLeave(p->pSrc);
84637 sqlite3_mutex_leave(p->pSrcDb->mutex);
84638 return rc;
84639 }
84640
84641 /*
@@ -84359,41 +84648,43 @@
84648
84649 /* Enter the mutexes */
84650 if( p==0 ) return SQLITE_OK;
84651 pSrcDb = p->pSrcDb;
84652 sqlite3_mutex_enter(pSrcDb->mutex);
84653 sqlite3BtreeEnter(p->pSrc);
84654 if( p->pDestDb ){
84655 sqlite3_mutex_enter(p->pDestDb->mutex);
84656 }
84657
84658 /* Detach this backup from the source pager. */
84659 if( p->pDestDb ){
84660 p->pSrc->nBackup--;
84661 }
84662 if( p->isAttached ){
84663 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
84664 assert( pp!=0 );
84665 while( *pp!=p ){
84666 pp = &(*pp)->pNext;
84667 assert( pp!=0 );
84668 }
84669 *pp = p->pNext;
84670 }
84671
84672 /* If a transaction is still open on the Btree, roll it back. */
84673 if( p->pDest ){
84674 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
84675 }
84676
84677 /* Set the error code of the destination database handle. */
84678 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
84679 if( p->pDestDb ){
84680 sqlite3Error(p->pDestDb, rc);
84681
84682 /* Exit the mutexes and free the backup context structure. */
84683 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
84684 }
84685 sqlite3BtreeLeave(p->pSrc);
84686 if( p->pDestDb ){
84687 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
84688 ** call to sqlite3_backup_init() and is destroyed by a call to
84689 ** sqlite3_backup_finish(). */
84690 sqlite3_free(p);
@@ -84447,11 +84738,11 @@
84738 Pgno iPage,
84739 const u8 *aData
84740 ){
84741 assert( p!=0 );
84742 do{
84743 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
84744 if( !isFatalError(p->rc) && iPage<p->iNext ){
84745 /* The backup process p has already copied page iPage. But now it
84746 ** has been modified by a transaction on the source pager. Copy
84747 ** the new data into the backup.
84748 */
@@ -84483,11 +84774,11 @@
84774 ** called.
84775 */
84776 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
84777 sqlite3_backup *p; /* Iterator variable */
84778 for(p=pBackup; p; p=p->pNext){
84779 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
84780 p->iNext = 1;
84781 }
84782 }
84783
84784 #ifndef SQLITE_OMIT_VACUUM
@@ -84501,12 +84792,10 @@
84792 */
84793 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
84794 int rc;
84795 sqlite3_file *pFd; /* File descriptor for database pTo */
84796 sqlite3_backup b;
 
 
84797 sqlite3BtreeEnter(pTo);
84798 sqlite3BtreeEnter(pFrom);
84799
84800 assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
84801 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
@@ -84521,17 +84810,13 @@
84810 ** to 0. This is used by the implementations of sqlite3_backup_step()
84811 ** and sqlite3_backup_finish() to detect that they are being called
84812 ** from this function, not directly by the user.
84813 */
84814 memset(&b, 0, sizeof(b));
 
 
 
 
84815 b.pSrcDb = pFrom->db;
84816 b.pSrc = pFrom;
84817 b.pDest = pTo;
84818 b.iNext = 1;
84819
84820 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
84821 ** file. By passing this as the number of pages to copy to
84822 ** sqlite3_backup_step(), we can guarantee that the copy finishes
@@ -84543,11 +84828,11 @@
84828
84829 rc = sqlite3_backup_finish(&b);
84830 if( rc==SQLITE_OK ){
84831 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
84832 }else{
84833 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
84834 }
84835
84836 assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
84837 copy_finished:
84838 sqlite3BtreeLeave(pFrom);
@@ -86859,11 +87144,10 @@
87144 p->pParse = pParse;
87145 pParse->pVdbe = p;
87146 assert( pParse->aLabel==0 );
87147 assert( pParse->nLabel==0 );
87148 assert( p->nOpAlloc==0 );
 
87149 sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
87150 return p;
87151 }
87152
87153 /*
@@ -87009,12 +87293,11 @@
87293
87294 assert( nOp<=(int)(1024/sizeof(Op)) );
87295 assert( nNew>=(v->nOpAlloc+nOp) );
87296 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
87297 if( pNew ){
87298 v->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
 
87299 v->aOp = pNew;
87300 }
87301 return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
87302 }
87303
@@ -87445,11 +87728,11 @@
87728 ** Resolve label "x" to be the address of the next instruction to
87729 ** be inserted. The parameter "x" must have been obtained from
87730 ** a prior call to sqlite3VdbeMakeLabel().
87731 */
87732 static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
87733 int nNewSize = 25 - p->nLabel;
87734 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
87735 nNewSize*sizeof(p->aLabel[0]));
87736 if( p->aLabel==0 ){
87737 p->nLabelAlloc = 0;
87738 }else{
@@ -89513,11 +89796,11 @@
89796 ** of the prepared statement.
89797 */
89798 n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
89799 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
89800 assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
89801 x.nFree = ROUNDDOWN8((p->nOpAlloc-p->nOp)*sizeof(Op)); /* Bytes unused mem */
89802 assert( x.nFree>=0 );
89803 assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
89804
89805 resolveP2Values(p, &nArg);
89806 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
@@ -92662,12 +92945,18 @@
92945 ** that sqlite3_prepare() generates. For example, if new functions or
92946 ** collating sequences are registered or if an authorizer function is
92947 ** added or changed.
92948 */
92949 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
92950 int iRet = 1;
92951 if( pStmt ){
92952 Vdbe *p = (Vdbe*)pStmt;
92953 sqlite3_mutex_enter(p->db->mutex);
92954 iRet = p->expired;
92955 sqlite3_mutex_leave(p->db->mutex);
92956 }
92957 return iRet;
92958 }
92959 #endif
92960
92961 /*
92962 ** Check on a Vdbe to make sure it has not been finalized. Log
@@ -93009,19 +93298,22 @@
93298 sqlite3ValueFree(pOld);
93299 }
93300
93301
93302 /**************************** sqlite3_result_ *******************************
93303 ** The following routines are used by application-defined SQL functions to
93304 ** specify the function return value. There are many variations on
93305 ** sqlite3_result_xxxx() for different types of return values.
93306 **
93307 ** The setStrOrError() function is a helper function that invokes
93308 ** sqlite3VdbeMemSetStr() to store the result as a string or blob.
93309 ** Appropriate errors are set if the string/blob is too big or if
93310 ** an OOM occurs.
93311 **
93312 ** The invokeValueDestructor(P,X) helper function invokes the destructor
93313 ** function X() on value P if P is not going to be used and need to
93314 ** be destroyed.
93315 */
93316 static void setResultStrOrError(
93317 sqlite3_context *pCtx, /* Function context */
93318 const char *z, /* String pointer */
93319 int n, /* Bytes in string, or negative */
@@ -93330,11 +93622,11 @@
93622 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
93623 SQLITE_STATIC);
93624 }
93625 }
93626
93627 /* Cause the SQL function to raise an SQLITE_TOOBIG error. */
93628 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
93629 #ifdef SQLITE_ENABLE_API_ARMOR
93630 if( pCtx==0 ) return;
93631 #endif
93632 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
@@ -93341,20 +93633,78 @@
93633 pCtx->isError = SQLITE_TOOBIG;
93634 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
93635 SQLITE_UTF8, SQLITE_STATIC);
93636 }
93637
93638 /* Cause the SQL function to raise an SQLITE_NOMEM error. */
93639 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
93640 #ifdef SQLITE_ENABLE_API_ARMOR
93641 if( pCtx==0 ) return;
93642 #endif
93643 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
93644 sqlite3VdbeMemSetNull(pCtx->pOut);
93645 pCtx->isError = SQLITE_NOMEM_BKPT;
93646 sqlite3OomFault(pCtx->pOut->db);
93647 }
93648
93649 /* Make the return value of the SQL function or virtual table pCtx
93650 ** be the content of the sqlite3_str object pStr. The eOwn flag
93651 ** determines ownership of the sqlite3_str object and its content.
93652 **
93653 ** eOwn Ownership transfer
93654 ** ------------- ------------------------------------------------
93655 **
93656 ** SQLITE_COPY The SQL function returns a copy the sqlite3_str
93657 ** content and leaves the sqlite3_str object itself
93658 ** unchanged.
93659 **
93660 ** SQLITE_XFER The content of the sqlite3_str is transferred to
93661 ** the SQL function and the SQL function takes
93662 ** responsibility for freeing that content when it is
93663 ** no longer needed. The sqlite3_str object is reset
93664 ** to an empty string.
93665 **
93666 ** SQLITE_FINISH Like SQLITE_XFER except that the pStr is also
93667 ** freed using sqlite3_str_free().
93668 */
93669 SQLITE_API void sqlite3_result_str(sqlite3_context *pCtx, sqlite3_str *pStr, int eOwn){
93670 #ifdef SQLITE_ENABLE_API_ARMOR
93671 if( pCtx==0 ) return;
93672 if( pStr==0 ) return;
93673 #endif
93674 testcase( pStr==(sqlite3_str*)&sqlite3OomStr );
93675 if( pStr->accError==0 ){
93676 if( pStr->nChar==0 ){
93677 setResultStrOrError(pCtx, "", 0, SQLITE_UTF8_ZT, SQLITE_STATIC);
93678 sqlite3_str_reset(pStr);
93679 }else{
93680 const char *zText = sqlite3_str_value(pStr);
93681 /* Only internal code has the ability to capture a pointer to
93682 ** an sqlite3_str object that uses static buffer. And none of
93683 ** those internal use cases every invoke the sqlite3_result_str()
93684 ** interface on a static-buffer sqlite3_str. Should this change
93685 ** in the future, the following assert() will let us know. */
93686 assert( isMalloced(pStr) );
93687 if( eOwn==SQLITE_COPY ){
93688 setResultStrOrError(pCtx, zText, pStr->nChar,
93689 SQLITE_UTF8, SQLITE_TRANSIENT);
93690 }else{
93691 setResultStrOrError(pCtx, zText, pStr->nChar,
93692 SQLITE_UTF8_ZT, SQLITE_DYNAMIC);
93693 sqlite3StrAccumInit(pStr, pStr->db, 0, 0, pStr->mxAlloc);
93694 }
93695 }
93696 }else if( pStr->accError==SQLITE_NOMEM ){
93697 sqlite3_result_error_nomem(pCtx);
93698 }else{
93699 assert( pStr->accError==SQLITE_TOOBIG );
93700 sqlite3_result_error_toobig(pCtx);
93701 }
93702 if( eOwn==SQLITE_FINISH ){
93703 sqlite3_str_free(pStr);
93704 }
93705 }
93706
93707 #ifndef SQLITE_UNTESTABLE
93708 /* Force the INT64 value currently stored as the result to be
93709 ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
93710 ** test-control.
@@ -96241,10 +96591,14 @@
96591 }
96592
96593 /*
96594 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
96595 ** with pOp->p3. Return the hash.
96596 **
96597 ** IMPORTANT RESTRICTION (tag-202607231411): This hash is only valid if the
96598 ** collating sequence for TEXT is BINARY. Hence, Bloom filters that use this
96599 ** hash will not work for look-ups that use any other collating sequence.
96600 */
96601 static u64 filterHash(const Mem *aMem, const Op *pOp){
96602 int i, mx;
96603 u64 h = 0;
96604
@@ -96253,15 +96607,32 @@
96607 const Mem *p = &aMem[i];
96608 if( p->flags & (MEM_Int|MEM_IntReal) ){
96609 h += p->u.i;
96610 }else if( p->flags & MEM_Real ){
96611 h += sqlite3VdbeIntValue(p);
96612 }else if( p->flags & MEM_Str ){
96613 u64 x;
96614 h += p->n;
96615 if( p->n >= sizeof(x) ){
96616 memcpy(&x, p->z, sizeof(x));
96617 h += x;
96618 memcpy(&x, p->z + p->n - sizeof(x), sizeof(x));
96619 h += x;
96620 }else{
96621 x = 0;
96622 memcpy(&x, p->z, p->n);
96623 h += x;
96624 }
96625 }else if( p->flags & MEM_Blob ){
96626 int n = p->n;
96627 u64 x = 0;
96628 if( n ){
96629 memcpy(&x, p->z, MIN(n, sizeof(x)));
96630 h += x;
96631 }
96632 h += n;
96633 if( p->flags & MEM_Zero ) h += p->u.nZero;
96634 }
96635 }
96636 return h;
96637 }
96638
@@ -101084,11 +101455,11 @@
101455 */
101456 case OP_SeekRowid: { /* jump0, in3, ncycle */
101457 VdbeCursor *pC;
101458 BtCursor *pCrsr;
101459 int res;
101460 i64 iKey;
101461
101462 pIn3 = &aMem[pOp->p3];
101463 testcase( pIn3->flags & MEM_Int );
101464 testcase( pIn3->flags & MEM_IntReal );
101465 testcase( pIn3->flags & MEM_Real );
@@ -101098,13 +101469,23 @@
101469 ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
101470 ** into an integer without loss of information. Take care to avoid
101471 ** changing the datatype of pIn3, however, as it is used by other
101472 ** parts of the prepared statement. */
101473 Mem x = pIn3[0];
101474 if( x.flags & MEM_Str ){
101475 applyNumericAffinity(&x, 1);
101476 }
101477 if( x.flags & MEM_Int ){
101478 iKey = x.u.i;
101479 }else
101480 if( (x.flags & MEM_Real)==0
101481 || x.u.r < -9223372036854775808.0
101482 || x.u.r > 9223372036854775807.0
101483 || (double)(iKey = sqlite3RealToI64(x.u.r))!=x.u.r
101484 ){
101485 goto jump_to_p2;
101486 }
101487 goto notExistsWithKey;
101488 }
101489 /* Fall through into OP_NotExists */
101490 /* no break */ deliberate_fall_through
101491 case OP_NotExists: /* jump, in3, ncycle */
@@ -102342,10 +102723,15 @@
102723 pTabCur = p->apCsr[pOp->p3];
102724 assert( pTabCur!=0 );
102725 assert( pTabCur->eCurType==CURTYPE_BTREE );
102726 assert( pTabCur->uc.pCursor!=0 );
102727 assert( pTabCur->isTable );
102728 #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
102729 assert(
102730 sqlite3BtreeCursorHintTblCsr(pC->uc.pCursor)==pTabCur->uc.pCursor
102731 );
102732 #endif
102733 pTabCur->nullRow = 0;
102734 pTabCur->movetoTarget = rowid;
102735 pTabCur->deferredMoveto = 1;
102736 pTabCur->cacheStatus = CACHE_STALE;
102737 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
@@ -104724,27 +105110,41 @@
105110 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
105111 goto jump_to_p2;
105112 }
105113
105114 #ifdef SQLITE_ENABLE_CURSOR_HINTS
105115 /* Opcode: CursorHint P1 * P3 P4 *
105116 **
105117 ** Provide a hint to cursor P1.
105118 **
105119 ** If P4 is of type P4_EXPR, then the hint is that the cursor need only return
105120 ** rows that satisfy the Expr in P4. TK_REGISTER terms in the P4 expression
105121 ** refer to values currently held in registers. TK_COLUMN terms in the P4
105122 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
105123 ** P3 is ignore in this case.
105124 **
105125 ** Or, if P4 is P4_NOTUSED, then the hint is that cursor P1 is an index cursor
105126 ** used to drive table cursor P3. In other words, that this VM may execute
105127 ** OP_DeferredSeek instructions to lazily position P3 based on current
105128 ** position of P1.
105129 */
105130 case OP_CursorHint: {
105131 VdbeCursor *pC;
105132 pC = p->apCsr[pOp->p1];
105133
105134 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
105135
 
105136 if( pC ){
105137 assert( pC->eCurType==CURTYPE_BTREE );
105138 if( pOp->p4type==P4_EXPR ){
105139 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
105140 pOp->p4.pExpr, aMem);
105141 }else if( p->apCsr[pOp->p3] ){
105142 sqlite3BtreeCursorHint(
105143 pC->uc.pCursor, BTREE_HINT_TABLECURSOR, p->apCsr[pOp->p3]->uc.pCursor
105144 );
105145 }
105146 }
105147 break;
105148 }
105149 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
105150
@@ -110329,13 +110729,15 @@
110729 if( pFJMatch ){
110730 assert( pExpr->op==TK_FUNCTION );
110731 assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 );
110732 assert( pExpr->x.pList==pFJMatch );
110733 assert( pFJMatch->nExpr>0 );
110734 for(i=0; i<pFJMatch->nExpr; i++){
110735 assert( pFJMatch->a[i].pExpr->op==TK_COLUMN );
110736 sqlite3AuthRead(pParse,pFJMatch->a[i].pExpr,pSchema,pNC->pSrcList);
110737 }
110738 }else if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
110739 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
110740 }
110741 }
110742 #endif
110743 /* Increment the nRef value on all name contexts from TopNC up to
@@ -110447,15 +110849,24 @@
110849 static SQLITE_NOINLINE void resolveSetExprSubtypeArg(ExprList *pList){
110850 int nn, ii;
110851 nn = pList ? pList->nExpr : 0;
110852 for(ii=0; ii<nn; ii++){
110853 Expr *pExpr = pList->a[ii].pExpr;
110854 while( 1 /*exit-by-break*/ ){
110855 ExprSetProperty(pExpr, EP_SubtArg);
110856 if( pExpr->op==TK_SELECT ){
110857 assert( ExprUseXSelect(pExpr) );
110858 assert( pExpr->x.pSelect!=0 );
110859 resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList);
110860 break;
110861 }
110862 if( pExpr->op==TK_UPLUS ){
110863 pExpr = pExpr->pLeft;
110864 assert( pExpr!=0 );
110865 }else{
110866 break;
110867 }
110868 }
110869 }
110870 }
110871
110872 /*
@@ -115538,10 +115949,12 @@
115949 }else{
115950 VdbeComment((v, "RHS of IN operator"));
115951 }
115952 #endif
115953 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
115954 assert( pKeyInfo!=0 || pParse->nErr );
115955 if( pKeyInfo==0 ) return;
115956
115957 if( ExprUseXSelect(pExpr) ){
115958 /* Case 1: expr IN (SELECT ...)
115959 **
115960 ** Generate code to write the results of the select into the temporary
@@ -115562,21 +115975,35 @@
115975 int rc;
115976 int addrBloom = 0;
115977 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
115978 dest.zAffSdst = exprINAffinity(pParse, pExpr);
115979 pSelect->iLimit = 0;
115980 assert( pEList!=0 );
115981 assert( pEList->nExpr>0 );
115982 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
115983 for(i=0; i<nVal; i++){
115984 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
115985 CollSeq *pColl;
115986 pKeyInfo->aColl[i] = pColl = sqlite3BinaryCompareCollSeq(
115987 pParse, p, pEList->a[i].pExpr
115988 );
115989 if( !sqlite3IsBinary(pColl) ){
115990 allowBloom = 0; /* tag-202607231411 */
115991 }
115992 }
115993 if( addrOnce
115994 && allowBloom
115995 && OptimizationEnabled(pParse->db, SQLITE_BloomFilter)
115996 ){
115997 int regBloom = ++pParse->nMem;
115998 addrBloom = sqlite3VdbeAddOp2(v, OP_Blob, 10000, regBloom);
115999 VdbeComment((v, "Bloom filter"));
116000 dest.iSDParm2 = regBloom;
116001 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
116002 pKeyInfo = 0;
116003 }
116004 testcase( pSelect->selFlags & SF_Distinct );
 
116005 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
116006 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
116007 sqlite3SelectDelete(pParse->db, pCopy);
116008 sqlite3DbFree(pParse->db, dest.zAffSdst);
116009 if( addrBloom ){
@@ -115590,20 +116017,10 @@
116017 }
116018 if( rc ){
116019 sqlite3KeyInfoUnref(pKeyInfo);
116020 return;
116021 }
 
 
 
 
 
 
 
 
 
 
116022 }
116023 }else if( ALWAYS(pExpr->x.pList!=0) ){
116024 /* Case 2: expr IN (exprlist)
116025 **
116026 ** For each expression, build an index key from the evaluation and
@@ -115620,14 +116037,13 @@
116037 if( affinity<=SQLITE_AFF_NONE ){
116038 affinity = SQLITE_AFF_BLOB;
116039 }else if( affinity==SQLITE_AFF_REAL ){
116040 affinity = SQLITE_AFF_NUMERIC;
116041 }
116042 assert( pKeyInfo!=0 );
116043 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
116044 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
 
116045
116046 /* Loop through each expression in <exprlist>. */
116047 r1 = sqlite3GetTempReg(pParse);
116048 r2 = sqlite3GetTempReg(pParse);
116049 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
@@ -116580,11 +116996,11 @@
116996 if( pExpr->op!=TK_FUNCTION ){
116997 return WRC_Prune;
116998 }
116999 assert( ExprUseXList(pExpr) );
117000 db = pWalker->pParse->db;
117001 n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
117002 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
117003 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
117004 pWalker->eCode = 1;
117005 return WRC_Abort;
117006 }
@@ -117229,11 +117645,16 @@
117645 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
117646 if( pDef==0 && pParse->explain ){
117647 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
117648 }
117649 #endif
117650 if( pDef==0
117651 || pDef->xFinalize!=0
117652 || ((pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 &&
117653 !pParse->nested &&
117654 (db->mDbFlags & DBFLAG_InternalFunc)==0)
117655 ){
117656 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
117657 break;
117658 }
117659 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
117660 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
@@ -121984,19 +122405,41 @@
122405
122406
122407 /*
122408 ** Argument z points into the body of a constraint - specifically the
122409 ** second token of the constraint definition. For a named constraint,
122410 ** z points to the second token of the constraint definition. For an
122411 ** unnamed NOT NULL constraint, z points to the first byte past the NOT
122412 ** keyword.
122413 **
122414 ** Argument eTok may be the token value of the first token of the constraint
122415 ** (e.g. TK_CHECK or TK_REFERENCES) or zero. If it is either TK_REFERENCES
122416 ** or TK_FOREIGN, special parsing is enabled to find the end of the foreign-key
122417 ** constraint definition.
122418 **
122419 ** Return the number of bytes until the end of the constraint.
122420 */
122421 static int getConstraint(const u8 *z, int eTok){
122422 int iOff = 0;
122423 int t = 0;
122424
122425 #ifndef SQLITE_OMIT_FOREIGN_KEY
122426 if( eTok==TK_FOREIGN ){
122427 /* For a FOREIGN KEY constraint, use getConstraint() to parse everything
122428 ** up to the REFERENCES keyword. Then getConstraintToken() to consume
122429 ** the TK_REFERENCES token itself. Then fall through to the special
122430 ** handling for TK_REFERENCES below. */
122431 iOff = getConstraint(z, 0);
122432 iOff += getConstraintToken(&z[iOff], &eTok);
122433 }
122434
122435 if( eTok==TK_REFERENCES ){
122436 /* REFERENCES is followed by a table name. Gobble this up here in
122437 ** case the table name is a fallback token like TK_GENERATED. */
122438 iOff += getConstraintToken(&z[iOff], &t);
122439 }
122440 #endif
122441
122442 /* Now, the current constraint proceeds until the next occurence of one
122443 ** of the following tokens:
122444 **
122445 ** CONSTRAINT, PRIMARY, NOT, UNIQUE, CHECK, DEFAULT,
@@ -122165,24 +122608,24 @@
122608 || t==TK_COMMA || t==TK_RP || t==TK_GENERATED || t==TK_AS
122609 ){
122610 t = TK_CHECK;
122611 }else{
122612 iOff += nTok;
122613 iOff += getConstraint(&zSql[iOff], t);
122614 }
122615
122616 if( cmp==0 || (iNotNull>=0 && t==TK_NOT) ){
122617 if( t!=TK_NOT && t!=TK_CHECK && t!=TK_REFERENCES && t!=TK_FOREIGN ){
122618 errorMPrintf(ctx, "constraint may not be dropped: %s", zCons);
122619 return;
122620 }
122621 iEnd = iOff;
122622 break;
122623 }
122624
122625 }else if( t==TK_NOT && iNotNull==ii ){
122626 iEnd = iOff + getConstraint(&zSql[iOff], 0);
122627 break;
122628 }else if( t==TK_RP || t==TK_ILLEGAL ){
122629 iEnd = -1;
122630 break;
122631 }else if( t==TK_COMMA ){
@@ -122236,13 +122679,12 @@
122679 const u8 *zSql = sqlite3_value_text(argv[0]);
122680 const char *zCons = (const char*)sqlite3_value_text(argv[1]);
122681 int iCol = sqlite3_value_int(argv[2]);
122682 int iOff = 0;
122683 int ii;
122684 sqlite3_str *pNew;
122685 int t = 0;
 
122686 UNUSED_PARAMETER(NotUsed);
122687
122688 if( skipCreateTable(ctx, zSql, &iOff) ) return;
122689
122690 for(ii=0; ii<=iCol || (iCol<0 && t!=TK_RP); ii++){
@@ -122258,17 +122700,15 @@
122700 }
122701 }
122702
122703 iOff += getWhitespace(&zSql[iOff]);
122704
122705 pNew = sqlite3_str_new(sqlite3_context_db_handle(ctx));
122706 sqlite3_str_append(pNew, (const char*)zSql, iOff);
122707 if( iCol<0 ) sqlite3_str_append(pNew, ",", 1);
122708 sqlite3_str_appendf(pNew, " %s%s", zCons, &zSql[iOff]);
122709 sqlite3_result_str(ctx, pNew, SQLITE_FINISH);
 
 
122710 }
122711
122712 /*
122713 ** Find a column named pCol in table pTab. If successful, set output
122714 ** parameter *piCol to the index of the column in the table and return
@@ -123524,11 +123964,11 @@
123964 sqlite3_str_appendf(&sStat, " %llu", iVal);
123965 #ifdef SQLITE_ENABLE_STAT4
123966 assert( p->current.anEq[i] || p->nRow==0 );
123967 #endif
123968 }
123969 sqlite3_result_str(context, &sStat, SQLITE_XFER);
123970 }
123971 #ifdef SQLITE_ENABLE_STAT4
123972 else if( eCall==STAT_GET_ROWID ){
123973 if( p->iGet<0 ){
123974 samplePushPrevious(p, 0);
@@ -123561,11 +124001,11 @@
124001 sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
124002 for(i=0; i<p->nCol; i++){
124003 sqlite3_str_appendf(&sStat, "%llu ", (u64)aCnt[i]);
124004 }
124005 if( sStat.nChar ) sStat.nChar--;
124006 sqlite3_result_str(context, &sStat, SQLITE_XFER);
124007 }
124008 #endif /* SQLITE_ENABLE_STAT4 */
124009 #ifndef SQLITE_DEBUG
124010 UNUSED_PARAMETER( argc );
124011 #endif
@@ -125649,10 +126089,11 @@
126089 }
126090 }
126091
126092 assert( pToplevel->nTableLock < 0x7fff0000 );
126093 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
126094 if( pToplevel->nTableLock==0 ) pToplevel->aTableLock = 0;
126095 pToplevel->aTableLock =
126096 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
126097 if( pToplevel->aTableLock ){
126098 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
126099 p->iDb = iDb;
@@ -125815,11 +126256,11 @@
126256 if( pParse->nTableLock ) codeTableLocks(pParse);
126257 #endif
126258
126259 /* Initialize any AUTOINCREMENT data structures required.
126260 */
126261 if( pParse->usesAinc ) sqlite3AutoincrementBegin(pParse);
126262
126263 /* Code constant expressions that were factored out of inner loops.
126264 */
126265 if( pParse->pConstExpr ){
126266 ExprList *pEL = pParse->pConstExpr;
@@ -125848,11 +126289,11 @@
126289 assert( v!=0 || pParse->nErr );
126290 assert( db->mallocFailed==0 || pParse->nErr );
126291 if( pParse->nErr==0 ){
126292 /* A minimum of one cursor is required if autoincrement is used
126293 * See ticket [a696379c1f08866] */
126294 assert( pParse->usesAinc==0 || pParse->nTab>0 );
126295 sqlite3VdbeMakeReady(v, pParse);
126296 pParse->rc = SQLITE_DONE;
126297 }else{
126298 pParse->rc = SQLITE_ERROR;
126299 }
@@ -127812,10 +128253,27 @@
128253 pIdx->aSortOrder = (u8*)zExtra;
128254 pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */
128255 pIdx->isResized = 1;
128256 return SQLITE_OK;
128257 }
128258
128259 /*
128260 ** Return true if the index pIdx can support a Bloom filter on its
128261 ** first N columns. Specifically, return true if all of the first N
128262 ** columns have the BINARY collating sequence or no collating sequence
128263 ** at all, and return false if there are any non-BINARY collating
128264 ** seqeuences on any of the first N columns. tag-202607231411
128265 */
128266 SQLITE_PRIVATE int sqlite3IndexBloomable(const Index *pIdx, int N){
128267 int i;
128268 assert( pIdx!=0 );
128269 assert( N <= pIdx->nColumn );
128270 for(i=0; i<N; i++){
128271 if( sqlite3StrICmp(pIdx->azColl[i],"BINARY")!=0 ) return 0;
128272 }
128273 return 1;
128274 }
128275
128276 /*
128277 ** Estimate the total row width for a table.
128278 */
128279 static void estimateTableWidth(Table *pTab){
@@ -128164,18 +128622,15 @@
128622
128623 #ifndef SQLITE_OMIT_VIRTUALTABLE
128624 /*
128625 ** Return true if zName is a shadow table name in the current database
128626 ** connection.
 
 
 
128627 */
128628 SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
128629 const char *zTail; /* Pointer to the last "_" in zName */
128630 Table *pTab; /* Table that zName is a shadow of */
128631 char *zCopy; /* Transient copy of zName after last "_" */
128632 zTail = strrchr(zName, '_');
128633 if( zTail==0 ) return 0;
128634 zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
128635 pTab = zCopy ? sqlite3FindTable(db, zCopy, 0) : 0;
128636 sqlite3DbFree(db, zCopy);
@@ -129683,12 +130138,13 @@
130138 }
130139 }
130140 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
130141 if( !ifNotExist ){
130142 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
130143 }else if( db->init.busy ){
130144 sqlite3ErrorMsg(pParse,""); /* corruptSchema() will do the error */
130145 }else{
 
130146 sqlite3CodeVerifySchema(pParse, iDb);
130147 sqlite3ForceNotReadOnly(pParse);
130148 }
130149 goto exit_create_index;
130150 }
@@ -133318,32 +133774,20 @@
133774 sqlite3_value **argv
133775 ){
133776 PrintfArguments x;
133777 StrAccum str;
133778 const char *zFormat;
 
133779 sqlite3 *db = sqlite3_context_db_handle(context);
133780
133781 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
133782 x.nArg = argc-1;
133783 x.nUsed = 0;
133784 x.apArg = argv+1;
133785 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
133786 str.printfFlags = SQLITE_PRINTF_SQLFUNC;
133787 sqlite3_str_appendf(&str, zFormat, &x);
133788 sqlite3_result_str(context, &str, SQLITE_XFER);
 
 
 
 
 
 
 
 
 
 
 
133789 }
133790 }
133791
133792 /*
133793 ** Implementation of the substr() function.
@@ -134286,16 +134730,11 @@
134730 sqlite3 *db = sqlite3_context_db_handle(context);
134731 assert( argc==1 );
134732 UNUSED_PARAMETER(argc);
134733 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
134734 sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context)));
134735 sqlite3_result_str(context, &str, SQLITE_XFER);
 
 
 
 
 
134736 }
134737
134738 /*
134739 ** The unicode() function. Return the integer unicode code-point value
134740 ** for the first character of the input string.
@@ -135324,32 +135763,22 @@
135763 #endif /* SQLITE_OMIT_WINDOWFUNC */
135764 static void groupConcatFinalize(sqlite3_context *context){
135765 GroupConcatCtx *pGCC
135766 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
135767 if( pGCC ){
135768 sqlite3_result_str(context, &pGCC->str, SQLITE_XFER);
135769 #ifndef SQLITE_OMIT_WINDOWFUNC
135770 sqlite3_free(pGCC->pnSepLengths);
135771 #endif
135772 }
135773 }
135774 #ifndef SQLITE_OMIT_WINDOWFUNC
135775 static void groupConcatValue(sqlite3_context *context){
135776 GroupConcatCtx *pGCC
135777 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
135778 if( pGCC && pGCC->nAccum>0 ){
135779 sqlite3_result_str(context, &pGCC->str, SQLITE_COPY);
 
 
 
 
 
 
 
 
 
 
135780 }
135781 }
135782 #else
135783 # define groupConcatValue 0
135784 #endif /* SQLITE_OMIT_WINDOWFUNC */
@@ -135976,17 +136405,21 @@
136405 static void percentSort(
136406 double *a, /* Array to sort */
136407 unsigned int n, /* Number of elements in array a[] */
136408 int iReq /* Element caller cares about (or -ve) */
136409 ){
136410 int iLt; /* Entries before a[iLt] are less than or equal to rPivot */
136411 int iGt; /* Entries a[iGt] and after are greater or equal to rPivot */
136412 int i; /* Loop counter */
136413 double rPivot; /* The pivot value */
136414
136415 assert( n>=2 );
136416 do{
136417 /* Put the first, middle, and last elements in sorted order.
136418 ** After doing so, return immediately if the array contains
136419 ** three or fewer elements as there is nothing more to do.
136420 */
136421 if( a[0]>a[n-1] ){
136422 SWAP_DOUBLE(a[0],a[n-1])
136423 }
136424 if( n==2 ) return;
136425 iGt = n-1;
@@ -135995,10 +136428,15 @@
136428 SWAP_DOUBLE(a[0],a[i])
136429 }else if( a[i]>a[iGt] ){
136430 SWAP_DOUBLE(a[i],a[iGt])
136431 }
136432 if( n==3 ) return;
136433
136434 /* Take the value of the middle element as the pivot. Shuffle
136435 ** values around so that all elements less than the pivot come
136436 ** before all elements greater than the pivot.
136437 */
136438 rPivot = a[i];
136439 iLt = i = 1;
136440 do{
136441 if( a[i]<rPivot ){
136442 if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])
@@ -136012,12 +136450,16 @@
136450 }else{
136451 i++;
136452 }
136453 }while( i<iGt );
136454
136455 assert( iLt>0 && iLt<iGt && iGt<n );
136456 testcase( iGt>iLt+1 );
136457 assert( a[iLt]==rPivot );
136458 assert( a[iLt-1]<=rPivot );
136459 assert( a[iGt]>=rPivot );
136460 assert( a[iLt+1]>=rPivot );
136461
136462 if( iReq>=0 ){
136463 /* In this case, the only elements that the caller requires sorted into
136464 ** the correct positions are elements a[iReq] and a[iReq+1]. At this
136465 ** point we know that element a[iLt] is in the correct position and
@@ -136190,12 +136632,11 @@
136632 sqlite3_str_appendall(pStr, ",\"journal\":");
136633 rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr);
136634 if( rc ) sqlite3_str_append(pStr, "null", 4);
136635 }
136636 sqlite3_str_append(pStr, "}", 1);
136637 sqlite3_result_str(context, pStr, SQLITE_FINISH);
 
136638 }
136639 sqlite3BtreeLeave(pBtree);
136640 }else{
136641 sqlite3_result_text(context, "{}", 2, SQLITE_STATIC);
136642 }
@@ -136307,12 +136748,12 @@
136748 }else{
136749 sqlite3_str_appendf(pResult, ", NULL");
136750 }
136751 }
136752 }
 
136753 }
136754 sqlite3_result_str(ctx, pResult, SQLITE_FINISH);
136755 sqlite3_free_filename(zFile);
136756 sqlite3_free(zErr);
136757 }
136758 #endif /* SQLITE_DEBUG */
136759
@@ -136405,11 +136846,11 @@
136846 VFUNCTION(random, 0, 0, 0, randomFunc ),
136847 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
136848 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
136849 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
136850 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
136851 SFUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
136852 FUNCTION(unistr, 1, 0, 0, unistrFunc ),
136853 FUNCTION(quote, 1, 0, 0, quoteFunc ),
136854 FUNCTION(unistr_quote, 1, 1, 0, quoteFunc ),
136855 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
136856 VFUNCTION(changes, 0, 0, 0, changes ),
@@ -138454,19 +138895,23 @@
138895 pParse->nErr++;
138896 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
138897 return 0;
138898 }
138899
138900 if( pToplevel->usesAinc==0 ){
138901 pToplevel->pAinc = 0;
138902 }
138903 pInfo = pToplevel->pAinc;
138904 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
138905 if( pInfo==0 ){
138906 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
138907 sqlite3ParserAddCleanup(pToplevel, sqlite3DbFree, pInfo);
138908 testcase( pParse->earlyCleanup );
138909 if( pParse->db->mallocFailed ) return 0;
138910 pInfo->pNext = pToplevel->pAinc;
138911 pToplevel->pAinc = pInfo;
138912 pToplevel->usesAinc = 1;
138913 pInfo->pTab = pTab;
138914 pInfo->iDb = iDb;
138915 pToplevel->nMem++; /* Register to hold name of table */
138916 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
138917 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
@@ -138491,10 +138936,11 @@
138936 ** only called from the top-level */
138937 assert( pParse->pTriggerTab==0 );
138938 assert( sqlite3IsToplevel(pParse) );
138939
138940 assert( v ); /* We failed long ago if this is not so */
138941 assert( pParse->usesAinc );
138942 for(p = pParse->pAinc; p; p = p->pNext){
138943 static const int iLn = VDBE_OFFSET_LINENO(2);
138944 static const VdbeOpList autoInc[] = {
138945 /* 0 */ {OP_Null, 0, 0, 0},
138946 /* 1 */ {OP_Rewind, 0, 10, 0},
@@ -138558,10 +139004,11 @@
139004 AutoincInfo *p;
139005 Vdbe *v = pParse->pVdbe;
139006 sqlite3 *db = pParse->db;
139007
139008 assert( v );
139009 assert( pParse->usesAinc );
139010 for(p = pParse->pAinc; p; p = p->pNext){
139011 static const int iLn = VDBE_OFFSET_LINENO(2);
139012 static const VdbeOpList autoIncEnd[] = {
139013 /* 0 */ {OP_NotNull, 0, 2, 0},
139014 /* 1 */ {OP_NewRowid, 0, 0, 0},
@@ -138590,11 +139037,11 @@
139037 aOp[3].p5 = OPFLAG_APPEND;
139038 sqlite3ReleaseTempReg(pParse, iRec);
139039 }
139040 }
139041 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
139042 if( pParse->usesAinc ) autoIncrementEnd(pParse);
139043 }
139044 #else
139045 /*
139046 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
139047 ** above are all no-ops
@@ -140244,10 +140691,26 @@
140691 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
140692 regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
140693 }else{
140694 pTrigger = 0;
140695 regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
140696 }
140697 if( regTrigCnt ){
140698 /* At this point regTrigCnt is non-zero if there are DELETE triggers
140699 ** or FK triggers. But we only care about these things if there is
140700 ** a chance that a row will be deleted by an ON CONFLICT REPLACE
140701 ** constraint. So zero regTrigCnt if no such constraint can be found. */
140702 if( overrideError!=OE_Replace ){
140703 if( overrideError!=OE_Default ){
140704 regTrigCnt = 0;
140705 }else if( pkChng==0 || pPk || pTab->keyConf!=OE_Replace ){
140706 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
140707 if( pIdx->onError==OE_Replace ) break;
140708 }
140709 if( pIdx==0 ) regTrigCnt = 0;
140710 }
140711 }
140712 }
140713 if( regTrigCnt ){
140714 /* Replace triggers might exist. Allocate the counter and
140715 ** initialize it to zero. */
140716 regTrigCnt = ++pParse->nMem;
@@ -140296,13 +140759,17 @@
140759 ** the UNIQUE constraints have run.
140760 */
140761 if( onError==OE_Replace /* IPK rule is REPLACE */
140762 && onError!=overrideError /* Rules for other constraints are different */
140763 && pTab->pIndex /* There exist other constraints */
 
140764 ){
140765 if( upsertIpkDelay ){
140766 ipkTop = upsertIpkDelay + 1;
140767 upsertIpkDelay = 0;
140768 }else{
140769 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
140770 }
140771 VdbeComment((v, "defer IPK REPLACE until last"));
140772 }
140773
140774 if( isUpdate ){
140775 /* pkChng!=0 does not mean that the rowid has changed, only that
@@ -140392,15 +140859,15 @@
140859 sqlite3VdbeGoto(v, ignoreDest);
140860 break;
140861 }
140862 }
140863 sqlite3VdbeResolveLabel(v, addrRowidOk);
140864 if( ipkTop ){
 
 
140865 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
140866 sqlite3VdbeJumpHere(v, ipkTop-1);
140867 }else if( pUpsert && pUpsertClause!=pUpsert ){
140868 upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto);
140869 }
140870 }
140871
140872 /* Test all UNIQUE constraints by creating entries for each UNIQUE
140873 ** index and making sure that duplicate entries do not already exist.
@@ -140416,10 +140883,11 @@
140883 int regIdx; /* Range of registers holding content for pIdx */
140884 int regR; /* Range of registers holding conflicting PK */
140885 int iThisCur; /* Cursor for this UNIQUE index */
140886 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
140887 int addrConflictCk; /* First opcode in the conflict check logic */
140888 int nConflictCk; /* Number of opcodes in conflict check logic */
140889
140890 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
140891 if( pUpsert ){
140892 pUpsertClause = sqlite3UpsertOfIndex(pUpsert, pIdx);
140893 if( upsertIpkDelay && pUpsertClause==pUpsert ){
@@ -140591,10 +141059,15 @@
141059 VdbeCoverageIf(v, op==OP_Ne);
141060 }
141061 }
141062 }
141063 }
141064
141065 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
141066 assert( nConflictCk>0 || db->mallocFailed );
141067 testcase( nConflictCk<=0 );
141068 testcase( nConflictCk>1 );
141069
141070 /* Generate code that executes if the new index entry is not unique */
141071 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
141072 || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
141073 switch( onError ){
@@ -140617,17 +141090,11 @@
141090 testcase( onError==OE_Ignore );
141091 sqlite3VdbeGoto(v, ignoreDest);
141092 break;
141093 }
141094 default: {
 
 
141095 assert( onError==OE_Replace );
 
 
 
 
141096 if( regTrigCnt ){
141097 sqlite3MultiWrite(pParse);
141098 nReplaceTrig++;
141099 }
141100 if( pTrigger && isUpdate ){
@@ -140637,62 +141104,62 @@
141104 regR, nPkField, 0, OE_Replace,
141105 (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
141106 if( pTrigger && isUpdate ){
141107 sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
141108 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141109 seenReplace = 1;
141110 break;
141111 }
141112 }
141113 if( regTrigCnt ){
141114 int addrBypass; /* Jump destination to bypass recheck logic */
141115
141116 sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
141117 addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
141118 VdbeComment((v, "bypass recheck"));
141119
141120 /* Here we insert code that will be invoked after all constraint
141121 ** checks have run, if and only if one or more replace triggers
141122 ** fired. */
141123 sqlite3VdbeResolveLabel(v, lblRecheckOk);
141124 lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
141125 if( pIdx->pPartIdxWhere ){
141126 /* Bypass the recheck if this partial index is not defined
141127 ** for the current row */
141128 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
141129 VdbeCoverage(v);
141130 }
141131 /* Copy the constraint check code from above, except change
141132 ** the constraint-ok jump destination to be the address of
141133 ** the next retest block */
141134 while( nConflictCk>0 ){
141135 VdbeOp x; /* Conflict check opcode to copy */
141136 /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
141137 ** Hence, make a complete copy of the opcode, rather than using
141138 ** a pointer to the opcode. */
141139 x = *sqlite3VdbeGetOp(v, addrConflictCk);
141140 if( x.opcode!=OP_IdxRowid ){
141141 int p2; /* New P2 value for copied conflict check opcode */
141142 const char *zP4;
141143 if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
141144 p2 = lblRecheckOk;
141145 }else{
141146 p2 = x.p2;
141147 }
141148 zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
141149 sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
141150 sqlite3VdbeChangeP5(v, x.p5);
141151 VdbeCoverageIf(v, p2!=x.p2);
141152 }
141153 nConflictCk--;
141154 addrConflictCk++;
141155 }
141156 /* If the retest fails, issue an abort */
141157 sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
141158
141159 sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
141160 }
141161 sqlite3VdbeResolveLabel(v, addrUniqueOk);
141162 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
141163 if( pUpsertClause
141164 && upsertIpkReturn
141165 && sqlite3UpsertNextIsIPK(pUpsertClause)
@@ -140726,12 +141193,12 @@
141193 VdbeCoverage(v);
141194 sqlite3RowidConstraint(pParse, OE_Abort, pTab);
141195 }else{
141196 sqlite3VdbeGoto(v, addrRecheck);
141197 }
 
141198 }
141199 if( regTrigCnt ) sqlite3VdbeResolveLabel(v, lblRecheckOk);
141200
141201 /* Generate the table record */
141202 if( HasRowid(pTab) ){
141203 int regRec = aRegIdx[ix];
141204 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
@@ -142023,10 +142490,11 @@
142490 void (*str_free)(sqlite3_str*);
142491 int (*carray_bind)(sqlite3_stmt*,int,void*,int,int,void(*)(void*));
142492 int (*carray_bind_v2)(sqlite3_stmt*,int,void*,int,int,void(*)(void*),void*);
142493 /* Version 3.54.0 and later */
142494 sqlite3_int64 (*incomplete)(const char*);
142495 void (*result_str)(sqlite3_context*,sqlite3_str*,int);
142496 };
142497
142498 /*
142499 ** This is the function signature used for all extension entry points. It
142500 ** is also defined in the file "loadext.c".
@@ -142368,10 +142836,11 @@
142836 #define sqlite3_str_free sqlite3_api->str_free
142837 #define sqlite3_carray_bind sqlite3_api->carray_bind
142838 #define sqlite3_carray_bind_v2 sqlite3_api->carray_bind_v2
142839 /* Version 3.54.0 and later */
142840 #define sqlite3_incomplete sqlite3_api->incomplete
142841 #define sqlite3_result_str sqlite3_api->result_str
142842 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
142843
142844 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
142845 /* This case when the file really is being compiled as a loadable
142846 ** extension */
@@ -142905,11 +143374,13 @@
143374 sqlite3_carray_bind_v2,
143375 #else
143376 0,
143377 0,
143378 #endif
143379 /* Version 3.54.0 and later */
143380 sqlite3_incomplete,
143381 sqlite3_result_str
143382 };
143383
143384 /* True if x is the directory separator character
143385 */
143386 #if SQLITE_OS_WIN
@@ -147203,10 +147674,11 @@
147674 corruptSchema(pData, argv, 0);
147675 return 1;
147676 }
147677
147678 assert( iDb>=0 && iDb<db->nDb );
147679 assert( db->aDb[iDb].pSchema!=0 );
147680 if( argv[3]==0 ){
147681 corruptSchema(pData, argv, 0);
147682 }else if( argv[4]
147683 && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
147684 && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
@@ -147277,10 +147749,20 @@
147749 ){
147750 if( sqlite3Config.bExtraSchemaChecks ){
147751 corruptSchema(pData, argv, "invalid rootpage");
147752 }
147753 }
147754 }
147755 if( pData->pzErrMsg[0]==0 ){
147756 Schema *pX = db->aDb[iDb].pSchema;
147757 if( pX->tblHash.count + pX->idxHash.count + pX->trigHash.count
147758 > (u32)db->aLimit[SQLITE_LIMIT_SCHEMA]
147759 ){
147760 *pData->pzErrMsg = sqlite3MPrintf(db, "too many schema objects");
147761 pData->rc = SQLITE_ERROR;
147762 return 1;
147763 }
147764 }
147765 return 0;
147766 }
147767
147768 /*
@@ -147674,11 +148156,11 @@
148156 sqlite3 *db = pParse->db;
148157 assert( db!=0 );
148158 assert( db->pParse==pParse );
148159 assert( pParse->nested==0 );
148160 #ifndef SQLITE_OMIT_SHARED_CACHE
148161 if( pParse->nTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
148162 #endif
148163 while( pParse->pCleanup ){
148164 ParseCleanup *pCleanup = pParse->pCleanup;
148165 pParse->pCleanup = pCleanup->pNext;
148166 pCleanup->xCleanup(db, pCleanup->pPtr);
@@ -147758,10 +148240,11 @@
148240 **
148241 ** Caution: Do not confuse this routine with sqlite3ParseObjectInit() which
148242 ** is generated by Lemon.
148243 */
148244 SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
148245 assert( db!=0 );
148246 memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
148247 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
148248 assert( db->pParse!=pParse );
148249 pParse->pOuterParse = db->pParse;
148250 db->pParse = pParse;
@@ -148157,11 +148640,11 @@
148640 int nBytes, /* Length of zSql in bytes. */
148641 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148642 const void **pzTail /* OUT: End of parsed string */
148643 ){
148644 int rc;
148645 rc = sqlite3Prepare16(db,zSql,nBytes&~1,0,ppStmt,pzTail);
148646 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148647 return rc;
148648 }
148649 SQLITE_API int sqlite3_prepare16_v2(
148650 sqlite3 *db, /* Database handle. */
@@ -148169,11 +148652,11 @@
148652 int nBytes, /* Length of zSql in bytes. */
148653 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148654 const void **pzTail /* OUT: End of parsed string */
148655 ){
148656 int rc;
148657 rc = sqlite3Prepare16(db,zSql,nBytes&~1,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
148658 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148659 return rc;
148660 }
148661 SQLITE_API int sqlite3_prepare16_v3(
148662 sqlite3 *db, /* Database handle. */
@@ -148182,11 +148665,11 @@
148665 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
148666 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
148667 const void **pzTail /* OUT: End of parsed string */
148668 ){
148669 int rc;
148670 rc = sqlite3Prepare16(db,zSql,nBytes&~1,
148671 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
148672 ppStmt,pzTail);
148673 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
148674 return rc;
148675 }
@@ -148855,11 +149338,11 @@
149338 pRight->u3.pOn = 0;
149339 pRight->fg.isOn = 1;
149340 p->selFlags |= SF_OnToWhere;
149341 }
149342
149343 if( pRight->fg.isTabFunc && joinType==EP_OuterON && pRight->u1.pFuncArg ){
149344 p->selFlags |= SF_OnToWhere;
149345 }
149346 }
149347 return 0;
149348 }
@@ -149321,10 +149804,52 @@
149804 }
149805 pSort->nDefer = (u8)nDefer;
149806 *ppExtra = pExtra;
149807 }
149808 #endif
149809
149810 #ifdef SQLITE_DEBUG
149811 /*
149812 ** This is a byte-code validation check that only runs when SQLITE_DEBUG
149813 ** is defined. This routine looks backwards through the bytecode
149814 ** for the definition of cursor with index iCur. It extracts the KeyInfo from
149815 ** that cursor (it must be an index cursor) and verifies that the cursor
149816 ** does not use any collating seqeuences other than BINARY for its first
149817 ** nCol columns.
149818 **
149819 ** This routine is used inside of an assert(). So it should return true
149820 ** on success and false if the invariant is not satisfied.
149821 **
149822 ** tag-202607231411
149823 */
149824 static int sqlite3CursorBloomable(Parse *pParse, int iCur, int nCol){
149825 int i,k;
149826 Vdbe *v = pParse->pVdbe;
149827 if( pParse->nErr ) return 1;
149828 assert( v );
149829 for(k=sqlite3VdbeCurrentAddr(v)-1; k>0; k--){
149830 const VdbeOp *pOp = sqlite3VdbeGetOp(v, k);
149831 const KeyInfo *pKeyInfo;
149832 if( pOp->p1!=iCur ) continue;
149833 if( pOp->opcode!=OP_OpenRead
149834 && pOp->opcode!=OP_OpenWrite
149835 && pOp->opcode!=OP_OpenEphemeral
149836 ){
149837 continue;
149838 }
149839 assert( pOp->p4type==P4_KEYINFO );
149840 pKeyInfo = (const KeyInfo*)pOp->p4.pKeyInfo;
149841 assert( pKeyInfo!=0 );
149842 for(i=0; i<nCol; i++){
149843 assert( sqlite3IsBinary(pKeyInfo->aColl[i]) );
149844 }
149845 return 1;
149846 }
149847 return 0;
149848 }
149849 #endif /* SQLITE_DEBUG */
149850
149851
149852 /*
149853 ** This routine generates the code for the inside of the inner loop
149854 ** of a SELECT.
149855 **
@@ -149592,10 +150117,11 @@
150117 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
150118 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
150119 r1, pDest->zAffSdst, nResultCol);
150120 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
150121 if( pDest->iSDParm2 ){
150122 assert( sqlite3CursorBloomable(pParse,iParm,nResultCol) );
150123 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
150124 regResult, nResultCol);
150125 ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
150126 }
150127 sqlite3ReleaseTempReg(pParse, r1);
@@ -151401,10 +151927,11 @@
151927 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
151928 r1, pDest->zAffSdst, pIn->nSdst);
151929 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
151930 pIn->iSdst, pIn->nSdst);
151931 if( pDest->iSDParm2>0 ){
151932 assert( sqlite3CursorBloomable(pParse, pDest->iSDParm, pIn->nSdst) );
151933 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
151934 pIn->iSdst, pIn->nSdst);
151935 ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
151936 }
151937 sqlite3ReleaseTempReg(pParse, r1);
@@ -155350,11 +155877,12 @@
155877 assert( ExprUseXList(pExpr) );
155878 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
155879 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
155880 if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
155881 pFrom = p->pSrc->a;
155882 if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */
155883 if( (p->selFlags & SF_Correlated)!=0 ) return 0; /* Not a correlated subq */
155884 pSub = pFrom->u4.pSubq->pSelect;
155885 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
155886 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
155887 do{
155888 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
@@ -157581,12 +158109,13 @@
158109 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
158110 if( !IN_RENAME_OBJECT ){
158111 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
158112 if( !noErr ){
158113 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
158114 }else if( db->init.busy ){
158115 sqlite3ErrorMsg(pParse,""); /* Err msg generated by corruptSchema() */
158116 }else{
 
158117 sqlite3CodeVerifySchema(pParse, iDb);
158118 VVA_ONLY( pParse->ifNotExists = 1; )
158119 }
158120 goto trigger_cleanup;
158121 }
@@ -161225,10 +161754,11 @@
161754 SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){
161755 HashElem *pThis, *pNext;
161756 #ifdef SQLITE_ENABLE_API_ARMOR
161757 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
161758 #endif
161759 sqlite3_mutex_enter(db->mutex);
161760 for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
161761 Module *pMod = (Module*)sqliteHashData(pThis);
161762 pNext = sqliteHashNext(pThis);
161763 if( azNames ){
161764 int ii;
@@ -161235,10 +161765,11 @@
161765 for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
161766 if( azNames[ii]!=0 ) continue;
161767 }
161768 createModule(db, pMod->zName, 0, 0, 0);
161769 }
161770 sqlite3_mutex_leave(db->mutex);
161771 return SQLITE_OK;
161772 }
161773
161774 /*
161775 ** Decrement the reference count on a Module object. Destroy the
@@ -161803,10 +162334,12 @@
162334 char *zErr = 0;
162335 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
162336 if( rc!=SQLITE_OK ){
162337 sqlite3ErrorMsg(pParse, "%s", zErr);
162338 pParse->rc = rc;
162339 }else{
162340 sqlite3MarkAllShadowTablesOf(db, pTab);
162341 }
162342 sqlite3DbFree(db, zErr);
162343 }
162344
162345 return rc;
@@ -163082,14 +163615,11 @@
163615 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
163616 SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
163617 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
163618 SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
163619 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*);
163620 SQLITE_PRIVATE int sqlite3WhereLoopBloomable(const WhereLoop*);
 
 
 
163621
163622 /*
163623 ** Bitmasks for the operators on WhereTerm objects. These are all
163624 ** operators that are of interest to the query planner. An
163625 ** OR-ed combination of these values can be used when searching for
@@ -164554,10 +165084,11 @@
165084 testcase( pTerm->wtFlags & TERM_VIRTUAL );
165085 regRowid = sqlite3GetTempReg(pParse);
165086 regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
165087 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
165088 VdbeCoverage(pParse->pVdbe);
165089 assert( sqlite3WhereLoopBloomable(pLoop) );
165090 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
165091 addrNxt, regRowid, 1);
165092 VdbeCoverage(pParse->pVdbe);
165093 }else{
165094 u16 nEq = pLoop->u.btree.nEq;
@@ -164567,10 +165098,11 @@
165098 assert( pLoop->wsFlags & WHERE_INDEXED );
165099 assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
165100 r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
165101 codeApplyAffinity(pParse, r1, nEq, zStartAff);
165102 sqlite3DbFree(pParse->db, zStartAff);
165103 assert( sqlite3WhereLoopBloomable(pLoop) );
165104 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
165105 addrNxt, r1, nEq);
165106 VdbeCoverage(pParse->pVdbe);
165107 }
165108 pLevel->regFilter = 0;
@@ -165170,10 +165702,11 @@
165702 if( regBignull ){
165703 sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
165704 VdbeComment((v, "NULL-scan pass ctr"));
165705 }
165706 if( pLevel->regFilter ){
165707 assert( sqlite3WhereLoopBloomable(pLoop) );
165708 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
165709 regBase, nEq);
165710 VdbeCoverage(v);
165711 filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
165712 }
@@ -165907,12 +166440,14 @@
166440 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
166441 VdbeCoverage(v);
166442 VdbeComment((v, "match against %s", pTab->zName));
166443 sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r);
166444 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
166445 if( pRJ->regBloom ){
166446 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
166447 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
166448 }
166449 sqlite3VdbeJumpHere(v, jmp1);
166450 sqlite3ReleaseTempRange(pParse, r, nPk+1);
166451 }
166452
166453 /* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -166060,11 +166595,11 @@
166595 WHERE_RIGHT_JOIN, 0);
166596 if( pSubWInfo ){
166597 int iCur = pLevel->iTabCur;
166598 int r = ++pParse->nMem;
166599 int nPk;
166600 int jmp = 0;
166601 int addrCont = sqlite3WhereContinueLabel(pSubWInfo);
166602 Table *pTab = pTabItem->pSTab;
166603 if( HasRowid(pTab) ){
166604 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
166605 nPk = 1;
@@ -166076,15 +166611,17 @@
166611 for(iPk=0; iPk<nPk; iPk++){
166612 int iCol = pPk->aiColumn[iPk];
166613 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
166614 }
166615 }
166616 if( pRJ->regBloom ){
166617 jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
166618 VdbeCoverage(v);
166619 }
166620 sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
166621 VdbeCoverage(v);
166622 if( jmp ) sqlite3VdbeJumpHere(v, jmp);
166623 sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
166624 sqlite3WhereEnd(pSubWInfo);
166625 }
166626 sqlite3ExprDelete(pParse->db, pSubWhere);
166627 ExplainQueryPlanPop(pParse);
@@ -167001,33 +167538,62 @@
167538 }
167539 }
167540 }
167541 }
167542
167543 /* At this point, okToChngToIN is true if original pTerm is a
167544 ** candidate to satisfy case 1, though we are not yet certain that
167545 ** the collating sequences are all compatible. Try to construct a
167546 ** new virtual term that is pTerm converted from an OR operator
167547 ** into an IN operator.
167548 **
167549 ** During construction, verify that the collating sequences on all
167550 ** subterms of the OR are compatible. Omit the construction of the
167551 ** new IN operator if there are any collating sequence mismatches.
167552 */
167553 if( okToChngToIN ){
167554 Expr *pDup; /* A transient duplicate expression */
167555 ExprList *pList = 0; /* The RHS of the IN operator */
167556 Expr *pLeft = 0; /* The LHS of the IN operator */
167557 CollSeq *pCollSeq = 0; /* Collating sequence to use */
167558 Expr *pNew; /* The complete IN operator */
167559
167560 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
167561 Expr *pThis;
167562 if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
167563 assert( pOrTerm->eOperator & WO_EQ );
167564 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
167565 assert( pOrTerm->leftCursor==iCursor );
167566 assert( pOrTerm->u.x.leftColumn==iColumn );
167567 pThis = pOrTerm->pExpr;
167568 pDup = sqlite3ExprDup(db, pThis->pRight, 0);
167569 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
167570 if( pLeft==0 ){
167571 pLeft = pThis->pLeft;
167572 pCollSeq = sqlite3ExprCompareCollSeq(pParse, pThis);
167573 }else{
167574 assert( 0==sqlite3ExprCompare(pParse,
167575 sqlite3ExprSkipCollate(pThis->pLeft),
167576 sqlite3ExprSkipCollate(pLeft), -1) );
167577 if( pCollSeq!=sqlite3ExprCompareCollSeq(pParse, pThis) ){
167578 pLeft = 0; /* Collating sequence mismatch */
167579 break;
167580 }
167581 }
167582 }
167583 if( pLeft==0 ){
167584 pNew = 0; /* Collating sequence mismatch */
167585 }else{
167586 pDup = sqlite3ExprDup(db, pLeft, 0);
167587 if( sqlite3ExprCollSeq(pParse, pDup)!=pCollSeq
167588 && ALWAYS(pCollSeq!=0)
167589 ){
167590 assert( pCollSeq->zName!=0 );
167591 pDup = sqlite3ExprAddCollateString(pParse, pDup, pCollSeq->zName);
167592 }
167593 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
167594 }
167595 if( pNew ){
167596 int idxNew;
167597 transferJoinMarkings(pNew, pExpr);
167598 assert( ExprUseXList(pNew) );
167599 pNew->x.pList = pList;
@@ -168006,10 +168572,14 @@
168572 Expr *pColRef;
168573 Expr *pTerm;
168574 if( pItem->fg.isTabFunc==0 ) return;
168575 pTab = pItem->pSTab;
168576 assert( pTab!=0 );
168577 if( !IsVirtual(pTab) ){
168578 sqlite3ErrorMsg(pParse, "'%s' is not a function", pItem->zName);
168579 return;
168580 }
168581 pArgs = pItem->u1.pFuncArg;
168582 if( pArgs==0 ) return;
168583 for(j=k=0; j<pArgs->nExpr; j++){
168584 Expr *pRhs;
168585 u32 joinType;
@@ -168039,10 +168609,20 @@
168609 }
168610 sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
168611 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
168612 }
168613 }
168614
168615 /*
168616 ** Return true if the WhereLoop pLoop can be use a Bloom filter.
168617 ** tag-202607231411
168618 */
168619 SQLITE_PRIVATE int sqlite3WhereLoopBloomable(const WhereLoop *pLoop){
168620 if( pLoop->wsFlags & WHERE_IPK ) return 1;
168621 if( NEVER((pLoop->wsFlags & WHERE_INDEXED)==0) ) return 0;
168622 return sqlite3IndexBloomable(pLoop->u.btree.pIndex, pLoop->u.btree.nEq);
168623 }
168624
168625 /************** End of whereexpr.c *******************************************/
168626 /************** Begin file where.c *******************************************/
168627 /*
168628 ** 2001 September 15
@@ -169051,11 +169631,11 @@
169631 WhereLoop *pLoop; /* The Loop object */
169632 char *zNotUsed; /* Extra space on the end of pIdx */
169633 Bitmask idxCols; /* Bitmap of columns used for indexing */
169634 Bitmask extraCols; /* Bitmap of additional columns */
169635 u8 sentWarning = 0; /* True if a warning has been issued */
169636 u8 useBloomFilter = 1; /* True to also add a Bloom filter */
169637 Expr *pPartial = 0; /* Partial Index Expression */
169638 int iContinue = 0; /* Jump here to skip excluded rows */
169639 SrcList *pTabList; /* The complete FROM clause */
169640 SrcItem *pSrc; /* The FROM clause term to get the next index */
169641 int addrCounter = 0; /* Address where integer counter is initialized */
@@ -169178,22 +169758,17 @@
169758 Expr *pX = pTerm->pExpr;
169759 idxCols |= cMask;
169760 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
169761 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
169762 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
169763 if( !sqlite3IsBinary(pColl) ){
169764 /* Disallow the use of a Bloom filter if any non-BINARY collating
169765 ** sequence is involved. tag-202607231411 */
169766 useBloomFilter = 0;
169767 }
169768 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
169769 n++;
 
 
 
 
 
 
 
 
 
 
169770 }
169771 }
169772 }
169773 assert( (u32)n==pLoop->u.btree.nEq );
169774
@@ -169259,10 +169834,11 @@
169834 regRecord = sqlite3GetTempReg(pParse);
169835 regBase = sqlite3GenerateIndexKey(
169836 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
169837 );
169838 if( pLevel->regFilter ){
169839 assert( sqlite3WhereLoopBloomable(pLoop) );
169840 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
169841 regBase, pLoop->u.btree.nEq);
169842 }
169843 sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
169844 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
@@ -169374,10 +169950,11 @@
169950 if( sz<10000 ){
169951 sz = 10000;
169952 }else if( sz>10000000 ){
169953 sz = 10000000;
169954 }
169955 assert( sqlite3WhereLoopBloomable(pLoop) );
169956 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
169957
169958 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
169959 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
169960 for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
@@ -169396,10 +169973,11 @@
169973 }else{
169974 Index *pIdx = pLoop->u.btree.pIndex;
169975 int n = pLoop->u.btree.nEq;
169976 int r1 = sqlite3GetTempRange(pParse, n);
169977 int jj;
169978 assert( pIdx!=0 );
169979 for(jj=0; jj<n; jj++){
169980 assert( pIdx->pTable==pItem->pSTab );
169981 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
169982 }
169983 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
@@ -173052,11 +173630,11 @@
173630 }
173631 #ifndef SQLITE_OMIT_VIRTUALTABLE
173632 if( IsVirtual(pItem->pSTab) ){
173633 SrcItem *p;
173634 for(p=&pItem[1]; p<pEnd; p++){
173635 if( (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
173636 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
173637 }
173638 }
173639 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
173640 }else
@@ -174682,23 +175260,21 @@
175260 Table *pTab = pItem->pSTab;
175261 if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
175262 pTab->tabFlags |= TF_MaybeReanalyze;
175263 if( i>=1
175264 && (pLoop->wsFlags & reqFlags)==reqFlags
175265 && sqlite3WhereLoopBloomable(pLoop)
175266 && nSearch > pTab->nRowLogEst
175267 ){
175268 testcase( pItem->fg.jointype & JT_LEFT );
175269 pLoop->wsFlags |= WHERE_BLOOMFILTER;
175270 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
175271 WHERETRACE(0xffffffff, (
175272 "-> use Bloom-filter on loop %c because there are ~%.1e "
175273 "lookups into %s which has only ~%.1e rows\n",
175274 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
175275 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
 
 
175276 }
175277 nSearch += pLoop->nOut;
175278 }
175279 }
175280
@@ -175432,26 +176008,31 @@
176008 }
176009 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
176010 (u8*)&colUsed, P4_INT64);
176011 }
176012 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
176013 #ifdef SQLITE_ENABLE_CURSOR_HINTS
176014 if( HasRowid(pTab) ){
176015 sqlite3VdbeAddOp3(v, OP_CursorHint, iIndexCur, 0, pTabItem->iCursor);
176016 }
176017 #endif
176018 }
176019 }
176020 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
176021 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
176022 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
176023 ){
176024 WhereRightJoin *pRJ = pLevel->pRJ;
176025 int bBloomable = 0;
176026 pRJ->iMatch = pParse->nTab++;
 
 
176027 pRJ->regReturn = ++pParse->nMem;
176028 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
176029 assert( pTab==pTabItem->pSTab );
176030 if( HasRowid(pTab) ){
176031 KeyInfo *pInfo;
176032 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
176033 bBloomable = 1;
176034 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
176035 if( pInfo ){
176036 pInfo->aColl[0] = 0;
176037 pInfo->aSortFlags[0] = 0;
176038 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
@@ -175458,10 +176039,17 @@
176039 }
176040 }else{
176041 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
176042 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
176043 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
176044 bBloomable = sqlite3IndexBloomable(pPk,pPk->nKeyCol);
176045 }
176046 if( bBloomable ){
176047 pRJ->regBloom = ++pParse->nMem;
176048 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
176049 }else{
176050 pRJ->regBloom = 0;
176051 }
176052 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
176053 /* The nature of RIGHT JOIN processing is such that it messes up
176054 ** the output order. So omit any ORDER BY/GROUP BY elimination
176055 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
@@ -176155,11 +176743,11 @@
176743 case SQLITE_INTEGER:
176744 iVal = sqlite3_value_int64(apArg[1]);
176745 break;
176746 case SQLITE_FLOAT: {
176747 double fVal = sqlite3_value_double(apArg[1]);
176748 if( sqlite3RealToI64(fVal)!=fVal ) goto error_out;
176749 iVal = (i64)fVal;
176750 break;
176751 }
176752 default:
176753 goto error_out;
@@ -186803,67 +187391,64 @@
187391 SQLITE_API char *sqlite3_data_directory = 0;
187392
187393 /*
187394 ** Initialize SQLite.
187395 **
187396 ** The sqlite3_initialize() routine must be called to initialize the
187397 ** memory allocation, VFS, and mutex subsystems prior to doing any
187398 ** serious work. As long as you do not compile with SQLITE_OMIT_AUTOINIT
187399 ** this routine will be called automatically by key routines such as
187400 ** sqlite3_open().
187401 **
187402 ** This routine is a no-op except on its very first call for the process,
187403 ** or for the first call after a call to sqlite3_shutdown. Most calls
187404 ** to sqlite3_initialize() are, in fact, no-ops. For that reason, the
187405 ** routine is broken into two pieces:
187406 **
187407 ** sqlite3Initialize() Does the actual work of initialization
187408 **
187409 ** sqlite3_initialize() Checks to see if initialization is needed
187410 ** and invokes sqlite3Initialize() if it is.
187411 **
187412 ** The sqlite3_initialize() interface is called frequently, but
187413 ** sqlite3Initialize() runs rarely. The function is broken up this way
187414 ** to avoid wasting CPU cycles with unnecessary stack setup for local
187415 ** variables in cases where it is not needed.
187416 **
187417 ** The first thread to call sqlite3_initialize() runs the initialization to
187418 ** completion. If subsequent threads call sqlite3_initialize() before the first
187419 ** thread has finished the initialization process, then the subsequent
187420 ** threads must block until the first thread finishes with the initialization.
187421 **
187422 ** The first thread might call this routine recursively. Recursive
187423 ** calls to this routine should not block, of course. Otherwise the
187424 ** initialization process would never complete.
187425 **
187426 ** Let X be the first thread to enter sqlite3_initialize(). Let Y be some
187427 ** other thread. While the initial invocation of sqlite3_initialize() by X
187428 ** is incomplete, it is required that:
187429 **
187430 ** * Calls to sqlite3_initialize() from Y must block until the outer-most
187431 ** call by X completes.
187432 **
187433 ** * Recursive calls to sqlite3_initialize() from thread X return
187434 ** immediately without blocking.
187435 */
187436 static SQLITE_NOINLINE int sqlite3Initialize(void){
187437 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
187438 int rc; /* Result code */
187439 #ifdef SQLITE_EXTRA_INIT
187440 int bRunExtraInit = 0; /* Extra initialization needed */
 
 
 
 
 
 
 
187441 #endif
187442
187443 /* If the following assert() fails on some obscure processor/compiler
187444 ** combination to warn that SQLite has been mis-compiled. If you hit
187445 ** this assert(), that means you need to recompile with the
187446 ** -DSQLITE_PTRSIZE=n compile-time option to set the correct pointer size.
187447 */
187448 assert( SQLITE_PTRSIZE==sizeof(char*) );
187449
 
 
 
 
 
 
 
 
 
 
187450 /* Make sure the mutex subsystem is initialized. If unable to
187451 ** initialize the mutex subsystem, return early with the error.
187452 ** If the system is so sick that we are unable to allocate a mutex,
187453 ** there is not much SQLite is going to be able to do.
187454 **
@@ -187003,10 +187588,30 @@
187588 int SQLITE_EXTRA_INIT(const char*);
187589 rc = SQLITE_EXTRA_INIT(0);
187590 }
187591 #endif
187592 return rc;
187593 }
187594 SQLITE_API int sqlite3_initialize(void){
187595 /* If this build does not support writable static data (WSD) natively
187596 ** then we have to invoke the (application-supplied) WSD initialization
187597 ** routine before doing anything else. */
187598 #ifdef SQLITE_OMIT_WSD
187599 rc = sqlite3_wsd_init(4096, 24);
187600 if( rc!=SQLITE_OK ){
187601 return rc;
187602 }
187603 #endif
187604
187605 if( sqlite3GlobalConfig.isInit ){
187606 /* SQLite has already been initialized. Fast early-out. */
187607 sqlite3MemoryBarrier();
187608 return SQLITE_OK;
187609 }else{
187610 /* Invoke sqlite3Initialize() to do the actual work. */
187611 return sqlite3Initialize();
187612 }
187613 }
187614
187615 /*
187616 ** Undo the effects of sqlite3_initialize(). Must not be called while
187617 ** there are outstanding database connections or memory allocations or
@@ -187755,17 +188360,21 @@
188360
188361 /*
188362 ** Return the ROWID of the most recent insert
188363 */
188364 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
188365 i64 iRet;
188366 #ifdef SQLITE_ENABLE_API_ARMOR
188367 if( !sqlite3SafetyCheckOk(db) ){
188368 (void)SQLITE_MISUSE_BKPT;
188369 return 0;
188370 }
188371 #endif
188372 sqlite3_mutex_enter(db->mutex);
188373 iRet = db->lastRowid;
188374 sqlite3_mutex_leave(db->mutex);
188375 return iRet;
188376 }
188377
188378 /*
188379 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
188380 */
@@ -187784,33 +188393,41 @@
188393 /*
188394 ** Return the number of changes in the most recently executed DML
188395 ** statement.
188396 */
188397 SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3 *db){
188398 i64 iRet;
188399 #ifdef SQLITE_ENABLE_API_ARMOR
188400 if( !sqlite3SafetyCheckOk(db) ){
188401 (void)SQLITE_MISUSE_BKPT;
188402 return 0;
188403 }
188404 #endif
188405 sqlite3_mutex_enter(db->mutex);
188406 iRet = db->nChange;
188407 sqlite3_mutex_leave(db->mutex);
188408 return iRet;
188409 }
188410 SQLITE_API int sqlite3_changes(sqlite3 *db){
188411 return (int)sqlite3_changes64(db);
188412 }
188413
188414 /*
188415 ** Return the number of changes since the database handle was opened.
188416 */
188417 SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
188418 i64 iRet;
188419 #ifdef SQLITE_ENABLE_API_ARMOR
188420 if( !sqlite3SafetyCheckOk(db) ){
188421 (void)SQLITE_MISUSE_BKPT;
188422 return 0;
188423 }
188424 #endif
188425 sqlite3_mutex_enter(db->mutex);
188426 iRet = db->nTotalChange;
188427 sqlite3_mutex_leave(db->mutex);
188428 return iRet;
188429 }
188430 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
188431 return (int)sqlite3_total_changes64(db);
188432 }
188433
@@ -188489,10 +189106,11 @@
189106 */
189107 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
189108 #ifdef SQLITE_ENABLE_API_ARMOR
189109 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
189110 #endif
189111 sqlite3_mutex_enter(db->mutex);
189112 if( ms>0 ){
189113 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
189114 (void*)db);
189115 db->busyTimeout = ms;
189116 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
@@ -188499,10 +189117,11 @@
189117 db->setlkTimeout = ms;
189118 #endif
189119 }else{
189120 sqlite3_busy_handler(db, 0, 0);
189121 }
189122 sqlite3_mutex_leave(db->mutex);
189123 return SQLITE_OK;
189124 }
189125
189126 /*
189127 ** Set the setlk timeout value.
@@ -189404,13 +190023,15 @@
190023 /*
190024 ** Return the byte offset of the most recent error
190025 */
190026 SQLITE_API int sqlite3_error_offset(sqlite3 *db){
190027 int iOffset = -1;
190028 if( db && sqlite3SafetyCheckSickOrOk(db) ){
190029 sqlite3_mutex_enter(db->mutex);
190030 if( db->errCode ){
190031 iOffset = db->errByteOffset;
190032 }
190033 sqlite3_mutex_leave(db->mutex);
190034 }
190035 return iOffset;
190036 }
190037
@@ -189460,29 +190081,47 @@
190081 /*
190082 ** Return the most recent error code generated by an SQLite routine. If NULL is
190083 ** passed to this function, we assume a malloc() failed during sqlite3_open().
190084 */
190085 SQLITE_API int sqlite3_errcode(sqlite3 *db){
190086 int iRet;
190087 if( !db ) return SQLITE_NOMEM_BKPT;
190088 if( !sqlite3SafetyCheckSickOrOk(db) ){
190089 return SQLITE_MISUSE_BKPT;
190090 }
190091 sqlite3_mutex_enter(db->mutex);
190092 if( db->mallocFailed ){
190093 iRet = SQLITE_NOMEM_BKPT;
190094 }else{
190095 iRet = db->errCode & db->errMask;
190096 }
190097 sqlite3_mutex_leave(db->mutex);
190098 return iRet;
190099 }
190100 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
190101 int iRet;
190102 if( !db ) return SQLITE_NOMEM_BKPT;
190103 if( !sqlite3SafetyCheckSickOrOk(db) ){
190104 return SQLITE_MISUSE_BKPT;
190105 }
190106 sqlite3_mutex_enter(db->mutex);
190107 if( db->mallocFailed ){
190108 iRet = SQLITE_NOMEM_BKPT;
190109 }else{
190110 iRet = db->errCode;
190111 }
190112 sqlite3_mutex_leave(db->mutex);
190113 return iRet;
190114 }
190115 SQLITE_API int sqlite3_system_errno(sqlite3 *db){
190116 int iRet = 0;
190117 if( db ){
190118 sqlite3_mutex_enter(db->mutex);
190119 iRet = db->iSysErrno;
190120 sqlite3_mutex_leave(db->mutex);
190121 }
190122 return iRet;
190123 }
190124
190125 /*
190126 ** Return a string that describes the kind of error specified in the
190127 ** argument. For now, this simply calls the internal sqlite3ErrStr()
@@ -189585,10 +190224,11 @@
190224 SQLITE_MAX_LIKE_PATTERN_LENGTH,
190225 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
190226 SQLITE_MAX_TRIGGER_DEPTH,
190227 SQLITE_MAX_WORKER_THREADS,
190228 SQLITE_MAX_PARSER_DEPTH,
190229 SQLITE_MAX_SCHEMA,
190230 };
190231
190232 /*
190233 ** Make sure the hard limits are set to reasonable values
190234 */
@@ -189667,25 +190307,28 @@
190307 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
190308 SQLITE_MAX_LIKE_PATTERN_LENGTH );
190309 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
190310 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
190311 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
190312 assert( aHardLimit[SQLITE_LIMIT_SCHEMA]==SQLITE_MAX_SCHEMA );
190313 assert( SQLITE_LIMIT_SCHEMA==(SQLITE_N_LIMIT-1) );
190314
190315
190316 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
190317 return -1;
190318 }
190319 sqlite3_mutex_enter(db->mutex);
190320 oldLimit = db->aLimit[limitId];
190321 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
190322 if( newLimit>aHardLimit[limitId] ){
190323 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
190324 }else if( newLimit<SQLITE_MIN_LENGTH && limitId==SQLITE_LIMIT_LENGTH ){
190325 newLimit = SQLITE_MIN_LENGTH;
190326 }
190327 db->aLimit[limitId] = newLimit;
190328 }
190329 sqlite3_mutex_leave(db->mutex);
190330 return oldLimit; /* IMP: R-53341-35419 */
190331 }
190332
190333 /*
190334 ** This function is used to parse both URIs and non-URI filenames passed by the
@@ -189724,22 +190367,22 @@
190367 int rc = SQLITE_OK;
190368 unsigned int flags = *pFlags;
190369 const char *zVfs = zDefaultVfs;
190370 char *zFile;
190371 char c;
190372 i64 nUri = strlen(zUri);
190373
190374 assert( *pzErrMsg==0 );
190375
190376 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
190377 || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
190378 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
190379 ){
190380 char *zOpt;
190381 int eState; /* Parser state when parsing URI */
190382 i64 iIn; /* Input character index */
190383 i64 iOut = 0; /* Output character index */
190384 u64 nByte = nUri+8; /* Bytes of space to allocate */
190385
190386 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
190387 ** method that there may be extra parameters following the file-name. */
190388 flags |= SQLITE_OPEN_URI;
@@ -189769,11 +190412,11 @@
190412 if( zUri[5]=='/' && zUri[6]=='/' ){
190413 iIn = 7;
190414 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
190415 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
190416 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
190417 (int)(iIn-7), &zUri[7]);
190418 rc = SQLITE_ERROR;
190419 goto parse_uri_out;
190420 }
190421 }
190422 #endif
@@ -189844,15 +190487,15 @@
190487
190488 /* Check if there were any options specified that should be interpreted
190489 ** here. Options that are interpreted here include "vfs" and those that
190490 ** correspond to flags that may be passed to the sqlite3_open_v2()
190491 ** method. */
190492 zOpt = &zFile[strlen(zFile)+1];
190493 while( zOpt[0] ){
190494 i64 nOpt = strlen(zOpt);
190495 char *zVal = &zOpt[nOpt+1];
190496 i64 nVal = strlen(zVal);
190497
190498 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
190499 zVfs = zVal;
190500 }else{
190501 struct OpenMode {
@@ -189894,11 +190537,11 @@
190537 if( aMode ){
190538 int i;
190539 int mode = 0;
190540 for(i=0; aMode[i].z; i++){
190541 const char *z = aMode[i].z;
190542 if( nVal==(i64)strlen(z) && 0==memcmp(zVal, z, nVal) ){
190543 mode = aMode[i].mode;
190544 break;
190545 }
190546 }
190547 if( mode==0 ){
@@ -190579,17 +191222,21 @@
191222 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
191223 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
191224 ** by the next COMMIT or ROLLBACK.
191225 */
191226 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
191227 int iRet;
191228 #ifdef SQLITE_ENABLE_API_ARMOR
191229 if( !sqlite3SafetyCheckOk(db) ){
191230 (void)SQLITE_MISUSE_BKPT;
191231 return 0;
191232 }
191233 #endif
191234 sqlite3_mutex_enter(db->mutex);
191235 iRet = db->autoCommit;
191236 sqlite3_mutex_leave(db->mutex);
191237 return iRet;
191238 }
191239
191240 /*
191241 ** The following routines are substitutes for constants SQLITE_CORRUPT,
191242 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
@@ -191610,21 +192257,23 @@
192257 /*
192258 ** Return the name of the N-th database schema. Return NULL if N is out
192259 ** of range.
192260 */
192261 SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N){
192262 const char *zRet = 0;
192263 #ifdef SQLITE_ENABLE_API_ARMOR
192264 if( !sqlite3SafetyCheckOk(db) ){
192265 (void)SQLITE_MISUSE_BKPT;
192266 return 0;
192267 }
192268 #endif
192269 sqlite3_mutex_enter(db->mutex);
192270 if( N>=0 && N<db->nDb ){
192271 zRet = db->aDb[N].zDbSName;
 
192272 }
192273 sqlite3_mutex_leave(db->mutex);
192274 return zRet;
192275 }
192276
192277 /*
192278 ** Return the filename of the database associated with a database
192279 ** connection.
@@ -197602,10 +198251,11 @@
198251 }else{
198252 int nDistance;
198253 char *p1;
198254 char *p2;
198255 char *aOut;
198256 i64 nAlloc = (i64)nPoslist*2 + FTS3_BUFFER_PADDING;
198257
198258 if( nMaxUndeferred>iPrev ){
198259 p1 = aPoslist;
198260 p2 = pPhrase->doclist.pList;
198261 nDistance = nMaxUndeferred - iPrev;
@@ -197613,11 +198263,11 @@
198263 p1 = pPhrase->doclist.pList;
198264 p2 = aPoslist;
198265 nDistance = iPrev - nMaxUndeferred;
198266 }
198267
198268 aOut = (char *)sqlite3Fts3MallocZero(nAlloc);
198269 if( !aOut ){
198270 sqlite3_free(aPoslist);
198271 return SQLITE_NOMEM;
198272 }
198273
@@ -207898,11 +208548,11 @@
208548 if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
208549 sqlite3_reset(pSelect);
208550 return FTS_CORRUPT_VTAB;
208551 }
208552
208553 pWriter->nLeafEst = (int)(((iEnd - iStart)+1)/FTS_MAX_APPENDABLE_HEIGHT);
208554 pWriter->iStart = iStart;
208555 pWriter->iEnd = iEnd;
208556 pWriter->iAbsLevel = iAbsLevel;
208557 pWriter->iIdx = iIdx;
208558
@@ -210015,12 +210665,12 @@
210665
210666 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
210667 ** to grow the buffer until so that it is big enough to accommodate the
210668 ** appended data.
210669 */
210670 if( (i64)pStr->n+(i64)nAppend+1>=(i64)pStr->nAlloc ){
210671 i64 nAlloc = pStr->nAlloc+(i64)nAppend+100;
210672 char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
210673 if( !zNew ){
210674 return SQLITE_NOMEM;
210675 }
210676 pStr->z = zNew;
@@ -213118,11 +213768,11 @@
213768 /*
213769 ** Expand pParse->aBlob so that it holds at least N bytes.
213770 **
213771 ** Return the number of errors.
213772 */
213773 static int jsonBlobExpand(JsonParse *pParse, u64 N){
213774 u8 *aNew;
213775 u64 t;
213776 assert( N>pParse->nBlobAlloc );
213777 if( pParse->nBlobAlloc==0 ){
213778 t = 100;
@@ -213146,11 +213796,11 @@
213796 **
213797 ** Return true on success. Return false on OOM.
213798 */
213799 static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){
213800 u8 *aOld;
213801 u64 nSize;
213802 assert( !pParse->bReadOnly );
213803 if( pParse->oom ) return 0;
213804 if( pParse->nBlobAlloc>0 ) return 1;
213805 aOld = pParse->aBlob;
213806 nSize = pParse->nBlob + nExtra;
@@ -213167,11 +213817,11 @@
213817 */
213818 static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte(
213819 JsonParse *pParse,
213820 u8 c
213821 ){
213822 jsonBlobExpand(pParse, (u64)pParse->nBlob+1);
213823 if( pParse->oom==0 ){
213824 assert( pParse->nBlob+1<=pParse->nBlobAlloc );
213825 pParse->aBlob[pParse->nBlob++] = c;
213826 }
213827 }
@@ -213194,11 +213844,11 @@
213844 JsonParse *pParse,
213845 u8 eType,
213846 u64 szPayload,
213847 const void *aPayload
213848 ){
213849 if( jsonBlobExpand(pParse, (u64)pParse->nBlob+(u64)szPayload+9) ) return;
213850 jsonBlobAppendNode(pParse, eType, szPayload, aPayload);
213851 }
213852
213853
213854 /* Append a node type byte together with the payload size and
@@ -213284,11 +213934,11 @@
213934 }else{
213935 nNeeded = 4;
213936 }
213937 delta = nNeeded - nExtra;
213938 if( delta ){
213939 u64 newSize = (u64)pParse->nBlob + delta;
213940 if( delta>0 ){
213941 if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){
213942 return 0; /* OOM error. Error state recorded in pParse->oom. */
213943 }
213944 a = &pParse->aBlob[i];
@@ -214220,11 +214870,12 @@
214870 u32 k = 0;
214871 const char *zIn = (const char*)&pParse->aBlob[i+n];
214872 if( sz==0 ) goto malformed_jsonb;
214873 if( zIn[0]=='-' ){
214874 jsonAppendChar(pOut, '-');
214875 if( sz<=1 ) goto malformed_jsonb;
214876 k = 1;
214877 }
214878 if( zIn[k]=='.' ){
214879 jsonAppendChar(pOut, '0');
214880 }
214881 for(; k<sz; k++){
@@ -214631,11 +215282,11 @@
215282 ){
215283 return;
215284 }
215285 if( d!=0 ){
215286 if( pParse->nBlob + d > pParse->nBlobAlloc ){
215287 jsonBlobExpand(pParse, (u64)pParse->nBlob+d);
215288 if( pParse->oom ) return;
215289 }
215290 memmove(&pParse->aBlob[iDel+nIns],
215291 &pParse->aBlob[iDel+nDel],
215292 pParse->nBlob - (iDel+nDel));
@@ -215418,12 +216069,11 @@
216069 jsonBlobAppendNode(pParse, JSONB_TEXTRAW, nJson, zJson);
216070 }
216071 break;
216072 }
216073 case SQLITE_FLOAT: {
216074 if( NEVER(sqlite3IsNaN(sqlite3_value_double(pArg))) ){
 
216075 jsonBlobAppendNode(pParse, JSONB_NULL, 0, 0);
216076 }else{
216077 int n = sqlite3_value_bytes(pArg);
216078 const char *z = (const char*)sqlite3_value_text(pArg);
216079 if( z==0 ) return 1;
@@ -217184,11 +217834,13 @@
217834 */
217835 static int jsonSkipLabel(JsonEachCursor *p){
217836 if( p->eType==JSONB_OBJECT ){
217837 u32 sz = 0;
217838 u32 n = jsonbPayloadSize(&p->sParse, p->i, &sz);
217839 sz += p->i + n;
217840 if( sz >= p->sParse.nBlob ) sz = p->i;
217841 return sz;
217842 }else{
217843 return p->i;
217844 }
217845 }
217846
@@ -218016,11 +218668,11 @@
218668 int mxLevel; /* iLevel value for root of the tree */
218669 RtreeSearchPoint *aPoint; /* Priority queue for search points */
218670 sqlite3_stmt *pReadAux; /* Statement to read aux-data */
218671 RtreeSearchPoint sPoint; /* Cached next search point */
218672 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
218673 u32 anQueue[RTREE_MAX_DEPTH+2]; /* Number of queued entries by iLevel */
218674 };
218675
218676 /* Return the Rtree of a RtreeCursor */
218677 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
218678
@@ -218499,11 +219151,11 @@
219151 ** are the leaves, and so on. If the depth as specified on the root node
219152 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
219153 */
219154 if( rc==SQLITE_OK && pNode && iNode==1 ){
219155 pRtree->iDepth = readInt16(pNode->zData);
219156 if( pRtree->iDepth>=RTREE_MAX_DEPTH ){
219157 rc = SQLITE_CORRUPT_VTAB;
219158 RTREE_IS_CORRUPT(pRtree);
219159 }
219160 }
219161
@@ -226154,31 +226806,31 @@
226806 int lenSrc, /* Length of the source file */
226807 const char *zDelta, /* Delta to apply to the pattern */
226808 int lenDelta, /* Length of the delta */
226809 char *zOut /* Write the output into this preallocated buffer */
226810 ){
226811 sqlite3_uint64 limit;
226812 sqlite3_uint64 total = 0;
226813 #if RBU_ENABLE_DELTA_CKSUM
226814 char *zOrigOut = zOut;
226815 #endif
226816
226817 limit = rbuDeltaGetInt(&zDelta, &lenDelta);
226818 if( lenDelta<=0 || *zDelta!='\n' ){
226819 /* ERROR: size integer not terminated by "\n" */
226820 return -1;
226821 }
226822 zDelta++; lenDelta--; /* Skip the \n */
226823 while( lenDelta>0 && zDelta[0] ){
226824 unsigned int cnt, ofst;
226825 cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
226826 if( lenDelta<=0 ) return -1;
226827 switch( zDelta[0] ){
226828 case '@': {
226829 zDelta++; lenDelta--;
226830 ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
226831 if( lenDelta>0 && zDelta[0]!=',' ){
226832 /* ERROR: copy command not terminated by ',' */
226833 return -1;
226834 }
226835 zDelta++; lenDelta--;
226836 total += cnt;
@@ -226199,11 +226851,11 @@
226851 total += cnt;
226852 if( total>limit ){
226853 /* ERROR: insert command gives an output larger than predicted */
226854 return -1;
226855 }
226856 if( cnt>lenDelta ){
226857 /* ERROR: insert count exceeds size of delta */
226858 return -1;
226859 }
226860 memcpy(zOut, zDelta, cnt);
226861 zOut += cnt;
@@ -228212,17 +228864,17 @@
228864 char *zWhere = rbuObjIterGetWhere(p, pIter);
228865 char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
228866 char *zUpdate = 0;
228867
228868 pUp->zMask = (char*)&pUp[1];
 
228869 pUp->pNext = pIter->pRbuUpdate;
228870 pIter->pRbuUpdate = pUp;
228871
228872 if( zSet ){
228873 const char *zPrefix = "";
228874 assert( p->rc==SQLITE_OK );
228875 memcpy(pUp->zMask, zMask, pIter->nTblCol);
228876 if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
228877 zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
228878 zPrefix, pIter->zTbl, zSet, zWhere
228879 );
228880 p->rc = prepareFreeAndCollectError(
@@ -228308,10 +228960,13 @@
228960 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
228961 break;
228962
228963 case RBU_STATE_ROW:
228964 pRet->nRow = sqlite3_column_int(pStmt, 1);
228965 if( pRet->nRow<0 ){
228966 rc = SQLITE_CORRUPT;
228967 }
228968 break;
228969
228970 case RBU_STATE_PROGRESS:
228971 pRet->nProgress = sqlite3_column_int64(pStmt, 1);
228972 break;
@@ -234473,11 +235128,11 @@
235128 SessionBuffer *p,
235129 const char *zStr,
235130 int *pRc
235131 ){
235132 int nStr = sqlite3Strlen30(zStr);
235133 if( 0==sessionBufferGrow(p, (i64)nStr+1, pRc) ){
235134 memcpy(&p->aBuf[p->nBuf], zStr, nStr);
235135 p->nBuf += nStr;
235136 p->aBuf[p->nBuf] = 0x00;
235137 }
235138 }
@@ -239557,11 +240212,16 @@
240212 int nRec;
240213 int rc = SQLITE_OK;
240214
240215 pIter->in.bNoDiscard = 1;
240216 while( SQLITE_ROW==(sessionChangesetNext(pIter, &aRec, &nRec, 0)) ){
240217 if( bRebase && pIter->bPatchset ){
240218 /* A patchset may not be used as a rebase */
240219 rc = SQLITE_ERROR;
240220 }else{
240221 rc = sessionOneChangeIterToHash(pGrp, pIter, bRebase);
240222 }
240223 if( rc!=SQLITE_OK ) break;
240224 }
240225
240226 if( rc==SQLITE_OK ) rc = pIter->rc;
240227 return rc;
@@ -239875,18 +240535,21 @@
240535 int nCol, /* Number of columns in each record */
240536 u8 *a1, int n1, /* Record 1 */
240537 u8 *a2, int n2, /* Record 2 */
240538 int *pRc /* IN/OUT: error code */
240539 ){
240540 u8 *a1Eof = &a1[n1];
240541 u8 *a2Eof = &a2[n2];
240542
240543 sessionBufferGrow(pBuf, (i64)n1+n2, pRc);
240544 if( *pRc==SQLITE_OK ){
240545 int i;
240546 u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
240547 for(i=0; i<nCol; i++){
240548 int nn1 = (a1<a1Eof ? sessionSerialLen(a1) : 0);
240549 int nn2 = (a2<a2Eof ? sessionSerialLen(a2) : 0);
240550 if( nn1==0 || (nn2>0 && (*a1==0 || *a1==0xFF)) ){
240551 memcpy(pOut, a2, nn2);
240552 pOut += nn2;
240553 }else{
240554 memcpy(pOut, a1, nn1);
240555 pOut += nn1;
@@ -239924,24 +240587,25 @@
240587 sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
240588 u8 *aRec, int nRec, /* Local change */
240589 u8 *aChange, int nChange, /* Record to rebase against */
240590 int *pRc /* IN/OUT: Return Code */
240591 ){
240592 sessionBufferGrow(pBuf, (i64)2+nRec+nChange, pRc);
240593 if( *pRc==SQLITE_OK ){
240594 int bData = 0;
240595 u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
240596 int i;
240597 u8 *a1 = aRec;
240598 u8 *a2 = aChange;
240599 u8 *a2Eof = &a2[nChange];
240600
240601 *pOut++ = SQLITE_UPDATE;
240602 *pOut++ = pIter->bIndirect;
240603 for(i=0; i<pIter->nCol; i++){
240604 int n1 = sessionSerialLen(a1);
240605 int n2 = (a2>=a2Eof) ? 0 : sessionSerialLen(a2);
240606 if( n2<=0 || pIter->abPK[i] || a2[0]==0 ){
240607 if( !pIter->abPK[i] && a1[0] ) bData = 1;
240608 memcpy(pOut, a1, n1);
240609 pOut += n1;
240610 }else if( a2[0]!=0xFF && a1[0] ){
240611 bData = 1;
@@ -240138,12 +240802,12 @@
240802 */
240803 SQLITE_API int sqlite3rebaser_configure(
240804 sqlite3_rebaser *p,
240805 int nRebase, const void *pRebase
240806 ){
 
240807 int rc; /* Return code */
240808 sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
240809 rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
240810 if( rc==SQLITE_OK ){
240811 rc = sessionChangesetToHash(pIter, &p->grp, 1);
240812 }
240813 sqlite3changeset_finalize(pIter);
@@ -250965,10 +251629,11 @@
251629 i64 szData = (sizeof(Fts5Data) + 7) & ~7;
251630 i64 nAlloc = szData + nByte + FTS5_DATA_PADDING;
251631 pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
251632 if( pRet ){
251633 pRet->nn = nByte;
251634 pRet->szLeaf = 0;
251635 aOut = pRet->p = (u8*)pRet + szData;
251636 }else{
251637 rc = SQLITE_NOMEM;
251638 }
251639
@@ -250977,14 +251642,12 @@
251642 }
251643 if( rc!=SQLITE_OK ){
251644 sqlite3_free(pRet);
251645 pRet = 0;
251646 }else{
 
251647 pRet->p[nByte] = 0x00;
251648 pRet->p[nByte+1] = 0x00;
 
251649 }
251650 }
251651 p->rc = rc;
251652 p->nRead++;
251653 }
@@ -251001,13 +251664,21 @@
251664 */
251665 static void fts5DataRelease(Fts5Data *pData){
251666 sqlite3_free(pData);
251667 }
251668
251669 /*
251670 ** Read a leaf-page record. This is similar to fts5DataRead(), except that
251671 ** it fills in the Fts5Data.szLeaf value before returning.
251672 */
251673 static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
251674 Fts5Data *pRet = fts5DataRead(p, iRowid);
251675 if( pRet ){
251676 assert( pRet->szLeaf==0 );
251677 if( pRet->nn>=4 ){
251678 pRet->szLeaf = fts5GetU16(&pRet->p[2]);
251679 }
251680 if( pRet->szLeaf<4 || pRet->szLeaf>pRet->nn ){
251681 FTS5_CORRUPT_ROWID(p, iRowid);
251682 fts5DataRelease(pRet);
251683 pRet = 0;
251684 }
@@ -252914,10 +253585,14 @@
253585 const u8 *a = pIter->pLeaf->p;
253586 int iTermOff = 0;
253587
253588 pIter->iPgidxOff = pIter->pLeaf->szLeaf;
253589 pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff);
253590 if( iTermOff > pIter->pLeaf->szLeaf ){
253591 p->rc = FTS5_CORRUPT;
253592 return;
253593 }
253594 pIter->iLeafOffset = iTermOff;
253595 fts5SegIterLoadTerm(p, pIter, 0);
253596 fts5SegIterLoadNPos(p, pIter);
253597 if( bDlidx ) fts5SegIterLoadDlidx(p, pIter);
253598
@@ -255240,19 +255915,19 @@
255915 for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
255916 i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
255917 int iNext = 0;
255918 u8 *aPg = 0;
255919
255920 pLeaf = fts5LeafRead(p, iRowid);
255921 if( pLeaf==0 ) break;
255922 aPg = pLeaf->p;
255923
255924 iNext = fts5GetU16(&aPg[0]);
255925 if( iNext!=0 ){
255926 *pbLastInDoclist = 0;
255927 }
255928 if( iNext==0 && pLeaf->szLeaf<pLeaf->nn ){
255929 fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
255930 }
255931
255932 if( iNext==0 ){
255933 /* The page contains no terms or rowids. Replace it with an empty
@@ -255535,19 +256210,19 @@
256210
256211 assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
256212 /* The entry being removed may be the only position list in
256213 ** its doclist. */
256214 for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
256215 Fts5Data *pPg = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
256216 int bEmpty = (pPg && pPg->nn==4);
256217 fts5DataRelease(pPg);
256218 if( bEmpty==0 ) break;
256219 }
256220
256221 if( iPgno==pSeg->iTermLeafPgno ){
256222 i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
256223 Fts5Data *pTerm = fts5LeafRead(p, iId);
256224 if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
256225 u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
256226 int nTermIdx = pTerm->nn - pTerm->szLeaf;
256227 int iTermIdx = 0;
256228 i64 iTermOff = 0;
@@ -258495,11 +259170,11 @@
259170 int i;
259171
259172 /* Now check that the iter.nEmpty leaves following the current leaf
259173 ** (a) exist and (b) contain no terms. */
259174 for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
259175 Fts5Data *pLeaf = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
259176 if( pLeaf ){
259177 if( !fts5LeafIsTermless(pLeaf)
259178 || (i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf))
259179 ){
259180 FTS5_CORRUPT_ROWID(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
@@ -258623,13 +259298,17 @@
259298 iRowidOff = fts5LeafFirstRowidOff(pLeaf);
259299 if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
259300 FTS5_CORRUPT_ROWID(p, iRow);
259301 }else{
259302 iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
259303 if( (i64)iOff+(i64)nTerm>(i64)pLeaf->szLeaf ){
259304 FTS5_CORRUPT_ROWID(p, iRow);
259305 }else{
259306 res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
259307 if( res==0 ) res = nTerm - nIdxTerm;
259308 if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow);
259309 }
259310 }
259311
259312 fts5IntegrityCheckPgidx(p, iRow, pLeaf);
259313 }
259314 fts5DataRelease(pLeaf);
@@ -262347,23 +263026,27 @@
263026 Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
263027 Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
263028
263029 if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
263030 Fts5Sorter *pSorter = pCsr->pSorter;
263031 if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){
263032 rc = SQLITE_RANGE;
 
 
 
263033 }else{
263034 int n;
263035 if( pSorter ){
263036 int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
263037 n = pSorter->aIdx[iPhrase] - i1;
263038 pIter->a = &pSorter->aPoslist[i1];
263039 }else{
263040 rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
263041 }
263042 if( rc==SQLITE_OK ){
263043 assert( pIter->a || n==0 );
263044 pIter->b = (pIter->a ? &pIter->a[n] : 0);
263045 *piCol = 0;
263046 fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
263047 }
263048 }
263049 }else{
263050 int n;
263051 rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
263052 if( rc==SQLITE_OK ){
@@ -263267,11 +263950,11 @@
263950 int nArg, /* Number of args */
263951 sqlite3_value **apUnused /* Function arguments */
263952 ){
263953 assert( nArg==0 );
263954 UNUSED_PARAM2(nArg, apUnused);
263955 sqlite3_result_text(pCtx, "fts5: 2026-07-24 16:28:47 2f1f4f73535386549c12694dc57cfe555eec689ae6824c6241aaf8d5befcd74d", -1, SQLITE_TRANSIENT);
263956 }
263957
263958 /*
263959 ** Implementation of fts5_locale(LOCALE, TEXT) function.
263960 **
@@ -263909,38 +264592,35 @@
264592
264593 if( bCreate ){
264594 if( pConfig->eContent==FTS5_CONTENT_NORMAL
264595 || pConfig->eContent==FTS5_CONTENT_UNINDEXED
264596 ){
264597 int i = 0;
264598 char *zDefn = 0;
264599 sqlite3_str *pDefn = sqlite3_str_new(pConfig->db);
264600
264601 sqlite3_str_appendf(pDefn, "id INTEGER PRIMARY KEY");
264602 for(i=0; i<pConfig->nCol; i++){
264603 if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->abUnindexed[i] ){
264604 sqlite3_str_appendf(pDefn, ", c%d", i);
264605 }
264606 }
264607 if( pConfig->bLocale ){
264608 for(i=0; i<pConfig->nCol; i++){
264609 if( pConfig->abUnindexed[i]==0 ){
264610 sqlite3_str_appendf(pDefn, ", l%d", i);
264611 }
264612 }
264613 }
264614 zDefn = sqlite3_str_finish(pDefn);
264615
264616 if( zDefn ){
264617 rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
264618 sqlite3_free(zDefn);
264619 }else{
264620 rc = SQLITE_NOMEM;
264621 }
 
 
 
264622 }
264623
264624 if( rc==SQLITE_OK && pConfig->bColumnsize ){
264625 const char *zCols = "id INTEGER PRIMARY KEY, sz BLOB";
264626 if( pConfig->bContentlessDelete ){
264627
+73 -11
--- 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.54.0"
150150
#define SQLITE_VERSION_NUMBER 3054000
151
-#define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
151
+#define SQLITE_SOURCE_ID "2026-07-24 16:28:47 2f1f4f73535386549c12694dc57cfe555eec689ae6824c6241aaf8d5befcd74d"
152152
#define SQLITE_SCM_BRANCH "trunk"
153153
#define SQLITE_SCM_TAGS ""
154
-#define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
154
+#define SQLITE_SCM_DATETIME "2026-07-24T16:28:47.830Z"
155155
156156
/*
157157
** CAPI3REF: Run-Time Library Version Numbers
158158
** KEYWORDS: sqlite3_version sqlite3_sourceid
159159
**
@@ -3411,11 +3411,11 @@
34113411
** authorizer will fail with an error message explaining that
34123412
** access is denied.
34133413
**
34143414
** ^The first parameter to the authorizer callback is a copy of the third
34153415
** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3416
-** to the callback is an integer [SQLITE_COPY | action code] that specifies
3416
+** to the callback is an integer [SQLITE_READ | action code] that specifies
34173417
** the particular action to be authorized. ^The third through sixth parameters
34183418
** to the callback are either NULL pointers or zero-terminated strings
34193419
** that contain additional details about the action to be authorized.
34203420
** Applications must always be prepared to encounter a NULL pointer in any
34213421
** of the third through the sixth parameters of the authorization callback.
@@ -3454,25 +3454,37 @@
34543454
** ^(Only a single authorizer can be in place on a database connection
34553455
** at a time. Each call to sqlite3_set_authorizer overrides the
34563456
** previous call.)^ ^Disable the authorizer by installing a NULL callback.
34573457
** The authorizer is disabled by default.
34583458
**
3459
-** The authorizer callback must not do anything that will modify
3459
+** <h3>Limitations And Caveats</h3><ul>
3460
+**
3461
+** <li>The authorizer callback must not do anything that will modify
34603462
** the database connection that invoked the authorizer callback.
34613463
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
34623464
** database connections for the meaning of "modify" in this paragraph.
34633465
**
3464
-** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3466
+** <li>^When [sqlite3_prepare_v2()] is used to prepare a statement, the
34653467
** statement might be re-prepared during [sqlite3_step()] due to a
34663468
** schema change. Hence, the application should ensure that the
34673469
** correct authorizer callback remains in place during the [sqlite3_step()].
34683470
**
3469
-** ^Note that the authorizer callback is invoked only during
3471
+** <li>^The authorizer callback is invoked only during
34703472
** [sqlite3_prepare()] or its variants. Authorization is not
34713473
** performed during statement evaluation in [sqlite3_step()], unless
34723474
** as stated in the previous paragraph, sqlite3_step() invokes
34733475
** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3476
+**
3477
+** <li>Authorizer callbacks for the expressions of a
3478
+** [generated column] are invoked when the schema is parsed (and specifically
3479
+** when the [CREATE TABLE] statement that contains the generated column is
3480
+** parsed) not when the generated column is used in a DML statement.
3481
+** This is deliberate, as one of the purposes of generated columns
3482
+** is to give schema designers the ability to provide gated access
3483
+** to privileged columns and/or functions.
3484
+**
3485
+** </ul>
34743486
*/
34753487
SQLITE_API int sqlite3_set_authorizer(
34763488
sqlite3*,
34773489
int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
34783490
void *pUserData
@@ -3543,12 +3555,17 @@
35433555
#define SQLITE_ANALYZE 28 /* Table Name NULL */
35443556
#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
35453557
#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
35463558
#define SQLITE_FUNCTION 31 /* NULL Function Name */
35473559
#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3548
-#define SQLITE_COPY 0 /* No longer used */
35493560
#define SQLITE_RECURSIVE 33 /* NULL NULL */
3561
+
3562
+/*
3563
+** Note: The SQLITE_COPY macro (with value 0) used to be one of the
3564
+** action codes above. That macro has now been repurposed as a possible
3565
+** value to the 3rd argument to sqlite3_result_str().
3566
+*/
35503567
35513568
/*
35523569
** CAPI3REF: Deprecated Tracing And Profiling Functions
35533570
** DEPRECATED
35543571
**
@@ -4413,10 +4430,14 @@
44134430
** nesting depth for separate triggers.</dd>)^
44144431
**
44154432
** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
44164433
** <dd>The maximum number of auxiliary worker threads that a single
44174434
** [prepared statement] may start.</dd>)^
4435
+**
4436
+** [[SQLITE_LIMIT_SCHEMA]] ^(<dt>SQLITE_LIMIT_SCHEMA</dt>
4437
+** <dd>The maximum number of objects (tables, indexes, triggers, and views)
4438
+** defined by the database schema.</dd>)^
44184439
** </dl>
44194440
*/
44204441
#define SQLITE_LIMIT_LENGTH 0
44214442
#define SQLITE_LIMIT_SQL_LENGTH 1
44224443
#define SQLITE_LIMIT_COLUMN 2
@@ -4428,10 +4449,11 @@
44284449
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
44294450
#define SQLITE_LIMIT_VARIABLE_NUMBER 9
44304451
#define SQLITE_LIMIT_TRIGGER_DEPTH 10
44314452
#define SQLITE_LIMIT_WORKER_THREADS 11
44324453
#define SQLITE_LIMIT_PARSER_DEPTH 12
4454
+#define SQLITE_LIMIT_SCHEMA 13
44334455
44344456
/*
44354457
** CAPI3REF: Prepare Flags
44364458
**
44374459
** These constants define various flags that can be passed into the
@@ -4539,10 +4561,12 @@
45394561
** there is a small performance advantage to passing an nByte parameter that
45404562
** is the number of bytes in the input string <i>including</i>
45414563
** the nul-terminator.
45424564
** Note that nByte measures the length of the input in bytes, not
45434565
** characters, even for the UTF-16 interfaces.
4566
+** For the sqlite3_prepare16() and sqlite3_prepare16_v2() interfaces,
4567
+** the nByte value must be even or undefined behavior can result.
45444568
**
45454569
** ^If pzTail is not NULL then *pzTail is made to point to the first byte
45464570
** past the end of the first SQL statement in zSql. These routines only
45474571
** compile the first statement in zSql, so *pzTail is left pointing to
45484572
** what remains uncompiled.
@@ -5285,11 +5309,11 @@
52855309
** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
52865310
** can be obtained by calling [sqlite3_reset()] on the
52875311
** [prepared statement]. ^In the "v2" interface,
52885312
** the more specific error code is returned directly by sqlite3_step().
52895313
**
5290
-** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5314
+** [SQLITE_MISUSE] means that this routine was called inappropriately.
52915315
** Perhaps it was called on a [prepared statement] that has
52925316
** already been [sqlite3_finalize | finalized] or on one that had
52935317
** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
52945318
** be the case that the same database connection is being used by two or
52955319
** more threads at the same moment in time.
@@ -6458,11 +6482,15 @@
64586482
** to by the second parameter and which is N bytes long where N is the
64596483
** third parameter.
64606484
**
64616485
** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
64626486
** interfaces set the result of the application-defined function to be
6463
-** a BLOB containing all zero bytes and N bytes in size.
6487
+** a BLOB containing all zero bytes and N bytes in size. The
6488
+** zeroblob64(C,N) interface returns a [result code], which is normally
6489
+** [SQLITE_OK] but might be some other value if the requested operation
6490
+** could not be complete, for example if insufficient memory is available
6491
+** or if the value of N is out of range.
64646492
**
64656493
** ^The sqlite3_result_double() interface sets the result from
64666494
** an application-defined function to be a floating point value specified
64676495
** by its 2nd argument.
64686496
**
@@ -8796,12 +8824,12 @@
87968824
** The lifecycle of an sqlite3_str object is as follows:
87978825
** <ol>
87988826
** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
87998827
** <li> ^Text is appended to the sqlite3_str object using various
88008828
** methods, such as [sqlite3_str_appendf()].
8801
-** <li> ^The sqlite3_str object is destroyed and the string it created
8802
-** is returned using the [sqlite3_str_finish()] interface.
8829
+** <li> The sqlite3_str object is destroyed and the string it created
8830
+** is returned using [sqlite3_str_finish()] or [sqlite3_result_str()].
88038831
** </ol>
88048832
*/
88058833
typedef struct sqlite3_str sqlite3_str;
88068834
88078835
/*
@@ -8849,10 +8877,44 @@
88498877
** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)).
88508878
*/
88518879
SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
88528880
SQLITE_API void sqlite3_str_free(sqlite3_str*);
88538881
8882
+/*
8883
+** CAPI3REF: Return A Dynamic String From an SQL Function
8884
+**
8885
+** The [sqlite3_result_str(C,S,F)] interface causes the
8886
+** [sqlite3_str|dynamic string] S to become the return value for the
8887
+** application-defined function or virtual table that uses
8888
+** [sqlite3_context] C. The F flag can be one of [SQLITE_COPY]
8889
+** or [SQLITE_XFER] or [SQLITE_FINISH].
8890
+**
8891
+** If the dynamic string is invalid or incomplete due to an out-of-memory
8892
+** or string-too-large error, then this routine transfers that error
8893
+** over to the SQL function.
8894
+**
8895
+** If the F argument is SQLITE_COPY, then a copy of the dynamic string
8896
+** content is made and the dynamic string object is unchanged.
8897
+** If the F argument is SQLITE_XFER, then ownership of the content
8898
+** in the dynamic is transferred to the SQL function (via a pointer copy
8899
+** rather than a string copy) and the dynamic string is reset to an
8900
+** empty string. The SQLITE_FINISH value for F works like SQLITE_RESET
8901
+** except that it also invokes the [sqlite3_str_free(S)] destructor
8902
+** on the dynamic string object.
8903
+*/
8904
+SQLITE_API void sqlite3_result_str(sqlite3_context*, sqlite3_str*, int);
8905
+
8906
+/*
8907
+** CAPI3REF: Control Flags For sqlite3_result_str()
8908
+**
8909
+** The following integers can be used as the third "F" argument
8910
+** to [sqlite3_result_str(C,S,F)].
8911
+*/
8912
+#define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */
8913
+#define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */
8914
+#define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */
8915
+
88548916
/*
88558917
** CAPI3REF: Add Content To A Dynamic String
88568918
** METHOD: sqlite3_str
88578919
**
88588920
** These interfaces add or remove content to an sqlite3_str object
88598921
--- 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.54.0"
150 #define SQLITE_VERSION_NUMBER 3054000
151 #define SQLITE_SOURCE_ID "2026-06-16 13:43:08 3f3fb9b638f59ad982beafb7c117f24ddd3da612e62c862510805fa672ffae06"
152 #define SQLITE_SCM_BRANCH "trunk"
153 #define SQLITE_SCM_TAGS ""
154 #define SQLITE_SCM_DATETIME "2026-06-16T13:43:08.110Z"
155
156 /*
157 ** CAPI3REF: Run-Time Library Version Numbers
158 ** KEYWORDS: sqlite3_version sqlite3_sourceid
159 **
@@ -3411,11 +3411,11 @@
3411 ** authorizer will fail with an error message explaining that
3412 ** access is denied.
3413 **
3414 ** ^The first parameter to the authorizer callback is a copy of the third
3415 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3416 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
3417 ** the particular action to be authorized. ^The third through sixth parameters
3418 ** to the callback are either NULL pointers or zero-terminated strings
3419 ** that contain additional details about the action to be authorized.
3420 ** Applications must always be prepared to encounter a NULL pointer in any
3421 ** of the third through the sixth parameters of the authorization callback.
@@ -3454,25 +3454,37 @@
3454 ** ^(Only a single authorizer can be in place on a database connection
3455 ** at a time. Each call to sqlite3_set_authorizer overrides the
3456 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3457 ** The authorizer is disabled by default.
3458 **
3459 ** The authorizer callback must not do anything that will modify
 
 
3460 ** the database connection that invoked the authorizer callback.
3461 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3462 ** database connections for the meaning of "modify" in this paragraph.
3463 **
3464 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3465 ** statement might be re-prepared during [sqlite3_step()] due to a
3466 ** schema change. Hence, the application should ensure that the
3467 ** correct authorizer callback remains in place during the [sqlite3_step()].
3468 **
3469 ** ^Note that the authorizer callback is invoked only during
3470 ** [sqlite3_prepare()] or its variants. Authorization is not
3471 ** performed during statement evaluation in [sqlite3_step()], unless
3472 ** as stated in the previous paragraph, sqlite3_step() invokes
3473 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
 
 
 
 
 
 
 
 
 
 
3474 */
3475 SQLITE_API int sqlite3_set_authorizer(
3476 sqlite3*,
3477 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3478 void *pUserData
@@ -3543,12 +3555,17 @@
3543 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3544 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3545 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3546 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3547 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3548 #define SQLITE_COPY 0 /* No longer used */
3549 #define SQLITE_RECURSIVE 33 /* NULL NULL */
 
 
 
 
 
 
3550
3551 /*
3552 ** CAPI3REF: Deprecated Tracing And Profiling Functions
3553 ** DEPRECATED
3554 **
@@ -4413,10 +4430,14 @@
4413 ** nesting depth for separate triggers.</dd>)^
4414 **
4415 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4416 ** <dd>The maximum number of auxiliary worker threads that a single
4417 ** [prepared statement] may start.</dd>)^
 
 
 
 
4418 ** </dl>
4419 */
4420 #define SQLITE_LIMIT_LENGTH 0
4421 #define SQLITE_LIMIT_SQL_LENGTH 1
4422 #define SQLITE_LIMIT_COLUMN 2
@@ -4428,10 +4449,11 @@
4428 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
4429 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
4430 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
4431 #define SQLITE_LIMIT_WORKER_THREADS 11
4432 #define SQLITE_LIMIT_PARSER_DEPTH 12
 
4433
4434 /*
4435 ** CAPI3REF: Prepare Flags
4436 **
4437 ** These constants define various flags that can be passed into the
@@ -4539,10 +4561,12 @@
4539 ** there is a small performance advantage to passing an nByte parameter that
4540 ** is the number of bytes in the input string <i>including</i>
4541 ** the nul-terminator.
4542 ** Note that nByte measures the length of the input in bytes, not
4543 ** characters, even for the UTF-16 interfaces.
 
 
4544 **
4545 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4546 ** past the end of the first SQL statement in zSql. These routines only
4547 ** compile the first statement in zSql, so *pzTail is left pointing to
4548 ** what remains uncompiled.
@@ -5285,11 +5309,11 @@
5285 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5286 ** can be obtained by calling [sqlite3_reset()] on the
5287 ** [prepared statement]. ^In the "v2" interface,
5288 ** the more specific error code is returned directly by sqlite3_step().
5289 **
5290 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5291 ** Perhaps it was called on a [prepared statement] that has
5292 ** already been [sqlite3_finalize | finalized] or on one that had
5293 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5294 ** be the case that the same database connection is being used by two or
5295 ** more threads at the same moment in time.
@@ -6458,11 +6482,15 @@
6458 ** to by the second parameter and which is N bytes long where N is the
6459 ** third parameter.
6460 **
6461 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6462 ** interfaces set the result of the application-defined function to be
6463 ** a BLOB containing all zero bytes and N bytes in size.
 
 
 
 
6464 **
6465 ** ^The sqlite3_result_double() interface sets the result from
6466 ** an application-defined function to be a floating point value specified
6467 ** by its 2nd argument.
6468 **
@@ -8796,12 +8824,12 @@
8796 ** The lifecycle of an sqlite3_str object is as follows:
8797 ** <ol>
8798 ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
8799 ** <li> ^Text is appended to the sqlite3_str object using various
8800 ** methods, such as [sqlite3_str_appendf()].
8801 ** <li> ^The sqlite3_str object is destroyed and the string it created
8802 ** is returned using the [sqlite3_str_finish()] interface.
8803 ** </ol>
8804 */
8805 typedef struct sqlite3_str sqlite3_str;
8806
8807 /*
@@ -8849,10 +8877,44 @@
8849 ** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)).
8850 */
8851 SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
8852 SQLITE_API void sqlite3_str_free(sqlite3_str*);
8853
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8854 /*
8855 ** CAPI3REF: Add Content To A Dynamic String
8856 ** METHOD: sqlite3_str
8857 **
8858 ** These interfaces add or remove content to an sqlite3_str object
8859
--- 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.54.0"
150 #define SQLITE_VERSION_NUMBER 3054000
151 #define SQLITE_SOURCE_ID "2026-07-24 16:28:47 2f1f4f73535386549c12694dc57cfe555eec689ae6824c6241aaf8d5befcd74d"
152 #define SQLITE_SCM_BRANCH "trunk"
153 #define SQLITE_SCM_TAGS ""
154 #define SQLITE_SCM_DATETIME "2026-07-24T16:28:47.830Z"
155
156 /*
157 ** CAPI3REF: Run-Time Library Version Numbers
158 ** KEYWORDS: sqlite3_version sqlite3_sourceid
159 **
@@ -3411,11 +3411,11 @@
3411 ** authorizer will fail with an error message explaining that
3412 ** access is denied.
3413 **
3414 ** ^The first parameter to the authorizer callback is a copy of the third
3415 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3416 ** to the callback is an integer [SQLITE_READ | action code] that specifies
3417 ** the particular action to be authorized. ^The third through sixth parameters
3418 ** to the callback are either NULL pointers or zero-terminated strings
3419 ** that contain additional details about the action to be authorized.
3420 ** Applications must always be prepared to encounter a NULL pointer in any
3421 ** of the third through the sixth parameters of the authorization callback.
@@ -3454,25 +3454,37 @@
3454 ** ^(Only a single authorizer can be in place on a database connection
3455 ** at a time. Each call to sqlite3_set_authorizer overrides the
3456 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
3457 ** The authorizer is disabled by default.
3458 **
3459 ** <h3>Limitations And Caveats</h3><ul>
3460 **
3461 ** <li>The authorizer callback must not do anything that will modify
3462 ** the database connection that invoked the authorizer callback.
3463 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3464 ** database connections for the meaning of "modify" in this paragraph.
3465 **
3466 ** <li>^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3467 ** statement might be re-prepared during [sqlite3_step()] due to a
3468 ** schema change. Hence, the application should ensure that the
3469 ** correct authorizer callback remains in place during the [sqlite3_step()].
3470 **
3471 ** <li>^The authorizer callback is invoked only during
3472 ** [sqlite3_prepare()] or its variants. Authorization is not
3473 ** performed during statement evaluation in [sqlite3_step()], unless
3474 ** as stated in the previous paragraph, sqlite3_step() invokes
3475 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3476 **
3477 ** <li>Authorizer callbacks for the expressions of a
3478 ** [generated column] are invoked when the schema is parsed (and specifically
3479 ** when the [CREATE TABLE] statement that contains the generated column is
3480 ** parsed) not when the generated column is used in a DML statement.
3481 ** This is deliberate, as one of the purposes of generated columns
3482 ** is to give schema designers the ability to provide gated access
3483 ** to privileged columns and/or functions.
3484 **
3485 ** </ul>
3486 */
3487 SQLITE_API int sqlite3_set_authorizer(
3488 sqlite3*,
3489 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3490 void *pUserData
@@ -3543,12 +3555,17 @@
3555 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3556 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3557 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3558 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3559 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
 
3560 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3561
3562 /*
3563 ** Note: The SQLITE_COPY macro (with value 0) used to be one of the
3564 ** action codes above. That macro has now been repurposed as a possible
3565 ** value to the 3rd argument to sqlite3_result_str().
3566 */
3567
3568 /*
3569 ** CAPI3REF: Deprecated Tracing And Profiling Functions
3570 ** DEPRECATED
3571 **
@@ -4413,10 +4430,14 @@
4430 ** nesting depth for separate triggers.</dd>)^
4431 **
4432 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4433 ** <dd>The maximum number of auxiliary worker threads that a single
4434 ** [prepared statement] may start.</dd>)^
4435 **
4436 ** [[SQLITE_LIMIT_SCHEMA]] ^(<dt>SQLITE_LIMIT_SCHEMA</dt>
4437 ** <dd>The maximum number of objects (tables, indexes, triggers, and views)
4438 ** defined by the database schema.</dd>)^
4439 ** </dl>
4440 */
4441 #define SQLITE_LIMIT_LENGTH 0
4442 #define SQLITE_LIMIT_SQL_LENGTH 1
4443 #define SQLITE_LIMIT_COLUMN 2
@@ -4428,10 +4449,11 @@
4449 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
4450 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
4451 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
4452 #define SQLITE_LIMIT_WORKER_THREADS 11
4453 #define SQLITE_LIMIT_PARSER_DEPTH 12
4454 #define SQLITE_LIMIT_SCHEMA 13
4455
4456 /*
4457 ** CAPI3REF: Prepare Flags
4458 **
4459 ** These constants define various flags that can be passed into the
@@ -4539,10 +4561,12 @@
4561 ** there is a small performance advantage to passing an nByte parameter that
4562 ** is the number of bytes in the input string <i>including</i>
4563 ** the nul-terminator.
4564 ** Note that nByte measures the length of the input in bytes, not
4565 ** characters, even for the UTF-16 interfaces.
4566 ** For the sqlite3_prepare16() and sqlite3_prepare16_v2() interfaces,
4567 ** the nByte value must be even or undefined behavior can result.
4568 **
4569 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4570 ** past the end of the first SQL statement in zSql. These routines only
4571 ** compile the first statement in zSql, so *pzTail is left pointing to
4572 ** what remains uncompiled.
@@ -5285,11 +5309,11 @@
5309 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5310 ** can be obtained by calling [sqlite3_reset()] on the
5311 ** [prepared statement]. ^In the "v2" interface,
5312 ** the more specific error code is returned directly by sqlite3_step().
5313 **
5314 ** [SQLITE_MISUSE] means that this routine was called inappropriately.
5315 ** Perhaps it was called on a [prepared statement] that has
5316 ** already been [sqlite3_finalize | finalized] or on one that had
5317 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
5318 ** be the case that the same database connection is being used by two or
5319 ** more threads at the same moment in time.
@@ -6458,11 +6482,15 @@
6482 ** to by the second parameter and which is N bytes long where N is the
6483 ** third parameter.
6484 **
6485 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6486 ** interfaces set the result of the application-defined function to be
6487 ** a BLOB containing all zero bytes and N bytes in size. The
6488 ** zeroblob64(C,N) interface returns a [result code], which is normally
6489 ** [SQLITE_OK] but might be some other value if the requested operation
6490 ** could not be complete, for example if insufficient memory is available
6491 ** or if the value of N is out of range.
6492 **
6493 ** ^The sqlite3_result_double() interface sets the result from
6494 ** an application-defined function to be a floating point value specified
6495 ** by its 2nd argument.
6496 **
@@ -8796,12 +8824,12 @@
8824 ** The lifecycle of an sqlite3_str object is as follows:
8825 ** <ol>
8826 ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
8827 ** <li> ^Text is appended to the sqlite3_str object using various
8828 ** methods, such as [sqlite3_str_appendf()].
8829 ** <li> The sqlite3_str object is destroyed and the string it created
8830 ** is returned using [sqlite3_str_finish()] or [sqlite3_result_str()].
8831 ** </ol>
8832 */
8833 typedef struct sqlite3_str sqlite3_str;
8834
8835 /*
@@ -8849,10 +8877,44 @@
8877 ** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)).
8878 */
8879 SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
8880 SQLITE_API void sqlite3_str_free(sqlite3_str*);
8881
8882 /*
8883 ** CAPI3REF: Return A Dynamic String From an SQL Function
8884 **
8885 ** The [sqlite3_result_str(C,S,F)] interface causes the
8886 ** [sqlite3_str|dynamic string] S to become the return value for the
8887 ** application-defined function or virtual table that uses
8888 ** [sqlite3_context] C. The F flag can be one of [SQLITE_COPY]
8889 ** or [SQLITE_XFER] or [SQLITE_FINISH].
8890 **
8891 ** If the dynamic string is invalid or incomplete due to an out-of-memory
8892 ** or string-too-large error, then this routine transfers that error
8893 ** over to the SQL function.
8894 **
8895 ** If the F argument is SQLITE_COPY, then a copy of the dynamic string
8896 ** content is made and the dynamic string object is unchanged.
8897 ** If the F argument is SQLITE_XFER, then ownership of the content
8898 ** in the dynamic is transferred to the SQL function (via a pointer copy
8899 ** rather than a string copy) and the dynamic string is reset to an
8900 ** empty string. The SQLITE_FINISH value for F works like SQLITE_RESET
8901 ** except that it also invokes the [sqlite3_str_free(S)] destructor
8902 ** on the dynamic string object.
8903 */
8904 SQLITE_API void sqlite3_result_str(sqlite3_context*, sqlite3_str*, int);
8905
8906 /*
8907 ** CAPI3REF: Control Flags For sqlite3_result_str()
8908 **
8909 ** The following integers can be used as the third "F" argument
8910 ** to [sqlite3_result_str(C,S,F)].
8911 */
8912 #define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */
8913 #define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */
8914 #define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */
8915
8916 /*
8917 ** CAPI3REF: Add Content To A Dynamic String
8918 ** METHOD: sqlite3_str
8919 **
8920 ** These interfaces add or remove content to an sqlite3_str object
8921
--- src/builtin.c
+++ src/builtin.c
@@ -698,10 +698,22 @@
698698
CX("isAdmin: %s,", JBOOL(g.perm.Admin || g.perm.Setup));
699699
CX("mayAttachForum: %s,", JBOOL(g.perm.AttachForum));
700700
CX("enableDebug: %s,", JBOOL(g.perm.Debug || g.perm.Admin));
701701
CX("isIndividual: %s", JBOOL(login_is_individual()));
702702
CX("};\n"/*fossil.user*/);
703
+ { /* Workaround for cases like:
704
+ ** https://fossil-scm.org/forum/forumpost/31cc00b361496cb8
705
+ ** Summary: custom skins which emit their own BODY need to have
706
+ ** the BODY element's CSS classes set so that various CSS selectors
707
+ ** and JS-side filters will work. */
708
+ char *pSlash = strchr(g.zPath,'/')/*hack taken from style.c*/;
709
+ if( pSlash ) *pSlash = 0;
710
+ CX("for(const x of [%!j, \"rpage-%j\",\"cpage-%j\"]) {"
711
+ "if(x) document.body.classList.add(x);};\n",
712
+ style_get_current_feature(), g.zPath, g.zPhase+1);
713
+ if( pSlash ) *pSlash = '/';
714
+ }
703715
CX("if(fossil.config.skin.isDark) "
704716
"document.body.classList.add('fossil-dark-style');\n");
705717
/*
706718
** fossil.page holds info about the current page. This is also
707719
** where the current page "should" store any of its own
708720
--- src/builtin.c
+++ src/builtin.c
@@ -698,10 +698,22 @@
698 CX("isAdmin: %s,", JBOOL(g.perm.Admin || g.perm.Setup));
699 CX("mayAttachForum: %s,", JBOOL(g.perm.AttachForum));
700 CX("enableDebug: %s,", JBOOL(g.perm.Debug || g.perm.Admin));
701 CX("isIndividual: %s", JBOOL(login_is_individual()));
702 CX("};\n"/*fossil.user*/);
 
 
 
 
 
 
 
 
 
 
 
 
703 CX("if(fossil.config.skin.isDark) "
704 "document.body.classList.add('fossil-dark-style');\n");
705 /*
706 ** fossil.page holds info about the current page. This is also
707 ** where the current page "should" store any of its own
708
--- src/builtin.c
+++ src/builtin.c
@@ -698,10 +698,22 @@
698 CX("isAdmin: %s,", JBOOL(g.perm.Admin || g.perm.Setup));
699 CX("mayAttachForum: %s,", JBOOL(g.perm.AttachForum));
700 CX("enableDebug: %s,", JBOOL(g.perm.Debug || g.perm.Admin));
701 CX("isIndividual: %s", JBOOL(login_is_individual()));
702 CX("};\n"/*fossil.user*/);
703 { /* Workaround for cases like:
704 ** https://fossil-scm.org/forum/forumpost/31cc00b361496cb8
705 ** Summary: custom skins which emit their own BODY need to have
706 ** the BODY element's CSS classes set so that various CSS selectors
707 ** and JS-side filters will work. */
708 char *pSlash = strchr(g.zPath,'/')/*hack taken from style.c*/;
709 if( pSlash ) *pSlash = 0;
710 CX("for(const x of [%!j, \"rpage-%j\",\"cpage-%j\"]) {"
711 "if(x) document.body.classList.add(x);};\n",
712 style_get_current_feature(), g.zPath, g.zPhase+1);
713 if( pSlash ) *pSlash = '/';
714 }
715 CX("if(fossil.config.skin.isDark) "
716 "document.body.classList.add('fossil-dark-style');\n");
717 /*
718 ** fossil.page holds info about the current page. This is also
719 ** where the current page "should" store any of its own
720
--- src/configure.c
+++ src/configure.c
@@ -144,10 +144,11 @@
144144
{ "comment-format", CONFIGSET_PROJ },
145145
{ "mimetypes", CONFIGSET_PROJ },
146146
{ "forbid-delta-manifests", CONFIGSET_PROJ },
147147
{ "mv-rm-files", CONFIGSET_PROJ },
148148
{ "forum-statuses", CONFIGSET_PROJ },
149
+ { "path-to-tag", CONFIGSET_PROJ },
149150
{ "ticket-table", CONFIGSET_TKT },
150151
{ "ticket-common", CONFIGSET_TKT },
151152
{ "ticket-change", CONFIGSET_TKT },
152153
{ "ticket-newpage", CONFIGSET_TKT },
153154
{ "ticket-viewpage", CONFIGSET_TKT },
154155
--- src/configure.c
+++ src/configure.c
@@ -144,10 +144,11 @@
144 { "comment-format", CONFIGSET_PROJ },
145 { "mimetypes", CONFIGSET_PROJ },
146 { "forbid-delta-manifests", CONFIGSET_PROJ },
147 { "mv-rm-files", CONFIGSET_PROJ },
148 { "forum-statuses", CONFIGSET_PROJ },
 
149 { "ticket-table", CONFIGSET_TKT },
150 { "ticket-common", CONFIGSET_TKT },
151 { "ticket-change", CONFIGSET_TKT },
152 { "ticket-newpage", CONFIGSET_TKT },
153 { "ticket-viewpage", CONFIGSET_TKT },
154
--- src/configure.c
+++ src/configure.c
@@ -144,10 +144,11 @@
144 { "comment-format", CONFIGSET_PROJ },
145 { "mimetypes", CONFIGSET_PROJ },
146 { "forbid-delta-manifests", CONFIGSET_PROJ },
147 { "mv-rm-files", CONFIGSET_PROJ },
148 { "forum-statuses", CONFIGSET_PROJ },
149 { "path-to-tag", CONFIGSET_PROJ },
150 { "ticket-table", CONFIGSET_TKT },
151 { "ticket-common", CONFIGSET_TKT },
152 { "ticket-change", CONFIGSET_TKT },
153 { "ticket-newpage", CONFIGSET_TKT },
154 { "ticket-viewpage", CONFIGSET_TKT },
155
+3 -3
--- src/delta.c
+++ src/delta.c
@@ -602,11 +602,11 @@
602602
if( lenDelta<=0 ) return -1;
603603
switch( zDelta[0] ){
604604
case '@': {
605605
zDelta++; lenDelta--;
606606
ofst = getInt(&zDelta, &lenDelta);
607
- if( lenDelta<=0 || zDelta[0]!=',' ){
607
+ if( lenDelta>0 && zDelta[0]!=',' ){
608608
/* ERROR: copy command not terminated by ',' */
609609
return -1;
610610
}
611611
zDelta++; lenDelta--;
612612
DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
@@ -629,11 +629,11 @@
629629
if( total>limit ){
630630
/* ERROR: insert command gives an output larger than predicted */
631631
return -1;
632632
}
633633
DEBUG1( printf("INSERT %d\n", cnt); )
634
- if( (i64)cnt>(i64)lenDelta ){
634
+ if( cnt>lenDelta ){
635635
/* ERROR: insert count exceeds size of delta */
636636
return -1;
637637
}
638638
memcpy(zOut, zDelta, cnt);
639639
zOut += cnt;
@@ -684,11 +684,11 @@
684684
if( lenDelta<=0 || *zDelta!='\n' ){
685685
/* ERROR: size integer not terminated by "\n" */
686686
return -1;
687687
}
688688
zDelta++; lenDelta--;
689
- while( *zDelta && lenDelta>0 ){
689
+ while( lenDelta>0 && *zDelta ){
690690
unsigned int cnt;
691691
cnt = getInt(&zDelta, &lenDelta);
692692
if( lenDelta<=0 ) break;
693693
switch( zDelta[0] ){
694694
case '@': {
695695
--- src/delta.c
+++ src/delta.c
@@ -602,11 +602,11 @@
602 if( lenDelta<=0 ) return -1;
603 switch( zDelta[0] ){
604 case '@': {
605 zDelta++; lenDelta--;
606 ofst = getInt(&zDelta, &lenDelta);
607 if( lenDelta<=0 || zDelta[0]!=',' ){
608 /* ERROR: copy command not terminated by ',' */
609 return -1;
610 }
611 zDelta++; lenDelta--;
612 DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
@@ -629,11 +629,11 @@
629 if( total>limit ){
630 /* ERROR: insert command gives an output larger than predicted */
631 return -1;
632 }
633 DEBUG1( printf("INSERT %d\n", cnt); )
634 if( (i64)cnt>(i64)lenDelta ){
635 /* ERROR: insert count exceeds size of delta */
636 return -1;
637 }
638 memcpy(zOut, zDelta, cnt);
639 zOut += cnt;
@@ -684,11 +684,11 @@
684 if( lenDelta<=0 || *zDelta!='\n' ){
685 /* ERROR: size integer not terminated by "\n" */
686 return -1;
687 }
688 zDelta++; lenDelta--;
689 while( *zDelta && lenDelta>0 ){
690 unsigned int cnt;
691 cnt = getInt(&zDelta, &lenDelta);
692 if( lenDelta<=0 ) break;
693 switch( zDelta[0] ){
694 case '@': {
695
--- src/delta.c
+++ src/delta.c
@@ -602,11 +602,11 @@
602 if( lenDelta<=0 ) return -1;
603 switch( zDelta[0] ){
604 case '@': {
605 zDelta++; lenDelta--;
606 ofst = getInt(&zDelta, &lenDelta);
607 if( lenDelta>0 && zDelta[0]!=',' ){
608 /* ERROR: copy command not terminated by ',' */
609 return -1;
610 }
611 zDelta++; lenDelta--;
612 DEBUG1( printf("COPY %d from %d\n", cnt, ofst); )
@@ -629,11 +629,11 @@
629 if( total>limit ){
630 /* ERROR: insert command gives an output larger than predicted */
631 return -1;
632 }
633 DEBUG1( printf("INSERT %d\n", cnt); )
634 if( cnt>lenDelta ){
635 /* ERROR: insert count exceeds size of delta */
636 return -1;
637 }
638 memcpy(zOut, zDelta, cnt);
639 zOut += cnt;
@@ -684,11 +684,11 @@
684 if( lenDelta<=0 || *zDelta!='\n' ){
685 /* ERROR: size integer not terminated by "\n" */
686 return -1;
687 }
688 zDelta++; lenDelta--;
689 while( lenDelta>0 && *zDelta ){
690 unsigned int cnt;
691 cnt = getInt(&zDelta, &lenDelta);
692 if( lenDelta<=0 ) break;
693 switch( zDelta[0] ){
694 case '@': {
695
+6 -2
--- src/forum.c
+++ src/forum.c
@@ -1307,12 +1307,14 @@
13071307
}
13081308
}else if( g.perm.ModForum ){
13091309
/* Allow moderators to approve or reject pending posts. Also allow
13101310
** forum supervisors to mark non-special users as trusted and therefore
13111311
** able to post unmoderated. */
1312
- @ <input type="submit" name="approve" value="Approve">
1313
- @ <input type="submit" name="reject" value="Reject">
1312
+ @ <input type="submit" name="approve" value="Approve" \
1313
+ @ class="action-approve">\
1314
+ @ <input type="submit" name="reject" value="Reject" \
1315
+ @ class="action-reject">\
13141316
if( g.perm.AdminForum && !login_is_special(pManifest->zUser) ){
13151317
@ <br><label><input type="checkbox" name="trust">
13161318
@ Trust user "%h(pManifest->zUser)" so that future posts by \
13171319
@ "%h(pManifest->zUser)" do not require moderation.
13181320
@ </label>
@@ -1606,10 +1608,11 @@
16061608
login_needed(g.anon.RdForum);
16071609
return;
16081610
}
16091611
if( zName==0 ){
16101612
webpage_error("Missing \"name=\" query parameter");
1613
+ return;
16111614
}
16121615
cgi_check_for_malice();
16131616
fpid = symbolic_name_to_rid(zName, "f");
16141617
if( fpid<=0 ){
16151618
if( fpid==0 ){
@@ -1620,10 +1623,11 @@
16201623
return;
16211624
}
16221625
froot = db_int(0, "SELECT froot FROM forumpost WHERE fpid=%d", fpid);
16231626
if( froot==0 ){
16241627
webpage_notfound_error("Not a forum post: \"%s\"", zName);
1628
+ return;
16251629
}
16261630
16271631
/* Decode the mode parameters. */
16281632
if( bRaw ){
16291633
mode = FD_RAW;
16301634
--- src/forum.c
+++ src/forum.c
@@ -1307,12 +1307,14 @@
1307 }
1308 }else if( g.perm.ModForum ){
1309 /* Allow moderators to approve or reject pending posts. Also allow
1310 ** forum supervisors to mark non-special users as trusted and therefore
1311 ** able to post unmoderated. */
1312 @ <input type="submit" name="approve" value="Approve">
1313 @ <input type="submit" name="reject" value="Reject">
 
 
1314 if( g.perm.AdminForum && !login_is_special(pManifest->zUser) ){
1315 @ <br><label><input type="checkbox" name="trust">
1316 @ Trust user "%h(pManifest->zUser)" so that future posts by \
1317 @ "%h(pManifest->zUser)" do not require moderation.
1318 @ </label>
@@ -1606,10 +1608,11 @@
1606 login_needed(g.anon.RdForum);
1607 return;
1608 }
1609 if( zName==0 ){
1610 webpage_error("Missing \"name=\" query parameter");
 
1611 }
1612 cgi_check_for_malice();
1613 fpid = symbolic_name_to_rid(zName, "f");
1614 if( fpid<=0 ){
1615 if( fpid==0 ){
@@ -1620,10 +1623,11 @@
1620 return;
1621 }
1622 froot = db_int(0, "SELECT froot FROM forumpost WHERE fpid=%d", fpid);
1623 if( froot==0 ){
1624 webpage_notfound_error("Not a forum post: \"%s\"", zName);
 
1625 }
1626
1627 /* Decode the mode parameters. */
1628 if( bRaw ){
1629 mode = FD_RAW;
1630
--- src/forum.c
+++ src/forum.c
@@ -1307,12 +1307,14 @@
1307 }
1308 }else if( g.perm.ModForum ){
1309 /* Allow moderators to approve or reject pending posts. Also allow
1310 ** forum supervisors to mark non-special users as trusted and therefore
1311 ** able to post unmoderated. */
1312 @ <input type="submit" name="approve" value="Approve" \
1313 @ class="action-approve">\
1314 @ <input type="submit" name="reject" value="Reject" \
1315 @ class="action-reject">\
1316 if( g.perm.AdminForum && !login_is_special(pManifest->zUser) ){
1317 @ <br><label><input type="checkbox" name="trust">
1318 @ Trust user "%h(pManifest->zUser)" so that future posts by \
1319 @ "%h(pManifest->zUser)" do not require moderation.
1320 @ </label>
@@ -1606,10 +1608,11 @@
1608 login_needed(g.anon.RdForum);
1609 return;
1610 }
1611 if( zName==0 ){
1612 webpage_error("Missing \"name=\" query parameter");
1613 return;
1614 }
1615 cgi_check_for_malice();
1616 fpid = symbolic_name_to_rid(zName, "f");
1617 if( fpid<=0 ){
1618 if( fpid==0 ){
@@ -1620,10 +1623,11 @@
1623 return;
1624 }
1625 froot = db_int(0, "SELECT froot FROM forumpost WHERE fpid=%d", fpid);
1626 if( froot==0 ){
1627 webpage_notfound_error("Not a forum post: \"%s\"", zName);
1628 return;
1629 }
1630
1631 /* Decode the mode parameters. */
1632 if( bRaw ){
1633 mode = FD_RAW;
1634
--- src/fossil.page.forumpost.js
+++ src/fossil.page.forumpost.js
@@ -171,11 +171,11 @@
171171
D.button("Preview", e=>this.#preview()),
172172
'title',
173173
'Preview your edits.'
174174
);
175175
e.button.submit = D.attr(
176
- D.button("Submit"),
176
+ D.button("Post as "+F.user.name),
177177
'title',
178178
'Save any edits to the server. Not permitted until Preview has been used.'
179179
);
180180
if( this.#draft && !opt.hideStash ){
181181
e.button.stash = D.attr(
@@ -251,10 +251,27 @@
251251
e.editor = D.attr(
252252
D.addClass(D.textarea(), 'editor'),
253253
'placeholder',
254254
'Your message to other forum-goers...'
255255
);
256
+ if( opt.inReplyTo && !F.user.isIndividual ){
257
+ const w = D.addClass(D.div(), 'warning');
258
+ w.append(
259
+ "You are not ",
260
+ D.a(F.repoUrl(
261
+ 'login'
262
+ /*, {
263
+ // Leads to a confusing 'you need more permissions
264
+ // to view /forumpost/.... warning
265
+ g: 'forumpost/'+(opt.inReplyTo || opt.edit?.uuid)
266
+ }*/
267
+ ), 'logged in'), ' so will be posting anonymously. ',
268
+ "If you log in then return here, your draft edit will ",
269
+ "still be here."
270
+ );
271
+ e.tabEdit.append(w);
272
+ }
256273
e.tabEdit.append(e.editor);
257274
e.tabEdit.dataset.tabLabel = (opt.edit || !opt.inReplyTo)
258275
? 'Edit' : 'Reply';
259276
this.#tabs.addTab( e.tabEdit );
260277
this.#tabs.switchToTab( e.tabEdit );
@@ -416,11 +433,12 @@
416433
}
417434
});
418435
e.buttons.append(e.button.toggleHeader);
419436
}
420437
421
- {
438
+ if(0){
439
+ // Tentatively replaced with the user name in the Submit button
422440
const eLbl = D.label(false, "Posting as "+F.user.name)
423441
eLbl.classList.add('logged-in-as');
424442
e.buttons.append(eLbl);
425443
}
426444
@@ -538,11 +556,16 @@
538556
#initHelpTab(){
539557
const eh = this.#e.help;
540558
const list = D.ul();
541559
D.append(
542560
D.li(list),
543
- D.attr(D.a(F.repoUrl('markup_help'), 'Markup styles'),
561
+ D.attr(D.a(F.repoUrl('md_rules'), 'Markdown markup rules'),
562
+ 'target', '_new')
563
+ );
564
+ D.append(
565
+ D.li(list),
566
+ D.attr(D.a(F.repoUrl('wiki_rules'), 'Fossil wiki markup rules'),
544567
'target', '_new')
545568
);
546569
D.append(
547570
D.li(list),
548571
"WARNING: draft edits are keyed on the ID of the message they ",
@@ -967,10 +990,33 @@
967990
state. */
968991
setTimeout(()=>{delete form.dataset.submitted}, 7000);
969992
return;
970993
};
971994
995
+ /**
996
+ The problem: "Approve", "Reject" and their ilk stays active
997
+ while their form post is in flight, just begging to be
998
+ clicked again. We don't really have a way to know when the
999
+ submit finishes, so we'll (A) disable them before submit and
1000
+ (B) reenable them after some long timeout in case the request
1001
+ fails. On a successful submit we're redirected, making this
1002
+ all moot.
1003
+ */
1004
+ const deactivateButtonInFlight = (elem, form)=>{
1005
+ if( elem.disabled ) return /* potential double-click protection */;
1006
+ elem.disabled = true;
1007
+ setTimeout(
1008
+ /* This is a stupid workaround for a failed request but none
1009
+ better come to mind except replacing the form.submit()
1010
+ with a fetch() POST, such that we can do this at
1011
+ precisely the right time. That change would not be
1012
+ difficult (we do this in /chat, /wikiedit, etc.) but
1013
+ that exceeds this morning's ambitions. */
1014
+ ()=>elem.disabled = false, 10000
1015
+ );
1016
+ form.submit();
1017
+ };
9721018
document.querySelectorAll("form").forEach(function(form){
9731019
/* Set up controls for closing posts and setting thread
9741020
status. */
9751021
form.addEventListener('submit', formSubmitted);
9761022
form
@@ -979,17 +1025,42 @@
9791025
e.classList.remove('hidden');
9801026
F.confirmer(e, {
9811027
confirmText: (e.classList.contains('action-reopen')
9821028
? "Confirm re-open"
9831029
: "Confirm close"),
984
- onconfirm: ()=>form.submit()
1030
+ onconfirm: ()=>deactivateButtonInFlight(e, form)
1031
+ });
1032
+ });
1033
+ form
1034
+ .querySelectorAll("input.action-approve, input.action-reject")
1035
+ .forEach(function(e){
1036
+ e.type = 'button'/*do not submit form on click*/;
1037
+ const isApprove = e.classList.contains('action-approve');
1038
+ F.confirmer(e, {
1039
+ confirmText: (isApprove
1040
+ ? "Confirm approval"
1041
+ : "Confirm rejection"),
1042
+ onconfirm: ()=>{
1043
+ form.append(
1044
+ /* Workaround for the button element's value not
1045
+ being sent with the form: inject a hidden field
1046
+ corresponding to the button's action. */
1047
+ D.attr(
1048
+ D.input('hidden'),
1049
+ 'name', isApprove ? 'approve' : 'reject',
1050
+ 'value', 'ignored'
1051
+ )
1052
+ );
1053
+ deactivateButtonInFlight(e, form);
1054
+ }
9851055
});
1056
+ /* We should also arguably disable the approve/reject
1057
+ button's counterpart while it's counting down. */
9861058
});
9871059
form
9881060
.querySelectorAll("input[type='button'].action-status")
9891061
.forEach(function(btn){
990
- btn.classList.remove('hidden');
9911062
const sel = btn.previousElementSibling;
9921063
const updateButton = ()=>{
9931064
/* Enable btn only when the status has been locally
9941065
modified. */
9951066
if( sel.dataset.initialValue ){
@@ -1008,11 +1079,11 @@
10081079
};
10091080
sel.addEventListener('change', updateButton, true);
10101081
updateButton();
10111082
F.confirmer(btn, {
10121083
confirmText: "Confirm status change",
1013
- onconfirm: ()=>form.submit()
1084
+ onconfirm: ()=>deactivateButtonInFlight(btn, form)
10141085
});
10151086
});
10161087
});
10171088
}
10181089
@@ -1155,27 +1226,47 @@
11551226
value here). */
11561227
|| fpid
11571228
);
11581229
let releaseLock;
11591230
if( window.navigator.locks ){
1231
+ /* This business with forceReleaseLockOnClose and 'pagehide'
1232
+ event is a workaround for Chrome being overly lazy in
1233
+ releasing Web Locks when a tab is closed. It sometimes
1234
+ waits half a minute or more before release.
1235
+
1236
+ Sidebar: we cannot use AbortController because it cannot
1237
+ be used with the ifAvailable lock check. */
1238
+ let forceReleaseLockOnClose = null;
1239
+ const handlePageHide = ()=>{
1240
+ if( forceReleaseLockOnClose ){
1241
+ forceReleaseLockOnClose();
1242
+ }
1243
+ };
1244
+ window.addEventListener('pagehide', handlePageHide);
11601245
releaseLock = await new Promise((resolve)=>{
11611246
window.navigator.locks.request(
11621247
'fossil-'+draftKey,
11631248
{ifAvailable: true},
1164
- async (lock) => {
1249
+ async (lock)=>{
11651250
if( !lock ){
11661251
/*lock contention*/
11671252
resolve(null);
11681253
return;
11691254
}
11701255
let release;
11711256
const lockReleased = new Promise(res=>release=res);
1172
- resolve(release);
1257
+ forceReleaseLockOnClose = release;
1258
+ const wrappedRelease = ()=>{
1259
+ window.removeEventListener('pagehide', handlePageHide);
1260
+ if( release ) release();
1261
+ };
1262
+ resolve(wrappedRelease);
11731263
await lockReleased/*hold the lock open*/;
11741264
});
11751265
});
11761266
if( !releaseLock ){
1267
+ window.removeEventListener('pagehide', handlePageHide);
11771268
reportFPEError(
11781269
ePost,
11791270
"This post is actively being replied to ",
11801271
"in another tab. To avoid losing edits, ",
11811272
"it cannot be opened here until the locking ",
11821273
--- src/fossil.page.forumpost.js
+++ src/fossil.page.forumpost.js
@@ -171,11 +171,11 @@
171 D.button("Preview", e=>this.#preview()),
172 'title',
173 'Preview your edits.'
174 );
175 e.button.submit = D.attr(
176 D.button("Submit"),
177 'title',
178 'Save any edits to the server. Not permitted until Preview has been used.'
179 );
180 if( this.#draft && !opt.hideStash ){
181 e.button.stash = D.attr(
@@ -251,10 +251,27 @@
251 e.editor = D.attr(
252 D.addClass(D.textarea(), 'editor'),
253 'placeholder',
254 'Your message to other forum-goers...'
255 );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256 e.tabEdit.append(e.editor);
257 e.tabEdit.dataset.tabLabel = (opt.edit || !opt.inReplyTo)
258 ? 'Edit' : 'Reply';
259 this.#tabs.addTab( e.tabEdit );
260 this.#tabs.switchToTab( e.tabEdit );
@@ -416,11 +433,12 @@
416 }
417 });
418 e.buttons.append(e.button.toggleHeader);
419 }
420
421 {
 
422 const eLbl = D.label(false, "Posting as "+F.user.name)
423 eLbl.classList.add('logged-in-as');
424 e.buttons.append(eLbl);
425 }
426
@@ -538,11 +556,16 @@
538 #initHelpTab(){
539 const eh = this.#e.help;
540 const list = D.ul();
541 D.append(
542 D.li(list),
543 D.attr(D.a(F.repoUrl('markup_help'), 'Markup styles'),
 
 
 
 
 
544 'target', '_new')
545 );
546 D.append(
547 D.li(list),
548 "WARNING: draft edits are keyed on the ID of the message they ",
@@ -967,10 +990,33 @@
967 state. */
968 setTimeout(()=>{delete form.dataset.submitted}, 7000);
969 return;
970 };
971
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
972 document.querySelectorAll("form").forEach(function(form){
973 /* Set up controls for closing posts and setting thread
974 status. */
975 form.addEventListener('submit', formSubmitted);
976 form
@@ -979,17 +1025,42 @@
979 e.classList.remove('hidden');
980 F.confirmer(e, {
981 confirmText: (e.classList.contains('action-reopen')
982 ? "Confirm re-open"
983 : "Confirm close"),
984 onconfirm: ()=>form.submit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
985 });
 
 
986 });
987 form
988 .querySelectorAll("input[type='button'].action-status")
989 .forEach(function(btn){
990 btn.classList.remove('hidden');
991 const sel = btn.previousElementSibling;
992 const updateButton = ()=>{
993 /* Enable btn only when the status has been locally
994 modified. */
995 if( sel.dataset.initialValue ){
@@ -1008,11 +1079,11 @@
1008 };
1009 sel.addEventListener('change', updateButton, true);
1010 updateButton();
1011 F.confirmer(btn, {
1012 confirmText: "Confirm status change",
1013 onconfirm: ()=>form.submit()
1014 });
1015 });
1016 });
1017 }
1018
@@ -1155,27 +1226,47 @@
1155 value here). */
1156 || fpid
1157 );
1158 let releaseLock;
1159 if( window.navigator.locks ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1160 releaseLock = await new Promise((resolve)=>{
1161 window.navigator.locks.request(
1162 'fossil-'+draftKey,
1163 {ifAvailable: true},
1164 async (lock) => {
1165 if( !lock ){
1166 /*lock contention*/
1167 resolve(null);
1168 return;
1169 }
1170 let release;
1171 const lockReleased = new Promise(res=>release=res);
1172 resolve(release);
 
 
 
 
 
1173 await lockReleased/*hold the lock open*/;
1174 });
1175 });
1176 if( !releaseLock ){
 
1177 reportFPEError(
1178 ePost,
1179 "This post is actively being replied to ",
1180 "in another tab. To avoid losing edits, ",
1181 "it cannot be opened here until the locking ",
1182
--- src/fossil.page.forumpost.js
+++ src/fossil.page.forumpost.js
@@ -171,11 +171,11 @@
171 D.button("Preview", e=>this.#preview()),
172 'title',
173 'Preview your edits.'
174 );
175 e.button.submit = D.attr(
176 D.button("Post as "+F.user.name),
177 'title',
178 'Save any edits to the server. Not permitted until Preview has been used.'
179 );
180 if( this.#draft && !opt.hideStash ){
181 e.button.stash = D.attr(
@@ -251,10 +251,27 @@
251 e.editor = D.attr(
252 D.addClass(D.textarea(), 'editor'),
253 'placeholder',
254 'Your message to other forum-goers...'
255 );
256 if( opt.inReplyTo && !F.user.isIndividual ){
257 const w = D.addClass(D.div(), 'warning');
258 w.append(
259 "You are not ",
260 D.a(F.repoUrl(
261 'login'
262 /*, {
263 // Leads to a confusing 'you need more permissions
264 // to view /forumpost/.... warning
265 g: 'forumpost/'+(opt.inReplyTo || opt.edit?.uuid)
266 }*/
267 ), 'logged in'), ' so will be posting anonymously. ',
268 "If you log in then return here, your draft edit will ",
269 "still be here."
270 );
271 e.tabEdit.append(w);
272 }
273 e.tabEdit.append(e.editor);
274 e.tabEdit.dataset.tabLabel = (opt.edit || !opt.inReplyTo)
275 ? 'Edit' : 'Reply';
276 this.#tabs.addTab( e.tabEdit );
277 this.#tabs.switchToTab( e.tabEdit );
@@ -416,11 +433,12 @@
433 }
434 });
435 e.buttons.append(e.button.toggleHeader);
436 }
437
438 if(0){
439 // Tentatively replaced with the user name in the Submit button
440 const eLbl = D.label(false, "Posting as "+F.user.name)
441 eLbl.classList.add('logged-in-as');
442 e.buttons.append(eLbl);
443 }
444
@@ -538,11 +556,16 @@
556 #initHelpTab(){
557 const eh = this.#e.help;
558 const list = D.ul();
559 D.append(
560 D.li(list),
561 D.attr(D.a(F.repoUrl('md_rules'), 'Markdown markup rules'),
562 'target', '_new')
563 );
564 D.append(
565 D.li(list),
566 D.attr(D.a(F.repoUrl('wiki_rules'), 'Fossil wiki markup rules'),
567 'target', '_new')
568 );
569 D.append(
570 D.li(list),
571 "WARNING: draft edits are keyed on the ID of the message they ",
@@ -967,10 +990,33 @@
990 state. */
991 setTimeout(()=>{delete form.dataset.submitted}, 7000);
992 return;
993 };
994
995 /**
996 The problem: "Approve", "Reject" and their ilk stays active
997 while their form post is in flight, just begging to be
998 clicked again. We don't really have a way to know when the
999 submit finishes, so we'll (A) disable them before submit and
1000 (B) reenable them after some long timeout in case the request
1001 fails. On a successful submit we're redirected, making this
1002 all moot.
1003 */
1004 const deactivateButtonInFlight = (elem, form)=>{
1005 if( elem.disabled ) return /* potential double-click protection */;
1006 elem.disabled = true;
1007 setTimeout(
1008 /* This is a stupid workaround for a failed request but none
1009 better come to mind except replacing the form.submit()
1010 with a fetch() POST, such that we can do this at
1011 precisely the right time. That change would not be
1012 difficult (we do this in /chat, /wikiedit, etc.) but
1013 that exceeds this morning's ambitions. */
1014 ()=>elem.disabled = false, 10000
1015 );
1016 form.submit();
1017 };
1018 document.querySelectorAll("form").forEach(function(form){
1019 /* Set up controls for closing posts and setting thread
1020 status. */
1021 form.addEventListener('submit', formSubmitted);
1022 form
@@ -979,17 +1025,42 @@
1025 e.classList.remove('hidden');
1026 F.confirmer(e, {
1027 confirmText: (e.classList.contains('action-reopen')
1028 ? "Confirm re-open"
1029 : "Confirm close"),
1030 onconfirm: ()=>deactivateButtonInFlight(e, form)
1031 });
1032 });
1033 form
1034 .querySelectorAll("input.action-approve, input.action-reject")
1035 .forEach(function(e){
1036 e.type = 'button'/*do not submit form on click*/;
1037 const isApprove = e.classList.contains('action-approve');
1038 F.confirmer(e, {
1039 confirmText: (isApprove
1040 ? "Confirm approval"
1041 : "Confirm rejection"),
1042 onconfirm: ()=>{
1043 form.append(
1044 /* Workaround for the button element's value not
1045 being sent with the form: inject a hidden field
1046 corresponding to the button's action. */
1047 D.attr(
1048 D.input('hidden'),
1049 'name', isApprove ? 'approve' : 'reject',
1050 'value', 'ignored'
1051 )
1052 );
1053 deactivateButtonInFlight(e, form);
1054 }
1055 });
1056 /* We should also arguably disable the approve/reject
1057 button's counterpart while it's counting down. */
1058 });
1059 form
1060 .querySelectorAll("input[type='button'].action-status")
1061 .forEach(function(btn){
 
1062 const sel = btn.previousElementSibling;
1063 const updateButton = ()=>{
1064 /* Enable btn only when the status has been locally
1065 modified. */
1066 if( sel.dataset.initialValue ){
@@ -1008,11 +1079,11 @@
1079 };
1080 sel.addEventListener('change', updateButton, true);
1081 updateButton();
1082 F.confirmer(btn, {
1083 confirmText: "Confirm status change",
1084 onconfirm: ()=>deactivateButtonInFlight(btn, form)
1085 });
1086 });
1087 });
1088 }
1089
@@ -1155,27 +1226,47 @@
1226 value here). */
1227 || fpid
1228 );
1229 let releaseLock;
1230 if( window.navigator.locks ){
1231 /* This business with forceReleaseLockOnClose and 'pagehide'
1232 event is a workaround for Chrome being overly lazy in
1233 releasing Web Locks when a tab is closed. It sometimes
1234 waits half a minute or more before release.
1235
1236 Sidebar: we cannot use AbortController because it cannot
1237 be used with the ifAvailable lock check. */
1238 let forceReleaseLockOnClose = null;
1239 const handlePageHide = ()=>{
1240 if( forceReleaseLockOnClose ){
1241 forceReleaseLockOnClose();
1242 }
1243 };
1244 window.addEventListener('pagehide', handlePageHide);
1245 releaseLock = await new Promise((resolve)=>{
1246 window.navigator.locks.request(
1247 'fossil-'+draftKey,
1248 {ifAvailable: true},
1249 async (lock)=>{
1250 if( !lock ){
1251 /*lock contention*/
1252 resolve(null);
1253 return;
1254 }
1255 let release;
1256 const lockReleased = new Promise(res=>release=res);
1257 forceReleaseLockOnClose = release;
1258 const wrappedRelease = ()=>{
1259 window.removeEventListener('pagehide', handlePageHide);
1260 if( release ) release();
1261 };
1262 resolve(wrappedRelease);
1263 await lockReleased/*hold the lock open*/;
1264 });
1265 });
1266 if( !releaseLock ){
1267 window.removeEventListener('pagehide', handlePageHide);
1268 reportFPEError(
1269 ePost,
1270 "This post is actively being replied to ",
1271 "in another tab. To avoid losing edits, ",
1272 "it cannot be opened here until the locking ",
1273
+16
--- src/info.c
+++ src/info.c
@@ -969,10 +969,21 @@
969969
ckout_normal_diff(vid);
970970
}
971971
style_finish_page();
972972
}
973973
974
+/*
975
+** SETTING: path-to-tag width=40
976
+**
977
+** If the path-to-tag setting is defined and is not an empty string
978
+** then then /info page for checking HASH will display a link to
979
+** a timeline showing an abbreviated path from the HASH check-in to
980
+** the next checkin that has a tag which is the value of this setting.
981
+**
982
+** A typical value for this setting is "release"
983
+*/
984
+
974985
/*
975986
** WEBPAGE: vinfo
976987
** WEBPAGE: ci
977988
** URL: /ci/ARTIFACTID
978989
** OR: /ci?name=ARTIFACTID
@@ -1095,11 +1106,16 @@
10951106
@ %z(href("%R/timeline?f=%!S&unhide",zUuid))family</a>
10961107
if( zParent ){
10971108
@ | %z(href("%R/timeline?p=%!S&unhide",zUuid))ancestors</a>
10981109
}
10991110
if( !isLeaf ){
1111
+ char *zPathTo = db_get("path-to-tag",0);
11001112
@ | %z(href("%R/timeline?d=%!S&unhide",zUuid))descendants</a>
1113
+ if( zPathTo!=0 && zPathTo[0]!=0 ){
1114
+ @ | %z(href("%R/timeline?from=%!S&ft=%t&min",zUuid,zPathTo))\
1115
+ @ path-to-%h(zPathTo)</a>
1116
+ }
11011117
}
11021118
if( zParent && !isLeaf ){
11031119
@ | %z(href("%R/timeline?dp=%!S&unhide",zUuid))both</a>
11041120
}
11051121
db_prepare(&q2,"SELECT substr(tag.tagname,5) FROM tagxref, tag "
11061122
--- src/info.c
+++ src/info.c
@@ -969,10 +969,21 @@
969 ckout_normal_diff(vid);
970 }
971 style_finish_page();
972 }
973
 
 
 
 
 
 
 
 
 
 
 
974 /*
975 ** WEBPAGE: vinfo
976 ** WEBPAGE: ci
977 ** URL: /ci/ARTIFACTID
978 ** OR: /ci?name=ARTIFACTID
@@ -1095,11 +1106,16 @@
1095 @ %z(href("%R/timeline?f=%!S&unhide",zUuid))family</a>
1096 if( zParent ){
1097 @ | %z(href("%R/timeline?p=%!S&unhide",zUuid))ancestors</a>
1098 }
1099 if( !isLeaf ){
 
1100 @ | %z(href("%R/timeline?d=%!S&unhide",zUuid))descendants</a>
 
 
 
 
1101 }
1102 if( zParent && !isLeaf ){
1103 @ | %z(href("%R/timeline?dp=%!S&unhide",zUuid))both</a>
1104 }
1105 db_prepare(&q2,"SELECT substr(tag.tagname,5) FROM tagxref, tag "
1106
--- src/info.c
+++ src/info.c
@@ -969,10 +969,21 @@
969 ckout_normal_diff(vid);
970 }
971 style_finish_page();
972 }
973
974 /*
975 ** SETTING: path-to-tag width=40
976 **
977 ** If the path-to-tag setting is defined and is not an empty string
978 ** then then /info page for checking HASH will display a link to
979 ** a timeline showing an abbreviated path from the HASH check-in to
980 ** the next checkin that has a tag which is the value of this setting.
981 **
982 ** A typical value for this setting is "release"
983 */
984
985 /*
986 ** WEBPAGE: vinfo
987 ** WEBPAGE: ci
988 ** URL: /ci/ARTIFACTID
989 ** OR: /ci?name=ARTIFACTID
@@ -1095,11 +1106,16 @@
1106 @ %z(href("%R/timeline?f=%!S&unhide",zUuid))family</a>
1107 if( zParent ){
1108 @ | %z(href("%R/timeline?p=%!S&unhide",zUuid))ancestors</a>
1109 }
1110 if( !isLeaf ){
1111 char *zPathTo = db_get("path-to-tag",0);
1112 @ | %z(href("%R/timeline?d=%!S&unhide",zUuid))descendants</a>
1113 if( zPathTo!=0 && zPathTo[0]!=0 ){
1114 @ | %z(href("%R/timeline?from=%!S&ft=%t&min",zUuid,zPathTo))\
1115 @ path-to-%h(zPathTo)</a>
1116 }
1117 }
1118 if( zParent && !isLeaf ){
1119 @ | %z(href("%R/timeline?dp=%!S&unhide",zUuid))both</a>
1120 }
1121 db_prepare(&q2,"SELECT substr(tag.tagname,5) FROM tagxref, tag "
1122
+3 -3
--- src/main.c
+++ src/main.c
@@ -761,14 +761,14 @@
761761
fossil_limit_memory(1);
762762
763763
/* When updating the minimum SQLite version, change the number here,
764764
** and also MINIMUM_SQLITE_VERSION value set in ../auto.def. Take
765765
** care that both places agree! */
766
- if( sqlite3_libversion_number()<3049000
767
- || strncmp(sqlite3_sourceid(),"2025-02-06",10)<0
766
+ if( sqlite3_libversion_number()<3054000
767
+ || strncmp(sqlite3_sourceid(),"2025-07-01",10)<0
768768
){
769
- fossil_panic("Unsuitable SQLite version %s, must be at least 3.49.0",
769
+ fossil_panic("Unsuitable SQLite version %s, must be at least 3.54.0",
770770
sqlite3_libversion());
771771
}
772772
773773
sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
774774
sqlite3_config(SQLITE_CONFIG_LOG, fossil_sqlite_log, 0);
775775
--- src/main.c
+++ src/main.c
@@ -761,14 +761,14 @@
761 fossil_limit_memory(1);
762
763 /* When updating the minimum SQLite version, change the number here,
764 ** and also MINIMUM_SQLITE_VERSION value set in ../auto.def. Take
765 ** care that both places agree! */
766 if( sqlite3_libversion_number()<3049000
767 || strncmp(sqlite3_sourceid(),"2025-02-06",10)<0
768 ){
769 fossil_panic("Unsuitable SQLite version %s, must be at least 3.49.0",
770 sqlite3_libversion());
771 }
772
773 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
774 sqlite3_config(SQLITE_CONFIG_LOG, fossil_sqlite_log, 0);
775
--- src/main.c
+++ src/main.c
@@ -761,14 +761,14 @@
761 fossil_limit_memory(1);
762
763 /* When updating the minimum SQLite version, change the number here,
764 ** and also MINIMUM_SQLITE_VERSION value set in ../auto.def. Take
765 ** care that both places agree! */
766 if( sqlite3_libversion_number()<3054000
767 || strncmp(sqlite3_sourceid(),"2025-07-01",10)<0
768 ){
769 fossil_panic("Unsuitable SQLite version %s, must be at least 3.54.0",
770 sqlite3_libversion());
771 }
772
773 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
774 sqlite3_config(SQLITE_CONFIG_LOG, fossil_sqlite_log, 0);
775
+61 -21
--- src/merge.c
+++ src/merge.c
@@ -300,10 +300,11 @@
300300
** lines are shown
301301
** -c|--context N Show N lines of context around each change,
302302
** with negative N meaning show all content. Only
303303
** meaningful in combination with --tcl or --tk.
304304
** --dark Use dark mode for the Tcl/Tk-based GUI
305
+** -v|--verbose Show extra information about each merge operation
305306
** --tk Bring up a Tcl/Tk GUI that shows the changes
306307
** associated with the most recent merge.
307308
**
308309
** Options used internally by --tk:
309310
** --diff12 FILE Bring up a separate --tk diff for just the baseline
@@ -323,10 +324,11 @@
323324
const char *zCnt;
324325
const char *zTcl;
325326
int bTk;
326327
int bDark;
327328
int bAll;
329
+ int bDetail;
328330
int nContext;
329331
Stmt q;
330332
const char *zWhere;
331333
int cnt = 0;
332334
const char *zDiff2 = 0;
@@ -336,10 +338,11 @@
336338
bTk = find_option("tk", 0, 0)!=0;
337339
zTcl = find_option("tcl", 0, 1);
338340
zCnt = find_option("context", "c", 1);
339341
bDark = find_option("dark", 0, 0)!=0;
340342
bAll = find_option("all", "a", 0)!=0;
343
+ bDetail = find_option("verbose", "v", 0)!=0;
341344
if( (zDiff2 = find_option("diff12", 0, 1))!=0 ){
342345
diffMode = 12;
343346
}else
344347
if( (zDiff2 = find_option("diff13", 0, 1))!=0 ){
345348
diffMode = 13;
@@ -388,31 +391,68 @@
388391
if( bAll ){
389392
zWhere = "";
390393
}else{
391394
zWhere = "WHERE op IN ('MERGE','CONFLICT','ERROR')";
392395
}
393
- db_prepare(&q,
394
- "WITH priority(op,pri) AS (VALUES('CONFLICT',0),('ERROR',0),"
395
- "('MERGE',1),('ADDED',2),('UPDATE',2))"
396
-
397
- /* 0 1 2 */
398
- "SELECT op, coalesce(fnr,fn), msg"
399
- " FROM mergestat JOIN priority USING(op)"
400
- " %s"
401
- " ORDER BY pri, coalesce(fnr,fn)",
402
- zWhere /*safe-for-%s*/
403
- );
404
- while( db_step(&q)==SQLITE_ROW ){
405
- const char *zOp = db_column_text(&q, 0);
406
- const char *zName = db_column_text(&q, 1);
407
- const char *zErr = db_column_text(&q, 2);
408
- if( zErr && fossil_strcmp(zOp,"CONFLICT")!=0 ){
409
- fossil_print("%-9s %s (%s)\n", zOp, zName, zErr);
410
- }else{
411
- fossil_print("%-9s %s\n", zOp, zName);
412
- }
413
- cnt++;
396
+ if( !bDetail ){
397
+ db_prepare(&q,
398
+ "WITH priority(op,pri) AS (VALUES('CONFLICT',0),('ERROR',0),"
399
+ "('MERGE',1),('ADDED',2),('UPDATE',2))"
400
+
401
+ /* 0 1 2 */
402
+ "SELECT op, coalesce(fnr,fn), msg"
403
+ " FROM mergestat JOIN priority USING(op)"
404
+ " %s"
405
+ " ORDER BY pri, coalesce(fnr,fn)",
406
+ zWhere /*safe-for-%s*/
407
+ );
408
+ while( db_step(&q)==SQLITE_ROW ){
409
+ const char *zOp = db_column_text(&q, 0);
410
+ const char *zName = db_column_text(&q, 1);
411
+ const char *zErr = db_column_text(&q, 2);
412
+ if( zErr && fossil_strcmp(zOp,"CONFLICT")!=0 ){
413
+ fossil_print("%-9s %s (%s)\n", zOp, zName, zErr);
414
+ }else{
415
+ fossil_print("%-9s %s\n", zOp, zName);
416
+ }
417
+ cnt++;
418
+ }
419
+ }else{
420
+ fossil_print(
421
+ " Status Local Pivot Merge-in Filename\n"
422
+ "--------- ---------- ---------- ---------- ----------------\n");
423
+ db_prepare(&q,
424
+ "WITH priority(op,pri) AS (VALUES('CONFLICT',0),('ERROR',0),"
425
+ "('MERGE',1),('ADDED',2),('UPDATE',2))"
426
+
427
+ /* 0 1 2 */
428
+ "SELECT op, coalesce(fnr,fn), msg,"
429
+ " (SELECT uuid FROM blob WHERE blob.rid=mergestat.ridv)," /* 3: local */
430
+ " (SELECT uuid FROM blob WHERE blob.rid=mergestat.ridp)," /* 4: pivot */
431
+ " (SELECT uuid FROM blob WHERE blob.rid=mergestat.ridm)" /* 5: mergein*/
432
+ " FROM mergestat JOIN priority USING(op)"
433
+ " %s"
434
+ " ORDER BY pri, coalesce(fnr,fn)",
435
+ zWhere /*safe-for-%s*/
436
+ );
437
+ while( db_step(&q)==SQLITE_ROW ){
438
+ const char *zOp = db_column_text(&q, 0);
439
+ const char *zName = db_column_text(&q, 1);
440
+ const char *zErr = db_column_text(&q, 2);
441
+ const char *zLocal = db_column_text(&q, 3);
442
+ const char *zPivot = db_column_text(&q, 4);
443
+ const char *zMergein = db_column_text(&q, 5);
444
+ if( zLocal==0 ) zLocal = "";
445
+ if( zErr && fossil_strcmp(zOp,"CONFLICT")!=0 ){
446
+ fossil_print("%-9s %10.10s %10.10s %10.10s %s (%s)\n",
447
+ zOp, zLocal, zPivot, zMergein, zName, zErr);
448
+ }else{
449
+ fossil_print("%-9s %10.10s %10.10s %10.10s %s\n",
450
+ zOp, zLocal, zPivot, zMergein, zName);
451
+ }
452
+ cnt++;
453
+ }
414454
}
415455
db_finalize(&q);
416456
if( !bAll && cnt==0 ){
417457
fossil_print(
418458
"No interesting changes in this merge. Use --all to see everything.\n"
419459
--- src/merge.c
+++ src/merge.c
@@ -300,10 +300,11 @@
300 ** lines are shown
301 ** -c|--context N Show N lines of context around each change,
302 ** with negative N meaning show all content. Only
303 ** meaningful in combination with --tcl or --tk.
304 ** --dark Use dark mode for the Tcl/Tk-based GUI
 
305 ** --tk Bring up a Tcl/Tk GUI that shows the changes
306 ** associated with the most recent merge.
307 **
308 ** Options used internally by --tk:
309 ** --diff12 FILE Bring up a separate --tk diff for just the baseline
@@ -323,10 +324,11 @@
323 const char *zCnt;
324 const char *zTcl;
325 int bTk;
326 int bDark;
327 int bAll;
 
328 int nContext;
329 Stmt q;
330 const char *zWhere;
331 int cnt = 0;
332 const char *zDiff2 = 0;
@@ -336,10 +338,11 @@
336 bTk = find_option("tk", 0, 0)!=0;
337 zTcl = find_option("tcl", 0, 1);
338 zCnt = find_option("context", "c", 1);
339 bDark = find_option("dark", 0, 0)!=0;
340 bAll = find_option("all", "a", 0)!=0;
 
341 if( (zDiff2 = find_option("diff12", 0, 1))!=0 ){
342 diffMode = 12;
343 }else
344 if( (zDiff2 = find_option("diff13", 0, 1))!=0 ){
345 diffMode = 13;
@@ -388,31 +391,68 @@
388 if( bAll ){
389 zWhere = "";
390 }else{
391 zWhere = "WHERE op IN ('MERGE','CONFLICT','ERROR')";
392 }
393 db_prepare(&q,
394 "WITH priority(op,pri) AS (VALUES('CONFLICT',0),('ERROR',0),"
395 "('MERGE',1),('ADDED',2),('UPDATE',2))"
396
397 /* 0 1 2 */
398 "SELECT op, coalesce(fnr,fn), msg"
399 " FROM mergestat JOIN priority USING(op)"
400 " %s"
401 " ORDER BY pri, coalesce(fnr,fn)",
402 zWhere /*safe-for-%s*/
403 );
404 while( db_step(&q)==SQLITE_ROW ){
405 const char *zOp = db_column_text(&q, 0);
406 const char *zName = db_column_text(&q, 1);
407 const char *zErr = db_column_text(&q, 2);
408 if( zErr && fossil_strcmp(zOp,"CONFLICT")!=0 ){
409 fossil_print("%-9s %s (%s)\n", zOp, zName, zErr);
410 }else{
411 fossil_print("%-9s %s\n", zOp, zName);
412 }
413 cnt++;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414 }
415 db_finalize(&q);
416 if( !bAll && cnt==0 ){
417 fossil_print(
418 "No interesting changes in this merge. Use --all to see everything.\n"
419
--- src/merge.c
+++ src/merge.c
@@ -300,10 +300,11 @@
300 ** lines are shown
301 ** -c|--context N Show N lines of context around each change,
302 ** with negative N meaning show all content. Only
303 ** meaningful in combination with --tcl or --tk.
304 ** --dark Use dark mode for the Tcl/Tk-based GUI
305 ** -v|--verbose Show extra information about each merge operation
306 ** --tk Bring up a Tcl/Tk GUI that shows the changes
307 ** associated with the most recent merge.
308 **
309 ** Options used internally by --tk:
310 ** --diff12 FILE Bring up a separate --tk diff for just the baseline
@@ -323,10 +324,11 @@
324 const char *zCnt;
325 const char *zTcl;
326 int bTk;
327 int bDark;
328 int bAll;
329 int bDetail;
330 int nContext;
331 Stmt q;
332 const char *zWhere;
333 int cnt = 0;
334 const char *zDiff2 = 0;
@@ -336,10 +338,11 @@
338 bTk = find_option("tk", 0, 0)!=0;
339 zTcl = find_option("tcl", 0, 1);
340 zCnt = find_option("context", "c", 1);
341 bDark = find_option("dark", 0, 0)!=0;
342 bAll = find_option("all", "a", 0)!=0;
343 bDetail = find_option("verbose", "v", 0)!=0;
344 if( (zDiff2 = find_option("diff12", 0, 1))!=0 ){
345 diffMode = 12;
346 }else
347 if( (zDiff2 = find_option("diff13", 0, 1))!=0 ){
348 diffMode = 13;
@@ -388,31 +391,68 @@
391 if( bAll ){
392 zWhere = "";
393 }else{
394 zWhere = "WHERE op IN ('MERGE','CONFLICT','ERROR')";
395 }
396 if( !bDetail ){
397 db_prepare(&q,
398 "WITH priority(op,pri) AS (VALUES('CONFLICT',0),('ERROR',0),"
399 "('MERGE',1),('ADDED',2),('UPDATE',2))"
400
401 /* 0 1 2 */
402 "SELECT op, coalesce(fnr,fn), msg"
403 " FROM mergestat JOIN priority USING(op)"
404 " %s"
405 " ORDER BY pri, coalesce(fnr,fn)",
406 zWhere /*safe-for-%s*/
407 );
408 while( db_step(&q)==SQLITE_ROW ){
409 const char *zOp = db_column_text(&q, 0);
410 const char *zName = db_column_text(&q, 1);
411 const char *zErr = db_column_text(&q, 2);
412 if( zErr && fossil_strcmp(zOp,"CONFLICT")!=0 ){
413 fossil_print("%-9s %s (%s)\n", zOp, zName, zErr);
414 }else{
415 fossil_print("%-9s %s\n", zOp, zName);
416 }
417 cnt++;
418 }
419 }else{
420 fossil_print(
421 " Status Local Pivot Merge-in Filename\n"
422 "--------- ---------- ---------- ---------- ----------------\n");
423 db_prepare(&q,
424 "WITH priority(op,pri) AS (VALUES('CONFLICT',0),('ERROR',0),"
425 "('MERGE',1),('ADDED',2),('UPDATE',2))"
426
427 /* 0 1 2 */
428 "SELECT op, coalesce(fnr,fn), msg,"
429 " (SELECT uuid FROM blob WHERE blob.rid=mergestat.ridv)," /* 3: local */
430 " (SELECT uuid FROM blob WHERE blob.rid=mergestat.ridp)," /* 4: pivot */
431 " (SELECT uuid FROM blob WHERE blob.rid=mergestat.ridm)" /* 5: mergein*/
432 " FROM mergestat JOIN priority USING(op)"
433 " %s"
434 " ORDER BY pri, coalesce(fnr,fn)",
435 zWhere /*safe-for-%s*/
436 );
437 while( db_step(&q)==SQLITE_ROW ){
438 const char *zOp = db_column_text(&q, 0);
439 const char *zName = db_column_text(&q, 1);
440 const char *zErr = db_column_text(&q, 2);
441 const char *zLocal = db_column_text(&q, 3);
442 const char *zPivot = db_column_text(&q, 4);
443 const char *zMergein = db_column_text(&q, 5);
444 if( zLocal==0 ) zLocal = "";
445 if( zErr && fossil_strcmp(zOp,"CONFLICT")!=0 ){
446 fossil_print("%-9s %10.10s %10.10s %10.10s %s (%s)\n",
447 zOp, zLocal, zPivot, zMergein, zName, zErr);
448 }else{
449 fossil_print("%-9s %10.10s %10.10s %10.10s %s\n",
450 zOp, zLocal, zPivot, zMergein, zName);
451 }
452 cnt++;
453 }
454 }
455 db_finalize(&q);
456 if( !bAll && cnt==0 ){
457 fossil_print(
458 "No interesting changes in this merge. Use --all to see everything.\n"
459
+19
--- src/path.c
+++ src/path.c
@@ -168,10 +168,14 @@
168168
/*
169169
** Compute the shortest path from iFrom to iTo
170170
**
171171
** If directOnly is true, then use only the "primary" links from parent to
172172
** child. In other words, ignore merges.
173
+**
174
+** If oneWayOnly is 1, then only follow edges from parent to child.
175
+** If oneWayOnly is 2, that is like 1 except the first edge out of iFrom
176
+** is allowed to be cherrypick edge.
173177
**
174178
** Return a pointer to the beginning of the path (the iFrom node).
175179
** Elements of the path can be traversed by following the PathNode.u.pTo
176180
** pointer chain.
177181
**
@@ -217,10 +221,25 @@
217221
"UNION ALL "
218222
"SELECT pid, 0 FROM plink WHERE :back AND cid=:pid"
219223
);
220224
}
221225
bag_init(&seen);
226
+ if( oneWayOnly==2 ){
227
+ Stmt s2;
228
+ db_prepare(&s2,
229
+ "SELECT childid FROM cherrypick WHERE parentid=%d AND NOT isExclude",
230
+ iFrom
231
+ );
232
+ while( db_step(&s2)==SQLITE_ROW ){
233
+ int cid = db_column_int(&s2,0);
234
+ PathNode *pNew;
235
+ if( bag_find(&seen, cid) ) continue;
236
+ pNew = path_new_node(cid, path.pStart, 1);
237
+ if( pHidden && bag_find(pHidden,cid) ) pNew->isHidden = 1;
238
+ }
239
+ db_finalize(&s2);
240
+ }
222241
while( (p = pqueuex_extract_ptr(&path.pending))!=0 ){
223242
if( path_debug ){
224243
printf("PULL %s %g\n", path_rid_desc(p->rid), p->u.rCost);
225244
}
226245
if( p->rid==iTo ){
227246
--- src/path.c
+++ src/path.c
@@ -168,10 +168,14 @@
168 /*
169 ** Compute the shortest path from iFrom to iTo
170 **
171 ** If directOnly is true, then use only the "primary" links from parent to
172 ** child. In other words, ignore merges.
 
 
 
 
173 **
174 ** Return a pointer to the beginning of the path (the iFrom node).
175 ** Elements of the path can be traversed by following the PathNode.u.pTo
176 ** pointer chain.
177 **
@@ -217,10 +221,25 @@
217 "UNION ALL "
218 "SELECT pid, 0 FROM plink WHERE :back AND cid=:pid"
219 );
220 }
221 bag_init(&seen);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222 while( (p = pqueuex_extract_ptr(&path.pending))!=0 ){
223 if( path_debug ){
224 printf("PULL %s %g\n", path_rid_desc(p->rid), p->u.rCost);
225 }
226 if( p->rid==iTo ){
227
--- src/path.c
+++ src/path.c
@@ -168,10 +168,14 @@
168 /*
169 ** Compute the shortest path from iFrom to iTo
170 **
171 ** If directOnly is true, then use only the "primary" links from parent to
172 ** child. In other words, ignore merges.
173 **
174 ** If oneWayOnly is 1, then only follow edges from parent to child.
175 ** If oneWayOnly is 2, that is like 1 except the first edge out of iFrom
176 ** is allowed to be cherrypick edge.
177 **
178 ** Return a pointer to the beginning of the path (the iFrom node).
179 ** Elements of the path can be traversed by following the PathNode.u.pTo
180 ** pointer chain.
181 **
@@ -217,10 +221,25 @@
221 "UNION ALL "
222 "SELECT pid, 0 FROM plink WHERE :back AND cid=:pid"
223 );
224 }
225 bag_init(&seen);
226 if( oneWayOnly==2 ){
227 Stmt s2;
228 db_prepare(&s2,
229 "SELECT childid FROM cherrypick WHERE parentid=%d AND NOT isExclude",
230 iFrom
231 );
232 while( db_step(&s2)==SQLITE_ROW ){
233 int cid = db_column_int(&s2,0);
234 PathNode *pNew;
235 if( bag_find(&seen, cid) ) continue;
236 pNew = path_new_node(cid, path.pStart, 1);
237 if( pHidden && bag_find(pHidden,cid) ) pNew->isHidden = 1;
238 }
239 db_finalize(&s2);
240 }
241 while( (p = pqueuex_extract_ptr(&path.pending))!=0 ){
242 if( path_debug ){
243 printf("PULL %s %g\n", path_rid_desc(p->rid), p->u.rCost);
244 }
245 if( p->rid==iTo ){
246
+8 -2
--- src/stash.c
+++ src/stash.c
@@ -365,16 +365,22 @@
365365
rc = -1;
366366
blob_zero(&b); /* because we reset it later */
367367
fossil_print("***** Cannot merge symlink %s\n", zNew);
368368
}else{
369369
rc = merge_3way(&a, zOPath, &b, &out, MERGE_KEEP_FILES);
370
- blob_write_to_file(&out, zNPath);
370
+ if( rc>=0 ){
371
+ blob_write_to_file(&out, zNPath);
372
+ file_setexe(zNPath, isExec);
373
+ }
371374
blob_reset(&out);
372
- file_setexe(zNPath, isExec);
373375
}
374376
if( rc ){
375377
fossil_print("CONFLICT %s\n", zNew);
378
+ if( rc<0 ){
379
+ fossil_print(" binary file left unchanged - resolve using "
380
+ "-baseline/-original/-merge\n");
381
+ }
376382
nConflict++;
377383
}else{
378384
fossil_print("MERGE %s\n", zNew);
379385
}
380386
}
381387
--- src/stash.c
+++ src/stash.c
@@ -365,16 +365,22 @@
365 rc = -1;
366 blob_zero(&b); /* because we reset it later */
367 fossil_print("***** Cannot merge symlink %s\n", zNew);
368 }else{
369 rc = merge_3way(&a, zOPath, &b, &out, MERGE_KEEP_FILES);
370 blob_write_to_file(&out, zNPath);
 
 
 
371 blob_reset(&out);
372 file_setexe(zNPath, isExec);
373 }
374 if( rc ){
375 fossil_print("CONFLICT %s\n", zNew);
 
 
 
 
376 nConflict++;
377 }else{
378 fossil_print("MERGE %s\n", zNew);
379 }
380 }
381
--- src/stash.c
+++ src/stash.c
@@ -365,16 +365,22 @@
365 rc = -1;
366 blob_zero(&b); /* because we reset it later */
367 fossil_print("***** Cannot merge symlink %s\n", zNew);
368 }else{
369 rc = merge_3way(&a, zOPath, &b, &out, MERGE_KEEP_FILES);
370 if( rc>=0 ){
371 blob_write_to_file(&out, zNPath);
372 file_setexe(zNPath, isExec);
373 }
374 blob_reset(&out);
 
375 }
376 if( rc ){
377 fossil_print("CONFLICT %s\n", zNew);
378 if( rc<0 ){
379 fossil_print(" binary file left unchanged - resolve using "
380 "-baseline/-original/-merge\n");
381 }
382 nConflict++;
383 }else{
384 fossil_print("MERGE %s\n", zNew);
385 }
386 }
387
+255 -61
--- src/statrep.c
+++ src/statrep.c
@@ -166,11 +166,11 @@
166166
case 'e':
167167
return "technotes";
168168
case 'f':
169169
return "forum posts";
170170
case 'h':
171
- return "forum threads";
171
+ return "new forum threads";
172172
case 'w':
173173
return "wiki changes";
174174
case 't':
175175
return "ticket changes";
176176
case 'g':
@@ -663,107 +663,134 @@
663663
db_finalize(&query);
664664
}
665665
666666
667667
/*
668
-** Helper for stats_report_by_month_year(), which generates a list of
669
-** week numbers. The "y" query parameter is the year in format YYYY.
668
+** Generator for the by-week report (RPT_BYWEEK).
669
+**
670
+** The "y" query parameter is the year in format YYYY.
671
+**
670672
** If zUserName is not NULL then the report is restricted to events
671673
** created by the named user account.
672674
*/
673
-static void stats_report_year_weeks(const char *zUserName){
674
- const char *zYear = P("y"); /* Year for which report shown */
675
- Stmt q;
676
- int nMaxEvents = 1; /* max number of events for
677
- all rows. */
678
- int iterations = 0; /* # of active time periods. */
679
- int rowCount = 0;
680
- int total = 0;
681
- char *zCurrentWeek; /* Current week number */
682
- double rNowFraction = 0.0; /* Fraction of current week that has
683
- ** passed */
675
+static void stats_report_byweek(const char *zUserName){
676
+ const char *zYear = P("y"); /* Year for which report shown */
677
+ int bShowAll = PB("sa"); /* Show all weeks if true, active if false */
678
+ Stmt q; /* Query */
679
+ int nMaxEvents = 1; /* max number of events in any row */
680
+ int rowCount = 0; /* Rows of output generated */
681
+ int total; /* Total number of events */
682
+ int iCurrentWeek; /* Current week number */
683
+ double rNowFraction = 0.0; /* Fraction of current week that has passed */
684
+ double rYearStart; /* Start of year */
685
+ double rYearEnd; /* End of the year */
686
+ double rWeekOne; /* Start of first Monday of the year */
687
+ double rWeekZero; /* If Jan01 is Mon, then rWeekOne, else rWeekOne-7.0 */
688
+ double rAllEnd; /* End of last week of year, overflow into next year */
684689
685690
stats_report_init_view();
686691
style_submenu_sql("y", "Year:",
687692
"WITH RECURSIVE a(b) AS ("
688693
" SELECT substr(date('now'),1,4) UNION ALL"
689
- " SELECT b-1 FROM a"
694
+ " SELECT b-1 FROM a\n"
690695
" WHERE b>0+(SELECT substr(date(min(mtime)),1,4) FROM event)"
691
- ") SELECT b, b FROM a ORDER BY b DESC");
696
+ ") SELECT b, b FROM a ORDER BY b DESC"
697
+ );
698
+ style_submenu_checkbox("sa", "Show-All", 0, 0);
692699
if( zYear==0 || strlen(zYear)!=4 ){
693700
zYear = db_text("1970","SELECT substr(date('now'),1,4);");
694701
}
695
- cgi_printf("<br>\n");
702
+ rYearStart = db_double(0.0,"SELECT julianday('%q-01-01')",zYear);
703
+ rYearEnd = db_double(0.0,"SELECT julianday('%q-01-01','end of year')",zYear);
704
+ rWeekOne = db_double(0.0,"SELECT julianday('%q-01-01','weekday 1')",zYear);
705
+ rWeekZero = rWeekOne>rYearStart ? rWeekOne - 7.0 : rWeekOne;
706
+ rAllEnd = db_double(0.0,
707
+ "SELECT julianday('%q-01-01','end of year','weekday 0')",
708
+ zYear);
709
+ db_multi_exec("CREATE TEMP TABLE wkdata(wk,n);");
696710
db_prepare(&q,
697
- "SELECT DISTINCT strftime('%%W',mtime) AS wk, "
698
- " count(*) AS n "
699
- " FROM v_reports "
700
- " WHERE %Q=substr(date(mtime),1,4) "
701
- " AND mtime < current_timestamp "
702
- " AND ifnull(coalesce(euser,user,'')=%Q,1)"
703
- " GROUP BY wk ORDER BY wk DESC", zYear, zUserName);
711
+ "WITH RECURSIVE c(wkn) AS (\n"
712
+ " VALUES(0+strftime('%%W',:YearStart))\n"
713
+ " UNION ALL\n"
714
+ " SELECT wkn+1 FROM c\n"
715
+ " WHERE wkn<0+strftime('%%W',min(julianday(),:YearEnd))\n"
716
+ ")\n"
717
+ "INSERT INTO wkdata(wk,n)\n"
718
+ " SELECT c.wkn, coalesce(x.n,0)\n"
719
+ " FROM c LEFT JOIN (\n"
720
+ " SELECT 0+strftime('%%W',min(max(mtime,:YearStart),:YearEnd)) AS w,\n"
721
+ " count(*) AS n\n"
722
+ " FROM v_reports\n"
723
+ " WHERE mtime BETWEEN :WeekZero AND :AllEnd\n"
724
+ " AND ifnull(coalesce(euser,user,'')=%Q,1)\n"
725
+ " GROUP BY w\n"
726
+ " ) AS x ON c.wkn=x.w",
727
+ zUserName
728
+ );
729
+ db_bind_double(&q, ":YearStart", rYearStart);
730
+ db_bind_double(&q, ":YearEnd", rYearEnd);
731
+ db_bind_double(&q, ":WeekZero", rWeekZero);
732
+ db_bind_double(&q, ":AllEnd", rAllEnd);
733
+ db_step(&q);
734
+ db_finalize(&q);
735
+
736
+ cgi_printf("<br>\n");
737
+
738
+#if 0
739
+ @ :YearStart = %h(db_text("","SELECT datetime(%!.17g)",rYearStart))<br>
740
+ @ :YearEnd = %h(db_text("","SELECT datetime(%!.17g)",rYearEnd))<br>
741
+ @ :WeekZero = %h(db_text("","SELECT datetime(%!.17g)",rWeekZero))<br>
742
+ @ :AllEnd = %h(db_text("","SELECT datetime(%!.17g)",rAllEnd))<br>
743
+#endif
744
+
704745
@ <h1>Timeline events (%h(stats_report_label_for_type()))
705746
@ for the calendar weeks of %h(zYear)
706747
if( zUserName ){
707748
@ for user %h(zUserName)
708749
}
709750
@ </h1>
710
- zCurrentWeek = db_text(0,
711
- "SELECT strftime('%%W','now') WHERE date() LIKE '%q%%'",
712
- zYear);
713
- if( zCurrentWeek ){
751
+ iCurrentWeek = db_int(0,
752
+ "SELECT strftime('%%W','now') WHERE date() LIKE '%q-%%'", zYear);
753
+ if( iCurrentWeek>0 ){
714754
rNowFraction = db_double(0.5,
715755
"SELECT (unixepoch()-unixepoch('now','weekday 0','-7 days'))/604800.0;");
716756
}
717
- style_table_sorter();
757
+ style_table_sorter();
718758
cgi_printf("<table class='statistics-report-table-events sortable' "
719759
"border='0' cellpadding='2' width='100%%' "
720760
"cellspacing='0' data-column-types='tnx' data-init-sort='0'>\n");
721761
cgi_printf("<thead><tr>"
722762
"<th>Week</th>"
723763
"<th>Events</th>"
724764
"<th width='90%%'><!-- relative commits graph --></th>"
725765
"</tr></thead>\n"
726766
"<tbody>\n");
727
- while( SQLITE_ROW == db_step(&q) ){
728
- int nCount = db_column_int(&q, 1);
729
- if( zCurrentWeek!=0
730
- && strcmp(db_column_text(&q,0),zCurrentWeek)==0
731
- && rNowFraction>0.05
732
- ){
733
- nCount = (int)(((double)nCount)/rNowFraction);
734
- }
735
- if(nCount>nMaxEvents){
736
- nMaxEvents = nCount;
737
- }
738
- ++iterations;
739
- }
740
- db_reset(&q);
741
- while( SQLITE_ROW == db_step(&q) ){
742
- const char *zWeek = db_column_text(&q,0);
767
+ nMaxEvents = db_int(0, "SELECT max(n) FROM wkdata");
768
+ db_prepare(&q, "SELECT wk, n FROM wkdata ORDER BY wk DESC");
769
+ while( SQLITE_ROW == db_step(&q) ){
770
+ const int iWeek = db_column_int(&q,0);
743771
const int nCount = db_column_int(&q,1);
744772
int nSize = (nCount>0 && nMaxEvents>0)
745773
? (int)(100 * nCount / nMaxEvents)
746774
: 0;
775
+ if( nCount==0 && !bShowAll ) continue;
747776
if(!nSize) nSize = 1;
748
- total += nCount;
749777
cgi_printf("<tr class='row%d'>", ++rowCount % 2 );
750
- cgi_printf("<td><a href='%R/timeline?yw=%t%s&y=%s",
751
- zYear, zWeek,
778
+ cgi_printf("<td><a href='%R/timeline?yw=%t%02d&y=%s",
779
+ zYear, iWeek,
752780
statsReportTimelineYFlag);
753781
if( zUserName ){
754782
cgi_printf("&u=%t",zUserName);
755783
}
756
- cgi_printf("'>%s</a></td>",zWeek);
784
+ cgi_printf("'>%02d</a></td>",iWeek);
757785
758786
cgi_printf("<td>%d</td>",nCount);
759787
cgi_printf("<td style='white-space: nowrap;'>");
760788
if( nCount ){
761
- if( zCurrentWeek!=0
762
- && strcmp(zWeek, zCurrentWeek)==0
763
- && rNowFraction>0.05
764
- && nMaxEvents>0
789
+ if( iCurrentWeek==iWeek
790
+ && rNowFraction>0.05
791
+ && nMaxEvents>0
765792
){
766793
/* If the timespan covered by this row contains "now", then project
767794
** the number of changes until the completion of the week and
768795
** show a dashed box of that projection. */
769796
int nProj = (int)(((double)nCount)/rNowFraction);
@@ -779,16 +806,177 @@
779806
}
780807
}
781808
cgi_printf("</td></tr>\n");
782809
}
783810
db_finalize(&q);
784
- cgi_printf("</tbody></table>");
785
- if(total){
786
- int nAvg = iterations ? (total/iterations) : 0;
787
- cgi_printf("<br><div>Total events: %d<br>"
788
- "Average per active week: %d</div>",
789
- total, nAvg);
811
+ cgi_printf("</tbody></table>\n<br>\n<div\n");
812
+ total = db_int(0, "SELECT sum(n) FROM wkdata");
813
+ cgi_printf("Total events: %d<br>\n", total);
814
+ if( total ){
815
+ cgi_printf("Weeks covered: %d<br>\n",
816
+ db_int(0, "SELECT count(*) FROM wkdata"));
817
+ cgi_printf("Average events per week: %.1f<br>\n",
818
+ db_double(0.0, "SELECT avg(n) FROM wkdata"));
819
+ cgi_printf("Median events per week: %.1f<br>\n",
820
+ db_double(0.0, "SELECT median(n) FROM wkdata"));
821
+ cgi_printf("Active weeks: %d<br>\n",
822
+ db_int(0, "SELECT count(*) FROM wkdata WHERE n>0"));
823
+ cgi_printf("Average events per active week: %.1f<br>\n",
824
+ db_double(0.0, "SELECT avg(n) FROM wkdata WHERE n>0"));
825
+ cgi_printf("Median events per active week: %.1f<br>\n",
826
+ db_double(0.0, "SELECT median(n) FROM wkdata WHERE n>0"));
827
+ }
828
+}
829
+
830
+/*
831
+** Generator for the by-day report (RPT_BYDAY).
832
+**
833
+** The "y" query parameter is the year in format YYYY.
834
+**
835
+** If zUserName is not NULL then the report is restricted to events
836
+** created by the named user account.
837
+*/
838
+static void stats_report_byday(const char *zUserName){
839
+ const char *zYear = P("y"); /* Year for which report shown */
840
+ int bShowAll = PB("sa"); /* Show all days if true, active if false */
841
+ char *zLimit; /* Date of last day to show */
842
+ Stmt q;
843
+ int nMaxEvents = 1; /* max number of events for all rows. */
844
+ int rowCount = 0;
845
+ int total;
846
+ char *zCurrentDay; /* Current week number */
847
+ double rNowFraction = 0.0; /* Fraction of current day that has
848
+ ** passed */
849
+
850
+ stats_report_init_view();
851
+ style_submenu_sql("y", "Year:",
852
+ "WITH RECURSIVE a(b) AS ("
853
+ " SELECT substr(date('now'),1,4) UNION ALL"
854
+ " SELECT b-1 FROM a\n"
855
+ " WHERE b>0+(SELECT substr(date(min(mtime)),1,4) FROM event)"
856
+ ") SELECT b, b FROM a ORDER BY b DESC"
857
+ );
858
+ style_submenu_checkbox("sa", "Show-All", 0, 0);
859
+ if( zYear==0 || strlen(zYear)!=4 ){
860
+ zYear = db_text("1970","SELECT substr(date('now'),1,4);");
861
+ }
862
+ zLimit = db_text("1971-01-01",
863
+ "SELECT min(date('%q-01-01','+1 year','-1 day'),date())",
864
+ zYear
865
+ );
866
+ db_multi_exec(
867
+ "CREATE TEMP TABLE daydata(dn,isodate,dow,n);\n"
868
+ "WITH RECURSIVE c(daynum, isodate, dow) AS (\n"
869
+ " VALUES(0,date('%q-01-01'),0+strftime('%%w','%q-01-01'))\n"
870
+ " UNION ALL\n"
871
+ " SELECT daynum+1, date(isodate,'+1 day'), (dow+1)%%7\n"
872
+ " FROM c\n"
873
+ " WHERE isodate<%Q\n"
874
+ ")\n"
875
+ "INSERT INTO daydata(dn,isodate,dow,n)\n"
876
+ " SELECT c.daynum, c.isodate, c.dow, coalesce(x.n,0)\n"
877
+ " FROM c LEFT JOIN (\n"
878
+ " SELECT date(mtime) AS edate, count(*) AS n\n"
879
+ " FROM v_reports\n"
880
+ " WHERE mtime BETWEEN julianday('%q-01-01')\n"
881
+ " AND julianday('%q 23:59:59.999')\n"
882
+ " AND ifnull(coalesce(euser,user,'')=%Q,1)\n"
883
+ " GROUP BY edate\n"
884
+ " ) AS x ON c.isodate=x.edate;\n",
885
+ zYear, zYear,
886
+ zLimit,
887
+ zYear,
888
+ zLimit,
889
+ zUserName
890
+ );
891
+ cgi_printf("<br>\n");
892
+ @ <h1>Timeline events (%h(stats_report_label_for_type()))
893
+ @ for the individual days of year %h(zYear)
894
+ if( zUserName ){
895
+ @ for user %h(zUserName)
896
+ }
897
+ @ </h1>
898
+ zCurrentDay = db_text(0, "SELECT date()");
899
+ if( zCurrentDay ){
900
+ rNowFraction = db_double(0.5,
901
+ "SELECT (unixepoch()-unixepoch('now','start of day'))/86400.0;");
902
+ }
903
+ style_table_sorter();
904
+ cgi_printf("<table class='statistics-report-table-events sortable' "
905
+ "border='0' cellpadding='2' width='100%%' "
906
+ "cellspacing='0' data-column-types='tnx' data-init-sort='0'>\n");
907
+ cgi_printf("<thead><tr>"
908
+ "<th>Day</th>"
909
+ "<th>Events</th>"
910
+ "<th width='90%%'><!-- relative commits graph --></th>"
911
+ "</tr></thead>\n"
912
+ "<tbody>\n");
913
+ nMaxEvents = db_int(0, "SELECT max(n) FROM daydata");
914
+ db_prepare(&q, "SELECT isodate,dow,n FROM daydata ORDER BY dn DESC");
915
+ while( SQLITE_ROW == db_step(&q) ){
916
+ static const char *azDayName[] = {
917
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
918
+ };
919
+ const char *zDate = db_column_text(&q,0);
920
+ int iDOW = db_column_int(&q,1);
921
+ const int nCount = db_column_int(&q,2);
922
+ int nSize = (nCount>0 && nMaxEvents>0)
923
+ ? (int)(100 * nCount / nMaxEvents)
924
+ : 0;
925
+ assert( iDOW>=0 && iDOW<=6 );
926
+ if( nCount==0 && !bShowAll ) continue;
927
+ if(!nSize) nSize = 1;
928
+ cgi_printf("<tr class='row%d'>", ++rowCount % 2 );
929
+ cgi_printf("<td><a href='%R/timeline?ymd=%s&y=%s",
930
+ zDate, statsReportTimelineYFlag);
931
+ if( zUserName ){
932
+ cgi_printf("&u=%t",zUserName);
933
+ }
934
+ cgi_printf("'>%s&nbsp;(%s)</a></td>",zDate,azDayName[iDOW]);
935
+
936
+ cgi_printf("<td>%d</td>",nCount);
937
+ cgi_printf("<td style='white-space: nowrap;'>");
938
+ if( nCount ){
939
+ if( zCurrentDay!=0
940
+ && strcmp(zDate, zCurrentDay)==0
941
+ && rNowFraction>0.05
942
+ && nMaxEvents>0
943
+ ){
944
+ /* If the timespan covered by this row contains "now", then project
945
+ ** the number of changes until the completion of the day and
946
+ ** show a dashed box of that projection. */
947
+ int nProj = (int)(nCount/rNowFraction);
948
+ int nExtra = (int)(100.0*nCount/rNowFraction - 100*nCount);
949
+ int nXSize = nExtra/nMaxEvents;
950
+ @ <span class='statistics-report-graph-line' \
951
+ @ style='display:inline-block;min-width:%d(nSize)%%;'>&nbsp;</span>\
952
+ @ <span class='statistics-report-graph-extra' title='%d(nProj)' \
953
+ @ style='display:inline-block;min-width:%d(nXSize)%%;'>&nbsp;</span>\
954
+ }else{
955
+ @ <div class='statistics-report-graph-line' \
956
+ @ style='width:%d(nSize)%%;'>&nbsp;</div> \
957
+ }
958
+ }
959
+ cgi_printf("</td></tr>\n");
960
+ }
961
+ db_finalize(&q);
962
+ cgi_printf("</tbody></table>\n<br>\n<div\n");
963
+ total = db_int(0, "SELECT sum(n) FROM daydata");
964
+ cgi_printf("Total events: %d<br>\n", total);
965
+ if( total ){
966
+ cgi_printf("Days covered: %d<br>\n",
967
+ db_int(0, "SELECT count(*) FROM daydata"));
968
+ cgi_printf("Average events per day: %.1f<br>\n",
969
+ db_double(0.0, "SELECT avg(n) FROM daydata"));
970
+ cgi_printf("Median events per day: %.1f<br>\n",
971
+ db_double(0.0, "SELECT median(n) FROM daydata"));
972
+ cgi_printf("Active days: %d<br>\n",
973
+ db_int(0, "SELECT count(*) FROM daydata WHERE n>0"));
974
+ cgi_printf("Average events per active day: %.1f<br>\n",
975
+ db_double(0.0, "SELECT avg(n) FROM daydata WHERE n>0"));
976
+ cgi_printf("Median events per active day: %.1f<br>\n",
977
+ db_double(0.0, "SELECT median(n) FROM daydata WHERE n>0"));
790978
}
791979
}
792980
793981
794982
/*
@@ -843,10 +1031,11 @@
8431031
#define RPT_BYWEEK 4
8441032
#define RPT_BYWEEKDAY 5
8451033
#define RPT_BYYEAR 6
8461034
#define RPT_LASTCHNG 7 /* Last change made for each user */
8471035
#define RPT_BYHOUR 8 /* hour-of-day */
1036
+#define RPT_BYDAY 9
8481037
#define RPT_NONE 0 /* None of the above */
8491038
8501039
/*
8511040
** WEBPAGE: reports
8521041
**
@@ -856,10 +1045,11 @@
8561045
**
8571046
** view=REPORT_NAME Valid REPORT_NAME values:
8581047
** * byyear
8591048
** * bymonth
8601049
** * byweek
1050
+** * byday
8611051
** * byweekday
8621052
** * byhour
8631053
** * byuser
8641054
** * byfile
8651055
** * lastchng
@@ -889,11 +1079,11 @@
8891079
void stats_report_page(){
8901080
const char *zView = P("view"); /* Which view/report to show. */
8911081
int eType = RPT_NONE; /* Numeric code for view/report to show */
8921082
int i; /* Loop counter */
8931083
const char *zUserName; /* Name of user */
894
- const char *azView[16]; /* Drop-down menu of view types */
1084
+ const char *azView[24]; /* Drop-down menu of view types */
8951085
static const struct {
8961086
const char *zName; /* Name of view= screen type */
8971087
const char *zVal; /* Value of view= query parameter */
8981088
int eType; /* Corresponding RPT_* define */
8991089
} aViewType[] = {
@@ -900,10 +1090,11 @@
9001090
{ "File Changes","byfile", RPT_BYFILE },
9011091
{ "Last Change", "lastchng", RPT_LASTCHNG },
9021092
{ "By Month", "bymonth", RPT_BYMONTH },
9031093
{ "By User", "byuser", RPT_BYUSER },
9041094
{ "By Week", "byweek", RPT_BYWEEK },
1095
+ { "By Day", "byday", RPT_BYDAY },
9051096
{ "By Weekday", "byweekday", RPT_BYWEEKDAY },
9061097
{ "By Year", "byyear", RPT_BYYEAR },
9071098
{ "By Hour", "byhour", RPT_BYHOUR },
9081099
};
9091100
static const char *const azType[] = {
@@ -963,11 +1154,14 @@
9631154
break;
9641155
case RPT_BYMONTH:
9651156
stats_report_by_month_year(1, zUserName);
9661157
break;
9671158
case RPT_BYWEEK:
968
- stats_report_year_weeks(zUserName);
1159
+ stats_report_byweek(zUserName);
1160
+ break;
1161
+ case RPT_BYDAY:
1162
+ stats_report_byday(zUserName);
9691163
break;
9701164
default:
9711165
case RPT_BYUSER:
9721166
stats_report_by_user();
9731167
break;
9741168
--- src/statrep.c
+++ src/statrep.c
@@ -166,11 +166,11 @@
166 case 'e':
167 return "technotes";
168 case 'f':
169 return "forum posts";
170 case 'h':
171 return "forum threads";
172 case 'w':
173 return "wiki changes";
174 case 't':
175 return "ticket changes";
176 case 'g':
@@ -663,107 +663,134 @@
663 db_finalize(&query);
664 }
665
666
667 /*
668 ** Helper for stats_report_by_month_year(), which generates a list of
669 ** week numbers. The "y" query parameter is the year in format YYYY.
 
 
670 ** If zUserName is not NULL then the report is restricted to events
671 ** created by the named user account.
672 */
673 static void stats_report_year_weeks(const char *zUserName){
674 const char *zYear = P("y"); /* Year for which report shown */
675 Stmt q;
676 int nMaxEvents = 1; /* max number of events for
677 all rows. */
678 int iterations = 0; /* # of active time periods. */
679 int rowCount = 0;
680 int total = 0;
681 char *zCurrentWeek; /* Current week number */
682 double rNowFraction = 0.0; /* Fraction of current week that has
683 ** passed */
 
 
 
684
685 stats_report_init_view();
686 style_submenu_sql("y", "Year:",
687 "WITH RECURSIVE a(b) AS ("
688 " SELECT substr(date('now'),1,4) UNION ALL"
689 " SELECT b-1 FROM a"
690 " WHERE b>0+(SELECT substr(date(min(mtime)),1,4) FROM event)"
691 ") SELECT b, b FROM a ORDER BY b DESC");
 
 
692 if( zYear==0 || strlen(zYear)!=4 ){
693 zYear = db_text("1970","SELECT substr(date('now'),1,4);");
694 }
695 cgi_printf("<br>\n");
 
 
 
 
 
 
 
696 db_prepare(&q,
697 "SELECT DISTINCT strftime('%%W',mtime) AS wk, "
698 " count(*) AS n "
699 " FROM v_reports "
700 " WHERE %Q=substr(date(mtime),1,4) "
701 " AND mtime < current_timestamp "
702 " AND ifnull(coalesce(euser,user,'')=%Q,1)"
703 " GROUP BY wk ORDER BY wk DESC", zYear, zUserName);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
704 @ <h1>Timeline events (%h(stats_report_label_for_type()))
705 @ for the calendar weeks of %h(zYear)
706 if( zUserName ){
707 @ for user %h(zUserName)
708 }
709 @ </h1>
710 zCurrentWeek = db_text(0,
711 "SELECT strftime('%%W','now') WHERE date() LIKE '%q%%'",
712 zYear);
713 if( zCurrentWeek ){
714 rNowFraction = db_double(0.5,
715 "SELECT (unixepoch()-unixepoch('now','weekday 0','-7 days'))/604800.0;");
716 }
717 style_table_sorter();
718 cgi_printf("<table class='statistics-report-table-events sortable' "
719 "border='0' cellpadding='2' width='100%%' "
720 "cellspacing='0' data-column-types='tnx' data-init-sort='0'>\n");
721 cgi_printf("<thead><tr>"
722 "<th>Week</th>"
723 "<th>Events</th>"
724 "<th width='90%%'><!-- relative commits graph --></th>"
725 "</tr></thead>\n"
726 "<tbody>\n");
727 while( SQLITE_ROW == db_step(&q) ){
728 int nCount = db_column_int(&q, 1);
729 if( zCurrentWeek!=0
730 && strcmp(db_column_text(&q,0),zCurrentWeek)==0
731 && rNowFraction>0.05
732 ){
733 nCount = (int)(((double)nCount)/rNowFraction);
734 }
735 if(nCount>nMaxEvents){
736 nMaxEvents = nCount;
737 }
738 ++iterations;
739 }
740 db_reset(&q);
741 while( SQLITE_ROW == db_step(&q) ){
742 const char *zWeek = db_column_text(&q,0);
743 const int nCount = db_column_int(&q,1);
744 int nSize = (nCount>0 && nMaxEvents>0)
745 ? (int)(100 * nCount / nMaxEvents)
746 : 0;
 
747 if(!nSize) nSize = 1;
748 total += nCount;
749 cgi_printf("<tr class='row%d'>", ++rowCount % 2 );
750 cgi_printf("<td><a href='%R/timeline?yw=%t%s&y=%s",
751 zYear, zWeek,
752 statsReportTimelineYFlag);
753 if( zUserName ){
754 cgi_printf("&u=%t",zUserName);
755 }
756 cgi_printf("'>%s</a></td>",zWeek);
757
758 cgi_printf("<td>%d</td>",nCount);
759 cgi_printf("<td style='white-space: nowrap;'>");
760 if( nCount ){
761 if( zCurrentWeek!=0
762 && strcmp(zWeek, zCurrentWeek)==0
763 && rNowFraction>0.05
764 && nMaxEvents>0
765 ){
766 /* If the timespan covered by this row contains "now", then project
767 ** the number of changes until the completion of the week and
768 ** show a dashed box of that projection. */
769 int nProj = (int)(((double)nCount)/rNowFraction);
@@ -779,16 +806,177 @@
779 }
780 }
781 cgi_printf("</td></tr>\n");
782 }
783 db_finalize(&q);
784 cgi_printf("</tbody></table>");
785 if(total){
786 int nAvg = iterations ? (total/iterations) : 0;
787 cgi_printf("<br><div>Total events: %d<br>"
788 "Average per active week: %d</div>",
789 total, nAvg);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790 }
791 }
792
793
794 /*
@@ -843,10 +1031,11 @@
843 #define RPT_BYWEEK 4
844 #define RPT_BYWEEKDAY 5
845 #define RPT_BYYEAR 6
846 #define RPT_LASTCHNG 7 /* Last change made for each user */
847 #define RPT_BYHOUR 8 /* hour-of-day */
 
848 #define RPT_NONE 0 /* None of the above */
849
850 /*
851 ** WEBPAGE: reports
852 **
@@ -856,10 +1045,11 @@
856 **
857 ** view=REPORT_NAME Valid REPORT_NAME values:
858 ** * byyear
859 ** * bymonth
860 ** * byweek
 
861 ** * byweekday
862 ** * byhour
863 ** * byuser
864 ** * byfile
865 ** * lastchng
@@ -889,11 +1079,11 @@
889 void stats_report_page(){
890 const char *zView = P("view"); /* Which view/report to show. */
891 int eType = RPT_NONE; /* Numeric code for view/report to show */
892 int i; /* Loop counter */
893 const char *zUserName; /* Name of user */
894 const char *azView[16]; /* Drop-down menu of view types */
895 static const struct {
896 const char *zName; /* Name of view= screen type */
897 const char *zVal; /* Value of view= query parameter */
898 int eType; /* Corresponding RPT_* define */
899 } aViewType[] = {
@@ -900,10 +1090,11 @@
900 { "File Changes","byfile", RPT_BYFILE },
901 { "Last Change", "lastchng", RPT_LASTCHNG },
902 { "By Month", "bymonth", RPT_BYMONTH },
903 { "By User", "byuser", RPT_BYUSER },
904 { "By Week", "byweek", RPT_BYWEEK },
 
905 { "By Weekday", "byweekday", RPT_BYWEEKDAY },
906 { "By Year", "byyear", RPT_BYYEAR },
907 { "By Hour", "byhour", RPT_BYHOUR },
908 };
909 static const char *const azType[] = {
@@ -963,11 +1154,14 @@
963 break;
964 case RPT_BYMONTH:
965 stats_report_by_month_year(1, zUserName);
966 break;
967 case RPT_BYWEEK:
968 stats_report_year_weeks(zUserName);
 
 
 
969 break;
970 default:
971 case RPT_BYUSER:
972 stats_report_by_user();
973 break;
974
--- src/statrep.c
+++ src/statrep.c
@@ -166,11 +166,11 @@
166 case 'e':
167 return "technotes";
168 case 'f':
169 return "forum posts";
170 case 'h':
171 return "new forum threads";
172 case 'w':
173 return "wiki changes";
174 case 't':
175 return "ticket changes";
176 case 'g':
@@ -663,107 +663,134 @@
663 db_finalize(&query);
664 }
665
666
667 /*
668 ** Generator for the by-week report (RPT_BYWEEK).
669 **
670 ** The "y" query parameter is the year in format YYYY.
671 **
672 ** If zUserName is not NULL then the report is restricted to events
673 ** created by the named user account.
674 */
675 static void stats_report_byweek(const char *zUserName){
676 const char *zYear = P("y"); /* Year for which report shown */
677 int bShowAll = PB("sa"); /* Show all weeks if true, active if false */
678 Stmt q; /* Query */
679 int nMaxEvents = 1; /* max number of events in any row */
680 int rowCount = 0; /* Rows of output generated */
681 int total; /* Total number of events */
682 int iCurrentWeek; /* Current week number */
683 double rNowFraction = 0.0; /* Fraction of current week that has passed */
684 double rYearStart; /* Start of year */
685 double rYearEnd; /* End of the year */
686 double rWeekOne; /* Start of first Monday of the year */
687 double rWeekZero; /* If Jan01 is Mon, then rWeekOne, else rWeekOne-7.0 */
688 double rAllEnd; /* End of last week of year, overflow into next year */
689
690 stats_report_init_view();
691 style_submenu_sql("y", "Year:",
692 "WITH RECURSIVE a(b) AS ("
693 " SELECT substr(date('now'),1,4) UNION ALL"
694 " SELECT b-1 FROM a\n"
695 " WHERE b>0+(SELECT substr(date(min(mtime)),1,4) FROM event)"
696 ") SELECT b, b FROM a ORDER BY b DESC"
697 );
698 style_submenu_checkbox("sa", "Show-All", 0, 0);
699 if( zYear==0 || strlen(zYear)!=4 ){
700 zYear = db_text("1970","SELECT substr(date('now'),1,4);");
701 }
702 rYearStart = db_double(0.0,"SELECT julianday('%q-01-01')",zYear);
703 rYearEnd = db_double(0.0,"SELECT julianday('%q-01-01','end of year')",zYear);
704 rWeekOne = db_double(0.0,"SELECT julianday('%q-01-01','weekday 1')",zYear);
705 rWeekZero = rWeekOne>rYearStart ? rWeekOne - 7.0 : rWeekOne;
706 rAllEnd = db_double(0.0,
707 "SELECT julianday('%q-01-01','end of year','weekday 0')",
708 zYear);
709 db_multi_exec("CREATE TEMP TABLE wkdata(wk,n);");
710 db_prepare(&q,
711 "WITH RECURSIVE c(wkn) AS (\n"
712 " VALUES(0+strftime('%%W',:YearStart))\n"
713 " UNION ALL\n"
714 " SELECT wkn+1 FROM c\n"
715 " WHERE wkn<0+strftime('%%W',min(julianday(),:YearEnd))\n"
716 ")\n"
717 "INSERT INTO wkdata(wk,n)\n"
718 " SELECT c.wkn, coalesce(x.n,0)\n"
719 " FROM c LEFT JOIN (\n"
720 " SELECT 0+strftime('%%W',min(max(mtime,:YearStart),:YearEnd)) AS w,\n"
721 " count(*) AS n\n"
722 " FROM v_reports\n"
723 " WHERE mtime BETWEEN :WeekZero AND :AllEnd\n"
724 " AND ifnull(coalesce(euser,user,'')=%Q,1)\n"
725 " GROUP BY w\n"
726 " ) AS x ON c.wkn=x.w",
727 zUserName
728 );
729 db_bind_double(&q, ":YearStart", rYearStart);
730 db_bind_double(&q, ":YearEnd", rYearEnd);
731 db_bind_double(&q, ":WeekZero", rWeekZero);
732 db_bind_double(&q, ":AllEnd", rAllEnd);
733 db_step(&q);
734 db_finalize(&q);
735
736 cgi_printf("<br>\n");
737
738 #if 0
739 @ :YearStart = %h(db_text("","SELECT datetime(%!.17g)",rYearStart))<br>
740 @ :YearEnd = %h(db_text("","SELECT datetime(%!.17g)",rYearEnd))<br>
741 @ :WeekZero = %h(db_text("","SELECT datetime(%!.17g)",rWeekZero))<br>
742 @ :AllEnd = %h(db_text("","SELECT datetime(%!.17g)",rAllEnd))<br>
743 #endif
744
745 @ <h1>Timeline events (%h(stats_report_label_for_type()))
746 @ for the calendar weeks of %h(zYear)
747 if( zUserName ){
748 @ for user %h(zUserName)
749 }
750 @ </h1>
751 iCurrentWeek = db_int(0,
752 "SELECT strftime('%%W','now') WHERE date() LIKE '%q-%%'", zYear);
753 if( iCurrentWeek>0 ){
 
754 rNowFraction = db_double(0.5,
755 "SELECT (unixepoch()-unixepoch('now','weekday 0','-7 days'))/604800.0;");
756 }
757 style_table_sorter();
758 cgi_printf("<table class='statistics-report-table-events sortable' "
759 "border='0' cellpadding='2' width='100%%' "
760 "cellspacing='0' data-column-types='tnx' data-init-sort='0'>\n");
761 cgi_printf("<thead><tr>"
762 "<th>Week</th>"
763 "<th>Events</th>"
764 "<th width='90%%'><!-- relative commits graph --></th>"
765 "</tr></thead>\n"
766 "<tbody>\n");
767 nMaxEvents = db_int(0, "SELECT max(n) FROM wkdata");
768 db_prepare(&q, "SELECT wk, n FROM wkdata ORDER BY wk DESC");
769 while( SQLITE_ROW == db_step(&q) ){
770 const int iWeek = db_column_int(&q,0);
 
 
 
 
 
 
 
 
 
 
 
 
771 const int nCount = db_column_int(&q,1);
772 int nSize = (nCount>0 && nMaxEvents>0)
773 ? (int)(100 * nCount / nMaxEvents)
774 : 0;
775 if( nCount==0 && !bShowAll ) continue;
776 if(!nSize) nSize = 1;
 
777 cgi_printf("<tr class='row%d'>", ++rowCount % 2 );
778 cgi_printf("<td><a href='%R/timeline?yw=%t%02d&y=%s",
779 zYear, iWeek,
780 statsReportTimelineYFlag);
781 if( zUserName ){
782 cgi_printf("&u=%t",zUserName);
783 }
784 cgi_printf("'>%02d</a></td>",iWeek);
785
786 cgi_printf("<td>%d</td>",nCount);
787 cgi_printf("<td style='white-space: nowrap;'>");
788 if( nCount ){
789 if( iCurrentWeek==iWeek
790 && rNowFraction>0.05
791 && nMaxEvents>0
 
792 ){
793 /* If the timespan covered by this row contains "now", then project
794 ** the number of changes until the completion of the week and
795 ** show a dashed box of that projection. */
796 int nProj = (int)(((double)nCount)/rNowFraction);
@@ -779,16 +806,177 @@
806 }
807 }
808 cgi_printf("</td></tr>\n");
809 }
810 db_finalize(&q);
811 cgi_printf("</tbody></table>\n<br>\n<div\n");
812 total = db_int(0, "SELECT sum(n) FROM wkdata");
813 cgi_printf("Total events: %d<br>\n", total);
814 if( total ){
815 cgi_printf("Weeks covered: %d<br>\n",
816 db_int(0, "SELECT count(*) FROM wkdata"));
817 cgi_printf("Average events per week: %.1f<br>\n",
818 db_double(0.0, "SELECT avg(n) FROM wkdata"));
819 cgi_printf("Median events per week: %.1f<br>\n",
820 db_double(0.0, "SELECT median(n) FROM wkdata"));
821 cgi_printf("Active weeks: %d<br>\n",
822 db_int(0, "SELECT count(*) FROM wkdata WHERE n>0"));
823 cgi_printf("Average events per active week: %.1f<br>\n",
824 db_double(0.0, "SELECT avg(n) FROM wkdata WHERE n>0"));
825 cgi_printf("Median events per active week: %.1f<br>\n",
826 db_double(0.0, "SELECT median(n) FROM wkdata WHERE n>0"));
827 }
828 }
829
830 /*
831 ** Generator for the by-day report (RPT_BYDAY).
832 **
833 ** The "y" query parameter is the year in format YYYY.
834 **
835 ** If zUserName is not NULL then the report is restricted to events
836 ** created by the named user account.
837 */
838 static void stats_report_byday(const char *zUserName){
839 const char *zYear = P("y"); /* Year for which report shown */
840 int bShowAll = PB("sa"); /* Show all days if true, active if false */
841 char *zLimit; /* Date of last day to show */
842 Stmt q;
843 int nMaxEvents = 1; /* max number of events for all rows. */
844 int rowCount = 0;
845 int total;
846 char *zCurrentDay; /* Current week number */
847 double rNowFraction = 0.0; /* Fraction of current day that has
848 ** passed */
849
850 stats_report_init_view();
851 style_submenu_sql("y", "Year:",
852 "WITH RECURSIVE a(b) AS ("
853 " SELECT substr(date('now'),1,4) UNION ALL"
854 " SELECT b-1 FROM a\n"
855 " WHERE b>0+(SELECT substr(date(min(mtime)),1,4) FROM event)"
856 ") SELECT b, b FROM a ORDER BY b DESC"
857 );
858 style_submenu_checkbox("sa", "Show-All", 0, 0);
859 if( zYear==0 || strlen(zYear)!=4 ){
860 zYear = db_text("1970","SELECT substr(date('now'),1,4);");
861 }
862 zLimit = db_text("1971-01-01",
863 "SELECT min(date('%q-01-01','+1 year','-1 day'),date())",
864 zYear
865 );
866 db_multi_exec(
867 "CREATE TEMP TABLE daydata(dn,isodate,dow,n);\n"
868 "WITH RECURSIVE c(daynum, isodate, dow) AS (\n"
869 " VALUES(0,date('%q-01-01'),0+strftime('%%w','%q-01-01'))\n"
870 " UNION ALL\n"
871 " SELECT daynum+1, date(isodate,'+1 day'), (dow+1)%%7\n"
872 " FROM c\n"
873 " WHERE isodate<%Q\n"
874 ")\n"
875 "INSERT INTO daydata(dn,isodate,dow,n)\n"
876 " SELECT c.daynum, c.isodate, c.dow, coalesce(x.n,0)\n"
877 " FROM c LEFT JOIN (\n"
878 " SELECT date(mtime) AS edate, count(*) AS n\n"
879 " FROM v_reports\n"
880 " WHERE mtime BETWEEN julianday('%q-01-01')\n"
881 " AND julianday('%q 23:59:59.999')\n"
882 " AND ifnull(coalesce(euser,user,'')=%Q,1)\n"
883 " GROUP BY edate\n"
884 " ) AS x ON c.isodate=x.edate;\n",
885 zYear, zYear,
886 zLimit,
887 zYear,
888 zLimit,
889 zUserName
890 );
891 cgi_printf("<br>\n");
892 @ <h1>Timeline events (%h(stats_report_label_for_type()))
893 @ for the individual days of year %h(zYear)
894 if( zUserName ){
895 @ for user %h(zUserName)
896 }
897 @ </h1>
898 zCurrentDay = db_text(0, "SELECT date()");
899 if( zCurrentDay ){
900 rNowFraction = db_double(0.5,
901 "SELECT (unixepoch()-unixepoch('now','start of day'))/86400.0;");
902 }
903 style_table_sorter();
904 cgi_printf("<table class='statistics-report-table-events sortable' "
905 "border='0' cellpadding='2' width='100%%' "
906 "cellspacing='0' data-column-types='tnx' data-init-sort='0'>\n");
907 cgi_printf("<thead><tr>"
908 "<th>Day</th>"
909 "<th>Events</th>"
910 "<th width='90%%'><!-- relative commits graph --></th>"
911 "</tr></thead>\n"
912 "<tbody>\n");
913 nMaxEvents = db_int(0, "SELECT max(n) FROM daydata");
914 db_prepare(&q, "SELECT isodate,dow,n FROM daydata ORDER BY dn DESC");
915 while( SQLITE_ROW == db_step(&q) ){
916 static const char *azDayName[] = {
917 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
918 };
919 const char *zDate = db_column_text(&q,0);
920 int iDOW = db_column_int(&q,1);
921 const int nCount = db_column_int(&q,2);
922 int nSize = (nCount>0 && nMaxEvents>0)
923 ? (int)(100 * nCount / nMaxEvents)
924 : 0;
925 assert( iDOW>=0 && iDOW<=6 );
926 if( nCount==0 && !bShowAll ) continue;
927 if(!nSize) nSize = 1;
928 cgi_printf("<tr class='row%d'>", ++rowCount % 2 );
929 cgi_printf("<td><a href='%R/timeline?ymd=%s&y=%s",
930 zDate, statsReportTimelineYFlag);
931 if( zUserName ){
932 cgi_printf("&u=%t",zUserName);
933 }
934 cgi_printf("'>%s&nbsp;(%s)</a></td>",zDate,azDayName[iDOW]);
935
936 cgi_printf("<td>%d</td>",nCount);
937 cgi_printf("<td style='white-space: nowrap;'>");
938 if( nCount ){
939 if( zCurrentDay!=0
940 && strcmp(zDate, zCurrentDay)==0
941 && rNowFraction>0.05
942 && nMaxEvents>0
943 ){
944 /* If the timespan covered by this row contains "now", then project
945 ** the number of changes until the completion of the day and
946 ** show a dashed box of that projection. */
947 int nProj = (int)(nCount/rNowFraction);
948 int nExtra = (int)(100.0*nCount/rNowFraction - 100*nCount);
949 int nXSize = nExtra/nMaxEvents;
950 @ <span class='statistics-report-graph-line' \
951 @ style='display:inline-block;min-width:%d(nSize)%%;'>&nbsp;</span>\
952 @ <span class='statistics-report-graph-extra' title='%d(nProj)' \
953 @ style='display:inline-block;min-width:%d(nXSize)%%;'>&nbsp;</span>\
954 }else{
955 @ <div class='statistics-report-graph-line' \
956 @ style='width:%d(nSize)%%;'>&nbsp;</div> \
957 }
958 }
959 cgi_printf("</td></tr>\n");
960 }
961 db_finalize(&q);
962 cgi_printf("</tbody></table>\n<br>\n<div\n");
963 total = db_int(0, "SELECT sum(n) FROM daydata");
964 cgi_printf("Total events: %d<br>\n", total);
965 if( total ){
966 cgi_printf("Days covered: %d<br>\n",
967 db_int(0, "SELECT count(*) FROM daydata"));
968 cgi_printf("Average events per day: %.1f<br>\n",
969 db_double(0.0, "SELECT avg(n) FROM daydata"));
970 cgi_printf("Median events per day: %.1f<br>\n",
971 db_double(0.0, "SELECT median(n) FROM daydata"));
972 cgi_printf("Active days: %d<br>\n",
973 db_int(0, "SELECT count(*) FROM daydata WHERE n>0"));
974 cgi_printf("Average events per active day: %.1f<br>\n",
975 db_double(0.0, "SELECT avg(n) FROM daydata WHERE n>0"));
976 cgi_printf("Median events per active day: %.1f<br>\n",
977 db_double(0.0, "SELECT median(n) FROM daydata WHERE n>0"));
978 }
979 }
980
981
982 /*
@@ -843,10 +1031,11 @@
1031 #define RPT_BYWEEK 4
1032 #define RPT_BYWEEKDAY 5
1033 #define RPT_BYYEAR 6
1034 #define RPT_LASTCHNG 7 /* Last change made for each user */
1035 #define RPT_BYHOUR 8 /* hour-of-day */
1036 #define RPT_BYDAY 9
1037 #define RPT_NONE 0 /* None of the above */
1038
1039 /*
1040 ** WEBPAGE: reports
1041 **
@@ -856,10 +1045,11 @@
1045 **
1046 ** view=REPORT_NAME Valid REPORT_NAME values:
1047 ** * byyear
1048 ** * bymonth
1049 ** * byweek
1050 ** * byday
1051 ** * byweekday
1052 ** * byhour
1053 ** * byuser
1054 ** * byfile
1055 ** * lastchng
@@ -889,11 +1079,11 @@
1079 void stats_report_page(){
1080 const char *zView = P("view"); /* Which view/report to show. */
1081 int eType = RPT_NONE; /* Numeric code for view/report to show */
1082 int i; /* Loop counter */
1083 const char *zUserName; /* Name of user */
1084 const char *azView[24]; /* Drop-down menu of view types */
1085 static const struct {
1086 const char *zName; /* Name of view= screen type */
1087 const char *zVal; /* Value of view= query parameter */
1088 int eType; /* Corresponding RPT_* define */
1089 } aViewType[] = {
@@ -900,10 +1090,11 @@
1090 { "File Changes","byfile", RPT_BYFILE },
1091 { "Last Change", "lastchng", RPT_LASTCHNG },
1092 { "By Month", "bymonth", RPT_BYMONTH },
1093 { "By User", "byuser", RPT_BYUSER },
1094 { "By Week", "byweek", RPT_BYWEEK },
1095 { "By Day", "byday", RPT_BYDAY },
1096 { "By Weekday", "byweekday", RPT_BYWEEKDAY },
1097 { "By Year", "byyear", RPT_BYYEAR },
1098 { "By Hour", "byhour", RPT_BYHOUR },
1099 };
1100 static const char *const azType[] = {
@@ -963,11 +1154,14 @@
1154 break;
1155 case RPT_BYMONTH:
1156 stats_report_by_month_year(1, zUserName);
1157 break;
1158 case RPT_BYWEEK:
1159 stats_report_byweek(zUserName);
1160 break;
1161 case RPT_BYDAY:
1162 stats_report_byday(zUserName);
1163 break;
1164 default:
1165 case RPT_BYUSER:
1166 stats_report_by_user();
1167 break;
1168
+10 -1
--- src/style.c
+++ src/style.c
@@ -744,10 +744,18 @@
744744
void style_set_current_feature(const char* zFeature){
745745
fossil_free( local_zCurrentFeature );
746746
local_zCurrentFeature = fossil_strdup(zFeature);
747747
Th_Store("current_feature", zFeature);
748748
}
749
+
750
+/*
751
+** Returns the local feature string, owned by this file and
752
+** invalidated by style_set_current_feature().
753
+*/
754
+const char * style_get_current_feature(void){
755
+ return local_zCurrentFeature;
756
+}
749757
750758
/*
751759
** Returns the current mainmenu value from either the --mainmenu flag
752760
** (handled by the server/ui/cgi commands), the "mainmenu" config
753761
** setting, or style_default_mainmenu(), in that order, returning the
@@ -1024,11 +1032,12 @@
10241032
** "sml" stands for submenu link.
10251033
*/
10261034
if( p->zLink==0 ){
10271035
@ <span class="label sml-%s(zClass)">%h(p->zLabel)</span>
10281036
}else{
1029
- @ <a class="label sml-%s(zClass)" href="%h(p->zLink)">%h(p->zLabel)</a>
1037
+ @ <a class="label sml-%s(zClass)" \
1038
+ @ href="%h(p->zLink)">%h(p->zLabel)</a>
10301039
}
10311040
}
10321041
}
10331042
fossil_strcpy(zClass,"smc-"); /* common prefix for submenu controls */
10341043
for(i=0; i<nSubmenuCtrl; i++){
10351044
--- src/style.c
+++ src/style.c
@@ -744,10 +744,18 @@
744 void style_set_current_feature(const char* zFeature){
745 fossil_free( local_zCurrentFeature );
746 local_zCurrentFeature = fossil_strdup(zFeature);
747 Th_Store("current_feature", zFeature);
748 }
 
 
 
 
 
 
 
 
749
750 /*
751 ** Returns the current mainmenu value from either the --mainmenu flag
752 ** (handled by the server/ui/cgi commands), the "mainmenu" config
753 ** setting, or style_default_mainmenu(), in that order, returning the
@@ -1024,11 +1032,12 @@
1024 ** "sml" stands for submenu link.
1025 */
1026 if( p->zLink==0 ){
1027 @ <span class="label sml-%s(zClass)">%h(p->zLabel)</span>
1028 }else{
1029 @ <a class="label sml-%s(zClass)" href="%h(p->zLink)">%h(p->zLabel)</a>
 
1030 }
1031 }
1032 }
1033 fossil_strcpy(zClass,"smc-"); /* common prefix for submenu controls */
1034 for(i=0; i<nSubmenuCtrl; i++){
1035
--- src/style.c
+++ src/style.c
@@ -744,10 +744,18 @@
744 void style_set_current_feature(const char* zFeature){
745 fossil_free( local_zCurrentFeature );
746 local_zCurrentFeature = fossil_strdup(zFeature);
747 Th_Store("current_feature", zFeature);
748 }
749
750 /*
751 ** Returns the local feature string, owned by this file and
752 ** invalidated by style_set_current_feature().
753 */
754 const char * style_get_current_feature(void){
755 return local_zCurrentFeature;
756 }
757
758 /*
759 ** Returns the current mainmenu value from either the --mainmenu flag
760 ** (handled by the server/ui/cgi commands), the "mainmenu" config
761 ** setting, or style_default_mainmenu(), in that order, returning the
@@ -1024,11 +1032,12 @@
1032 ** "sml" stands for submenu link.
1033 */
1034 if( p->zLink==0 ){
1035 @ <span class="label sml-%s(zClass)">%h(p->zLabel)</span>
1036 }else{
1037 @ <a class="label sml-%s(zClass)" \
1038 @ href="%h(p->zLink)">%h(p->zLabel)</a>
1039 }
1040 }
1041 }
1042 fossil_strcpy(zClass,"smc-"); /* common prefix for submenu controls */
1043 for(i=0; i<nSubmenuCtrl; i++){
1044
--- src/style.forum.css
+++ src/style.forum.css
@@ -101,5 +101,9 @@
101101
.forumTime {
102102
/* Animate the transition when a ForumPostEditor shifts
103103
its post to the left. */
104104
transition: margin-left 0.25s linear;
105105
}
106
+
107
+.forum form input.action-approve {
108
+ margin-right: 1em;
109
+}
106110
--- src/style.forum.css
+++ src/style.forum.css
@@ -101,5 +101,9 @@
101 .forumTime {
102 /* Animate the transition when a ForumPostEditor shifts
103 its post to the left. */
104 transition: margin-left 0.25s linear;
105 }
 
 
 
 
106
--- src/style.forum.css
+++ src/style.forum.css
@@ -101,5 +101,9 @@
101 .forumTime {
102 /* Animate the transition when a ForumPostEditor shifts
103 its post to the left. */
104 transition: margin-left 0.25s linear;
105 }
106
107 .forum form input.action-approve {
108 margin-right: 1em;
109 }
110
+40 -13
--- src/timeline.c
+++ src/timeline.c
@@ -1267,11 +1267,11 @@
12671267
** set the y= parameter that determines which elements to display
12681268
** on the timeline.
12691269
*/
12701270
static void timeline_y_submenu(int isDisabled){
12711271
static int i = 0;
1272
- static const char *az[16];
1272
+ static const char *az[20];
12731273
if( i==0 ){
12741274
az[0] = "all";
12751275
az[1] = "Any Type";
12761276
i = 2;
12771277
if( g.perm.Read ){
@@ -1295,10 +1295,12 @@
12951295
az[i++] = "Wiki";
12961296
}
12971297
if( g.perm.RdForum ){
12981298
az[i++] = "f";
12991299
az[i++] = "Forum";
1300
+ az[i++] = "h";
1301
+ az[i++] = "New Threads";
13001302
}
13011303
assert( i<=count(az) );
13021304
}
13031305
if( i>2 ){
13041306
style_submenu_multichoice("y", i/2, az, isDisabled);
@@ -1507,10 +1509,18 @@
15071509
** when moving either forwards are backwards in time from a
15081510
** particular starting point (iFrom). Return the rid of that
15091511
** first check-in. If there are no check-ins in the descendant
15101512
** or ancestor set of check-in iFrom that match the tag, then
15111513
** return 0.
1514
+**
1515
+** If looking fowards (if bForward is true) then the first link
1516
+** is allowed to be a cherrypick, but subsequent links must be
1517
+** either full merges or normal check-ins. The idea is that we
1518
+** are looking for the first use of the code in the iFrom check-in
1519
+** that has the zEnd tag. The first link is allowed to be a cherrypick
1520
+** because the code in question crosses that link, but the code does
1521
+** not cross any subsequent cherrypick.
15121522
*/
15131523
static int timeline_endpoint(
15141524
int iFrom, /* Starting point */
15151525
const char *zEnd, /* Tag we are searching for */
15161526
int bForward /* 1: forwards in time (descendants) 0: backwards */
@@ -1530,10 +1540,14 @@
15301540
if( tagId ){
15311541
db_prepare(&q,
15321542
"WITH RECURSIVE dx(id,mtime) AS ("
15331543
" SELECT %d, event.mtime FROM event WHERE objid=%d"
15341544
" UNION"
1545
+ " SELECT cp.childid, event.mtime FROM cherrypick AS cp, event"
1546
+ " WHERE cp.parentid=%d AND NOT cp.isExclude"
1547
+ " AND event.objid=cp.childid"
1548
+ " UNION"
15351549
" SELECT plink.cid, plink.mtime"
15361550
" FROM dx, plink"
15371551
" WHERE plink.pid=dx.id"
15381552
" AND plink.mtime<=(SELECT max(event.mtime) FROM tagxref, event"
15391553
" WHERE tagxref.tagid=%d AND tagxref.tagtype>0"
@@ -1540,24 +1554,28 @@
15401554
" AND event.objid=tagxref.rid)"
15411555
" ORDER BY plink.mtime)"
15421556
"SELECT id FROM dx, tagxref"
15431557
" WHERE tagid=%d AND tagtype>0 AND rid=id"
15441558
" ORDER BY dx.mtime LIMIT 1",
1545
- iFrom, iFrom, tagId, tagId
1559
+ iFrom, iFrom, iFrom, tagId, tagId
15461560
);
15471561
}else{
15481562
db_prepare(&q,
15491563
"WITH RECURSIVE dx(id,mtime) AS ("
15501564
" SELECT %d, event.mtime FROM event WHERE objid=%d"
1565
+ " UNION"
1566
+ " SELECT cp.childid, event.mtime FROM cherrypick AS cp, event"
1567
+ " WHERE cp.parentid=%d AND NOT cp.isExclude"
1568
+ " AND event.objid=cp.childid"
15511569
" UNION"
15521570
" SELECT plink.cid, plink.mtime"
15531571
" FROM dx, plink"
15541572
" WHERE plink.pid=dx.id"
15551573
" AND plink.mtime<=(SELECT mtime FROM event WHERE objid=%d)"
15561574
" ORDER BY plink.mtime)"
15571575
"SELECT id FROM dx WHERE id=%d",
1558
- iFrom, iFrom, endId, endId
1576
+ iFrom, iFrom, iFrom, endId, endId
15591577
);
15601578
}
15611579
}else{
15621580
if( tagId ){
15631581
db_prepare(&q,
@@ -1720,11 +1738,11 @@
17201738
** mionly Show related parents but not related children.
17211739
** nowiki Do not show wiki associated with branch or tag
17221740
** ms=MATCHSTYLE Set tag name match algorithm. One of "exact", "glob",
17231741
** "like", or "regexp".
17241742
** u=USER Only show items associated with USER
1725
-** y=TYPE 'ci', 'w', 't', 'n', 'e', 'f', or 'all'.
1743
+** y=TYPE 'ci', 'w', 't', 'n', 'e', 'f', 'h', or 'all'.
17261744
** ss=VIEWSTYLE c: "Compact", v: "Verbose", m: "Modern", j: "Columnar",
17271745
** x: "Classic".
17281746
** advm Use the "Advanced" or "Busy" menu design.
17291747
** ng No Graph.
17301748
** ncp Omit cherrypick merges
@@ -1850,11 +1868,11 @@
18501868
int showCherrypicks = 1; /* True to show cherrypick merges */
18511869
int haveParameterN; /* True if n= query parameter present */
18521870
int from_to_mode = 0; /* 0: from,to. 1: from,ft 2: from,bt */
18531871
int showSql = PB("showsql"); /* True to show the SQL */
18541872
Blob allSql; /* Copy of all SQL text */
1855
- int bMin = P("min")!=0; /* True if "min" query parameter used */
1873
+ int bMin = PB("min"); /* True if "min" query parameter used */
18561874
18571875
login_check_credentials();
18581876
url_initialize(&url, "timeline");
18591877
cgi_query_parameters_to_url(&url);
18601878
blob_init(&allSql, 0, 0);
@@ -2219,11 +2237,11 @@
22192237
22202238
if( from_rid && to_rid ){
22212239
if( from_to_mode==0 ){
22222240
p = path_shortest(from_rid, to_rid, 0, 0, 0, cost);
22232241
}else if( from_to_mode==1 ){
2224
- p = path_shortest(from_rid, to_rid, 0, 1, 0, cost);
2242
+ p = path_shortest(from_rid, to_rid, 0, 2, 0, cost);
22252243
earlierRid = commonAncs = from_rid;
22262244
laterRid = to_rid;
22272245
}else{
22282246
p = path_shortest(to_rid, from_rid, 0, 1, 0, cost);
22292247
earlierRid = commonAncs = to_rid;
@@ -2270,10 +2288,11 @@
22702288
}else{
22712289
cnt++;
22722290
blob_append_sql(&ins, ",(%d)", p->rid);
22732291
}
22742292
}
2293
+ style_submenu_checkbox("min","Brief",0,0);
22752294
}
22762295
path_reset();
22772296
db_multi_exec("%s", blob_str(&ins)/*safe-for-%s*/);
22782297
blob_reset(&ins);
22792298
if( related ){
@@ -2661,26 +2680,26 @@
26612680
int bZulu = 0;
26622681
const char *zTZMod;
26632682
zYearWeek = timeline_expand_datetime(zYearWeek, &bZulu);
26642683
z = db_text(0, "SELECT strftime('%%Y-%%W',%Q)", zYearWeek);
26652684
if( z && z[0] ){
2666
- zYearWeekStart = db_text(0, "SELECT date(%Q,'-6 days','weekday 1')",
2685
+ zYearWeekStart = db_text(0, "SELECT date(%Q,'weekday -1')",
26672686
zYearWeek);
26682687
zYearWeek = z;
26692688
}else{
26702689
if( strlen(zYearWeek)==7 ){
26712690
zYearWeekStart = db_text(0,
2672
- "SELECT date('%.4q-01-01','%+d days','weekday 1')",
2673
- zYearWeek, atoi(zYearWeek+5)*7-6);
2691
+ "SELECT date('%.4q-01-01','weekday 1','%+d days')",
2692
+ zYearWeek, atoi(zYearWeek+5)*7 - 7);
26742693
}else{
26752694
zYearWeekStart = 0;
26762695
}
26772696
if( zYearWeekStart==0 || zYearWeekStart[0]==0 ){
26782697
zYearWeekStart = db_text(0,
2679
- "SELECT date('now','-6 days','weekday 1');");
2698
+ "SELECT date('now','weekday -1');");
26802699
zYearWeek = db_text(0,
2681
- "SELECT strftime('%%Y-%%W','now','-6 days','weekday 1')");
2700
+ "SELECT strftime('%%Y-%%W','now','weekday -1')");
26822701
}
26832702
}
26842703
zTZMod = (bZulu==0 && fossil_ui_localtime()) ? "utc" : "+00:00";
26852704
if( db_int(0,
26862705
"SELECT EXISTS (SELECT 1 FROM event CROSS JOIN blob"
@@ -2944,10 +2963,11 @@
29442963
|| (zType[0]=='n' && !g.perm.RdTkt)
29452964
|| (zType[0]=='e' && !g.perm.RdWiki)
29462965
|| (zType[0]=='c' && !g.perm.Read)
29472966
|| (zType[0]=='g' && !g.perm.Read)
29482967
|| (zType[0]=='f' && !g.perm.RdForum)
2968
+ || (zType[0]=='h' && !g.perm.RdForum)
29492969
){
29502970
zType = "all";
29512971
}
29522972
if( zType[0]=='a' ){
29532973
if( !g.perm.Read || !g.perm.RdWiki || !g.perm.RdTkt ){
@@ -2973,10 +2993,13 @@
29732993
}
29742994
}else{ /* zType!="all" */
29752995
if( zType[0]=='n' ){
29762996
blob_append_sql(&cond,
29772997
" AND event.type='t' AND event.comment GLOB 'New ticket*'");
2998
+ }else if( zType[0]=='h' ){
2999
+ blob_append_sql(&cond,
3000
+ " AND event.type='f' AND event.comment GLOB 'Post:*'");
29783001
}else{
29793002
blob_append_sql(&cond, " AND event.type=%Q", zType);
29803003
}
29813004
if( zType[0]=='c' ){
29823005
zEType = "check-in";
@@ -2990,10 +3013,12 @@
29903013
zEType = "technical note";
29913014
}else if( zType[0]=='g' ){
29923015
zEType = "tag";
29933016
}else if( zType[0]=='f' ){
29943017
zEType = "forum post";
3018
+ }else if( zType[0]=='h' ){
3019
+ zEType = "new forum thread";
29953020
}
29963021
}
29973022
if( zUser ){
29983023
int n = db_int(0,"SELECT count(*) FROM event"
29993024
" WHERE user=%Q OR euser=%Q", zUser, zUser);
@@ -3072,12 +3097,14 @@
30723097
zPlural = n==1 ? "" : "s";
30733098
if( zYearMonth ){
30743099
blob_appendf(&desc, "%d %s%s for the month beginning %h",
30753100
n, zEType, zPlural, zYearMonth);
30763101
}else if( zYearWeek ){
3077
- blob_appendf(&desc, "%d %s%s for week %h beginning on %h",
3078
- n, zEType, zPlural, zYearWeek, zYearWeekStart);
3102
+ char *zEnd = db_text("?","SELECT date(%Q,'weekday 0')",zYearWeekStart);
3103
+ blob_appendf(&desc, "%d %s%s for week %h spanning %h to %h",
3104
+ n, zEType, zPlural, zYearWeek, zYearWeekStart, zEnd);
3105
+ fossil_free(zEnd);
30793106
}else if( zDay ){
30803107
blob_appendf(&desc, "%d %s%s occurring on %h", n, zEType, zPlural, zDay);
30813108
}else if( zNDays ){
30823109
blob_appendf(&desc, "%d %s%s within the past %d day%s",
30833110
n, zEType, zPlural, nDays, nDays>1 ? "s" : "");
30843111
--- src/timeline.c
+++ src/timeline.c
@@ -1267,11 +1267,11 @@
1267 ** set the y= parameter that determines which elements to display
1268 ** on the timeline.
1269 */
1270 static void timeline_y_submenu(int isDisabled){
1271 static int i = 0;
1272 static const char *az[16];
1273 if( i==0 ){
1274 az[0] = "all";
1275 az[1] = "Any Type";
1276 i = 2;
1277 if( g.perm.Read ){
@@ -1295,10 +1295,12 @@
1295 az[i++] = "Wiki";
1296 }
1297 if( g.perm.RdForum ){
1298 az[i++] = "f";
1299 az[i++] = "Forum";
 
 
1300 }
1301 assert( i<=count(az) );
1302 }
1303 if( i>2 ){
1304 style_submenu_multichoice("y", i/2, az, isDisabled);
@@ -1507,10 +1509,18 @@
1507 ** when moving either forwards are backwards in time from a
1508 ** particular starting point (iFrom). Return the rid of that
1509 ** first check-in. If there are no check-ins in the descendant
1510 ** or ancestor set of check-in iFrom that match the tag, then
1511 ** return 0.
 
 
 
 
 
 
 
 
1512 */
1513 static int timeline_endpoint(
1514 int iFrom, /* Starting point */
1515 const char *zEnd, /* Tag we are searching for */
1516 int bForward /* 1: forwards in time (descendants) 0: backwards */
@@ -1530,10 +1540,14 @@
1530 if( tagId ){
1531 db_prepare(&q,
1532 "WITH RECURSIVE dx(id,mtime) AS ("
1533 " SELECT %d, event.mtime FROM event WHERE objid=%d"
1534 " UNION"
 
 
 
 
1535 " SELECT plink.cid, plink.mtime"
1536 " FROM dx, plink"
1537 " WHERE plink.pid=dx.id"
1538 " AND plink.mtime<=(SELECT max(event.mtime) FROM tagxref, event"
1539 " WHERE tagxref.tagid=%d AND tagxref.tagtype>0"
@@ -1540,24 +1554,28 @@
1540 " AND event.objid=tagxref.rid)"
1541 " ORDER BY plink.mtime)"
1542 "SELECT id FROM dx, tagxref"
1543 " WHERE tagid=%d AND tagtype>0 AND rid=id"
1544 " ORDER BY dx.mtime LIMIT 1",
1545 iFrom, iFrom, tagId, tagId
1546 );
1547 }else{
1548 db_prepare(&q,
1549 "WITH RECURSIVE dx(id,mtime) AS ("
1550 " SELECT %d, event.mtime FROM event WHERE objid=%d"
 
 
 
 
1551 " UNION"
1552 " SELECT plink.cid, plink.mtime"
1553 " FROM dx, plink"
1554 " WHERE plink.pid=dx.id"
1555 " AND plink.mtime<=(SELECT mtime FROM event WHERE objid=%d)"
1556 " ORDER BY plink.mtime)"
1557 "SELECT id FROM dx WHERE id=%d",
1558 iFrom, iFrom, endId, endId
1559 );
1560 }
1561 }else{
1562 if( tagId ){
1563 db_prepare(&q,
@@ -1720,11 +1738,11 @@
1720 ** mionly Show related parents but not related children.
1721 ** nowiki Do not show wiki associated with branch or tag
1722 ** ms=MATCHSTYLE Set tag name match algorithm. One of "exact", "glob",
1723 ** "like", or "regexp".
1724 ** u=USER Only show items associated with USER
1725 ** y=TYPE 'ci', 'w', 't', 'n', 'e', 'f', or 'all'.
1726 ** ss=VIEWSTYLE c: "Compact", v: "Verbose", m: "Modern", j: "Columnar",
1727 ** x: "Classic".
1728 ** advm Use the "Advanced" or "Busy" menu design.
1729 ** ng No Graph.
1730 ** ncp Omit cherrypick merges
@@ -1850,11 +1868,11 @@
1850 int showCherrypicks = 1; /* True to show cherrypick merges */
1851 int haveParameterN; /* True if n= query parameter present */
1852 int from_to_mode = 0; /* 0: from,to. 1: from,ft 2: from,bt */
1853 int showSql = PB("showsql"); /* True to show the SQL */
1854 Blob allSql; /* Copy of all SQL text */
1855 int bMin = P("min")!=0; /* True if "min" query parameter used */
1856
1857 login_check_credentials();
1858 url_initialize(&url, "timeline");
1859 cgi_query_parameters_to_url(&url);
1860 blob_init(&allSql, 0, 0);
@@ -2219,11 +2237,11 @@
2219
2220 if( from_rid && to_rid ){
2221 if( from_to_mode==0 ){
2222 p = path_shortest(from_rid, to_rid, 0, 0, 0, cost);
2223 }else if( from_to_mode==1 ){
2224 p = path_shortest(from_rid, to_rid, 0, 1, 0, cost);
2225 earlierRid = commonAncs = from_rid;
2226 laterRid = to_rid;
2227 }else{
2228 p = path_shortest(to_rid, from_rid, 0, 1, 0, cost);
2229 earlierRid = commonAncs = to_rid;
@@ -2270,10 +2288,11 @@
2270 }else{
2271 cnt++;
2272 blob_append_sql(&ins, ",(%d)", p->rid);
2273 }
2274 }
 
2275 }
2276 path_reset();
2277 db_multi_exec("%s", blob_str(&ins)/*safe-for-%s*/);
2278 blob_reset(&ins);
2279 if( related ){
@@ -2661,26 +2680,26 @@
2661 int bZulu = 0;
2662 const char *zTZMod;
2663 zYearWeek = timeline_expand_datetime(zYearWeek, &bZulu);
2664 z = db_text(0, "SELECT strftime('%%Y-%%W',%Q)", zYearWeek);
2665 if( z && z[0] ){
2666 zYearWeekStart = db_text(0, "SELECT date(%Q,'-6 days','weekday 1')",
2667 zYearWeek);
2668 zYearWeek = z;
2669 }else{
2670 if( strlen(zYearWeek)==7 ){
2671 zYearWeekStart = db_text(0,
2672 "SELECT date('%.4q-01-01','%+d days','weekday 1')",
2673 zYearWeek, atoi(zYearWeek+5)*7-6);
2674 }else{
2675 zYearWeekStart = 0;
2676 }
2677 if( zYearWeekStart==0 || zYearWeekStart[0]==0 ){
2678 zYearWeekStart = db_text(0,
2679 "SELECT date('now','-6 days','weekday 1');");
2680 zYearWeek = db_text(0,
2681 "SELECT strftime('%%Y-%%W','now','-6 days','weekday 1')");
2682 }
2683 }
2684 zTZMod = (bZulu==0 && fossil_ui_localtime()) ? "utc" : "+00:00";
2685 if( db_int(0,
2686 "SELECT EXISTS (SELECT 1 FROM event CROSS JOIN blob"
@@ -2944,10 +2963,11 @@
2944 || (zType[0]=='n' && !g.perm.RdTkt)
2945 || (zType[0]=='e' && !g.perm.RdWiki)
2946 || (zType[0]=='c' && !g.perm.Read)
2947 || (zType[0]=='g' && !g.perm.Read)
2948 || (zType[0]=='f' && !g.perm.RdForum)
 
2949 ){
2950 zType = "all";
2951 }
2952 if( zType[0]=='a' ){
2953 if( !g.perm.Read || !g.perm.RdWiki || !g.perm.RdTkt ){
@@ -2973,10 +2993,13 @@
2973 }
2974 }else{ /* zType!="all" */
2975 if( zType[0]=='n' ){
2976 blob_append_sql(&cond,
2977 " AND event.type='t' AND event.comment GLOB 'New ticket*'");
 
 
 
2978 }else{
2979 blob_append_sql(&cond, " AND event.type=%Q", zType);
2980 }
2981 if( zType[0]=='c' ){
2982 zEType = "check-in";
@@ -2990,10 +3013,12 @@
2990 zEType = "technical note";
2991 }else if( zType[0]=='g' ){
2992 zEType = "tag";
2993 }else if( zType[0]=='f' ){
2994 zEType = "forum post";
 
 
2995 }
2996 }
2997 if( zUser ){
2998 int n = db_int(0,"SELECT count(*) FROM event"
2999 " WHERE user=%Q OR euser=%Q", zUser, zUser);
@@ -3072,12 +3097,14 @@
3072 zPlural = n==1 ? "" : "s";
3073 if( zYearMonth ){
3074 blob_appendf(&desc, "%d %s%s for the month beginning %h",
3075 n, zEType, zPlural, zYearMonth);
3076 }else if( zYearWeek ){
3077 blob_appendf(&desc, "%d %s%s for week %h beginning on %h",
3078 n, zEType, zPlural, zYearWeek, zYearWeekStart);
 
 
3079 }else if( zDay ){
3080 blob_appendf(&desc, "%d %s%s occurring on %h", n, zEType, zPlural, zDay);
3081 }else if( zNDays ){
3082 blob_appendf(&desc, "%d %s%s within the past %d day%s",
3083 n, zEType, zPlural, nDays, nDays>1 ? "s" : "");
3084
--- src/timeline.c
+++ src/timeline.c
@@ -1267,11 +1267,11 @@
1267 ** set the y= parameter that determines which elements to display
1268 ** on the timeline.
1269 */
1270 static void timeline_y_submenu(int isDisabled){
1271 static int i = 0;
1272 static const char *az[20];
1273 if( i==0 ){
1274 az[0] = "all";
1275 az[1] = "Any Type";
1276 i = 2;
1277 if( g.perm.Read ){
@@ -1295,10 +1295,12 @@
1295 az[i++] = "Wiki";
1296 }
1297 if( g.perm.RdForum ){
1298 az[i++] = "f";
1299 az[i++] = "Forum";
1300 az[i++] = "h";
1301 az[i++] = "New Threads";
1302 }
1303 assert( i<=count(az) );
1304 }
1305 if( i>2 ){
1306 style_submenu_multichoice("y", i/2, az, isDisabled);
@@ -1507,10 +1509,18 @@
1509 ** when moving either forwards are backwards in time from a
1510 ** particular starting point (iFrom). Return the rid of that
1511 ** first check-in. If there are no check-ins in the descendant
1512 ** or ancestor set of check-in iFrom that match the tag, then
1513 ** return 0.
1514 **
1515 ** If looking fowards (if bForward is true) then the first link
1516 ** is allowed to be a cherrypick, but subsequent links must be
1517 ** either full merges or normal check-ins. The idea is that we
1518 ** are looking for the first use of the code in the iFrom check-in
1519 ** that has the zEnd tag. The first link is allowed to be a cherrypick
1520 ** because the code in question crosses that link, but the code does
1521 ** not cross any subsequent cherrypick.
1522 */
1523 static int timeline_endpoint(
1524 int iFrom, /* Starting point */
1525 const char *zEnd, /* Tag we are searching for */
1526 int bForward /* 1: forwards in time (descendants) 0: backwards */
@@ -1530,10 +1540,14 @@
1540 if( tagId ){
1541 db_prepare(&q,
1542 "WITH RECURSIVE dx(id,mtime) AS ("
1543 " SELECT %d, event.mtime FROM event WHERE objid=%d"
1544 " UNION"
1545 " SELECT cp.childid, event.mtime FROM cherrypick AS cp, event"
1546 " WHERE cp.parentid=%d AND NOT cp.isExclude"
1547 " AND event.objid=cp.childid"
1548 " UNION"
1549 " SELECT plink.cid, plink.mtime"
1550 " FROM dx, plink"
1551 " WHERE plink.pid=dx.id"
1552 " AND plink.mtime<=(SELECT max(event.mtime) FROM tagxref, event"
1553 " WHERE tagxref.tagid=%d AND tagxref.tagtype>0"
@@ -1540,24 +1554,28 @@
1554 " AND event.objid=tagxref.rid)"
1555 " ORDER BY plink.mtime)"
1556 "SELECT id FROM dx, tagxref"
1557 " WHERE tagid=%d AND tagtype>0 AND rid=id"
1558 " ORDER BY dx.mtime LIMIT 1",
1559 iFrom, iFrom, iFrom, tagId, tagId
1560 );
1561 }else{
1562 db_prepare(&q,
1563 "WITH RECURSIVE dx(id,mtime) AS ("
1564 " SELECT %d, event.mtime FROM event WHERE objid=%d"
1565 " UNION"
1566 " SELECT cp.childid, event.mtime FROM cherrypick AS cp, event"
1567 " WHERE cp.parentid=%d AND NOT cp.isExclude"
1568 " AND event.objid=cp.childid"
1569 " UNION"
1570 " SELECT plink.cid, plink.mtime"
1571 " FROM dx, plink"
1572 " WHERE plink.pid=dx.id"
1573 " AND plink.mtime<=(SELECT mtime FROM event WHERE objid=%d)"
1574 " ORDER BY plink.mtime)"
1575 "SELECT id FROM dx WHERE id=%d",
1576 iFrom, iFrom, iFrom, endId, endId
1577 );
1578 }
1579 }else{
1580 if( tagId ){
1581 db_prepare(&q,
@@ -1720,11 +1738,11 @@
1738 ** mionly Show related parents but not related children.
1739 ** nowiki Do not show wiki associated with branch or tag
1740 ** ms=MATCHSTYLE Set tag name match algorithm. One of "exact", "glob",
1741 ** "like", or "regexp".
1742 ** u=USER Only show items associated with USER
1743 ** y=TYPE 'ci', 'w', 't', 'n', 'e', 'f', 'h', or 'all'.
1744 ** ss=VIEWSTYLE c: "Compact", v: "Verbose", m: "Modern", j: "Columnar",
1745 ** x: "Classic".
1746 ** advm Use the "Advanced" or "Busy" menu design.
1747 ** ng No Graph.
1748 ** ncp Omit cherrypick merges
@@ -1850,11 +1868,11 @@
1868 int showCherrypicks = 1; /* True to show cherrypick merges */
1869 int haveParameterN; /* True if n= query parameter present */
1870 int from_to_mode = 0; /* 0: from,to. 1: from,ft 2: from,bt */
1871 int showSql = PB("showsql"); /* True to show the SQL */
1872 Blob allSql; /* Copy of all SQL text */
1873 int bMin = PB("min"); /* True if "min" query parameter used */
1874
1875 login_check_credentials();
1876 url_initialize(&url, "timeline");
1877 cgi_query_parameters_to_url(&url);
1878 blob_init(&allSql, 0, 0);
@@ -2219,11 +2237,11 @@
2237
2238 if( from_rid && to_rid ){
2239 if( from_to_mode==0 ){
2240 p = path_shortest(from_rid, to_rid, 0, 0, 0, cost);
2241 }else if( from_to_mode==1 ){
2242 p = path_shortest(from_rid, to_rid, 0, 2, 0, cost);
2243 earlierRid = commonAncs = from_rid;
2244 laterRid = to_rid;
2245 }else{
2246 p = path_shortest(to_rid, from_rid, 0, 1, 0, cost);
2247 earlierRid = commonAncs = to_rid;
@@ -2270,10 +2288,11 @@
2288 }else{
2289 cnt++;
2290 blob_append_sql(&ins, ",(%d)", p->rid);
2291 }
2292 }
2293 style_submenu_checkbox("min","Brief",0,0);
2294 }
2295 path_reset();
2296 db_multi_exec("%s", blob_str(&ins)/*safe-for-%s*/);
2297 blob_reset(&ins);
2298 if( related ){
@@ -2661,26 +2680,26 @@
2680 int bZulu = 0;
2681 const char *zTZMod;
2682 zYearWeek = timeline_expand_datetime(zYearWeek, &bZulu);
2683 z = db_text(0, "SELECT strftime('%%Y-%%W',%Q)", zYearWeek);
2684 if( z && z[0] ){
2685 zYearWeekStart = db_text(0, "SELECT date(%Q,'weekday -1')",
2686 zYearWeek);
2687 zYearWeek = z;
2688 }else{
2689 if( strlen(zYearWeek)==7 ){
2690 zYearWeekStart = db_text(0,
2691 "SELECT date('%.4q-01-01','weekday 1','%+d days')",
2692 zYearWeek, atoi(zYearWeek+5)*7 - 7);
2693 }else{
2694 zYearWeekStart = 0;
2695 }
2696 if( zYearWeekStart==0 || zYearWeekStart[0]==0 ){
2697 zYearWeekStart = db_text(0,
2698 "SELECT date('now','weekday -1');");
2699 zYearWeek = db_text(0,
2700 "SELECT strftime('%%Y-%%W','now','weekday -1')");
2701 }
2702 }
2703 zTZMod = (bZulu==0 && fossil_ui_localtime()) ? "utc" : "+00:00";
2704 if( db_int(0,
2705 "SELECT EXISTS (SELECT 1 FROM event CROSS JOIN blob"
@@ -2944,10 +2963,11 @@
2963 || (zType[0]=='n' && !g.perm.RdTkt)
2964 || (zType[0]=='e' && !g.perm.RdWiki)
2965 || (zType[0]=='c' && !g.perm.Read)
2966 || (zType[0]=='g' && !g.perm.Read)
2967 || (zType[0]=='f' && !g.perm.RdForum)
2968 || (zType[0]=='h' && !g.perm.RdForum)
2969 ){
2970 zType = "all";
2971 }
2972 if( zType[0]=='a' ){
2973 if( !g.perm.Read || !g.perm.RdWiki || !g.perm.RdTkt ){
@@ -2973,10 +2993,13 @@
2993 }
2994 }else{ /* zType!="all" */
2995 if( zType[0]=='n' ){
2996 blob_append_sql(&cond,
2997 " AND event.type='t' AND event.comment GLOB 'New ticket*'");
2998 }else if( zType[0]=='h' ){
2999 blob_append_sql(&cond,
3000 " AND event.type='f' AND event.comment GLOB 'Post:*'");
3001 }else{
3002 blob_append_sql(&cond, " AND event.type=%Q", zType);
3003 }
3004 if( zType[0]=='c' ){
3005 zEType = "check-in";
@@ -2990,10 +3013,12 @@
3013 zEType = "technical note";
3014 }else if( zType[0]=='g' ){
3015 zEType = "tag";
3016 }else if( zType[0]=='f' ){
3017 zEType = "forum post";
3018 }else if( zType[0]=='h' ){
3019 zEType = "new forum thread";
3020 }
3021 }
3022 if( zUser ){
3023 int n = db_int(0,"SELECT count(*) FROM event"
3024 " WHERE user=%Q OR euser=%Q", zUser, zUser);
@@ -3072,12 +3097,14 @@
3097 zPlural = n==1 ? "" : "s";
3098 if( zYearMonth ){
3099 blob_appendf(&desc, "%d %s%s for the month beginning %h",
3100 n, zEType, zPlural, zYearMonth);
3101 }else if( zYearWeek ){
3102 char *zEnd = db_text("?","SELECT date(%Q,'weekday 0')",zYearWeekStart);
3103 blob_appendf(&desc, "%d %s%s for week %h spanning %h to %h",
3104 n, zEType, zPlural, zYearWeek, zYearWeekStart, zEnd);
3105 fossil_free(zEnd);
3106 }else if( zDay ){
3107 blob_appendf(&desc, "%d %s%s occurring on %h", n, zEType, zPlural, zDay);
3108 }else if( zNDays ){
3109 blob_appendf(&desc, "%d %s%s within the past %d day%s",
3110 n, zEType, zPlural, nDays, nDays>1 ? "s" : "");
3111
+3 -5
--- src/wiki.c
+++ src/wiki.c
@@ -2073,11 +2073,10 @@
20732073
int wiki_cmd_commit(const char *zPageName, int rid, Blob *pContent,
20742074
const char *zMimeType, int localUser){
20752075
Blob wiki; /* Wiki page content */
20762076
Blob cksum; /* wiki checksum */
20772077
char *zDate; /* timestamp */
2078
- char *zUuid; /* uuid for rid */
20792078
20802079
blob_zero(&wiki);
20812080
zDate = date_in_standard_format("now");
20822081
blob_appendf(&wiki, "D %s\n", zDate);
20832082
free(zDate);
@@ -2085,17 +2084,16 @@
20852084
if( zMimeType && *zMimeType
20862085
&& 0!=fossil_strcmp(zMimeType,"text/x-fossil-wiki") ){
20872086
blob_appendf(&wiki, "N %F\n", zMimeType);
20882087
}
20892088
if( rid ){
2090
- zUuid = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", rid);
2091
- blob_appendf(&wiki, "P %s\n", zUuid);
2092
- free(zUuid);
2089
+ char *zUuid = rid_to_uuid(rid);
2090
+ blob_appendf(&wiki, "P %z\n", zUuid);
20932091
}
20942092
user_select();
20952093
if( !login_is_nobody() ){
2096
- blob_appendf(&wiki, "U %F\n", login_name());
2094
+ blob_appendf(&wiki, "U %F\n", login_name());
20972095
}
20982096
blob_appendf( &wiki, "W %d\n%s\n", blob_size(pContent),
20992097
blob_str(pContent) );
21002098
md5sum_blob(&wiki, &cksum);
21012099
blob_appendf(&wiki, "Z %b\n", &cksum);
21022100
--- src/wiki.c
+++ src/wiki.c
@@ -2073,11 +2073,10 @@
2073 int wiki_cmd_commit(const char *zPageName, int rid, Blob *pContent,
2074 const char *zMimeType, int localUser){
2075 Blob wiki; /* Wiki page content */
2076 Blob cksum; /* wiki checksum */
2077 char *zDate; /* timestamp */
2078 char *zUuid; /* uuid for rid */
2079
2080 blob_zero(&wiki);
2081 zDate = date_in_standard_format("now");
2082 blob_appendf(&wiki, "D %s\n", zDate);
2083 free(zDate);
@@ -2085,17 +2084,16 @@
2085 if( zMimeType && *zMimeType
2086 && 0!=fossil_strcmp(zMimeType,"text/x-fossil-wiki") ){
2087 blob_appendf(&wiki, "N %F\n", zMimeType);
2088 }
2089 if( rid ){
2090 zUuid = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", rid);
2091 blob_appendf(&wiki, "P %s\n", zUuid);
2092 free(zUuid);
2093 }
2094 user_select();
2095 if( !login_is_nobody() ){
2096 blob_appendf(&wiki, "U %F\n", login_name());
2097 }
2098 blob_appendf( &wiki, "W %d\n%s\n", blob_size(pContent),
2099 blob_str(pContent) );
2100 md5sum_blob(&wiki, &cksum);
2101 blob_appendf(&wiki, "Z %b\n", &cksum);
2102
--- src/wiki.c
+++ src/wiki.c
@@ -2073,11 +2073,10 @@
2073 int wiki_cmd_commit(const char *zPageName, int rid, Blob *pContent,
2074 const char *zMimeType, int localUser){
2075 Blob wiki; /* Wiki page content */
2076 Blob cksum; /* wiki checksum */
2077 char *zDate; /* timestamp */
 
2078
2079 blob_zero(&wiki);
2080 zDate = date_in_standard_format("now");
2081 blob_appendf(&wiki, "D %s\n", zDate);
2082 free(zDate);
@@ -2085,17 +2084,16 @@
2084 if( zMimeType && *zMimeType
2085 && 0!=fossil_strcmp(zMimeType,"text/x-fossil-wiki") ){
2086 blob_appendf(&wiki, "N %F\n", zMimeType);
2087 }
2088 if( rid ){
2089 char *zUuid = rid_to_uuid(rid);
2090 blob_appendf(&wiki, "P %z\n", zUuid);
 
2091 }
2092 user_select();
2093 if( !login_is_nobody() ){
2094 blob_appendf(&wiki, "U %F\n", login_name());
2095 }
2096 blob_appendf( &wiki, "W %d\n%s\n", blob_size(pContent),
2097 blob_str(pContent) );
2098 md5sum_blob(&wiki, &cksum);
2099 blob_appendf(&wiki, "Z %b\n", &cksum);
2100
+58 -10
--- src/wikiformat.c
+++ src/wikiformat.c
@@ -302,12 +302,12 @@
302302
MARKUP_TR,
303303
MARKUP_TT,
304304
MARKUP_U,
305305
MARKUP_UL,
306306
MARKUP_VAR,
307
- MARKUP_WBR,
308
- MARKUP_VERBATIM
307
+ MARKUP_VERBATIM,
308
+ MARKUP_WBR
309309
};
310310
311311
/*
312312
** The various markup is divided into the following types:
313313
*/
@@ -469,13 +469,13 @@
469469
{ "tt", MARKUP_TT, MUTYPE_FONT, AMSK_STYLE },
470470
{ "u", MARKUP_U, MUTYPE_FONT, AMSK_STYLE },
471471
{ "ul", MARKUP_UL, MUTYPE_LIST,
472472
AMSK_TYPE|AMSK_COMPACT|AMSK_STYLE },
473473
{ "var", MARKUP_VAR, MUTYPE_FONT, AMSK_STYLE },
474
- { "wbr", MARKUP_WBR, MUTYPE_SINGLE, 0 },
475474
{ "verbatim", MARKUP_VERBATIM, MUTYPE_SPECIAL,
476475
AMSK_ID|AMSK_TYPE },
476
+ { "wbr", MARKUP_WBR, MUTYPE_SINGLE, 0 },
477477
};
478478
479479
void show_allowed_wiki_markup( void ){
480480
int i; /* loop over allowedAttr */
481481
for( i=1 ; i<=count(aMarkup) - 1 ; i++ ){
@@ -984,10 +984,57 @@
984984
while( fossil_isspace(z[i]) ){ i++; }
985985
if( z[i]==0 || z[i]=='>' || (z[i]=='/' && z[i+1]=='>') ) break;
986986
}
987987
return seen;
988988
}
989
+
990
+/*
991
+** Append an HTML attribute value, rewriting root-relative URLs in src
992
+** and srcset the same way (%R prefix).
993
+*/
994
+static void appendRewrittenAttrValue(Blob *pOut, int iACode, const char *zVal){
995
+ if( iACode==ATTR_SRC && zVal[0]=='/' ){
996
+ blob_appendf(pOut, "=\"%R%s\"", zVal);
997
+ return;
998
+ }
999
+ if( iACode==ATTR_SRCSET ){
1000
+ const char *z = zVal;
1001
+ int nCand = 0;
1002
+ blob_append_char(pOut, '=');
1003
+ blob_append_char(pOut, '"');
1004
+ while( z[0] ){
1005
+ const char *zComma = strchr(z, ',');
1006
+ int len = zComma ? (int)(zComma - z) : (int)strlen(z);
1007
+ const char *zCand = z;
1008
+ int urlStart = 0;
1009
+ int urlLen;
1010
+ if( len>0 ){
1011
+ while( urlStart<len && fossil_isspace(zCand[urlStart]) ) urlStart++;
1012
+ urlLen = urlStart;
1013
+ while( urlLen<len && !fossil_isspace(zCand[urlLen]) ) urlLen++;
1014
+ urlLen -= urlStart;
1015
+ if( nCand++ ) blob_append_char(pOut, ',');
1016
+ if( urlStart>0 ){
1017
+ blob_append(pOut, zCand, urlStart);
1018
+ }
1019
+ if( urlLen>0 && zCand[urlStart]=='/' ){
1020
+ blob_appendf(pOut, "%R%.*s", urlLen, zCand+urlStart);
1021
+ }else if( urlLen>0 ){
1022
+ blob_appendf(pOut, "%.*s", urlLen, zCand+urlStart);
1023
+ }
1024
+ if( urlStart+urlLen < len ){
1025
+ blob_appendf(pOut, "%.*s", len-urlStart-urlLen, zCand+urlStart+urlLen);
1026
+ }
1027
+ }
1028
+ if( zComma==0 ) break;
1029
+ z = zComma + 1;
1030
+ }
1031
+ blob_append_char(pOut, '"');
1032
+ return;
1033
+ }
1034
+ blob_appendf(pOut, "=\"%s\"", zVal);
1035
+}
9891036
9901037
/*
9911038
** Render markup on the given blob.
9921039
*/
9931040
static void renderMarkup(Blob *pOut, ParsedMarkup *p){
@@ -997,16 +1044,11 @@
9971044
}else{
9981045
blob_appendf(pOut, "<%s", aMarkup[p->iCode].zName);
9991046
for(i=0; i<p->nAttr; i++){
10001047
blob_appendf(pOut, " %s", aAttribute[p->aAttr[i].iACode].zName);
10011048
if( p->aAttr[i].zValue ){
1002
- const char *zVal = p->aAttr[i].zValue;
1003
- if( p->aAttr[i].iACode==ATTR_SRC && zVal[0]=='/' ){
1004
- blob_appendf(pOut, "=\"%R%s\"", zVal);
1005
- }else{
1006
- blob_appendf(pOut, "=\"%s\"", zVal);
1007
- }
1049
+ appendRewrittenAttrValue(pOut, p->aAttr[i].iACode, p->aAttr[i].zValue);
10081050
}
10091051
}
10101052
if (p->iType & MUTYPE_SINGLE){
10111053
blob_append_string(pOut, " /");
10121054
}
@@ -3105,19 +3147,25 @@
31053147
}
31063148
31073149
/*
31083150
** COMMAND: test-safe-html
31093151
**
3110
-** Usage: %fossil test-safe-html FILE ...
3152
+** Usage: %fossil test-safe-html ?OPTIONS? FILE ...
31113153
**
31123154
** Read files named on the command-line. Send the text of each file
31133155
** through safe_html_append() and then write the result on
31143156
** standard output.
3157
+**
3158
+** Options:
3159
+** --top PATH Use PATH as g.zTop when rewriting root-relative URLs
31153160
*/
31163161
void test_safe_html_cmd(void){
31173162
int i;
31183163
Blob x;
3164
+ const char *zTop = find_option("top",0,1);
3165
+ verify_all_options();
3166
+ if( zTop ) g.zTop = (char*)zTop;
31193167
for(i=2; i<g.argc; i++){
31203168
char *z;
31213169
int n;
31223170
blob_read_from_file(&x, g.argv[i], ExtFILE);
31233171
blob_terminate(&x);
31243172
--- src/wikiformat.c
+++ src/wikiformat.c
@@ -302,12 +302,12 @@
302 MARKUP_TR,
303 MARKUP_TT,
304 MARKUP_U,
305 MARKUP_UL,
306 MARKUP_VAR,
307 MARKUP_WBR,
308 MARKUP_VERBATIM
309 };
310
311 /*
312 ** The various markup is divided into the following types:
313 */
@@ -469,13 +469,13 @@
469 { "tt", MARKUP_TT, MUTYPE_FONT, AMSK_STYLE },
470 { "u", MARKUP_U, MUTYPE_FONT, AMSK_STYLE },
471 { "ul", MARKUP_UL, MUTYPE_LIST,
472 AMSK_TYPE|AMSK_COMPACT|AMSK_STYLE },
473 { "var", MARKUP_VAR, MUTYPE_FONT, AMSK_STYLE },
474 { "wbr", MARKUP_WBR, MUTYPE_SINGLE, 0 },
475 { "verbatim", MARKUP_VERBATIM, MUTYPE_SPECIAL,
476 AMSK_ID|AMSK_TYPE },
 
477 };
478
479 void show_allowed_wiki_markup( void ){
480 int i; /* loop over allowedAttr */
481 for( i=1 ; i<=count(aMarkup) - 1 ; i++ ){
@@ -984,10 +984,57 @@
984 while( fossil_isspace(z[i]) ){ i++; }
985 if( z[i]==0 || z[i]=='>' || (z[i]=='/' && z[i+1]=='>') ) break;
986 }
987 return seen;
988 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
989
990 /*
991 ** Render markup on the given blob.
992 */
993 static void renderMarkup(Blob *pOut, ParsedMarkup *p){
@@ -997,16 +1044,11 @@
997 }else{
998 blob_appendf(pOut, "<%s", aMarkup[p->iCode].zName);
999 for(i=0; i<p->nAttr; i++){
1000 blob_appendf(pOut, " %s", aAttribute[p->aAttr[i].iACode].zName);
1001 if( p->aAttr[i].zValue ){
1002 const char *zVal = p->aAttr[i].zValue;
1003 if( p->aAttr[i].iACode==ATTR_SRC && zVal[0]=='/' ){
1004 blob_appendf(pOut, "=\"%R%s\"", zVal);
1005 }else{
1006 blob_appendf(pOut, "=\"%s\"", zVal);
1007 }
1008 }
1009 }
1010 if (p->iType & MUTYPE_SINGLE){
1011 blob_append_string(pOut, " /");
1012 }
@@ -3105,19 +3147,25 @@
3105 }
3106
3107 /*
3108 ** COMMAND: test-safe-html
3109 **
3110 ** Usage: %fossil test-safe-html FILE ...
3111 **
3112 ** Read files named on the command-line. Send the text of each file
3113 ** through safe_html_append() and then write the result on
3114 ** standard output.
 
 
 
3115 */
3116 void test_safe_html_cmd(void){
3117 int i;
3118 Blob x;
 
 
 
3119 for(i=2; i<g.argc; i++){
3120 char *z;
3121 int n;
3122 blob_read_from_file(&x, g.argv[i], ExtFILE);
3123 blob_terminate(&x);
3124
--- src/wikiformat.c
+++ src/wikiformat.c
@@ -302,12 +302,12 @@
302 MARKUP_TR,
303 MARKUP_TT,
304 MARKUP_U,
305 MARKUP_UL,
306 MARKUP_VAR,
307 MARKUP_VERBATIM,
308 MARKUP_WBR
309 };
310
311 /*
312 ** The various markup is divided into the following types:
313 */
@@ -469,13 +469,13 @@
469 { "tt", MARKUP_TT, MUTYPE_FONT, AMSK_STYLE },
470 { "u", MARKUP_U, MUTYPE_FONT, AMSK_STYLE },
471 { "ul", MARKUP_UL, MUTYPE_LIST,
472 AMSK_TYPE|AMSK_COMPACT|AMSK_STYLE },
473 { "var", MARKUP_VAR, MUTYPE_FONT, AMSK_STYLE },
 
474 { "verbatim", MARKUP_VERBATIM, MUTYPE_SPECIAL,
475 AMSK_ID|AMSK_TYPE },
476 { "wbr", MARKUP_WBR, MUTYPE_SINGLE, 0 },
477 };
478
479 void show_allowed_wiki_markup( void ){
480 int i; /* loop over allowedAttr */
481 for( i=1 ; i<=count(aMarkup) - 1 ; i++ ){
@@ -984,10 +984,57 @@
984 while( fossil_isspace(z[i]) ){ i++; }
985 if( z[i]==0 || z[i]=='>' || (z[i]=='/' && z[i+1]=='>') ) break;
986 }
987 return seen;
988 }
989
990 /*
991 ** Append an HTML attribute value, rewriting root-relative URLs in src
992 ** and srcset the same way (%R prefix).
993 */
994 static void appendRewrittenAttrValue(Blob *pOut, int iACode, const char *zVal){
995 if( iACode==ATTR_SRC && zVal[0]=='/' ){
996 blob_appendf(pOut, "=\"%R%s\"", zVal);
997 return;
998 }
999 if( iACode==ATTR_SRCSET ){
1000 const char *z = zVal;
1001 int nCand = 0;
1002 blob_append_char(pOut, '=');
1003 blob_append_char(pOut, '"');
1004 while( z[0] ){
1005 const char *zComma = strchr(z, ',');
1006 int len = zComma ? (int)(zComma - z) : (int)strlen(z);
1007 const char *zCand = z;
1008 int urlStart = 0;
1009 int urlLen;
1010 if( len>0 ){
1011 while( urlStart<len && fossil_isspace(zCand[urlStart]) ) urlStart++;
1012 urlLen = urlStart;
1013 while( urlLen<len && !fossil_isspace(zCand[urlLen]) ) urlLen++;
1014 urlLen -= urlStart;
1015 if( nCand++ ) blob_append_char(pOut, ',');
1016 if( urlStart>0 ){
1017 blob_append(pOut, zCand, urlStart);
1018 }
1019 if( urlLen>0 && zCand[urlStart]=='/' ){
1020 blob_appendf(pOut, "%R%.*s", urlLen, zCand+urlStart);
1021 }else if( urlLen>0 ){
1022 blob_appendf(pOut, "%.*s", urlLen, zCand+urlStart);
1023 }
1024 if( urlStart+urlLen < len ){
1025 blob_appendf(pOut, "%.*s", len-urlStart-urlLen, zCand+urlStart+urlLen);
1026 }
1027 }
1028 if( zComma==0 ) break;
1029 z = zComma + 1;
1030 }
1031 blob_append_char(pOut, '"');
1032 return;
1033 }
1034 blob_appendf(pOut, "=\"%s\"", zVal);
1035 }
1036
1037 /*
1038 ** Render markup on the given blob.
1039 */
1040 static void renderMarkup(Blob *pOut, ParsedMarkup *p){
@@ -997,16 +1044,11 @@
1044 }else{
1045 blob_appendf(pOut, "<%s", aMarkup[p->iCode].zName);
1046 for(i=0; i<p->nAttr; i++){
1047 blob_appendf(pOut, " %s", aAttribute[p->aAttr[i].iACode].zName);
1048 if( p->aAttr[i].zValue ){
1049 appendRewrittenAttrValue(pOut, p->aAttr[i].iACode, p->aAttr[i].zValue);
 
 
 
 
 
1050 }
1051 }
1052 if (p->iType & MUTYPE_SINGLE){
1053 blob_append_string(pOut, " /");
1054 }
@@ -3105,19 +3147,25 @@
3147 }
3148
3149 /*
3150 ** COMMAND: test-safe-html
3151 **
3152 ** Usage: %fossil test-safe-html ?OPTIONS? FILE ...
3153 **
3154 ** Read files named on the command-line. Send the text of each file
3155 ** through safe_html_append() and then write the result on
3156 ** standard output.
3157 **
3158 ** Options:
3159 ** --top PATH Use PATH as g.zTop when rewriting root-relative URLs
3160 */
3161 void test_safe_html_cmd(void){
3162 int i;
3163 Blob x;
3164 const char *zTop = find_option("top",0,1);
3165 verify_all_options();
3166 if( zTop ) g.zTop = (char*)zTop;
3167 for(i=2; i<g.argc; i++){
3168 char *z;
3169 int n;
3170 blob_read_from_file(&x, g.argv[i], ExtFILE);
3171 blob_terminate(&x);
3172
--- www/changes.wiki
+++ www/changes.wiki
@@ -22,10 +22,12 @@
2222
capability.
2323
<li> Add the "[/help/attachment-size-limit|attachment-size-limit]" setting
2424
to limit the size of file attachments to wiki pages, tech notes,
2525
tickets, and forum posts.
2626
<li> Addded several HTML5 tags deemed harmless to the MD/wiki allowlists.
27
+ <li> Fix various pages on deployments where a custom skin emits
28
+ its own <code>BODY</code> tag without the expected CSS classes.
2729
</ol>
2830
2931
<h2 id='v2_28'>Changes for version 2.28 (2026-03-11)</h2><ol>
3032
<li> Improvements to [./antibot.wiki|anti-robot defenses]:<ol type="a">
3133
<li> The default configuration now allows robots to download any tarball
3234
--- www/changes.wiki
+++ www/changes.wiki
@@ -22,10 +22,12 @@
22 capability.
23 <li> Add the "[/help/attachment-size-limit|attachment-size-limit]" setting
24 to limit the size of file attachments to wiki pages, tech notes,
25 tickets, and forum posts.
26 <li> Addded several HTML5 tags deemed harmless to the MD/wiki allowlists.
 
 
27 </ol>
28
29 <h2 id='v2_28'>Changes for version 2.28 (2026-03-11)</h2><ol>
30 <li> Improvements to [./antibot.wiki|anti-robot defenses]:<ol type="a">
31 <li> The default configuration now allows robots to download any tarball
32
--- www/changes.wiki
+++ www/changes.wiki
@@ -22,10 +22,12 @@
22 capability.
23 <li> Add the "[/help/attachment-size-limit|attachment-size-limit]" setting
24 to limit the size of file attachments to wiki pages, tech notes,
25 tickets, and forum posts.
26 <li> Addded several HTML5 tags deemed harmless to the MD/wiki allowlists.
27 <li> Fix various pages on deployments where a custom skin emits
28 its own <code>BODY</code> tag without the expected CSS classes.
29 </ol>
30
31 <h2 id='v2_28'>Changes for version 2.28 (2026-03-11)</h2><ol>
32 <li> Improvements to [./antibot.wiki|anti-robot defenses]:<ol type="a">
33 <li> The default configuration now allows robots to download any tarball
34
--- www/fileformat.wiki
+++ www/fileformat.wiki
@@ -369,16 +369,24 @@
369369
extra newline.
370370
371371
The <b>C</b> card on a wiki page is optional. The argument is a comment
372372
that explains why the changes were made. The ability to have a <b>C</b>
373373
card on a wiki page artifact was added on 2019-12-02 at the suggestion
374
-of user George Krivov and is not currently used or generated by the
374
+of user George Krivov and is not currently used or generated by the
375375
implementation. Older versions of Fossil will reject a wiki-page
376376
artifact that includes a <b>C</b> card.
377377
378378
An example wiki artifact can be seen
379379
[/artifact?name=7b2f5fd0e0&txt=1 | here].
380
+
381
+Historical note: though <b>U</b> cards are technically required for
382
+wiki pages by this specification, Fossil has historically elided them
383
+if the submitter is "nobody". Very few repositories enable "nobody" to
384
+write to wiki pages, so relatively few wiki artifacts without U cards
385
+exist, but they do exist. Implementations are recommended to accept a
386
+missing U card as an alias for a U card with the value
387
+<tt>nobody</tt>.
380388
381389
<h3 id="tktchng">2.5 Ticket Changes</h3>
382390
383391
A ticket-change artifact represents a change to a trouble ticket.
384392
The following cards are allowed on a ticket change artifact:
385393
--- www/fileformat.wiki
+++ www/fileformat.wiki
@@ -369,16 +369,24 @@
369 extra newline.
370
371 The <b>C</b> card on a wiki page is optional. The argument is a comment
372 that explains why the changes were made. The ability to have a <b>C</b>
373 card on a wiki page artifact was added on 2019-12-02 at the suggestion
374 of user George Krivov and is not currently used or generated by the
375 implementation. Older versions of Fossil will reject a wiki-page
376 artifact that includes a <b>C</b> card.
377
378 An example wiki artifact can be seen
379 [/artifact?name=7b2f5fd0e0&txt=1 | here].
 
 
 
 
 
 
 
 
380
381 <h3 id="tktchng">2.5 Ticket Changes</h3>
382
383 A ticket-change artifact represents a change to a trouble ticket.
384 The following cards are allowed on a ticket change artifact:
385
--- www/fileformat.wiki
+++ www/fileformat.wiki
@@ -369,16 +369,24 @@
369 extra newline.
370
371 The <b>C</b> card on a wiki page is optional. The argument is a comment
372 that explains why the changes were made. The ability to have a <b>C</b>
373 card on a wiki page artifact was added on 2019-12-02 at the suggestion
374 of user George Krivov and is not currently used or generated by the
375 implementation. Older versions of Fossil will reject a wiki-page
376 artifact that includes a <b>C</b> card.
377
378 An example wiki artifact can be seen
379 [/artifact?name=7b2f5fd0e0&txt=1 | here].
380
381 Historical note: though <b>U</b> cards are technically required for
382 wiki pages by this specification, Fossil has historically elided them
383 if the submitter is "nobody". Very few repositories enable "nobody" to
384 write to wiki pages, so relatively few wiki artifacts without U cards
385 exist, but they do exist. Implementations are recommended to accept a
386 missing U card as an alias for a U card with the value
387 <tt>nobody</tt>.
388
389 <h3 id="tktchng">2.5 Ticket Changes</h3>
390
391 A ticket-change artifact represents a change to a trouble ticket.
392 The following cards are allowed on a ticket change artifact:
393
--- www/wikitheory.wiki
+++ www/wikitheory.wiki
@@ -24,11 +24,11 @@
2424
are also more widely known, and are thus provided as an alternative.
2525
2626
<h2>Stand-alone Wiki Pages</h2>
2727
2828
Each wiki page has its own revision history which is independent of
29
-the sequence of check-ins (check-ins). Wiki pages can branch and merge
29
+the sequence of check-ins. Wiki pages can branch and merge
3030
just like check-ins, though as of this writing (2008-07-29) there is
3131
no mechanism in the user interface to support branching and merging.
3232
The current implementation of the wiki shows the version of the wiki
3333
page that has the most recent time stamp.
3434
3535
--- www/wikitheory.wiki
+++ www/wikitheory.wiki
@@ -24,11 +24,11 @@
24 are also more widely known, and are thus provided as an alternative.
25
26 <h2>Stand-alone Wiki Pages</h2>
27
28 Each wiki page has its own revision history which is independent of
29 the sequence of check-ins (check-ins). Wiki pages can branch and merge
30 just like check-ins, though as of this writing (2008-07-29) there is
31 no mechanism in the user interface to support branching and merging.
32 The current implementation of the wiki shows the version of the wiki
33 page that has the most recent time stamp.
34
35
--- www/wikitheory.wiki
+++ www/wikitheory.wiki
@@ -24,11 +24,11 @@
24 are also more widely known, and are thus provided as an alternative.
25
26 <h2>Stand-alone Wiki Pages</h2>
27
28 Each wiki page has its own revision history which is independent of
29 the sequence of check-ins. Wiki pages can branch and merge
30 just like check-ins, though as of this writing (2008-07-29) there is
31 no mechanism in the user interface to support branching and merging.
32 The current implementation of the wiki shows the version of the wiki
33 page that has the most recent time stamp.
34
35

Keyboard Shortcuts

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