4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 ******************************************************************************
13 ** This SQLite JSON functions.
15 ** This file began as an extension in ext/misc/json1.c in 2015. That
16 ** extension proved so useful that it has now been moved into the core.
18 ** For the time being, all JSON is stored as pure text. (We might add
19 ** a JSONB type in the future which stores a binary encoding of JSON in
20 ** a BLOB, but there is no support for JSONB in the current implementation.
21 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
22 ** how JSONB might improve on that.)
24 #ifndef SQLITE_OMIT_JSON
25 #include "sqliteInt.h"
28 ** Growing our own isspace() routine this way is twice as fast as
29 ** the library isspace() function, resulting in a 7% overall performance
30 ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
32 static const char jsonIsSpace
[] = {
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
35 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
36 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
37 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
38 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
39 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
42 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
43 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
44 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
45 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
46 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
47 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
51 #define fast_isspace(x) (jsonIsSpace[(unsigned char)x])
54 ** Characters that are special to JSON. Control charaters,
57 static const char jsonIsOk
[256] = {
58 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
59 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
60 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
61 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
62 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
63 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,
64 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
65 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
67 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
68 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
69 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
70 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
71 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
72 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
73 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
74 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
78 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_COVERAGE_TEST)
85 typedef struct JsonString JsonString
;
86 typedef struct JsonNode JsonNode
;
87 typedef struct JsonParse JsonParse
;
88 typedef struct JsonCleanup JsonCleanup
;
90 /* An instance of this object represents a JSON string
91 ** under construction. Really, this is a generic string accumulator
92 ** that can be and is used to create strings other than JSON.
95 sqlite3_context
*pCtx
; /* Function context - put error messages here */
96 char *zBuf
; /* Append JSON content here */
97 u64 nAlloc
; /* Bytes of storage available in zBuf[] */
98 u64 nUsed
; /* Bytes of zBuf[] currently used */
99 u8 bStatic
; /* True if zBuf is static space */
100 u8 bErr
; /* True if an error has been encountered */
101 char zSpace
[100]; /* Initial static space */
104 /* A deferred cleanup task. A list of JsonCleanup objects might be
105 ** run when the JsonParse object is destroyed.
108 JsonCleanup
*pJCNext
; /* Next in a list */
109 void (*xOp
)(void*); /* Routine to run */
110 void *pArg
; /* Argument to xOp() */
115 #define JSON_SUBST 0 /* Special edit node. Uses u.iPrev */
121 #define JSON_STRING 6
123 #define JSON_OBJECT 8
125 /* The "subtype" set for JSON values */
126 #define JSON_SUBTYPE 74 /* Ascii for "J" */
129 ** Names of the various JSON types:
131 static const char * const jsonType
[] = {
133 "null", "true", "false", "integer", "real", "text", "array", "object"
136 /* Bit values for the JsonNode.jnFlag field
138 #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
139 #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
140 #define JNODE_REMOVE 0x04 /* Do not output */
141 #define JNODE_REPLACE 0x08 /* Target of a JSON_SUBST node */
142 #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
143 #define JNODE_LABEL 0x20 /* Is a label of an object */
144 #define JNODE_JSON5 0x40 /* Node contains JSON5 enhancements */
147 /* A single node of parsed JSON. An array of these nodes describes
148 ** a parse of JSON + edits.
150 ** Use the json_parse() SQL function (available when compiled with
151 ** -DSQLITE_DEBUG) to see a dump of complete JsonParse objects, including
152 ** a complete listing and decoding of the array of JsonNodes.
155 u8 eType
; /* One of the JSON_ type values */
156 u8 jnFlags
; /* JNODE flags */
157 u8 eU
; /* Which union element to use */
158 u32 n
; /* Bytes of content for INT, REAL or STRING
159 ** Number of sub-nodes for ARRAY and OBJECT
160 ** Node that SUBST applies to */
162 const char *zJContent
; /* 1: Content for INT, REAL, and STRING */
163 u32 iAppend
; /* 2: More terms for ARRAY and OBJECT */
164 u32 iKey
; /* 3: Key for ARRAY objects in json_tree() */
165 u32 iPrev
; /* 4: Previous SUBST node, or 0 */
170 /* A parsed and possibly edited JSON string. Lifecycle:
172 ** 1. JSON comes in and is parsed into an array aNode[]. The original
173 ** JSON text is stored in zJson.
175 ** 2. Zero or more changes are made (via json_remove() or json_replace()
176 ** or similar) to the aNode[] array.
178 ** 3. A new, edited and mimified JSON string is generated from aNode
179 ** and stored in zAlt. The JsonParse object always owns zAlt.
181 ** Step 1 always happens. Step 2 and 3 may or may not happen, depending
184 ** aNode[].u.zJContent entries typically point into zJson. Hence zJson
185 ** must remain valid for the lifespan of the parse. For edits,
186 ** aNode[].u.zJContent might point to malloced space other than zJson.
187 ** Entries in pClup are responsible for freeing that extra malloced space.
189 ** When walking the parse tree in aNode[], edits are ignored if useMod is
193 u32 nNode
; /* Number of slots of aNode[] used */
194 u32 nAlloc
; /* Number of slots of aNode[] allocated */
195 JsonNode
*aNode
; /* Array of nodes containing the parse */
196 char *zJson
; /* Original JSON string (before edits) */
197 char *zAlt
; /* Revised and/or mimified JSON */
198 u32
*aUp
; /* Index of parent of each node */
199 JsonCleanup
*pClup
;/* Cleanup operations prior to freeing this object */
200 u16 iDepth
; /* Nesting depth */
201 u8 nErr
; /* Number of errors seen */
202 u8 oom
; /* Set to true if out of memory */
203 u8 bJsonIsRCStr
; /* True if zJson is an RCStr */
204 u8 hasNonstd
; /* True if input uses non-standard features like JSON5 */
205 u8 useMod
; /* Actually use the edits contain inside aNode */
206 u8 hasMod
; /* aNode contains edits from the original zJson */
207 u32 nJPRef
; /* Number of references to this object */
208 int nJson
; /* Length of the zJson string in bytes */
209 int nAlt
; /* Length of alternative JSON string zAlt, in bytes */
210 u32 iErr
; /* Error location in zJson[] */
211 u32 iSubst
; /* Last JSON_SUBST entry in aNode[] */
212 u32 iHold
; /* Age of this entry in the cache for LRU replacement */
216 ** Maximum nesting depth of JSON for this implementation.
218 ** This limit is needed to avoid a stack overflow in the recursive
219 ** descent parser. A depth of 1000 is far deeper than any sane JSON
220 ** should go. Historical note: This limit was 2000 prior to version 3.42.0
222 #define JSON_MAX_DEPTH 1000
224 /**************************************************************************
225 ** Utility routines for dealing with JsonString objects
226 **************************************************************************/
228 /* Set the JsonString object to an empty string
230 static void jsonZero(JsonString
*p
){
232 p
->nAlloc
= sizeof(p
->zSpace
);
237 /* Initialize the JsonString object
239 static void jsonInit(JsonString
*p
, sqlite3_context
*pCtx
){
245 /* Free all allocated memory and reset the JsonString object back to its
248 static void jsonReset(JsonString
*p
){
249 if( !p
->bStatic
) sqlite3RCStrUnref(p
->zBuf
);
253 /* Report an out-of-memory (OOM) condition
255 static void jsonOom(JsonString
*p
){
257 sqlite3_result_error_nomem(p
->pCtx
);
261 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
262 ** Return zero on success. Return non-zero on an OOM error
264 static int jsonGrow(JsonString
*p
, u32 N
){
265 u64 nTotal
= N
<p
->nAlloc
? p
->nAlloc
*2 : p
->nAlloc
+N
+10;
268 if( p
->bErr
) return 1;
269 zNew
= sqlite3RCStrNew(nTotal
);
274 memcpy(zNew
, p
->zBuf
, (size_t)p
->nUsed
);
278 p
->zBuf
= sqlite3RCStrResize(p
->zBuf
, nTotal
);
289 /* Append N bytes from zIn onto the end of the JsonString string.
291 static SQLITE_NOINLINE
void jsonAppendExpand(
297 if( jsonGrow(p
,N
) ) return;
298 memcpy(p
->zBuf
+p
->nUsed
, zIn
, N
);
301 static void jsonAppendRaw(JsonString
*p
, const char *zIn
, u32 N
){
303 if( N
+p
->nUsed
>= p
->nAlloc
){
304 jsonAppendExpand(p
,zIn
,N
);
306 memcpy(p
->zBuf
+p
->nUsed
, zIn
, N
);
310 static void jsonAppendRawNZ(JsonString
*p
, const char *zIn
, u32 N
){
312 if( N
+p
->nUsed
>= p
->nAlloc
){
313 jsonAppendExpand(p
,zIn
,N
);
315 memcpy(p
->zBuf
+p
->nUsed
, zIn
, N
);
321 /* Append formatted text (not to exceed N bytes) to the JsonString.
323 static void jsonPrintf(int N
, JsonString
*p
, const char *zFormat
, ...){
325 if( (p
->nUsed
+ N
>= p
->nAlloc
) && jsonGrow(p
, N
) ) return;
326 va_start(ap
, zFormat
);
327 sqlite3_vsnprintf(N
, p
->zBuf
+p
->nUsed
, zFormat
, ap
);
329 p
->nUsed
+= (int)strlen(p
->zBuf
+p
->nUsed
);
332 /* Append a single character
334 static SQLITE_NOINLINE
void jsonAppendCharExpand(JsonString
*p
, char c
){
335 if( jsonGrow(p
,1) ) return;
336 p
->zBuf
[p
->nUsed
++] = c
;
338 static void jsonAppendChar(JsonString
*p
, char c
){
339 if( p
->nUsed
>=p
->nAlloc
){
340 jsonAppendCharExpand(p
,c
);
342 p
->zBuf
[p
->nUsed
++] = c
;
346 /* Try to force the string to be a zero-terminated RCStr string.
348 ** Return true on success. Return false if an OOM prevents this
351 static int jsonForceRCStr(JsonString
*p
){
352 jsonAppendChar(p
, 0);
353 if( p
->bErr
) return 0;
355 if( p
->bStatic
==0 ) return 1;
358 jsonGrow(p
, p
->nUsed
);
360 return p
->bStatic
==0;
364 /* Append a comma separator to the output buffer, if the previous
365 ** character is not '[' or '{'.
367 static void jsonAppendSeparator(JsonString
*p
){
369 if( p
->nUsed
==0 ) return;
370 c
= p
->zBuf
[p
->nUsed
-1];
371 if( c
=='[' || c
=='{' ) return;
372 jsonAppendChar(p
, ',');
375 /* Append the N-byte string in zIn to the end of the JsonString string
376 ** under construction. Enclose the string in "..." and escape
377 ** any double-quotes or backslash characters contained within the
380 static void jsonAppendString(JsonString
*p
, const char *zIn
, u32 N
){
382 if( zIn
==0 || ((N
+p
->nUsed
+2 >= p
->nAlloc
) && jsonGrow(p
,N
+2)!=0) ) return;
383 p
->zBuf
[p
->nUsed
++] = '"';
385 unsigned char c
= ((unsigned const char*)zIn
)[i
];
387 p
->zBuf
[p
->nUsed
++] = c
;
388 }else if( c
=='"' || c
=='\\' ){
390 if( (p
->nUsed
+N
+3-i
> p
->nAlloc
) && jsonGrow(p
,N
+3-i
)!=0 ) return;
391 p
->zBuf
[p
->nUsed
++] = '\\';
392 p
->zBuf
[p
->nUsed
++] = c
;
394 p
->zBuf
[p
->nUsed
++] = c
;
396 static const char aSpecial
[] = {
397 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
398 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
400 assert( sizeof(aSpecial
)==32 );
401 assert( aSpecial
['\b']=='b' );
402 assert( aSpecial
['\f']=='f' );
403 assert( aSpecial
['\n']=='n' );
404 assert( aSpecial
['\r']=='r' );
405 assert( aSpecial
['\t']=='t' );
406 assert( c
>=0 && c
<sizeof(aSpecial
) );
409 goto json_simple_escape
;
411 if( (p
->nUsed
+N
+7+i
> p
->nAlloc
) && jsonGrow(p
,N
+7-i
)!=0 ) return;
412 p
->zBuf
[p
->nUsed
++] = '\\';
413 p
->zBuf
[p
->nUsed
++] = 'u';
414 p
->zBuf
[p
->nUsed
++] = '0';
415 p
->zBuf
[p
->nUsed
++] = '0';
416 p
->zBuf
[p
->nUsed
++] = "0123456789abcdef"[c
>>4];
417 p
->zBuf
[p
->nUsed
++] = "0123456789abcdef"[c
&0xf];
420 p
->zBuf
[p
->nUsed
++] = '"';
421 assert( p
->nUsed
<p
->nAlloc
);
425 ** The zIn[0..N] string is a JSON5 string literal. Append to p a translation
426 ** of the string literal that standard JSON and that omits all JSON5
429 static void jsonAppendNormalizedString(JsonString
*p
, const char *zIn
, u32 N
){
431 jsonAppendChar(p
, '"');
435 for(i
=0; i
<N
&& zIn
[i
]!='\\'; i
++){}
437 jsonAppendRawNZ(p
, zIn
, i
);
442 assert( zIn
[0]=='\\' );
443 switch( (u8
)zIn
[1] ){
445 jsonAppendChar(p
, '\'');
448 jsonAppendRawNZ(p
, "\\u0009", 6);
451 jsonAppendRawNZ(p
, "\\u00", 4);
452 jsonAppendRawNZ(p
, &zIn
[2], 2);
457 jsonAppendRawNZ(p
, "\\u0000", 6);
469 assert( 0x80==(u8
)zIn
[2] );
470 assert( 0xa8==(u8
)zIn
[3] || 0xa9==(u8
)zIn
[3] );
475 jsonAppendRawNZ(p
, zIn
, 2);
481 jsonAppendChar(p
, '"');
485 ** The zIn[0..N] string is a JSON5 integer literal. Append to p a translation
486 ** of the string literal that standard JSON and that omits all JSON5
489 static void jsonAppendNormalizedInt(JsonString
*p
, const char *zIn
, u32 N
){
493 }else if( zIn
[0]=='-' ){
494 jsonAppendChar(p
, '-');
498 if( zIn
[0]=='0' && (zIn
[1]=='x' || zIn
[1]=='X') ){
500 int rc
= sqlite3DecOrHexToI64(zIn
, &i
);
502 jsonPrintf(100,p
,"%lld",i
);
505 jsonAppendRawNZ(p
, "9.0e999", 7);
510 jsonAppendRawNZ(p
, zIn
, N
);
514 ** The zIn[0..N] string is a JSON5 real literal. Append to p a translation
515 ** of the string literal that standard JSON and that omits all JSON5
518 static void jsonAppendNormalizedReal(JsonString
*p
, const char *zIn
, u32 N
){
523 }else if( zIn
[0]=='-' ){
524 jsonAppendChar(p
, '-');
529 jsonAppendChar(p
, '0');
532 if( zIn
[i
]=='.' && (i
+1==N
|| !sqlite3Isdigit(zIn
[i
+1])) ){
534 jsonAppendRaw(p
, zIn
, i
);
537 jsonAppendChar(p
, '0');
542 jsonAppendRawNZ(p
, zIn
, N
);
549 ** Append a function parameter value to the JSON string under
552 static void jsonAppendValue(
553 JsonString
*p
, /* Append to this JSON string */
554 sqlite3_value
*pValue
/* Value to append */
556 switch( sqlite3_value_type(pValue
) ){
558 jsonAppendRawNZ(p
, "null", 4);
562 jsonPrintf(100, p
, "%!0.15g", sqlite3_value_double(pValue
));
565 case SQLITE_INTEGER
: {
566 const char *z
= (const char*)sqlite3_value_text(pValue
);
567 u32 n
= (u32
)sqlite3_value_bytes(pValue
);
568 jsonAppendRaw(p
, z
, n
);
572 const char *z
= (const char*)sqlite3_value_text(pValue
);
573 u32 n
= (u32
)sqlite3_value_bytes(pValue
);
574 if( sqlite3_value_subtype(pValue
)==JSON_SUBTYPE
){
575 jsonAppendRaw(p
, z
, n
);
577 jsonAppendString(p
, z
, n
);
583 sqlite3_result_error(p
->pCtx
, "JSON cannot hold BLOB values", -1);
593 /* Make the JSON in p the result of the SQL function.
595 ** The JSON string is reset.
597 static void jsonResult(JsonString
*p
){
600 sqlite3_result_text64(p
->pCtx
, p
->zBuf
, p
->nUsed
,
601 SQLITE_TRANSIENT
, SQLITE_UTF8
);
602 }else if( jsonForceRCStr(p
) ){
603 sqlite3RCStrRef(p
->zBuf
);
604 sqlite3_result_text64(p
->pCtx
, p
->zBuf
, p
->nUsed
,
605 (void(*)(void*))sqlite3RCStrUnref
,
610 sqlite3_result_error_nomem(p
->pCtx
);
615 /**************************************************************************
616 ** Utility routines for dealing with JsonNode and JsonParse objects
617 **************************************************************************/
620 ** Return the number of consecutive JsonNode slots need to represent
621 ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
622 ** OBJECT types, the number might be larger.
624 ** Appended elements are not counted. The value returned is the number
625 ** by which the JsonNode counter should increment in order to go to the
628 static u32
jsonNodeSize(JsonNode
*pNode
){
629 return pNode
->eType
>=JSON_ARRAY
? pNode
->n
+1 : 1;
633 ** Reclaim all memory allocated by a JsonParse object. But do not
634 ** delete the JsonParse object itself.
636 static void jsonParseReset(JsonParse
*pParse
){
637 while( pParse
->pClup
){
638 JsonCleanup
*pTask
= pParse
->pClup
;
639 pParse
->pClup
= pTask
->pJCNext
;
640 pTask
->xOp(pTask
->pArg
);
643 assert( pParse
->nJPRef
<=1 );
645 sqlite3_free(pParse
->aNode
);
651 sqlite3_free(pParse
->aUp
);
654 if( pParse
->bJsonIsRCStr
){
655 sqlite3RCStrUnref(pParse
->zJson
);
657 pParse
->bJsonIsRCStr
= 0;
660 sqlite3RCStrUnref(pParse
->zAlt
);
666 ** Free a JsonParse object that was obtained from sqlite3_malloc().
668 ** Note that destroying JsonParse might call sqlite3RCStrUnref() to
669 ** destroy the zJson value. The RCStr object might recursively invoke
670 ** JsonParse to destroy this pParse object again. Take care to ensure
671 ** that this recursive destructor sequence terminates harmlessly.
673 static void jsonParseFree(JsonParse
*pParse
){
674 if( pParse
->nJPRef
>1 ){
677 jsonParseReset(pParse
);
678 sqlite3_free(pParse
);
683 ** Add a cleanup task to the JsonParse object.
685 ** If an OOM occurs, the cleanup operation happens immediately
686 ** and this function returns SQLITE_NOMEM.
688 static int jsonParseAddCleanup(
689 JsonParse
*pParse
, /* Add the cleanup task to this parser */
690 void(*xOp
)(void*), /* The cleanup task */
691 void *pArg
/* Argument to the cleanup */
693 JsonCleanup
*pTask
= sqlite3_malloc64( sizeof(*pTask
) );
699 pTask
->pJCNext
= pParse
->pClup
;
700 pParse
->pClup
= pTask
;
707 ** Convert the JsonNode pNode into a pure JSON string and
708 ** append to pOut. Subsubstructure is also included. Return
709 ** the number of JsonNode objects that are encoded.
711 static void jsonRenderNode(
712 JsonParse
*pParse
, /* the complete parse of the JSON */
713 JsonNode
*pNode
, /* The node to render */
714 JsonString
*pOut
/* Write JSON here */
717 while( (pNode
->jnFlags
& JNODE_REPLACE
)!=0 && pParse
->useMod
){
718 u32 idx
= (u32
)(pNode
- pParse
->aNode
);
719 u32 i
= pParse
->iSubst
;
720 while( 1 /*exit-by-break*/ ){
721 assert( i
<pParse
->nNode
);
722 assert( pParse
->aNode
[i
].eType
==JSON_SUBST
);
723 assert( pParse
->aNode
[i
].eU
==4 );
724 assert( pParse
->aNode
[i
].u
.iPrev
<i
);
725 if( pParse
->aNode
[i
].n
==idx
){
726 pNode
= &pParse
->aNode
[i
+1];
729 i
= pParse
->aNode
[i
].u
.iPrev
;
732 switch( pNode
->eType
){
734 assert( pNode
->eType
==JSON_NULL
);
735 jsonAppendRawNZ(pOut
, "null", 4);
739 jsonAppendRawNZ(pOut
, "true", 4);
743 jsonAppendRawNZ(pOut
, "false", 5);
747 assert( pNode
->eU
==1 );
748 if( pNode
->jnFlags
& JNODE_RAW
){
749 if( pNode
->jnFlags
& JNODE_LABEL
){
750 jsonAppendChar(pOut
, '"');
751 jsonAppendRaw(pOut
, pNode
->u
.zJContent
, pNode
->n
);
752 jsonAppendChar(pOut
, '"');
754 jsonAppendString(pOut
, pNode
->u
.zJContent
, pNode
->n
);
756 }else if( pNode
->jnFlags
& JNODE_JSON5
){
757 jsonAppendNormalizedString(pOut
, pNode
->u
.zJContent
, pNode
->n
);
759 assert( pNode
->n
>0 );
760 jsonAppendRawNZ(pOut
, pNode
->u
.zJContent
, pNode
->n
);
765 assert( pNode
->eU
==1 );
766 if( pNode
->jnFlags
& JNODE_JSON5
){
767 jsonAppendNormalizedReal(pOut
, pNode
->u
.zJContent
, pNode
->n
);
769 assert( pNode
->n
>0 );
770 jsonAppendRawNZ(pOut
, pNode
->u
.zJContent
, pNode
->n
);
775 assert( pNode
->eU
==1 );
776 if( pNode
->jnFlags
& JNODE_JSON5
){
777 jsonAppendNormalizedInt(pOut
, pNode
->u
.zJContent
, pNode
->n
);
779 assert( pNode
->n
>0 );
780 jsonAppendRawNZ(pOut
, pNode
->u
.zJContent
, pNode
->n
);
786 jsonAppendChar(pOut
, '[');
788 while( j
<=pNode
->n
){
789 if( (pNode
[j
].jnFlags
& JNODE_REMOVE
)==0 || pParse
->useMod
==0 ){
790 jsonAppendSeparator(pOut
);
791 jsonRenderNode(pParse
, &pNode
[j
], pOut
);
793 j
+= jsonNodeSize(&pNode
[j
]);
795 if( (pNode
->jnFlags
& JNODE_APPEND
)==0 ) break;
796 if( pParse
->useMod
==0 ) break;
797 assert( pNode
->eU
==2 );
798 pNode
= &pParse
->aNode
[pNode
->u
.iAppend
];
801 jsonAppendChar(pOut
, ']');
806 jsonAppendChar(pOut
, '{');
808 while( j
<=pNode
->n
){
809 if( (pNode
[j
+1].jnFlags
& JNODE_REMOVE
)==0 || pParse
->useMod
==0 ){
810 jsonAppendSeparator(pOut
);
811 jsonRenderNode(pParse
, &pNode
[j
], pOut
);
812 jsonAppendChar(pOut
, ':');
813 jsonRenderNode(pParse
, &pNode
[j
+1], pOut
);
815 j
+= 1 + jsonNodeSize(&pNode
[j
+1]);
817 if( (pNode
->jnFlags
& JNODE_APPEND
)==0 ) break;
818 if( pParse
->useMod
==0 ) break;
819 assert( pNode
->eU
==2 );
820 pNode
= &pParse
->aNode
[pNode
->u
.iAppend
];
823 jsonAppendChar(pOut
, '}');
830 ** Return a JsonNode and all its descendants as a JSON string.
832 static void jsonReturnJson(
833 JsonParse
*pParse
, /* The complete JSON */
834 JsonNode
*pNode
, /* Node to return */
835 sqlite3_context
*pCtx
, /* Return value for this function */
836 int bGenerateAlt
/* Also store the rendered text in zAlt */
840 sqlite3_result_error_nomem(pCtx
);
843 if( pParse
->nErr
==0 ){
845 jsonRenderNode(pParse
, pNode
, &s
);
846 if( bGenerateAlt
&& pParse
->zAlt
==0 && jsonForceRCStr(&s
) ){
847 pParse
->zAlt
= sqlite3RCStrRef(s
.zBuf
);
848 pParse
->nAlt
= s
.nUsed
;
851 sqlite3_result_subtype(pCtx
, JSON_SUBTYPE
);
856 ** Translate a single byte of Hex into an integer.
857 ** This routine only works if h really is a valid hexadecimal
858 ** character: 0..9a..fA..F
860 static u8
jsonHexToInt(int h
){
861 assert( (h
>='0' && h
<='9') || (h
>='a' && h
<='f') || (h
>='A' && h
<='F') );
867 return (u8
)(h
& 0xf);
871 ** Convert a 4-byte hex string into an integer
873 static u32
jsonHexToInt4(const char *z
){
875 assert( sqlite3Isxdigit(z
[0]) );
876 assert( sqlite3Isxdigit(z
[1]) );
877 assert( sqlite3Isxdigit(z
[2]) );
878 assert( sqlite3Isxdigit(z
[3]) );
879 v
= (jsonHexToInt(z
[0])<<12)
880 + (jsonHexToInt(z
[1])<<8)
881 + (jsonHexToInt(z
[2])<<4)
882 + jsonHexToInt(z
[3]);
887 ** Make the JsonNode the return value of the function.
889 static void jsonReturn(
890 JsonParse
*pParse
, /* Complete JSON parse tree */
891 JsonNode
*pNode
, /* Node to return */
892 sqlite3_context
*pCtx
/* Return value for this function */
894 switch( pNode
->eType
){
896 assert( pNode
->eType
==JSON_NULL
);
897 sqlite3_result_null(pCtx
);
901 sqlite3_result_int(pCtx
, 1);
905 sqlite3_result_int(pCtx
, 0);
914 assert( pNode
->eU
==1 );
915 z
= pNode
->u
.zJContent
;
916 if( z
[0]=='-' ){ z
++; bNeg
= 1; }
917 else if( z
[0]=='+' ){ z
++; }
918 rc
= sqlite3DecOrHexToI64(z
, &i
);
920 sqlite3_result_int64(pCtx
, bNeg
? -i
: i
);
921 }else if( rc
==3 && bNeg
){
922 sqlite3_result_int64(pCtx
, SMALLEST_INT64
);
931 assert( pNode
->eU
==1 );
933 z
= pNode
->u
.zJContent
;
934 sqlite3AtoF(z
, &r
, sqlite3Strlen30(z
), SQLITE_UTF8
);
935 sqlite3_result_double(pCtx
, r
);
939 if( pNode
->jnFlags
& JNODE_RAW
){
940 assert( pNode
->eU
==1 );
941 sqlite3_result_text(pCtx
, pNode
->u
.zJContent
, pNode
->n
,
943 }else if( (pNode
->jnFlags
& JNODE_ESCAPE
)==0 ){
944 /* JSON formatted without any backslash-escapes */
945 assert( pNode
->eU
==1 );
946 sqlite3_result_text(pCtx
, pNode
->u
.zJContent
+1, pNode
->n
-2,
949 /* Translate JSON formatted string into raw text */
956 assert( pNode
->eU
==1 );
957 z
= pNode
->u
.zJContent
;
958 zOut
= sqlite3_malloc( nOut
+1 );
960 sqlite3_result_error_nomem(pCtx
);
963 for(i
=1, j
=0; i
<n
-1; i
++){
968 u32 v
= jsonHexToInt4(z
+i
+1);
973 }else if( v
<=0x7ff ){
974 zOut
[j
++] = (char)(0xc0 | (v
>>6));
975 zOut
[j
++] = 0x80 | (v
&0x3f);
978 if( (v
&0xfc00)==0xd800
982 && ((vlo
= jsonHexToInt4(z
+i
+3))&0xfc00)==0xdc00
984 /* We have a surrogate pair */
985 v
= ((v
&0x3ff)<<10) + (vlo
&0x3ff) + 0x10000;
987 zOut
[j
++] = 0xf0 | (v
>>18);
988 zOut
[j
++] = 0x80 | ((v
>>12)&0x3f);
989 zOut
[j
++] = 0x80 | ((v
>>6)&0x3f);
990 zOut
[j
++] = 0x80 | (v
&0x3f);
992 zOut
[j
++] = 0xe0 | (v
>>12);
993 zOut
[j
++] = 0x80 | ((v
>>6)&0x3f);
994 zOut
[j
++] = 0x80 | (v
&0x3f);
1010 }else if( c
=='\'' || c
=='"' || c
=='/' || c
=='\\' ){
1011 /* pass through unchanged */
1015 c
= (jsonHexToInt(z
[i
+1])<<4) | jsonHexToInt(z
[i
+2]);
1017 }else if( c
=='\r' && z
[i
+1]=='\n' ){
1020 }else if( 0xe2==(u8
)c
){
1021 assert( 0x80==(u8
)z
[i
+1] );
1022 assert( 0xa8==(u8
)z
[i
+2] || 0xa9==(u8
)z
[i
+2] );
1028 } /* end if( c=='\\' ) */
1032 sqlite3_result_text(pCtx
, zOut
, j
, sqlite3_free
);
1038 jsonReturnJson(pParse
, pNode
, pCtx
, 0);
1044 /* Forward reference */
1045 static int jsonParseAddNode(JsonParse
*,u32
,u32
,const char*);
1048 ** A macro to hint to the compiler that a function should not be
1051 #if defined(__GNUC__)
1052 # define JSON_NOINLINE __attribute__((noinline))
1053 #elif defined(_MSC_VER) && _MSC_VER>=1310
1054 # define JSON_NOINLINE __declspec(noinline)
1056 # define JSON_NOINLINE
1061 ** Add a single node to pParse->aNode after first expanding the
1062 ** size of the aNode array. Return the index of the new node.
1064 ** If an OOM error occurs, set pParse->oom and return -1.
1066 static JSON_NOINLINE
int jsonParseAddNodeExpand(
1067 JsonParse
*pParse
, /* Append the node to this object */
1068 u32 eType
, /* Node type */
1069 u32 n
, /* Content size or sub-node count */
1070 const char *zContent
/* Content */
1074 assert( pParse
->nNode
>=pParse
->nAlloc
);
1075 if( pParse
->oom
) return -1;
1076 nNew
= pParse
->nAlloc
*2 + 10;
1077 pNew
= sqlite3_realloc64(pParse
->aNode
, sizeof(JsonNode
)*nNew
);
1082 pParse
->nAlloc
= sqlite3_msize(pNew
)/sizeof(JsonNode
);
1083 pParse
->aNode
= pNew
;
1084 assert( pParse
->nNode
<pParse
->nAlloc
);
1085 return jsonParseAddNode(pParse
, eType
, n
, zContent
);
1089 ** Create a new JsonNode instance based on the arguments and append that
1090 ** instance to the JsonParse. Return the index in pParse->aNode[] of the
1091 ** new node, or -1 if a memory allocation fails.
1093 static int jsonParseAddNode(
1094 JsonParse
*pParse
, /* Append the node to this object */
1095 u32 eType
, /* Node type */
1096 u32 n
, /* Content size or sub-node count */
1097 const char *zContent
/* Content */
1100 assert( pParse
->aNode
!=0 || pParse
->nNode
>=pParse
->nAlloc
);
1101 if( pParse
->nNode
>=pParse
->nAlloc
){
1102 return jsonParseAddNodeExpand(pParse
, eType
, n
, zContent
);
1104 assert( pParse
->aNode
!=0 );
1105 p
= &pParse
->aNode
[pParse
->nNode
];
1107 p
->eType
= (u8
)(eType
& 0xff);
1108 p
->jnFlags
= (u8
)(eType
>> 8);
1109 VVA( p
->eU
= zContent
? 1 : 0 );
1111 p
->u
.zJContent
= zContent
;
1112 return pParse
->nNode
++;
1116 ** Add an array of new nodes to the current pParse->aNode array.
1117 ** Return the index of the first node added.
1119 ** If an OOM error occurs, set pParse->oom.
1121 static void jsonParseAddNodeArray(
1122 JsonParse
*pParse
, /* Append the node to this object */
1123 JsonNode
*aNode
, /* Array of nodes to add */
1124 u32 nNode
/* Number of elements in aNew */
1128 if( pParse
->nNode
+ nNode
> pParse
->nAlloc
){
1129 u32 nNew
= pParse
->nNode
+ nNode
;
1130 JsonNode
*aNew
= sqlite3_realloc64(pParse
->aNode
, nNew
*sizeof(JsonNode
));
1135 pParse
->nAlloc
= sqlite3_msize(aNew
)/sizeof(JsonNode
);
1136 pParse
->aNode
= aNew
;
1138 memcpy(&pParse
->aNode
[pParse
->nNode
], aNode
, nNode
*sizeof(JsonNode
));
1139 pParse
->nNode
+= nNode
;
1143 ** Add a new JSON_SUBST node. The node immediately following
1144 ** this new node will be the substitute content for iNode.
1146 static int jsonParseAddSubstNode(
1147 JsonParse
*pParse
, /* Add the JSON_SUBST here */
1148 u32 iNode
/* References this node */
1150 int idx
= jsonParseAddNode(pParse
, JSON_SUBST
, iNode
, 0);
1151 if( pParse
->oom
) return -1;
1152 pParse
->aNode
[iNode
].jnFlags
|= JNODE_REPLACE
;
1153 pParse
->aNode
[idx
].eU
= 4;
1154 pParse
->aNode
[idx
].u
.iPrev
= pParse
->iSubst
;
1155 pParse
->iSubst
= idx
;
1162 ** Return true if z[] begins with 2 (or more) hexadecimal digits
1164 static int jsonIs2Hex(const char *z
){
1165 return sqlite3Isxdigit(z
[0]) && sqlite3Isxdigit(z
[1]);
1169 ** Return true if z[] begins with 4 (or more) hexadecimal digits
1171 static int jsonIs4Hex(const char *z
){
1172 return jsonIs2Hex(z
) && jsonIs2Hex(&z
[2]);
1176 ** Return the number of bytes of JSON5 whitespace at the beginning of
1177 ** the input string z[].
1179 ** JSON5 whitespace consists of any of the following characters:
1181 ** Unicode UTF-8 Name
1182 ** U+0009 09 horizontal tab
1183 ** U+000a 0a line feed
1184 ** U+000b 0b vertical tab
1185 ** U+000c 0c form feed
1186 ** U+000d 0d carriage return
1188 ** U+00a0 c2 a0 non-breaking space
1189 ** U+1680 e1 9a 80 ogham space mark
1190 ** U+2000 e2 80 80 en quad
1191 ** U+2001 e2 80 81 em quad
1192 ** U+2002 e2 80 82 en space
1193 ** U+2003 e2 80 83 em space
1194 ** U+2004 e2 80 84 three-per-em space
1195 ** U+2005 e2 80 85 four-per-em space
1196 ** U+2006 e2 80 86 six-per-em space
1197 ** U+2007 e2 80 87 figure space
1198 ** U+2008 e2 80 88 punctuation space
1199 ** U+2009 e2 80 89 thin space
1200 ** U+200a e2 80 8a hair space
1201 ** U+2028 e2 80 a8 line separator
1202 ** U+2029 e2 80 a9 paragraph separator
1203 ** U+202f e2 80 af narrow no-break space (NNBSP)
1204 ** U+205f e2 81 9f medium mathematical space (MMSP)
1205 ** U+3000 e3 80 80 ideographical space
1206 ** U+FEFF ef bb bf byte order mark
1208 ** In addition, comments between '/', '*' and '*', '/' and
1209 ** from '/', '/' to end-of-line are also considered to be whitespace.
1211 static int json5Whitespace(const char *zIn
){
1213 const u8
*z
= (u8
*)zIn
;
1214 while( 1 /*exit by "goto whitespace_done"*/ ){
1226 if( z
[n
+1]=='*' && z
[n
+2]!=0 ){
1228 for(j
=n
+3; z
[j
]!='/' || z
[j
-1]!='*'; j
++){
1229 if( z
[j
]==0 ) goto whitespace_done
;
1233 }else if( z
[n
+1]=='/' ){
1236 for(j
=n
+2; (c
= z
[j
])!=0; j
++){
1237 if( c
=='\n' || c
=='\r' ) break;
1238 if( 0xe2==(u8
)c
&& 0x80==(u8
)z
[j
+1]
1239 && (0xa8==(u8
)z
[j
+2] || 0xa9==(u8
)z
[j
+2])
1249 goto whitespace_done
;
1256 goto whitespace_done
;
1259 if( z
[n
+1]==0x9a && z
[n
+2]==0x80 ){
1263 goto whitespace_done
;
1268 if( c
<0x80 ) goto whitespace_done
;
1269 if( c
<=0x8a || c
==0xa8 || c
==0xa9 || c
==0xaf ){
1273 }else if( z
[n
+1]==0x81 && z
[n
+2]==0x9f ){
1277 goto whitespace_done
;
1280 if( z
[n
+1]==0x80 && z
[n
+2]==0x80 ){
1284 goto whitespace_done
;
1287 if( z
[n
+1]==0xbb && z
[n
+2]==0xbf ){
1291 goto whitespace_done
;
1294 goto whitespace_done
;
1303 ** Extra floating-point literals to allow in JSON.
1305 static const struct NanInfName
{
1314 { 'i', 'I', 3, JSON_REAL
, 7, "inf", "9.0e999" },
1315 { 'i', 'I', 8, JSON_REAL
, 7, "infinity", "9.0e999" },
1316 { 'n', 'N', 3, JSON_NULL
, 4, "NaN", "null" },
1317 { 'q', 'Q', 4, JSON_NULL
, 4, "QNaN", "null" },
1318 { 's', 'S', 4, JSON_NULL
, 4, "SNaN", "null" },
1322 ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
1323 ** index of the first character past the end of the value parsed.
1325 ** Special return values:
1334 static int jsonParseValue(JsonParse
*pParse
, u32 i
){
1340 const char *z
= pParse
->zJson
;
1345 iThis
= jsonParseAddNode(pParse
, JSON_OBJECT
, 0, 0);
1346 if( iThis
<0 ) return -1;
1347 if( ++pParse
->iDepth
> JSON_MAX_DEPTH
){
1352 u32 nNode
= pParse
->nNode
;
1353 x
= jsonParseValue(pParse
, j
);
1357 if( pParse
->nNode
!=(u32
)iThis
+1 ) pParse
->hasNonstd
= 1;
1360 j
+= json5Whitespace(&z
[j
]);
1361 if( sqlite3JsonId1(z
[j
])
1362 || (z
[j
]=='\\' && z
[j
+1]=='u' && jsonIs4Hex(&z
[j
+2]))
1365 while( (sqlite3JsonId2(z
[k
]) && json5Whitespace(&z
[k
])==0)
1366 || (z
[k
]=='\\' && z
[k
+1]=='u' && jsonIs4Hex(&z
[k
+2]))
1370 jsonParseAddNode(pParse
, JSON_STRING
| (JNODE_RAW
<<8), k
-j
, &z
[j
]);
1371 pParse
->hasNonstd
= 1;
1374 if( x
!=-1 ) pParse
->iErr
= j
;
1378 if( pParse
->oom
) return -1;
1379 pNode
= &pParse
->aNode
[nNode
];
1380 if( pNode
->eType
!=JSON_STRING
){
1384 pNode
->jnFlags
|= JNODE_LABEL
;
1389 if( fast_isspace(z
[j
]) ){
1390 do{ j
++; }while( fast_isspace(z
[j
]) );
1393 goto parse_object_value
;
1396 x
= jsonParseValue(pParse
, j
);
1398 if( x
!=(-1) ) pParse
->iErr
= j
;
1404 x
= jsonParseValue(pParse
, j
);
1406 if( x
!=(-1) ) pParse
->iErr
= j
;
1412 }else if( z
[j
]=='}' ){
1415 if( fast_isspace(z
[j
]) ){
1416 do{ j
++; }while( fast_isspace(z
[j
]) );
1419 }else if( z
[j
]=='}' ){
1423 x
= jsonParseValue(pParse
, j
);
1436 pParse
->aNode
[iThis
].n
= pParse
->nNode
- (u32
)iThis
- 1;
1442 iThis
= jsonParseAddNode(pParse
, JSON_ARRAY
, 0, 0);
1443 if( iThis
<0 ) return -1;
1444 if( ++pParse
->iDepth
> JSON_MAX_DEPTH
){
1448 memset(&pParse
->aNode
[iThis
].u
, 0, sizeof(pParse
->aNode
[iThis
].u
));
1450 x
= jsonParseValue(pParse
, j
);
1454 if( pParse
->nNode
!=(u32
)iThis
+1 ) pParse
->hasNonstd
= 1;
1457 if( x
!=(-1) ) pParse
->iErr
= j
;
1463 }else if( z
[j
]==']' ){
1466 if( fast_isspace(z
[j
]) ){
1467 do{ j
++; }while( fast_isspace(z
[j
]) );
1470 }else if( z
[j
]==']' ){
1474 x
= jsonParseValue(pParse
, j
);
1487 pParse
->aNode
[iThis
].n
= pParse
->nNode
- (u32
)iThis
- 1;
1494 pParse
->hasNonstd
= 1;
1495 jnFlags
= JNODE_JSON5
;
1503 if( jsonIsOk
[(unsigned char)z
[j
]] ) continue;
1507 }else if( c
=='\\' ){
1509 if( c
=='"' || c
=='\\' || c
=='/' || c
=='b' || c
=='f'
1510 || c
=='n' || c
=='r' || c
=='t'
1511 || (c
=='u' && jsonIs4Hex(&z
[j
+1])) ){
1512 jnFlags
|= JNODE_ESCAPE
;
1513 }else if( c
=='\'' || c
=='0' || c
=='v' || c
=='\n'
1514 || (0xe2==(u8
)c
&& 0x80==(u8
)z
[j
+1]
1515 && (0xa8==(u8
)z
[j
+2] || 0xa9==(u8
)z
[j
+2]))
1516 || (c
=='x' && jsonIs2Hex(&z
[j
+1])) ){
1517 jnFlags
|= (JNODE_ESCAPE
|JNODE_JSON5
);
1518 pParse
->hasNonstd
= 1;
1519 }else if( c
=='\r' ){
1520 if( z
[j
+1]=='\n' ) j
++;
1521 jnFlags
|= (JNODE_ESCAPE
|JNODE_JSON5
);
1522 pParse
->hasNonstd
= 1;
1527 }else if( c
<=0x1f ){
1528 /* Control characters are not allowed in strings */
1533 jsonParseAddNode(pParse
, JSON_STRING
| (jnFlags
<<8), j
+1-i
, &z
[i
]);
1537 if( strncmp(z
+i
,"true",4)==0 && !sqlite3Isalnum(z
[i
+4]) ){
1538 jsonParseAddNode(pParse
, JSON_TRUE
, 0, 0);
1545 if( strncmp(z
+i
,"false",5)==0 && !sqlite3Isalnum(z
[i
+5]) ){
1546 jsonParseAddNode(pParse
, JSON_FALSE
, 0, 0);
1553 u8 seenDP
, seenE
, jnFlags
;
1554 pParse
->hasNonstd
= 1;
1555 jnFlags
= JNODE_JSON5
;
1558 if( sqlite3Isdigit(z
[i
+1]) ){
1559 pParse
->hasNonstd
= 1;
1560 jnFlags
= JNODE_JSON5
;
1563 goto parse_number_2
;
1583 assert( '-' < '0' );
1584 assert( '+' < '0' );
1585 assert( '.' < '0' );
1590 if( (z
[i
+1]=='x' || z
[i
+1]=='X') && sqlite3Isxdigit(z
[i
+2]) ){
1591 assert( seenDP
==JSON_INT
);
1592 pParse
->hasNonstd
= 1;
1593 jnFlags
|= JNODE_JSON5
;
1594 for(j
=i
+3; sqlite3Isxdigit(z
[j
]); j
++){}
1595 goto parse_number_finish
;
1596 }else if( sqlite3Isdigit(z
[i
+1]) ){
1601 if( !sqlite3Isdigit(z
[i
+1]) ){
1602 /* JSON5 allows for "+Infinity" and "-Infinity" using exactly
1603 ** that case. SQLite also allows these in any case and it allows
1604 ** "+inf" and "-inf". */
1605 if( (z
[i
+1]=='I' || z
[i
+1]=='i')
1606 && sqlite3StrNICmp(&z
[i
+1], "inf",3)==0
1608 pParse
->hasNonstd
= 1;
1610 jsonParseAddNode(pParse
, JSON_REAL
, 8, "-9.0e999");
1612 jsonParseAddNode(pParse
, JSON_REAL
, 7, "9.0e999");
1614 return i
+ (sqlite3StrNICmp(&z
[i
+4],"inity",5)==0 ? 9 : 4);
1617 pParse
->hasNonstd
= 1;
1618 jnFlags
|= JNODE_JSON5
;
1619 goto parse_number_2
;
1625 if( sqlite3Isdigit(z
[i
+2]) ){
1628 }else if( (z
[i
+2]=='x' || z
[i
+2]=='X') && sqlite3Isxdigit(z
[i
+3]) ){
1629 pParse
->hasNonstd
= 1;
1630 jnFlags
|= JNODE_JSON5
;
1631 for(j
=i
+4; sqlite3Isxdigit(z
[j
]); j
++){}
1632 goto parse_number_finish
;
1640 if( sqlite3Isdigit(c
) ) continue;
1642 if( seenDP
==JSON_REAL
){
1649 if( c
=='e' || c
=='E' ){
1651 if( ALWAYS(z
[j
-1]=='.') && ALWAYS(j
-2>=i
) && sqlite3Isdigit(z
[j
-2]) ){
1652 pParse
->hasNonstd
= 1;
1653 jnFlags
|= JNODE_JSON5
;
1666 if( c
=='+' || c
=='-' ){
1670 if( c
<'0' || c
>'9' ){
1679 if( ALWAYS(z
[j
-1]=='.') && ALWAYS(j
-2>=i
) && sqlite3Isdigit(z
[j
-2]) ){
1680 pParse
->hasNonstd
= 1;
1681 jnFlags
|= JNODE_JSON5
;
1687 parse_number_finish
:
1688 jsonParseAddNode(pParse
, seenDP
| (jnFlags
<<8), j
- i
, &z
[i
]);
1693 return -2; /* End of {...} */
1697 return -3; /* End of [...] */
1701 return -4; /* List separator */
1705 return -5; /* Object label/value separator */
1708 return 0; /* End of file */
1716 }while( fast_isspace(z
[i
]) );
1717 goto json_parse_restart
;
1727 j
= json5Whitespace(&z
[i
]);
1730 pParse
->hasNonstd
= 1;
1731 goto json_parse_restart
;
1737 if( strncmp(z
+i
,"null",4)==0 && !sqlite3Isalnum(z
[i
+4]) ){
1738 jsonParseAddNode(pParse
, JSON_NULL
, 0, 0);
1741 /* fall-through into the default case that checks for NaN */
1747 for(k
=0; k
<sizeof(aNanInfName
)/sizeof(aNanInfName
[0]); k
++){
1748 if( c
!=aNanInfName
[k
].c1
&& c
!=aNanInfName
[k
].c2
) continue;
1749 nn
= aNanInfName
[k
].n
;
1750 if( sqlite3StrNICmp(&z
[i
], aNanInfName
[k
].zMatch
, nn
)!=0 ){
1753 if( sqlite3Isalnum(z
[i
+nn
]) ) continue;
1754 jsonParseAddNode(pParse
, aNanInfName
[k
].eType
,
1755 aNanInfName
[k
].nRepl
, aNanInfName
[k
].zRepl
);
1756 pParse
->hasNonstd
= 1;
1760 return -1; /* Syntax error */
1762 } /* End switch(z[i]) */
1766 ** Parse a complete JSON string. Return 0 on success or non-zero if there
1767 ** are any errors. If an error occurs, free all memory held by pParse,
1768 ** but not pParse itself.
1770 ** pParse must be initialized to an empty parse object prior to calling
1773 static int jsonParse(
1774 JsonParse
*pParse
, /* Initialize and fill this JsonParse object */
1775 sqlite3_context
*pCtx
/* Report errors here */
1778 const char *zJson
= pParse
->zJson
;
1779 i
= jsonParseValue(pParse
, 0);
1780 if( pParse
->oom
) i
= -1;
1782 assert( pParse
->iDepth
==0 );
1783 while( fast_isspace(zJson
[i
]) ) i
++;
1785 i
+= json5Whitespace(&zJson
[i
]);
1787 jsonParseReset(pParse
);
1790 pParse
->hasNonstd
= 1;
1796 sqlite3_result_error_nomem(pCtx
);
1798 sqlite3_result_error(pCtx
, "malformed JSON", -1);
1801 jsonParseReset(pParse
);
1808 /* Mark node i of pParse as being a child of iParent. Call recursively
1809 ** to fill in all the descendants of node i.
1811 static void jsonParseFillInParentage(JsonParse
*pParse
, u32 i
, u32 iParent
){
1812 JsonNode
*pNode
= &pParse
->aNode
[i
];
1814 pParse
->aUp
[i
] = iParent
;
1815 switch( pNode
->eType
){
1817 for(j
=1; j
<=pNode
->n
; j
+= jsonNodeSize(pNode
+j
)){
1818 jsonParseFillInParentage(pParse
, i
+j
, i
);
1823 for(j
=1; j
<=pNode
->n
; j
+= jsonNodeSize(pNode
+j
+1)+1){
1824 pParse
->aUp
[i
+j
] = i
;
1825 jsonParseFillInParentage(pParse
, i
+j
+1, i
);
1836 ** Compute the parentage of all nodes in a completed parse.
1838 static int jsonParseFindParents(JsonParse
*pParse
){
1840 assert( pParse
->aUp
==0 );
1841 aUp
= pParse
->aUp
= sqlite3_malloc64( sizeof(u32
)*pParse
->nNode
);
1844 return SQLITE_NOMEM
;
1846 jsonParseFillInParentage(pParse
, 0, 0);
1851 ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
1853 #define JSON_CACHE_ID (-429938) /* First cache entry */
1854 #define JSON_CACHE_SZ 4 /* Max number of cache entries */
1857 ** Obtain a complete parse of the JSON found in the pJson argument
1859 ** Use the sqlite3_get_auxdata() cache to find a preexisting parse
1860 ** if it is available. If the cache is not available or if it
1861 ** is no longer valid, parse the JSON again and return the new parse.
1862 ** Also register the new parse so that it will be available for
1863 ** future sqlite3_get_auxdata() calls.
1865 ** If an error occurs and pErrCtx!=0 then report the error on pErrCtx
1868 ** The returned pointer (if it is not NULL) is owned by the cache in
1869 ** most cases, not the caller. The caller does NOT need to invoke
1870 ** jsonParseFree(), in most cases.
1872 ** Except, if an error occurs and pErrCtx==0 then return the JsonParse
1873 ** object with JsonParse.nErr non-zero and the caller will own the JsonParse
1874 ** object. In that case, it will be the responsibility of the caller to
1875 ** invoke jsonParseFree(). To summarize:
1877 ** pErrCtx!=0 || p->nErr==0 ==> Return value p is owned by the
1878 ** cache. Call does not need to
1881 ** pErrCtx==0 && p->nErr!=0 ==> Return value is owned by the caller
1882 ** and so the caller must free it.
1884 static JsonParse
*jsonParseCached(
1885 sqlite3_context
*pCtx
, /* Context to use for cache search */
1886 sqlite3_value
*pJson
, /* Function param containing JSON text */
1887 sqlite3_context
*pErrCtx
, /* Write parse errors here if not NULL */
1888 int bUnedited
/* No prior edits allowed */
1890 char *zJson
= (char*)sqlite3_value_text(pJson
);
1891 int nJson
= sqlite3_value_bytes(pJson
);
1893 JsonParse
*pMatch
= 0;
1896 u32 iMinHold
= 0xffffffff;
1900 if( zJson
==0 ) return 0;
1901 for(iKey
=0; iKey
<JSON_CACHE_SZ
; iKey
++){
1902 p
= (JsonParse
*)sqlite3_get_auxdata(pCtx
, JSON_CACHE_ID
+iKey
);
1909 && (p
->hasMod
==0 || bUnedited
==0)
1910 && (p
->zJson
==zJson
|| memcmp(p
->zJson
,zJson
,nJson
)==0)
1920 && memcmp(p
->zAlt
, zJson
, nJson
)==0
1925 }else if( p
->iHold
<iMinHold
){
1926 iMinHold
= p
->iHold
;
1929 if( p
->iHold
>iMaxHold
){
1930 iMaxHold
= p
->iHold
;
1934 /* The input JSON text was found in the cache. Use the preexisting
1935 ** parse of this JSON */
1937 pMatch
->iHold
= iMaxHold
+1;
1938 assert( pMatch
->nJPRef
>0 ); /* pMatch is owned by the cache */
1942 /* The input JSON was not found anywhere in the cache. We will need
1943 ** to parse it ourselves and generate a new JsonParse object.
1945 bJsonRCStr
= sqlite3ValueIsOfClass(pJson
,(void(*)(void*))sqlite3RCStrUnref
);
1946 p
= sqlite3_malloc64( sizeof(*p
) + (bJsonRCStr
? 0 : nJson
+1) );
1948 sqlite3_result_error_nomem(pCtx
);
1951 memset(p
, 0, sizeof(*p
));
1953 p
->zJson
= sqlite3RCStrRef(zJson
);
1954 p
->bJsonIsRCStr
= 1;
1956 p
->zJson
= (char*)&p
[1];
1957 memcpy(p
->zJson
, zJson
, nJson
+1);
1960 if( jsonParse(p
, pErrCtx
) ){
1963 assert( p
->nJPRef
==1 ); /* Caller will own the new JsonParse object p */
1970 p
->iHold
= iMaxHold
+1;
1971 /* Transfer ownership of the new JsonParse to the cache */
1972 sqlite3_set_auxdata(pCtx
, JSON_CACHE_ID
+iMinKey
, p
,
1973 (void(*)(void*))jsonParseFree
);
1974 return (JsonParse
*)sqlite3_get_auxdata(pCtx
, JSON_CACHE_ID
+iMinKey
);
1978 ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1981 static int jsonLabelCompare(const JsonNode
*pNode
, const char *zKey
, u32 nKey
){
1982 assert( pNode
->eU
==1 );
1983 if( pNode
->jnFlags
& JNODE_RAW
){
1984 if( pNode
->n
!=nKey
) return 0;
1985 return strncmp(pNode
->u
.zJContent
, zKey
, nKey
)==0;
1987 if( pNode
->n
!=nKey
+2 ) return 0;
1988 return strncmp(pNode
->u
.zJContent
+1, zKey
, nKey
)==0;
1991 static int jsonSameLabel(const JsonNode
*p1
, const JsonNode
*p2
){
1992 if( p1
->jnFlags
& JNODE_RAW
){
1993 return jsonLabelCompare(p2
, p1
->u
.zJContent
, p1
->n
);
1994 }else if( p2
->jnFlags
& JNODE_RAW
){
1995 return jsonLabelCompare(p1
, p2
->u
.zJContent
, p2
->n
);
1997 return p1
->n
==p2
->n
&& strncmp(p1
->u
.zJContent
,p2
->u
.zJContent
,p1
->n
)==0;
2001 /* forward declaration */
2002 static JsonNode
*jsonLookupAppend(JsonParse
*,const char*,int*,const char**);
2005 ** Search along zPath to find the node specified. Return a pointer
2006 ** to that node, or NULL if zPath is malformed or if there is no such
2009 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
2010 ** possible to do so and if no existing node corresponds to zPath. If
2011 ** new nodes are appended *pApnd is set to 1.
2013 static JsonNode
*jsonLookupStep(
2014 JsonParse
*pParse
, /* The JSON to search */
2015 u32 iRoot
, /* Begin the search at this node */
2016 const char *zPath
, /* The path to search */
2017 int *pApnd
, /* Append nodes to complete path if not NULL */
2018 const char **pzErr
/* Make *pzErr point to any syntax error in zPath */
2023 if( pParse
->oom
) return 0;
2024 pRoot
= &pParse
->aNode
[iRoot
];
2025 if( pRoot
->jnFlags
& (JNODE_REPLACE
|JNODE_REMOVE
) && pParse
->useMod
){
2026 while( (pRoot
->jnFlags
& JNODE_REPLACE
)!=0 ){
2027 u32 idx
= (u32
)(pRoot
- pParse
->aNode
);
2029 while( 1 /*exit-by-break*/ ){
2030 assert( i
<pParse
->nNode
);
2031 assert( pParse
->aNode
[i
].eType
==JSON_SUBST
);
2032 assert( pParse
->aNode
[i
].eU
==4 );
2033 assert( pParse
->aNode
[i
].u
.iPrev
<i
);
2034 if( pParse
->aNode
[i
].n
==idx
){
2035 pRoot
= &pParse
->aNode
[i
+1];
2039 i
= pParse
->aNode
[i
].u
.iPrev
;
2042 if( pRoot
->jnFlags
& JNODE_REMOVE
){
2046 if( zPath
[0]==0 ) return pRoot
;
2047 if( zPath
[0]=='.' ){
2048 if( pRoot
->eType
!=JSON_OBJECT
) return 0;
2050 if( zPath
[0]=='"' ){
2052 for(i
=1; zPath
[i
] && zPath
[i
]!='"'; i
++){}
2060 testcase( nKey
==0 );
2063 for(i
=0; zPath
[i
] && zPath
[i
]!='.' && zPath
[i
]!='['; i
++){}
2072 while( j
<=pRoot
->n
){
2073 if( jsonLabelCompare(pRoot
+j
, zKey
, nKey
) ){
2074 return jsonLookupStep(pParse
, iRoot
+j
+1, &zPath
[i
], pApnd
, pzErr
);
2077 j
+= jsonNodeSize(&pRoot
[j
]);
2079 if( (pRoot
->jnFlags
& JNODE_APPEND
)==0 ) break;
2080 if( pParse
->useMod
==0 ) break;
2081 assert( pRoot
->eU
==2 );
2082 iRoot
= pRoot
->u
.iAppend
;
2083 pRoot
= &pParse
->aNode
[iRoot
];
2089 assert( pParse
->useMod
);
2090 iStart
= jsonParseAddNode(pParse
, JSON_OBJECT
, 2, 0);
2091 iLabel
= jsonParseAddNode(pParse
, JSON_STRING
, nKey
, zKey
);
2093 pNode
= jsonLookupAppend(pParse
, zPath
, pApnd
, pzErr
);
2094 if( pParse
->oom
) return 0;
2096 pRoot
= &pParse
->aNode
[iRoot
];
2097 assert( pRoot
->eU
==0 );
2098 pRoot
->u
.iAppend
= iStart
;
2099 pRoot
->jnFlags
|= JNODE_APPEND
;
2100 VVA( pRoot
->eU
= 2 );
2101 pParse
->aNode
[iLabel
].jnFlags
|= JNODE_RAW
;
2105 }else if( zPath
[0]=='[' ){
2108 while( sqlite3Isdigit(zPath
[j
]) ){
2109 i
= i
*10 + zPath
[j
] - '0';
2112 if( j
<2 || zPath
[j
]!=']' ){
2113 if( zPath
[1]=='#' ){
2114 JsonNode
*pBase
= pRoot
;
2116 if( pRoot
->eType
!=JSON_ARRAY
) return 0;
2118 while( j
<=pBase
->n
){
2119 if( (pBase
[j
].jnFlags
& JNODE_REMOVE
)==0 || pParse
->useMod
==0 ) i
++;
2120 j
+= jsonNodeSize(&pBase
[j
]);
2122 if( (pBase
->jnFlags
& JNODE_APPEND
)==0 ) break;
2123 if( pParse
->useMod
==0 ) break;
2124 assert( pBase
->eU
==2 );
2125 iBase
= pBase
->u
.iAppend
;
2126 pBase
= &pParse
->aNode
[iBase
];
2130 if( zPath
[2]=='-' && sqlite3Isdigit(zPath
[3]) ){
2134 x
= x
*10 + zPath
[j
] - '0';
2136 }while( sqlite3Isdigit(zPath
[j
]) );
2140 if( zPath
[j
]!=']' ){
2149 if( pRoot
->eType
!=JSON_ARRAY
) return 0;
2154 && (i
>0 || ((pRoot
[j
].jnFlags
& JNODE_REMOVE
)!=0 && pParse
->useMod
))
2156 if( (pRoot
[j
].jnFlags
& JNODE_REMOVE
)==0 || pParse
->useMod
==0 ) i
--;
2157 j
+= jsonNodeSize(&pRoot
[j
]);
2159 if( (pRoot
->jnFlags
& JNODE_APPEND
)==0 ) break;
2160 if( pParse
->useMod
==0 ) break;
2161 assert( pRoot
->eU
==2 );
2162 iRoot
= pRoot
->u
.iAppend
;
2163 pRoot
= &pParse
->aNode
[iRoot
];
2167 return jsonLookupStep(pParse
, iRoot
+j
, zPath
, pApnd
, pzErr
);
2169 if( i
==0 && pApnd
){
2172 assert( pParse
->useMod
);
2173 iStart
= jsonParseAddNode(pParse
, JSON_ARRAY
, 1, 0);
2174 pNode
= jsonLookupAppend(pParse
, zPath
, pApnd
, pzErr
);
2175 if( pParse
->oom
) return 0;
2177 pRoot
= &pParse
->aNode
[iRoot
];
2178 assert( pRoot
->eU
==0 );
2179 pRoot
->u
.iAppend
= iStart
;
2180 pRoot
->jnFlags
|= JNODE_APPEND
;
2181 VVA( pRoot
->eU
= 2 );
2192 ** Append content to pParse that will complete zPath. Return a pointer
2193 ** to the inserted node, or return NULL if the append fails.
2195 static JsonNode
*jsonLookupAppend(
2196 JsonParse
*pParse
, /* Append content to the JSON parse */
2197 const char *zPath
, /* Description of content to append */
2198 int *pApnd
, /* Set this flag to 1 */
2199 const char **pzErr
/* Make this point to any syntax error */
2203 jsonParseAddNode(pParse
, JSON_NULL
, 0, 0);
2204 return pParse
->oom
? 0 : &pParse
->aNode
[pParse
->nNode
-1];
2206 if( zPath
[0]=='.' ){
2207 jsonParseAddNode(pParse
, JSON_OBJECT
, 0, 0);
2208 }else if( strncmp(zPath
,"[0]",3)==0 ){
2209 jsonParseAddNode(pParse
, JSON_ARRAY
, 0, 0);
2213 if( pParse
->oom
) return 0;
2214 return jsonLookupStep(pParse
, pParse
->nNode
-1, zPath
, pApnd
, pzErr
);
2218 ** Return the text of a syntax error message on a JSON path. Space is
2219 ** obtained from sqlite3_malloc().
2221 static char *jsonPathSyntaxError(const char *zErr
){
2222 return sqlite3_mprintf("JSON path error near '%q'", zErr
);
2226 ** Do a node lookup using zPath. Return a pointer to the node on success.
2227 ** Return NULL if not found or if there is an error.
2229 ** On an error, write an error message into pCtx and increment the
2230 ** pParse->nErr counter.
2232 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
2233 ** nodes are appended.
2235 static JsonNode
*jsonLookup(
2236 JsonParse
*pParse
, /* The JSON to search */
2237 const char *zPath
, /* The path to search */
2238 int *pApnd
, /* Append nodes to complete path if not NULL */
2239 sqlite3_context
*pCtx
/* Report errors here, if not NULL */
2241 const char *zErr
= 0;
2242 JsonNode
*pNode
= 0;
2245 if( zPath
==0 ) return 0;
2246 if( zPath
[0]!='$' ){
2251 pNode
= jsonLookupStep(pParse
, 0, zPath
, pApnd
, &zErr
);
2252 if( zErr
==0 ) return pNode
;
2256 assert( zErr
!=0 && pCtx
!=0 );
2257 zMsg
= jsonPathSyntaxError(zErr
);
2259 sqlite3_result_error(pCtx
, zMsg
, -1);
2262 sqlite3_result_error_nomem(pCtx
);
2269 ** Report the wrong number of arguments for json_insert(), json_replace()
2272 static void jsonWrongNumArgs(
2273 sqlite3_context
*pCtx
,
2274 const char *zFuncName
2276 char *zMsg
= sqlite3_mprintf("json_%s() needs an odd number of arguments",
2278 sqlite3_result_error(pCtx
, zMsg
, -1);
2283 ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
2285 static void jsonRemoveAllNulls(JsonNode
*pNode
){
2287 assert( pNode
->eType
==JSON_OBJECT
);
2289 for(i
=2; i
<=n
; i
+= jsonNodeSize(&pNode
[i
])+1){
2290 switch( pNode
[i
].eType
){
2292 pNode
[i
].jnFlags
|= JNODE_REMOVE
;
2295 jsonRemoveAllNulls(&pNode
[i
]);
2302 /****************************************************************************
2303 ** SQL functions used for testing and debugging
2304 ****************************************************************************/
2308 ** Print N node entries.
2310 static void jsonDebugPrintNodeEntries(
2311 JsonNode
*aNode
, /* First node entry to print */
2312 int N
/* Number of node entries to print */
2317 if( aNode
[i
].jnFlags
& JNODE_LABEL
){
2320 zType
= jsonType
[aNode
[i
].eType
];
2322 printf("node %4u: %-7s n=%-5d", i
, zType
, aNode
[i
].n
);
2323 if( (aNode
[i
].jnFlags
& ~JNODE_LABEL
)!=0 ){
2324 u8 f
= aNode
[i
].jnFlags
;
2325 if( f
& JNODE_RAW
) printf(" RAW");
2326 if( f
& JNODE_ESCAPE
) printf(" ESCAPE");
2327 if( f
& JNODE_REMOVE
) printf(" REMOVE");
2328 if( f
& JNODE_REPLACE
) printf(" REPLACE");
2329 if( f
& JNODE_APPEND
) printf(" APPEND");
2330 if( f
& JNODE_JSON5
) printf(" JSON5");
2332 switch( aNode
[i
].eU
){
2333 case 1: printf(" zJContent=[%.*s]\n",
2334 aNode
[i
].n
, aNode
[i
].u
.zJContent
); break;
2335 case 2: printf(" iAppend=%u\n", aNode
[i
].u
.iAppend
); break;
2336 case 3: printf(" iKey=%u\n", aNode
[i
].u
.iKey
); break;
2337 case 4: printf(" iPrev=%u\n", aNode
[i
].u
.iPrev
); break;
2338 default: printf("\n");
2342 #endif /* SQLITE_DEBUG */
2345 #if 0 /* 1 for debugging. 0 normally. Requires -DSQLITE_DEBUG too */
2346 static void jsonDebugPrintParse(JsonParse
*p
){
2347 jsonDebugPrintNodeEntries(p
->aNode
, p
->nNode
);
2349 static void jsonDebugPrintNode(JsonNode
*pNode
){
2350 jsonDebugPrintNodeEntries(pNode
, jsonNodeSize(pNode
));
2353 /* The usual case */
2354 # define jsonDebugPrintNode(X)
2355 # define jsonDebugPrintParse(X)
2360 ** SQL function: json_parse(JSON)
2362 ** Parse JSON using jsonParseCached(). Then print a dump of that
2363 ** parse on standard output. Return the mimified JSON result, just
2364 ** like the json() function.
2366 static void jsonParseFunc(
2367 sqlite3_context
*ctx
,
2369 sqlite3_value
**argv
2371 JsonParse
*p
; /* The parse */
2374 p
= jsonParseCached(ctx
, argv
[0], ctx
, 0);
2376 printf("nNode = %u\n", p
->nNode
);
2377 printf("nAlloc = %u\n", p
->nAlloc
);
2378 printf("nJson = %d\n", p
->nJson
);
2379 printf("nAlt = %d\n", p
->nAlt
);
2380 printf("nErr = %u\n", p
->nErr
);
2381 printf("oom = %u\n", p
->oom
);
2382 printf("hasNonstd = %u\n", p
->hasNonstd
);
2383 printf("useMod = %u\n", p
->useMod
);
2384 printf("hasMod = %u\n", p
->hasMod
);
2385 printf("nJPRef = %u\n", p
->nJPRef
);
2386 printf("iSubst = %u\n", p
->iSubst
);
2387 printf("iHold = %u\n", p
->iHold
);
2388 jsonDebugPrintNodeEntries(p
->aNode
, p
->nNode
);
2389 jsonReturnJson(p
, p
->aNode
, ctx
, 1);
2393 ** The json_test1(JSON) function return true (1) if the input is JSON
2394 ** text generated by another json function. It returns (0) if the input
2395 ** is not known to be JSON.
2397 static void jsonTest1Func(
2398 sqlite3_context
*ctx
,
2400 sqlite3_value
**argv
2402 UNUSED_PARAMETER(argc
);
2403 sqlite3_result_int(ctx
, sqlite3_value_subtype(argv
[0])==JSON_SUBTYPE
);
2405 #endif /* SQLITE_DEBUG */
2407 /****************************************************************************
2408 ** Scalar SQL function implementations
2409 ****************************************************************************/
2412 ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
2413 ** corresponding to the SQL value input. Mostly this means putting
2414 ** double-quotes around strings and returning the unquoted string "null"
2415 ** when given a NULL input.
2417 static void jsonQuoteFunc(
2418 sqlite3_context
*ctx
,
2420 sqlite3_value
**argv
2423 UNUSED_PARAMETER(argc
);
2426 jsonAppendValue(&jx
, argv
[0]);
2428 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
2432 ** Implementation of the json_array(VALUE,...) function. Return a JSON
2433 ** array that contains all values given in arguments. Or if any argument
2434 ** is a BLOB, throw an error.
2436 static void jsonArrayFunc(
2437 sqlite3_context
*ctx
,
2439 sqlite3_value
**argv
2445 jsonAppendChar(&jx
, '[');
2446 for(i
=0; i
<argc
; i
++){
2447 jsonAppendSeparator(&jx
);
2448 jsonAppendValue(&jx
, argv
[i
]);
2450 jsonAppendChar(&jx
, ']');
2452 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
2457 ** json_array_length(JSON)
2458 ** json_array_length(JSON, PATH)
2460 ** Return the number of elements in the top-level JSON array.
2461 ** Return 0 if the input is not a well-formed JSON array.
2463 static void jsonArrayLengthFunc(
2464 sqlite3_context
*ctx
,
2466 sqlite3_value
**argv
2468 JsonParse
*p
; /* The parse */
2469 sqlite3_int64 n
= 0;
2473 p
= jsonParseCached(ctx
, argv
[0], ctx
, 0);
2477 const char *zPath
= (const char*)sqlite3_value_text(argv
[1]);
2478 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
2485 if( pNode
->eType
==JSON_ARRAY
){
2486 while( 1 /*exit-by-break*/ ){
2487 for(i
=1; i
<=pNode
->n
; n
++){
2488 i
+= jsonNodeSize(&pNode
[i
]);
2490 if( (pNode
->jnFlags
& JNODE_APPEND
)==0 ) break;
2491 if( p
->useMod
==0 ) break;
2492 assert( pNode
->eU
==2 );
2493 pNode
= &p
->aNode
[pNode
->u
.iAppend
];
2496 sqlite3_result_int64(ctx
, n
);
2500 ** Bit values for the flags passed into jsonExtractFunc() or
2501 ** jsonSetFunc() via the user-data value.
2503 #define JSON_JSON 0x01 /* Result is always JSON */
2504 #define JSON_SQL 0x02 /* Result is always SQL */
2505 #define JSON_ABPATH 0x03 /* Allow abbreviated JSON path specs */
2506 #define JSON_ISSET 0x04 /* json_set(), not json_insert() */
2509 ** json_extract(JSON, PATH, ...)
2513 ** Return the element described by PATH. Return NULL if that PATH element
2516 ** If JSON_JSON is set or if more that one PATH argument is supplied then
2517 ** always return a JSON representation of the result. If JSON_SQL is set,
2518 ** then always return an SQL representation of the result. If neither flag
2519 ** is present and argc==2, then return JSON for objects and arrays and SQL
2520 ** for all other values.
2522 ** When multiple PATH arguments are supplied, the result is a JSON array
2523 ** containing the result of each PATH.
2525 ** Abbreviated JSON path expressions are allows if JSON_ABPATH, for
2526 ** compatibility with PG.
2528 static void jsonExtractFunc(
2529 sqlite3_context
*ctx
,
2531 sqlite3_value
**argv
2533 JsonParse
*p
; /* The parse */
2536 int flags
= SQLITE_PTR_TO_INT(sqlite3_user_data(ctx
));
2539 if( argc
<2 ) return;
2540 p
= jsonParseCached(ctx
, argv
[0], ctx
, 0);
2543 /* With a single PATH argument */
2544 zPath
= (const char*)sqlite3_value_text(argv
[1]);
2545 if( zPath
==0 ) return;
2546 if( flags
& JSON_ABPATH
){
2547 if( zPath
[0]!='$' || (zPath
[1]!='.' && zPath
[1]!='[' && zPath
[1]!=0) ){
2548 /* The -> and ->> operators accept abbreviated PATH arguments. This
2549 ** is mostly for compatibility with PostgreSQL, but also for
2552 ** NUMBER ==> $[NUMBER] // PG compatible
2553 ** LABEL ==> $.LABEL // PG compatible
2554 ** [NUMBER] ==> $[NUMBER] // Not PG. Purely for convenience
2557 if( sqlite3Isdigit(zPath
[0]) ){
2558 jsonAppendRawNZ(&jx
, "$[", 2);
2559 jsonAppendRaw(&jx
, zPath
, (int)strlen(zPath
));
2560 jsonAppendRawNZ(&jx
, "]", 2);
2562 jsonAppendRawNZ(&jx
, "$.", 1 + (zPath
[0]!='['));
2563 jsonAppendRaw(&jx
, zPath
, (int)strlen(zPath
));
2564 jsonAppendChar(&jx
, 0);
2566 pNode
= jx
.bErr
? 0 : jsonLookup(p
, jx
.zBuf
, 0, ctx
);
2569 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
2572 if( flags
& JSON_JSON
){
2573 jsonReturnJson(p
, pNode
, ctx
, 0);
2575 jsonReturn(p
, pNode
, ctx
);
2576 sqlite3_result_subtype(ctx
, 0);
2580 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
2581 if( p
->nErr
==0 && pNode
) jsonReturn(p
, pNode
, ctx
);
2584 /* Two or more PATH arguments results in a JSON array with each
2585 ** element of the array being the value selected by one of the PATHs */
2588 jsonAppendChar(&jx
, '[');
2589 for(i
=1; i
<argc
; i
++){
2590 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
2591 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
2592 if( p
->nErr
) break;
2593 jsonAppendSeparator(&jx
);
2595 jsonRenderNode(p
, pNode
, &jx
);
2597 jsonAppendRawNZ(&jx
, "null", 4);
2601 jsonAppendChar(&jx
, ']');
2603 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
2609 /* This is the RFC 7396 MergePatch algorithm.
2611 static JsonNode
*jsonMergePatch(
2612 JsonParse
*pParse
, /* The JSON parser that contains the TARGET */
2613 u32 iTarget
, /* Node of the TARGET in pParse */
2614 JsonNode
*pPatch
/* The PATCH */
2619 if( pPatch
->eType
!=JSON_OBJECT
){
2622 assert( iTarget
<pParse
->nNode
);
2623 pTarget
= &pParse
->aNode
[iTarget
];
2624 assert( (pPatch
->jnFlags
& JNODE_APPEND
)==0 );
2625 if( pTarget
->eType
!=JSON_OBJECT
){
2626 jsonRemoveAllNulls(pPatch
);
2630 for(i
=1; i
<pPatch
->n
; i
+= jsonNodeSize(&pPatch
[i
+1])+1){
2633 assert( pPatch
[i
].eType
==JSON_STRING
);
2634 assert( pPatch
[i
].jnFlags
& JNODE_LABEL
);
2635 assert( pPatch
[i
].eU
==1 );
2637 zKey
= pPatch
[i
].u
.zJContent
;
2638 for(j
=1; j
<pTarget
->n
; j
+= jsonNodeSize(&pTarget
[j
+1])+1 ){
2639 assert( pTarget
[j
].eType
==JSON_STRING
);
2640 assert( pTarget
[j
].jnFlags
& JNODE_LABEL
);
2641 if( jsonSameLabel(&pPatch
[i
], &pTarget
[j
]) ){
2642 if( pTarget
[j
+1].jnFlags
& (JNODE_REMOVE
|JNODE_REPLACE
) ) break;
2643 if( pPatch
[i
+1].eType
==JSON_NULL
){
2644 pTarget
[j
+1].jnFlags
|= JNODE_REMOVE
;
2646 JsonNode
*pNew
= jsonMergePatch(pParse
, iTarget
+j
+1, &pPatch
[i
+1]);
2647 if( pNew
==0 ) return 0;
2648 if( pNew
!=&pParse
->aNode
[iTarget
+j
+1] ){
2649 jsonParseAddSubstNode(pParse
, iTarget
+j
+1);
2650 jsonParseAddNodeArray(pParse
, pNew
, jsonNodeSize(pNew
));
2652 pTarget
= &pParse
->aNode
[iTarget
];
2657 if( j
>=pTarget
->n
&& pPatch
[i
+1].eType
!=JSON_NULL
){
2661 iStart
= jsonParseAddNode(pParse
, JSON_OBJECT
, 0, 0);
2662 jsonParseAddNode(pParse
, JSON_STRING
, nKey
, zKey
);
2663 pApnd
= &pPatch
[i
+1];
2664 if( pApnd
->eType
==JSON_OBJECT
) jsonRemoveAllNulls(pApnd
);
2665 nApnd
= jsonNodeSize(pApnd
);
2666 jsonParseAddNodeArray(pParse
, pApnd
, jsonNodeSize(pApnd
));
2667 if( pParse
->oom
) return 0;
2668 pParse
->aNode
[iStart
].n
= 1+nApnd
;
2669 pParse
->aNode
[iRoot
].jnFlags
|= JNODE_APPEND
;
2670 pParse
->aNode
[iRoot
].u
.iAppend
= iStart
;
2671 VVA( pParse
->aNode
[iRoot
].eU
= 2 );
2673 pTarget
= &pParse
->aNode
[iTarget
];
2680 ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
2681 ** object that is the result of running the RFC 7396 MergePatch() algorithm
2682 ** on the two arguments.
2684 static void jsonPatchFunc(
2685 sqlite3_context
*ctx
,
2687 sqlite3_value
**argv
2689 JsonParse
*pX
; /* The JSON that is being patched */
2690 JsonParse
*pY
; /* The patch */
2691 JsonNode
*pResult
; /* The result of the merge */
2693 UNUSED_PARAMETER(argc
);
2694 pX
= jsonParseCached(ctx
, argv
[0], ctx
, 1);
2696 assert( pX
->hasMod
==0 );
2698 pY
= jsonParseCached(ctx
, argv
[1], ctx
, 1);
2702 pResult
= jsonMergePatch(pX
, 0, pY
->aNode
);
2703 assert( pResult
!=0 || pX
->oom
);
2704 if( pResult
&& pX
->oom
==0 ){
2705 jsonDebugPrintParse(pX
);
2706 jsonDebugPrintNode(pResult
);
2707 jsonReturnJson(pX
, pResult
, ctx
, 0);
2709 sqlite3_result_error_nomem(ctx
);
2715 ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
2716 ** object that contains all name/value given in arguments. Or if any name
2717 ** is not a string or if any value is a BLOB, throw an error.
2719 static void jsonObjectFunc(
2720 sqlite3_context
*ctx
,
2722 sqlite3_value
**argv
2730 sqlite3_result_error(ctx
, "json_object() requires an even number "
2731 "of arguments", -1);
2735 jsonAppendChar(&jx
, '{');
2736 for(i
=0; i
<argc
; i
+=2){
2737 if( sqlite3_value_type(argv
[i
])!=SQLITE_TEXT
){
2738 sqlite3_result_error(ctx
, "json_object() labels must be TEXT", -1);
2742 jsonAppendSeparator(&jx
);
2743 z
= (const char*)sqlite3_value_text(argv
[i
]);
2744 n
= (u32
)sqlite3_value_bytes(argv
[i
]);
2745 jsonAppendString(&jx
, z
, n
);
2746 jsonAppendChar(&jx
, ':');
2747 jsonAppendValue(&jx
, argv
[i
+1]);
2749 jsonAppendChar(&jx
, '}');
2751 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
2756 ** json_remove(JSON, PATH, ...)
2758 ** Remove the named elements from JSON and return the result. malformed
2759 ** JSON or PATH arguments result in an error.
2761 static void jsonRemoveFunc(
2762 sqlite3_context
*ctx
,
2764 sqlite3_value
**argv
2766 JsonParse
*pParse
; /* The parse */
2771 if( argc
<1 ) return;
2772 pParse
= jsonParseCached(ctx
, argv
[0], ctx
, argc
>1);
2773 if( pParse
==0 ) return;
2774 for(i
=1; i
<(u32
)argc
; i
++){
2775 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
2776 if( zPath
==0 ) goto remove_done
;
2777 pNode
= jsonLookup(pParse
, zPath
, 0, ctx
);
2778 if( pParse
->nErr
) goto remove_done
;
2780 pNode
->jnFlags
|= JNODE_REMOVE
;
2785 if( (pParse
->aNode
[0].jnFlags
& JNODE_REMOVE
)==0 ){
2786 jsonReturnJson(pParse
, pParse
->aNode
, ctx
, 1);
2789 jsonDebugPrintParse(p
);
2793 ** Substitute the value at iNode with the pValue parameter.
2795 static void jsonReplaceNode(
2796 sqlite3_context
*pCtx
,
2799 sqlite3_value
*pValue
2801 int idx
= jsonParseAddSubstNode(p
, iNode
);
2806 switch( sqlite3_value_type(pValue
) ){
2808 jsonParseAddNode(p
, JSON_NULL
, 0, 0);
2811 case SQLITE_FLOAT
: {
2812 char *z
= sqlite3_mprintf("%!0.15g", sqlite3_value_double(pValue
));
2818 n
= sqlite3Strlen30(z
);
2819 jsonParseAddNode(p
, JSON_REAL
, n
, z
);
2820 jsonParseAddCleanup(p
, sqlite3_free
, z
);
2823 case SQLITE_INTEGER
: {
2824 char *z
= sqlite3_mprintf("%lld", sqlite3_value_int64(pValue
));
2830 n
= sqlite3Strlen30(z
);
2831 jsonParseAddNode(p
, JSON_INT
, n
, z
);
2832 jsonParseAddCleanup(p
, sqlite3_free
, z
);
2837 const char *z
= (const char*)sqlite3_value_text(pValue
);
2838 u32 n
= (u32
)sqlite3_value_bytes(pValue
);
2843 if( sqlite3_value_subtype(pValue
)!=JSON_SUBTYPE
){
2844 char *zCopy
= sqlite3DbStrDup(0, z
);
2847 jsonParseAddCleanup(p
, sqlite3_free
, zCopy
);
2850 sqlite3_result_error_nomem(pCtx
);
2852 k
= jsonParseAddNode(p
, JSON_STRING
, n
, zCopy
);
2853 assert( k
>0 || p
->oom
);
2854 if( p
->oom
==0 ) p
->aNode
[k
].jnFlags
|= JNODE_RAW
;
2856 JsonParse
*pPatch
= jsonParseCached(pCtx
, pValue
, pCtx
, 1);
2861 jsonParseAddNodeArray(p
, pPatch
->aNode
, pPatch
->nNode
);
2862 /* The nodes copied out of pPatch and into p likely contain
2863 ** u.zJContent pointers into pPatch->zJson. So preserve the
2864 ** content of pPatch until p is destroyed. */
2865 assert( pPatch
->nJPRef
>=1 );
2867 jsonParseAddCleanup(p
, (void(*)(void*))jsonParseFree
, pPatch
);
2872 jsonParseAddNode(p
, JSON_NULL
, 0, 0);
2873 sqlite3_result_error(pCtx
, "JSON cannot hold BLOB values", -1);
2881 ** json_replace(JSON, PATH, VALUE, ...)
2883 ** Replace the value at PATH with VALUE. If PATH does not already exist,
2884 ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
2886 static void jsonReplaceFunc(
2887 sqlite3_context
*ctx
,
2889 sqlite3_value
**argv
2891 JsonParse
*pParse
; /* The parse */
2896 if( argc
<1 ) return;
2898 jsonWrongNumArgs(ctx
, "replace");
2901 pParse
= jsonParseCached(ctx
, argv
[0], ctx
, argc
>1);
2902 if( pParse
==0 ) return;
2903 for(i
=1; i
<(u32
)argc
; i
+=2){
2904 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
2906 pNode
= jsonLookup(pParse
, zPath
, 0, ctx
);
2907 if( pParse
->nErr
) goto replace_err
;
2909 jsonReplaceNode(ctx
, pParse
, (u32
)(pNode
- pParse
->aNode
), argv
[i
+1]);
2912 jsonReturnJson(pParse
, pParse
->aNode
, ctx
, 1);
2914 jsonDebugPrintParse(pParse
);
2919 ** json_set(JSON, PATH, VALUE, ...)
2921 ** Set the value at PATH to VALUE. Create the PATH if it does not already
2922 ** exist. Overwrite existing values that do exist.
2923 ** If JSON or PATH is malformed, throw an error.
2925 ** json_insert(JSON, PATH, VALUE, ...)
2927 ** Create PATH and initialize it to VALUE. If PATH already exists, this
2928 ** routine is a no-op. If JSON or PATH is malformed, throw an error.
2930 static void jsonSetFunc(
2931 sqlite3_context
*ctx
,
2933 sqlite3_value
**argv
2935 JsonParse
*pParse
; /* The parse */
2940 int bIsSet
= sqlite3_user_data(ctx
)!=0;
2942 if( argc
<1 ) return;
2944 jsonWrongNumArgs(ctx
, bIsSet
? "set" : "insert");
2947 pParse
= jsonParseCached(ctx
, argv
[0], ctx
, argc
>1);
2948 if( pParse
==0 ) return;
2949 for(i
=1; i
<(u32
)argc
; i
+=2){
2950 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
2953 pNode
= jsonLookup(pParse
, zPath
, &bApnd
, ctx
);
2955 sqlite3_result_error_nomem(ctx
);
2957 }else if( pParse
->nErr
){
2959 }else if( pNode
&& (bApnd
|| bIsSet
) ){
2960 jsonReplaceNode(ctx
, pParse
, (u32
)(pNode
- pParse
->aNode
), argv
[i
+1]);
2963 jsonDebugPrintParse(pParse
);
2964 jsonReturnJson(pParse
, pParse
->aNode
, ctx
, 1);
2967 /* no cleanup required */;
2972 ** json_type(JSON, PATH)
2974 ** Return the top-level "type" of a JSON string. json_type() raises an
2975 ** error if either the JSON or PATH inputs are not well-formed.
2977 static void jsonTypeFunc(
2978 sqlite3_context
*ctx
,
2980 sqlite3_value
**argv
2982 JsonParse
*p
; /* The parse */
2986 p
= jsonParseCached(ctx
, argv
[0], ctx
, 0);
2989 zPath
= (const char*)sqlite3_value_text(argv
[1]);
2990 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
2995 sqlite3_result_text(ctx
, jsonType
[pNode
->eType
], -1, SQLITE_STATIC
);
3002 ** Return 1 if JSON is a well-formed canonical JSON string according
3003 ** to RFC-7159. Return 0 otherwise.
3005 static void jsonValidFunc(
3006 sqlite3_context
*ctx
,
3008 sqlite3_value
**argv
3010 JsonParse
*p
; /* The parse */
3011 UNUSED_PARAMETER(argc
);
3012 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
3013 #ifdef SQLITE_LEGACY_JSON_VALID
3014 /* Incorrect legacy behavior was to return FALSE for a NULL input */
3015 sqlite3_result_int(ctx
, 0);
3019 p
= jsonParseCached(ctx
, argv
[0], 0, 0);
3020 if( p
==0 || p
->oom
){
3021 sqlite3_result_error_nomem(ctx
);
3024 sqlite3_result_int(ctx
, p
->nErr
==0 && (p
->hasNonstd
==0 || p
->useMod
));
3025 if( p
->nErr
) jsonParseFree(p
);
3030 ** json_error_position(JSON)
3032 ** If the argument is not an interpretable JSON string, then return the 1-based
3033 ** character position at which the parser first recognized that the input
3034 ** was in error. The left-most character is 1. If the string is valid
3035 ** JSON, then return 0.
3037 ** Note that json_valid() is only true for strictly conforming canonical JSON.
3038 ** But this routine returns zero if the input contains extension. Thus:
3040 ** (1) If the input X is strictly conforming canonical JSON:
3042 ** json_valid(X) returns true
3043 ** json_error_position(X) returns 0
3045 ** (2) If the input X is JSON but it includes extension (such as JSON5) that
3046 ** are not part of RFC-8259:
3048 ** json_valid(X) returns false
3049 ** json_error_position(X) return 0
3051 ** (3) If the input X cannot be interpreted as JSON even taking extensions
3054 ** json_valid(X) return false
3055 ** json_error_position(X) returns 1 or more
3057 static void jsonErrorFunc(
3058 sqlite3_context
*ctx
,
3060 sqlite3_value
**argv
3062 JsonParse
*p
; /* The parse */
3063 UNUSED_PARAMETER(argc
);
3064 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
) return;
3065 p
= jsonParseCached(ctx
, argv
[0], 0, 0);
3066 if( p
==0 || p
->oom
){
3067 sqlite3_result_error_nomem(ctx
);
3069 }else if( p
->nErr
==0 ){
3070 sqlite3_result_int(ctx
, 0);
3074 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
3075 for(i
=0; i
<p
->iErr
&& ALWAYS(z
[i
]); i
++){
3076 if( (z
[i
]&0xc0)!=0x80 ) n
++;
3078 sqlite3_result_int(ctx
, n
);
3084 /****************************************************************************
3085 ** Aggregate SQL function implementations
3086 ****************************************************************************/
3088 ** json_group_array(VALUE)
3090 ** Return a JSON array composed of all values in the aggregate.
3092 static void jsonArrayStep(
3093 sqlite3_context
*ctx
,
3095 sqlite3_value
**argv
3098 UNUSED_PARAMETER(argc
);
3099 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, sizeof(*pStr
));
3101 if( pStr
->zBuf
==0 ){
3102 jsonInit(pStr
, ctx
);
3103 jsonAppendChar(pStr
, '[');
3104 }else if( pStr
->nUsed
>1 ){
3105 jsonAppendChar(pStr
, ',');
3108 jsonAppendValue(pStr
, argv
[0]);
3111 static void jsonArrayCompute(sqlite3_context
*ctx
, int isFinal
){
3113 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, 0);
3116 jsonAppendChar(pStr
, ']');
3118 if( pStr
->bErr
==1 ) sqlite3_result_error_nomem(ctx
);
3119 assert( pStr
->bStatic
);
3120 }else if( isFinal
){
3121 sqlite3_result_text(ctx
, pStr
->zBuf
, (int)pStr
->nUsed
,
3122 pStr
->bStatic
? SQLITE_TRANSIENT
:
3123 (void(*)(void*))sqlite3RCStrUnref
);
3126 sqlite3_result_text(ctx
, pStr
->zBuf
, (int)pStr
->nUsed
, SQLITE_TRANSIENT
);
3130 sqlite3_result_text(ctx
, "[]", 2, SQLITE_STATIC
);
3132 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
3134 static void jsonArrayValue(sqlite3_context
*ctx
){
3135 jsonArrayCompute(ctx
, 0);
3137 static void jsonArrayFinal(sqlite3_context
*ctx
){
3138 jsonArrayCompute(ctx
, 1);
3141 #ifndef SQLITE_OMIT_WINDOWFUNC
3143 ** This method works for both json_group_array() and json_group_object().
3144 ** It works by removing the first element of the group by searching forward
3145 ** to the first comma (",") that is not within a string and deleting all
3146 ** text through that comma.
3148 static void jsonGroupInverse(
3149 sqlite3_context
*ctx
,
3151 sqlite3_value
**argv
3159 UNUSED_PARAMETER(argc
);
3160 UNUSED_PARAMETER(argv
);
3161 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, 0);
3163 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
3164 ** always have been called to initialize it */
3165 if( NEVER(!pStr
) ) return;
3168 for(i
=1; i
<pStr
->nUsed
&& ((c
= z
[i
])!=',' || inStr
|| nNest
); i
++){
3171 }else if( c
=='\\' ){
3174 if( c
=='{' || c
=='[' ) nNest
++;
3175 if( c
=='}' || c
==']' ) nNest
--;
3178 if( i
<pStr
->nUsed
){
3180 memmove(&z
[1], &z
[i
+1], (size_t)pStr
->nUsed
-1);
3187 # define jsonGroupInverse 0
3192 ** json_group_obj(NAME,VALUE)
3194 ** Return a JSON object composed of all names and values in the aggregate.
3196 static void jsonObjectStep(
3197 sqlite3_context
*ctx
,
3199 sqlite3_value
**argv
3204 UNUSED_PARAMETER(argc
);
3205 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, sizeof(*pStr
));
3207 if( pStr
->zBuf
==0 ){
3208 jsonInit(pStr
, ctx
);
3209 jsonAppendChar(pStr
, '{');
3210 }else if( pStr
->nUsed
>1 ){
3211 jsonAppendChar(pStr
, ',');
3214 z
= (const char*)sqlite3_value_text(argv
[0]);
3215 n
= (u32
)sqlite3_value_bytes(argv
[0]);
3216 jsonAppendString(pStr
, z
, n
);
3217 jsonAppendChar(pStr
, ':');
3218 jsonAppendValue(pStr
, argv
[1]);
3221 static void jsonObjectCompute(sqlite3_context
*ctx
, int isFinal
){
3223 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, 0);
3225 jsonAppendChar(pStr
, '}');
3227 if( pStr
->bErr
==1 ) sqlite3_result_error_nomem(ctx
);
3228 assert( pStr
->bStatic
);
3229 }else if( isFinal
){
3230 sqlite3_result_text(ctx
, pStr
->zBuf
, (int)pStr
->nUsed
,
3231 pStr
->bStatic
? SQLITE_TRANSIENT
:
3232 (void(*)(void*))sqlite3RCStrUnref
);
3235 sqlite3_result_text(ctx
, pStr
->zBuf
, (int)pStr
->nUsed
, SQLITE_TRANSIENT
);
3239 sqlite3_result_text(ctx
, "{}", 2, SQLITE_STATIC
);
3241 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
3243 static void jsonObjectValue(sqlite3_context
*ctx
){
3244 jsonObjectCompute(ctx
, 0);
3246 static void jsonObjectFinal(sqlite3_context
*ctx
){
3247 jsonObjectCompute(ctx
, 1);
3252 #ifndef SQLITE_OMIT_VIRTUALTABLE
3253 /****************************************************************************
3254 ** The json_each virtual table
3255 ****************************************************************************/
3256 typedef struct JsonEachCursor JsonEachCursor
;
3257 struct JsonEachCursor
{
3258 sqlite3_vtab_cursor base
; /* Base class - must be first */
3259 u32 iRowid
; /* The rowid */
3260 u32 iBegin
; /* The first node of the scan */
3261 u32 i
; /* Index in sParse.aNode[] of current row */
3262 u32 iEnd
; /* EOF when i equals or exceeds this value */
3263 u8 eType
; /* Type of top-level element */
3264 u8 bRecursive
; /* True for json_tree(). False for json_each() */
3265 char *zJson
; /* Input JSON */
3266 char *zRoot
; /* Path by which to filter zJson */
3267 JsonParse sParse
; /* Parse of the input JSON */
3270 /* Constructor for the json_each virtual table */
3271 static int jsonEachConnect(
3274 int argc
, const char *const*argv
,
3275 sqlite3_vtab
**ppVtab
,
3281 /* Column numbers */
3283 #define JEACH_VALUE 1
3284 #define JEACH_TYPE 2
3285 #define JEACH_ATOM 3
3287 #define JEACH_PARENT 5
3288 #define JEACH_FULLKEY 6
3289 #define JEACH_PATH 7
3290 /* The xBestIndex method assumes that the JSON and ROOT columns are
3291 ** the last two columns in the table. Should this ever changes, be
3292 ** sure to update the xBestIndex method. */
3293 #define JEACH_JSON 8
3294 #define JEACH_ROOT 9
3296 UNUSED_PARAMETER(pzErr
);
3297 UNUSED_PARAMETER(argv
);
3298 UNUSED_PARAMETER(argc
);
3299 UNUSED_PARAMETER(pAux
);
3300 rc
= sqlite3_declare_vtab(db
,
3301 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
3302 "json HIDDEN,root HIDDEN)");
3303 if( rc
==SQLITE_OK
){
3304 pNew
= *ppVtab
= sqlite3_malloc( sizeof(*pNew
) );
3305 if( pNew
==0 ) return SQLITE_NOMEM
;
3306 memset(pNew
, 0, sizeof(*pNew
));
3307 sqlite3_vtab_config(db
, SQLITE_VTAB_INNOCUOUS
);
3312 /* destructor for json_each virtual table */
3313 static int jsonEachDisconnect(sqlite3_vtab
*pVtab
){
3314 sqlite3_free(pVtab
);
3318 /* constructor for a JsonEachCursor object for json_each(). */
3319 static int jsonEachOpenEach(sqlite3_vtab
*p
, sqlite3_vtab_cursor
**ppCursor
){
3320 JsonEachCursor
*pCur
;
3322 UNUSED_PARAMETER(p
);
3323 pCur
= sqlite3_malloc( sizeof(*pCur
) );
3324 if( pCur
==0 ) return SQLITE_NOMEM
;
3325 memset(pCur
, 0, sizeof(*pCur
));
3326 *ppCursor
= &pCur
->base
;
3330 /* constructor for a JsonEachCursor object for json_tree(). */
3331 static int jsonEachOpenTree(sqlite3_vtab
*p
, sqlite3_vtab_cursor
**ppCursor
){
3332 int rc
= jsonEachOpenEach(p
, ppCursor
);
3333 if( rc
==SQLITE_OK
){
3334 JsonEachCursor
*pCur
= (JsonEachCursor
*)*ppCursor
;
3335 pCur
->bRecursive
= 1;
3340 /* Reset a JsonEachCursor back to its original state. Free any memory
3342 static void jsonEachCursorReset(JsonEachCursor
*p
){
3343 sqlite3_free(p
->zRoot
);
3344 jsonParseReset(&p
->sParse
);
3353 /* Destructor for a jsonEachCursor object */
3354 static int jsonEachClose(sqlite3_vtab_cursor
*cur
){
3355 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
3356 jsonEachCursorReset(p
);
3361 /* Return TRUE if the jsonEachCursor object has been advanced off the end
3362 ** of the JSON object */
3363 static int jsonEachEof(sqlite3_vtab_cursor
*cur
){
3364 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
3365 return p
->i
>= p
->iEnd
;
3368 /* Advance the cursor to the next element for json_tree() */
3369 static int jsonEachNext(sqlite3_vtab_cursor
*cur
){
3370 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
3371 if( p
->bRecursive
){
3372 if( p
->sParse
.aNode
[p
->i
].jnFlags
& JNODE_LABEL
) p
->i
++;
3376 u32 iUp
= p
->sParse
.aUp
[p
->i
];
3377 JsonNode
*pUp
= &p
->sParse
.aNode
[iUp
];
3378 p
->eType
= pUp
->eType
;
3379 if( pUp
->eType
==JSON_ARRAY
){
3380 assert( pUp
->eU
==0 || pUp
->eU
==3 );
3381 testcase( pUp
->eU
==3 );
3393 p
->i
+= jsonNodeSize(&p
->sParse
.aNode
[p
->i
]);
3398 p
->i
+= 1 + jsonNodeSize(&p
->sParse
.aNode
[p
->i
+1]);
3411 /* Append an object label to the JSON Path being constructed
3414 static void jsonAppendObjectPathElement(
3420 assert( pNode
->eType
==JSON_STRING
);
3421 assert( pNode
->jnFlags
& JNODE_LABEL
);
3422 assert( pNode
->eU
==1 );
3423 z
= pNode
->u
.zJContent
;
3425 if( (pNode
->jnFlags
& JNODE_RAW
)==0 ){
3427 assert( z
[0]=='"' || z
[0]=='\'' );
3428 assert( z
[nn
-1]=='"' || z
[0]=='\'' );
3429 if( nn
>2 && sqlite3Isalpha(z
[1]) ){
3430 for(jj
=2; jj
<nn
-1 && sqlite3Isalnum(z
[jj
]); jj
++){}
3437 jsonPrintf(nn
+2, pStr
, ".%.*s", nn
, z
);
3440 /* Append the name of the path for element i to pStr
3442 static void jsonEachComputePath(
3443 JsonEachCursor
*p
, /* The cursor */
3444 JsonString
*pStr
, /* Write the path here */
3445 u32 i
/* Path to this element */
3447 JsonNode
*pNode
, *pUp
;
3450 jsonAppendChar(pStr
, '$');
3453 iUp
= p
->sParse
.aUp
[i
];
3454 jsonEachComputePath(p
, pStr
, iUp
);
3455 pNode
= &p
->sParse
.aNode
[i
];
3456 pUp
= &p
->sParse
.aNode
[iUp
];
3457 if( pUp
->eType
==JSON_ARRAY
){
3458 assert( pUp
->eU
==3 || (pUp
->eU
==0 && pUp
->u
.iKey
==0) );
3459 testcase( pUp
->eU
==0 );
3460 jsonPrintf(30, pStr
, "[%d]", pUp
->u
.iKey
);
3462 assert( pUp
->eType
==JSON_OBJECT
);
3463 if( (pNode
->jnFlags
& JNODE_LABEL
)==0 ) pNode
--;
3464 jsonAppendObjectPathElement(pStr
, pNode
);
3468 /* Return the value of a column */
3469 static int jsonEachColumn(
3470 sqlite3_vtab_cursor
*cur
, /* The cursor */
3471 sqlite3_context
*ctx
, /* First argument to sqlite3_result_...() */
3472 int i
/* Which column to return */
3474 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
3475 JsonNode
*pThis
= &p
->sParse
.aNode
[p
->i
];
3478 if( p
->i
==0 ) break;
3479 if( p
->eType
==JSON_OBJECT
){
3480 jsonReturn(&p
->sParse
, pThis
, ctx
);
3481 }else if( p
->eType
==JSON_ARRAY
){
3483 if( p
->bRecursive
){
3484 if( p
->iRowid
==0 ) break;
3485 assert( p
->sParse
.aNode
[p
->sParse
.aUp
[p
->i
]].eU
==3 );
3486 iKey
= p
->sParse
.aNode
[p
->sParse
.aUp
[p
->i
]].u
.iKey
;
3490 sqlite3_result_int64(ctx
, (sqlite3_int64
)iKey
);
3495 if( pThis
->jnFlags
& JNODE_LABEL
) pThis
++;
3496 jsonReturn(&p
->sParse
, pThis
, ctx
);
3500 if( pThis
->jnFlags
& JNODE_LABEL
) pThis
++;
3501 sqlite3_result_text(ctx
, jsonType
[pThis
->eType
], -1, SQLITE_STATIC
);
3505 if( pThis
->jnFlags
& JNODE_LABEL
) pThis
++;
3506 if( pThis
->eType
>=JSON_ARRAY
) break;
3507 jsonReturn(&p
->sParse
, pThis
, ctx
);
3511 sqlite3_result_int64(ctx
,
3512 (sqlite3_int64
)p
->i
+ ((pThis
->jnFlags
& JNODE_LABEL
)!=0));
3515 case JEACH_PARENT
: {
3516 if( p
->i
>p
->iBegin
&& p
->bRecursive
){
3517 sqlite3_result_int64(ctx
, (sqlite3_int64
)p
->sParse
.aUp
[p
->i
]);
3521 case JEACH_FULLKEY
: {
3524 if( p
->bRecursive
){
3525 jsonEachComputePath(p
, &x
, p
->i
);
3528 jsonAppendRaw(&x
, p
->zRoot
, (int)strlen(p
->zRoot
));
3530 jsonAppendChar(&x
, '$');
3532 if( p
->eType
==JSON_ARRAY
){
3533 jsonPrintf(30, &x
, "[%d]", p
->iRowid
);
3534 }else if( p
->eType
==JSON_OBJECT
){
3535 jsonAppendObjectPathElement(&x
, pThis
);
3542 if( p
->bRecursive
){
3545 jsonEachComputePath(p
, &x
, p
->sParse
.aUp
[p
->i
]);
3549 /* For json_each() path and root are the same so fall through
3550 ** into the root case */
3551 /* no break */ deliberate_fall_through
3554 const char *zRoot
= p
->zRoot
;
3555 if( zRoot
==0 ) zRoot
= "$";
3556 sqlite3_result_text(ctx
, zRoot
, -1, SQLITE_STATIC
);
3560 assert( i
==JEACH_JSON
);
3561 sqlite3_result_text(ctx
, p
->sParse
.zJson
, -1, SQLITE_STATIC
);
3568 /* Return the current rowid value */
3569 static int jsonEachRowid(sqlite3_vtab_cursor
*cur
, sqlite_int64
*pRowid
){
3570 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
3571 *pRowid
= p
->iRowid
;
3575 /* The query strategy is to look for an equality constraint on the json
3576 ** column. Without such a constraint, the table cannot operate. idxNum is
3577 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
3580 static int jsonEachBestIndex(
3582 sqlite3_index_info
*pIdxInfo
3584 int i
; /* Loop counter or computed array index */
3585 int aIdx
[2]; /* Index of constraints for JSON and ROOT */
3586 int unusableMask
= 0; /* Mask of unusable JSON and ROOT constraints */
3587 int idxMask
= 0; /* Mask of usable == constraints JSON and ROOT */
3588 const struct sqlite3_index_constraint
*pConstraint
;
3590 /* This implementation assumes that JSON and ROOT are the last two
3591 ** columns in the table */
3592 assert( JEACH_ROOT
== JEACH_JSON
+1 );
3593 UNUSED_PARAMETER(tab
);
3594 aIdx
[0] = aIdx
[1] = -1;
3595 pConstraint
= pIdxInfo
->aConstraint
;
3596 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++, pConstraint
++){
3599 if( pConstraint
->iColumn
< JEACH_JSON
) continue;
3600 iCol
= pConstraint
->iColumn
- JEACH_JSON
;
3601 assert( iCol
==0 || iCol
==1 );
3602 testcase( iCol
==0 );
3604 if( pConstraint
->usable
==0 ){
3605 unusableMask
|= iMask
;
3606 }else if( pConstraint
->op
==SQLITE_INDEX_CONSTRAINT_EQ
){
3611 if( pIdxInfo
->nOrderBy
>0
3612 && pIdxInfo
->aOrderBy
[0].iColumn
<0
3613 && pIdxInfo
->aOrderBy
[0].desc
==0
3615 pIdxInfo
->orderByConsumed
= 1;
3618 if( (unusableMask
& ~idxMask
)!=0 ){
3619 /* If there are any unusable constraints on JSON or ROOT, then reject
3620 ** this entire plan */
3621 return SQLITE_CONSTRAINT
;
3624 /* No JSON input. Leave estimatedCost at the huge value that it was
3625 ** initialized to to discourage the query planner from selecting this
3627 pIdxInfo
->idxNum
= 0;
3629 pIdxInfo
->estimatedCost
= 1.0;
3631 pIdxInfo
->aConstraintUsage
[i
].argvIndex
= 1;
3632 pIdxInfo
->aConstraintUsage
[i
].omit
= 1;
3634 pIdxInfo
->idxNum
= 1; /* Only JSON supplied. Plan 1 */
3637 pIdxInfo
->aConstraintUsage
[i
].argvIndex
= 2;
3638 pIdxInfo
->aConstraintUsage
[i
].omit
= 1;
3639 pIdxInfo
->idxNum
= 3; /* Both JSON and ROOT are supplied. Plan 3 */
3645 /* Start a search on a new JSON string */
3646 static int jsonEachFilter(
3647 sqlite3_vtab_cursor
*cur
,
3648 int idxNum
, const char *idxStr
,
3649 int argc
, sqlite3_value
**argv
3651 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
3653 const char *zRoot
= 0;
3656 UNUSED_PARAMETER(idxStr
);
3657 UNUSED_PARAMETER(argc
);
3658 jsonEachCursorReset(p
);
3659 if( idxNum
==0 ) return SQLITE_OK
;
3660 z
= (const char*)sqlite3_value_text(argv
[0]);
3661 if( z
==0 ) return SQLITE_OK
;
3662 memset(&p
->sParse
, 0, sizeof(p
->sParse
));
3663 p
->sParse
.nJPRef
= 1;
3664 if( sqlite3ValueIsOfClass(argv
[0], (void(*)(void*))sqlite3RCStrUnref
) ){
3665 p
->sParse
.zJson
= sqlite3RCStrRef((char*)z
);
3667 n
= sqlite3_value_bytes(argv
[0]);
3668 p
->sParse
.zJson
= sqlite3RCStrNew( n
+1 );
3669 if( p
->sParse
.zJson
==0 ) return SQLITE_NOMEM
;
3670 memcpy(p
->sParse
.zJson
, z
, (size_t)n
+1);
3672 p
->sParse
.bJsonIsRCStr
= 1;
3673 p
->zJson
= p
->sParse
.zJson
;
3674 if( jsonParse(&p
->sParse
, 0) ){
3675 int rc
= SQLITE_NOMEM
;
3676 if( p
->sParse
.oom
==0 ){
3677 sqlite3_free(cur
->pVtab
->zErrMsg
);
3678 cur
->pVtab
->zErrMsg
= sqlite3_mprintf("malformed JSON");
3679 if( cur
->pVtab
->zErrMsg
) rc
= SQLITE_ERROR
;
3681 jsonEachCursorReset(p
);
3683 }else if( p
->bRecursive
&& jsonParseFindParents(&p
->sParse
) ){
3684 jsonEachCursorReset(p
);
3685 return SQLITE_NOMEM
;
3687 JsonNode
*pNode
= 0;
3689 const char *zErr
= 0;
3690 zRoot
= (const char*)sqlite3_value_text(argv
[1]);
3691 if( zRoot
==0 ) return SQLITE_OK
;
3692 n
= sqlite3_value_bytes(argv
[1]);
3693 p
->zRoot
= sqlite3_malloc64( n
+1 );
3694 if( p
->zRoot
==0 ) return SQLITE_NOMEM
;
3695 memcpy(p
->zRoot
, zRoot
, (size_t)n
+1);
3696 if( zRoot
[0]!='$' ){
3699 pNode
= jsonLookupStep(&p
->sParse
, 0, p
->zRoot
+1, 0, &zErr
);
3702 sqlite3_free(cur
->pVtab
->zErrMsg
);
3703 cur
->pVtab
->zErrMsg
= jsonPathSyntaxError(zErr
);
3704 jsonEachCursorReset(p
);
3705 return cur
->pVtab
->zErrMsg
? SQLITE_ERROR
: SQLITE_NOMEM
;
3706 }else if( pNode
==0 ){
3710 pNode
= p
->sParse
.aNode
;
3712 p
->iBegin
= p
->i
= (int)(pNode
- p
->sParse
.aNode
);
3713 p
->eType
= pNode
->eType
;
3714 if( p
->eType
>=JSON_ARRAY
){
3715 assert( pNode
->eU
==0 );
3716 VVA( pNode
->eU
= 3 );
3718 p
->iEnd
= p
->i
+ pNode
->n
+ 1;
3719 if( p
->bRecursive
){
3720 p
->eType
= p
->sParse
.aNode
[p
->sParse
.aUp
[p
->i
]].eType
;
3721 if( p
->i
>0 && (p
->sParse
.aNode
[p
->i
-1].jnFlags
& JNODE_LABEL
)!=0 ){
3734 /* The methods of the json_each virtual table */
3735 static sqlite3_module jsonEachModule
= {
3738 jsonEachConnect
, /* xConnect */
3739 jsonEachBestIndex
, /* xBestIndex */
3740 jsonEachDisconnect
, /* xDisconnect */
3742 jsonEachOpenEach
, /* xOpen - open a cursor */
3743 jsonEachClose
, /* xClose - close a cursor */
3744 jsonEachFilter
, /* xFilter - configure scan constraints */
3745 jsonEachNext
, /* xNext - advance a cursor */
3746 jsonEachEof
, /* xEof - check for end of scan */
3747 jsonEachColumn
, /* xColumn - read data */
3748 jsonEachRowid
, /* xRowid - read data */
3754 0, /* xFindMethod */
3758 0, /* xRollbackTo */
3762 /* The methods of the json_tree virtual table. */
3763 static sqlite3_module jsonTreeModule
= {
3766 jsonEachConnect
, /* xConnect */
3767 jsonEachBestIndex
, /* xBestIndex */
3768 jsonEachDisconnect
, /* xDisconnect */
3770 jsonEachOpenTree
, /* xOpen - open a cursor */
3771 jsonEachClose
, /* xClose - close a cursor */
3772 jsonEachFilter
, /* xFilter - configure scan constraints */
3773 jsonEachNext
, /* xNext - advance a cursor */
3774 jsonEachEof
, /* xEof - check for end of scan */
3775 jsonEachColumn
, /* xColumn - read data */
3776 jsonEachRowid
, /* xRowid - read data */
3782 0, /* xFindMethod */
3786 0, /* xRollbackTo */
3789 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3790 #endif /* !defined(SQLITE_OMIT_JSON) */
3793 ** Register JSON functions.
3795 void sqlite3RegisterJsonFunctions(void){
3796 #ifndef SQLITE_OMIT_JSON
3797 static FuncDef aJsonFunc
[] = {
3798 JFUNCTION(json
, 1, 0, jsonRemoveFunc
),
3799 JFUNCTION(json_array
, -1, 0, jsonArrayFunc
),
3800 JFUNCTION(json_array_length
, 1, 0, jsonArrayLengthFunc
),
3801 JFUNCTION(json_array_length
, 2, 0, jsonArrayLengthFunc
),
3802 JFUNCTION(json_error_position
,1, 0, jsonErrorFunc
),
3803 JFUNCTION(json_extract
, -1, 0, jsonExtractFunc
),
3804 JFUNCTION(->, 2, JSON_JSON
, jsonExtractFunc
),
3805 JFUNCTION(->>, 2, JSON_SQL
, jsonExtractFunc
),
3806 JFUNCTION(json_insert
, -1, 0, jsonSetFunc
),
3807 JFUNCTION(json_object
, -1, 0, jsonObjectFunc
),
3808 JFUNCTION(json_patch
, 2, 0, jsonPatchFunc
),
3809 JFUNCTION(json_quote
, 1, 0, jsonQuoteFunc
),
3810 JFUNCTION(json_remove
, -1, 0, jsonRemoveFunc
),
3811 JFUNCTION(json_replace
, -1, 0, jsonReplaceFunc
),
3812 JFUNCTION(json_set
, -1, JSON_ISSET
, jsonSetFunc
),
3813 JFUNCTION(json_type
, 1, 0, jsonTypeFunc
),
3814 JFUNCTION(json_type
, 2, 0, jsonTypeFunc
),
3815 JFUNCTION(json_valid
, 1, 0, jsonValidFunc
),
3817 JFUNCTION(json_parse
, 1, 0, jsonParseFunc
),
3818 JFUNCTION(json_test1
, 1, 0, jsonTest1Func
),
3820 WAGGREGATE(json_group_array
, 1, 0, 0,
3821 jsonArrayStep
, jsonArrayFinal
, jsonArrayValue
, jsonGroupInverse
,
3822 SQLITE_SUBTYPE
|SQLITE_UTF8
|SQLITE_DETERMINISTIC
),
3823 WAGGREGATE(json_group_object
, 2, 0, 0,
3824 jsonObjectStep
, jsonObjectFinal
, jsonObjectValue
, jsonGroupInverse
,
3825 SQLITE_SUBTYPE
|SQLITE_UTF8
|SQLITE_DETERMINISTIC
)
3827 sqlite3InsertBuiltinFuncs(aJsonFunc
, ArraySize(aJsonFunc
));
3831 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
3833 ** Register the JSON table-valued functions
3835 int sqlite3JsonTableFunctions(sqlite3
*db
){
3837 static const struct {
3839 sqlite3_module
*pModule
;
3841 { "json_each", &jsonEachModule
},
3842 { "json_tree", &jsonTreeModule
},
3845 for(i
=0; i
<sizeof(aMod
)/sizeof(aMod
[0]) && rc
==SQLITE_OK
; i
++){
3846 rc
= sqlite3_create_module(db
, aMod
[i
].zName
, aMod
[i
].pModule
, 0);
3850 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */