Fossil SCM

Update with all changes from trunk.

andybradford 2024-02-03 16:55 UTC clone-resume merge
Commit c454059a18bd2c3564b6ec7f42b317e5e392233fd002b19cec72f267c2b261b4
150 files changed +3 -2 +3 +1 -1 +156 -39 +5722 -2759 +73 -18 -3 +11 -2 +58 -32 +16 -11 +2 -1 +1 -1 +3 -3 +11 -11 +6 -6 +4 -3 +6 -5 +2 -2 +1 -1 +5 -5 +6 -6 +18 -4 +1 -1 +1 -1 +1 -1 +1 -1 +19 -17 +19 -17 +2 -1 +20 -10 +32 -1 +202 -25 +18 -16 +4 -4 +4 -4 +8 -8 +1 -1 +14 -12 +2 -1 +18 -5 +17 -4 +4 -1 +26 -6 +4 -4 +1 -1 +3 -3 +7 -7 +1 +1 -1 +3 -4 +4 -4 +49 -30 +9 -6 +3 -2 +2 -2 +16 -11 +4 -2 +2 -1 +23 -14 +2 -1 +11 -8 +12 -12 +1 -1 +7 -7 +3 -3 +31 -5 +2 -2 +3 -3 +1 -1 +15 -11 +16 -13 +2 -2 +4 -4 +3 -2 +9 -7 +122 -38 +7 -7 +3 -3 +1 -1 +2 -1 +16 -16 +1 -1 +61 -1 +2 -2 +2 -2 +2 -2 +1 -1 +16 -13 +73 -14 +1 -1 +13 -13 +4 -2 -1 +9 -3 +2 -2 +2 -1 +3 +5 -4 +2 -1 +6 -3 +20 -16 +2 -2 +2 -1 +18 -12 +1 -1 +3 -3 +2 -1 +13 -5 +37 -20 +1 -1 +7 -7 +7 -7 +7 -7 +17 -17 +3 -1 +1 -13 +1 -1 +44 +5 +15 -2 +30 -30 +1 -1 +39 -32 +9 -9 +3 -1 +12 -10 +5 -5 +3 -3 +645 +5 -5 +14 -10 +7 -3 +7 -6 +15 -13 +53 -3 +14 -17 +2 -2 +17 -10 +16 -14 +28 -10 +125 +1 -1 +4 -2 +1 -1 +2 -2 +4 -2 +7 +19 -19 +2 -2 +2 -2
~ Dockerfile ~ auto.def ~ extsrc/pikchr.c ~ extsrc/shell.c ~ extsrc/sqlite3.c ~ extsrc/sqlite3.h ~ skins/default/css.txt ~ src/ajax.c ~ src/alerts.c ~ src/allrepo.c ~ src/attach.c ~ src/backlink.c ~ src/backoffice.c ~ src/blob.c ~ src/branch.c ~ src/browse.c ~ src/builtin.c ~ src/cache.c ~ src/capabilities.c ~ src/cgi.c ~ src/chat.c ~ src/checkin.c ~ src/clone.c ~ src/clone.c ~ src/comformat.c ~ src/cookies.c ~ src/db.c ~ src/db.c ~ src/deltafunc.c ~ src/diff.c ~ src/diff.tcl ~ src/diffcmd.c ~ src/dispatch.c ~ src/doc.c ~ src/etag.c ~ src/export.c ~ src/file.c ~ src/fileedit.c ~ src/foci.c ~ src/fossil.page.chat.js ~ src/fossil.page.fileedit.js ~ src/fossil.page.whistory.js ~ src/fossil.page.wikiedit.js ~ src/graph.c ~ src/graph.js ~ src/http.c ~ src/http_ssl.c ~ src/http_transport.c ~ src/import.c ~ src/info.c ~ src/interwiki.c ~ src/json.c ~ src/json_artifact.c ~ src/json_branch.c ~ src/json_config.c ~ src/json_finfo.c ~ src/json_login.c ~ src/json_tag.c ~ src/json_timeline.c ~ src/json_user.c ~ src/json_wiki.c ~ src/login.c ~ src/lookslike.c ~ src/main.c ~ src/manifest.c ~ src/markdown.c ~ src/markdown_html.c ~ src/merge.c ~ src/merge3.c ~ src/name.c ~ src/patch.c ~ src/pikchrshow.c ~ src/rebuild.c ~ src/report.c ~ src/rss.c ~ src/search.c ~ src/security_audit.c ~ src/setup.c ~ src/setupuser.c ~ src/sha1.c ~ src/sha1hard.c ~ src/sha3.c ~ src/shun.c ~ src/sitemap.c ~ src/skins.c ~ src/smtp.c ~ src/sqlcmd.c ~ src/stash.c ~ src/stat.c ~ src/statrep.c ~ src/style.c ~ src/style.fileedit.css ~ src/style.wikiedit.css ~ src/sync.c ~ src/tag.c ~ src/tar.c ~ src/terminal.c ~ src/th.c ~ src/th_main.c ~ src/th_tcl.c ~ src/timeline.c ~ src/tkt.c ~ src/unicode.c ~ src/unversioned.c ~ src/update.c ~ src/url.c ~ src/user.c ~ src/vfile.c ~ src/wiki.c ~ src/wikiformat.c ~ src/winhttp.c ~ src/xfer.c ~ src/xfer.c ~ src/zip.c ~ test/amend.test ~ test/commit-warning.test ~ test/delta1.test ~ test/diff.test ~ test/fake-editor.tcl ~ test/json.test ~ test/merge1.test ~ test/merge2.test ~ test/merge3.test ~ test/merge4.test ~ test/merge5.test ~ test/merge_renames.test ~ test/merge_warn.test ~ test/revert.test ~ test/rewrite-test-output.tcl ~ test/set-manifest.test ~ test/settings-repo.test ~ test/settings.test ~ test/stash.test ~ test/symlinks.test ~ test/tester.tcl ~ test/th1-docs.test ~ test/th1-hooks.test ~ test/th1-tcl.test ~ test/th1.test ~ test/unversioned.test ~ test/update.test ~ tools/codecheck1.c ~ tools/makeheaders.c ~ tools/mkindex.c ~ tools/skintxt2config.c ~ tools/sqlcompattest.c ~ www/changes.wiki ~ www/customskin.md ~ www/tech_overview.wiki ~ www/unvers.wiki
+3 -2
--- Dockerfile
+++ Dockerfile
@@ -81,10 +81,11 @@
8181
## ---------------------------------------------------------------------
8282
8383
ENV PATH "/bin"
8484
EXPOSE 8080/tcp
8585
USER fossil
86
-ENTRYPOINT [ "fossil", "server", "museum/repo.fossil" ]
86
+ENTRYPOINT [ "fossil", "server" ]
8787
CMD [ \
8888
"--create", \
8989
"--jsmode", "bundled", \
90
- "--user", "admin" ]
90
+ "--user", "admin", \
91
+ "museum/repo.fossil" ]
9192
--- Dockerfile
+++ Dockerfile
@@ -81,10 +81,11 @@
81 ## ---------------------------------------------------------------------
82
83 ENV PATH "/bin"
84 EXPOSE 8080/tcp
85 USER fossil
86 ENTRYPOINT [ "fossil", "server", "museum/repo.fossil" ]
87 CMD [ \
88 "--create", \
89 "--jsmode", "bundled", \
90 "--user", "admin" ]
 
91
--- Dockerfile
+++ Dockerfile
@@ -81,10 +81,11 @@
81 ## ---------------------------------------------------------------------
82
83 ENV PATH "/bin"
84 EXPOSE 8080/tcp
85 USER fossil
86 ENTRYPOINT [ "fossil", "server" ]
87 CMD [ \
88 "--create", \
89 "--jsmode", "bundled", \
90 "--user", "admin", \
91 "museum/repo.fossil" ]
92
+3
--- auto.def
+++ auto.def
@@ -455,10 +455,12 @@
455455
}
456456
if {$found} {
457457
define FOSSIL_ENABLE_SSL
458458
define-append EXTRA_CFLAGS $cflags
459459
define-append EXTRA_LDFLAGS $ldflags
460
+ define-append CFLAGS $cflags
461
+ define-append LDFLAGS $ldflags
460462
if {[info exists ssllibs]} {
461463
define-append LIBS $ssllibs
462464
} else {
463465
define-append LIBS -lssl -lcrypto
464466
}
@@ -655,10 +657,11 @@
655657
msg-result "Found Tcl $version at $tclconfig(TCL_PREFIX)"
656658
if {!$tclprivatestubs} {
657659
define-append LIBS $libs
658660
}
659661
define-append EXTRA_CFLAGS $cflags
662
+ define-append CFLAGS $cflags
660663
if {[info exists zlibpath] && $zlibpath eq "tree"} {
661664
#
662665
# NOTE: When using zlib in the source tree, prevent Tcl from
663666
# pulling in the system one.
664667
#
665668
--- auto.def
+++ auto.def
@@ -455,10 +455,12 @@
455 }
456 if {$found} {
457 define FOSSIL_ENABLE_SSL
458 define-append EXTRA_CFLAGS $cflags
459 define-append EXTRA_LDFLAGS $ldflags
 
 
460 if {[info exists ssllibs]} {
461 define-append LIBS $ssllibs
462 } else {
463 define-append LIBS -lssl -lcrypto
464 }
@@ -655,10 +657,11 @@
655 msg-result "Found Tcl $version at $tclconfig(TCL_PREFIX)"
656 if {!$tclprivatestubs} {
657 define-append LIBS $libs
658 }
659 define-append EXTRA_CFLAGS $cflags
 
660 if {[info exists zlibpath] && $zlibpath eq "tree"} {
661 #
662 # NOTE: When using zlib in the source tree, prevent Tcl from
663 # pulling in the system one.
664 #
665
--- auto.def
+++ auto.def
@@ -455,10 +455,12 @@
455 }
456 if {$found} {
457 define FOSSIL_ENABLE_SSL
458 define-append EXTRA_CFLAGS $cflags
459 define-append EXTRA_LDFLAGS $ldflags
460 define-append CFLAGS $cflags
461 define-append LDFLAGS $ldflags
462 if {[info exists ssllibs]} {
463 define-append LIBS $ssllibs
464 } else {
465 define-append LIBS -lssl -lcrypto
466 }
@@ -655,10 +657,11 @@
657 msg-result "Found Tcl $version at $tclconfig(TCL_PREFIX)"
658 if {!$tclprivatestubs} {
659 define-append LIBS $libs
660 }
661 define-append EXTRA_CFLAGS $cflags
662 define-append CFLAGS $cflags
663 if {[info exists zlibpath] && $zlibpath eq "tree"} {
664 #
665 # NOTE: When using zlib in the source tree, prevent Tcl from
666 # pulling in the system one.
667 #
668
+1 -1
--- extsrc/pikchr.c
+++ extsrc/pikchr.c
@@ -5108,11 +5108,11 @@
51085108
int iEnd; /* End position of the error context */
51095109
int iLineno; /* Line number of the error */
51105110
int iFirstLineno; /* Line number of start of error context */
51115111
int i; /* Loop counter */
51125112
int iBump = 0; /* Bump the location of the error cursor */
5113
- char zLineno[20]; /* Buffer in which to generate line numbers */
5113
+ char zLineno[24]; /* Buffer in which to generate line numbers */
51145114
51155115
iErrPt = (int)(pErr->z - p->sIn.z);
51165116
if( iErrPt>=(int)p->sIn.n ){
51175117
iErrPt = p->sIn.n-1;
51185118
iBump = 1;
51195119
--- extsrc/pikchr.c
+++ extsrc/pikchr.c
@@ -5108,11 +5108,11 @@
5108 int iEnd; /* End position of the error context */
5109 int iLineno; /* Line number of the error */
5110 int iFirstLineno; /* Line number of start of error context */
5111 int i; /* Loop counter */
5112 int iBump = 0; /* Bump the location of the error cursor */
5113 char zLineno[20]; /* Buffer in which to generate line numbers */
5114
5115 iErrPt = (int)(pErr->z - p->sIn.z);
5116 if( iErrPt>=(int)p->sIn.n ){
5117 iErrPt = p->sIn.n-1;
5118 iBump = 1;
5119
--- extsrc/pikchr.c
+++ extsrc/pikchr.c
@@ -5108,11 +5108,11 @@
5108 int iEnd; /* End position of the error context */
5109 int iLineno; /* Line number of the error */
5110 int iFirstLineno; /* Line number of start of error context */
5111 int i; /* Loop counter */
5112 int iBump = 0; /* Bump the location of the error cursor */
5113 char zLineno[24]; /* Buffer in which to generate line numbers */
5114
5115 iErrPt = (int)(pErr->z - p->sIn.z);
5116 if( iErrPt>=(int)p->sIn.n ){
5117 iErrPt = p->sIn.n-1;
5118 iBump = 1;
5119
+156 -39
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -294,11 +294,11 @@
294294
** When this .h file and its companion .c are directly incorporated into
295295
** a source conglomeration (such as shell.c), the preprocessor symbol
296296
** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
297297
** translation for Windows is effected for the build.
298298
*/
299
-
299
+#define HAVE_CONSOLE_IO_H 1
300300
#ifndef SQLITE_INTERNAL_LINKAGE
301301
# define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
302302
# include <stdio.h>
303303
#else
304304
# define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
@@ -432,12 +432,12 @@
432432
** Returns the number of accepted char values.
433433
*/
434434
#ifdef CONSIO_SPUTB
435435
SQLITE_INTERNAL_LINKAGE int
436436
fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
437
-#endif
438437
/* Like fPutbUtf8 except stream is always the designated output. */
438
+#endif
439439
SQLITE_INTERNAL_LINKAGE int
440440
oPutbUtf8(const char *cBuf, int nAccept);
441441
/* Like fPutbUtf8 except stream is always the designated error. */
442442
#ifdef CONSIO_EPUTB
443443
SQLITE_INTERNAL_LINKAGE int
@@ -573,12 +573,14 @@
573573
# include <stdarg.h>
574574
# include <string.h>
575575
# include <stdlib.h>
576576
# include <limits.h>
577577
# include <assert.h>
578
-# include "console_io.h"
579578
/* # include "sqlite3.h" */
579
+#endif
580
+#ifndef HAVE_CONSOLE_IO_H
581
+# include "console_io.h"
580582
#endif
581583
582584
#ifndef SQLITE_CIO_NO_TRANSLATE
583585
# if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
584586
# ifndef SHELL_NO_SYSINC
@@ -1098,32 +1100,31 @@
10981100
return z;
10991101
}
11001102
#endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
11011103
11021104
#ifndef SQLITE_CIO_NO_TRANSLATE
1103
-
1104
-#ifdef CONSIO_SPUTB
1105
+# ifdef CONSIO_SPUTB
11051106
SQLITE_INTERNAL_LINKAGE int
11061107
fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
11071108
assert(pfO!=0);
1108
-# if CIO_WIN_WC_XLATE
1109
+# if CIO_WIN_WC_XLATE
11091110
PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
11101111
PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
11111112
if( pstReachesConsole(ppst) ){
11121113
int rv;
11131114
maybeSetupAsConsole(ppst, 1);
11141115
rv = conZstrEmit(ppst, cBuf, nAccept);
11151116
if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
11161117
return rv;
11171118
}else {
1118
-# endif
1119
+# endif
11191120
return (int)fwrite(cBuf, 1, nAccept, pfO);
1120
-# if CIO_WIN_WC_XLATE
1121
+# if CIO_WIN_WC_XLATE
11211122
}
1123
+# endif
1124
+}
11221125
# endif
1123
-}
1124
-#endif /* defined(CONSIO_SPUTB) */
11251126
11261127
SQLITE_INTERNAL_LINKAGE int
11271128
oPutbUtf8(const char *cBuf, int nAccept){
11281129
FILE *pfOut;
11291130
PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
@@ -1230,10 +1231,11 @@
12301231
#undef SHELL_INVALID_FILE_PTR
12311232
12321233
/************************* End ../ext/consio/console_io.c ********************/
12331234
12341235
#ifndef SQLITE_SHELL_FIDDLE
1236
+
12351237
/* From here onward, fgets() is redirected to the console_io library. */
12361238
# define fgets(b,n,f) fGetsUtf8(b,n,f)
12371239
/*
12381240
* Define macros for emitting output text in various ways:
12391241
* sputz(s, z) => emit 0-terminated string z to given stream s
@@ -1254,10 +1256,11 @@
12541256
# define oputz(z) oPutsUtf8(z)
12551257
# define oputf oPrintfUtf8
12561258
# define eputz(z) ePutsUtf8(z)
12571259
# define eputf ePrintfUtf8
12581260
# define oputb(buf,na) oPutbUtf8(buf,na)
1261
+
12591262
#else
12601263
/* For Fiddle, all console handling and emit redirection is omitted. */
12611264
# define sputz(fp,z) fputs(z,fp)
12621265
# define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
12631266
# define oputz(z) fputs(z,stdout)
@@ -1337,11 +1340,11 @@
13371340
static void endTimer(void){
13381341
if( enableTimer ){
13391342
sqlite3_int64 iEnd = timeOfDay();
13401343
struct rusage sEnd;
13411344
getrusage(RUSAGE_SELF, &sEnd);
1342
- oputf("Run Time: real %.3f user %f sys %f\n",
1345
+ sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
13431346
(iEnd - iBegin)*0.001,
13441347
timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
13451348
timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
13461349
}
13471350
}
@@ -1416,11 +1419,11 @@
14161419
static void endTimer(void){
14171420
if( enableTimer && getProcessTimesAddr){
14181421
FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
14191422
sqlite3_int64 ftWallEnd = timeOfDay();
14201423
getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1421
- oputf("Run Time: real %.3f user %f sys %f\n",
1424
+ sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
14221425
(ftWallEnd - ftWallBegin)*0.001,
14231426
timeDiff(&ftUserBegin, &ftUserEnd),
14241427
timeDiff(&ftKernelBegin, &ftKernelEnd));
14251428
}
14261429
}
@@ -1713,18 +1716,18 @@
17131716
** and is an ordinary file or a character stream source.
17141717
** Otherwise return 0.
17151718
*/
17161719
static FILE * openChrSource(const char *zFile){
17171720
#if defined(_WIN32) || defined(WIN32)
1718
- struct _stat x = {0};
1721
+ struct __stat64 x = {0};
17191722
# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
17201723
/* On Windows, open first, then check the stream nature. This order
17211724
** is necessary because _stat() and sibs, when checking a named pipe,
17221725
** effectively break the pipe as its supplier sees it. */
17231726
FILE *rv = fopen(zFile, "rb");
17241727
if( rv==0 ) return 0;
1725
- if( _fstat(_fileno(rv), &x) != 0
1728
+ if( _fstat64(_fileno(rv), &x) != 0
17261729
|| !STAT_CHR_SRC(x.st_mode)){
17271730
fclose(rv);
17281731
rv = 0;
17291732
}
17301733
return rv;
@@ -14825,10 +14828,11 @@
1482514828
/* Load the "byte of payload including overflow" field */
1482614829
if( bNextPage || iOff>pCsr->nPage ){
1482714830
bNextPage = 1;
1482814831
}else{
1482914832
iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
14833
+ if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
1483014834
}
1483114835
1483214836
/* If this is a leaf intkey cell, load the rowid */
1483314837
if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
1483414838
iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
@@ -18141,10 +18145,11 @@
1814118145
u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
1814218146
u8 nEqpLevel; /* Depth of the EQP output graph */
1814318147
u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
1814418148
u8 bSafeMode; /* True to prohibit unsafe operations */
1814518149
u8 bSafeModePersist; /* The long-term value of bSafeMode */
18150
+ u8 eRestoreState; /* See comments above doAutoDetectRestore() */
1814618151
ColModeOpts cmOpts; /* Option values affecting columnar mode output */
1814718152
unsigned statsOn; /* True to display memory stats before each finalize */
1814818153
unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
1814918154
int inputNesting; /* Track nesting level of .read and other redirects */
1815018155
int outCount; /* Revert to stdout when reaching zero */
@@ -22168,11 +22173,10 @@
2216822173
sqlite3_open_v2(zDbFilename, &p->db,
2216922174
SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
2217022175
break;
2217122176
}
2217222177
}
22173
- globalDb = p->db;
2217422178
if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
2217522179
eputf("Error: unable to open database \"%s\": %s\n",
2217622180
zDbFilename, sqlite3_errmsg(p->db));
2217722181
if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
2217822182
exit(1);
@@ -22185,10 +22189,11 @@
2218522189
}else{
2218622190
eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
2218722191
zDbFilename);
2218822192
}
2218922193
}
22194
+ globalDb = p->db;
2219022195
sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
2219122196
2219222197
/* Reflect the use or absence of --unsafe-testing invocation. */
2219322198
{
2219422199
int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
@@ -23580,11 +23585,10 @@
2358023585
eputz("Where sub-commands are:\n");
2358123586
eputz(" fkey-indexes\n");
2358223587
return SQLITE_ERROR;
2358323588
}
2358423589
23585
-#if !defined SQLITE_OMIT_VIRTUALTABLE
2358623590
static void shellPrepare(
2358723591
sqlite3 *db,
2358823592
int *pRc,
2358923593
const char *zSql,
2359023594
sqlite3_stmt **ppStmt
@@ -23599,16 +23603,12 @@
2359923603
}
2360023604
}
2360123605
2360223606
/*
2360323607
** Create a prepared statement using printf-style arguments for the SQL.
23604
-**
23605
-** This routine is could be marked "static". But it is not always used,
23606
-** depending on compile-time options. By omitting the "static", we avoid
23607
-** nuisance compiler warnings about "defined but not used".
2360823608
*/
23609
-void shellPreparePrintf(
23609
+static void shellPreparePrintf(
2361023610
sqlite3 *db,
2361123611
int *pRc,
2361223612
sqlite3_stmt **ppStmt,
2361323613
const char *zFmt,
2361423614
...
@@ -23627,17 +23627,14 @@
2362723627
sqlite3_free(z);
2362823628
}
2362923629
}
2363023630
}
2363123631
23632
-/* Finalize the prepared statement created using shellPreparePrintf().
23633
-**
23634
-** This routine is could be marked "static". But it is not always used,
23635
-** depending on compile-time options. By omitting the "static", we avoid
23636
-** nuisance compiler warnings about "defined but not used".
23632
+/*
23633
+** Finalize the prepared statement created using shellPreparePrintf().
2363723634
*/
23638
-void shellFinalize(
23635
+static void shellFinalize(
2363923636
int *pRc,
2364023637
sqlite3_stmt *pStmt
2364123638
){
2364223639
if( pStmt ){
2364323640
sqlite3 *db = sqlite3_db_handle(pStmt);
@@ -23649,10 +23646,11 @@
2364923646
*pRc = rc;
2365023647
}
2365123648
}
2365223649
}
2365323650
23651
+#if !defined SQLITE_OMIT_VIRTUALTABLE
2365423652
/* Reset the prepared statement created using shellPreparePrintf().
2365523653
**
2365623654
** This routine is could be marked "static". But it is not always used,
2365723655
** depending on compile-time options. By omitting the "static", we avoid
2365823656
** nuisance compiler warnings about "defined but not used".
@@ -24714,10 +24712,34 @@
2471424712
sqlite3_close(*pDb);
2471524713
*pDb = 0;
2471624714
return zColsSpec;
2471724715
}
2471824716
}
24717
+
24718
+/*
24719
+** Check if the sqlite_schema table contains one or more virtual tables. If
24720
+** parameter zLike is not NULL, then it is an SQL expression that the
24721
+** sqlite_schema row must also match. If one or more such rows are found,
24722
+** print the following warning to the output:
24723
+**
24724
+** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
24725
+*/
24726
+static int outputDumpWarning(ShellState *p, const char *zLike){
24727
+ int rc = SQLITE_OK;
24728
+ sqlite3_stmt *pStmt = 0;
24729
+ shellPreparePrintf(p->db, &rc, &pStmt,
24730
+ "SELECT 1 FROM sqlite_schema o WHERE "
24731
+ "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
24732
+ );
24733
+ if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24734
+ oputz("/* WARNING: "
24735
+ "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
24736
+ );
24737
+ }
24738
+ shellFinalize(&rc, pStmt);
24739
+ return rc;
24740
+}
2471924741
2472024742
/*
2472124743
** If an input line begins with "." then invoke this routine to
2472224744
** process that line.
2472324745
**
@@ -25177,10 +25199,11 @@
2517725199
}
2517825200
}
2517925201
2518025202
open_db(p, 0);
2518125203
25204
+ outputDumpWarning(p, zLike);
2518225205
if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
2518325206
/* When playing back a "dump", the content might appear in an order
2518425207
** which causes immediate foreign key constraints to be violated.
2518525208
** So disable foreign-key constraint enforcement to prevent problems. */
2518625209
oputz("PRAGMA foreign_keys=OFF;\n");
@@ -27605,10 +27628,11 @@
2760527628
{"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
2760627629
/*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
2760727630
{"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" },
2760827631
{"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
2760927632
{"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
27633
+ {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" },
2761027634
{"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
2761127635
{"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
2761227636
{"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
2761327637
#ifdef YYCOVERAGE
2761427638
{"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
@@ -27823,10 +27847,20 @@
2782327847
int opt = (unsigned int)integerValue(azArg[2]);
2782427848
rc2 = sqlite3_test_control(testctrl, p->db, opt);
2782527849
isOk = 3;
2782627850
}
2782727851
break;
27852
+ case SQLITE_TESTCTRL_JSON_SELFCHECK:
27853
+ if( nArg==2 ){
27854
+ rc2 = -1;
27855
+ isOk = 1;
27856
+ }else{
27857
+ rc2 = booleanValue(azArg[2]);
27858
+ isOk = 3;
27859
+ }
27860
+ sqlite3_test_control(testctrl, &rc2);
27861
+ break;
2782827862
}
2782927863
}
2783027864
if( isOk==0 && iCtrl>=0 ){
2783127865
oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
2783227866
rc = 1;
@@ -28228,10 +28262,92 @@
2822828262
zSql[nSql+1] = 0;
2822928263
rc = sqlite3_complete(zSql);
2823028264
zSql[nSql] = 0;
2823128265
return rc;
2823228266
}
28267
+
28268
+/*
28269
+** This function is called after processing each line of SQL in the
28270
+** runOneSqlLine() function. Its purpose is to detect scenarios where
28271
+** defensive mode should be automatically turned off. Specifically, when
28272
+**
28273
+** 1. The first line of input is "PRAGMA foreign_keys=OFF;",
28274
+** 2. The second line of input is "BEGIN TRANSACTION;",
28275
+** 3. The database is empty, and
28276
+** 4. The shell is not running in --safe mode.
28277
+**
28278
+** The implementation uses the ShellState.eRestoreState to maintain state:
28279
+**
28280
+** 0: Have not seen any SQL.
28281
+** 1: Have seen "PRAGMA foreign_keys=OFF;".
28282
+** 2-6: Currently running .dump transaction. If the "2" bit is set,
28283
+** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
28284
+** 7: Nothing left to do. This function becomes a no-op.
28285
+*/
28286
+static int doAutoDetectRestore(ShellState *p, const char *zSql){
28287
+ int rc = SQLITE_OK;
28288
+
28289
+ if( p->eRestoreState<7 ){
28290
+ switch( p->eRestoreState ){
28291
+ case 0: {
28292
+ const char *zExpect = "PRAGMA foreign_keys=OFF;";
28293
+ assert( strlen(zExpect)==24 );
28294
+ if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
28295
+ p->eRestoreState = 1;
28296
+ }else{
28297
+ p->eRestoreState = 7;
28298
+ }
28299
+ break;
28300
+ };
28301
+
28302
+ case 1: {
28303
+ int bIsDump = 0;
28304
+ const char *zExpect = "BEGIN TRANSACTION;";
28305
+ assert( strlen(zExpect)==18 );
28306
+ if( memcmp(zSql, zExpect, 19)==0 ){
28307
+ /* Now check if the database is empty. */
28308
+ const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
28309
+ sqlite3_stmt *pStmt = 0;
28310
+
28311
+ bIsDump = 1;
28312
+ shellPrepare(p->db, &rc, zQuery, &pStmt);
28313
+ if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
28314
+ bIsDump = 0;
28315
+ }
28316
+ shellFinalize(&rc, pStmt);
28317
+ }
28318
+ if( bIsDump && rc==SQLITE_OK ){
28319
+ int bDefense = 0;
28320
+ int bDqsDdl = 0;
28321
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
28322
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
28323
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
28324
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
28325
+ p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
28326
+ }else{
28327
+ p->eRestoreState = 7;
28328
+ }
28329
+ break;
28330
+ }
28331
+
28332
+ default: {
28333
+ if( sqlite3_get_autocommit(p->db) ){
28334
+ if( (p->eRestoreState & 2) ){
28335
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
28336
+ }
28337
+ if( (p->eRestoreState & 4) ){
28338
+ sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
28339
+ }
28340
+ p->eRestoreState = 7;
28341
+ }
28342
+ break;
28343
+ }
28344
+ }
28345
+ }
28346
+
28347
+ return rc;
28348
+}
2823328349
2823428350
/*
2823528351
** Run a single line of SQL. Return the number of errors.
2823628352
*/
2823728353
static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
@@ -28276,10 +28392,12 @@
2827628392
sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
2827728393
"changes: %lld total_changes: %lld",
2827828394
sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
2827928395
oputf("%s\n", zLineBuf);
2828028396
}
28397
+
28398
+ if( doAutoDetectRestore(p, zSql) ) return 1;
2828128399
return 0;
2828228400
}
2828328401
2828428402
static void echo_group_input(ShellState *p, const char *zDo){
2828528403
if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
@@ -28709,18 +28827,18 @@
2870928827
GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
2871028828
SetConsoleTextAttribute(out,
2871128829
FOREGROUND_RED|FOREGROUND_INTENSITY
2871228830
);
2871328831
#endif
28714
- oputz(zText);
28832
+ sputz(stdout, zText);
2871528833
#if !SQLITE_OS_WINRT
2871628834
SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
2871728835
#endif
2871828836
}
2871928837
#else
2872028838
static void printBold(const char *zText){
28721
- oputf("\033[1m%s\033[0m", zText);
28839
+ sputf(stdout, "\033[1m%s\033[0m", zText);
2872228840
}
2872328841
#endif
2872428842
2872528843
/*
2872628844
** Get the argument to an --option. Throw an error and die if no argument
@@ -28910,14 +29028,10 @@
2891029028
){
2891129029
(void)cmdline_option_value(argc, argv, ++i);
2891229030
}else if( cli_strcmp(z,"-init")==0 ){
2891329031
zInitFile = cmdline_option_value(argc, argv, ++i);
2891429032
}else if( cli_strcmp(z,"-interactive")==0 ){
28915
- /* Need to check for interactive override here to so that it can
28916
- ** affect console setup (for Windows only) and testing thereof.
28917
- */
28918
- stdin_is_interactive = 1;
2891929033
}else if( cli_strcmp(z,"-batch")==0 ){
2892029034
/* Need to check for batch mode here to so we can avoid printing
2892129035
** informational messages (like from process_sqliterc) before
2892229036
** we do the actual processing of arguments later in a second pass.
2892329037
*/
@@ -29183,15 +29297,18 @@
2918329297
*/
2918429298
ShellSetFlag(&data, SHFLG_Backslash);
2918529299
}else if( cli_strcmp(z,"-bail")==0 ){
2918629300
/* No-op. The bail_on_error flag should already be set. */
2918729301
}else if( cli_strcmp(z,"-version")==0 ){
29188
- oputf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
29189
- 8*(int)sizeof(char*));
29302
+ sputf(stdout, "%s %s (%d-bit)\n",
29303
+ sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
2919029304
return 0;
2919129305
}else if( cli_strcmp(z,"-interactive")==0 ){
29192
- /* already handled */
29306
+ /* Need to check for interactive override here to so that it can
29307
+ ** affect console setup (for Windows only) and testing thereof.
29308
+ */
29309
+ stdin_is_interactive = 1;
2919329310
}else if( cli_strcmp(z,"-batch")==0 ){
2919429311
/* already handled */
2919529312
}else if( cli_strcmp(z,"-utf8")==0 ){
2919629313
/* already handled */
2919729314
}else if( cli_strcmp(z,"-no-utf8")==0 ){
@@ -29316,17 +29433,17 @@
2931629433
#if CIO_WIN_WC_XLATE
2931729434
# define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
2931829435
#else
2931929436
# define SHELL_CIO_CHAR_SET ""
2932029437
#endif
29321
- oputf("SQLite version %s %.19s%s\n" /*extra-version-info*/
29438
+ sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
2932229439
"Enter \".help\" for usage hints.\n",
2932329440
sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
2932429441
if( warnInmemoryDb ){
29325
- oputz("Connected to a ");
29442
+ sputz(stdout, "Connected to a ");
2932629443
printBold("transient in-memory database");
29327
- oputz(".\nUse \".open FILENAME\" to reopen on a"
29444
+ sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
2932829445
" persistent database.\n");
2932929446
}
2933029447
zHistory = getenv("SQLITE_HISTORY");
2933129448
if( zHistory ){
2933229449
zHistory = strdup(zHistory);
2933329450
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -294,11 +294,11 @@
294 ** When this .h file and its companion .c are directly incorporated into
295 ** a source conglomeration (such as shell.c), the preprocessor symbol
296 ** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
297 ** translation for Windows is effected for the build.
298 */
299
300 #ifndef SQLITE_INTERNAL_LINKAGE
301 # define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
302 # include <stdio.h>
303 #else
304 # define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
@@ -432,12 +432,12 @@
432 ** Returns the number of accepted char values.
433 */
434 #ifdef CONSIO_SPUTB
435 SQLITE_INTERNAL_LINKAGE int
436 fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
437 #endif
438 /* Like fPutbUtf8 except stream is always the designated output. */
 
439 SQLITE_INTERNAL_LINKAGE int
440 oPutbUtf8(const char *cBuf, int nAccept);
441 /* Like fPutbUtf8 except stream is always the designated error. */
442 #ifdef CONSIO_EPUTB
443 SQLITE_INTERNAL_LINKAGE int
@@ -573,12 +573,14 @@
573 # include <stdarg.h>
574 # include <string.h>
575 # include <stdlib.h>
576 # include <limits.h>
577 # include <assert.h>
578 # include "console_io.h"
579 /* # include "sqlite3.h" */
 
 
 
580 #endif
581
582 #ifndef SQLITE_CIO_NO_TRANSLATE
583 # if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
584 # ifndef SHELL_NO_SYSINC
@@ -1098,32 +1100,31 @@
1098 return z;
1099 }
1100 #endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1101
1102 #ifndef SQLITE_CIO_NO_TRANSLATE
1103
1104 #ifdef CONSIO_SPUTB
1105 SQLITE_INTERNAL_LINKAGE int
1106 fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1107 assert(pfO!=0);
1108 # if CIO_WIN_WC_XLATE
1109 PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1110 PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1111 if( pstReachesConsole(ppst) ){
1112 int rv;
1113 maybeSetupAsConsole(ppst, 1);
1114 rv = conZstrEmit(ppst, cBuf, nAccept);
1115 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1116 return rv;
1117 }else {
1118 # endif
1119 return (int)fwrite(cBuf, 1, nAccept, pfO);
1120 # if CIO_WIN_WC_XLATE
1121 }
 
 
1122 # endif
1123 }
1124 #endif /* defined(CONSIO_SPUTB) */
1125
1126 SQLITE_INTERNAL_LINKAGE int
1127 oPutbUtf8(const char *cBuf, int nAccept){
1128 FILE *pfOut;
1129 PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
@@ -1230,10 +1231,11 @@
1230 #undef SHELL_INVALID_FILE_PTR
1231
1232 /************************* End ../ext/consio/console_io.c ********************/
1233
1234 #ifndef SQLITE_SHELL_FIDDLE
 
1235 /* From here onward, fgets() is redirected to the console_io library. */
1236 # define fgets(b,n,f) fGetsUtf8(b,n,f)
1237 /*
1238 * Define macros for emitting output text in various ways:
1239 * sputz(s, z) => emit 0-terminated string z to given stream s
@@ -1254,10 +1256,11 @@
1254 # define oputz(z) oPutsUtf8(z)
1255 # define oputf oPrintfUtf8
1256 # define eputz(z) ePutsUtf8(z)
1257 # define eputf ePrintfUtf8
1258 # define oputb(buf,na) oPutbUtf8(buf,na)
 
1259 #else
1260 /* For Fiddle, all console handling and emit redirection is omitted. */
1261 # define sputz(fp,z) fputs(z,fp)
1262 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1263 # define oputz(z) fputs(z,stdout)
@@ -1337,11 +1340,11 @@
1337 static void endTimer(void){
1338 if( enableTimer ){
1339 sqlite3_int64 iEnd = timeOfDay();
1340 struct rusage sEnd;
1341 getrusage(RUSAGE_SELF, &sEnd);
1342 oputf("Run Time: real %.3f user %f sys %f\n",
1343 (iEnd - iBegin)*0.001,
1344 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1345 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1346 }
1347 }
@@ -1416,11 +1419,11 @@
1416 static void endTimer(void){
1417 if( enableTimer && getProcessTimesAddr){
1418 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1419 sqlite3_int64 ftWallEnd = timeOfDay();
1420 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1421 oputf("Run Time: real %.3f user %f sys %f\n",
1422 (ftWallEnd - ftWallBegin)*0.001,
1423 timeDiff(&ftUserBegin, &ftUserEnd),
1424 timeDiff(&ftKernelBegin, &ftKernelEnd));
1425 }
1426 }
@@ -1713,18 +1716,18 @@
1713 ** and is an ordinary file or a character stream source.
1714 ** Otherwise return 0.
1715 */
1716 static FILE * openChrSource(const char *zFile){
1717 #if defined(_WIN32) || defined(WIN32)
1718 struct _stat x = {0};
1719 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1720 /* On Windows, open first, then check the stream nature. This order
1721 ** is necessary because _stat() and sibs, when checking a named pipe,
1722 ** effectively break the pipe as its supplier sees it. */
1723 FILE *rv = fopen(zFile, "rb");
1724 if( rv==0 ) return 0;
1725 if( _fstat(_fileno(rv), &x) != 0
1726 || !STAT_CHR_SRC(x.st_mode)){
1727 fclose(rv);
1728 rv = 0;
1729 }
1730 return rv;
@@ -14825,10 +14828,11 @@
14825 /* Load the "byte of payload including overflow" field */
14826 if( bNextPage || iOff>pCsr->nPage ){
14827 bNextPage = 1;
14828 }else{
14829 iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
 
14830 }
14831
14832 /* If this is a leaf intkey cell, load the rowid */
14833 if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
14834 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
@@ -18141,10 +18145,11 @@
18141 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
18142 u8 nEqpLevel; /* Depth of the EQP output graph */
18143 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
18144 u8 bSafeMode; /* True to prohibit unsafe operations */
18145 u8 bSafeModePersist; /* The long-term value of bSafeMode */
 
18146 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
18147 unsigned statsOn; /* True to display memory stats before each finalize */
18148 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
18149 int inputNesting; /* Track nesting level of .read and other redirects */
18150 int outCount; /* Revert to stdout when reaching zero */
@@ -22168,11 +22173,10 @@
22168 sqlite3_open_v2(zDbFilename, &p->db,
22169 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
22170 break;
22171 }
22172 }
22173 globalDb = p->db;
22174 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22175 eputf("Error: unable to open database \"%s\": %s\n",
22176 zDbFilename, sqlite3_errmsg(p->db));
22177 if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
22178 exit(1);
@@ -22185,10 +22189,11 @@
22185 }else{
22186 eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
22187 zDbFilename);
22188 }
22189 }
 
22190 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
22191
22192 /* Reflect the use or absence of --unsafe-testing invocation. */
22193 {
22194 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
@@ -23580,11 +23585,10 @@
23580 eputz("Where sub-commands are:\n");
23581 eputz(" fkey-indexes\n");
23582 return SQLITE_ERROR;
23583 }
23584
23585 #if !defined SQLITE_OMIT_VIRTUALTABLE
23586 static void shellPrepare(
23587 sqlite3 *db,
23588 int *pRc,
23589 const char *zSql,
23590 sqlite3_stmt **ppStmt
@@ -23599,16 +23603,12 @@
23599 }
23600 }
23601
23602 /*
23603 ** Create a prepared statement using printf-style arguments for the SQL.
23604 **
23605 ** This routine is could be marked "static". But it is not always used,
23606 ** depending on compile-time options. By omitting the "static", we avoid
23607 ** nuisance compiler warnings about "defined but not used".
23608 */
23609 void shellPreparePrintf(
23610 sqlite3 *db,
23611 int *pRc,
23612 sqlite3_stmt **ppStmt,
23613 const char *zFmt,
23614 ...
@@ -23627,17 +23627,14 @@
23627 sqlite3_free(z);
23628 }
23629 }
23630 }
23631
23632 /* Finalize the prepared statement created using shellPreparePrintf().
23633 **
23634 ** This routine is could be marked "static". But it is not always used,
23635 ** depending on compile-time options. By omitting the "static", we avoid
23636 ** nuisance compiler warnings about "defined but not used".
23637 */
23638 void shellFinalize(
23639 int *pRc,
23640 sqlite3_stmt *pStmt
23641 ){
23642 if( pStmt ){
23643 sqlite3 *db = sqlite3_db_handle(pStmt);
@@ -23649,10 +23646,11 @@
23649 *pRc = rc;
23650 }
23651 }
23652 }
23653
 
23654 /* Reset the prepared statement created using shellPreparePrintf().
23655 **
23656 ** This routine is could be marked "static". But it is not always used,
23657 ** depending on compile-time options. By omitting the "static", we avoid
23658 ** nuisance compiler warnings about "defined but not used".
@@ -24714,10 +24712,34 @@
24714 sqlite3_close(*pDb);
24715 *pDb = 0;
24716 return zColsSpec;
24717 }
24718 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24719
24720 /*
24721 ** If an input line begins with "." then invoke this routine to
24722 ** process that line.
24723 **
@@ -25177,10 +25199,11 @@
25177 }
25178 }
25179
25180 open_db(p, 0);
25181
 
25182 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25183 /* When playing back a "dump", the content might appear in an order
25184 ** which causes immediate foreign key constraints to be violated.
25185 ** So disable foreign-key constraint enforcement to prevent problems. */
25186 oputz("PRAGMA foreign_keys=OFF;\n");
@@ -27605,10 +27628,11 @@
27605 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
27606 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
27607 {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" },
27608 {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
27609 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
 
27610 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
27611 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
27612 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
27613 #ifdef YYCOVERAGE
27614 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
@@ -27823,10 +27847,20 @@
27823 int opt = (unsigned int)integerValue(azArg[2]);
27824 rc2 = sqlite3_test_control(testctrl, p->db, opt);
27825 isOk = 3;
27826 }
27827 break;
 
 
 
 
 
 
 
 
 
 
27828 }
27829 }
27830 if( isOk==0 && iCtrl>=0 ){
27831 oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
27832 rc = 1;
@@ -28228,10 +28262,92 @@
28228 zSql[nSql+1] = 0;
28229 rc = sqlite3_complete(zSql);
28230 zSql[nSql] = 0;
28231 return rc;
28232 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28233
28234 /*
28235 ** Run a single line of SQL. Return the number of errors.
28236 */
28237 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
@@ -28276,10 +28392,12 @@
28276 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
28277 "changes: %lld total_changes: %lld",
28278 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
28279 oputf("%s\n", zLineBuf);
28280 }
 
 
28281 return 0;
28282 }
28283
28284 static void echo_group_input(ShellState *p, const char *zDo){
28285 if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
@@ -28709,18 +28827,18 @@
28709 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
28710 SetConsoleTextAttribute(out,
28711 FOREGROUND_RED|FOREGROUND_INTENSITY
28712 );
28713 #endif
28714 oputz(zText);
28715 #if !SQLITE_OS_WINRT
28716 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
28717 #endif
28718 }
28719 #else
28720 static void printBold(const char *zText){
28721 oputf("\033[1m%s\033[0m", zText);
28722 }
28723 #endif
28724
28725 /*
28726 ** Get the argument to an --option. Throw an error and die if no argument
@@ -28910,14 +29028,10 @@
28910 ){
28911 (void)cmdline_option_value(argc, argv, ++i);
28912 }else if( cli_strcmp(z,"-init")==0 ){
28913 zInitFile = cmdline_option_value(argc, argv, ++i);
28914 }else if( cli_strcmp(z,"-interactive")==0 ){
28915 /* Need to check for interactive override here to so that it can
28916 ** affect console setup (for Windows only) and testing thereof.
28917 */
28918 stdin_is_interactive = 1;
28919 }else if( cli_strcmp(z,"-batch")==0 ){
28920 /* Need to check for batch mode here to so we can avoid printing
28921 ** informational messages (like from process_sqliterc) before
28922 ** we do the actual processing of arguments later in a second pass.
28923 */
@@ -29183,15 +29297,18 @@
29183 */
29184 ShellSetFlag(&data, SHFLG_Backslash);
29185 }else if( cli_strcmp(z,"-bail")==0 ){
29186 /* No-op. The bail_on_error flag should already be set. */
29187 }else if( cli_strcmp(z,"-version")==0 ){
29188 oputf("%s %s (%d-bit)\n", sqlite3_libversion(), sqlite3_sourceid(),
29189 8*(int)sizeof(char*));
29190 return 0;
29191 }else if( cli_strcmp(z,"-interactive")==0 ){
29192 /* already handled */
 
 
 
29193 }else if( cli_strcmp(z,"-batch")==0 ){
29194 /* already handled */
29195 }else if( cli_strcmp(z,"-utf8")==0 ){
29196 /* already handled */
29197 }else if( cli_strcmp(z,"-no-utf8")==0 ){
@@ -29316,17 +29433,17 @@
29316 #if CIO_WIN_WC_XLATE
29317 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
29318 #else
29319 # define SHELL_CIO_CHAR_SET ""
29320 #endif
29321 oputf("SQLite version %s %.19s%s\n" /*extra-version-info*/
29322 "Enter \".help\" for usage hints.\n",
29323 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
29324 if( warnInmemoryDb ){
29325 oputz("Connected to a ");
29326 printBold("transient in-memory database");
29327 oputz(".\nUse \".open FILENAME\" to reopen on a"
29328 " persistent database.\n");
29329 }
29330 zHistory = getenv("SQLITE_HISTORY");
29331 if( zHistory ){
29332 zHistory = strdup(zHistory);
29333
--- extsrc/shell.c
+++ extsrc/shell.c
@@ -294,11 +294,11 @@
294 ** When this .h file and its companion .c are directly incorporated into
295 ** a source conglomeration (such as shell.c), the preprocessor symbol
296 ** CIO_WIN_WC_XLATE is defined as 0 or 1, reflecting whether console I/O
297 ** translation for Windows is effected for the build.
298 */
299 #define HAVE_CONSOLE_IO_H 1
300 #ifndef SQLITE_INTERNAL_LINKAGE
301 # define SQLITE_INTERNAL_LINKAGE extern /* external to translation unit */
302 # include <stdio.h>
303 #else
304 # define SHELL_NO_SYSINC /* Better yet, modify mkshellc.tcl for this. */
@@ -432,12 +432,12 @@
432 ** Returns the number of accepted char values.
433 */
434 #ifdef CONSIO_SPUTB
435 SQLITE_INTERNAL_LINKAGE int
436 fPutbUtf8(FILE *pfOut, const char *cBuf, int nAccept);
 
437 /* Like fPutbUtf8 except stream is always the designated output. */
438 #endif
439 SQLITE_INTERNAL_LINKAGE int
440 oPutbUtf8(const char *cBuf, int nAccept);
441 /* Like fPutbUtf8 except stream is always the designated error. */
442 #ifdef CONSIO_EPUTB
443 SQLITE_INTERNAL_LINKAGE int
@@ -573,12 +573,14 @@
573 # include <stdarg.h>
574 # include <string.h>
575 # include <stdlib.h>
576 # include <limits.h>
577 # include <assert.h>
 
578 /* # include "sqlite3.h" */
579 #endif
580 #ifndef HAVE_CONSOLE_IO_H
581 # include "console_io.h"
582 #endif
583
584 #ifndef SQLITE_CIO_NO_TRANSLATE
585 # if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
586 # ifndef SHELL_NO_SYSINC
@@ -1098,32 +1100,31 @@
1100 return z;
1101 }
1102 #endif /*!(defined(SQLITE_CIO_NO_UTF8SCAN)&&defined(SQLITE_CIO_NO_TRANSLATE))*/
1103
1104 #ifndef SQLITE_CIO_NO_TRANSLATE
1105 # ifdef CONSIO_SPUTB
 
1106 SQLITE_INTERNAL_LINKAGE int
1107 fPutbUtf8(FILE *pfO, const char *cBuf, int nAccept){
1108 assert(pfO!=0);
1109 # if CIO_WIN_WC_XLATE
1110 PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
1111 PerStreamTags *ppst = getEmitStreamInfo(0, &pst, &pfO);
1112 if( pstReachesConsole(ppst) ){
1113 int rv;
1114 maybeSetupAsConsole(ppst, 1);
1115 rv = conZstrEmit(ppst, cBuf, nAccept);
1116 if( 0 == isKnownWritable(ppst->pf) ) restoreConsoleArb(ppst);
1117 return rv;
1118 }else {
1119 # endif
1120 return (int)fwrite(cBuf, 1, nAccept, pfO);
1121 # if CIO_WIN_WC_XLATE
1122 }
1123 # endif
1124 }
1125 # endif
 
 
1126
1127 SQLITE_INTERNAL_LINKAGE int
1128 oPutbUtf8(const char *cBuf, int nAccept){
1129 FILE *pfOut;
1130 PerStreamTags pst = PST_INITIALIZER; /* for unknown streams */
@@ -1230,10 +1231,11 @@
1231 #undef SHELL_INVALID_FILE_PTR
1232
1233 /************************* End ../ext/consio/console_io.c ********************/
1234
1235 #ifndef SQLITE_SHELL_FIDDLE
1236
1237 /* From here onward, fgets() is redirected to the console_io library. */
1238 # define fgets(b,n,f) fGetsUtf8(b,n,f)
1239 /*
1240 * Define macros for emitting output text in various ways:
1241 * sputz(s, z) => emit 0-terminated string z to given stream s
@@ -1254,10 +1256,11 @@
1256 # define oputz(z) oPutsUtf8(z)
1257 # define oputf oPrintfUtf8
1258 # define eputz(z) ePutsUtf8(z)
1259 # define eputf ePrintfUtf8
1260 # define oputb(buf,na) oPutbUtf8(buf,na)
1261
1262 #else
1263 /* For Fiddle, all console handling and emit redirection is omitted. */
1264 # define sputz(fp,z) fputs(z,fp)
1265 # define sputf(fp,fmt, ...) fprintf(fp,fmt,__VA_ARGS__)
1266 # define oputz(z) fputs(z,stdout)
@@ -1337,11 +1340,11 @@
1340 static void endTimer(void){
1341 if( enableTimer ){
1342 sqlite3_int64 iEnd = timeOfDay();
1343 struct rusage sEnd;
1344 getrusage(RUSAGE_SELF, &sEnd);
1345 sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1346 (iEnd - iBegin)*0.001,
1347 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
1348 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
1349 }
1350 }
@@ -1416,11 +1419,11 @@
1419 static void endTimer(void){
1420 if( enableTimer && getProcessTimesAddr){
1421 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
1422 sqlite3_int64 ftWallEnd = timeOfDay();
1423 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
1424 sputf(stdout, "Run Time: real %.3f user %f sys %f\n",
1425 (ftWallEnd - ftWallBegin)*0.001,
1426 timeDiff(&ftUserBegin, &ftUserEnd),
1427 timeDiff(&ftKernelBegin, &ftKernelEnd));
1428 }
1429 }
@@ -1713,18 +1716,18 @@
1716 ** and is an ordinary file or a character stream source.
1717 ** Otherwise return 0.
1718 */
1719 static FILE * openChrSource(const char *zFile){
1720 #if defined(_WIN32) || defined(WIN32)
1721 struct __stat64 x = {0};
1722 # define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0)
1723 /* On Windows, open first, then check the stream nature. This order
1724 ** is necessary because _stat() and sibs, when checking a named pipe,
1725 ** effectively break the pipe as its supplier sees it. */
1726 FILE *rv = fopen(zFile, "rb");
1727 if( rv==0 ) return 0;
1728 if( _fstat64(_fileno(rv), &x) != 0
1729 || !STAT_CHR_SRC(x.st_mode)){
1730 fclose(rv);
1731 rv = 0;
1732 }
1733 return rv;
@@ -14825,10 +14828,11 @@
14828 /* Load the "byte of payload including overflow" field */
14829 if( bNextPage || iOff>pCsr->nPage ){
14830 bNextPage = 1;
14831 }else{
14832 iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload);
14833 if( nPayload>0x7fffff00 ) nPayload &= 0x3fff;
14834 }
14835
14836 /* If this is a leaf intkey cell, load the rowid */
14837 if( bHasRowid && !bNextPage && iOff<pCsr->nPage ){
14838 iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey);
@@ -18141,10 +18145,11 @@
18145 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
18146 u8 nEqpLevel; /* Depth of the EQP output graph */
18147 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
18148 u8 bSafeMode; /* True to prohibit unsafe operations */
18149 u8 bSafeModePersist; /* The long-term value of bSafeMode */
18150 u8 eRestoreState; /* See comments above doAutoDetectRestore() */
18151 ColModeOpts cmOpts; /* Option values affecting columnar mode output */
18152 unsigned statsOn; /* True to display memory stats before each finalize */
18153 unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */
18154 int inputNesting; /* Track nesting level of .read and other redirects */
18155 int outCount; /* Revert to stdout when reaching zero */
@@ -22168,11 +22173,10 @@
22173 sqlite3_open_v2(zDbFilename, &p->db,
22174 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
22175 break;
22176 }
22177 }
 
22178 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
22179 eputf("Error: unable to open database \"%s\": %s\n",
22180 zDbFilename, sqlite3_errmsg(p->db));
22181 if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
22182 exit(1);
@@ -22185,10 +22189,11 @@
22189 }else{
22190 eputf("Notice: using substitute in-memory database instead of \"%s\"\n",
22191 zDbFilename);
22192 }
22193 }
22194 globalDb = p->db;
22195 sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
22196
22197 /* Reflect the use or absence of --unsafe-testing invocation. */
22198 {
22199 int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
@@ -23580,11 +23585,10 @@
23585 eputz("Where sub-commands are:\n");
23586 eputz(" fkey-indexes\n");
23587 return SQLITE_ERROR;
23588 }
23589
 
23590 static void shellPrepare(
23591 sqlite3 *db,
23592 int *pRc,
23593 const char *zSql,
23594 sqlite3_stmt **ppStmt
@@ -23599,16 +23603,12 @@
23603 }
23604 }
23605
23606 /*
23607 ** Create a prepared statement using printf-style arguments for the SQL.
 
 
 
 
23608 */
23609 static void shellPreparePrintf(
23610 sqlite3 *db,
23611 int *pRc,
23612 sqlite3_stmt **ppStmt,
23613 const char *zFmt,
23614 ...
@@ -23627,17 +23627,14 @@
23627 sqlite3_free(z);
23628 }
23629 }
23630 }
23631
23632 /*
23633 ** Finalize the prepared statement created using shellPreparePrintf().
 
 
 
23634 */
23635 static void shellFinalize(
23636 int *pRc,
23637 sqlite3_stmt *pStmt
23638 ){
23639 if( pStmt ){
23640 sqlite3 *db = sqlite3_db_handle(pStmt);
@@ -23649,10 +23646,11 @@
23646 *pRc = rc;
23647 }
23648 }
23649 }
23650
23651 #if !defined SQLITE_OMIT_VIRTUALTABLE
23652 /* Reset the prepared statement created using shellPreparePrintf().
23653 **
23654 ** This routine is could be marked "static". But it is not always used,
23655 ** depending on compile-time options. By omitting the "static", we avoid
23656 ** nuisance compiler warnings about "defined but not used".
@@ -24714,10 +24712,34 @@
24712 sqlite3_close(*pDb);
24713 *pDb = 0;
24714 return zColsSpec;
24715 }
24716 }
24717
24718 /*
24719 ** Check if the sqlite_schema table contains one or more virtual tables. If
24720 ** parameter zLike is not NULL, then it is an SQL expression that the
24721 ** sqlite_schema row must also match. If one or more such rows are found,
24722 ** print the following warning to the output:
24723 **
24724 ** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled
24725 */
24726 static int outputDumpWarning(ShellState *p, const char *zLike){
24727 int rc = SQLITE_OK;
24728 sqlite3_stmt *pStmt = 0;
24729 shellPreparePrintf(p->db, &rc, &pStmt,
24730 "SELECT 1 FROM sqlite_schema o WHERE "
24731 "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true"
24732 );
24733 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
24734 oputz("/* WARNING: "
24735 "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n"
24736 );
24737 }
24738 shellFinalize(&rc, pStmt);
24739 return rc;
24740 }
24741
24742 /*
24743 ** If an input line begins with "." then invoke this routine to
24744 ** process that line.
24745 **
@@ -25177,10 +25199,11 @@
25199 }
25200 }
25201
25202 open_db(p, 0);
25203
25204 outputDumpWarning(p, zLike);
25205 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
25206 /* When playing back a "dump", the content might appear in an order
25207 ** which causes immediate foreign key constraints to be violated.
25208 ** So disable foreign-key constraint enforcement to prevent problems. */
25209 oputz("PRAGMA foreign_keys=OFF;\n");
@@ -27605,10 +27628,11 @@
27628 {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" },
27629 /*{"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/
27630 {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" },
27631 {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"},
27632 {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" },
27633 {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" },
27634 {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" },
27635 {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" },
27636 {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" },
27637 #ifdef YYCOVERAGE
27638 {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" },
@@ -27823,10 +27847,20 @@
27847 int opt = (unsigned int)integerValue(azArg[2]);
27848 rc2 = sqlite3_test_control(testctrl, p->db, opt);
27849 isOk = 3;
27850 }
27851 break;
27852 case SQLITE_TESTCTRL_JSON_SELFCHECK:
27853 if( nArg==2 ){
27854 rc2 = -1;
27855 isOk = 1;
27856 }else{
27857 rc2 = booleanValue(azArg[2]);
27858 isOk = 3;
27859 }
27860 sqlite3_test_control(testctrl, &rc2);
27861 break;
27862 }
27863 }
27864 if( isOk==0 && iCtrl>=0 ){
27865 oputf("Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
27866 rc = 1;
@@ -28228,10 +28262,92 @@
28262 zSql[nSql+1] = 0;
28263 rc = sqlite3_complete(zSql);
28264 zSql[nSql] = 0;
28265 return rc;
28266 }
28267
28268 /*
28269 ** This function is called after processing each line of SQL in the
28270 ** runOneSqlLine() function. Its purpose is to detect scenarios where
28271 ** defensive mode should be automatically turned off. Specifically, when
28272 **
28273 ** 1. The first line of input is "PRAGMA foreign_keys=OFF;",
28274 ** 2. The second line of input is "BEGIN TRANSACTION;",
28275 ** 3. The database is empty, and
28276 ** 4. The shell is not running in --safe mode.
28277 **
28278 ** The implementation uses the ShellState.eRestoreState to maintain state:
28279 **
28280 ** 0: Have not seen any SQL.
28281 ** 1: Have seen "PRAGMA foreign_keys=OFF;".
28282 ** 2-6: Currently running .dump transaction. If the "2" bit is set,
28283 ** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL.
28284 ** 7: Nothing left to do. This function becomes a no-op.
28285 */
28286 static int doAutoDetectRestore(ShellState *p, const char *zSql){
28287 int rc = SQLITE_OK;
28288
28289 if( p->eRestoreState<7 ){
28290 switch( p->eRestoreState ){
28291 case 0: {
28292 const char *zExpect = "PRAGMA foreign_keys=OFF;";
28293 assert( strlen(zExpect)==24 );
28294 if( p->bSafeMode==0 && memcmp(zSql, zExpect, 25)==0 ){
28295 p->eRestoreState = 1;
28296 }else{
28297 p->eRestoreState = 7;
28298 }
28299 break;
28300 };
28301
28302 case 1: {
28303 int bIsDump = 0;
28304 const char *zExpect = "BEGIN TRANSACTION;";
28305 assert( strlen(zExpect)==18 );
28306 if( memcmp(zSql, zExpect, 19)==0 ){
28307 /* Now check if the database is empty. */
28308 const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1";
28309 sqlite3_stmt *pStmt = 0;
28310
28311 bIsDump = 1;
28312 shellPrepare(p->db, &rc, zQuery, &pStmt);
28313 if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
28314 bIsDump = 0;
28315 }
28316 shellFinalize(&rc, pStmt);
28317 }
28318 if( bIsDump && rc==SQLITE_OK ){
28319 int bDefense = 0;
28320 int bDqsDdl = 0;
28321 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense);
28322 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl);
28323 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
28324 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0);
28325 p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0);
28326 }else{
28327 p->eRestoreState = 7;
28328 }
28329 break;
28330 }
28331
28332 default: {
28333 if( sqlite3_get_autocommit(p->db) ){
28334 if( (p->eRestoreState & 2) ){
28335 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0);
28336 }
28337 if( (p->eRestoreState & 4) ){
28338 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0);
28339 }
28340 p->eRestoreState = 7;
28341 }
28342 break;
28343 }
28344 }
28345 }
28346
28347 return rc;
28348 }
28349
28350 /*
28351 ** Run a single line of SQL. Return the number of errors.
28352 */
28353 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
@@ -28276,10 +28392,12 @@
28392 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf,
28393 "changes: %lld total_changes: %lld",
28394 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db));
28395 oputf("%s\n", zLineBuf);
28396 }
28397
28398 if( doAutoDetectRestore(p, zSql) ) return 1;
28399 return 0;
28400 }
28401
28402 static void echo_group_input(ShellState *p, const char *zDo){
28403 if( ShellHasFlag(p, SHFLG_Echo) ) oputf("%s\n", zDo);
@@ -28709,18 +28827,18 @@
28827 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
28828 SetConsoleTextAttribute(out,
28829 FOREGROUND_RED|FOREGROUND_INTENSITY
28830 );
28831 #endif
28832 sputz(stdout, zText);
28833 #if !SQLITE_OS_WINRT
28834 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
28835 #endif
28836 }
28837 #else
28838 static void printBold(const char *zText){
28839 sputf(stdout, "\033[1m%s\033[0m", zText);
28840 }
28841 #endif
28842
28843 /*
28844 ** Get the argument to an --option. Throw an error and die if no argument
@@ -28910,14 +29028,10 @@
29028 ){
29029 (void)cmdline_option_value(argc, argv, ++i);
29030 }else if( cli_strcmp(z,"-init")==0 ){
29031 zInitFile = cmdline_option_value(argc, argv, ++i);
29032 }else if( cli_strcmp(z,"-interactive")==0 ){
 
 
 
 
29033 }else if( cli_strcmp(z,"-batch")==0 ){
29034 /* Need to check for batch mode here to so we can avoid printing
29035 ** informational messages (like from process_sqliterc) before
29036 ** we do the actual processing of arguments later in a second pass.
29037 */
@@ -29183,15 +29297,18 @@
29297 */
29298 ShellSetFlag(&data, SHFLG_Backslash);
29299 }else if( cli_strcmp(z,"-bail")==0 ){
29300 /* No-op. The bail_on_error flag should already be set. */
29301 }else if( cli_strcmp(z,"-version")==0 ){
29302 sputf(stdout, "%s %s (%d-bit)\n",
29303 sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*));
29304 return 0;
29305 }else if( cli_strcmp(z,"-interactive")==0 ){
29306 /* Need to check for interactive override here to so that it can
29307 ** affect console setup (for Windows only) and testing thereof.
29308 */
29309 stdin_is_interactive = 1;
29310 }else if( cli_strcmp(z,"-batch")==0 ){
29311 /* already handled */
29312 }else if( cli_strcmp(z,"-utf8")==0 ){
29313 /* already handled */
29314 }else if( cli_strcmp(z,"-no-utf8")==0 ){
@@ -29316,17 +29433,17 @@
29433 #if CIO_WIN_WC_XLATE
29434 # define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "")
29435 #else
29436 # define SHELL_CIO_CHAR_SET ""
29437 #endif
29438 sputf(stdout, "SQLite version %s %.19s%s\n" /*extra-version-info*/
29439 "Enter \".help\" for usage hints.\n",
29440 sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET);
29441 if( warnInmemoryDb ){
29442 sputz(stdout, "Connected to a ");
29443 printBold("transient in-memory database");
29444 sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a"
29445 " persistent database.\n");
29446 }
29447 zHistory = getenv("SQLITE_HISTORY");
29448 if( zHistory ){
29449 zHistory = strdup(zHistory);
29450
+5722 -2759
--- extsrc/sqlite3.c
+++ extsrc/sqlite3.c
@@ -1,8 +1,8 @@
11
/******************************************************************************
22
** This file is an amalgamation of many separate C source files from SQLite
3
-** version 3.44.2. By combining all the individual C code files into this
3
+** version 3.45.1. By combining all the individual C code files into this
44
** single large file, the entire code can be compiled as a single translation
55
** unit. This allows many compilers to do optimizations that would not be
66
** possible if the files were compiled separately. Performance improvements
77
** of 5% or more are commonly seen when SQLite is compiled as a single
88
** translation unit.
@@ -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
-** ebead0e7230cd33bcec9f95d2183069565b9.
21
+** e876e51a0ed5c5b3126f52e532044363a014.
2222
*/
2323
#define SQLITE_CORE 1
2424
#define SQLITE_AMALGAMATION 1
2525
#ifndef SQLITE_PRIVATE
2626
# define SQLITE_PRIVATE static
@@ -457,13 +457,13 @@
457457
**
458458
** See also: [sqlite3_libversion()],
459459
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
460460
** [sqlite_version()] and [sqlite_source_id()].
461461
*/
462
-#define SQLITE_VERSION "3.44.2"
463
-#define SQLITE_VERSION_NUMBER 3044002
464
-#define SQLITE_SOURCE_ID "2023-11-24 11:41:44 ebead0e7230cd33bcec9f95d2183069565b9e709bf745c9b5db65cc0cbf92c0f"
462
+#define SQLITE_VERSION "3.45.1"
463
+#define SQLITE_VERSION_NUMBER 3045001
464
+#define SQLITE_SOURCE_ID "2024-01-30 16:01:20 e876e51a0ed5c5b3126f52e532044363a014bc594cfefa87ffb5b82257cc467a"
465465
466466
/*
467467
** CAPI3REF: Run-Time Library Version Numbers
468468
** KEYWORDS: sqlite3_version sqlite3_sourceid
469469
**
@@ -4265,19 +4265,21 @@
42654265
** <li> sqlite3_errmsg16()
42664266
** <li> sqlite3_error_offset()
42674267
** </ul>
42684268
**
42694269
** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4270
-** text that describes the error, as either UTF-8 or UTF-16 respectively.
4270
+** text that describes the error, as either UTF-8 or UTF-16 respectively,
4271
+** or NULL if no error message is available.
42714272
** (See how SQLite handles [invalid UTF] for exceptions to this rule.)
42724273
** ^(Memory to hold the error message string is managed internally.
42734274
** The application does not need to worry about freeing the result.
42744275
** However, the error string might be overwritten or deallocated by
42754276
** subsequent calls to other SQLite interface functions.)^
42764277
**
4277
-** ^The sqlite3_errstr() interface returns the English-language text
4278
-** that describes the [result code], as UTF-8.
4278
+** ^The sqlite3_errstr(E) interface returns the English-language text
4279
+** that describes the [result code] E, as UTF-8, or NULL if E is not an
4280
+** result code for which a text error message is available.
42794281
** ^(Memory to hold the error message string is managed internally
42804282
** and must not be freed by the application)^.
42814283
**
42824284
** ^If the most recent error references a specific token in the input
42834285
** SQL, the sqlite3_error_offset() interface returns the byte offset
@@ -8348,13 +8350,15 @@
83488350
** can enter.)^ If the same thread tries to enter any mutex other
83498351
** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
83508352
**
83518353
** ^(Some systems (for example, Windows 95) do not support the operation
83528354
** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
8353
-** will always return SQLITE_BUSY. The SQLite core only ever uses
8354
-** sqlite3_mutex_try() as an optimization so this is acceptable
8355
-** behavior.)^
8355
+** will always return SQLITE_BUSY. In most cases the SQLite core only uses
8356
+** sqlite3_mutex_try() as an optimization, so this is acceptable
8357
+** behavior. The exceptions are unix builds that set the
8358
+** SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working
8359
+** sqlite3_mutex_try() is required.)^
83568360
**
83578361
** ^The sqlite3_mutex_leave() routine exits a mutex that was
83588362
** previously entered by the same thread. The behavior
83598363
** is undefined if the mutex is not currently entered by the
83608364
** calling thread or is not currently allocated.
@@ -8609,10 +8613,11 @@
86098613
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
86108614
#define SQLITE_TESTCTRL_PENDING_BYTE 11
86118615
#define SQLITE_TESTCTRL_ASSERT 12
86128616
#define SQLITE_TESTCTRL_ALWAYS 13
86138617
#define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */
8618
+#define SQLITE_TESTCTRL_JSON_SELFCHECK 14
86148619
#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
86158620
#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
86168621
#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
86178622
#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
86188623
#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
@@ -13122,23 +13127,28 @@
1312213127
**
1312313128
** This function may be quite inefficient if used with an FTS5 table
1312413129
** created with the "columnsize=0" option.
1312513130
**
1312613131
** xColumnText:
13127
-** This function attempts to retrieve the text of column iCol of the
13128
-** current document. If successful, (*pz) is set to point to a buffer
13132
+** If parameter iCol is less than zero, or greater than or equal to the
13133
+** number of columns in the table, SQLITE_RANGE is returned.
13134
+**
13135
+** Otherwise, this function attempts to retrieve the text of column iCol of
13136
+** the current document. If successful, (*pz) is set to point to a buffer
1312913137
** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
1313013138
** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
1313113139
** if an error occurs, an SQLite error code is returned and the final values
1313213140
** of (*pz) and (*pn) are undefined.
1313313141
**
1313413142
** xPhraseCount:
1313513143
** Returns the number of phrases in the current query expression.
1313613144
**
1313713145
** xPhraseSize:
13138
-** Returns the number of tokens in phrase iPhrase of the query. Phrases
13139
-** are numbered starting from zero.
13146
+** If parameter iCol is less than zero, or greater than or equal to the
13147
+** number of phrases in the current query, as returned by xPhraseCount,
13148
+** 0 is returned. Otherwise, this function returns the number of tokens in
13149
+** phrase iPhrase of the query. Phrases are numbered starting from zero.
1314013150
**
1314113151
** xInstCount:
1314213152
** Set *pnInst to the total number of occurrences of all phrases within
1314313153
** the query within the current row. Return SQLITE_OK if successful, or
1314413154
** an error code (i.e. SQLITE_NOMEM) if an error occurs.
@@ -13150,16 +13160,17 @@
1315013160
**
1315113161
** xInst:
1315213162
** Query for the details of phrase match iIdx within the current row.
1315313163
** Phrase matches are numbered starting from zero, so the iIdx argument
1315413164
** should be greater than or equal to zero and smaller than the value
13155
-** output by xInstCount().
13165
+** output by xInstCount(). If iIdx is less than zero or greater than
13166
+** or equal to the value returned by xInstCount(), SQLITE_RANGE is returned.
1315613167
**
13157
-** Usually, output parameter *piPhrase is set to the phrase number, *piCol
13168
+** Otherwise, output parameter *piPhrase is set to the phrase number, *piCol
1315813169
** to the column in which it occurs and *piOff the token offset of the
13159
-** first token of the phrase. Returns SQLITE_OK if successful, or an error
13160
-** code (i.e. SQLITE_NOMEM) if an error occurs.
13170
+** first token of the phrase. SQLITE_OK is returned if successful, or an
13171
+** error code (i.e. SQLITE_NOMEM) if an error occurs.
1316113172
**
1316213173
** This API can be quite slow if used with an FTS5 table created with the
1316313174
** "detail=none" or "detail=column" option.
1316413175
**
1316513176
** xRowid:
@@ -13180,10 +13191,14 @@
1318013191
** row visited, the callback function passed as the fourth argument
1318113192
** is invoked. The context and API objects passed to the callback
1318213193
** function may be used to access the properties of each matched row.
1318313194
** Invoking Api.xUserData() returns a copy of the pointer passed as
1318413195
** the third argument to pUserData.
13196
+**
13197
+** If parameter iPhrase is less than zero, or greater than or equal to
13198
+** the number of phrases in the query, as returned by xPhraseCount(),
13199
+** this function returns SQLITE_RANGE.
1318513200
**
1318613201
** If the callback function returns any value other than SQLITE_OK, the
1318713202
** query is abandoned and the xQueryPhrase function returns immediately.
1318813203
** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
1318913204
** Otherwise, the error code is propagated upwards.
@@ -13295,13 +13310,46 @@
1329513310
** significantly more efficient than those alternatives when used with
1329613311
** "detail=column" tables.
1329713312
**
1329813313
** xPhraseNextColumn()
1329913314
** See xPhraseFirstColumn above.
13315
+**
13316
+** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken)
13317
+** This is used to access token iToken of phrase iPhrase of the current
13318
+** query. Before returning, output parameter *ppToken is set to point
13319
+** to a buffer containing the requested token, and *pnToken to the
13320
+** size of this buffer in bytes.
13321
+**
13322
+** If iPhrase or iToken are less than zero, or if iPhrase is greater than
13323
+** or equal to the number of phrases in the query as reported by
13324
+** xPhraseCount(), or if iToken is equal to or greater than the number of
13325
+** tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken
13326
+ are both zeroed.
13327
+**
13328
+** The output text is not a copy of the query text that specified the
13329
+** token. It is the output of the tokenizer module. For tokendata=1
13330
+** tables, this includes any embedded 0x00 and trailing data.
13331
+**
13332
+** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken)
13333
+** This is used to access token iToken of phrase hit iIdx within the
13334
+** current row. If iIdx is less than zero or greater than or equal to the
13335
+** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise,
13336
+** output variable (*ppToken) is set to point to a buffer containing the
13337
+** matching document token, and (*pnToken) to the size of that buffer in
13338
+** bytes. This API is not available if the specified token matches a
13339
+** prefix query term. In that case both output variables are always set
13340
+** to 0.
13341
+**
13342
+** The output text is not a copy of the document text that was tokenized.
13343
+** It is the output of the tokenizer module. For tokendata=1 tables, this
13344
+** includes any embedded 0x00 and trailing data.
13345
+**
13346
+** This API can be quite slow if used with an FTS5 table created with the
13347
+** "detail=none" or "detail=column" option.
1330013348
*/
1330113349
struct Fts5ExtensionApi {
13302
- int iVersion; /* Currently always set to 2 */
13350
+ int iVersion; /* Currently always set to 3 */
1330313351
1330413352
void *(*xUserData)(Fts5Context*);
1330513353
1330613354
int (*xColumnCount)(Fts5Context*);
1330713355
int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
@@ -13332,10 +13380,17 @@
1333213380
int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
1333313381
void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
1333413382
1333513383
int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
1333613384
void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
13385
+
13386
+ /* Below this point are iVersion>=3 only */
13387
+ int (*xQueryToken)(Fts5Context*,
13388
+ int iPhrase, int iToken,
13389
+ const char **ppToken, int *pnToken
13390
+ );
13391
+ int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*);
1333713392
};
1333813393
1333913394
/*
1334013395
** CUSTOM AUXILIARY FUNCTIONS
1334113396
*************************************************************************/
@@ -13818,11 +13873,11 @@
1381813873
** This is really just the default value for the max_page_count pragma.
1381913874
** This value can be lowered (or raised) at run-time using that the
1382013875
** max_page_count macro.
1382113876
*/
1382213877
#ifndef SQLITE_MAX_PAGE_COUNT
13823
-# define SQLITE_MAX_PAGE_COUNT 1073741823
13878
+# define SQLITE_MAX_PAGE_COUNT 0xfffffffe /* 4294967294 */
1382413879
#endif
1382513880
1382613881
/*
1382713882
** Maximum length (in bytes) of the pattern in a LIKE or GLOB
1382813883
** operator.
@@ -13956,10 +14011,23 @@
1395614011
#if defined(_MSC_VER) && !defined(SQLITE_OMIT_SEH)
1395714012
# define SQLITE_USE_SEH 1
1395814013
#else
1395914014
# undef SQLITE_USE_SEH
1396014015
#endif
14016
+
14017
+/*
14018
+** Enable SQLITE_DIRECT_OVERFLOW_READ, unless the build explicitly
14019
+** disables it using -DSQLITE_DIRECT_OVERFLOW_READ=0
14020
+*/
14021
+#if defined(SQLITE_DIRECT_OVERFLOW_READ) && SQLITE_DIRECT_OVERFLOW_READ+1==1
14022
+ /* Disable if -DSQLITE_DIRECT_OVERFLOW_READ=0 */
14023
+# undef SQLITE_DIRECT_OVERFLOW_READ
14024
+#else
14025
+ /* In all other cases, enable */
14026
+# define SQLITE_DIRECT_OVERFLOW_READ 1
14027
+#endif
14028
+
1396114029
1396214030
/*
1396314031
** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
1396414032
** 0 means mutexes are permanently disable and the library is never
1396514033
** threadsafe. 1 means the library is serialized which is the highest
@@ -15839,11 +15907,11 @@
1583915907
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
1584015908
SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
1584115909
SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
1584215910
SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
1584315911
SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
15844
-SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
15912
+SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, u64*);
1584515913
SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
1584615914
SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
1584715915
1584815916
/* Functions used to truncate the database file. */
1584915917
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
@@ -16426,10 +16494,11 @@
1642616494
#define P4_VTAB (-11) /* P4 is a pointer to an sqlite3_vtab structure */
1642716495
#define P4_REAL (-12) /* P4 is a 64-bit floating point value */
1642816496
#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
1642916497
#define P4_INTARRAY (-14) /* P4 is a vector of 32-bit integers */
1643016498
#define P4_FUNCCTX (-15) /* P4 is a pointer to an sqlite3_context object */
16499
+#define P4_TABLEREF (-16) /* Like P4_TABLE, but reference counted */
1643116500
1643216501
/* Error message codes for OP_Halt */
1643316502
#define P5_ConstraintNotNull 1
1643416503
#define P5_ConstraintUnique 2
1643516504
#define P5_ConstraintCheck 3
@@ -16648,17 +16717,19 @@
1664816717
#define OP_VColumn 176 /* synopsis: r[P3]=vcolumn(P2) */
1664916718
#define OP_VRename 177
1665016719
#define OP_Pagecount 178
1665116720
#define OP_MaxPgcnt 179
1665216721
#define OP_ClrSubtype 180 /* synopsis: r[P1].subtype = 0 */
16653
-#define OP_FilterAdd 181 /* synopsis: filter(P1) += key(P3@P4) */
16654
-#define OP_Trace 182
16655
-#define OP_CursorHint 183
16656
-#define OP_ReleaseReg 184 /* synopsis: release r[P1@P2] mask P3 */
16657
-#define OP_Noop 185
16658
-#define OP_Explain 186
16659
-#define OP_Abortable 187
16722
+#define OP_GetSubtype 181 /* synopsis: r[P2] = r[P1].subtype */
16723
+#define OP_SetSubtype 182 /* synopsis: r[P2].subtype = r[P1] */
16724
+#define OP_FilterAdd 183 /* synopsis: filter(P1) += key(P3@P4) */
16725
+#define OP_Trace 184
16726
+#define OP_CursorHint 185
16727
+#define OP_ReleaseReg 186 /* synopsis: release r[P1@P2] mask P3 */
16728
+#define OP_Noop 187
16729
+#define OP_Explain 188
16730
+#define OP_Abortable 189
1666016731
1666116732
/* Properties such as "out2" or "jump" that are specified in
1666216733
** comments following the "case" for each opcode in the vdbe.c
1666316734
** are encoded into bitvectors as follows:
1666416735
*/
@@ -16690,12 +16761,12 @@
1669016761
/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\
1669116762
/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
1669216763
/* 152 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
1669316764
/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
1669416765
/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\
16695
-/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x00, 0x00, 0x00,\
16696
-/* 184 */ 0x00, 0x00, 0x00, 0x00,}
16766
+/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\
16767
+/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}
1669716768
1669816769
/* The resolve3P2Values() routine is able to run faster if it knows
1669916770
** the value of the largest JUMP opcode. The smaller the maximum
1670016771
** JUMP opcode the better, so the mkopcodeh.tcl script that
1670116772
** generated this include file strives to group all JUMP opcodes
@@ -17952,15 +18023,15 @@
1795218023
{nArg, SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
1795318024
SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
1795418025
#define MFUNCTION(zName, nArg, xPtr, xFunc) \
1795518026
{nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8, \
1795618027
xPtr, 0, xFunc, 0, 0, 0, #zName, {0} }
17957
-#define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, iArg, xFunc) \
18028
+#define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, bJsonB, iArg, xFunc) \
1795818029
{nArg, SQLITE_FUNC_BUILTIN|SQLITE_DETERMINISTIC|SQLITE_FUNC_CONSTANT|\
1795918030
SQLITE_UTF8|((bUseCache)*SQLITE_FUNC_RUNONLY)|\
1796018031
((bRS)*SQLITE_SUBTYPE)|((bWS)*SQLITE_RESULT_SUBTYPE), \
17961
- SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
18032
+ SQLITE_INT_TO_PTR(iArg|((bJsonB)*JSON_BLOB)),0,xFunc,0, 0, 0, #zName, {0} }
1796218033
#define INLINE_FUNC(zName, nArg, iArg, mFlags) \
1796318034
{nArg, SQLITE_FUNC_BUILTIN|\
1796418035
SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
1796518036
SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
1796618037
#define TEST_FUNC(zName, nArg, iArg, mFlags) \
@@ -18591,10 +18662,11 @@
1859118662
unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
1859218663
unsigned isResized:1; /* True if resizeIndexObject() has been called */
1859318664
unsigned isCovering:1; /* True if this is a covering index */
1859418665
unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
1859518666
unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
18667
+ unsigned bLowQual:1; /* sqlite_stat1 says this is a low-quality index */
1859618668
unsigned bNoQuery:1; /* Do not use this index to optimize queries */
1859718669
unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
1859818670
unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */
1859918671
unsigned bHasExpr:1; /* Index contains an expression, either a literal
1860018672
** expression, or a reference to a VIRTUAL column */
@@ -18704,10 +18776,11 @@
1870418776
int iDistinct; /* Ephemeral table used to enforce DISTINCT */
1870518777
int iDistAddr; /* Address of OP_OpenEphemeral */
1870618778
int iOBTab; /* Ephemeral table to implement ORDER BY */
1870718779
u8 bOBPayload; /* iOBTab has payload columns separate from key */
1870818780
u8 bOBUnique; /* Enforce uniqueness on iOBTab keys */
18781
+ u8 bUseSubtype; /* Transfer subtype info through sorter */
1870918782
} *aFunc;
1871018783
int nFunc; /* Number of entries in aFunc[] */
1871118784
u32 selId; /* Select to which this AggInfo belongs */
1871218785
#ifdef SQLITE_DEBUG
1871318786
Select *pSelect; /* SELECT statement that this AggInfo supports */
@@ -19237,10 +19310,11 @@
1923719310
} uNC;
1923819311
NameContext *pNext; /* Next outer name context. NULL for outermost */
1923919312
int nRef; /* Number of names resolved by this context */
1924019313
int nNcErr; /* Number of errors encountered while resolving names */
1924119314
int ncFlags; /* Zero or more NC_* flags defined below */
19315
+ u32 nNestedSelect; /* Number of nested selects using this NC */
1924219316
Select *pWinSelect; /* SELECT statement for any window functions */
1924319317
};
1924419318
1924519319
/*
1924619320
** Allowed values for the NameContext, ncFlags field.
@@ -19953,10 +20027,13 @@
1995320027
** 2. Use sqlite3RCStrUnref() to free an RCStr string rather than
1995420028
** sqlite3_free()
1995520029
**
1995620030
** 3. Make a (read-only) copy of a read-only RCStr string using
1995720031
** sqlite3RCStrRef().
20032
+**
20033
+** "String" is in the name, but an RCStr object can also be used to hold
20034
+** binary data.
1995820035
*/
1995920036
struct RCStr {
1996020037
u64 nRCRef; /* Number of references */
1996120038
/* Total structure size should be a multiple of 8 bytes for alignment */
1996220039
};
@@ -20011,10 +20088,13 @@
2001120088
u8 bOpenUri; /* True to interpret filenames as URIs */
2001220089
u8 bUseCis; /* Use covering indices for full-scans */
2001320090
u8 bSmallMalloc; /* Avoid large memory allocations if true */
2001420091
u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */
2001520092
u8 bUseLongDouble; /* Make use of long double */
20093
+#ifdef SQLITE_DEBUG
20094
+ u8 bJsonSelfcheck; /* Double-check JSON parsing */
20095
+#endif
2001620096
int mxStrlen; /* Maximum string length */
2001720097
int neverCorrupt; /* Database is always well-formed */
2001820098
int szLookaside; /* Default lookaside buffer size */
2001920099
int nLookaside; /* Default lookaside buffer count */
2002020100
int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
@@ -20637,19 +20717,21 @@
2063720717
SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*);
2063820718
SQLITE_PRIVATE void sqlite3ExprOrderByAggregateError(Parse*,Expr*);
2063920719
SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*);
2064020720
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
2064120721
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
20722
+SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3*,void*);
2064220723
SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse*, Expr*);
2064320724
SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
2064420725
SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
2064520726
SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
2064620727
SQLITE_PRIVATE Select *sqlite3ExprListToValues(Parse*, int, ExprList*);
2064720728
SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
2064820729
SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int);
2064920730
SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
2065020731
SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
20732
+SQLITE_PRIVATE void sqlite3ExprListDeleteGeneric(sqlite3*,void*);
2065120733
SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
2065220734
SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
2065320735
SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
2065420736
SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
2065520737
SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
@@ -20736,10 +20818,11 @@
2073620818
SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
2073720819
#endif
2073820820
SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
2073920821
SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
2074020822
SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
20823
+SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3*, void*);
2074120824
SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
2074220825
#ifndef SQLITE_OMIT_AUTOINCREMENT
2074320826
SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
2074420827
SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
2074520828
#else
@@ -20772,10 +20855,11 @@
2077220855
SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
2077320856
SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
2077420857
SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
2077520858
Expr*,ExprList*,u32,Expr*);
2077620859
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
20860
+SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3*,void*);
2077720861
SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
2077820862
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, Trigger*);
2077920863
SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
2078020864
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
2078120865
SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
@@ -20998,10 +21082,11 @@
2099821082
#ifndef SQLITE_OMIT_UTF16
2099921083
SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
2100021084
#endif
2100121085
SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
2100221086
SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
21087
+SQLITE_PRIVATE int sqlite3Utf8ReadLimited(const u8*, int, u32*);
2100321088
SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
2100421089
SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
2100521090
SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
2100621091
SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
2100721092
SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
@@ -21344,10 +21429,11 @@
2134421429
#ifndef SQLITE_OMIT_CTE
2134521430
SQLITE_PRIVATE Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8);
2134621431
SQLITE_PRIVATE void sqlite3CteDelete(sqlite3*,Cte*);
2134721432
SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Cte*);
2134821433
SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
21434
+SQLITE_PRIVATE void sqlite3WithDeleteGeneric(sqlite3*,void*);
2134921435
SQLITE_PRIVATE With *sqlite3WithPush(Parse*, With*, u8);
2135021436
#else
2135121437
# define sqlite3CteNew(P,T,E,S) ((void*)0)
2135221438
# define sqlite3CteDelete(D,C)
2135321439
# define sqlite3CteWithAdd(P,W,C) ((void*)0)
@@ -22721,10 +22807,13 @@
2272122807
SQLITE_USE_URI, /* bOpenUri */
2272222808
SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
2272322809
0, /* bSmallMalloc */
2272422810
1, /* bExtraSchemaChecks */
2272522811
sizeof(LONGDOUBLE_TYPE)>8, /* bUseLongDouble */
22812
+#ifdef SQLITE_DEBUG
22813
+ 0, /* bJsonSelfcheck */
22814
+#endif
2272622815
0x7ffffffe, /* mxStrlen */
2272722816
0, /* neverCorrupt */
2272822817
SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
2272922818
SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
2273022819
{0,0,0,0,0,0,0,0}, /* m */
@@ -23973,11 +24062,11 @@
2397324062
/* no break */ deliberate_fall_through
2397424063
case SQLITE_DBSTATUS_CACHE_HIT:
2397524064
case SQLITE_DBSTATUS_CACHE_MISS:
2397624065
case SQLITE_DBSTATUS_CACHE_WRITE:{
2397724066
int i;
23978
- int nRet = 0;
24067
+ u64 nRet = 0;
2397924068
assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
2398024069
assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
2398124070
2398224071
for(i=0; i<db->nDb; i++){
2398324072
if( db->aDb[i].pBt ){
@@ -23986,11 +24075,11 @@
2398624075
}
2398724076
}
2398824077
*pHighwater = 0; /* IMP: R-42420-56072 */
2398924078
/* IMP: R-54100-20147 */
2399024079
/* IMP: R-29431-39229 */
23991
- *pCurrent = nRet;
24080
+ *pCurrent = (int)nRet & 0x7fffffff;
2399224081
break;
2399324082
}
2399424083
2399524084
/* Set *pCurrent to non-zero if there are unresolved deferred foreign
2399624085
** key constraints. Set *pCurrent to zero if all foreign key constraints
@@ -25055,10 +25144,16 @@
2505525144
n = sqlite3_value_bytes(argv[i]);
2505625145
if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
2505725146
}
2505825147
computeJD(p);
2505925148
if( p->isError || !validJulianDay(p->iJD) ) return 1;
25149
+ if( argc==1 && p->validYMD && p->D>28 ){
25150
+ /* Make sure a YYYY-MM-DD is normalized.
25151
+ ** Example: 2023-02-31 -> 2023-03-03 */
25152
+ assert( p->validJD );
25153
+ p->validYMD = 0;
25154
+ }
2506025155
return 0;
2506125156
}
2506225157
2506325158
2506425159
/*
@@ -32083,11 +32178,11 @@
3208332178
va_end(ap);
3208432179
}
3208532180
3208632181
3208732182
/*****************************************************************************
32088
-** Reference counted string storage
32183
+** Reference counted string/blob storage
3208932184
*****************************************************************************/
3209032185
3209132186
/*
3209232187
** Increase the reference count of the string by one.
3209332188
**
@@ -32935,11 +33030,11 @@
3293533030
pX = pExpr->pLeft;
3293633031
assert( ExprUseXList(pExpr) );
3293733032
assert( pExpr->x.pList->nExpr==2 );
3293833033
pY = pExpr->x.pList->a[0].pExpr;
3293933034
pZ = pExpr->x.pList->a[1].pExpr;
32940
- sqlite3TreeViewLine(pView, "BETWEEN");
33035
+ sqlite3TreeViewLine(pView, "BETWEEN%s", zFlgs);
3294133036
sqlite3TreeViewExpr(pView, pX, 1);
3294233037
sqlite3TreeViewExpr(pView, pY, 1);
3294333038
sqlite3TreeViewExpr(pView, pZ, 0);
3294433039
break;
3294533040
}
@@ -34070,11 +34165,42 @@
3407034165
|| (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
3407134166
}
3407234167
return c;
3407334168
}
3407434169
34075
-
34170
+/*
34171
+** Read a single UTF8 character out of buffer z[], but reading no
34172
+** more than n characters from the buffer. z[] is not zero-terminated.
34173
+**
34174
+** Return the number of bytes used to construct the character.
34175
+**
34176
+** Invalid UTF8 might generate a strange result. No effort is made
34177
+** to detect invalid UTF8.
34178
+**
34179
+** At most 4 bytes will be read out of z[]. The return value will always
34180
+** be between 1 and 4.
34181
+*/
34182
+SQLITE_PRIVATE int sqlite3Utf8ReadLimited(
34183
+ const u8 *z,
34184
+ int n,
34185
+ u32 *piOut
34186
+){
34187
+ u32 c;
34188
+ int i = 1;
34189
+ assert( n>0 );
34190
+ c = z[0];
34191
+ if( c>=0xc0 ){
34192
+ c = sqlite3Utf8Trans1[c-0xc0];
34193
+ if( n>4 ) n = 4;
34194
+ while( i<n && (z[i] & 0xc0)==0x80 ){
34195
+ c = (c<<6) + (0x3f & z[i]);
34196
+ i++;
34197
+ }
34198
+ }
34199
+ *piOut = c;
34200
+ return i;
34201
+}
3407634202
3407734203
3407834204
/*
3407934205
** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
3408034206
** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
@@ -34585,11 +34711,11 @@
3458534711
** Load the sqlite3.iSysErrno field if that is an appropriate thing
3458634712
** to do based on the SQLite error code in rc.
3458734713
*/
3458834714
SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
3458934715
if( rc==SQLITE_IOERR_NOMEM ) return;
34590
-#ifdef SQLITE_USE_SEH
34716
+#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
3459134717
if( rc==SQLITE_IOERR_IN_PAGE ){
3459234718
int ii;
3459334719
int iErr;
3459434720
sqlite3BtreeEnterAll(db);
3459534721
for(ii=0; ii<db->nDb; ii++){
@@ -36839,17 +36965,19 @@
3683936965
/* 176 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
3684036966
/* 177 */ "VRename" OpHelp(""),
3684136967
/* 178 */ "Pagecount" OpHelp(""),
3684236968
/* 179 */ "MaxPgcnt" OpHelp(""),
3684336969
/* 180 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),
36844
- /* 181 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),
36845
- /* 182 */ "Trace" OpHelp(""),
36846
- /* 183 */ "CursorHint" OpHelp(""),
36847
- /* 184 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
36848
- /* 185 */ "Noop" OpHelp(""),
36849
- /* 186 */ "Explain" OpHelp(""),
36850
- /* 187 */ "Abortable" OpHelp(""),
36970
+ /* 181 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),
36971
+ /* 182 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),
36972
+ /* 183 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),
36973
+ /* 184 */ "Trace" OpHelp(""),
36974
+ /* 185 */ "CursorHint" OpHelp(""),
36975
+ /* 186 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
36976
+ /* 187 */ "Noop" OpHelp(""),
36977
+ /* 188 */ "Explain" OpHelp(""),
36978
+ /* 189 */ "Abortable" OpHelp(""),
3685136979
};
3685236980
return azName[i];
3685336981
}
3685436982
#endif
3685536983
@@ -41891,11 +42019,17 @@
4189142019
return SQLITE_OK;
4189242020
}
4189342021
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4189442022
case SQLITE_FCNTL_LOCK_TIMEOUT: {
4189542023
int iOld = pFile->iBusyTimeout;
42024
+#if SQLITE_ENABLE_SETLK_TIMEOUT==1
4189642025
pFile->iBusyTimeout = *(int*)pArg;
42026
+#elif SQLITE_ENABLE_SETLK_TIMEOUT==2
42027
+ pFile->iBusyTimeout = !!(*(int*)pArg);
42028
+#else
42029
+# error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"
42030
+#endif
4189742031
*(int*)pArg = iOld;
4189842032
return SQLITE_OK;
4189942033
}
4190042034
#endif
4190142035
#if SQLITE_MAX_MMAP_SIZE>0
@@ -42144,10 +42278,29 @@
4214442278
** zFilename
4214542279
**
4214642280
** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
4214742281
** unixMutexHeld() is true when reading or writing any other field
4214842282
** in this structure.
42283
+**
42284
+** aLock[SQLITE_SHM_NLOCK]:
42285
+** This array records the various locks held by clients on each of the
42286
+** SQLITE_SHM_NLOCK slots. If the aLock[] entry is set to 0, then no
42287
+** locks are held by the process on this slot. If it is set to -1, then
42288
+** some client holds an EXCLUSIVE lock on the locking slot. If the aLock[]
42289
+** value is set to a positive value, then it is the number of shared
42290
+** locks currently held on the slot.
42291
+**
42292
+** aMutex[SQLITE_SHM_NLOCK]:
42293
+** Normally, when SQLITE_ENABLE_SETLK_TIMEOUT is not defined, mutex
42294
+** pShmMutex is used to protect the aLock[] array and the right to
42295
+** call fcntl() on unixShmNode.hShm to obtain or release locks.
42296
+**
42297
+** If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array
42298
+** of mutexes - one for each locking slot. To read or write locking
42299
+** slot aLock[iSlot], the caller must hold the corresponding mutex
42300
+** aMutex[iSlot]. Similarly, to call fcntl() to obtain or release a
42301
+** lock corresponding to slot iSlot, mutex aMutex[iSlot] must be held.
4214942302
*/
4215042303
struct unixShmNode {
4215142304
unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
4215242305
sqlite3_mutex *pShmMutex; /* Mutex to access this object */
4215342306
char *zFilename; /* Name of the mmapped file */
@@ -42157,14 +42310,15 @@
4215742310
u8 isReadonly; /* True if read-only */
4215842311
u8 isUnlocked; /* True if no DMS lock held */
4215942312
char **apRegion; /* Array of mapped shared-memory regions */
4216042313
int nRef; /* Number of unixShm objects pointing to this */
4216142314
unixShm *pFirst; /* All unixShm objects pointing to this */
42315
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42316
+ sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK];
42317
+#endif
4216242318
int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
4216342319
#ifdef SQLITE_DEBUG
42164
- u8 exclMask; /* Mask of exclusive locks held */
42165
- u8 sharedMask; /* Mask of shared locks held */
4216642320
u8 nextShmId; /* Next available unixShm.id value */
4216742321
#endif
4216842322
};
4216942323
4217042324
/*
@@ -42243,20 +42397,39 @@
4224342397
){
4224442398
unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4224542399
struct flock f; /* The posix advisory locking structure */
4224642400
int rc = SQLITE_OK; /* Result code form fcntl() */
4224742401
42248
- /* Access to the unixShmNode object is serialized by the caller */
4224942402
pShmNode = pFile->pInode->pShmNode;
42250
- assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
42251
- assert( pShmNode->nRef>0 || unixMutexHeld() );
42403
+
42404
+ /* Assert that the parameters are within expected range and that the
42405
+ ** correct mutex or mutexes are held. */
42406
+ assert( pShmNode->nRef>=0 );
42407
+ assert( (ofst==UNIX_SHM_DMS && n==1)
42408
+ || (ofst>=UNIX_SHM_BASE && ofst+n<=(UNIX_SHM_BASE+SQLITE_SHM_NLOCK))
42409
+ );
42410
+ if( ofst==UNIX_SHM_DMS ){
42411
+ assert( pShmNode->nRef>0 || unixMutexHeld() );
42412
+ assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
42413
+ }else{
42414
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42415
+ int ii;
42416
+ for(ii=ofst-UNIX_SHM_BASE; ii<ofst-UNIX_SHM_BASE+n; ii++){
42417
+ assert( sqlite3_mutex_held(pShmNode->aMutex[ii]) );
42418
+ }
42419
+#else
42420
+ assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
42421
+ assert( pShmNode->nRef>0 );
42422
+#endif
42423
+ }
4225242424
4225342425
/* Shared locks never span more than one byte */
4225442426
assert( n==1 || lockType!=F_RDLCK );
4225542427
4225642428
/* Locks are within range */
4225742429
assert( n>=1 && n<=SQLITE_SHM_NLOCK );
42430
+ assert( ofst>=UNIX_SHM_BASE && ofst<=(UNIX_SHM_DMS+SQLITE_SHM_NLOCK) );
4225842431
4225942432
if( pShmNode->hShm>=0 ){
4226042433
int res;
4226142434
/* Initialize the locking parameters */
4226242435
f.l_type = lockType;
@@ -42263,50 +42436,39 @@
4226342436
f.l_whence = SEEK_SET;
4226442437
f.l_start = ofst;
4226542438
f.l_len = n;
4226642439
res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4226742440
if( res==-1 ){
42268
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42441
+#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && SQLITE_ENABLE_SETLK_TIMEOUT==1
4226942442
rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
4227042443
#else
4227142444
rc = SQLITE_BUSY;
4227242445
#endif
4227342446
}
4227442447
}
4227542448
42276
- /* Update the global lock state and do debug tracing */
42277
-#ifdef SQLITE_DEBUG
42278
- { u16 mask;
42279
- OSTRACE(("SHM-LOCK "));
42280
- mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
42281
- if( rc==SQLITE_OK ){
42282
- if( lockType==F_UNLCK ){
42283
- OSTRACE(("unlock %d ok", ofst));
42284
- pShmNode->exclMask &= ~mask;
42285
- pShmNode->sharedMask &= ~mask;
42286
- }else if( lockType==F_RDLCK ){
42287
- OSTRACE(("read-lock %d ok", ofst));
42288
- pShmNode->exclMask &= ~mask;
42289
- pShmNode->sharedMask |= mask;
42290
- }else{
42291
- assert( lockType==F_WRLCK );
42292
- OSTRACE(("write-lock %d ok", ofst));
42293
- pShmNode->exclMask |= mask;
42294
- pShmNode->sharedMask &= ~mask;
42295
- }
42296
- }else{
42297
- if( lockType==F_UNLCK ){
42298
- OSTRACE(("unlock %d failed", ofst));
42299
- }else if( lockType==F_RDLCK ){
42300
- OSTRACE(("read-lock failed"));
42301
- }else{
42302
- assert( lockType==F_WRLCK );
42303
- OSTRACE(("write-lock %d failed", ofst));
42304
- }
42305
- }
42306
- OSTRACE((" - afterwards %03x,%03x\n",
42307
- pShmNode->sharedMask, pShmNode->exclMask));
42449
+ /* Do debug tracing */
42450
+#ifdef SQLITE_DEBUG
42451
+ OSTRACE(("SHM-LOCK "));
42452
+ if( rc==SQLITE_OK ){
42453
+ if( lockType==F_UNLCK ){
42454
+ OSTRACE(("unlock %d..%d ok\n", ofst, ofst+n-1));
42455
+ }else if( lockType==F_RDLCK ){
42456
+ OSTRACE(("read-lock %d..%d ok\n", ofst, ofst+n-1));
42457
+ }else{
42458
+ assert( lockType==F_WRLCK );
42459
+ OSTRACE(("write-lock %d..%d ok\n", ofst, ofst+n-1));
42460
+ }
42461
+ }else{
42462
+ if( lockType==F_UNLCK ){
42463
+ OSTRACE(("unlock %d..%d failed\n", ofst, ofst+n-1));
42464
+ }else if( lockType==F_RDLCK ){
42465
+ OSTRACE(("read-lock %d..%d failed\n", ofst, ofst+n-1));
42466
+ }else{
42467
+ assert( lockType==F_WRLCK );
42468
+ OSTRACE(("write-lock %d..%d failed\n", ofst, ofst+n-1));
42469
+ }
4230842470
}
4230942471
#endif
4231042472
4231142473
return rc;
4231242474
}
@@ -42340,10 +42502,15 @@
4234042502
if( p && ALWAYS(p->nRef==0) ){
4234142503
int nShmPerMap = unixShmRegionPerMap();
4234242504
int i;
4234342505
assert( p->pInode==pFd->pInode );
4234442506
sqlite3_mutex_free(p->pShmMutex);
42507
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42508
+ for(i=0; i<SQLITE_SHM_NLOCK; i++){
42509
+ sqlite3_mutex_free(p->aMutex[i]);
42510
+ }
42511
+#endif
4234542512
for(i=0; i<p->nRegion; i+=nShmPerMap){
4234642513
if( p->hShm>=0 ){
4234742514
osMunmap(p->apRegion[i], p->szRegion);
4234842515
}else{
4234942516
sqlite3_free(p->apRegion[i]);
@@ -42399,11 +42566,24 @@
4239942566
}else if( lock.l_type==F_UNLCK ){
4240042567
if( pShmNode->isReadonly ){
4240142568
pShmNode->isUnlocked = 1;
4240242569
rc = SQLITE_READONLY_CANTINIT;
4240342570
}else{
42571
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42572
+ /* Do not use a blocking lock here. If the lock cannot be obtained
42573
+ ** immediately, it means some other connection is truncating the
42574
+ ** *-shm file. And after it has done so, it will not release its
42575
+ ** lock, but only downgrade it to a shared lock. So no point in
42576
+ ** blocking here. The call below to obtain the shared DMS lock may
42577
+ ** use a blocking lock. */
42578
+ int iSaveTimeout = pDbFd->iBusyTimeout;
42579
+ pDbFd->iBusyTimeout = 0;
42580
+#endif
4240442581
rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
42582
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42583
+ pDbFd->iBusyTimeout = iSaveTimeout;
42584
+#endif
4240542585
/* The first connection to attach must truncate the -shm file. We
4240642586
** truncate to 3 bytes (an arbitrary small number, less than the
4240742587
** -shm header size) rather than 0 as a system debugging aid, to
4240842588
** help detect if a -shm file truncation is legitimate or is the work
4240942589
** or a rogue process. */
@@ -42520,10 +42700,22 @@
4252042700
pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4252142701
if( pShmNode->pShmMutex==0 ){
4252242702
rc = SQLITE_NOMEM_BKPT;
4252342703
goto shm_open_err;
4252442704
}
42705
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42706
+ {
42707
+ int ii;
42708
+ for(ii=0; ii<SQLITE_SHM_NLOCK; ii++){
42709
+ pShmNode->aMutex[ii] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
42710
+ if( pShmNode->aMutex[ii]==0 ){
42711
+ rc = SQLITE_NOMEM_BKPT;
42712
+ goto shm_open_err;
42713
+ }
42714
+ }
42715
+ }
42716
+#endif
4252542717
}
4252642718
4252742719
if( pInode->bProcessLock==0 ){
4252842720
if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
4252942721
pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
@@ -42741,13 +42933,15 @@
4274142933
**
4274242934
** assert( assertLockingArrayOk(pShmNode) );
4274342935
*/
4274442936
#ifdef SQLITE_DEBUG
4274542937
static int assertLockingArrayOk(unixShmNode *pShmNode){
42938
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42939
+ return 1;
42940
+#else
4274642941
unixShm *pX;
4274742942
int aLock[SQLITE_SHM_NLOCK];
42748
- assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
4274942943
4275042944
memset(aLock, 0, sizeof(aLock));
4275142945
for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4275242946
int i;
4275342947
for(i=0; i<SQLITE_SHM_NLOCK; i++){
@@ -42761,17 +42955,18 @@
4276142955
}
4276242956
}
4276342957
4276442958
assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
4276542959
return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
42960
+#endif
4276642961
}
4276742962
#endif
4276842963
4276942964
/*
4277042965
** Change the lock state for a shared-memory segment.
4277142966
**
42772
-** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
42967
+** Note that the relationship between SHARED and EXCLUSIVE locks is a little
4277342968
** different here than in posix. In xShmLock(), one can go from unlocked
4277442969
** to shared and back or from unlocked to exclusive and back. But one may
4277542970
** not go from shared to exclusive or from exclusive to shared.
4277642971
*/
4277742972
static int unixShmLock(
@@ -42782,11 +42977,11 @@
4278242977
){
4278342978
unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4278442979
unixShm *p; /* The shared memory being locked */
4278542980
unixShmNode *pShmNode; /* The underlying file iNode */
4278642981
int rc = SQLITE_OK; /* Result code */
42787
- u16 mask; /* Mask of locks to take or release */
42982
+ u16 mask = (1<<(ofst+n)) - (1<<ofst); /* Mask of locks to take or release */
4278842983
int *aLock;
4278942984
4279042985
p = pDbFd->pShm;
4279142986
if( p==0 ) return SQLITE_IOERR_SHMLOCK;
4279242987
pShmNode = p->pShmNode;
@@ -42817,92 +43012,155 @@
4281743012
** held.
4281843013
**
4281943014
** It is not permitted to block on the RECOVER lock.
4282043015
*/
4282143016
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
42822
- assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
42823
- (ofst!=2) /* not RECOVER */
42824
- && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
42825
- && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
42826
- && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
42827
- ));
42828
-#endif
42829
-
42830
- mask = (1<<(ofst+n)) - (1<<ofst);
42831
- assert( n>1 || mask==(1<<ofst) );
42832
- sqlite3_mutex_enter(pShmNode->pShmMutex);
42833
- assert( assertLockingArrayOk(pShmNode) );
42834
- if( flags & SQLITE_SHM_UNLOCK ){
42835
- if( (p->exclMask|p->sharedMask) & mask ){
42836
- int ii;
42837
- int bUnlock = 1;
42838
-
42839
- for(ii=ofst; ii<ofst+n; ii++){
42840
- if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
42841
- bUnlock = 0;
42842
- }
42843
- }
42844
-
42845
- if( bUnlock ){
42846
- rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
42847
- if( rc==SQLITE_OK ){
42848
- memset(&aLock[ofst], 0, sizeof(int)*n);
42849
- }
42850
- }else if( ALWAYS(p->sharedMask & (1<<ofst)) ){
42851
- assert( n==1 && aLock[ofst]>1 );
42852
- aLock[ofst]--;
42853
- }
42854
-
42855
- /* Undo the local locks */
42856
- if( rc==SQLITE_OK ){
42857
- p->exclMask &= ~mask;
42858
- p->sharedMask &= ~mask;
42859
- }
42860
- }
42861
- }else if( flags & SQLITE_SHM_SHARED ){
42862
- assert( n==1 );
42863
- assert( (p->exclMask & (1<<ofst))==0 );
42864
- if( (p->sharedMask & mask)==0 ){
42865
- if( aLock[ofst]<0 ){
42866
- rc = SQLITE_BUSY;
42867
- }else if( aLock[ofst]==0 ){
42868
- rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
42869
- }
42870
-
42871
- /* Get the local shared locks */
42872
- if( rc==SQLITE_OK ){
42873
- p->sharedMask |= mask;
42874
- aLock[ofst]++;
42875
- }
42876
- }
42877
- }else{
42878
- /* Make sure no sibling connections hold locks that will block this
42879
- ** lock. If any do, return SQLITE_BUSY right away. */
42880
- int ii;
42881
- for(ii=ofst; ii<ofst+n; ii++){
42882
- assert( (p->sharedMask & mask)==0 );
42883
- if( ALWAYS((p->exclMask & (1<<ii))==0) && aLock[ii] ){
42884
- rc = SQLITE_BUSY;
42885
- break;
42886
- }
42887
- }
42888
-
42889
- /* Get the exclusive locks at the system level. Then if successful
42890
- ** also update the in-memory values. */
42891
- if( rc==SQLITE_OK ){
42892
- rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
42893
- if( rc==SQLITE_OK ){
42894
- assert( (p->sharedMask & mask)==0 );
42895
- p->exclMask |= mask;
42896
- for(ii=ofst; ii<ofst+n; ii++){
42897
- aLock[ii] = -1;
42898
- }
42899
- }
42900
- }
42901
- }
42902
- assert( assertLockingArrayOk(pShmNode) );
42903
- sqlite3_mutex_leave(pShmNode->pShmMutex);
43017
+ {
43018
+ u16 lockMask = (p->exclMask|p->sharedMask);
43019
+ assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
43020
+ (ofst!=2) /* not RECOVER */
43021
+ && (ofst!=1 || lockMask==0 || lockMask==2)
43022
+ && (ofst!=0 || lockMask<3)
43023
+ && (ofst<3 || lockMask<(1<<ofst))
43024
+ ));
43025
+ }
43026
+#endif
43027
+
43028
+ /* Check if there is any work to do. There are three cases:
43029
+ **
43030
+ ** a) An unlock operation where there are locks to unlock,
43031
+ ** b) An shared lock where the requested lock is not already held
43032
+ ** c) An exclusive lock where the requested lock is not already held
43033
+ **
43034
+ ** The SQLite core never requests an exclusive lock that it already holds.
43035
+ ** This is assert()ed below.
43036
+ */
43037
+ assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)
43038
+ || 0==(p->exclMask & mask)
43039
+ );
43040
+ if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask))
43041
+ || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask))
43042
+ || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK))
43043
+ ){
43044
+
43045
+ /* Take the required mutexes. In SETLK_TIMEOUT mode (blocking locks), if
43046
+ ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any
43047
+ ** other thread is holding this mutex, then it is either holding or about
43048
+ ** to hold a lock exclusive to the one being requested, and we may
43049
+ ** therefore return SQLITE_BUSY to the caller.
43050
+ **
43051
+ ** Doing this prevents some deadlock scenarios. For example, thread 1 may
43052
+ ** be a checkpointer blocked waiting on the WRITER lock. And thread 2
43053
+ ** may be a normal SQL client upgrading to a write transaction. In this
43054
+ ** case thread 2 does a non-blocking request for the WRITER lock. But -
43055
+ ** if it were to use sqlite3_mutex_enter() then it would effectively
43056
+ ** become a (doomed) blocking request, as thread 2 would block until thread
43057
+ ** 1 obtained WRITER and released the mutex. Since thread 2 already holds
43058
+ ** a lock on a read-locking slot at this point, this breaks the
43059
+ ** anti-deadlock rules (see above). */
43060
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43061
+ int iMutex;
43062
+ for(iMutex=ofst; iMutex<ofst+n; iMutex++){
43063
+ if( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) ){
43064
+ rc = sqlite3_mutex_try(pShmNode->aMutex[iMutex]);
43065
+ if( rc!=SQLITE_OK ) goto leave_shmnode_mutexes;
43066
+ }else{
43067
+ sqlite3_mutex_enter(pShmNode->aMutex[iMutex]);
43068
+ }
43069
+ }
43070
+#else
43071
+ sqlite3_mutex_enter(pShmNode->pShmMutex);
43072
+#endif
43073
+
43074
+ if( ALWAYS(rc==SQLITE_OK) ){
43075
+ if( flags & SQLITE_SHM_UNLOCK ){
43076
+ /* Case (a) - unlock. */
43077
+ int bUnlock = 1;
43078
+ assert( (p->exclMask & p->sharedMask)==0 );
43079
+ assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask );
43080
+ assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask );
43081
+
43082
+ /* If this is a SHARED lock being unlocked, it is possible that other
43083
+ ** clients within this process are holding the same SHARED lock. In
43084
+ ** this case, set bUnlock to 0 so that the posix lock is not removed
43085
+ ** from the file-descriptor below. */
43086
+ if( flags & SQLITE_SHM_SHARED ){
43087
+ assert( n==1 );
43088
+ assert( aLock[ofst]>=1 );
43089
+ if( aLock[ofst]>1 ){
43090
+ bUnlock = 0;
43091
+ aLock[ofst]--;
43092
+ p->sharedMask &= ~mask;
43093
+ }
43094
+ }
43095
+
43096
+ if( bUnlock ){
43097
+ rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
43098
+ if( rc==SQLITE_OK ){
43099
+ memset(&aLock[ofst], 0, sizeof(int)*n);
43100
+ p->sharedMask &= ~mask;
43101
+ p->exclMask &= ~mask;
43102
+ }
43103
+ }
43104
+ }else if( flags & SQLITE_SHM_SHARED ){
43105
+ /* Case (b) - a shared lock. */
43106
+
43107
+ if( aLock[ofst]<0 ){
43108
+ /* An exclusive lock is held by some other connection. BUSY. */
43109
+ rc = SQLITE_BUSY;
43110
+ }else if( aLock[ofst]==0 ){
43111
+ rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
43112
+ }
43113
+
43114
+ /* Get the local shared locks */
43115
+ if( rc==SQLITE_OK ){
43116
+ p->sharedMask |= mask;
43117
+ aLock[ofst]++;
43118
+ }
43119
+ }else{
43120
+ /* Case (c) - an exclusive lock. */
43121
+ int ii;
43122
+
43123
+ assert( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) );
43124
+ assert( (p->sharedMask & mask)==0 );
43125
+ assert( (p->exclMask & mask)==0 );
43126
+
43127
+ /* Make sure no sibling connections hold locks that will block this
43128
+ ** lock. If any do, return SQLITE_BUSY right away. */
43129
+ for(ii=ofst; ii<ofst+n; ii++){
43130
+ if( aLock[ii] ){
43131
+ rc = SQLITE_BUSY;
43132
+ break;
43133
+ }
43134
+ }
43135
+
43136
+ /* Get the exclusive locks at the system level. Then if successful
43137
+ ** also update the in-memory values. */
43138
+ if( rc==SQLITE_OK ){
43139
+ rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
43140
+ if( rc==SQLITE_OK ){
43141
+ p->exclMask |= mask;
43142
+ for(ii=ofst; ii<ofst+n; ii++){
43143
+ aLock[ii] = -1;
43144
+ }
43145
+ }
43146
+ }
43147
+ }
43148
+ assert( assertLockingArrayOk(pShmNode) );
43149
+ }
43150
+
43151
+ /* Drop the mutexes acquired above. */
43152
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
43153
+ leave_shmnode_mutexes:
43154
+ for(iMutex--; iMutex>=ofst; iMutex--){
43155
+ sqlite3_mutex_leave(pShmNode->aMutex[iMutex]);
43156
+ }
43157
+#else
43158
+ sqlite3_mutex_leave(pShmNode->pShmMutex);
43159
+#endif
43160
+ }
43161
+
4290443162
OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4290543163
p->id, osGetpid(0), p->sharedMask, p->exclMask));
4290643164
return rc;
4290743165
}
4290843166
@@ -43148,15 +43406,20 @@
4314843406
#endif
4314943407
*pp = 0;
4315043408
4315143409
#if SQLITE_MAX_MMAP_SIZE>0
4315243410
if( pFd->mmapSizeMax>0 ){
43411
+ /* Ensure that there is always at least a 256 byte buffer of addressable
43412
+ ** memory following the returned page. If the database is corrupt,
43413
+ ** SQLite may overread the page slightly (in practice only a few bytes,
43414
+ ** but 256 is safe, round, number). */
43415
+ const int nEofBuffer = 256;
4315343416
if( pFd->pMapRegion==0 ){
4315443417
int rc = unixMapfile(pFd, -1);
4315543418
if( rc!=SQLITE_OK ) return rc;
4315643419
}
43157
- if( pFd->mmapSize >= iOff+nAmt ){
43420
+ if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
4315843421
*pp = &((u8 *)pFd->pMapRegion)[iOff];
4315943422
pFd->nFetchOut++;
4316043423
}
4316143424
}
4316243425
#endif
@@ -50505,19 +50768,24 @@
5050550768
OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
5050650769
osGetCurrentProcessId(), fd, iOff, nAmt, pp));
5050750770
5050850771
#if SQLITE_MAX_MMAP_SIZE>0
5050950772
if( pFd->mmapSizeMax>0 ){
50773
+ /* Ensure that there is always at least a 256 byte buffer of addressable
50774
+ ** memory following the returned page. If the database is corrupt,
50775
+ ** SQLite may overread the page slightly (in practice only a few bytes,
50776
+ ** but 256 is safe, round, number). */
50777
+ const int nEofBuffer = 256;
5051050778
if( pFd->pMapRegion==0 ){
5051150779
int rc = winMapfile(pFd, -1);
5051250780
if( rc!=SQLITE_OK ){
5051350781
OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
5051450782
osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
5051550783
return rc;
5051650784
}
5051750785
}
50518
- if( pFd->mmapSize >= iOff+nAmt ){
50786
+ if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
5051950787
assert( pFd->pMapRegion!=0 );
5052050788
*pp = &((u8 *)pFd->pMapRegion)[iOff];
5052150789
pFd->nFetchOut++;
5052250790
}
5052350791
}
@@ -57116,11 +57384,11 @@
5711657384
i64 journalSizeLimit; /* Size limit for persistent journal files */
5711757385
char *zFilename; /* Name of the database file */
5711857386
char *zJournal; /* Name of the journal file */
5711957387
int (*xBusyHandler)(void*); /* Function to call when busy */
5712057388
void *pBusyHandlerArg; /* Context argument for xBusyHandler */
57121
- int aStat[4]; /* Total cache hits, misses, writes, spills */
57389
+ u32 aStat[4]; /* Total cache hits, misses, writes, spills */
5712257390
#ifdef SQLITE_TEST
5712357391
int nRead; /* Database pages read */
5712457392
#endif
5712557393
void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
5712657394
int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
@@ -57246,13 +57514,12 @@
5724657514
if( pPager->fd->pMethods==0 ) return 0;
5724757515
if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
5724857516
#ifndef SQLITE_OMIT_WAL
5724957517
if( pPager->pWal ){
5725057518
u32 iRead = 0;
57251
- int rc;
57252
- rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
57253
- return (rc==SQLITE_OK && iRead==0);
57519
+ (void)sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
57520
+ return iRead==0;
5725457521
}
5725557522
#endif
5725657523
return 1;
5725757524
}
5725857525
#endif
@@ -63260,15 +63527,15 @@
6326063527
a[1] = sqlite3PcachePagecount(pPager->pPCache);
6326163528
a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
6326263529
a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
6326363530
a[4] = pPager->eState;
6326463531
a[5] = pPager->errCode;
63265
- a[6] = pPager->aStat[PAGER_STAT_HIT];
63266
- a[7] = pPager->aStat[PAGER_STAT_MISS];
63532
+ a[6] = (int)pPager->aStat[PAGER_STAT_HIT] & 0x7fffffff;
63533
+ a[7] = (int)pPager->aStat[PAGER_STAT_MISS] & 0x7fffffff;
6326763534
a[8] = 0; /* Used to be pPager->nOvfl */
6326863535
a[9] = pPager->nRead;
63269
- a[10] = pPager->aStat[PAGER_STAT_WRITE];
63536
+ a[10] = (int)pPager->aStat[PAGER_STAT_WRITE] & 0x7fffffff;
6327063537
return a;
6327163538
}
6327263539
#endif
6327363540
6327463541
/*
@@ -63280,11 +63547,11 @@
6328063547
** Before returning, *pnVal is incremented by the
6328163548
** current cache hit or miss count, according to the value of eStat. If the
6328263549
** reset parameter is non-zero, the cache hit or miss count is zeroed before
6328363550
** returning.
6328463551
*/
63285
-SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
63552
+SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, u64 *pnVal){
6328663553
6328763554
assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
6328863555
|| eStat==SQLITE_DBSTATUS_CACHE_MISS
6328963556
|| eStat==SQLITE_DBSTATUS_CACHE_WRITE
6329063557
|| eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
@@ -64220,11 +64487,11 @@
6422064487
assert( pPager->eState>=PAGER_READER );
6422164488
return sqlite3WalFramesize(pPager->pWal);
6422264489
}
6422364490
#endif
6422464491
64225
-#ifdef SQLITE_USE_SEH
64492
+#if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL)
6422664493
SQLITE_PRIVATE int sqlite3PagerWalSystemErrno(Pager *pPager){
6422764494
return sqlite3WalSystemErrno(pPager->pWal);
6422864495
}
6422964496
#endif
6423064497
@@ -66236,10 +66503,23 @@
6623666503
*pp = p;
6623766504
return rc;
6623866505
}
6623966506
6624066507
#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
66508
+
66509
+
66510
+/*
66511
+** Attempt to enable blocking locks that block for nMs ms. Return 1 if
66512
+** blocking locks are successfully enabled, or 0 otherwise.
66513
+*/
66514
+static int walEnableBlockingMs(Wal *pWal, int nMs){
66515
+ int rc = sqlite3OsFileControl(
66516
+ pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&nMs
66517
+ );
66518
+ return (rc==SQLITE_OK);
66519
+}
66520
+
6624166521
/*
6624266522
** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
6624366523
** they are supported by the VFS, and (b) the database handle is configured
6624466524
** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
6624566525
** or 0 otherwise.
@@ -66247,15 +66527,11 @@
6624766527
static int walEnableBlocking(Wal *pWal){
6624866528
int res = 0;
6624966529
if( pWal->db ){
6625066530
int tmout = pWal->db->busyTimeout;
6625166531
if( tmout ){
66252
- int rc;
66253
- rc = sqlite3OsFileControl(
66254
- pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
66255
- );
66256
- res = (rc==SQLITE_OK);
66532
+ res = walEnableBlockingMs(pWal, tmout);
6625766533
}
6625866534
}
6625966535
return res;
6626066536
}
6626166537
@@ -66300,24 +66576,14 @@
6630066576
*/
6630166577
SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){
6630266578
pWal->db = db;
6630366579
}
6630466580
66305
-/*
66306
-** Take an exclusive WRITE lock. Blocking if so configured.
66307
-*/
66308
-static int walLockWriter(Wal *pWal){
66309
- int rc;
66310
- walEnableBlocking(pWal);
66311
- rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
66312
- walDisableBlocking(pWal);
66313
- return rc;
66314
-}
6631566581
#else
6631666582
# define walEnableBlocking(x) 0
6631766583
# define walDisableBlocking(x)
66318
-# define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)
66584
+# define walEnableBlockingMs(pWal, ms) 0
6631966585
# define sqlite3WalDb(pWal, db)
6632066586
#endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
6632166587
6632266588
6632366589
/*
@@ -66914,19 +67180,22 @@
6691467180
walUnlockShared(pWal, WAL_WRITE_LOCK);
6691567181
rc = SQLITE_READONLY_RECOVERY;
6691667182
}
6691767183
}else{
6691867184
int bWriteLock = pWal->writeLock;
66919
- if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){
67185
+ if( bWriteLock
67186
+ || SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1))
67187
+ ){
6692067188
pWal->writeLock = 1;
6692167189
if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
6692267190
badHdr = walIndexTryHdr(pWal, pChanged);
6692367191
if( badHdr ){
6692467192
/* If the wal-index header is still malformed even while holding
6692567193
** a WRITE lock, it can only mean that the header is corrupted and
6692667194
** needs to be reconstructed. So run recovery to do exactly that.
66927
- */
67195
+ ** Disable blocking locks first. */
67196
+ walDisableBlocking(pWal);
6692867197
rc = walIndexRecover(pWal);
6692967198
*pChanged = 1;
6693067199
}
6693167200
}
6693267201
if( bWriteLock==0 ){
@@ -67132,10 +67401,41 @@
6713267401
*pChanged = 1;
6713367402
}
6713467403
return rc;
6713567404
}
6713667405
67406
+/*
67407
+** The final argument passed to walTryBeginRead() is of type (int*). The
67408
+** caller should invoke walTryBeginRead as follows:
67409
+**
67410
+** int cnt = 0;
67411
+** do {
67412
+** rc = walTryBeginRead(..., &cnt);
67413
+** }while( rc==WAL_RETRY );
67414
+**
67415
+** The final value of "cnt" is of no use to the caller. It is used by
67416
+** the implementation of walTryBeginRead() as follows:
67417
+**
67418
+** + Each time walTryBeginRead() is called, it is incremented. Once
67419
+** it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead()
67420
+** has many times been invoked and failed with WAL_RETRY - walTryBeginRead()
67421
+** returns SQLITE_PROTOCOL.
67422
+**
67423
+** + If SQLITE_ENABLE_SETLK_TIMEOUT is defined and walTryBeginRead() failed
67424
+** because a blocking lock timed out (SQLITE_BUSY_TIMEOUT from the OS
67425
+** layer), the WAL_RETRY_BLOCKED_MASK bit is set in "cnt". In this case
67426
+** the next invocation of walTryBeginRead() may omit an expected call to
67427
+** sqlite3OsSleep(). There has already been a delay when the previous call
67428
+** waited on a lock.
67429
+*/
67430
+#define WAL_RETRY_PROTOCOL_LIMIT 100
67431
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67432
+# define WAL_RETRY_BLOCKED_MASK 0x10000000
67433
+#else
67434
+# define WAL_RETRY_BLOCKED_MASK 0
67435
+#endif
67436
+
6713767437
/*
6713867438
** Attempt to start a read transaction. This might fail due to a race or
6713967439
** other transient condition. When that happens, it returns WAL_RETRY to
6714067440
** indicate to the caller that it is safe to retry immediately.
6714167441
**
@@ -67182,17 +67482,20 @@
6718267482
** checkpoint process do as much work as possible. This routine might
6718367483
** update values of the aReadMark[] array in the header, but if it does
6718467484
** so it takes care to hold an exclusive lock on the corresponding
6718567485
** WAL_READ_LOCK() while changing values.
6718667486
*/
67187
-static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
67487
+static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){
6718867488
volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
6718967489
u32 mxReadMark; /* Largest aReadMark[] value */
6719067490
int mxI; /* Index of largest aReadMark[] value */
6719167491
int i; /* Loop counter */
6719267492
int rc = SQLITE_OK; /* Return code */
6719367493
u32 mxFrame; /* Wal frame to lock to */
67494
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67495
+ int nBlockTmout = 0;
67496
+#endif
6719467497
6719567498
assert( pWal->readLock<0 ); /* Not currently locked */
6719667499
6719767500
/* useWal may only be set for read/write connections */
6719867501
assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
@@ -67212,25 +67515,52 @@
6721267515
** is more of a scheduler yield than an actual delay. But on the 10th
6721367516
** an subsequent retries, the delays start becoming longer and longer,
6721467517
** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
6721567518
** The total delay time before giving up is less than 10 seconds.
6721667519
*/
67217
- if( cnt>5 ){
67520
+ (*pCnt)++;
67521
+ if( *pCnt>5 ){
6721867522
int nDelay = 1; /* Pause time in microseconds */
67219
- if( cnt>100 ){
67523
+ int cnt = (*pCnt & ~WAL_RETRY_BLOCKED_MASK);
67524
+ if( cnt>WAL_RETRY_PROTOCOL_LIMIT ){
6722067525
VVA_ONLY( pWal->lockError = 1; )
6722167526
return SQLITE_PROTOCOL;
6722267527
}
67223
- if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
67528
+ if( *pCnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
67529
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67530
+ /* In SQLITE_ENABLE_SETLK_TIMEOUT builds, configure the file-descriptor
67531
+ ** to block for locks for approximately nDelay us. This affects three
67532
+ ** locks: (a) the shared lock taken on the DMS slot in os_unix.c (if
67533
+ ** using os_unix.c), (b) the WRITER lock taken in walIndexReadHdr() if the
67534
+ ** first attempted read fails, and (c) the shared lock taken on the
67535
+ ** read-mark.
67536
+ **
67537
+ ** If the previous call failed due to an SQLITE_BUSY_TIMEOUT error,
67538
+ ** then sleep for the minimum of 1us. The previous call already provided
67539
+ ** an extra delay while it was blocking on the lock.
67540
+ */
67541
+ nBlockTmout = (nDelay+998) / 1000;
67542
+ if( !useWal && walEnableBlockingMs(pWal, nBlockTmout) ){
67543
+ if( *pCnt & WAL_RETRY_BLOCKED_MASK ) nDelay = 1;
67544
+ }
67545
+#endif
6722467546
sqlite3OsSleep(pWal->pVfs, nDelay);
67547
+ *pCnt &= ~WAL_RETRY_BLOCKED_MASK;
6722567548
}
6722667549
6722767550
if( !useWal ){
6722867551
assert( rc==SQLITE_OK );
6722967552
if( pWal->bShmUnreliable==0 ){
6723067553
rc = walIndexReadHdr(pWal, pChanged);
6723167554
}
67555
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67556
+ walDisableBlocking(pWal);
67557
+ if( rc==SQLITE_BUSY_TIMEOUT ){
67558
+ rc = SQLITE_BUSY;
67559
+ *pCnt |= WAL_RETRY_BLOCKED_MASK;
67560
+ }
67561
+#endif
6723267562
if( rc==SQLITE_BUSY ){
6723367563
/* If there is not a recovery running in another thread or process
6723467564
** then convert BUSY errors to WAL_RETRY. If recovery is known to
6723567565
** be running, convert BUSY to BUSY_RECOVERY. There is a race here
6723667566
** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
@@ -67341,13 +67671,23 @@
6734167671
if( mxI==0 ){
6734267672
assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
6734367673
return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
6734467674
}
6734567675
67676
+ (void)walEnableBlockingMs(pWal, nBlockTmout);
6734667677
rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
67678
+ walDisableBlocking(pWal);
6734767679
if( rc ){
67348
- return rc==SQLITE_BUSY ? WAL_RETRY : rc;
67680
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
67681
+ if( rc==SQLITE_BUSY_TIMEOUT ){
67682
+ *pCnt |= WAL_RETRY_BLOCKED_MASK;
67683
+ }
67684
+#else
67685
+ assert( rc!=SQLITE_BUSY_TIMEOUT );
67686
+#endif
67687
+ assert( (rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT );
67688
+ return (rc&0xFF)==SQLITE_BUSY ? WAL_RETRY : rc;
6734967689
}
6735067690
/* Now that the read-lock has been obtained, check that neither the
6735167691
** value in the aReadMark[] array or the contents of the wal-index
6735267692
** header have changed.
6735367693
**
@@ -67531,11 +67871,11 @@
6753167871
ckptLock = 1;
6753267872
}
6753367873
#endif
6753467874
6753567875
do{
67536
- rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
67876
+ rc = walTryBeginRead(pWal, pChanged, 0, &cnt);
6753767877
}while( rc==WAL_RETRY );
6753867878
testcase( (rc&0xff)==SQLITE_BUSY );
6753967879
testcase( (rc&0xff)==SQLITE_IOERR );
6754067880
testcase( rc==SQLITE_PROTOCOL );
6754167881
testcase( rc==SQLITE_OK );
@@ -67712,10 +68052,11 @@
6771268052
if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
6771368053
assert( iFrame>iRead || CORRUPT_DB );
6771468054
iRead = iFrame;
6771568055
}
6771668056
if( (nCollide--)==0 ){
68057
+ *piRead = 0;
6771768058
return SQLITE_CORRUPT_BKPT;
6771868059
}
6771968060
iKey = walNextHash(iKey);
6772068061
}
6772168062
if( iRead ) break;
@@ -68015,11 +68356,11 @@
6801568356
walUnlockShared(pWal, WAL_READ_LOCK(0));
6801668357
pWal->readLock = -1;
6801768358
cnt = 0;
6801868359
do{
6801968360
int notUsed;
68020
- rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
68361
+ rc = walTryBeginRead(pWal, &notUsed, 1, &cnt);
6802168362
}while( rc==WAL_RETRY );
6802268363
assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
6802368364
testcase( (rc&0xff)==SQLITE_IOERR );
6802468365
testcase( rc==SQLITE_PROTOCOL );
6802568366
testcase( rc==SQLITE_OK );
@@ -68436,14 +68777,13 @@
6843668777
assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
6843768778
6843868779
if( pWal->readOnly ) return SQLITE_READONLY;
6843968780
WALTRACE(("WAL%p: checkpoint begins\n", pWal));
6844068781
68441
- /* Enable blocking locks, if possible. If blocking locks are successfully
68442
- ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
68782
+ /* Enable blocking locks, if possible. */
6844368783
sqlite3WalDb(pWal, db);
68444
- (void)walEnableBlocking(pWal);
68784
+ if( xBusy2 ) (void)walEnableBlocking(pWal);
6844568785
6844668786
/* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
6844768787
** "checkpoint" lock on the database file.
6844868788
** EVIDENCE-OF: R-10421-19736 If any other process is running a
6844968789
** checkpoint operation at the same time, the lock cannot be obtained and
@@ -68480,13 +68820,18 @@
6848068820
6848168821
6848268822
/* Read the wal-index header. */
6848368823
SEH_TRY {
6848468824
if( rc==SQLITE_OK ){
68825
+ /* For a passive checkpoint, do not re-enable blocking locks after
68826
+ ** reading the wal-index header. A passive checkpoint should not block
68827
+ ** or invoke the busy handler. The only lock such a checkpoint may
68828
+ ** attempt to obtain is a lock on a read-slot, and it should give up
68829
+ ** immediately and do a partial checkpoint if it cannot obtain it. */
6848568830
walDisableBlocking(pWal);
6848668831
rc = walIndexReadHdr(pWal, &isChanged);
68487
- (void)walEnableBlocking(pWal);
68832
+ if( eMode2!=SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal);
6848868833
if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
6848968834
sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
6849068835
}
6849168836
}
6849268837
@@ -68819,11 +69164,11 @@
6881969164
** 20 1 Bytes of unused space at the end of each page
6882069165
** 21 1 Max embedded payload fraction (must be 64)
6882169166
** 22 1 Min embedded payload fraction (must be 32)
6882269167
** 23 1 Min leaf payload fraction (must be 32)
6882369168
** 24 4 File change counter
68824
-** 28 4 Reserved for future use
69169
+** 28 4 The size of the database in pages
6882569170
** 32 4 First freelist page
6882669171
** 36 4 Number of freelist pages in the file
6882769172
** 40 60 15 4-byte meta values passed to higher layers
6882869173
**
6882969174
** 40 4 Schema cookie
@@ -74946,11 +75291,10 @@
7494675291
u8 aSave[4];
7494775292
u8 *aWrite = &pBuf[-4];
7494875293
assert( aWrite>=pBufStart ); /* due to (6) */
7494975294
memcpy(aSave, aWrite, 4);
7495075295
rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
74951
- if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
7495275296
nextPage = get4byte(aWrite);
7495375297
memcpy(aWrite, aSave, 4);
7495475298
}else
7495575299
#endif
7495675300
@@ -76066,11 +76410,14 @@
7606676410
if( pCur->skipNext<0 ) return SQLITE_OK;
7606776411
}
7606876412
}
7606976413
7607076414
pPage = pCur->pPage;
76071
- assert( pPage->isInit );
76415
+ if( sqlite3FaultSim(412) ) pPage->isInit = 0;
76416
+ if( !pPage->isInit ){
76417
+ return SQLITE_CORRUPT_BKPT;
76418
+ }
7607276419
if( !pPage->leaf ){
7607376420
int idx = pCur->ix;
7607476421
rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
7607576422
if( rc ) return rc;
7607676423
rc = moveToRightmost(pCur);
@@ -85370,10 +85717,14 @@
8537085717
}
8537185718
case P4_VTAB : {
8537285719
if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
8537385720
break;
8537485721
}
85722
+ case P4_TABLEREF: {
85723
+ if( db->pnBytesFreed==0 ) sqlite3DeleteTable(db, (Table*)p4);
85724
+ break;
85725
+ }
8537585726
}
8537685727
}
8537785728
8537885729
/*
8537985730
** Free the space allocated for aOp and any p4 values allocated for the
@@ -85497,11 +85848,11 @@
8549785848
Op *pOp,
8549885849
const char *zP4,
8549985850
int n
8550085851
){
8550185852
if( pOp->p4type ){
85502
- freeP4(p->db, pOp->p4type, pOp->p4.p);
85853
+ assert( pOp->p4type > P4_FREE_IF_LE );
8550385854
pOp->p4type = 0;
8550485855
pOp->p4.p = 0;
8550585856
}
8550685857
if( n<0 ){
8550785858
sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
@@ -89620,11 +89971,19 @@
8962089971
SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
8962189972
int i;
8962289973
int rc = SQLITE_OK;
8962389974
Vdbe *p = (Vdbe*)pStmt;
8962489975
#if SQLITE_THREADSAFE
89625
- sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
89976
+ sqlite3_mutex *mutex;
89977
+#endif
89978
+#ifdef SQLITE_ENABLE_API_ARMOR
89979
+ if( pStmt==0 ){
89980
+ return SQLITE_MISUSE_BKPT;
89981
+ }
89982
+#endif
89983
+#if SQLITE_THREADSAFE
89984
+ mutex = p->db->mutex;
8962689985
#endif
8962789986
sqlite3_mutex_enter(mutex);
8962889987
for(i=0; i<p->nVar; i++){
8962989988
sqlite3VdbeMemRelease(&p->aVar[i]);
8963089989
p->aVar[i].flags = MEM_Null;
@@ -90410,13 +90769,12 @@
9041090769
** pointer to it.
9041190770
*/
9041290771
SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
9041390772
#ifdef SQLITE_ENABLE_API_ARMOR
9041490773
if( p==0 ) return 0;
90415
-#else
90774
+#endif
9041690775
assert( p && p->pFunc );
90417
-#endif
9041890776
return p->pFunc->pUserData;
9041990777
}
9042090778
9042190779
/*
9042290780
** Extract the user data from a sqlite3_context structure and return a
@@ -94231,11 +94589,11 @@
9423194589
*/
9423294590
case OP_AddImm: { /* in1 */
9423394591
pIn1 = &aMem[pOp->p1];
9423494592
memAboutToChange(p, pIn1);
9423594593
sqlite3VdbeMemIntegerify(pIn1);
94236
- pIn1->u.i += pOp->p2;
94594
+ *(u64*)&pIn1->u.i += (u64)pOp->p2;
9423794595
break;
9423894596
}
9423994597
9424094598
/* Opcode: MustBeInt P1 P2 * * *
9424194599
**
@@ -100377,28 +100735,27 @@
100377100735
const sqlite3_module *pModule;
100378100736
char *zErr = 0;
100379100737
100380100738
pOut = &aMem[pOp->p2];
100381100739
sqlite3VdbeMemSetNull(pOut); /* Innocent until proven guilty */
100382
- assert( pOp->p4type==P4_TABLE );
100740
+ assert( pOp->p4type==P4_TABLEREF );
100383100741
pTab = pOp->p4.pTab;
100384100742
assert( pTab!=0 );
100743
+ assert( pTab->nTabRef>0 );
100385100744
assert( IsVirtual(pTab) );
100386100745
if( pTab->u.vtab.p==0 ) break;
100387100746
pVtab = pTab->u.vtab.p->pVtab;
100388100747
assert( pVtab!=0 );
100389100748
pModule = pVtab->pModule;
100390100749
assert( pModule!=0 );
100391100750
assert( pModule->iVersion>=4 );
100392100751
assert( pModule->xIntegrity!=0 );
100393
- pTab->nTabRef++;
100394100752
sqlite3VtabLock(pTab->u.vtab.p);
100395100753
assert( pOp->p1>=0 && pOp->p1<db->nDb );
100396100754
rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
100397100755
pOp->p3, &zErr);
100398100756
sqlite3VtabUnlock(pTab->u.vtab.p);
100399
- sqlite3DeleteTable(db, pTab);
100400100757
if( rc ){
100401100758
sqlite3_free(zErr);
100402100759
goto abort_due_to_error;
100403100760
}
100404100761
if( zErr ){
@@ -100519,10 +100876,11 @@
100519100876
case OP_VColumn: { /* ncycle */
100520100877
sqlite3_vtab *pVtab;
100521100878
const sqlite3_module *pModule;
100522100879
Mem *pDest;
100523100880
sqlite3_context sContext;
100881
+ FuncDef nullFunc;
100524100882
100525100883
VdbeCursor *pCur = p->apCsr[pOp->p1];
100526100884
assert( pCur!=0 );
100527100885
assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
100528100886
pDest = &aMem[pOp->p3];
@@ -100536,10 +100894,13 @@
100536100894
pModule = pVtab->pModule;
100537100895
assert( pModule->xColumn );
100538100896
memset(&sContext, 0, sizeof(sContext));
100539100897
sContext.pOut = pDest;
100540100898
sContext.enc = encoding;
100899
+ nullFunc.pUserData = 0;
100900
+ nullFunc.funcFlags = SQLITE_RESULT_SUBTYPE;
100901
+ sContext.pFunc = &nullFunc;
100541100902
assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
100542100903
if( pOp->p5 & OPFLAG_NOCHNG ){
100543100904
sqlite3VdbeMemSetNull(pDest);
100544100905
pDest->flags = MEM_Null|MEM_Zero;
100545100906
pDest->u.nZero = 0;
@@ -100867,10 +101228,46 @@
100867101228
case OP_ClrSubtype: { /* in1 */
100868101229
pIn1 = &aMem[pOp->p1];
100869101230
pIn1->flags &= ~MEM_Subtype;
100870101231
break;
100871101232
}
101233
+
101234
+/* Opcode: GetSubtype P1 P2 * * *
101235
+** Synopsis: r[P2] = r[P1].subtype
101236
+**
101237
+** Extract the subtype value from register P1 and write that subtype
101238
+** into register P2. If P1 has no subtype, then P1 gets a NULL.
101239
+*/
101240
+case OP_GetSubtype: { /* in1 out2 */
101241
+ pIn1 = &aMem[pOp->p1];
101242
+ pOut = &aMem[pOp->p2];
101243
+ if( pIn1->flags & MEM_Subtype ){
101244
+ sqlite3VdbeMemSetInt64(pOut, pIn1->eSubtype);
101245
+ }else{
101246
+ sqlite3VdbeMemSetNull(pOut);
101247
+ }
101248
+ break;
101249
+}
101250
+
101251
+/* Opcode: SetSubtype P1 P2 * * *
101252
+** Synopsis: r[P2].subtype = r[P1]
101253
+**
101254
+** Set the subtype value of register P2 to the integer from register P1.
101255
+** If P1 is NULL, clear the subtype from p2.
101256
+*/
101257
+case OP_SetSubtype: { /* in1 out2 */
101258
+ pIn1 = &aMem[pOp->p1];
101259
+ pOut = &aMem[pOp->p2];
101260
+ if( pIn1->flags & MEM_Null ){
101261
+ pOut->flags &= ~MEM_Subtype;
101262
+ }else{
101263
+ assert( pIn1->flags & MEM_Int );
101264
+ pOut->flags |= MEM_Subtype;
101265
+ pOut->eSubtype = (u8)(pIn1->u.i & 0xff);
101266
+ }
101267
+ break;
101268
+}
100872101269
100873101270
/* Opcode: FilterAdd P1 * P3 P4 *
100874101271
** Synopsis: filter(P1) += key(P3@P4)
100875101272
**
100876101273
** Compute a hash on the P4 registers starting with r[P3] and
@@ -105916,10 +106313,11 @@
105916106313
105917106314
n = pExpr->iColumn;
105918106315
assert( ExprUseYTab(pExpr) );
105919106316
pExTab = pExpr->y.pTab;
105920106317
assert( pExTab!=0 );
106318
+ assert( n < pExTab->nCol );
105921106319
if( (pExTab->tabFlags & TF_HasGenerated)!=0
105922106320
&& (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
105923106321
){
105924106322
testcase( pExTab->nCol==BMS-1 );
105925106323
testcase( pExTab->nCol==BMS );
@@ -106492,10 +106890,11 @@
106492106890
sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
106493106891
}
106494106892
sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
106495106893
pParse->checkSchema = 1;
106496106894
pTopNC->nNcErr++;
106895
+ eNewExprOp = TK_NULL;
106497106896
}
106498106897
assert( pFJMatch==0 );
106499106898
106500106899
/* Remove all substructure from pExpr */
106501106900
if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
@@ -106518,11 +106917,11 @@
106518106917
** (See ticket [b92e5e8ec2cdbaa1]).
106519106918
**
106520106919
** If a generated column is referenced, set bits for every column
106521106920
** of the table.
106522106921
*/
106523
- if( pExpr->iColumn>=0 && pMatch!=0 ){
106922
+ if( pExpr->iColumn>=0 && cnt==1 && pMatch!=0 ){
106524106923
pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
106525106924
}
106526106925
106527106926
pExpr->op = eNewExprOp;
106528106927
lookupname_end:
@@ -106983,15 +107382,16 @@
106983107382
#endif
106984107383
pNC2 = pNC;
106985107384
while( pNC2
106986107385
&& sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
106987107386
){
106988
- pExpr->op2++;
107387
+ pExpr->op2 += (1 + pNC2->nNestedSelect);
106989107388
pNC2 = pNC2->pNext;
106990107389
}
106991107390
assert( pDef!=0 || IN_RENAME_OBJECT );
106992107391
if( pNC2 && pDef ){
107392
+ pExpr->op2 += pNC2->nNestedSelect;
106993107393
assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
106994107394
assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
106995107395
testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
106996107396
testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
106997107397
pNC2->ncFlags |= NC_HasAgg
@@ -107546,10 +107946,11 @@
107546107946
p->pOrderBy = 0;
107547107947
}
107548107948
107549107949
/* Recursively resolve names in all subqueries in the FROM clause
107550107950
*/
107951
+ if( pOuterNC ) pOuterNC->nNestedSelect++;
107551107952
for(i=0; i<p->pSrc->nSrc; i++){
107552107953
SrcItem *pItem = &p->pSrc->a[i];
107553107954
if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
107554107955
int nRef = pOuterNC ? pOuterNC->nRef : 0;
107555107956
const char *zSavedContext = pParse->zAuthContext;
@@ -107569,10 +107970,13 @@
107569107970
if( pOuterNC ){
107570107971
assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
107571107972
pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
107572107973
}
107573107974
}
107975
+ }
107976
+ if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
107977
+ pOuterNC->nNestedSelect--;
107574107978
}
107575107979
107576107980
/* Set up the local name-context to pass to sqlite3ResolveExprNames() to
107577107981
** resolve the result-set expression list.
107578107982
*/
@@ -109157,13 +109561,11 @@
109157109561
assert( pExpr->op==TK_FUNCTION );
109158109562
assert( pExpr->pLeft==0 );
109159109563
assert( ExprUseXList(pExpr) );
109160109564
if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
109161109565
/* Ignore ORDER BY on zero-argument aggregates */
109162
- sqlite3ParserAddCleanup(pParse,
109163
- (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
109164
- pOrderBy);
109566
+ sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy);
109165109567
return;
109166109568
}
109167109569
if( IsWindowFunc(pExpr) ){
109168109570
sqlite3ExprOrderByAggregateError(pParse, pExpr);
109169109571
sqlite3ExprListDelete(db, pOrderBy);
@@ -109340,10 +109742,13 @@
109340109742
}
109341109743
}
109342109744
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
109343109745
if( p ) sqlite3ExprDeleteNN(db, p);
109344109746
}
109747
+SQLITE_PRIVATE void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){
109748
+ if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p);
109749
+}
109345109750
109346109751
/*
109347109752
** Clear both elements of an OnOrUsing object
109348109753
*/
109349109754
SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
@@ -109365,13 +109770,11 @@
109365109770
**
109366109771
** The deferred delete is (currently) implemented by adding the
109367109772
** pExpr to the pParse->pConstExpr list with a register number of 0.
109368109773
*/
109369109774
SQLITE_PRIVATE void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
109370
- sqlite3ParserAddCleanup(pParse,
109371
- (void(*)(sqlite3*,void*))sqlite3ExprDelete,
109372
- pExpr);
109775
+ sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
109373109776
}
109374109777
109375109778
/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
109376109779
** expression.
109377109780
*/
@@ -110173,10 +110576,13 @@
110173110576
sqlite3DbNNFreeNN(db, pList);
110174110577
}
110175110578
SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
110176110579
if( pList ) exprListDeleteNN(db, pList);
110177110580
}
110581
+SQLITE_PRIVATE void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){
110582
+ if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList);
110583
+}
110178110584
110179110585
/*
110180110586
** Return the bitwise-OR of all Expr.flags fields in the given
110181110587
** ExprList.
110182110588
*/
@@ -110672,13 +111078,14 @@
110672111078
case TK_BLOB:
110673111079
return 0;
110674111080
case TK_COLUMN:
110675111081
assert( ExprUseYTab(p) );
110676111082
return ExprHasProperty(p, EP_CanBeNull) ||
110677
- p->y.pTab==0 || /* Reference to column of index on expression */
111083
+ NEVER(p->y.pTab==0) || /* Reference to column of index on expr */
110678111084
(p->iColumn>=0
110679111085
&& p->y.pTab->aCol!=0 /* Possible due to prior error */
111086
+ && ALWAYS(p->iColumn<p->y.pTab->nCol)
110680111087
&& p->y.pTab->aCol[p->iColumn].notNull==0);
110681111088
default:
110682111089
return 1;
110683111090
}
110684111091
}
@@ -113256,12 +113663,14 @@
113256113663
assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
113257113664
if( pParse->pVdbe==0 ) return;
113258113665
inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
113259113666
if( inReg!=target ){
113260113667
u8 op;
113261
- if( ALWAYS(pExpr)
113262
- && (ExprHasProperty(pExpr,EP_Subquery) || pExpr->op==TK_REGISTER)
113668
+ Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr);
113669
+ testcase( pX!=pExpr );
113670
+ if( ALWAYS(pX)
113671
+ && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER)
113263113672
){
113264113673
op = OP_Copy;
113265113674
}else{
113266113675
op = OP_SCopy;
113267113676
}
@@ -114703,17 +115112,18 @@
114703115112
return WRC_Continue;
114704115113
}
114705115114
case TK_AGG_FUNCTION: {
114706115115
if( (pNC->ncFlags & NC_InAggFunc)==0
114707115116
&& pWalker->walkerDepth==pExpr->op2
115117
+ && pExpr->pAggInfo==0
114708115118
){
114709115119
/* Check to see if pExpr is a duplicate of another aggregate
114710115120
** function that is already in the pAggInfo structure
114711115121
*/
114712115122
struct AggInfo_func *pItem = pAggInfo->aFunc;
114713115123
for(i=0; i<pAggInfo->nFunc; i++, pItem++){
114714
- if( pItem->pFExpr==pExpr ) break;
115124
+ if( NEVER(pItem->pFExpr==pExpr) ) break;
114715115125
if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
114716115126
break;
114717115127
}
114718115128
}
114719115129
if( i>=pAggInfo->nFunc ){
@@ -114752,10 +115162,12 @@
114752115162
pItem->bOBPayload = 0;
114753115163
pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
114754115164
}else{
114755115165
pItem->bOBPayload = 1;
114756115166
}
115167
+ pItem->bUseSubtype =
115168
+ (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0;
114757115169
}else{
114758115170
pItem->iOBTab = -1;
114759115171
}
114760115172
if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
114761115173
pItem->iDistinct = pParse->nTab++;
@@ -117518,13 +117930,13 @@
117518117930
** information.
117519117931
*/
117520117932
typedef struct StatAccum StatAccum;
117521117933
typedef struct StatSample StatSample;
117522117934
struct StatSample {
117523
- tRowcnt *anEq; /* sqlite_stat4.nEq */
117524117935
tRowcnt *anDLt; /* sqlite_stat4.nDLt */
117525117936
#ifdef SQLITE_ENABLE_STAT4
117937
+ tRowcnt *anEq; /* sqlite_stat4.nEq */
117526117938
tRowcnt *anLt; /* sqlite_stat4.nLt */
117527117939
union {
117528117940
i64 iRowid; /* Rowid in main table of the key */
117529117941
u8 *aRowid; /* Key for WITHOUT ROWID tables */
117530117942
} u;
@@ -117678,13 +118090,13 @@
117678118090
assert( nKeyCol<=nCol );
117679118091
assert( nKeyCol>0 );
117680118092
117681118093
/* Allocate the space required for the StatAccum object */
117682118094
n = sizeof(*p)
117683
- + sizeof(tRowcnt)*nColUp /* StatAccum.anEq */
117684
- + sizeof(tRowcnt)*nColUp; /* StatAccum.anDLt */
118095
+ + sizeof(tRowcnt)*nColUp; /* StatAccum.anDLt */
117685118096
#ifdef SQLITE_ENABLE_STAT4
118097
+ n += sizeof(tRowcnt)*nColUp; /* StatAccum.anEq */
117686118098
if( mxSample ){
117687118099
n += sizeof(tRowcnt)*nColUp /* StatAccum.anLt */
117688118100
+ sizeof(StatSample)*(nCol+mxSample) /* StatAccum.aBest[], a[] */
117689118101
+ sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
117690118102
}
@@ -117701,13 +118113,13 @@
117701118113
p->nLimit = sqlite3_value_int64(argv[3]);
117702118114
p->nCol = nCol;
117703118115
p->nKeyCol = nKeyCol;
117704118116
p->nSkipAhead = 0;
117705118117
p->current.anDLt = (tRowcnt*)&p[1];
117706
- p->current.anEq = &p->current.anDLt[nColUp];
117707118118
117708118119
#ifdef SQLITE_ENABLE_STAT4
118120
+ p->current.anEq = &p->current.anDLt[nColUp];
117709118121
p->mxSample = p->nLimit==0 ? mxSample : 0;
117710118122
if( mxSample ){
117711118123
u8 *pSpace; /* Allocated space not yet assigned */
117712118124
int i; /* Used to iterate through p->aSample[] */
117713118125
@@ -117970,28 +118382,32 @@
117970118382
assert( p->nCol>0 );
117971118383
assert( iChng<p->nCol );
117972118384
117973118385
if( p->nRow==0 ){
117974118386
/* This is the first call to this function. Do initialization. */
118387
+#ifdef SQLITE_ENABLE_STAT4
117975118388
for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
118389
+#endif
117976118390
}else{
117977118391
/* Second and subsequent calls get processed here */
117978118392
#ifdef SQLITE_ENABLE_STAT4
117979118393
if( p->mxSample ) samplePushPrevious(p, iChng);
117980118394
#endif
117981118395
117982118396
/* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
117983118397
** to the current row of the index. */
118398
+#ifdef SQLITE_ENABLE_STAT4
117984118399
for(i=0; i<iChng; i++){
117985118400
p->current.anEq[i]++;
117986118401
}
118402
+#endif
117987118403
for(i=iChng; i<p->nCol; i++){
117988118404
p->current.anDLt[i]++;
117989118405
#ifdef SQLITE_ENABLE_STAT4
117990118406
if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
117991
-#endif
117992118407
p->current.anEq[i] = 1;
118408
+#endif
117993118409
}
117994118410
}
117995118411
117996118412
p->nRow++;
117997118413
#ifdef SQLITE_ENABLE_STAT4
@@ -118121,11 +118537,13 @@
118121118537
for(i=0; i<p->nKeyCol; i++){
118122118538
u64 nDistinct = p->current.anDLt[i] + 1;
118123118539
u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
118124118540
if( iVal==2 && p->nRow*10 <= nDistinct*11 ) iVal = 1;
118125118541
sqlite3_str_appendf(&sStat, " %llu", iVal);
118542
+#ifdef SQLITE_ENABLE_STAT4
118126118543
assert( p->current.anEq[i] );
118544
+#endif
118127118545
}
118128118546
sqlite3ResultStrAccum(context, &sStat);
118129118547
}
118130118548
#ifdef SQLITE_ENABLE_STAT4
118131118549
else if( eCall==STAT_GET_ROWID ){
@@ -118810,10 +119228,20 @@
118810119228
}
118811119229
#endif
118812119230
while( z[0]!=0 && z[0]!=' ' ) z++;
118813119231
while( z[0]==' ' ) z++;
118814119232
}
119233
+
119234
+ /* Set the bLowQual flag if the peak number of rows obtained
119235
+ ** from a full equality match is so large that a full table scan
119236
+ ** seems likely to be faster than using the index.
119237
+ */
119238
+ if( aLog[0] > 66 /* Index has more than 100 rows */
119239
+ && aLog[0] <= aLog[nOut-1] /* And only a single value seen */
119240
+ ){
119241
+ pIndex->bLowQual = 1;
119242
+ }
118815119243
}
118816119244
}
118817119245
118818119246
/*
118819119247
** This callback is invoked once for each index when reading the
@@ -120856,11 +121284,11 @@
120856121284
** the DEFAULT clause or the AS clause of a generated column.
120857121285
** Return NULL if the column has no associated expression.
120858121286
*/
120859121287
SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
120860121288
if( pCol->iDflt==0 ) return 0;
120861
- if( NEVER(!IsOrdinaryTable(pTab)) ) return 0;
121289
+ if( !IsOrdinaryTable(pTab) ) return 0;
120862121290
if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
120863121291
if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
120864121292
return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
120865121293
}
120866121294
@@ -121008,10 +121436,13 @@
121008121436
/* Do not delete the table until the reference count reaches zero. */
121009121437
assert( db!=0 );
121010121438
if( !pTable ) return;
121011121439
if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
121012121440
deleteTable(db, pTable);
121441
+}
121442
+SQLITE_PRIVATE void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){
121443
+ sqlite3DeleteTable(db, (Table*)pTable);
121013121444
}
121014121445
121015121446
121016121447
/*
121017121448
** Unlink the given table from the hash tables and the delete the
@@ -121546,11 +121977,12 @@
121546121977
#endif
121547121978
121548121979
/*
121549121980
** Clean up the data structures associated with the RETURNING clause.
121550121981
*/
121551
-static void sqlite3DeleteReturning(sqlite3 *db, Returning *pRet){
121982
+static void sqlite3DeleteReturning(sqlite3 *db, void *pArg){
121983
+ Returning *pRet = (Returning*)pArg;
121552121984
Hash *pHash;
121553121985
pHash = &(db->aDb[1].pSchema->trigHash);
121554121986
sqlite3HashInsert(pHash, pRet->zName, 0);
121555121987
sqlite3ExprListDelete(db, pRet->pReturnEL);
121556121988
sqlite3DbFree(db, pRet);
@@ -121588,12 +122020,11 @@
121588122020
return;
121589122021
}
121590122022
pParse->u1.pReturning = pRet;
121591122023
pRet->pParse = pParse;
121592122024
pRet->pReturnEL = pList;
121593
- sqlite3ParserAddCleanup(pParse,
121594
- (void(*)(sqlite3*,void*))sqlite3DeleteReturning, pRet);
122025
+ sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);
121595122026
testcase( pParse->earlyCleanup );
121596122027
if( db->mallocFailed ) return;
121597122028
sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
121598122029
"sqlite_returning_%p", pParse);
121599122030
pRet->retTrig.zName = pRet->zName;
@@ -121788,11 +122219,12 @@
121788122219
char aff = SQLITE_AFF_NUMERIC;
121789122220
const char *zChar = 0;
121790122221
121791122222
assert( zIn!=0 );
121792122223
while( zIn[0] ){
121793
- h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
122224
+ u8 x = *(u8*)zIn;
122225
+ h = (h<<8) + sqlite3UpperToLower[x];
121794122226
zIn++;
121795122227
if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
121796122228
aff = SQLITE_AFF_TEXT;
121797122229
zChar = zIn;
121798122230
}else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
@@ -125653,20 +126085,21 @@
125653126085
}
125654126086
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
125655126087
if( iDb<0 ) return;
125656126088
z = sqlite3NameFromToken(db, pObjName);
125657126089
if( z==0 ) return;
125658
- zDb = db->aDb[iDb].zDbSName;
126090
+ zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
125659126091
pTab = sqlite3FindTable(db, z, zDb);
125660126092
if( pTab ){
125661126093
reindexTable(pParse, pTab, 0);
125662126094
sqlite3DbFree(db, z);
125663126095
return;
125664126096
}
125665126097
pIndex = sqlite3FindIndex(db, z, zDb);
125666126098
sqlite3DbFree(db, z);
125667126099
if( pIndex ){
126100
+ iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema);
125668126101
sqlite3BeginWriteOperation(pParse, 0, iDb);
125669126102
sqlite3RefillIndex(pParse, pIndex, -1);
125670126103
return;
125671126104
}
125672126105
sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
@@ -125827,10 +126260,13 @@
125827126260
for(i=0; i<pWith->nCte; i++){
125828126261
cteClear(db, &pWith->a[i]);
125829126262
}
125830126263
sqlite3DbFree(db, pWith);
125831126264
}
126265
+}
126266
+SQLITE_PRIVATE void sqlite3WithDeleteGeneric(sqlite3 *db, void *pWith){
126267
+ sqlite3WithDelete(db, (With*)pWith);
125832126268
}
125833126269
#endif /* !defined(SQLITE_OMIT_CTE) */
125834126270
125835126271
/************** End of build.c ***********************************************/
125836126272
/************** Begin file callback.c ****************************************/
@@ -139053,11 +139489,12 @@
139053139489
if( NEVER(pVTab==0) ) continue;
139054139490
if( NEVER(pVTab->pModule==0) ) continue;
139055139491
if( pVTab->pModule->iVersion<4 ) continue;
139056139492
if( pVTab->pModule->xIntegrity==0 ) continue;
139057139493
sqlite3VdbeAddOp3(v, OP_VCheck, i, 3, isQuick);
139058
- sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
139494
+ pTab->nTabRef++;
139495
+ sqlite3VdbeAppendP4(v, pTab, P4_TABLEREF);
139059139496
a1 = sqlite3VdbeAddOp1(v, OP_IsNull, 3); VdbeCoverage(v);
139060139497
integrityCheckResultRow(v);
139061139498
sqlite3VdbeJumpHere(v, a1);
139062139499
#endif
139063139500
continue;
@@ -141080,10 +141517,11 @@
141080141517
sqlite3BtreeLeaveAll(db);
141081141518
rc = sqlite3ApiExit(db, rc);
141082141519
assert( (rc&db->errMask)==rc );
141083141520
db->busyHandler.nBusy = 0;
141084141521
sqlite3_mutex_leave(db->mutex);
141522
+ assert( rc==SQLITE_OK || (*ppStmt)==0 );
141085141523
return rc;
141086141524
}
141087141525
141088141526
141089141527
/*
@@ -141476,10 +141914,13 @@
141476141914
/*
141477141915
** Delete the given Select structure and all of its substructures.
141478141916
*/
141479141917
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
141480141918
if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
141919
+}
141920
+SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3 *db, void *p){
141921
+ if( ALWAYS(p) ) clearSelect(db, (Select*)p, 1);
141481141922
}
141482141923
141483141924
/*
141484141925
** Return a pointer to the right-most SELECT statement in a compound.
141485141926
*/
@@ -144497,13 +144938,11 @@
144497144938
144498144939
multi_select_end:
144499144940
pDest->iSdst = dest.iSdst;
144500144941
pDest->nSdst = dest.nSdst;
144501144942
if( pDelete ){
144502
- sqlite3ParserAddCleanup(pParse,
144503
- (void(*)(sqlite3*,void*))sqlite3SelectDelete,
144504
- pDelete);
144943
+ sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pDelete);
144505144944
}
144506144945
return rc;
144507144946
}
144508144947
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
144509144948
@@ -145050,12 +145489,11 @@
145050145489
sqlite3VdbeResolveLabel(v, labelEnd);
145051145490
145052145491
/* Make arrangements to free the 2nd and subsequent arms of the compound
145053145492
** after the parse has finished */
145054145493
if( pSplit->pPrior ){
145055
- sqlite3ParserAddCleanup(pParse,
145056
- (void(*)(sqlite3*,void*))sqlite3SelectDelete, pSplit->pPrior);
145494
+ sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSplit->pPrior);
145057145495
}
145058145496
pSplit->pPrior = pPrior;
145059145497
pPrior->pNext = pSplit;
145060145498
sqlite3ExprListDelete(db, pPrior->pOrderBy);
145061145499
pPrior->pOrderBy = 0;
@@ -145872,13 +146310,11 @@
145872146310
*/
145873146311
if( ALWAYS(pSubitem->pTab!=0) ){
145874146312
Table *pTabToDel = pSubitem->pTab;
145875146313
if( pTabToDel->nTabRef==1 ){
145876146314
Parse *pToplevel = sqlite3ParseToplevel(pParse);
145877
- sqlite3ParserAddCleanup(pToplevel,
145878
- (void(*)(sqlite3*,void*))sqlite3DeleteTable,
145879
- pTabToDel);
146315
+ sqlite3ParserAddCleanup(pToplevel, sqlite3DeleteTableGeneric, pTabToDel);
145880146316
testcase( pToplevel->earlyCleanup );
145881146317
}else{
145882146318
pTabToDel->nTabRef--;
145883146319
}
145884146320
pSubitem->pTab = 0;
@@ -146921,12 +147357,11 @@
146921147357
** calling this routine, Instead, use only the return value.
146922147358
*/
146923147359
SQLITE_PRIVATE With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
146924147360
if( pWith ){
146925147361
if( bFree ){
146926
- pWith = (With*)sqlite3ParserAddCleanup(pParse,
146927
- (void(*)(sqlite3*,void*))sqlite3WithDelete,
147362
+ pWith = (With*)sqlite3ParserAddCleanup(pParse, sqlite3WithDeleteGeneric,
146928147363
pWith);
146929147364
if( pWith==0 ) return 0;
146930147365
}
146931147366
if( pParse->nErr==0 ){
146932147367
assert( pParse->pWith!=pWith );
@@ -147955,19 +148390,23 @@
147955148390
KeyInfo *pKeyInfo;
147956148391
int nExtra = 0;
147957148392
assert( pFunc->pFExpr->pLeft!=0 );
147958148393
assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
147959148394
assert( ExprUseXList(pFunc->pFExpr->pLeft) );
148395
+ assert( pFunc->pFunc!=0 );
147960148396
pOBList = pFunc->pFExpr->pLeft->x.pList;
147961148397
if( !pFunc->bOBUnique ){
147962148398
nExtra++; /* One extra column for the OP_Sequence */
147963148399
}
147964148400
if( pFunc->bOBPayload ){
147965148401
/* extra columns for the function arguments */
147966148402
assert( ExprUseXList(pFunc->pFExpr) );
147967148403
nExtra += pFunc->pFExpr->x.pList->nExpr;
147968148404
}
148405
+ if( pFunc->bUseSubtype ){
148406
+ nExtra += pFunc->pFExpr->x.pList->nExpr;
148407
+ }
147969148408
pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOBList, 0, nExtra);
147970148409
if( !pFunc->bOBUnique && pParse->nErr==0 ){
147971148410
pKeyInfo->nKeyField++;
147972148411
}
147973148412
sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
@@ -147990,20 +148429,21 @@
147990148429
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
147991148430
ExprList *pList;
147992148431
assert( ExprUseXList(pF->pFExpr) );
147993148432
pList = pF->pFExpr->x.pList;
147994148433
if( pF->iOBTab>=0 ){
147995
- /* For an ORDER BY aggregate, calls to OP_AggStep where deferred and
147996
- ** all content was stored in emphermal table pF->iOBTab. Extract that
147997
- ** content now (in ORDER BY order) and make all calls to OP_AggStep
148434
+ /* For an ORDER BY aggregate, calls to OP_AggStep were deferred. Inputs
148435
+ ** were stored in emphermal table pF->iOBTab. Here, we extract those
148436
+ ** inputs (in ORDER BY order) and make all calls to OP_AggStep
147998148437
** before doing the OP_AggFinal call. */
147999148438
int iTop; /* Start of loop for extracting columns */
148000148439
int nArg; /* Number of columns to extract */
148001148440
int nKey; /* Key columns to be skipped */
148002148441
int regAgg; /* Extract into this array */
148003148442
int j; /* Loop counter */
148004148443
148444
+ assert( pF->pFunc!=0 );
148005148445
nArg = pList->nExpr;
148006148446
regAgg = sqlite3GetTempRange(pParse, nArg);
148007148447
148008148448
if( pF->bOBPayload==0 ){
148009148449
nKey = 0;
@@ -148016,10 +148456,19 @@
148016148456
}
148017148457
iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
148018148458
for(j=nArg-1; j>=0; j--){
148019148459
sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
148020148460
}
148461
+ if( pF->bUseSubtype ){
148462
+ int regSubtype = sqlite3GetTempReg(pParse);
148463
+ int iBaseCol = nKey + nArg + (pF->bOBPayload==0 && pF->bOBUnique==0);
148464
+ for(j=nArg-1; j>=0; j--){
148465
+ sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, iBaseCol+j, regSubtype);
148466
+ sqlite3VdbeAddOp2(v, OP_SetSubtype, regSubtype, regAgg+j);
148467
+ }
148468
+ sqlite3ReleaseTempReg(pParse, regSubtype);
148469
+ }
148021148470
sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
148022148471
sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
148023148472
sqlite3VdbeChangeP5(v, (u8)nArg);
148024148473
sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
148025148474
sqlite3VdbeJumpHere(v, iTop);
@@ -148070,10 +148519,11 @@
148070148519
int regAggSz = 0;
148071148520
int regDistinct = 0;
148072148521
ExprList *pList;
148073148522
assert( ExprUseXList(pF->pFExpr) );
148074148523
assert( !IsWindowFunc(pF->pFExpr) );
148524
+ assert( pF->pFunc!=0 );
148075148525
pList = pF->pFExpr->x.pList;
148076148526
if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
148077148527
Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
148078148528
if( pAggInfo->nAccumulator
148079148529
&& (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
@@ -148113,10 +148563,13 @@
148113148563
if( !pF->bOBUnique ){
148114148564
regAggSz++; /* One register for OP_Sequence */
148115148565
}
148116148566
if( pF->bOBPayload ){
148117148567
regAggSz += nArg;
148568
+ }
148569
+ if( pF->bUseSubtype ){
148570
+ regAggSz += nArg;
148118148571
}
148119148572
regAggSz++; /* One extra register to hold result of MakeRecord */
148120148573
regAgg = sqlite3GetTempRange(pParse, regAggSz);
148121148574
regDistinct = regAgg;
148122148575
sqlite3ExprCodeExprList(pParse, pOBList, regAgg, 0, SQLITE_ECEL_DUP);
@@ -148126,10 +148579,18 @@
148126148579
jj++;
148127148580
}
148128148581
if( pF->bOBPayload ){
148129148582
regDistinct = regAgg+jj;
148130148583
sqlite3ExprCodeExprList(pParse, pList, regDistinct, 0, SQLITE_ECEL_DUP);
148584
+ jj += nArg;
148585
+ }
148586
+ if( pF->bUseSubtype ){
148587
+ int kk;
148588
+ int regBase = pF->bOBPayload ? regDistinct : regAgg;
148589
+ for(kk=0; kk<nArg; kk++, jj++){
148590
+ sqlite3VdbeAddOp2(v, OP_GetSubtype, regBase+kk, regAgg+jj);
148591
+ }
148131148592
}
148132148593
}else if( pList ){
148133148594
nArg = pList->nExpr;
148134148595
regAgg = sqlite3GetTempRange(pParse, nArg);
148135148596
regDistinct = regAgg;
@@ -148330,11 +148791,12 @@
148330148791
}
148331148792
148332148793
/*
148333148794
** Deallocate a single AggInfo object
148334148795
*/
148335
-static void agginfoFree(sqlite3 *db, AggInfo *p){
148796
+static void agginfoFree(sqlite3 *db, void *pArg){
148797
+ AggInfo *p = (AggInfo*)pArg;
148336148798
sqlite3DbFree(db, p->aCol);
148337148799
sqlite3DbFree(db, p->aFunc);
148338148800
sqlite3DbFreeNN(db, p);
148339148801
}
148340148802
@@ -148404,11 +148866,11 @@
148404148866
pSub->pPrior = 0;
148405148867
pSub->pNext = 0;
148406148868
pSub->selFlags |= SF_Aggregate;
148407148869
pSub->selFlags &= ~SF_Compound;
148408148870
pSub->nSelectRow = 0;
148409
- sqlite3ExprListDelete(db, pSub->pEList);
148871
+ sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList);
148410148872
pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
148411148873
pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
148412148874
pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
148413148875
sqlite3PExprAddSelect(pParse, pTerm, pSub);
148414148876
if( pExpr==0 ){
@@ -148584,13 +149046,12 @@
148584149046
TREETRACE(0x800,pParse,p, ("dropping superfluous ORDER BY:\n"));
148585149047
if( sqlite3TreeTrace & 0x800 ){
148586149048
sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
148587149049
}
148588149050
#endif
148589
- sqlite3ParserAddCleanup(pParse,
148590
- (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
148591
- p->pOrderBy);
149051
+ sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
149052
+ p->pOrderBy);
148592149053
testcase( pParse->earlyCleanup );
148593149054
p->pOrderBy = 0;
148594149055
}
148595149056
p->selFlags &= ~SF_Distinct;
148596149057
p->selFlags |= SF_NoopOrderBy;
@@ -148778,13 +149239,12 @@
148778149239
&& (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
148779149240
&& OptimizationEnabled(db, SQLITE_OmitOrderBy)
148780149241
){
148781149242
TREETRACE(0x800,pParse,p,
148782149243
("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
148783
- sqlite3ParserAddCleanup(pParse,
148784
- (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
148785
- pSub->pOrderBy);
149244
+ sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
149245
+ pSub->pOrderBy);
148786149246
pSub->pOrderBy = 0;
148787149247
}
148788149248
148789149249
/* If the outer query contains a "complex" result set (that is,
148790149250
** if the result set of the outer query uses functions or subqueries)
@@ -149309,12 +149769,11 @@
149309149769
** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
149310149770
** SELECT statement.
149311149771
*/
149312149772
pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
149313149773
if( pAggInfo ){
149314
- sqlite3ParserAddCleanup(pParse,
149315
- (void(*)(sqlite3*,void*))agginfoFree, pAggInfo);
149774
+ sqlite3ParserAddCleanup(pParse, agginfoFree, pAggInfo);
149316149775
testcase( pParse->earlyCleanup );
149317149776
}
149318149777
if( db->mallocFailed ){
149319149778
goto select_end;
149320149779
}
@@ -153959,11 +154418,10 @@
153959154418
assert( sqlite3BtreeHoldsAllMutexes(db) );
153960154419
assert( sqlite3_mutex_held(db->mutex) );
153961154420
153962154421
if( p ){
153963154422
db->pDisconnect = 0;
153964
- sqlite3ExpirePreparedStatements(db, 0);
153965154423
do {
153966154424
VTable *pNext = p->pNext;
153967154425
sqlite3VtabUnlock(p);
153968154426
p = pNext;
153969154427
}while( p );
@@ -155525,11 +155983,11 @@
155525155983
*/
155526155984
SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
155527155985
#ifdef WHERETRACE_ENABLED
155528155986
SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
155529155987
SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm);
155530
-SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC);
155988
+SQLITE_PRIVATE void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC);
155531155989
#endif
155532155990
SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
155533155991
WhereClause *pWC, /* The WHERE clause to be searched */
155534155992
int iCur, /* Cursor number of LHS */
155535155993
int iColumn, /* Column number of LHS */
@@ -160987,16 +161445,26 @@
160987161445
int iEnd = sqlite3VdbeCurrentAddr(v);
160988161446
if( pParse->db->mallocFailed ) return;
160989161447
for(; iStart<iEnd; iStart++, pOp++){
160990161448
if( pOp->p1!=iTabCur ) continue;
160991161449
if( pOp->opcode==OP_Column ){
161450
+#ifdef SQLITE_DEBUG
161451
+ if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
161452
+ printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart);
161453
+ }
161454
+#endif
160992161455
pOp->opcode = OP_Copy;
160993161456
pOp->p1 = pOp->p2 + iRegister;
160994161457
pOp->p2 = pOp->p3;
160995161458
pOp->p3 = 0;
160996161459
pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */
160997161460
}else if( pOp->opcode==OP_Rowid ){
161461
+#ifdef SQLITE_DEBUG
161462
+ if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
161463
+ printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart);
161464
+ }
161465
+#endif
160998161466
pOp->opcode = OP_Sequence;
160999161467
pOp->p1 = iAutoidxCur;
161000161468
#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
161001161469
if( iAutoidxCur==0 ){
161002161470
pOp->opcode = OP_Null;
@@ -162319,11 +162787,12 @@
162319162787
nNew = sqlite3LogEst(iUpper - iLower);
162320162788
/* TUNING: If both iUpper and iLower are derived from the same
162321162789
** sample, then assume they are 4x more selective. This brings
162322162790
** the estimated selectivity more in line with what it would be
162323162791
** if estimated without the use of STAT4 tables. */
162324
- if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
162792
+ if( iLwrIdx==iUprIdx ){ nNew -= 20; }
162793
+ assert( 20==sqlite3LogEst(4) );
162325162794
}else{
162326162795
nNew = 10; assert( 10==sqlite3LogEst(2) );
162327162796
}
162328162797
if( nNew<nOut ){
162329162798
nOut = nNew;
@@ -162543,21 +163012,38 @@
162543163012
#endif
162544163013
162545163014
#ifdef WHERETRACE_ENABLED
162546163015
/*
162547163016
** Print a WhereLoop object for debugging purposes
163017
+**
163018
+** Format example:
163019
+**
163020
+** .--- Position in WHERE clause rSetup, rRun, nOut ---.
163021
+** | |
163022
+** | .--- selfMask nTerm ------. |
163023
+** | | | |
163024
+** | | .-- prereq Idx wsFlags----. | |
163025
+** | | | Name | | |
163026
+** | | | __|__ nEq ---. ___|__ | __|__
163027
+** | / \ / \ / \ | / \ / \ / \
163028
+** 1.002.001 t2.t2xy 2 f 010241 N 2 cost 0,56,31
162548163029
*/
162549
-SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
162550
- WhereInfo *pWInfo = pWC->pWInfo;
162551
- int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
162552
- SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
162553
- Table *pTab = pItem->pTab;
162554
- Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
162555
- sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
162556
- p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
162557
- sqlite3DebugPrintf(" %12s",
162558
- pItem->zAlias ? pItem->zAlias : pTab->zName);
163030
+SQLITE_PRIVATE void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC){
163031
+ if( pWC ){
163032
+ WhereInfo *pWInfo = pWC->pWInfo;
163033
+ int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
163034
+ SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
163035
+ Table *pTab = pItem->pTab;
163036
+ Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
163037
+ sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
163038
+ p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
163039
+ sqlite3DebugPrintf(" %12s",
163040
+ pItem->zAlias ? pItem->zAlias : pTab->zName);
163041
+ }else{
163042
+ sqlite3DebugPrintf("%c%2d.%03llx.%03llx %c%d",
163043
+ p->cId, p->iTab, p->maskSelf, p->prereq & 0xfff, p->cId, p->iTab);
163044
+ }
162559163045
if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
162560163046
const char *zName;
162561163047
if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
162562163048
if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
162563163049
int i = sqlite3Strlen30(zName) - 1;
@@ -162589,10 +163075,19 @@
162589163075
int i;
162590163076
for(i=0; i<p->nLTerm; i++){
162591163077
sqlite3WhereTermPrint(p->aLTerm[i], i);
162592163078
}
162593163079
}
163080
+}
163081
+SQLITE_PRIVATE void sqlite3ShowWhereLoop(const WhereLoop *p){
163082
+ if( p ) sqlite3WhereLoopPrint(p, 0);
163083
+}
163084
+SQLITE_PRIVATE void sqlite3ShowWhereLoopList(const WhereLoop *p){
163085
+ while( p ){
163086
+ sqlite3ShowWhereLoop(p);
163087
+ p = p->pNextLoop;
163088
+ }
162594163089
}
162595163090
#endif
162596163091
162597163092
/*
162598163093
** Convert bulk memory into a valid WhereLoop that can be passed
@@ -162702,50 +163197,64 @@
162702163197
}
162703163198
sqlite3DbNNFreeNN(db, pWInfo);
162704163199
}
162705163200
162706163201
/*
162707
-** Return TRUE if all of the following are true:
162708
-**
162709
-** (1) X has the same or lower cost, or returns the same or fewer rows,
162710
-** than Y.
162711
-** (2) X uses fewer WHERE clause terms than Y
162712
-** (3) Every WHERE clause term used by X is also used by Y
162713
-** (4) X skips at least as many columns as Y
162714
-** (5) If X is a covering index, than Y is too
162715
-**
162716
-** Conditions (2) and (3) mean that X is a "proper subset" of Y.
162717
-** If X is a proper subset of Y then Y is a better choice and ought
162718
-** to have a lower cost. This routine returns TRUE when that cost
162719
-** relationship is inverted and needs to be adjusted. Constraint (4)
162720
-** was added because if X uses skip-scan less than Y it still might
162721
-** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
162722
-** was added because a covering index probably deserves to have a lower cost
162723
-** than a non-covering index even if it is a proper subset.
163202
+** Return TRUE if X is a proper subset of Y but is of equal or less cost.
163203
+** In other words, return true if all constraints of X are also part of Y
163204
+** and Y has additional constraints that might speed the search that X lacks
163205
+** but the cost of running X is not more than the cost of running Y.
163206
+**
163207
+** In other words, return true if the cost relationwship between X and Y
163208
+** is inverted and needs to be adjusted.
163209
+**
163210
+** Case 1:
163211
+**
163212
+** (1a) X and Y use the same index.
163213
+** (1b) X has fewer == terms than Y
163214
+** (1c) Neither X nor Y use skip-scan
163215
+** (1d) X does not have a a greater cost than Y
163216
+**
163217
+** Case 2:
163218
+**
163219
+** (2a) X has the same or lower cost, or returns the same or fewer rows,
163220
+** than Y.
163221
+** (2b) X uses fewer WHERE clause terms than Y
163222
+** (2c) Every WHERE clause term used by X is also used by Y
163223
+** (2d) X skips at least as many columns as Y
163224
+** (2e) If X is a covering index, than Y is too
162724163225
*/
162725163226
static int whereLoopCheaperProperSubset(
162726163227
const WhereLoop *pX, /* First WhereLoop to compare */
162727163228
const WhereLoop *pY /* Compare against this WhereLoop */
162728163229
){
162729163230
int i, j;
163231
+ if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0; /* (1d) and (2a) */
163232
+ assert( (pX->wsFlags & WHERE_VIRTUALTABLE)==0 );
163233
+ assert( (pY->wsFlags & WHERE_VIRTUALTABLE)==0 );
163234
+ if( pX->u.btree.nEq < pY->u.btree.nEq /* (1b) */
163235
+ && pX->u.btree.pIndex==pY->u.btree.pIndex /* (1a) */
163236
+ && pX->nSkip==0 && pY->nSkip==0 /* (1c) */
163237
+ ){
163238
+ return 1; /* Case 1 is true */
163239
+ }
162730163240
if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
162731
- return 0; /* X is not a subset of Y */
163241
+ return 0; /* (2b) */
162732163242
}
162733
- if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0;
162734
- if( pY->nSkip > pX->nSkip ) return 0;
163243
+ if( pY->nSkip > pX->nSkip ) return 0; /* (2d) */
162735163244
for(i=pX->nLTerm-1; i>=0; i--){
162736163245
if( pX->aLTerm[i]==0 ) continue;
162737163246
for(j=pY->nLTerm-1; j>=0; j--){
162738163247
if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
162739163248
}
162740
- if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
163249
+ if( j<0 ) return 0; /* (2c) */
162741163250
}
162742163251
if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
162743163252
&& (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
162744
- return 0; /* Constraint (5) */
163253
+ return 0; /* (2e) */
162745163254
}
162746
- return 1; /* All conditions meet */
163255
+ return 1; /* Case 2 is true */
162747163256
}
162748163257
162749163258
/*
162750163259
** Try to adjust the cost and number of output rows of WhereLoop pTemplate
162751163260
** upwards or downwards so that:
@@ -163231,11 +163740,14 @@
163231163740
opMask = WO_LT|WO_LE;
163232163741
}else{
163233163742
assert( pNew->u.btree.nBtm==0 );
163234163743
opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
163235163744
}
163236
- if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
163745
+ if( pProbe->bUnordered || pProbe->bLowQual ){
163746
+ if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
163747
+ if( pProbe->bLowQual ) opMask &= ~(WO_EQ|WO_IN|WO_IS);
163748
+ }
163237163749
163238163750
assert( pNew->u.btree.nEq<pProbe->nColumn );
163239163751
assert( pNew->u.btree.nEq<pProbe->nKeyCol
163240163752
|| pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
163241163753
@@ -166311,11 +166823,14 @@
166311166823
db = pParse->db;
166312166824
memset(&sWLB, 0, sizeof(sWLB));
166313166825
166314166826
/* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
166315166827
testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
166316
- if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
166828
+ if( pOrderBy && pOrderBy->nExpr>=BMS ){
166829
+ pOrderBy = 0;
166830
+ wctrlFlags &= ~WHERE_WANT_DISTINCT;
166831
+ }
166317166832
166318166833
/* The number of tables in the FROM clause is limited by the number of
166319166834
** bits in a Bitmask
166320166835
*/
166321166836
testcase( pTabList->nSrc==BMS );
@@ -166336,11 +166851,14 @@
166336166851
** struct, the contents of WhereInfo.a[], the WhereClause structure
166337166852
** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
166338166853
** field (type Bitmask) it must be aligned on an 8-byte boundary on
166339166854
** some architectures. Hence the ROUND8() below.
166340166855
*/
166341
- nByteWInfo = ROUND8P(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
166856
+ nByteWInfo = ROUND8P(sizeof(WhereInfo));
166857
+ if( nTabList>1 ){
166858
+ nByteWInfo = ROUND8P(nByteWInfo + (nTabList-1)*sizeof(WhereLevel));
166859
+ }
166342166860
pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
166343166861
if( db->mallocFailed ){
166344166862
sqlite3DbFree(db, pWInfo);
166345166863
pWInfo = 0;
166346166864
goto whereBeginError;
@@ -166898,10 +167416,15 @@
166898167416
whereBeginError:
166899167417
if( pWInfo ){
166900167418
pParse->nQueryLoop = pWInfo->savedNQueryLoop;
166901167419
whereInfoFree(db, pWInfo);
166902167420
}
167421
+#ifdef WHERETRACE_ENABLED
167422
+ /* Prevent harmless compiler warnings about debugging routines
167423
+ ** being declared but never used */
167424
+ sqlite3ShowWhereLoopList(0);
167425
+#endif /* WHERETRACE_ENABLED */
166903167426
return 0;
166904167427
}
166905167428
166906167429
/*
166907167430
** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
@@ -182234,10 +182757,32 @@
182234182757
rc = SQLITE_NOTFOUND;
182235182758
}
182236182759
break;
182237182760
}
182238182761
#endif
182762
+
182763
+ /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
182764
+ **
182765
+ ** Activate or deactivate validation of JSONB that is generated from
182766
+ ** text. Off by default, as the validation is slow. Validation is
182767
+ ** only available if compiled using SQLITE_DEBUG.
182768
+ **
182769
+ ** If onOff is initially 1, then turn it on. If onOff is initially
182770
+ ** off, turn it off. If onOff is initially -1, then change onOff
182771
+ ** to be the current setting.
182772
+ */
182773
+ case SQLITE_TESTCTRL_JSON_SELFCHECK: {
182774
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
182775
+ int *pOnOff = va_arg(ap, int*);
182776
+ if( *pOnOff<0 ){
182777
+ *pOnOff = sqlite3Config.bJsonSelfcheck;
182778
+ }else{
182779
+ sqlite3Config.bJsonSelfcheck = (u8)((*pOnOff)&0xff);
182780
+ }
182781
+#endif
182782
+ break;
182783
+ }
182239182784
}
182240182785
va_end(ap);
182241182786
#endif /* SQLITE_UNTESTABLE */
182242182787
return rc;
182243182788
}
@@ -184217,10 +184762,12 @@
184217184762
SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
184218184763
SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
184219184764
#endif
184220184765
184221184766
SQLITE_PRIVATE int sqlite3Fts3ExprIterate(Fts3Expr*, int (*x)(Fts3Expr*,int,void*), void*);
184767
+
184768
+SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk);
184222184769
184223184770
#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
184224184771
#endif /* _FTSINT_H */
184225184772
184226184773
/************** End of fts3Int.h *********************************************/
@@ -187940,42 +188487,33 @@
187940188487
187941188488
/*
187942188489
** Implementation of the xIntegrity() method on the FTS3/FTS4 virtual
187943188490
** table.
187944188491
*/
187945
-static int fts3Integrity(
188492
+static int fts3IntegrityMethod(
187946188493
sqlite3_vtab *pVtab, /* The virtual table to be checked */
187947188494
const char *zSchema, /* Name of schema in which pVtab lives */
187948188495
const char *zTabname, /* Name of the pVTab table */
187949188496
int isQuick, /* True if this is a quick_check */
187950188497
char **pzErr /* Write error message here */
187951188498
){
187952188499
Fts3Table *p = (Fts3Table*)pVtab;
187953
- char *zSql;
187954188500
int rc;
187955
- char *zErr = 0;
188501
+ int bOk = 0;
187956188502
187957
- assert( pzErr!=0 );
187958
- assert( *pzErr==0 );
187959188503
UNUSED_PARAMETER(isQuick);
187960
- zSql = sqlite3_mprintf(
187961
- "INSERT INTO \"%w\".\"%w\"(\"%w\") VALUES('integrity-check');",
187962
- zSchema, zTabname, zTabname);
187963
- if( zSql==0 ){
187964
- return SQLITE_NOMEM;
187965
- }
187966
- rc = sqlite3_exec(p->db, zSql, 0, 0, &zErr);
187967
- sqlite3_free(zSql);
187968
- if( (rc&0xff)==SQLITE_CORRUPT ){
188504
+ rc = sqlite3Fts3IntegrityCheck(p, &bOk);
188505
+ assert( rc!=SQLITE_CORRUPT_VTAB || bOk==0 );
188506
+ if( rc!=SQLITE_OK && rc!=SQLITE_CORRUPT_VTAB ){
188507
+ *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
188508
+ " FTS%d table %s.%s: %s",
188509
+ p->bFts4 ? 4 : 3, zSchema, zTabname, sqlite3_errstr(rc));
188510
+ }else if( bOk==0 ){
187969188511
*pzErr = sqlite3_mprintf("malformed inverted index for FTS%d table %s.%s",
187970188512
p->bFts4 ? 4 : 3, zSchema, zTabname);
187971
- }else if( rc!=SQLITE_OK ){
187972
- *pzErr = sqlite3_mprintf("unable to validate the inverted index for"
187973
- " FTS%d table %s.%s: %s",
187974
- p->bFts4 ? 4 : 3, zSchema, zTabname, zErr);
187975188513
}
187976
- sqlite3_free(zErr);
188514
+ sqlite3Fts3SegmentsClose(p);
187977188515
return SQLITE_OK;
187978188516
}
187979188517
187980188518
187981188519
@@ -188002,11 +188540,11 @@
188002188540
/* xRename */ fts3RenameMethod,
188003188541
/* xSavepoint */ fts3SavepointMethod,
188004188542
/* xRelease */ fts3ReleaseMethod,
188005188543
/* xRollbackTo */ fts3RollbackToMethod,
188006188544
/* xShadowName */ fts3ShadowName,
188007
- /* xIntegrity */ fts3Integrity,
188545
+ /* xIntegrity */ fts3IntegrityMethod,
188008188546
};
188009188547
188010188548
/*
188011188549
** This function is registered as the module destructor (called when an
188012188550
** FTS3 enabled database connection is closed). It frees the memory
@@ -199556,11 +200094,11 @@
199556200094
** to false before returning.
199557200095
**
199558200096
** If an error occurs (e.g. an OOM or IO error), return an SQLite error
199559200097
** code. The final value of *pbOk is undefined in this case.
199560200098
*/
199561
-static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
200099
+SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){
199562200100
int rc = SQLITE_OK; /* Return code */
199563200101
u64 cksum1 = 0; /* Checksum based on FTS index contents */
199564200102
u64 cksum2 = 0; /* Checksum based on %_content contents */
199565200103
sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
199566200104
@@ -199634,11 +200172,11 @@
199634200172
}
199635200173
199636200174
sqlite3_finalize(pStmt);
199637200175
}
199638200176
199639
- *pbOk = (cksum1==cksum2);
200177
+ *pbOk = (rc==SQLITE_OK && cksum1==cksum2);
199640200178
return rc;
199641200179
}
199642200180
199643200181
/*
199644200182
** Run the integrity-check. If no error occurs and the current contents of
@@ -199674,11 +200212,11 @@
199674200212
static int fts3DoIntegrityCheck(
199675200213
Fts3Table *p /* FTS3 table handle */
199676200214
){
199677200215
int rc;
199678200216
int bOk = 0;
199679
- rc = fts3IntegrityCheck(p, &bOk);
200217
+ rc = sqlite3Fts3IntegrityCheck(p, &bOk);
199680200218
if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
199681200219
return rc;
199682200220
}
199683200221
199684200222
/*
@@ -202648,28 +203186,149 @@
202648203186
** May you find forgiveness for yourself and forgive others.
202649203187
** May you share freely, never taking more than you give.
202650203188
**
202651203189
******************************************************************************
202652203190
**
202653
-** This SQLite JSON functions.
203191
+** SQLite JSON functions.
202654203192
**
202655203193
** This file began as an extension in ext/misc/json1.c in 2015. That
202656203194
** extension proved so useful that it has now been moved into the core.
202657203195
**
202658
-** For the time being, all JSON is stored as pure text. (We might add
202659
-** a JSONB type in the future which stores a binary encoding of JSON in
202660
-** a BLOB, but there is no support for JSONB in the current implementation.
202661
-** This implementation parses JSON text at 250 MB/s, so it is hard to see
202662
-** how JSONB might improve on that.)
203196
+** The original design stored all JSON as pure text, canonical RFC-8259.
203197
+** Support for JSON-5 extensions was added with version 3.42.0 (2023-05-16).
203198
+** All generated JSON text still conforms strictly to RFC-8259, but text
203199
+** with JSON-5 extensions is accepted as input.
203200
+**
203201
+** Beginning with version 3.45.0 (circa 2024-01-01), these routines also
203202
+** accept BLOB values that have JSON encoded using a binary representation
203203
+** called "JSONB". The name JSONB comes from PostgreSQL, however the on-disk
203204
+** format SQLite JSONB is completely different and incompatible with
203205
+** PostgreSQL JSONB.
203206
+**
203207
+** Decoding and interpreting JSONB is still O(N) where N is the size of
203208
+** the input, the same as text JSON. However, the constant of proportionality
203209
+** for JSONB is much smaller due to faster parsing. The size of each
203210
+** element in JSONB is encoded in its header, so there is no need to search
203211
+** for delimiters using persnickety syntax rules. JSONB seems to be about
203212
+** 3x faster than text JSON as a result. JSONB is also tends to be slightly
203213
+** smaller than text JSON, by 5% or 10%, but there are corner cases where
203214
+** JSONB can be slightly larger. So you are not far mistaken to say that
203215
+** a JSONB blob is the same size as the equivalent RFC-8259 text.
203216
+**
203217
+**
203218
+** THE JSONB ENCODING:
203219
+**
203220
+** Every JSON element is encoded in JSONB as a header and a payload.
203221
+** The header is between 1 and 9 bytes in size. The payload is zero
203222
+** or more bytes.
203223
+**
203224
+** The lower 4 bits of the first byte of the header determines the
203225
+** element type:
203226
+**
203227
+** 0: NULL
203228
+** 1: TRUE
203229
+** 2: FALSE
203230
+** 3: INT -- RFC-8259 integer literal
203231
+** 4: INT5 -- JSON5 integer literal
203232
+** 5: FLOAT -- RFC-8259 floating point literal
203233
+** 6: FLOAT5 -- JSON5 floating point literal
203234
+** 7: TEXT -- Text literal acceptable to both SQL and JSON
203235
+** 8: TEXTJ -- Text containing RFC-8259 escapes
203236
+** 9: TEXT5 -- Text containing JSON5 and/or RFC-8259 escapes
203237
+** 10: TEXTRAW -- Text containing unescaped syntax characters
203238
+** 11: ARRAY
203239
+** 12: OBJECT
203240
+**
203241
+** The other three possible values (13-15) are reserved for future
203242
+** enhancements.
203243
+**
203244
+** The upper 4 bits of the first byte determine the size of the header
203245
+** and sometimes also the size of the payload. If X is the first byte
203246
+** of the element and if X>>4 is between 0 and 11, then the payload
203247
+** will be that many bytes in size and the header is exactly one byte
203248
+** in size. Other four values for X>>4 (12-15) indicate that the header
203249
+** is more than one byte in size and that the payload size is determined
203250
+** by the remainder of the header, interpreted as a unsigned big-endian
203251
+** integer.
203252
+**
203253
+** Value of X>>4 Size integer Total header size
203254
+** ------------- -------------------- -----------------
203255
+** 12 1 byte (0-255) 2
203256
+** 13 2 byte (0-65535) 3
203257
+** 14 4 byte (0-4294967295) 5
203258
+** 15 8 byte (0-1.8e19) 9
203259
+**
203260
+** The payload size need not be expressed in its minimal form. For example,
203261
+** if the payload size is 10, the size can be expressed in any of 5 different
203262
+** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by on 0x0a byte,
203263
+** (3) (X>>4)==13 followed by 0x00 and 0x0a, (4) (X>>4)==14 followed by
203264
+** 0x00 0x00 0x00 0x0a, or (5) (X>>4)==15 followed by 7 bytes of 0x00 and
203265
+** a single byte of 0x0a. The shorter forms are preferred, of course, but
203266
+** sometimes when generating JSONB, the payload size is not known in advance
203267
+** and it is convenient to reserve sufficient header space to cover the
203268
+** largest possible payload size and then come back later and patch up
203269
+** the size when it becomes known, resulting in a non-minimal encoding.
203270
+**
203271
+** The value (X>>4)==15 is not actually used in the current implementation
203272
+** (as SQLite is currently unable handle BLOBs larger than about 2GB)
203273
+** but is included in the design to allow for future enhancements.
203274
+**
203275
+** The payload follows the header. NULL, TRUE, and FALSE have no payload and
203276
+** their payload size must always be zero. The payload for INT, INT5,
203277
+** FLOAT, FLOAT5, TEXT, TEXTJ, TEXT5, and TEXTROW is text. Note that the
203278
+** "..." or '...' delimiters are omitted from the various text encodings.
203279
+** The payload for ARRAY and OBJECT is a list of additional elements that
203280
+** are the content for the array or object. The payload for an OBJECT
203281
+** must be an even number of elements. The first element of each pair is
203282
+** the label and must be of type TEXT, TEXTJ, TEXT5, or TEXTRAW.
203283
+**
203284
+** A valid JSONB blob consists of a single element, as described above.
203285
+** Usually this will be an ARRAY or OBJECT element which has many more
203286
+** elements as its content. But the overall blob is just a single element.
203287
+**
203288
+** Input validation for JSONB blobs simply checks that the element type
203289
+** code is between 0 and 12 and that the total size of the element
203290
+** (header plus payload) is the same as the size of the BLOB. If those
203291
+** checks are true, the BLOB is assumed to be JSONB and processing continues.
203292
+** Errors are only raised if some other miscoding is discovered during
203293
+** processing.
203294
+**
203295
+** Additional information can be found in the doc/jsonb.md file of the
203296
+** canonical SQLite source tree.
202663203297
*/
202664203298
#ifndef SQLITE_OMIT_JSON
202665203299
/* #include "sqliteInt.h" */
202666203300
203301
+/* JSONB element types
203302
+*/
203303
+#define JSONB_NULL 0 /* "null" */
203304
+#define JSONB_TRUE 1 /* "true" */
203305
+#define JSONB_FALSE 2 /* "false" */
203306
+#define JSONB_INT 3 /* integer acceptable to JSON and SQL */
203307
+#define JSONB_INT5 4 /* integer in 0x000 notation */
203308
+#define JSONB_FLOAT 5 /* float acceptable to JSON and SQL */
203309
+#define JSONB_FLOAT5 6 /* float with JSON5 extensions */
203310
+#define JSONB_TEXT 7 /* Text compatible with both JSON and SQL */
203311
+#define JSONB_TEXTJ 8 /* Text with JSON escapes */
203312
+#define JSONB_TEXT5 9 /* Text with JSON-5 escape */
203313
+#define JSONB_TEXTRAW 10 /* SQL text that needs escaping for JSON */
203314
+#define JSONB_ARRAY 11 /* An array */
203315
+#define JSONB_OBJECT 12 /* An object */
203316
+
203317
+/* Human-readable names for the JSONB values. The index for each
203318
+** string must correspond to the JSONB_* integer above.
203319
+*/
203320
+static const char * const jsonbType[] = {
203321
+ "null", "true", "false", "integer", "integer",
203322
+ "real", "real", "text", "text", "text",
203323
+ "text", "array", "object", "", "", "", ""
203324
+};
203325
+
202667203326
/*
202668203327
** Growing our own isspace() routine this way is twice as fast as
202669203328
** the library isspace() function, resulting in a 7% overall performance
202670
-** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
203329
+** increase for the text-JSON parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
202671203330
*/
202672203331
static const char jsonIsSpace[] = {
202673203332
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
202674203333
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202675203334
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -202686,15 +203345,23 @@
202686203345
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202687203346
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202688203347
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202689203348
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202690203349
};
202691
-#define fast_isspace(x) (jsonIsSpace[(unsigned char)x])
203350
+#define jsonIsspace(x) (jsonIsSpace[(unsigned char)x])
202692203351
202693203352
/*
202694
-** Characters that are special to JSON. Control charaters,
202695
-** '"' and '\\'.
203353
+** The set of all space characters recognized by jsonIsspace().
203354
+** Useful as the second argument to strspn().
203355
+*/
203356
+static const char jsonSpaces[] = "\011\012\015\040";
203357
+
203358
+/*
203359
+** Characters that are special to JSON. Control characters,
203360
+** '"' and '\\' and '\''. Actually, '\'' is not special to
203361
+** canonical JSON, but it is special in JSON-5, so we include
203362
+** it in the set of special characters.
202696203363
*/
202697203364
static const char jsonIsOk[256] = {
202698203365
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202699203366
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
202700203367
1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -202712,247 +203379,364 @@
202712203379
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
202713203380
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
202714203381
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
202715203382
};
202716203383
202717
-
202718
-#if !defined(SQLITE_DEBUG) && !defined(SQLITE_COVERAGE_TEST)
202719
-# define VVA(X)
202720
-#else
202721
-# define VVA(X) X
202722
-#endif
202723
-
202724203384
/* Objects */
203385
+typedef struct JsonCache JsonCache;
202725203386
typedef struct JsonString JsonString;
202726
-typedef struct JsonNode JsonNode;
202727203387
typedef struct JsonParse JsonParse;
202728
-typedef struct JsonCleanup JsonCleanup;
203388
+
203389
+/*
203390
+** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
203391
+*/
203392
+#define JSON_CACHE_ID (-429938) /* Cache entry */
203393
+#define JSON_CACHE_SIZE 4 /* Max number of cache entries */
203394
+
203395
+/*
203396
+** jsonUnescapeOneChar() returns this invalid code point if it encounters
203397
+** a syntax error.
203398
+*/
203399
+#define JSON_INVALID_CHAR 0x99999
203400
+
203401
+/* A cache mapping JSON text into JSONB blobs.
203402
+**
203403
+** Each cache entry is a JsonParse object with the following restrictions:
203404
+**
203405
+** * The bReadOnly flag must be set
203406
+**
203407
+** * The aBlob[] array must be owned by the JsonParse object. In other
203408
+** words, nBlobAlloc must be non-zero.
203409
+**
203410
+** * eEdit and delta must be zero.
203411
+**
203412
+** * zJson must be an RCStr. In other words bJsonIsRCStr must be true.
203413
+*/
203414
+struct JsonCache {
203415
+ sqlite3 *db; /* Database connection */
203416
+ int nUsed; /* Number of active entries in the cache */
203417
+ JsonParse *a[JSON_CACHE_SIZE]; /* One line for each cache entry */
203418
+};
202729203419
202730203420
/* An instance of this object represents a JSON string
202731203421
** under construction. Really, this is a generic string accumulator
202732203422
** that can be and is used to create strings other than JSON.
203423
+**
203424
+** If the generated string is longer than will fit into the zSpace[] buffer,
203425
+** then it will be an RCStr string. This aids with caching of large
203426
+** JSON strings.
202733203427
*/
202734203428
struct JsonString {
202735203429
sqlite3_context *pCtx; /* Function context - put error messages here */
202736203430
char *zBuf; /* Append JSON content here */
202737203431
u64 nAlloc; /* Bytes of storage available in zBuf[] */
202738203432
u64 nUsed; /* Bytes of zBuf[] currently used */
202739203433
u8 bStatic; /* True if zBuf is static space */
202740
- u8 bErr; /* True if an error has been encountered */
203434
+ u8 eErr; /* True if an error has been encountered */
202741203435
char zSpace[100]; /* Initial static space */
202742203436
};
202743203437
202744
-/* A deferred cleanup task. A list of JsonCleanup objects might be
202745
-** run when the JsonParse object is destroyed.
202746
-*/
202747
-struct JsonCleanup {
202748
- JsonCleanup *pJCNext; /* Next in a list */
202749
- void (*xOp)(void*); /* Routine to run */
202750
- void *pArg; /* Argument to xOp() */
202751
-};
202752
-
202753
-/* JSON type values
202754
-*/
202755
-#define JSON_SUBST 0 /* Special edit node. Uses u.iPrev */
202756
-#define JSON_NULL 1
202757
-#define JSON_TRUE 2
202758
-#define JSON_FALSE 3
202759
-#define JSON_INT 4
202760
-#define JSON_REAL 5
202761
-#define JSON_STRING 6
202762
-#define JSON_ARRAY 7
202763
-#define JSON_OBJECT 8
202764
-
202765
-/* The "subtype" set for JSON values */
203438
+/* Allowed values for JsonString.eErr */
203439
+#define JSTRING_OOM 0x01 /* Out of memory */
203440
+#define JSTRING_MALFORMED 0x02 /* Malformed JSONB */
203441
+#define JSTRING_ERR 0x04 /* Error already sent to sqlite3_result */
203442
+
203443
+/* The "subtype" set for text JSON values passed through using
203444
+** sqlite3_result_subtype() and sqlite3_value_subtype().
203445
+*/
202766203446
#define JSON_SUBTYPE 74 /* Ascii for "J" */
202767203447
202768203448
/*
202769
-** Names of the various JSON types:
202770
-*/
202771
-static const char * const jsonType[] = {
202772
- "subst",
202773
- "null", "true", "false", "integer", "real", "text", "array", "object"
202774
-};
202775
-
202776
-/* Bit values for the JsonNode.jnFlag field
202777
-*/
202778
-#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
202779
-#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
202780
-#define JNODE_REMOVE 0x04 /* Do not output */
202781
-#define JNODE_REPLACE 0x08 /* Target of a JSON_SUBST node */
202782
-#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
202783
-#define JNODE_LABEL 0x20 /* Is a label of an object */
202784
-#define JNODE_JSON5 0x40 /* Node contains JSON5 enhancements */
202785
-
202786
-
202787
-/* A single node of parsed JSON. An array of these nodes describes
202788
-** a parse of JSON + edits.
202789
-**
202790
-** Use the json_parse() SQL function (available when compiled with
202791
-** -DSQLITE_DEBUG) to see a dump of complete JsonParse objects, including
202792
-** a complete listing and decoding of the array of JsonNodes.
202793
-*/
202794
-struct JsonNode {
202795
- u8 eType; /* One of the JSON_ type values */
202796
- u8 jnFlags; /* JNODE flags */
202797
- u8 eU; /* Which union element to use */
202798
- u32 n; /* Bytes of content for INT, REAL or STRING
202799
- ** Number of sub-nodes for ARRAY and OBJECT
202800
- ** Node that SUBST applies to */
202801
- union {
202802
- const char *zJContent; /* 1: Content for INT, REAL, and STRING */
202803
- u32 iAppend; /* 2: More terms for ARRAY and OBJECT */
202804
- u32 iKey; /* 3: Key for ARRAY objects in json_tree() */
202805
- u32 iPrev; /* 4: Previous SUBST node, or 0 */
202806
- } u;
202807
-};
202808
-
202809
-
202810
-/* A parsed and possibly edited JSON string. Lifecycle:
202811
-**
202812
-** 1. JSON comes in and is parsed into an array aNode[]. The original
202813
-** JSON text is stored in zJson.
202814
-**
202815
-** 2. Zero or more changes are made (via json_remove() or json_replace()
202816
-** or similar) to the aNode[] array.
202817
-**
202818
-** 3. A new, edited and mimified JSON string is generated from aNode
202819
-** and stored in zAlt. The JsonParse object always owns zAlt.
202820
-**
202821
-** Step 1 always happens. Step 2 and 3 may or may not happen, depending
202822
-** on the operation.
202823
-**
202824
-** aNode[].u.zJContent entries typically point into zJson. Hence zJson
202825
-** must remain valid for the lifespan of the parse. For edits,
202826
-** aNode[].u.zJContent might point to malloced space other than zJson.
202827
-** Entries in pClup are responsible for freeing that extra malloced space.
202828
-**
202829
-** When walking the parse tree in aNode[], edits are ignored if useMod is
202830
-** false.
203449
+** Bit values for the flags passed into various SQL function implementations
203450
+** via the sqlite3_user_data() value.
203451
+*/
203452
+#define JSON_JSON 0x01 /* Result is always JSON */
203453
+#define JSON_SQL 0x02 /* Result is always SQL */
203454
+#define JSON_ABPATH 0x03 /* Allow abbreviated JSON path specs */
203455
+#define JSON_ISSET 0x04 /* json_set(), not json_insert() */
203456
+#define JSON_BLOB 0x08 /* Use the BLOB output format */
203457
+
203458
+
203459
+/* A parsed JSON value. Lifecycle:
203460
+**
203461
+** 1. JSON comes in and is parsed into a JSONB value in aBlob. The
203462
+** original text is stored in zJson. This step is skipped if the
203463
+** input is JSONB instead of text JSON.
203464
+**
203465
+** 2. The aBlob[] array is searched using the JSON path notation, if needed.
203466
+**
203467
+** 3. Zero or more changes are made to aBlob[] (via json_remove() or
203468
+** json_replace() or json_patch() or similar).
203469
+**
203470
+** 4. New JSON text is generated from the aBlob[] for output. This step
203471
+** is skipped if the function is one of the jsonb_* functions that
203472
+** returns JSONB instead of text JSON.
202831203473
*/
202832203474
struct JsonParse {
202833
- u32 nNode; /* Number of slots of aNode[] used */
202834
- u32 nAlloc; /* Number of slots of aNode[] allocated */
202835
- JsonNode *aNode; /* Array of nodes containing the parse */
202836
- char *zJson; /* Original JSON string (before edits) */
202837
- char *zAlt; /* Revised and/or mimified JSON */
202838
- u32 *aUp; /* Index of parent of each node */
202839
- JsonCleanup *pClup;/* Cleanup operations prior to freeing this object */
203475
+ u8 *aBlob; /* JSONB representation of JSON value */
203476
+ u32 nBlob; /* Bytes of aBlob[] actually used */
203477
+ u32 nBlobAlloc; /* Bytes allocated to aBlob[]. 0 if aBlob is external */
203478
+ char *zJson; /* Json text used for parsing */
203479
+ sqlite3 *db; /* The database connection to which this object belongs */
203480
+ int nJson; /* Length of the zJson string in bytes */
203481
+ u32 nJPRef; /* Number of references to this object */
203482
+ u32 iErr; /* Error location in zJson[] */
202840203483
u16 iDepth; /* Nesting depth */
202841203484
u8 nErr; /* Number of errors seen */
202842203485
u8 oom; /* Set to true if out of memory */
202843203486
u8 bJsonIsRCStr; /* True if zJson is an RCStr */
202844203487
u8 hasNonstd; /* True if input uses non-standard features like JSON5 */
202845
- u8 useMod; /* Actually use the edits contain inside aNode */
202846
- u8 hasMod; /* aNode contains edits from the original zJson */
202847
- u32 nJPRef; /* Number of references to this object */
202848
- int nJson; /* Length of the zJson string in bytes */
202849
- int nAlt; /* Length of alternative JSON string zAlt, in bytes */
202850
- u32 iErr; /* Error location in zJson[] */
202851
- u32 iSubst; /* Last JSON_SUBST entry in aNode[] */
202852
- u32 iHold; /* Age of this entry in the cache for LRU replacement */
203488
+ u8 bReadOnly; /* Do not modify. */
203489
+ /* Search and edit information. See jsonLookupStep() */
203490
+ u8 eEdit; /* Edit operation to apply */
203491
+ int delta; /* Size change due to the edit */
203492
+ u32 nIns; /* Number of bytes to insert */
203493
+ u32 iLabel; /* Location of label if search landed on an object value */
203494
+ u8 *aIns; /* Content to be inserted */
202853203495
};
202854203496
203497
+/* Allowed values for JsonParse.eEdit */
203498
+#define JEDIT_DEL 1 /* Delete if exists */
203499
+#define JEDIT_REPL 2 /* Overwrite if exists */
203500
+#define JEDIT_INS 3 /* Insert if not exists */
203501
+#define JEDIT_SET 4 /* Insert or overwrite */
203502
+
202855203503
/*
202856203504
** Maximum nesting depth of JSON for this implementation.
202857203505
**
202858203506
** This limit is needed to avoid a stack overflow in the recursive
202859203507
** descent parser. A depth of 1000 is far deeper than any sane JSON
202860203508
** should go. Historical note: This limit was 2000 prior to version 3.42.0
202861203509
*/
202862
-#define JSON_MAX_DEPTH 1000
203510
+#ifndef SQLITE_JSON_MAX_DEPTH
203511
+# define JSON_MAX_DEPTH 1000
203512
+#else
203513
+# define JSON_MAX_DEPTH SQLITE_JSON_MAX_DEPTH
203514
+#endif
203515
+
203516
+/*
203517
+** Allowed values for the flgs argument to jsonParseFuncArg();
203518
+*/
203519
+#define JSON_EDITABLE 0x01 /* Generate a writable JsonParse object */
203520
+#define JSON_KEEPERROR 0x02 /* Return non-NULL even if there is an error */
203521
+
203522
+/**************************************************************************
203523
+** Forward references
203524
+**************************************************************************/
203525
+static void jsonReturnStringAsBlob(JsonString*);
203526
+static int jsonFuncArgMightBeBinary(sqlite3_value *pJson);
203527
+static u32 jsonTranslateBlobToText(const JsonParse*,u32,JsonString*);
203528
+static void jsonReturnParse(sqlite3_context*,JsonParse*);
203529
+static JsonParse *jsonParseFuncArg(sqlite3_context*,sqlite3_value*,u32);
203530
+static void jsonParseFree(JsonParse*);
203531
+static u32 jsonbPayloadSize(const JsonParse*, u32, u32*);
203532
+static u32 jsonUnescapeOneChar(const char*, u32, u32*);
203533
+
203534
+/**************************************************************************
203535
+** Utility routines for dealing with JsonCache objects
203536
+**************************************************************************/
203537
+
203538
+/*
203539
+** Free a JsonCache object.
203540
+*/
203541
+static void jsonCacheDelete(JsonCache *p){
203542
+ int i;
203543
+ for(i=0; i<p->nUsed; i++){
203544
+ jsonParseFree(p->a[i]);
203545
+ }
203546
+ sqlite3DbFree(p->db, p);
203547
+}
203548
+static void jsonCacheDeleteGeneric(void *p){
203549
+ jsonCacheDelete((JsonCache*)p);
203550
+}
203551
+
203552
+/*
203553
+** Insert a new entry into the cache. If the cache is full, expel
203554
+** the least recently used entry. Return SQLITE_OK on success or a
203555
+** result code otherwise.
203556
+**
203557
+** Cache entries are stored in age order, oldest first.
203558
+*/
203559
+static int jsonCacheInsert(
203560
+ sqlite3_context *ctx, /* The SQL statement context holding the cache */
203561
+ JsonParse *pParse /* The parse object to be added to the cache */
203562
+){
203563
+ JsonCache *p;
203564
+
203565
+ assert( pParse->zJson!=0 );
203566
+ assert( pParse->bJsonIsRCStr );
203567
+ assert( pParse->delta==0 );
203568
+ p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID);
203569
+ if( p==0 ){
203570
+ sqlite3 *db = sqlite3_context_db_handle(ctx);
203571
+ p = sqlite3DbMallocZero(db, sizeof(*p));
203572
+ if( p==0 ) return SQLITE_NOMEM;
203573
+ p->db = db;
203574
+ sqlite3_set_auxdata(ctx, JSON_CACHE_ID, p, jsonCacheDeleteGeneric);
203575
+ p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID);
203576
+ if( p==0 ) return SQLITE_NOMEM;
203577
+ }
203578
+ if( p->nUsed >= JSON_CACHE_SIZE ){
203579
+ jsonParseFree(p->a[0]);
203580
+ memmove(p->a, &p->a[1], (JSON_CACHE_SIZE-1)*sizeof(p->a[0]));
203581
+ p->nUsed = JSON_CACHE_SIZE-1;
203582
+ }
203583
+ assert( pParse->nBlobAlloc>0 );
203584
+ pParse->eEdit = 0;
203585
+ pParse->nJPRef++;
203586
+ pParse->bReadOnly = 1;
203587
+ p->a[p->nUsed] = pParse;
203588
+ p->nUsed++;
203589
+ return SQLITE_OK;
203590
+}
203591
+
203592
+/*
203593
+** Search for a cached translation the json text supplied by pArg. Return
203594
+** the JsonParse object if found. Return NULL if not found.
203595
+**
203596
+** When a match if found, the matching entry is moved to become the
203597
+** most-recently used entry if it isn't so already.
203598
+**
203599
+** The JsonParse object returned still belongs to the Cache and might
203600
+** be deleted at any moment. If the caller whants the JsonParse to
203601
+** linger, it needs to increment the nPJRef reference counter.
203602
+*/
203603
+static JsonParse *jsonCacheSearch(
203604
+ sqlite3_context *ctx, /* The SQL statement context holding the cache */
203605
+ sqlite3_value *pArg /* Function argument containing SQL text */
203606
+){
203607
+ JsonCache *p;
203608
+ int i;
203609
+ const char *zJson;
203610
+ int nJson;
203611
+
203612
+ if( sqlite3_value_type(pArg)!=SQLITE_TEXT ){
203613
+ return 0;
203614
+ }
203615
+ zJson = (const char*)sqlite3_value_text(pArg);
203616
+ if( zJson==0 ) return 0;
203617
+ nJson = sqlite3_value_bytes(pArg);
203618
+
203619
+ p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID);
203620
+ if( p==0 ){
203621
+ return 0;
203622
+ }
203623
+ for(i=0; i<p->nUsed; i++){
203624
+ if( p->a[i]->zJson==zJson ) break;
203625
+ }
203626
+ if( i>=p->nUsed ){
203627
+ for(i=0; i<p->nUsed; i++){
203628
+ if( p->a[i]->nJson!=nJson ) continue;
203629
+ if( memcmp(p->a[i]->zJson, zJson, nJson)==0 ) break;
203630
+ }
203631
+ }
203632
+ if( i<p->nUsed ){
203633
+ if( i<p->nUsed-1 ){
203634
+ /* Make the matching entry the most recently used entry */
203635
+ JsonParse *tmp = p->a[i];
203636
+ memmove(&p->a[i], &p->a[i+1], (p->nUsed-i-1)*sizeof(tmp));
203637
+ p->a[p->nUsed-1] = tmp;
203638
+ i = p->nUsed - 1;
203639
+ }
203640
+ assert( p->a[i]->delta==0 );
203641
+ return p->a[i];
203642
+ }else{
203643
+ return 0;
203644
+ }
203645
+}
202863203646
202864203647
/**************************************************************************
202865203648
** Utility routines for dealing with JsonString objects
202866203649
**************************************************************************/
202867203650
202868
-/* Set the JsonString object to an empty string
203651
+/* Turn uninitialized bulk memory into a valid JsonString object
203652
+** holding a zero-length string.
202869203653
*/
202870
-static void jsonZero(JsonString *p){
203654
+static void jsonStringZero(JsonString *p){
202871203655
p->zBuf = p->zSpace;
202872203656
p->nAlloc = sizeof(p->zSpace);
202873203657
p->nUsed = 0;
202874203658
p->bStatic = 1;
202875203659
}
202876203660
202877203661
/* Initialize the JsonString object
202878203662
*/
202879
-static void jsonInit(JsonString *p, sqlite3_context *pCtx){
203663
+static void jsonStringInit(JsonString *p, sqlite3_context *pCtx){
202880203664
p->pCtx = pCtx;
202881
- p->bErr = 0;
202882
- jsonZero(p);
203665
+ p->eErr = 0;
203666
+ jsonStringZero(p);
202883203667
}
202884203668
202885203669
/* Free all allocated memory and reset the JsonString object back to its
202886203670
** initial state.
202887203671
*/
202888
-static void jsonReset(JsonString *p){
203672
+static void jsonStringReset(JsonString *p){
202889203673
if( !p->bStatic ) sqlite3RCStrUnref(p->zBuf);
202890
- jsonZero(p);
203674
+ jsonStringZero(p);
202891203675
}
202892203676
202893203677
/* Report an out-of-memory (OOM) condition
202894203678
*/
202895
-static void jsonOom(JsonString *p){
202896
- p->bErr = 1;
202897
- sqlite3_result_error_nomem(p->pCtx);
202898
- jsonReset(p);
203679
+static void jsonStringOom(JsonString *p){
203680
+ p->eErr |= JSTRING_OOM;
203681
+ if( p->pCtx ) sqlite3_result_error_nomem(p->pCtx);
203682
+ jsonStringReset(p);
202899203683
}
202900203684
202901203685
/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
202902203686
** Return zero on success. Return non-zero on an OOM error
202903203687
*/
202904
-static int jsonGrow(JsonString *p, u32 N){
203688
+static int jsonStringGrow(JsonString *p, u32 N){
202905203689
u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
202906203690
char *zNew;
202907203691
if( p->bStatic ){
202908
- if( p->bErr ) return 1;
203692
+ if( p->eErr ) return 1;
202909203693
zNew = sqlite3RCStrNew(nTotal);
202910203694
if( zNew==0 ){
202911
- jsonOom(p);
203695
+ jsonStringOom(p);
202912203696
return SQLITE_NOMEM;
202913203697
}
202914203698
memcpy(zNew, p->zBuf, (size_t)p->nUsed);
202915203699
p->zBuf = zNew;
202916203700
p->bStatic = 0;
202917203701
}else{
202918203702
p->zBuf = sqlite3RCStrResize(p->zBuf, nTotal);
202919203703
if( p->zBuf==0 ){
202920
- p->bErr = 1;
202921
- jsonZero(p);
203704
+ p->eErr |= JSTRING_OOM;
203705
+ jsonStringZero(p);
202922203706
return SQLITE_NOMEM;
202923203707
}
202924203708
}
202925203709
p->nAlloc = nTotal;
202926203710
return SQLITE_OK;
202927203711
}
202928203712
202929203713
/* Append N bytes from zIn onto the end of the JsonString string.
202930203714
*/
202931
-static SQLITE_NOINLINE void jsonAppendExpand(
203715
+static SQLITE_NOINLINE void jsonStringExpandAndAppend(
202932203716
JsonString *p,
202933203717
const char *zIn,
202934203718
u32 N
202935203719
){
202936203720
assert( N>0 );
202937
- if( jsonGrow(p,N) ) return;
203721
+ if( jsonStringGrow(p,N) ) return;
202938203722
memcpy(p->zBuf+p->nUsed, zIn, N);
202939203723
p->nUsed += N;
202940203724
}
202941203725
static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
202942203726
if( N==0 ) return;
202943203727
if( N+p->nUsed >= p->nAlloc ){
202944
- jsonAppendExpand(p,zIn,N);
203728
+ jsonStringExpandAndAppend(p,zIn,N);
202945203729
}else{
202946203730
memcpy(p->zBuf+p->nUsed, zIn, N);
202947203731
p->nUsed += N;
202948203732
}
202949203733
}
202950203734
static void jsonAppendRawNZ(JsonString *p, const char *zIn, u32 N){
202951203735
assert( N>0 );
202952203736
if( N+p->nUsed >= p->nAlloc ){
202953
- jsonAppendExpand(p,zIn,N);
203737
+ jsonStringExpandAndAppend(p,zIn,N);
202954203738
}else{
202955203739
memcpy(p->zBuf+p->nUsed, zIn, N);
202956203740
p->nUsed += N;
202957203741
}
202958203742
}
@@ -202960,21 +203744,21 @@
202960203744
202961203745
/* Append formatted text (not to exceed N bytes) to the JsonString.
202962203746
*/
202963203747
static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
202964203748
va_list ap;
202965
- if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
203749
+ if( (p->nUsed + N >= p->nAlloc) && jsonStringGrow(p, N) ) return;
202966203750
va_start(ap, zFormat);
202967203751
sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
202968203752
va_end(ap);
202969203753
p->nUsed += (int)strlen(p->zBuf+p->nUsed);
202970203754
}
202971203755
202972203756
/* Append a single character
202973203757
*/
202974203758
static SQLITE_NOINLINE void jsonAppendCharExpand(JsonString *p, char c){
202975
- if( jsonGrow(p,1) ) return;
203759
+ if( jsonStringGrow(p,1) ) return;
202976203760
p->zBuf[p->nUsed++] = c;
202977203761
}
202978203762
static void jsonAppendChar(JsonString *p, char c){
202979203763
if( p->nUsed>=p->nAlloc ){
202980203764
jsonAppendCharExpand(p,c);
@@ -202981,27 +203765,30 @@
202981203765
}else{
202982203766
p->zBuf[p->nUsed++] = c;
202983203767
}
202984203768
}
202985203769
202986
-/* Try to force the string to be a zero-terminated RCStr string.
203770
+/* Remove a single character from the end of the string
203771
+*/
203772
+static void jsonStringTrimOneChar(JsonString *p){
203773
+ if( p->eErr==0 ){
203774
+ assert( p->nUsed>0 );
203775
+ p->nUsed--;
203776
+ }
203777
+}
203778
+
203779
+
203780
+/* Make sure there is a zero terminator on p->zBuf[]
202987203781
**
202988203782
** Return true on success. Return false if an OOM prevents this
202989203783
** from happening.
202990203784
*/
202991
-static int jsonForceRCStr(JsonString *p){
203785
+static int jsonStringTerminate(JsonString *p){
202992203786
jsonAppendChar(p, 0);
202993
- if( p->bErr ) return 0;
202994
- p->nUsed--;
202995
- if( p->bStatic==0 ) return 1;
202996
- p->nAlloc = 0;
202997
- p->nUsed++;
202998
- jsonGrow(p, p->nUsed);
202999
- p->nUsed--;
203000
- return p->bStatic==0;
203001
-}
203002
-
203787
+ jsonStringTrimOneChar(p);
203788
+ return p->eErr==0;
203789
+}
203003203790
203004203791
/* Append a comma separator to the output buffer, if the previous
203005203792
** character is not '[' or '{'.
203006203793
*/
203007203794
static void jsonAppendSeparator(JsonString *p){
@@ -203011,25 +203798,70 @@
203011203798
if( c=='[' || c=='{' ) return;
203012203799
jsonAppendChar(p, ',');
203013203800
}
203014203801
203015203802
/* Append the N-byte string in zIn to the end of the JsonString string
203016
-** under construction. Enclose the string in "..." and escape
203017
-** any double-quotes or backslash characters contained within the
203803
+** under construction. Enclose the string in double-quotes ("...") and
203804
+** escape any double-quotes or backslash characters contained within the
203018203805
** string.
203806
+**
203807
+** This routine is a high-runner. There is a measurable performance
203808
+** increase associated with unwinding the jsonIsOk[] loop.
203019203809
*/
203020203810
static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
203021
- u32 i;
203022
- if( zIn==0 || ((N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0) ) return;
203811
+ u32 k;
203812
+ u8 c;
203813
+ const u8 *z = (const u8*)zIn;
203814
+ if( z==0 ) return;
203815
+ if( (N+p->nUsed+2 >= p->nAlloc) && jsonStringGrow(p,N+2)!=0 ) return;
203023203816
p->zBuf[p->nUsed++] = '"';
203024
- for(i=0; i<N; i++){
203025
- unsigned char c = ((unsigned const char*)zIn)[i];
203026
- if( jsonIsOk[c] ){
203027
- p->zBuf[p->nUsed++] = c;
203028
- }else if( c=='"' || c=='\\' ){
203817
+ while( 1 /*exit-by-break*/ ){
203818
+ k = 0;
203819
+ /* The following while() is the 4-way unwound equivalent of
203820
+ **
203821
+ ** while( k<N && jsonIsOk[z[k]] ){ k++; }
203822
+ */
203823
+ while( 1 /* Exit by break */ ){
203824
+ if( k+3>=N ){
203825
+ while( k<N && jsonIsOk[z[k]] ){ k++; }
203826
+ break;
203827
+ }
203828
+ if( !jsonIsOk[z[k]] ){
203829
+ break;
203830
+ }
203831
+ if( !jsonIsOk[z[k+1]] ){
203832
+ k += 1;
203833
+ break;
203834
+ }
203835
+ if( !jsonIsOk[z[k+2]] ){
203836
+ k += 2;
203837
+ break;
203838
+ }
203839
+ if( !jsonIsOk[z[k+3]] ){
203840
+ k += 3;
203841
+ break;
203842
+ }else{
203843
+ k += 4;
203844
+ }
203845
+ }
203846
+ if( k>=N ){
203847
+ if( k>0 ){
203848
+ memcpy(&p->zBuf[p->nUsed], z, k);
203849
+ p->nUsed += k;
203850
+ }
203851
+ break;
203852
+ }
203853
+ if( k>0 ){
203854
+ memcpy(&p->zBuf[p->nUsed], z, k);
203855
+ p->nUsed += k;
203856
+ z += k;
203857
+ N -= k;
203858
+ }
203859
+ c = z[0];
203860
+ if( c=='"' || c=='\\' ){
203029203861
json_simple_escape:
203030
- if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
203862
+ if( (p->nUsed+N+3 > p->nAlloc) && jsonStringGrow(p,N+3)!=0 ) return;
203031203863
p->zBuf[p->nUsed++] = '\\';
203032203864
p->zBuf[p->nUsed++] = c;
203033203865
}else if( c=='\'' ){
203034203866
p->zBuf[p->nUsed++] = c;
203035203867
}else{
@@ -203046,158 +203878,30 @@
203046203878
assert( c>=0 && c<sizeof(aSpecial) );
203047203879
if( aSpecial[c] ){
203048203880
c = aSpecial[c];
203049203881
goto json_simple_escape;
203050203882
}
203051
- if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
203883
+ if( (p->nUsed+N+7 > p->nAlloc) && jsonStringGrow(p,N+7)!=0 ) return;
203052203884
p->zBuf[p->nUsed++] = '\\';
203053203885
p->zBuf[p->nUsed++] = 'u';
203054203886
p->zBuf[p->nUsed++] = '0';
203055203887
p->zBuf[p->nUsed++] = '0';
203056203888
p->zBuf[p->nUsed++] = "0123456789abcdef"[c>>4];
203057203889
p->zBuf[p->nUsed++] = "0123456789abcdef"[c&0xf];
203058203890
}
203891
+ z++;
203892
+ N--;
203059203893
}
203060203894
p->zBuf[p->nUsed++] = '"';
203061203895
assert( p->nUsed<p->nAlloc );
203062203896
}
203063203897
203064203898
/*
203065
-** The zIn[0..N] string is a JSON5 string literal. Append to p a translation
203066
-** of the string literal that standard JSON and that omits all JSON5
203067
-** features.
203068
-*/
203069
-static void jsonAppendNormalizedString(JsonString *p, const char *zIn, u32 N){
203070
- u32 i;
203071
- jsonAppendChar(p, '"');
203072
- zIn++;
203073
- N -= 2;
203074
- while( N>0 ){
203075
- for(i=0; i<N && zIn[i]!='\\' && zIn[i]!='"'; i++){}
203076
- if( i>0 ){
203077
- jsonAppendRawNZ(p, zIn, i);
203078
- zIn += i;
203079
- N -= i;
203080
- if( N==0 ) break;
203081
- }
203082
- if( zIn[0]=='"' ){
203083
- jsonAppendRawNZ(p, "\\\"", 2);
203084
- zIn++;
203085
- N--;
203086
- continue;
203087
- }
203088
- assert( zIn[0]=='\\' );
203089
- switch( (u8)zIn[1] ){
203090
- case '\'':
203091
- jsonAppendChar(p, '\'');
203092
- break;
203093
- case 'v':
203094
- jsonAppendRawNZ(p, "\\u0009", 6);
203095
- break;
203096
- case 'x':
203097
- jsonAppendRawNZ(p, "\\u00", 4);
203098
- jsonAppendRawNZ(p, &zIn[2], 2);
203099
- zIn += 2;
203100
- N -= 2;
203101
- break;
203102
- case '0':
203103
- jsonAppendRawNZ(p, "\\u0000", 6);
203104
- break;
203105
- case '\r':
203106
- if( zIn[2]=='\n' ){
203107
- zIn++;
203108
- N--;
203109
- }
203110
- break;
203111
- case '\n':
203112
- break;
203113
- case 0xe2:
203114
- assert( N>=4 );
203115
- assert( 0x80==(u8)zIn[2] );
203116
- assert( 0xa8==(u8)zIn[3] || 0xa9==(u8)zIn[3] );
203117
- zIn += 2;
203118
- N -= 2;
203119
- break;
203120
- default:
203121
- jsonAppendRawNZ(p, zIn, 2);
203122
- break;
203123
- }
203124
- zIn += 2;
203125
- N -= 2;
203126
- }
203127
- jsonAppendChar(p, '"');
203128
-}
203129
-
203130
-/*
203131
-** The zIn[0..N] string is a JSON5 integer literal. Append to p a translation
203132
-** of the string literal that standard JSON and that omits all JSON5
203133
-** features.
203134
-*/
203135
-static void jsonAppendNormalizedInt(JsonString *p, const char *zIn, u32 N){
203136
- if( zIn[0]=='+' ){
203137
- zIn++;
203138
- N--;
203139
- }else if( zIn[0]=='-' ){
203140
- jsonAppendChar(p, '-');
203141
- zIn++;
203142
- N--;
203143
- }
203144
- if( zIn[0]=='0' && (zIn[1]=='x' || zIn[1]=='X') ){
203145
- sqlite3_int64 i = 0;
203146
- int rc = sqlite3DecOrHexToI64(zIn, &i);
203147
- if( rc<=1 ){
203148
- jsonPrintf(100,p,"%lld",i);
203149
- }else{
203150
- assert( rc==2 );
203151
- jsonAppendRawNZ(p, "9.0e999", 7);
203152
- }
203153
- return;
203154
- }
203155
- assert( N>0 );
203156
- jsonAppendRawNZ(p, zIn, N);
203157
-}
203158
-
203159
-/*
203160
-** The zIn[0..N] string is a JSON5 real literal. Append to p a translation
203161
-** of the string literal that standard JSON and that omits all JSON5
203162
-** features.
203163
-*/
203164
-static void jsonAppendNormalizedReal(JsonString *p, const char *zIn, u32 N){
203165
- u32 i;
203166
- if( zIn[0]=='+' ){
203167
- zIn++;
203168
- N--;
203169
- }else if( zIn[0]=='-' ){
203170
- jsonAppendChar(p, '-');
203171
- zIn++;
203172
- N--;
203173
- }
203174
- if( zIn[0]=='.' ){
203175
- jsonAppendChar(p, '0');
203176
- }
203177
- for(i=0; i<N; i++){
203178
- if( zIn[i]=='.' && (i+1==N || !sqlite3Isdigit(zIn[i+1])) ){
203179
- i++;
203180
- jsonAppendRaw(p, zIn, i);
203181
- zIn += i;
203182
- N -= i;
203183
- jsonAppendChar(p, '0');
203184
- break;
203185
- }
203186
- }
203187
- if( N>0 ){
203188
- jsonAppendRawNZ(p, zIn, N);
203189
- }
203190
-}
203191
-
203192
-
203193
-
203194
-/*
203195
-** Append a function parameter value to the JSON string under
203196
-** construction.
203197
-*/
203198
-static void jsonAppendValue(
203899
+** Append an sqlite3_value (such as a function parameter) to the JSON
203900
+** string under construction in p.
203901
+*/
203902
+static void jsonAppendSqlValue(
203199203903
JsonString *p, /* Append to this JSON string */
203200203904
sqlite3_value *pValue /* Value to append */
203201203905
){
203202203906
switch( sqlite3_value_type(pValue) ){
203203203907
case SQLITE_NULL: {
@@ -203223,591 +203927,147 @@
203223203927
jsonAppendString(p, z, n);
203224203928
}
203225203929
break;
203226203930
}
203227203931
default: {
203228
- if( p->bErr==0 ){
203932
+ if( jsonFuncArgMightBeBinary(pValue) ){
203933
+ JsonParse px;
203934
+ memset(&px, 0, sizeof(px));
203935
+ px.aBlob = (u8*)sqlite3_value_blob(pValue);
203936
+ px.nBlob = sqlite3_value_bytes(pValue);
203937
+ jsonTranslateBlobToText(&px, 0, p);
203938
+ }else if( p->eErr==0 ){
203229203939
sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
203230
- p->bErr = 2;
203231
- jsonReset(p);
203940
+ p->eErr = JSTRING_ERR;
203941
+ jsonStringReset(p);
203232203942
}
203233203943
break;
203234203944
}
203235203945
}
203236203946
}
203237203947
203238
-
203239
-/* Make the JSON in p the result of the SQL function.
203948
+/* Make the text in p (which is probably a generated JSON text string)
203949
+** the result of the SQL function.
203240203950
**
203241
-** The JSON string is reset.
203951
+** The JsonString is reset.
203952
+**
203953
+** If pParse and ctx are both non-NULL, then the SQL string in p is
203954
+** loaded into the zJson field of the pParse object as a RCStr and the
203955
+** pParse is added to the cache.
203242203956
*/
203243
-static void jsonResult(JsonString *p){
203244
- if( p->bErr==0 ){
203245
- if( p->bStatic ){
203957
+static void jsonReturnString(
203958
+ JsonString *p, /* String to return */
203959
+ JsonParse *pParse, /* JSONB source or NULL */
203960
+ sqlite3_context *ctx /* Where to cache */
203961
+){
203962
+ assert( (pParse!=0)==(ctx!=0) );
203963
+ assert( ctx==0 || ctx==p->pCtx );
203964
+ if( p->eErr==0 ){
203965
+ int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(p->pCtx));
203966
+ if( flags & JSON_BLOB ){
203967
+ jsonReturnStringAsBlob(p);
203968
+ }else if( p->bStatic ){
203246203969
sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
203247203970
SQLITE_TRANSIENT, SQLITE_UTF8);
203248
- }else if( jsonForceRCStr(p) ){
203249
- sqlite3RCStrRef(p->zBuf);
203250
- sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
203971
+ }else if( jsonStringTerminate(p) ){
203972
+ if( pParse && pParse->bJsonIsRCStr==0 && pParse->nBlobAlloc>0 ){
203973
+ int rc;
203974
+ pParse->zJson = sqlite3RCStrRef(p->zBuf);
203975
+ pParse->nJson = p->nUsed;
203976
+ pParse->bJsonIsRCStr = 1;
203977
+ rc = jsonCacheInsert(ctx, pParse);
203978
+ if( rc==SQLITE_NOMEM ){
203979
+ sqlite3_result_error_nomem(ctx);
203980
+ jsonStringReset(p);
203981
+ return;
203982
+ }
203983
+ }
203984
+ sqlite3_result_text64(p->pCtx, sqlite3RCStrRef(p->zBuf), p->nUsed,
203251203985
sqlite3RCStrUnref,
203252203986
SQLITE_UTF8);
203987
+ }else{
203988
+ sqlite3_result_error_nomem(p->pCtx);
203253203989
}
203254
- }
203255
- if( p->bErr==1 ){
203990
+ }else if( p->eErr & JSTRING_OOM ){
203256203991
sqlite3_result_error_nomem(p->pCtx);
203992
+ }else if( p->eErr & JSTRING_MALFORMED ){
203993
+ sqlite3_result_error(p->pCtx, "malformed JSON", -1);
203257203994
}
203258
- jsonReset(p);
203995
+ jsonStringReset(p);
203259203996
}
203260203997
203261203998
/**************************************************************************
203262
-** Utility routines for dealing with JsonNode and JsonParse objects
203999
+** Utility routines for dealing with JsonParse objects
203263204000
**************************************************************************/
203264204001
203265
-/*
203266
-** Return the number of consecutive JsonNode slots need to represent
203267
-** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
203268
-** OBJECT types, the number might be larger.
203269
-**
203270
-** Appended elements are not counted. The value returned is the number
203271
-** by which the JsonNode counter should increment in order to go to the
203272
-** next peer value.
203273
-*/
203274
-static u32 jsonNodeSize(JsonNode *pNode){
203275
- return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
203276
-}
203277
-
203278204002
/*
203279204003
** Reclaim all memory allocated by a JsonParse object. But do not
203280204004
** delete the JsonParse object itself.
203281204005
*/
203282204006
static void jsonParseReset(JsonParse *pParse){
203283
- while( pParse->pClup ){
203284
- JsonCleanup *pTask = pParse->pClup;
203285
- pParse->pClup = pTask->pJCNext;
203286
- pTask->xOp(pTask->pArg);
203287
- sqlite3_free(pTask);
203288
- }
203289204007
assert( pParse->nJPRef<=1 );
203290
- if( pParse->aNode ){
203291
- sqlite3_free(pParse->aNode);
203292
- pParse->aNode = 0;
203293
- }
203294
- pParse->nNode = 0;
203295
- pParse->nAlloc = 0;
203296
- if( pParse->aUp ){
203297
- sqlite3_free(pParse->aUp);
203298
- pParse->aUp = 0;
203299
- }
203300204008
if( pParse->bJsonIsRCStr ){
203301204009
sqlite3RCStrUnref(pParse->zJson);
203302204010
pParse->zJson = 0;
204011
+ pParse->nJson = 0;
203303204012
pParse->bJsonIsRCStr = 0;
203304204013
}
203305
- if( pParse->zAlt ){
203306
- sqlite3RCStrUnref(pParse->zAlt);
203307
- pParse->zAlt = 0;
204014
+ if( pParse->nBlobAlloc ){
204015
+ sqlite3DbFree(pParse->db, pParse->aBlob);
204016
+ pParse->aBlob = 0;
204017
+ pParse->nBlob = 0;
204018
+ pParse->nBlobAlloc = 0;
203308204019
}
203309204020
}
203310204021
203311204022
/*
203312
-** Free a JsonParse object that was obtained from sqlite3_malloc().
203313
-**
203314
-** Note that destroying JsonParse might call sqlite3RCStrUnref() to
203315
-** destroy the zJson value. The RCStr object might recursively invoke
203316
-** JsonParse to destroy this pParse object again. Take care to ensure
203317
-** that this recursive destructor sequence terminates harmlessly.
204023
+** Decrement the reference count on the JsonParse object. When the
204024
+** count reaches zero, free the object.
203318204025
*/
203319204026
static void jsonParseFree(JsonParse *pParse){
203320
- if( pParse->nJPRef>1 ){
203321
- pParse->nJPRef--;
203322
- }else{
203323
- jsonParseReset(pParse);
203324
- sqlite3_free(pParse);
203325
- }
203326
-}
203327
-
203328
-/*
203329
-** Add a cleanup task to the JsonParse object.
203330
-**
203331
-** If an OOM occurs, the cleanup operation happens immediately
203332
-** and this function returns SQLITE_NOMEM.
203333
-*/
203334
-static int jsonParseAddCleanup(
203335
- JsonParse *pParse, /* Add the cleanup task to this parser */
203336
- void(*xOp)(void*), /* The cleanup task */
203337
- void *pArg /* Argument to the cleanup */
203338
-){
203339
- JsonCleanup *pTask = sqlite3_malloc64( sizeof(*pTask) );
203340
- if( pTask==0 ){
203341
- pParse->oom = 1;
203342
- xOp(pArg);
203343
- return SQLITE_ERROR;
203344
- }
203345
- pTask->pJCNext = pParse->pClup;
203346
- pParse->pClup = pTask;
203347
- pTask->xOp = xOp;
203348
- pTask->pArg = pArg;
203349
- return SQLITE_OK;
203350
-}
203351
-
203352
-/*
203353
-** Convert the JsonNode pNode into a pure JSON string and
203354
-** append to pOut. Subsubstructure is also included. Return
203355
-** the number of JsonNode objects that are encoded.
203356
-*/
203357
-static void jsonRenderNode(
203358
- JsonParse *pParse, /* the complete parse of the JSON */
203359
- JsonNode *pNode, /* The node to render */
203360
- JsonString *pOut /* Write JSON here */
203361
-){
203362
- assert( pNode!=0 );
203363
- while( (pNode->jnFlags & JNODE_REPLACE)!=0 && pParse->useMod ){
203364
- u32 idx = (u32)(pNode - pParse->aNode);
203365
- u32 i = pParse->iSubst;
203366
- while( 1 /*exit-by-break*/ ){
203367
- assert( i<pParse->nNode );
203368
- assert( pParse->aNode[i].eType==JSON_SUBST );
203369
- assert( pParse->aNode[i].eU==4 );
203370
- assert( pParse->aNode[i].u.iPrev<i );
203371
- if( pParse->aNode[i].n==idx ){
203372
- pNode = &pParse->aNode[i+1];
203373
- break;
203374
- }
203375
- i = pParse->aNode[i].u.iPrev;
203376
- }
203377
- }
203378
- switch( pNode->eType ){
203379
- default: {
203380
- assert( pNode->eType==JSON_NULL );
203381
- jsonAppendRawNZ(pOut, "null", 4);
203382
- break;
203383
- }
203384
- case JSON_TRUE: {
203385
- jsonAppendRawNZ(pOut, "true", 4);
203386
- break;
203387
- }
203388
- case JSON_FALSE: {
203389
- jsonAppendRawNZ(pOut, "false", 5);
203390
- break;
203391
- }
203392
- case JSON_STRING: {
203393
- assert( pNode->eU==1 );
203394
- if( pNode->jnFlags & JNODE_RAW ){
203395
- if( pNode->jnFlags & JNODE_LABEL ){
203396
- jsonAppendChar(pOut, '"');
203397
- jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
203398
- jsonAppendChar(pOut, '"');
203399
- }else{
203400
- jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
203401
- }
203402
- }else if( pNode->jnFlags & JNODE_JSON5 ){
203403
- jsonAppendNormalizedString(pOut, pNode->u.zJContent, pNode->n);
203404
- }else{
203405
- assert( pNode->n>0 );
203406
- jsonAppendRawNZ(pOut, pNode->u.zJContent, pNode->n);
203407
- }
203408
- break;
203409
- }
203410
- case JSON_REAL: {
203411
- assert( pNode->eU==1 );
203412
- if( pNode->jnFlags & JNODE_JSON5 ){
203413
- jsonAppendNormalizedReal(pOut, pNode->u.zJContent, pNode->n);
203414
- }else{
203415
- assert( pNode->n>0 );
203416
- jsonAppendRawNZ(pOut, pNode->u.zJContent, pNode->n);
203417
- }
203418
- break;
203419
- }
203420
- case JSON_INT: {
203421
- assert( pNode->eU==1 );
203422
- if( pNode->jnFlags & JNODE_JSON5 ){
203423
- jsonAppendNormalizedInt(pOut, pNode->u.zJContent, pNode->n);
203424
- }else{
203425
- assert( pNode->n>0 );
203426
- jsonAppendRawNZ(pOut, pNode->u.zJContent, pNode->n);
203427
- }
203428
- break;
203429
- }
203430
- case JSON_ARRAY: {
203431
- u32 j = 1;
203432
- jsonAppendChar(pOut, '[');
203433
- for(;;){
203434
- while( j<=pNode->n ){
203435
- if( (pNode[j].jnFlags & JNODE_REMOVE)==0 || pParse->useMod==0 ){
203436
- jsonAppendSeparator(pOut);
203437
- jsonRenderNode(pParse, &pNode[j], pOut);
203438
- }
203439
- j += jsonNodeSize(&pNode[j]);
203440
- }
203441
- if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
203442
- if( pParse->useMod==0 ) break;
203443
- assert( pNode->eU==2 );
203444
- pNode = &pParse->aNode[pNode->u.iAppend];
203445
- j = 1;
203446
- }
203447
- jsonAppendChar(pOut, ']');
203448
- break;
203449
- }
203450
- case JSON_OBJECT: {
203451
- u32 j = 1;
203452
- jsonAppendChar(pOut, '{');
203453
- for(;;){
203454
- while( j<=pNode->n ){
203455
- if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 || pParse->useMod==0 ){
203456
- jsonAppendSeparator(pOut);
203457
- jsonRenderNode(pParse, &pNode[j], pOut);
203458
- jsonAppendChar(pOut, ':');
203459
- jsonRenderNode(pParse, &pNode[j+1], pOut);
203460
- }
203461
- j += 1 + jsonNodeSize(&pNode[j+1]);
203462
- }
203463
- if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
203464
- if( pParse->useMod==0 ) break;
203465
- assert( pNode->eU==2 );
203466
- pNode = &pParse->aNode[pNode->u.iAppend];
203467
- j = 1;
203468
- }
203469
- jsonAppendChar(pOut, '}');
203470
- break;
203471
- }
203472
- }
203473
-}
203474
-
203475
-/*
203476
-** Return a JsonNode and all its descendants as a JSON string.
203477
-*/
203478
-static void jsonReturnJson(
203479
- JsonParse *pParse, /* The complete JSON */
203480
- JsonNode *pNode, /* Node to return */
203481
- sqlite3_context *pCtx, /* Return value for this function */
203482
- int bGenerateAlt, /* Also store the rendered text in zAlt */
203483
- int omitSubtype /* Do not call sqlite3_result_subtype() */
203484
-){
203485
- JsonString s;
203486
- if( pParse->oom ){
203487
- sqlite3_result_error_nomem(pCtx);
203488
- return;
203489
- }
203490
- if( pParse->nErr==0 ){
203491
- jsonInit(&s, pCtx);
203492
- jsonRenderNode(pParse, pNode, &s);
203493
- if( bGenerateAlt && pParse->zAlt==0 && jsonForceRCStr(&s) ){
203494
- pParse->zAlt = sqlite3RCStrRef(s.zBuf);
203495
- pParse->nAlt = s.nUsed;
203496
- }
203497
- jsonResult(&s);
203498
- if( !omitSubtype ) sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
203499
- }
203500
-}
204027
+ if( pParse ){
204028
+ if( pParse->nJPRef>1 ){
204029
+ pParse->nJPRef--;
204030
+ }else{
204031
+ jsonParseReset(pParse);
204032
+ sqlite3DbFree(pParse->db, pParse);
204033
+ }
204034
+ }
204035
+}
204036
+
204037
+/**************************************************************************
204038
+** Utility routines for the JSON text parser
204039
+**************************************************************************/
203501204040
203502204041
/*
203503204042
** Translate a single byte of Hex into an integer.
203504
-** This routine only works if h really is a valid hexadecimal
203505
-** character: 0..9a..fA..F
204043
+** This routine only gives a correct answer if h really is a valid hexadecimal
204044
+** character: 0..9a..fA..F. But unlike sqlite3HexToInt(), it does not
204045
+** assert() if the digit is not hex.
203506204046
*/
203507204047
static u8 jsonHexToInt(int h){
203508
- assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
204048
+#ifdef SQLITE_ASCII
204049
+ h += 9*(1&(h>>6));
204050
+#endif
203509204051
#ifdef SQLITE_EBCDIC
203510204052
h += 9*(1&~(h>>4));
203511
-#else
203512
- h += 9*(1&(h>>6));
203513204053
#endif
203514204054
return (u8)(h & 0xf);
203515204055
}
203516204056
203517204057
/*
203518204058
** Convert a 4-byte hex string into an integer
203519204059
*/
203520204060
static u32 jsonHexToInt4(const char *z){
203521204061
u32 v;
203522
- assert( sqlite3Isxdigit(z[0]) );
203523
- assert( sqlite3Isxdigit(z[1]) );
203524
- assert( sqlite3Isxdigit(z[2]) );
203525
- assert( sqlite3Isxdigit(z[3]) );
203526204062
v = (jsonHexToInt(z[0])<<12)
203527204063
+ (jsonHexToInt(z[1])<<8)
203528204064
+ (jsonHexToInt(z[2])<<4)
203529204065
+ jsonHexToInt(z[3]);
203530204066
return v;
203531204067
}
203532204068
203533
-/*
203534
-** Make the JsonNode the return value of the function.
203535
-*/
203536
-static void jsonReturn(
203537
- JsonParse *pParse, /* Complete JSON parse tree */
203538
- JsonNode *pNode, /* Node to return */
203539
- sqlite3_context *pCtx, /* Return value for this function */
203540
- int omitSubtype /* Do not call sqlite3_result_subtype() */
203541
-){
203542
- switch( pNode->eType ){
203543
- default: {
203544
- assert( pNode->eType==JSON_NULL );
203545
- sqlite3_result_null(pCtx);
203546
- break;
203547
- }
203548
- case JSON_TRUE: {
203549
- sqlite3_result_int(pCtx, 1);
203550
- break;
203551
- }
203552
- case JSON_FALSE: {
203553
- sqlite3_result_int(pCtx, 0);
203554
- break;
203555
- }
203556
- case JSON_INT: {
203557
- sqlite3_int64 i = 0;
203558
- int rc;
203559
- int bNeg = 0;
203560
- const char *z;
203561
-
203562
- assert( pNode->eU==1 );
203563
- z = pNode->u.zJContent;
203564
- if( z[0]=='-' ){ z++; bNeg = 1; }
203565
- else if( z[0]=='+' ){ z++; }
203566
- rc = sqlite3DecOrHexToI64(z, &i);
203567
- if( rc<=1 ){
203568
- sqlite3_result_int64(pCtx, bNeg ? -i : i);
203569
- }else if( rc==3 && bNeg ){
203570
- sqlite3_result_int64(pCtx, SMALLEST_INT64);
203571
- }else{
203572
- goto to_double;
203573
- }
203574
- break;
203575
- }
203576
- case JSON_REAL: {
203577
- double r;
203578
- const char *z;
203579
- assert( pNode->eU==1 );
203580
- to_double:
203581
- z = pNode->u.zJContent;
203582
- sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
203583
- sqlite3_result_double(pCtx, r);
203584
- break;
203585
- }
203586
- case JSON_STRING: {
203587
- if( pNode->jnFlags & JNODE_RAW ){
203588
- assert( pNode->eU==1 );
203589
- sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
203590
- SQLITE_TRANSIENT);
203591
- }else if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
203592
- /* JSON formatted without any backslash-escapes */
203593
- assert( pNode->eU==1 );
203594
- sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
203595
- SQLITE_TRANSIENT);
203596
- }else{
203597
- /* Translate JSON formatted string into raw text */
203598
- u32 i;
203599
- u32 n = pNode->n;
203600
- const char *z;
203601
- char *zOut;
203602
- u32 j;
203603
- u32 nOut = n;
203604
- assert( pNode->eU==1 );
203605
- z = pNode->u.zJContent;
203606
- zOut = sqlite3_malloc( nOut+1 );
203607
- if( zOut==0 ){
203608
- sqlite3_result_error_nomem(pCtx);
203609
- break;
203610
- }
203611
- for(i=1, j=0; i<n-1; i++){
203612
- char c = z[i];
203613
- if( c=='\\' ){
203614
- c = z[++i];
203615
- if( c=='u' ){
203616
- u32 v = jsonHexToInt4(z+i+1);
203617
- i += 4;
203618
- if( v==0 ) break;
203619
- if( v<=0x7f ){
203620
- zOut[j++] = (char)v;
203621
- }else if( v<=0x7ff ){
203622
- zOut[j++] = (char)(0xc0 | (v>>6));
203623
- zOut[j++] = 0x80 | (v&0x3f);
203624
- }else{
203625
- u32 vlo;
203626
- if( (v&0xfc00)==0xd800
203627
- && i<n-6
203628
- && z[i+1]=='\\'
203629
- && z[i+2]=='u'
203630
- && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
203631
- ){
203632
- /* We have a surrogate pair */
203633
- v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
203634
- i += 6;
203635
- zOut[j++] = 0xf0 | (v>>18);
203636
- zOut[j++] = 0x80 | ((v>>12)&0x3f);
203637
- zOut[j++] = 0x80 | ((v>>6)&0x3f);
203638
- zOut[j++] = 0x80 | (v&0x3f);
203639
- }else{
203640
- zOut[j++] = 0xe0 | (v>>12);
203641
- zOut[j++] = 0x80 | ((v>>6)&0x3f);
203642
- zOut[j++] = 0x80 | (v&0x3f);
203643
- }
203644
- }
203645
- continue;
203646
- }else if( c=='b' ){
203647
- c = '\b';
203648
- }else if( c=='f' ){
203649
- c = '\f';
203650
- }else if( c=='n' ){
203651
- c = '\n';
203652
- }else if( c=='r' ){
203653
- c = '\r';
203654
- }else if( c=='t' ){
203655
- c = '\t';
203656
- }else if( c=='v' ){
203657
- c = '\v';
203658
- }else if( c=='\'' || c=='"' || c=='/' || c=='\\' ){
203659
- /* pass through unchanged */
203660
- }else if( c=='0' ){
203661
- c = 0;
203662
- }else if( c=='x' ){
203663
- c = (jsonHexToInt(z[i+1])<<4) | jsonHexToInt(z[i+2]);
203664
- i += 2;
203665
- }else if( c=='\r' && z[i+1]=='\n' ){
203666
- i++;
203667
- continue;
203668
- }else if( 0xe2==(u8)c ){
203669
- assert( 0x80==(u8)z[i+1] );
203670
- assert( 0xa8==(u8)z[i+2] || 0xa9==(u8)z[i+2] );
203671
- i += 2;
203672
- continue;
203673
- }else{
203674
- continue;
203675
- }
203676
- } /* end if( c=='\\' ) */
203677
- zOut[j++] = c;
203678
- } /* end for() */
203679
- zOut[j] = 0;
203680
- sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
203681
- }
203682
- break;
203683
- }
203684
- case JSON_ARRAY:
203685
- case JSON_OBJECT: {
203686
- jsonReturnJson(pParse, pNode, pCtx, 0, omitSubtype);
203687
- break;
203688
- }
203689
- }
203690
-}
203691
-
203692
-/* Forward reference */
203693
-static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
203694
-
203695
-/*
203696
-** A macro to hint to the compiler that a function should not be
203697
-** inlined.
203698
-*/
203699
-#if defined(__GNUC__)
203700
-# define JSON_NOINLINE __attribute__((noinline))
203701
-#elif defined(_MSC_VER) && _MSC_VER>=1310
203702
-# define JSON_NOINLINE __declspec(noinline)
203703
-#else
203704
-# define JSON_NOINLINE
203705
-#endif
203706
-
203707
-
203708
-/*
203709
-** Add a single node to pParse->aNode after first expanding the
203710
-** size of the aNode array. Return the index of the new node.
203711
-**
203712
-** If an OOM error occurs, set pParse->oom and return -1.
203713
-*/
203714
-static JSON_NOINLINE int jsonParseAddNodeExpand(
203715
- JsonParse *pParse, /* Append the node to this object */
203716
- u32 eType, /* Node type */
203717
- u32 n, /* Content size or sub-node count */
203718
- const char *zContent /* Content */
203719
-){
203720
- u32 nNew;
203721
- JsonNode *pNew;
203722
- assert( pParse->nNode>=pParse->nAlloc );
203723
- if( pParse->oom ) return -1;
203724
- nNew = pParse->nAlloc*2 + 10;
203725
- pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
203726
- if( pNew==0 ){
203727
- pParse->oom = 1;
203728
- return -1;
203729
- }
203730
- pParse->nAlloc = sqlite3_msize(pNew)/sizeof(JsonNode);
203731
- pParse->aNode = pNew;
203732
- assert( pParse->nNode<pParse->nAlloc );
203733
- return jsonParseAddNode(pParse, eType, n, zContent);
203734
-}
203735
-
203736
-/*
203737
-** Create a new JsonNode instance based on the arguments and append that
203738
-** instance to the JsonParse. Return the index in pParse->aNode[] of the
203739
-** new node, or -1 if a memory allocation fails.
203740
-*/
203741
-static int jsonParseAddNode(
203742
- JsonParse *pParse, /* Append the node to this object */
203743
- u32 eType, /* Node type */
203744
- u32 n, /* Content size or sub-node count */
203745
- const char *zContent /* Content */
203746
-){
203747
- JsonNode *p;
203748
- assert( pParse->aNode!=0 || pParse->nNode>=pParse->nAlloc );
203749
- if( pParse->nNode>=pParse->nAlloc ){
203750
- return jsonParseAddNodeExpand(pParse, eType, n, zContent);
203751
- }
203752
- assert( pParse->aNode!=0 );
203753
- p = &pParse->aNode[pParse->nNode];
203754
- assert( p!=0 );
203755
- p->eType = (u8)(eType & 0xff);
203756
- p->jnFlags = (u8)(eType >> 8);
203757
- VVA( p->eU = zContent ? 1 : 0 );
203758
- p->n = n;
203759
- p->u.zJContent = zContent;
203760
- return pParse->nNode++;
203761
-}
203762
-
203763
-/*
203764
-** Add an array of new nodes to the current pParse->aNode array.
203765
-** Return the index of the first node added.
203766
-**
203767
-** If an OOM error occurs, set pParse->oom.
203768
-*/
203769
-static void jsonParseAddNodeArray(
203770
- JsonParse *pParse, /* Append the node to this object */
203771
- JsonNode *aNode, /* Array of nodes to add */
203772
- u32 nNode /* Number of elements in aNew */
203773
-){
203774
- assert( aNode!=0 );
203775
- assert( nNode>=1 );
203776
- if( pParse->nNode + nNode > pParse->nAlloc ){
203777
- u32 nNew = pParse->nNode + nNode;
203778
- JsonNode *aNew = sqlite3_realloc64(pParse->aNode, nNew*sizeof(JsonNode));
203779
- if( aNew==0 ){
203780
- pParse->oom = 1;
203781
- return;
203782
- }
203783
- pParse->nAlloc = sqlite3_msize(aNew)/sizeof(JsonNode);
203784
- pParse->aNode = aNew;
203785
- }
203786
- memcpy(&pParse->aNode[pParse->nNode], aNode, nNode*sizeof(JsonNode));
203787
- pParse->nNode += nNode;
203788
-}
203789
-
203790
-/*
203791
-** Add a new JSON_SUBST node. The node immediately following
203792
-** this new node will be the substitute content for iNode.
203793
-*/
203794
-static int jsonParseAddSubstNode(
203795
- JsonParse *pParse, /* Add the JSON_SUBST here */
203796
- u32 iNode /* References this node */
203797
-){
203798
- int idx = jsonParseAddNode(pParse, JSON_SUBST, iNode, 0);
203799
- if( pParse->oom ) return -1;
203800
- pParse->aNode[iNode].jnFlags |= JNODE_REPLACE;
203801
- pParse->aNode[idx].eU = 4;
203802
- pParse->aNode[idx].u.iPrev = pParse->iSubst;
203803
- pParse->iSubst = idx;
203804
- pParse->hasMod = 1;
203805
- pParse->useMod = 1;
203806
- return idx;
203807
-}
203808
-
203809204069
/*
203810204070
** Return true if z[] begins with 2 (or more) hexadecimal digits
203811204071
*/
203812204072
static int jsonIs2Hex(const char *z){
203813204073
return sqlite3Isxdigit(z[0]) && sqlite3Isxdigit(z[1]);
@@ -203957,101 +204217,538 @@
203957204217
char eType;
203958204218
char nRepl;
203959204219
char *zMatch;
203960204220
char *zRepl;
203961204221
} aNanInfName[] = {
203962
- { 'i', 'I', 3, JSON_REAL, 7, "inf", "9.0e999" },
203963
- { 'i', 'I', 8, JSON_REAL, 7, "infinity", "9.0e999" },
203964
- { 'n', 'N', 3, JSON_NULL, 4, "NaN", "null" },
203965
- { 'q', 'Q', 4, JSON_NULL, 4, "QNaN", "null" },
203966
- { 's', 'S', 4, JSON_NULL, 4, "SNaN", "null" },
203967
-};
203968
-
203969
-/*
203970
-** Parse a single JSON value which begins at pParse->zJson[i]. Return the
203971
-** index of the first character past the end of the value parsed.
203972
-**
203973
-** Special return values:
204222
+ { 'i', 'I', 3, JSONB_FLOAT, 7, "inf", "9.0e999" },
204223
+ { 'i', 'I', 8, JSONB_FLOAT, 7, "infinity", "9.0e999" },
204224
+ { 'n', 'N', 3, JSONB_NULL, 4, "NaN", "null" },
204225
+ { 'q', 'Q', 4, JSONB_NULL, 4, "QNaN", "null" },
204226
+ { 's', 'S', 4, JSONB_NULL, 4, "SNaN", "null" },
204227
+};
204228
+
204229
+
204230
+/*
204231
+** Report the wrong number of arguments for json_insert(), json_replace()
204232
+** or json_set().
204233
+*/
204234
+static void jsonWrongNumArgs(
204235
+ sqlite3_context *pCtx,
204236
+ const char *zFuncName
204237
+){
204238
+ char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
204239
+ zFuncName);
204240
+ sqlite3_result_error(pCtx, zMsg, -1);
204241
+ sqlite3_free(zMsg);
204242
+}
204243
+
204244
+/****************************************************************************
204245
+** Utility routines for dealing with the binary BLOB representation of JSON
204246
+****************************************************************************/
204247
+
204248
+/*
204249
+** Expand pParse->aBlob so that it holds at least N bytes.
204250
+**
204251
+** Return the number of errors.
204252
+*/
204253
+static int jsonBlobExpand(JsonParse *pParse, u32 N){
204254
+ u8 *aNew;
204255
+ u32 t;
204256
+ assert( N>pParse->nBlobAlloc );
204257
+ if( pParse->nBlobAlloc==0 ){
204258
+ t = 100;
204259
+ }else{
204260
+ t = pParse->nBlobAlloc*2;
204261
+ }
204262
+ if( t<N ) t = N+100;
204263
+ aNew = sqlite3DbRealloc(pParse->db, pParse->aBlob, t);
204264
+ if( aNew==0 ){ pParse->oom = 1; return 1; }
204265
+ pParse->aBlob = aNew;
204266
+ pParse->nBlobAlloc = t;
204267
+ return 0;
204268
+}
204269
+
204270
+/*
204271
+** If pParse->aBlob is not previously editable (because it is taken
204272
+** from sqlite3_value_blob(), as indicated by the fact that
204273
+** pParse->nBlobAlloc==0 and pParse->nBlob>0) then make it editable
204274
+** by making a copy into space obtained from malloc.
204275
+**
204276
+** Return true on success. Return false on OOM.
204277
+*/
204278
+static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){
204279
+ u8 *aOld;
204280
+ u32 nSize;
204281
+ assert( !pParse->bReadOnly );
204282
+ if( pParse->oom ) return 0;
204283
+ if( pParse->nBlobAlloc>0 ) return 1;
204284
+ aOld = pParse->aBlob;
204285
+ nSize = pParse->nBlob + nExtra;
204286
+ pParse->aBlob = 0;
204287
+ if( jsonBlobExpand(pParse, nSize) ){
204288
+ return 0;
204289
+ }
204290
+ assert( pParse->nBlobAlloc >= pParse->nBlob + nExtra );
204291
+ memcpy(pParse->aBlob, aOld, pParse->nBlob);
204292
+ return 1;
204293
+}
204294
+
204295
+/* Expand pParse->aBlob and append one bytes.
204296
+*/
204297
+static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte(
204298
+ JsonParse *pParse,
204299
+ u8 c
204300
+){
204301
+ jsonBlobExpand(pParse, pParse->nBlob+1);
204302
+ if( pParse->oom==0 ){
204303
+ assert( pParse->nBlob+1<=pParse->nBlobAlloc );
204304
+ pParse->aBlob[pParse->nBlob++] = c;
204305
+ }
204306
+}
204307
+
204308
+/* Append a single character.
204309
+*/
204310
+static void jsonBlobAppendOneByte(JsonParse *pParse, u8 c){
204311
+ if( pParse->nBlob >= pParse->nBlobAlloc ){
204312
+ jsonBlobExpandAndAppendOneByte(pParse, c);
204313
+ }else{
204314
+ pParse->aBlob[pParse->nBlob++] = c;
204315
+ }
204316
+}
204317
+
204318
+/* Slow version of jsonBlobAppendNode() that first resizes the
204319
+** pParse->aBlob structure.
204320
+*/
204321
+static void jsonBlobAppendNode(JsonParse*,u8,u32,const void*);
204322
+static SQLITE_NOINLINE void jsonBlobExpandAndAppendNode(
204323
+ JsonParse *pParse,
204324
+ u8 eType,
204325
+ u32 szPayload,
204326
+ const void *aPayload
204327
+){
204328
+ if( jsonBlobExpand(pParse, pParse->nBlob+szPayload+9) ) return;
204329
+ jsonBlobAppendNode(pParse, eType, szPayload, aPayload);
204330
+}
204331
+
204332
+
204333
+/* Append an node type byte together with the payload size and
204334
+** possibly also the payload.
204335
+**
204336
+** If aPayload is not NULL, then it is a pointer to the payload which
204337
+** is also appended. If aPayload is NULL, the pParse->aBlob[] array
204338
+** is resized (if necessary) so that it is big enough to hold the
204339
+** payload, but the payload is not appended and pParse->nBlob is left
204340
+** pointing to where the first byte of payload will eventually be.
204341
+*/
204342
+static void jsonBlobAppendNode(
204343
+ JsonParse *pParse, /* The JsonParse object under construction */
204344
+ u8 eType, /* Node type. One of JSONB_* */
204345
+ u32 szPayload, /* Number of bytes of payload */
204346
+ const void *aPayload /* The payload. Might be NULL */
204347
+){
204348
+ u8 *a;
204349
+ if( pParse->nBlob+szPayload+9 > pParse->nBlobAlloc ){
204350
+ jsonBlobExpandAndAppendNode(pParse,eType,szPayload,aPayload);
204351
+ return;
204352
+ }
204353
+ assert( pParse->aBlob!=0 );
204354
+ a = &pParse->aBlob[pParse->nBlob];
204355
+ if( szPayload<=11 ){
204356
+ a[0] = eType | (szPayload<<4);
204357
+ pParse->nBlob += 1;
204358
+ }else if( szPayload<=0xff ){
204359
+ a[0] = eType | 0xc0;
204360
+ a[1] = szPayload & 0xff;
204361
+ pParse->nBlob += 2;
204362
+ }else if( szPayload<=0xffff ){
204363
+ a[0] = eType | 0xd0;
204364
+ a[1] = (szPayload >> 8) & 0xff;
204365
+ a[2] = szPayload & 0xff;
204366
+ pParse->nBlob += 3;
204367
+ }else{
204368
+ a[0] = eType | 0xe0;
204369
+ a[1] = (szPayload >> 24) & 0xff;
204370
+ a[2] = (szPayload >> 16) & 0xff;
204371
+ a[3] = (szPayload >> 8) & 0xff;
204372
+ a[4] = szPayload & 0xff;
204373
+ pParse->nBlob += 5;
204374
+ }
204375
+ if( aPayload ){
204376
+ pParse->nBlob += szPayload;
204377
+ memcpy(&pParse->aBlob[pParse->nBlob-szPayload], aPayload, szPayload);
204378
+ }
204379
+}
204380
+
204381
+/* Change the payload size for the node at index i to be szPayload.
204382
+*/
204383
+static int jsonBlobChangePayloadSize(
204384
+ JsonParse *pParse,
204385
+ u32 i,
204386
+ u32 szPayload
204387
+){
204388
+ u8 *a;
204389
+ u8 szType;
204390
+ u8 nExtra;
204391
+ u8 nNeeded;
204392
+ int delta;
204393
+ if( pParse->oom ) return 0;
204394
+ a = &pParse->aBlob[i];
204395
+ szType = a[0]>>4;
204396
+ if( szType<=11 ){
204397
+ nExtra = 0;
204398
+ }else if( szType==12 ){
204399
+ nExtra = 1;
204400
+ }else if( szType==13 ){
204401
+ nExtra = 2;
204402
+ }else{
204403
+ nExtra = 4;
204404
+ }
204405
+ if( szPayload<=11 ){
204406
+ nNeeded = 0;
204407
+ }else if( szPayload<=0xff ){
204408
+ nNeeded = 1;
204409
+ }else if( szPayload<=0xffff ){
204410
+ nNeeded = 2;
204411
+ }else{
204412
+ nNeeded = 4;
204413
+ }
204414
+ delta = nNeeded - nExtra;
204415
+ if( delta ){
204416
+ u32 newSize = pParse->nBlob + delta;
204417
+ if( delta>0 ){
204418
+ if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){
204419
+ return 0; /* OOM error. Error state recorded in pParse->oom. */
204420
+ }
204421
+ a = &pParse->aBlob[i];
204422
+ memmove(&a[1+delta], &a[1], pParse->nBlob - (i+1));
204423
+ }else{
204424
+ memmove(&a[1], &a[1-delta], pParse->nBlob - (i+1-delta));
204425
+ }
204426
+ pParse->nBlob = newSize;
204427
+ }
204428
+ if( nNeeded==0 ){
204429
+ a[0] = (a[0] & 0x0f) | (szPayload<<4);
204430
+ }else if( nNeeded==1 ){
204431
+ a[0] = (a[0] & 0x0f) | 0xc0;
204432
+ a[1] = szPayload & 0xff;
204433
+ }else if( nNeeded==2 ){
204434
+ a[0] = (a[0] & 0x0f) | 0xd0;
204435
+ a[1] = (szPayload >> 8) & 0xff;
204436
+ a[2] = szPayload & 0xff;
204437
+ }else{
204438
+ a[0] = (a[0] & 0x0f) | 0xe0;
204439
+ a[1] = (szPayload >> 24) & 0xff;
204440
+ a[2] = (szPayload >> 16) & 0xff;
204441
+ a[3] = (szPayload >> 8) & 0xff;
204442
+ a[4] = szPayload & 0xff;
204443
+ }
204444
+ return delta;
204445
+}
204446
+
204447
+/*
204448
+** If z[0] is 'u' and is followed by exactly 4 hexadecimal character,
204449
+** then set *pOp to JSONB_TEXTJ and return true. If not, do not make
204450
+** any changes to *pOp and return false.
204451
+*/
204452
+static int jsonIs4HexB(const char *z, int *pOp){
204453
+ if( z[0]!='u' ) return 0;
204454
+ if( !jsonIs4Hex(&z[1]) ) return 0;
204455
+ *pOp = JSONB_TEXTJ;
204456
+ return 1;
204457
+}
204458
+
204459
+/*
204460
+** Check a single element of the JSONB in pParse for validity.
204461
+**
204462
+** The element to be checked starts at offset i and must end at on the
204463
+** last byte before iEnd.
204464
+**
204465
+** Return 0 if everything is correct. Return the 1-based byte offset of the
204466
+** error if a problem is detected. (In other words, if the error is at offset
204467
+** 0, return 1).
204468
+*/
204469
+static u32 jsonbValidityCheck(
204470
+ const JsonParse *pParse, /* Input JSONB. Only aBlob and nBlob are used */
204471
+ u32 i, /* Start of element as pParse->aBlob[i] */
204472
+ u32 iEnd, /* One more than the last byte of the element */
204473
+ u32 iDepth /* Current nesting depth */
204474
+){
204475
+ u32 n, sz, j, k;
204476
+ const u8 *z;
204477
+ u8 x;
204478
+ if( iDepth>JSON_MAX_DEPTH ) return i+1;
204479
+ sz = 0;
204480
+ n = jsonbPayloadSize(pParse, i, &sz);
204481
+ if( NEVER(n==0) ) return i+1; /* Checked by caller */
204482
+ if( NEVER(i+n+sz!=iEnd) ) return i+1; /* Checked by caller */
204483
+ z = pParse->aBlob;
204484
+ x = z[i] & 0x0f;
204485
+ switch( x ){
204486
+ case JSONB_NULL:
204487
+ case JSONB_TRUE:
204488
+ case JSONB_FALSE: {
204489
+ return n+sz==1 ? 0 : i+1;
204490
+ }
204491
+ case JSONB_INT: {
204492
+ if( sz<1 ) return i+1;
204493
+ j = i+n;
204494
+ if( z[j]=='-' ){
204495
+ j++;
204496
+ if( sz<2 ) return i+1;
204497
+ }
204498
+ k = i+n+sz;
204499
+ while( j<k ){
204500
+ if( sqlite3Isdigit(z[j]) ){
204501
+ j++;
204502
+ }else{
204503
+ return j+1;
204504
+ }
204505
+ }
204506
+ return 0;
204507
+ }
204508
+ case JSONB_INT5: {
204509
+ if( sz<3 ) return i+1;
204510
+ j = i+n;
204511
+ if( z[j]=='-' ){
204512
+ if( sz<4 ) return i+1;
204513
+ j++;
204514
+ }
204515
+ if( z[j]!='0' ) return i+1;
204516
+ if( z[j+1]!='x' && z[j+1]!='X' ) return j+2;
204517
+ j += 2;
204518
+ k = i+n+sz;
204519
+ while( j<k ){
204520
+ if( sqlite3Isxdigit(z[j]) ){
204521
+ j++;
204522
+ }else{
204523
+ return j+1;
204524
+ }
204525
+ }
204526
+ return 0;
204527
+ }
204528
+ case JSONB_FLOAT:
204529
+ case JSONB_FLOAT5: {
204530
+ u8 seen = 0; /* 0: initial. 1: '.' seen 2: 'e' seen */
204531
+ if( sz<2 ) return i+1;
204532
+ j = i+n;
204533
+ k = j+sz;
204534
+ if( z[j]=='-' ){
204535
+ j++;
204536
+ if( sz<3 ) return i+1;
204537
+ }
204538
+ if( z[j]=='.' ){
204539
+ if( x==JSONB_FLOAT ) return j+1;
204540
+ if( !sqlite3Isdigit(z[j+1]) ) return j+1;
204541
+ j += 2;
204542
+ seen = 1;
204543
+ }else if( z[j]=='0' && x==JSONB_FLOAT ){
204544
+ if( j+3>k ) return j+1;
204545
+ if( z[j+1]!='.' && z[j+1]!='e' && z[j+1]!='E' ) return j+1;
204546
+ j++;
204547
+ }
204548
+ for(; j<k; j++){
204549
+ if( sqlite3Isdigit(z[j]) ) continue;
204550
+ if( z[j]=='.' ){
204551
+ if( seen>0 ) return j+1;
204552
+ if( x==JSONB_FLOAT && (j==k-1 || !sqlite3Isdigit(z[j+1])) ){
204553
+ return j+1;
204554
+ }
204555
+ seen = 1;
204556
+ continue;
204557
+ }
204558
+ if( z[j]=='e' || z[j]=='E' ){
204559
+ if( seen==2 ) return j+1;
204560
+ if( j==k-1 ) return j+1;
204561
+ if( z[j+1]=='+' || z[j+1]=='-' ){
204562
+ j++;
204563
+ if( j==k-1 ) return j+1;
204564
+ }
204565
+ seen = 2;
204566
+ continue;
204567
+ }
204568
+ return j+1;
204569
+ }
204570
+ if( seen==0 ) return i+1;
204571
+ return 0;
204572
+ }
204573
+ case JSONB_TEXT: {
204574
+ j = i+n;
204575
+ k = j+sz;
204576
+ while( j<k ){
204577
+ if( !jsonIsOk[z[j]] && z[j]!='\'' ) return j+1;
204578
+ j++;
204579
+ }
204580
+ return 0;
204581
+ }
204582
+ case JSONB_TEXTJ:
204583
+ case JSONB_TEXT5: {
204584
+ j = i+n;
204585
+ k = j+sz;
204586
+ while( j<k ){
204587
+ if( !jsonIsOk[z[j]] && z[j]!='\'' ){
204588
+ if( z[j]=='"' ){
204589
+ if( x==JSONB_TEXTJ ) return j+1;
204590
+ }else if( z[j]!='\\' || j+1>=k ){
204591
+ return j+1;
204592
+ }else if( strchr("\"\\/bfnrt",z[j+1])!=0 ){
204593
+ j++;
204594
+ }else if( z[j+1]=='u' ){
204595
+ if( j+5>=k ) return j+1;
204596
+ if( !jsonIs4Hex((const char*)&z[j+2]) ) return j+1;
204597
+ j++;
204598
+ }else if( x!=JSONB_TEXT5 ){
204599
+ return j+1;
204600
+ }else{
204601
+ u32 c = 0;
204602
+ u32 szC = jsonUnescapeOneChar((const char*)&z[j], k-j, &c);
204603
+ if( c==JSON_INVALID_CHAR ) return j+1;
204604
+ j += szC - 1;
204605
+ }
204606
+ }
204607
+ j++;
204608
+ }
204609
+ return 0;
204610
+ }
204611
+ case JSONB_TEXTRAW: {
204612
+ return 0;
204613
+ }
204614
+ case JSONB_ARRAY: {
204615
+ u32 sub;
204616
+ j = i+n;
204617
+ k = j+sz;
204618
+ while( j<k ){
204619
+ sz = 0;
204620
+ n = jsonbPayloadSize(pParse, j, &sz);
204621
+ if( n==0 ) return j+1;
204622
+ if( j+n+sz>k ) return j+1;
204623
+ sub = jsonbValidityCheck(pParse, j, j+n+sz, iDepth+1);
204624
+ if( sub ) return sub;
204625
+ j += n + sz;
204626
+ }
204627
+ assert( j==k );
204628
+ return 0;
204629
+ }
204630
+ case JSONB_OBJECT: {
204631
+ u32 cnt = 0;
204632
+ u32 sub;
204633
+ j = i+n;
204634
+ k = j+sz;
204635
+ while( j<k ){
204636
+ sz = 0;
204637
+ n = jsonbPayloadSize(pParse, j, &sz);
204638
+ if( n==0 ) return j+1;
204639
+ if( j+n+sz>k ) return j+1;
204640
+ if( (cnt & 1)==0 ){
204641
+ x = z[j] & 0x0f;
204642
+ if( x<JSONB_TEXT || x>JSONB_TEXTRAW ) return j+1;
204643
+ }
204644
+ sub = jsonbValidityCheck(pParse, j, j+n+sz, iDepth+1);
204645
+ if( sub ) return sub;
204646
+ cnt++;
204647
+ j += n + sz;
204648
+ }
204649
+ assert( j==k );
204650
+ if( (cnt & 1)!=0 ) return j+1;
204651
+ return 0;
204652
+ }
204653
+ default: {
204654
+ return i+1;
204655
+ }
204656
+ }
204657
+}
204658
+
204659
+/*
204660
+** Translate a single element of JSON text at pParse->zJson[i] into
204661
+** its equivalent binary JSONB representation. Append the translation into
204662
+** pParse->aBlob[] beginning at pParse->nBlob. The size of
204663
+** pParse->aBlob[] is increased as necessary.
204664
+**
204665
+** Return the index of the first character past the end of the element parsed,
204666
+** or one of the following special result codes:
203974204667
**
203975204668
** 0 End of input
203976
-** -1 Syntax error
203977
-** -2 '}' seen
203978
-** -3 ']' seen
203979
-** -4 ',' seen
203980
-** -5 ':' seen
204669
+** -1 Syntax error or OOM
204670
+** -2 '}' seen \
204671
+** -3 ']' seen \___ For these returns, pParse->iErr is set to
204672
+** -4 ',' seen / the index in zJson[] of the seen character
204673
+** -5 ':' seen /
203981204674
*/
203982
-static int jsonParseValue(JsonParse *pParse, u32 i){
204675
+static int jsonTranslateTextToBlob(JsonParse *pParse, u32 i){
203983204676
char c;
203984204677
u32 j;
203985
- int iThis;
204678
+ u32 iThis, iStart;
203986204679
int x;
203987
- JsonNode *pNode;
204680
+ u8 t;
203988204681
const char *z = pParse->zJson;
203989204682
json_parse_restart:
203990204683
switch( (u8)z[i] ){
203991204684
case '{': {
203992204685
/* Parse object */
203993
- iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
203994
- if( iThis<0 ) return -1;
204686
+ iThis = pParse->nBlob;
204687
+ jsonBlobAppendNode(pParse, JSONB_OBJECT, pParse->nJson-i, 0);
203995204688
if( ++pParse->iDepth > JSON_MAX_DEPTH ){
203996204689
pParse->iErr = i;
203997204690
return -1;
203998204691
}
204692
+ iStart = pParse->nBlob;
203999204693
for(j=i+1;;j++){
204000
- u32 nNode = pParse->nNode;
204001
- x = jsonParseValue(pParse, j);
204694
+ u32 iBlob = pParse->nBlob;
204695
+ x = jsonTranslateTextToBlob(pParse, j);
204002204696
if( x<=0 ){
204697
+ int op;
204003204698
if( x==(-2) ){
204004204699
j = pParse->iErr;
204005
- if( pParse->nNode!=(u32)iThis+1 ) pParse->hasNonstd = 1;
204700
+ if( pParse->nBlob!=(u32)iStart ) pParse->hasNonstd = 1;
204006204701
break;
204007204702
}
204008204703
j += json5Whitespace(&z[j]);
204704
+ op = JSONB_TEXT;
204009204705
if( sqlite3JsonId1(z[j])
204010
- || (z[j]=='\\' && z[j+1]=='u' && jsonIs4Hex(&z[j+2]))
204706
+ || (z[j]=='\\' && jsonIs4HexB(&z[j+1], &op))
204011204707
){
204012204708
int k = j+1;
204013204709
while( (sqlite3JsonId2(z[k]) && json5Whitespace(&z[k])==0)
204014
- || (z[k]=='\\' && z[k+1]=='u' && jsonIs4Hex(&z[k+2]))
204710
+ || (z[k]=='\\' && jsonIs4HexB(&z[k+1], &op))
204015204711
){
204016204712
k++;
204017204713
}
204018
- jsonParseAddNode(pParse, JSON_STRING | (JNODE_RAW<<8), k-j, &z[j]);
204714
+ assert( iBlob==pParse->nBlob );
204715
+ jsonBlobAppendNode(pParse, op, k-j, &z[j]);
204019204716
pParse->hasNonstd = 1;
204020204717
x = k;
204021204718
}else{
204022204719
if( x!=-1 ) pParse->iErr = j;
204023204720
return -1;
204024204721
}
204025204722
}
204026204723
if( pParse->oom ) return -1;
204027
- pNode = &pParse->aNode[nNode];
204028
- if( pNode->eType!=JSON_STRING ){
204724
+ t = pParse->aBlob[iBlob] & 0x0f;
204725
+ if( t<JSONB_TEXT || t>JSONB_TEXTRAW ){
204029204726
pParse->iErr = j;
204030204727
return -1;
204031204728
}
204032
- pNode->jnFlags |= JNODE_LABEL;
204033204729
j = x;
204034204730
if( z[j]==':' ){
204035204731
j++;
204036204732
}else{
204037
- if( fast_isspace(z[j]) ){
204038
- do{ j++; }while( fast_isspace(z[j]) );
204733
+ if( jsonIsspace(z[j]) ){
204734
+ /* strspn() is not helpful here */
204735
+ do{ j++; }while( jsonIsspace(z[j]) );
204039204736
if( z[j]==':' ){
204040204737
j++;
204041204738
goto parse_object_value;
204042204739
}
204043204740
}
204044
- x = jsonParseValue(pParse, j);
204741
+ x = jsonTranslateTextToBlob(pParse, j);
204045204742
if( x!=(-5) ){
204046204743
if( x!=(-1) ) pParse->iErr = j;
204047204744
return -1;
204048204745
}
204049204746
j = pParse->iErr+1;
204050204747
}
204051204748
parse_object_value:
204052
- x = jsonParseValue(pParse, j);
204749
+ x = jsonTranslateTextToBlob(pParse, j);
204053204750
if( x<=0 ){
204054204751
if( x!=(-1) ) pParse->iErr = j;
204055204752
return -1;
204056204753
}
204057204754
j = x;
@@ -204058,19 +204755,19 @@
204058204755
if( z[j]==',' ){
204059204756
continue;
204060204757
}else if( z[j]=='}' ){
204061204758
break;
204062204759
}else{
204063
- if( fast_isspace(z[j]) ){
204064
- do{ j++; }while( fast_isspace(z[j]) );
204760
+ if( jsonIsspace(z[j]) ){
204761
+ j += 1 + (u32)strspn(&z[j+1], jsonSpaces);
204065204762
if( z[j]==',' ){
204066204763
continue;
204067204764
}else if( z[j]=='}' ){
204068204765
break;
204069204766
}
204070204767
}
204071
- x = jsonParseValue(pParse, j);
204768
+ x = jsonTranslateTextToBlob(pParse, j);
204072204769
if( x==(-4) ){
204073204770
j = pParse->iErr;
204074204771
continue;
204075204772
}
204076204773
if( x==(-2) ){
@@ -204079,29 +204776,30 @@
204079204776
}
204080204777
}
204081204778
pParse->iErr = j;
204082204779
return -1;
204083204780
}
204084
- pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
204781
+ jsonBlobChangePayloadSize(pParse, iThis, pParse->nBlob - iStart);
204085204782
pParse->iDepth--;
204086204783
return j+1;
204087204784
}
204088204785
case '[': {
204089204786
/* Parse array */
204090
- iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
204091
- if( iThis<0 ) return -1;
204787
+ iThis = pParse->nBlob;
204788
+ jsonBlobAppendNode(pParse, JSONB_ARRAY, pParse->nJson - i, 0);
204789
+ iStart = pParse->nBlob;
204790
+ if( pParse->oom ) return -1;
204092204791
if( ++pParse->iDepth > JSON_MAX_DEPTH ){
204093204792
pParse->iErr = i;
204094204793
return -1;
204095204794
}
204096
- memset(&pParse->aNode[iThis].u, 0, sizeof(pParse->aNode[iThis].u));
204097204795
for(j=i+1;;j++){
204098
- x = jsonParseValue(pParse, j);
204796
+ x = jsonTranslateTextToBlob(pParse, j);
204099204797
if( x<=0 ){
204100204798
if( x==(-3) ){
204101204799
j = pParse->iErr;
204102
- if( pParse->nNode!=(u32)iThis+1 ) pParse->hasNonstd = 1;
204800
+ if( pParse->nBlob!=iStart ) pParse->hasNonstd = 1;
204103204801
break;
204104204802
}
204105204803
if( x!=(-1) ) pParse->iErr = j;
204106204804
return -1;
204107204805
}
@@ -204109,19 +204807,19 @@
204109204807
if( z[j]==',' ){
204110204808
continue;
204111204809
}else if( z[j]==']' ){
204112204810
break;
204113204811
}else{
204114
- if( fast_isspace(z[j]) ){
204115
- do{ j++; }while( fast_isspace(z[j]) );
204812
+ if( jsonIsspace(z[j]) ){
204813
+ j += 1 + (u32)strspn(&z[j+1], jsonSpaces);
204116204814
if( z[j]==',' ){
204117204815
continue;
204118204816
}else if( z[j]==']' ){
204119204817
break;
204120204818
}
204121204819
}
204122
- x = jsonParseValue(pParse, j);
204820
+ x = jsonTranslateTextToBlob(pParse, j);
204123204821
if( x==(-4) ){
204124204822
j = pParse->iErr;
204125204823
continue;
204126204824
}
204127204825
if( x==(-3) ){
@@ -204130,86 +204828,98 @@
204130204828
}
204131204829
}
204132204830
pParse->iErr = j;
204133204831
return -1;
204134204832
}
204135
- pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
204833
+ jsonBlobChangePayloadSize(pParse, iThis, pParse->nBlob - iStart);
204136204834
pParse->iDepth--;
204137204835
return j+1;
204138204836
}
204139204837
case '\'': {
204140
- u8 jnFlags;
204838
+ u8 opcode;
204141204839
char cDelim;
204142204840
pParse->hasNonstd = 1;
204143
- jnFlags = JNODE_JSON5;
204841
+ opcode = JSONB_TEXT;
204144204842
goto parse_string;
204145204843
case '"':
204146204844
/* Parse string */
204147
- jnFlags = 0;
204845
+ opcode = JSONB_TEXT;
204148204846
parse_string:
204149204847
cDelim = z[i];
204150
- for(j=i+1; 1; j++){
204151
- if( jsonIsOk[(unsigned char)z[j]] ) continue;
204848
+ j = i+1;
204849
+ while( 1 /*exit-by-break*/ ){
204850
+ if( jsonIsOk[(u8)z[j]] ){
204851
+ if( !jsonIsOk[(u8)z[j+1]] ){
204852
+ j += 1;
204853
+ }else if( !jsonIsOk[(u8)z[j+2]] ){
204854
+ j += 2;
204855
+ }else{
204856
+ j += 3;
204857
+ continue;
204858
+ }
204859
+ }
204152204860
c = z[j];
204153204861
if( c==cDelim ){
204154204862
break;
204155204863
}else if( c=='\\' ){
204156204864
c = z[++j];
204157204865
if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
204158204866
|| c=='n' || c=='r' || c=='t'
204159204867
|| (c=='u' && jsonIs4Hex(&z[j+1])) ){
204160
- jnFlags |= JNODE_ESCAPE;
204868
+ if( opcode==JSONB_TEXT ) opcode = JSONB_TEXTJ;
204161204869
}else if( c=='\'' || c=='0' || c=='v' || c=='\n'
204162204870
|| (0xe2==(u8)c && 0x80==(u8)z[j+1]
204163204871
&& (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2]))
204164204872
|| (c=='x' && jsonIs2Hex(&z[j+1])) ){
204165
- jnFlags |= (JNODE_ESCAPE|JNODE_JSON5);
204873
+ opcode = JSONB_TEXT5;
204166204874
pParse->hasNonstd = 1;
204167204875
}else if( c=='\r' ){
204168204876
if( z[j+1]=='\n' ) j++;
204169
- jnFlags |= (JNODE_ESCAPE|JNODE_JSON5);
204877
+ opcode = JSONB_TEXT5;
204170204878
pParse->hasNonstd = 1;
204171204879
}else{
204172204880
pParse->iErr = j;
204173204881
return -1;
204174204882
}
204175204883
}else if( c<=0x1f ){
204176204884
/* Control characters are not allowed in strings */
204177204885
pParse->iErr = j;
204178204886
return -1;
204887
+ }else if( c=='"' ){
204888
+ opcode = JSONB_TEXT5;
204179204889
}
204890
+ j++;
204180204891
}
204181
- jsonParseAddNode(pParse, JSON_STRING | (jnFlags<<8), j+1-i, &z[i]);
204892
+ jsonBlobAppendNode(pParse, opcode, j-1-i, &z[i+1]);
204182204893
return j+1;
204183204894
}
204184204895
case 't': {
204185204896
if( strncmp(z+i,"true",4)==0 && !sqlite3Isalnum(z[i+4]) ){
204186
- jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
204897
+ jsonBlobAppendOneByte(pParse, JSONB_TRUE);
204187204898
return i+4;
204188204899
}
204189204900
pParse->iErr = i;
204190204901
return -1;
204191204902
}
204192204903
case 'f': {
204193204904
if( strncmp(z+i,"false",5)==0 && !sqlite3Isalnum(z[i+5]) ){
204194
- jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
204905
+ jsonBlobAppendOneByte(pParse, JSONB_FALSE);
204195204906
return i+5;
204196204907
}
204197204908
pParse->iErr = i;
204198204909
return -1;
204199204910
}
204200204911
case '+': {
204201
- u8 seenDP, seenE, jnFlags;
204912
+ u8 seenE;
204202204913
pParse->hasNonstd = 1;
204203
- jnFlags = JNODE_JSON5;
204914
+ t = 0x00; /* Bit 0x01: JSON5. Bit 0x02: FLOAT */
204204204915
goto parse_number;
204205204916
case '.':
204206204917
if( sqlite3Isdigit(z[i+1]) ){
204207204918
pParse->hasNonstd = 1;
204208
- jnFlags = JNODE_JSON5;
204919
+ t = 0x03; /* Bit 0x01: JSON5. Bit 0x02: FLOAT */
204209204920
seenE = 0;
204210
- seenDP = JSON_REAL;
204211204921
goto parse_number_2;
204212204922
}
204213204923
pParse->iErr = i;
204214204924
return -1;
204215204925
case '-':
@@ -204222,25 +204932,24 @@
204222204932
case '6':
204223204933
case '7':
204224204934
case '8':
204225204935
case '9':
204226204936
/* Parse number */
204227
- jnFlags = 0;
204937
+ t = 0x00; /* Bit 0x01: JSON5. Bit 0x02: FLOAT */
204228204938
parse_number:
204229
- seenDP = JSON_INT;
204230204939
seenE = 0;
204231204940
assert( '-' < '0' );
204232204941
assert( '+' < '0' );
204233204942
assert( '.' < '0' );
204234204943
c = z[i];
204235204944
204236204945
if( c<='0' ){
204237204946
if( c=='0' ){
204238204947
if( (z[i+1]=='x' || z[i+1]=='X') && sqlite3Isxdigit(z[i+2]) ){
204239
- assert( seenDP==JSON_INT );
204948
+ assert( t==0x00 );
204240204949
pParse->hasNonstd = 1;
204241
- jnFlags |= JNODE_JSON5;
204950
+ t = 0x01;
204242204951
for(j=i+3; sqlite3Isxdigit(z[j]); j++){}
204243204952
goto parse_number_finish;
204244204953
}else if( sqlite3Isdigit(z[i+1]) ){
204245204954
pParse->iErr = i+1;
204246204955
return -1;
@@ -204253,19 +204962,19 @@
204253204962
if( (z[i+1]=='I' || z[i+1]=='i')
204254204963
&& sqlite3StrNICmp(&z[i+1], "inf",3)==0
204255204964
){
204256204965
pParse->hasNonstd = 1;
204257204966
if( z[i]=='-' ){
204258
- jsonParseAddNode(pParse, JSON_REAL, 8, "-9.0e999");
204967
+ jsonBlobAppendNode(pParse, JSONB_FLOAT, 6, "-9e999");
204259204968
}else{
204260
- jsonParseAddNode(pParse, JSON_REAL, 7, "9.0e999");
204969
+ jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999");
204261204970
}
204262204971
return i + (sqlite3StrNICmp(&z[i+4],"inity",5)==0 ? 9 : 4);
204263204972
}
204264204973
if( z[i+1]=='.' ){
204265204974
pParse->hasNonstd = 1;
204266
- jnFlags |= JNODE_JSON5;
204975
+ t |= 0x01;
204267204976
goto parse_number_2;
204268204977
}
204269204978
pParse->iErr = i;
204270204979
return -1;
204271204980
}
@@ -204273,44 +204982,45 @@
204273204982
if( sqlite3Isdigit(z[i+2]) ){
204274204983
pParse->iErr = i+1;
204275204984
return -1;
204276204985
}else if( (z[i+2]=='x' || z[i+2]=='X') && sqlite3Isxdigit(z[i+3]) ){
204277204986
pParse->hasNonstd = 1;
204278
- jnFlags |= JNODE_JSON5;
204987
+ t |= 0x01;
204279204988
for(j=i+4; sqlite3Isxdigit(z[j]); j++){}
204280204989
goto parse_number_finish;
204281204990
}
204282204991
}
204283204992
}
204284204993
}
204994
+
204285204995
parse_number_2:
204286204996
for(j=i+1;; j++){
204287204997
c = z[j];
204288204998
if( sqlite3Isdigit(c) ) continue;
204289204999
if( c=='.' ){
204290
- if( seenDP==JSON_REAL ){
205000
+ if( (t & 0x02)!=0 ){
204291205001
pParse->iErr = j;
204292205002
return -1;
204293205003
}
204294
- seenDP = JSON_REAL;
205004
+ t |= 0x02;
204295205005
continue;
204296205006
}
204297205007
if( c=='e' || c=='E' ){
204298205008
if( z[j-1]<'0' ){
204299205009
if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){
204300205010
pParse->hasNonstd = 1;
204301
- jnFlags |= JNODE_JSON5;
205011
+ t |= 0x01;
204302205012
}else{
204303205013
pParse->iErr = j;
204304205014
return -1;
204305205015
}
204306205016
}
204307205017
if( seenE ){
204308205018
pParse->iErr = j;
204309205019
return -1;
204310205020
}
204311
- seenDP = JSON_REAL;
205021
+ t |= 0x02;
204312205022
seenE = 1;
204313205023
c = z[j+1];
204314205024
if( c=='+' || c=='-' ){
204315205025
j++;
204316205026
c = z[j+1];
@@ -204324,18 +205034,22 @@
204324205034
break;
204325205035
}
204326205036
if( z[j-1]<'0' ){
204327205037
if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){
204328205038
pParse->hasNonstd = 1;
204329
- jnFlags |= JNODE_JSON5;
205039
+ t |= 0x01;
204330205040
}else{
204331205041
pParse->iErr = j;
204332205042
return -1;
204333205043
}
204334205044
}
204335205045
parse_number_finish:
204336
- jsonParseAddNode(pParse, seenDP | (jnFlags<<8), j - i, &z[i]);
205046
+ assert( JSONB_INT+0x01==JSONB_INT5 );
205047
+ assert( JSONB_FLOAT+0x01==JSONB_FLOAT5 );
205048
+ assert( JSONB_INT+0x02==JSONB_FLOAT );
205049
+ if( z[i]=='+' ) i++;
205050
+ jsonBlobAppendNode(pParse, JSONB_INT+t, j-i, &z[i]);
204337205051
return j;
204338205052
}
204339205053
case '}': {
204340205054
pParse->iErr = i;
204341205055
return -2; /* End of {...} */
@@ -204357,13 +205071,11 @@
204357205071
}
204358205072
case 0x09:
204359205073
case 0x0a:
204360205074
case 0x0d:
204361205075
case 0x20: {
204362
- do{
204363
- i++;
204364
- }while( fast_isspace(z[i]) );
205076
+ i += 1 + (u32)strspn(&z[i+1], jsonSpaces);
204365205077
goto json_parse_restart;
204366205078
}
204367205079
case 0x0b:
204368205080
case 0x0c:
204369205081
case '/':
@@ -204381,11 +205093,11 @@
204381205093
pParse->iErr = i;
204382205094
return -1;
204383205095
}
204384205096
case 'n': {
204385205097
if( strncmp(z+i,"null",4)==0 && !sqlite3Isalnum(z[i+4]) ){
204386
- jsonParseAddNode(pParse, JSON_NULL, 0, 0);
205098
+ jsonBlobAppendOneByte(pParse, JSONB_NULL);
204387205099
return i+4;
204388205100
}
204389205101
/* fall-through into the default case that checks for NaN */
204390205102
}
204391205103
default: {
@@ -204397,43 +205109,53 @@
204397205109
nn = aNanInfName[k].n;
204398205110
if( sqlite3StrNICmp(&z[i], aNanInfName[k].zMatch, nn)!=0 ){
204399205111
continue;
204400205112
}
204401205113
if( sqlite3Isalnum(z[i+nn]) ) continue;
204402
- jsonParseAddNode(pParse, aNanInfName[k].eType,
204403
- aNanInfName[k].nRepl, aNanInfName[k].zRepl);
205114
+ if( aNanInfName[k].eType==JSONB_FLOAT ){
205115
+ jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999");
205116
+ }else{
205117
+ jsonBlobAppendOneByte(pParse, JSONB_NULL);
205118
+ }
204404205119
pParse->hasNonstd = 1;
204405205120
return i + nn;
204406205121
}
204407205122
pParse->iErr = i;
204408205123
return -1; /* Syntax error */
204409205124
}
204410205125
} /* End switch(z[i]) */
204411205126
}
205127
+
204412205128
204413205129
/*
204414205130
** Parse a complete JSON string. Return 0 on success or non-zero if there
204415205131
** are any errors. If an error occurs, free all memory held by pParse,
204416205132
** but not pParse itself.
204417205133
**
204418205134
** pParse must be initialized to an empty parse object prior to calling
204419205135
** this routine.
204420205136
*/
204421
-static int jsonParse(
205137
+static int jsonConvertTextToBlob(
204422205138
JsonParse *pParse, /* Initialize and fill this JsonParse object */
204423205139
sqlite3_context *pCtx /* Report errors here */
204424205140
){
204425205141
int i;
204426205142
const char *zJson = pParse->zJson;
204427
- i = jsonParseValue(pParse, 0);
205143
+ i = jsonTranslateTextToBlob(pParse, 0);
204428205144
if( pParse->oom ) i = -1;
204429205145
if( i>0 ){
205146
+#ifdef SQLITE_DEBUG
204430205147
assert( pParse->iDepth==0 );
204431
- while( fast_isspace(zJson[i]) ) i++;
205148
+ if( sqlite3Config.bJsonSelfcheck ){
205149
+ assert( jsonbValidityCheck(pParse, 0, pParse->nBlob, 0)==0 );
205150
+ }
205151
+#endif
205152
+ while( jsonIsspace(zJson[i]) ) i++;
204432205153
if( zJson[i] ){
204433205154
i += json5Whitespace(&zJson[i]);
204434205155
if( zJson[i] ){
205156
+ if( pCtx ) sqlite3_result_error(pCtx, "malformed JSON", -1);
204435205157
jsonParseReset(pParse);
204436205158
return 1;
204437205159
}
204438205160
pParse->hasNonstd = 1;
204439205161
}
@@ -204450,617 +205172,1579 @@
204450205172
return 1;
204451205173
}
204452205174
return 0;
204453205175
}
204454205176
204455
-
204456
-/* Mark node i of pParse as being a child of iParent. Call recursively
204457
-** to fill in all the descendants of node i.
204458
-*/
204459
-static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
204460
- JsonNode *pNode = &pParse->aNode[i];
204461
- u32 j;
204462
- pParse->aUp[i] = iParent;
204463
- switch( pNode->eType ){
204464
- case JSON_ARRAY: {
204465
- for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
204466
- jsonParseFillInParentage(pParse, i+j, i);
204467
- }
204468
- break;
204469
- }
204470
- case JSON_OBJECT: {
204471
- for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
204472
- pParse->aUp[i+j] = i;
204473
- jsonParseFillInParentage(pParse, i+j+1, i);
204474
- }
204475
- break;
204476
- }
204477
- default: {
204478
- break;
204479
- }
204480
- }
204481
-}
204482
-
204483
-/*
204484
-** Compute the parentage of all nodes in a completed parse.
204485
-*/
204486
-static int jsonParseFindParents(JsonParse *pParse){
204487
- u32 *aUp;
204488
- assert( pParse->aUp==0 );
204489
- aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
204490
- if( aUp==0 ){
204491
- pParse->oom = 1;
204492
- return SQLITE_NOMEM;
204493
- }
204494
- jsonParseFillInParentage(pParse, 0, 0);
204495
- return SQLITE_OK;
204496
-}
204497
-
204498
-/*
204499
-** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
204500
-*/
204501
-#define JSON_CACHE_ID (-429938) /* First cache entry */
204502
-#define JSON_CACHE_SZ 4 /* Max number of cache entries */
204503
-
204504
-/*
204505
-** Obtain a complete parse of the JSON found in the pJson argument
204506
-**
204507
-** Use the sqlite3_get_auxdata() cache to find a preexisting parse
204508
-** if it is available. If the cache is not available or if it
204509
-** is no longer valid, parse the JSON again and return the new parse.
204510
-** Also register the new parse so that it will be available for
204511
-** future sqlite3_get_auxdata() calls.
204512
-**
204513
-** If an error occurs and pErrCtx!=0 then report the error on pErrCtx
204514
-** and return NULL.
204515
-**
204516
-** The returned pointer (if it is not NULL) is owned by the cache in
204517
-** most cases, not the caller. The caller does NOT need to invoke
204518
-** jsonParseFree(), in most cases.
204519
-**
204520
-** Except, if an error occurs and pErrCtx==0 then return the JsonParse
204521
-** object with JsonParse.nErr non-zero and the caller will own the JsonParse
204522
-** object. In that case, it will be the responsibility of the caller to
204523
-** invoke jsonParseFree(). To summarize:
204524
-**
204525
-** pErrCtx!=0 || p->nErr==0 ==> Return value p is owned by the
204526
-** cache. Call does not need to
204527
-** free it.
204528
-**
204529
-** pErrCtx==0 && p->nErr!=0 ==> Return value is owned by the caller
204530
-** and so the caller must free it.
204531
-*/
204532
-static JsonParse *jsonParseCached(
204533
- sqlite3_context *pCtx, /* Context to use for cache search */
204534
- sqlite3_value *pJson, /* Function param containing JSON text */
204535
- sqlite3_context *pErrCtx, /* Write parse errors here if not NULL */
204536
- int bUnedited /* No prior edits allowed */
204537
-){
204538
- char *zJson = (char*)sqlite3_value_text(pJson);
204539
- int nJson = sqlite3_value_bytes(pJson);
204540
- JsonParse *p;
204541
- JsonParse *pMatch = 0;
204542
- int iKey;
204543
- int iMinKey = 0;
204544
- u32 iMinHold = 0xffffffff;
204545
- u32 iMaxHold = 0;
204546
- int bJsonRCStr;
204547
-
204548
- if( zJson==0 ) return 0;
204549
- for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
204550
- p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
204551
- if( p==0 ){
204552
- iMinKey = iKey;
204553
- break;
204554
- }
204555
- if( pMatch==0
204556
- && p->nJson==nJson
204557
- && (p->hasMod==0 || bUnedited==0)
204558
- && (p->zJson==zJson || memcmp(p->zJson,zJson,nJson)==0)
204559
- ){
204560
- p->nErr = 0;
204561
- p->useMod = 0;
204562
- pMatch = p;
204563
- }else
204564
- if( pMatch==0
204565
- && p->zAlt!=0
204566
- && bUnedited==0
204567
- && p->nAlt==nJson
204568
- && memcmp(p->zAlt, zJson, nJson)==0
204569
- ){
204570
- p->nErr = 0;
204571
- p->useMod = 1;
204572
- pMatch = p;
204573
- }else if( p->iHold<iMinHold ){
204574
- iMinHold = p->iHold;
204575
- iMinKey = iKey;
204576
- }
204577
- if( p->iHold>iMaxHold ){
204578
- iMaxHold = p->iHold;
204579
- }
204580
- }
204581
- if( pMatch ){
204582
- /* The input JSON text was found in the cache. Use the preexisting
204583
- ** parse of this JSON */
204584
- pMatch->nErr = 0;
204585
- pMatch->iHold = iMaxHold+1;
204586
- assert( pMatch->nJPRef>0 ); /* pMatch is owned by the cache */
204587
- return pMatch;
204588
- }
204589
-
204590
- /* The input JSON was not found anywhere in the cache. We will need
204591
- ** to parse it ourselves and generate a new JsonParse object.
204592
- */
204593
- bJsonRCStr = sqlite3ValueIsOfClass(pJson,sqlite3RCStrUnref);
204594
- p = sqlite3_malloc64( sizeof(*p) + (bJsonRCStr ? 0 : nJson+1) );
204595
- if( p==0 ){
204596
- sqlite3_result_error_nomem(pCtx);
204597
- return 0;
204598
- }
204599
- memset(p, 0, sizeof(*p));
204600
- if( bJsonRCStr ){
204601
- p->zJson = sqlite3RCStrRef(zJson);
204602
- p->bJsonIsRCStr = 1;
204603
- }else{
204604
- p->zJson = (char*)&p[1];
204605
- memcpy(p->zJson, zJson, nJson+1);
204606
- }
204607
- p->nJPRef = 1;
204608
- if( jsonParse(p, pErrCtx) ){
204609
- if( pErrCtx==0 ){
204610
- p->nErr = 1;
204611
- assert( p->nJPRef==1 ); /* Caller will own the new JsonParse object p */
204612
- return p;
204613
- }
204614
- jsonParseFree(p);
204615
- return 0;
204616
- }
204617
- p->nJson = nJson;
204618
- p->iHold = iMaxHold+1;
204619
- /* Transfer ownership of the new JsonParse to the cache */
204620
- sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
204621
- (void(*)(void*))jsonParseFree);
204622
- return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
204623
-}
204624
-
204625
-/*
204626
-** Compare the OBJECT label at pNode against zKey,nKey. Return true on
204627
-** a match.
204628
-*/
204629
-static int jsonLabelCompare(const JsonNode *pNode, const char *zKey, u32 nKey){
204630
- assert( pNode->eU==1 );
204631
- if( pNode->jnFlags & JNODE_RAW ){
204632
- if( pNode->n!=nKey ) return 0;
204633
- return strncmp(pNode->u.zJContent, zKey, nKey)==0;
204634
- }else{
204635
- if( pNode->n!=nKey+2 ) return 0;
204636
- return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
204637
- }
204638
-}
204639
-static int jsonSameLabel(const JsonNode *p1, const JsonNode *p2){
204640
- if( p1->jnFlags & JNODE_RAW ){
204641
- return jsonLabelCompare(p2, p1->u.zJContent, p1->n);
204642
- }else if( p2->jnFlags & JNODE_RAW ){
204643
- return jsonLabelCompare(p1, p2->u.zJContent, p2->n);
204644
- }else{
204645
- return p1->n==p2->n && strncmp(p1->u.zJContent,p2->u.zJContent,p1->n)==0;
204646
- }
204647
-}
204648
-
204649
-/* forward declaration */
204650
-static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
204651
-
204652
-/*
204653
-** Search along zPath to find the node specified. Return a pointer
204654
-** to that node, or NULL if zPath is malformed or if there is no such
204655
-** node.
204656
-**
204657
-** If pApnd!=0, then try to append new nodes to complete zPath if it is
204658
-** possible to do so and if no existing node corresponds to zPath. If
204659
-** new nodes are appended *pApnd is set to 1.
204660
-*/
204661
-static JsonNode *jsonLookupStep(
204662
- JsonParse *pParse, /* The JSON to search */
204663
- u32 iRoot, /* Begin the search at this node */
204664
- const char *zPath, /* The path to search */
204665
- int *pApnd, /* Append nodes to complete path if not NULL */
204666
- const char **pzErr /* Make *pzErr point to any syntax error in zPath */
204667
-){
204668
- u32 i, j, nKey;
204669
- const char *zKey;
204670
- JsonNode *pRoot;
204671
- if( pParse->oom ) return 0;
204672
- pRoot = &pParse->aNode[iRoot];
204673
- if( pRoot->jnFlags & (JNODE_REPLACE|JNODE_REMOVE) && pParse->useMod ){
204674
- while( (pRoot->jnFlags & JNODE_REPLACE)!=0 ){
204675
- u32 idx = (u32)(pRoot - pParse->aNode);
204676
- i = pParse->iSubst;
204677
- while( 1 /*exit-by-break*/ ){
204678
- assert( i<pParse->nNode );
204679
- assert( pParse->aNode[i].eType==JSON_SUBST );
204680
- assert( pParse->aNode[i].eU==4 );
204681
- assert( pParse->aNode[i].u.iPrev<i );
204682
- if( pParse->aNode[i].n==idx ){
204683
- pRoot = &pParse->aNode[i+1];
204684
- iRoot = i+1;
204685
- break;
204686
- }
204687
- i = pParse->aNode[i].u.iPrev;
204688
- }
204689
- }
204690
- if( pRoot->jnFlags & JNODE_REMOVE ){
204691
- return 0;
204692
- }
204693
- }
204694
- if( zPath[0]==0 ) return pRoot;
204695
- if( zPath[0]=='.' ){
204696
- if( pRoot->eType!=JSON_OBJECT ) return 0;
205177
+/*
205178
+** The input string pStr is a well-formed JSON text string. Convert
205179
+** this into the JSONB format and make it the return value of the
205180
+** SQL function.
205181
+*/
205182
+static void jsonReturnStringAsBlob(JsonString *pStr){
205183
+ JsonParse px;
205184
+ memset(&px, 0, sizeof(px));
205185
+ jsonStringTerminate(pStr);
205186
+ px.zJson = pStr->zBuf;
205187
+ px.nJson = pStr->nUsed;
205188
+ px.db = sqlite3_context_db_handle(pStr->pCtx);
205189
+ (void)jsonTranslateTextToBlob(&px, 0);
205190
+ if( px.oom ){
205191
+ sqlite3DbFree(px.db, px.aBlob);
205192
+ sqlite3_result_error_nomem(pStr->pCtx);
205193
+ }else{
205194
+ assert( px.nBlobAlloc>0 );
205195
+ assert( !px.bReadOnly );
205196
+ sqlite3_result_blob(pStr->pCtx, px.aBlob, px.nBlob, SQLITE_DYNAMIC);
205197
+ }
205198
+}
205199
+
205200
+/* The byte at index i is a node type-code. This routine
205201
+** determines the payload size for that node and writes that
205202
+** payload size in to *pSz. It returns the offset from i to the
205203
+** beginning of the payload. Return 0 on error.
205204
+*/