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 extension implements JSON functions. The interface is
14 ** modeled after MySQL JSON functions:
16 ** https://dev.mysql.com/doc/refman/5.7/en/json.html
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 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
25 #if !defined(SQLITEINT_H)
26 #include "sqlite3ext.h"
28 SQLITE_EXTENSION_INIT1
34 /* Mark a function parameter as unused, to suppress nuisance compiler
37 # define UNUSED_PARAM(X) (void)(X)
41 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
42 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
46 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
47 ** to pass signed char values.
50 /* Use the SQLite core versions if this routine is part of the
51 ** SQLite amalgamation */
52 # define safe_isdigit(x) sqlite3Isdigit(x)
53 # define safe_isalnum(x) sqlite3Isalnum(x)
54 # define safe_isxdigit(x) sqlite3Isxdigit(x)
56 /* Use the standard library for separate compilation */
57 #include <ctype.h> /* amalgamator: keep */
58 # define safe_isdigit(x) isdigit((unsigned char)(x))
59 # define safe_isalnum(x) isalnum((unsigned char)(x))
60 # define safe_isxdigit(x) isxdigit((unsigned char)(x))
64 ** Growing our own isspace() routine this way is twice as fast as
65 ** the library isspace() function, resulting in a 7% overall performance
66 ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
68 static const char jsonIsSpace
[] = {
69 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
74 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
75 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
76 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86 #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
88 #ifndef SQLITE_AMALGAMATION
89 /* Unsigned integer types. These are already defined in the sqliteInt.h,
90 ** but the definitions need to be repeated for separate compilation. */
91 typedef sqlite3_uint64 u64
;
92 typedef unsigned int u32
;
93 typedef unsigned short int u16
;
94 typedef unsigned char u8
;
98 typedef struct JsonString JsonString
;
99 typedef struct JsonNode JsonNode
;
100 typedef struct JsonParse JsonParse
;
102 /* An instance of this object represents a JSON string
103 ** under construction. Really, this is a generic string accumulator
104 ** that can be and is used to create strings other than JSON.
107 sqlite3_context
*pCtx
; /* Function context - put error messages here */
108 char *zBuf
; /* Append JSON content here */
109 u64 nAlloc
; /* Bytes of storage available in zBuf[] */
110 u64 nUsed
; /* Bytes of zBuf[] currently used */
111 u8 bStatic
; /* True if zBuf is static space */
112 u8 bErr
; /* True if an error has been encountered */
113 char zSpace
[100]; /* Initial static space */
123 #define JSON_STRING 5
125 #define JSON_OBJECT 7
127 /* The "subtype" set for JSON values */
128 #define JSON_SUBTYPE 74 /* Ascii for "J" */
131 ** Names of the various JSON types:
133 static const char * const jsonType
[] = {
134 "null", "true", "false", "integer", "real", "text", "array", "object"
137 /* Bit values for the JsonNode.jnFlag field
139 #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
140 #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
141 #define JNODE_REMOVE 0x04 /* Do not output */
142 #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
143 #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
144 #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
145 #define JNODE_LABEL 0x40 /* Is a label of an object */
148 /* A single node of parsed JSON
151 u8 eType
; /* One of the JSON_ type values */
152 u8 jnFlags
; /* JNODE flags */
153 u32 n
; /* Bytes of content, or number of sub-nodes */
155 const char *zJContent
; /* Content for INT, REAL, and STRING */
156 u32 iAppend
; /* More terms for ARRAY and OBJECT */
157 u32 iKey
; /* Key for ARRAY objects in json_tree() */
158 u32 iReplace
; /* Replacement content for JNODE_REPLACE */
159 JsonNode
*pPatch
; /* Node chain of patch for JNODE_PATCH */
163 /* A completely parsed JSON string
166 u32 nNode
; /* Number of slots of aNode[] used */
167 u32 nAlloc
; /* Number of slots of aNode[] allocated */
168 JsonNode
*aNode
; /* Array of nodes containing the parse */
169 const char *zJson
; /* Original JSON string */
170 u32
*aUp
; /* Index of parent of each node */
171 u8 oom
; /* Set to true if out of memory */
172 u8 nErr
; /* Number of errors seen */
173 u16 iDepth
; /* Nesting depth */
174 int nJson
; /* Length of the zJson string in bytes */
178 ** Maximum nesting depth of JSON for this implementation.
180 ** This limit is needed to avoid a stack overflow in the recursive
181 ** descent parser. A depth of 2000 is far deeper than any sane JSON
184 #define JSON_MAX_DEPTH 2000
186 /**************************************************************************
187 ** Utility routines for dealing with JsonString objects
188 **************************************************************************/
190 /* Set the JsonString object to an empty string
192 static void jsonZero(JsonString
*p
){
194 p
->nAlloc
= sizeof(p
->zSpace
);
199 /* Initialize the JsonString object
201 static void jsonInit(JsonString
*p
, sqlite3_context
*pCtx
){
208 /* Free all allocated memory and reset the JsonString object back to its
211 static void jsonReset(JsonString
*p
){
212 if( !p
->bStatic
) sqlite3_free(p
->zBuf
);
217 /* Report an out-of-memory (OOM) condition
219 static void jsonOom(JsonString
*p
){
221 sqlite3_result_error_nomem(p
->pCtx
);
225 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
226 ** Return zero on success. Return non-zero on an OOM error
228 static int jsonGrow(JsonString
*p
, u32 N
){
229 u64 nTotal
= N
<p
->nAlloc
? p
->nAlloc
*2 : p
->nAlloc
+N
+10;
232 if( p
->bErr
) return 1;
233 zNew
= sqlite3_malloc64(nTotal
);
238 memcpy(zNew
, p
->zBuf
, (size_t)p
->nUsed
);
242 zNew
= sqlite3_realloc64(p
->zBuf
, nTotal
);
253 /* Append N bytes from zIn onto the end of the JsonString string.
255 static void jsonAppendRaw(JsonString
*p
, const char *zIn
, u32 N
){
256 if( (N
+p
->nUsed
>= p
->nAlloc
) && jsonGrow(p
,N
)!=0 ) return;
257 memcpy(p
->zBuf
+p
->nUsed
, zIn
, N
);
261 /* Append formatted text (not to exceed N bytes) to the JsonString.
263 static void jsonPrintf(int N
, JsonString
*p
, const char *zFormat
, ...){
265 if( (p
->nUsed
+ N
>= p
->nAlloc
) && jsonGrow(p
, N
) ) return;
266 va_start(ap
, zFormat
);
267 sqlite3_vsnprintf(N
, p
->zBuf
+p
->nUsed
, zFormat
, ap
);
269 p
->nUsed
+= (int)strlen(p
->zBuf
+p
->nUsed
);
272 /* Append a single character
274 static void jsonAppendChar(JsonString
*p
, char c
){
275 if( p
->nUsed
>=p
->nAlloc
&& jsonGrow(p
,1)!=0 ) return;
276 p
->zBuf
[p
->nUsed
++] = c
;
279 /* Append a comma separator to the output buffer, if the previous
280 ** character is not '[' or '{'.
282 static void jsonAppendSeparator(JsonString
*p
){
284 if( p
->nUsed
==0 ) return;
285 c
= p
->zBuf
[p
->nUsed
-1];
286 if( c
!='[' && c
!='{' ) jsonAppendChar(p
, ',');
289 /* Append the N-byte string in zIn to the end of the JsonString string
290 ** under construction. Enclose the string in "..." and escape
291 ** any double-quotes or backslash characters contained within the
294 static void jsonAppendString(JsonString
*p
, const char *zIn
, u32 N
){
296 if( (N
+p
->nUsed
+2 >= p
->nAlloc
) && jsonGrow(p
,N
+2)!=0 ) return;
297 p
->zBuf
[p
->nUsed
++] = '"';
299 unsigned char c
= ((unsigned const char*)zIn
)[i
];
300 if( c
=='"' || c
=='\\' ){
302 if( (p
->nUsed
+N
+3-i
> p
->nAlloc
) && jsonGrow(p
,N
+3-i
)!=0 ) return;
303 p
->zBuf
[p
->nUsed
++] = '\\';
305 static const char aSpecial
[] = {
306 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
307 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
309 assert( sizeof(aSpecial
)==32 );
310 assert( aSpecial
['\b']=='b' );
311 assert( aSpecial
['\f']=='f' );
312 assert( aSpecial
['\n']=='n' );
313 assert( aSpecial
['\r']=='r' );
314 assert( aSpecial
['\t']=='t' );
317 goto json_simple_escape
;
319 if( (p
->nUsed
+N
+7+i
> p
->nAlloc
) && jsonGrow(p
,N
+7-i
)!=0 ) return;
320 p
->zBuf
[p
->nUsed
++] = '\\';
321 p
->zBuf
[p
->nUsed
++] = 'u';
322 p
->zBuf
[p
->nUsed
++] = '0';
323 p
->zBuf
[p
->nUsed
++] = '0';
324 p
->zBuf
[p
->nUsed
++] = '0' + (c
>>4);
325 c
= "0123456789abcdef"[c
&0xf];
327 p
->zBuf
[p
->nUsed
++] = c
;
329 p
->zBuf
[p
->nUsed
++] = '"';
330 assert( p
->nUsed
<p
->nAlloc
);
334 ** Append a function parameter value to the JSON string under
337 static void jsonAppendValue(
338 JsonString
*p
, /* Append to this JSON string */
339 sqlite3_value
*pValue
/* Value to append */
341 switch( sqlite3_value_type(pValue
) ){
343 jsonAppendRaw(p
, "null", 4);
348 const char *z
= (const char*)sqlite3_value_text(pValue
);
349 u32 n
= (u32
)sqlite3_value_bytes(pValue
);
350 jsonAppendRaw(p
, z
, n
);
354 const char *z
= (const char*)sqlite3_value_text(pValue
);
355 u32 n
= (u32
)sqlite3_value_bytes(pValue
);
356 if( sqlite3_value_subtype(pValue
)==JSON_SUBTYPE
){
357 jsonAppendRaw(p
, z
, n
);
359 jsonAppendString(p
, z
, n
);
365 sqlite3_result_error(p
->pCtx
, "JSON cannot hold BLOB values", -1);
375 /* Make the JSON in p the result of the SQL function.
377 static void jsonResult(JsonString
*p
){
379 sqlite3_result_text64(p
->pCtx
, p
->zBuf
, p
->nUsed
,
380 p
->bStatic
? SQLITE_TRANSIENT
: sqlite3_free
,
384 assert( p
->bStatic
);
387 /**************************************************************************
388 ** Utility routines for dealing with JsonNode and JsonParse objects
389 **************************************************************************/
392 ** Return the number of consecutive JsonNode slots need to represent
393 ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
394 ** OBJECT types, the number might be larger.
396 ** Appended elements are not counted. The value returned is the number
397 ** by which the JsonNode counter should increment in order to go to the
400 static u32
jsonNodeSize(JsonNode
*pNode
){
401 return pNode
->eType
>=JSON_ARRAY
? pNode
->n
+1 : 1;
405 ** Reclaim all memory allocated by a JsonParse object. But do not
406 ** delete the JsonParse object itself.
408 static void jsonParseReset(JsonParse
*pParse
){
409 sqlite3_free(pParse
->aNode
);
413 sqlite3_free(pParse
->aUp
);
418 ** Free a JsonParse object that was obtained from sqlite3_malloc().
420 static void jsonParseFree(JsonParse
*pParse
){
421 jsonParseReset(pParse
);
422 sqlite3_free(pParse
);
426 ** Convert the JsonNode pNode into a pure JSON string and
427 ** append to pOut. Subsubstructure is also included. Return
428 ** the number of JsonNode objects that are encoded.
430 static void jsonRenderNode(
431 JsonNode
*pNode
, /* The node to render */
432 JsonString
*pOut
, /* Write JSON here */
433 sqlite3_value
**aReplace
/* Replacement values */
435 if( pNode
->jnFlags
& (JNODE_REPLACE
|JNODE_PATCH
) ){
436 if( pNode
->jnFlags
& JNODE_REPLACE
){
437 jsonAppendValue(pOut
, aReplace
[pNode
->u
.iReplace
]);
440 pNode
= pNode
->u
.pPatch
;
442 switch( pNode
->eType
){
444 assert( pNode
->eType
==JSON_NULL
);
445 jsonAppendRaw(pOut
, "null", 4);
449 jsonAppendRaw(pOut
, "true", 4);
453 jsonAppendRaw(pOut
, "false", 5);
457 if( pNode
->jnFlags
& JNODE_RAW
){
458 jsonAppendString(pOut
, pNode
->u
.zJContent
, pNode
->n
);
461 /* Fall through into the next case */
465 jsonAppendRaw(pOut
, pNode
->u
.zJContent
, pNode
->n
);
470 jsonAppendChar(pOut
, '[');
472 while( j
<=pNode
->n
){
473 if( (pNode
[j
].jnFlags
& JNODE_REMOVE
)==0 ){
474 jsonAppendSeparator(pOut
);
475 jsonRenderNode(&pNode
[j
], pOut
, aReplace
);
477 j
+= jsonNodeSize(&pNode
[j
]);
479 if( (pNode
->jnFlags
& JNODE_APPEND
)==0 ) break;
480 pNode
= &pNode
[pNode
->u
.iAppend
];
483 jsonAppendChar(pOut
, ']');
488 jsonAppendChar(pOut
, '{');
490 while( j
<=pNode
->n
){
491 if( (pNode
[j
+1].jnFlags
& JNODE_REMOVE
)==0 ){
492 jsonAppendSeparator(pOut
);
493 jsonRenderNode(&pNode
[j
], pOut
, aReplace
);
494 jsonAppendChar(pOut
, ':');
495 jsonRenderNode(&pNode
[j
+1], pOut
, aReplace
);
497 j
+= 1 + jsonNodeSize(&pNode
[j
+1]);
499 if( (pNode
->jnFlags
& JNODE_APPEND
)==0 ) break;
500 pNode
= &pNode
[pNode
->u
.iAppend
];
503 jsonAppendChar(pOut
, '}');
510 ** Return a JsonNode and all its descendents as a JSON string.
512 static void jsonReturnJson(
513 JsonNode
*pNode
, /* Node to return */
514 sqlite3_context
*pCtx
, /* Return value for this function */
515 sqlite3_value
**aReplace
/* Array of replacement values */
519 jsonRenderNode(pNode
, &s
, aReplace
);
521 sqlite3_result_subtype(pCtx
, JSON_SUBTYPE
);
525 ** Make the JsonNode the return value of the function.
527 static void jsonReturn(
528 JsonNode
*pNode
, /* Node to return */
529 sqlite3_context
*pCtx
, /* Return value for this function */
530 sqlite3_value
**aReplace
/* Array of replacement values */
532 switch( pNode
->eType
){
534 assert( pNode
->eType
==JSON_NULL
);
535 sqlite3_result_null(pCtx
);
539 sqlite3_result_int(pCtx
, 1);
543 sqlite3_result_int(pCtx
, 0);
548 const char *z
= pNode
->u
.zJContent
;
549 if( z
[0]=='-' ){ z
++; }
550 while( z
[0]>='0' && z
[0]<='9' ){
551 unsigned v
= *(z
++) - '0';
552 if( i
>=LARGEST_INT64
/10 ){
553 if( i
>LARGEST_INT64
/10 ) goto int_as_real
;
554 if( z
[0]>='0' && z
[0]<='9' ) goto int_as_real
;
555 if( v
==9 ) goto int_as_real
;
557 if( pNode
->u
.zJContent
[0]=='-' ){
558 sqlite3_result_int64(pCtx
, SMALLEST_INT64
);
567 if( pNode
->u
.zJContent
[0]=='-' ){ i
= -i
; }
568 sqlite3_result_int64(pCtx
, i
);
571 int_as_real
: /* fall through to real */;
575 #ifdef SQLITE_AMALGAMATION
576 const char *z
= pNode
->u
.zJContent
;
577 sqlite3AtoF(z
, &r
, sqlite3Strlen30(z
), SQLITE_UTF8
);
579 r
= strtod(pNode
->u
.zJContent
, 0);
581 sqlite3_result_double(pCtx
, r
);
585 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
586 ** json_insert() and json_replace() and those routines do not
587 ** call jsonReturn() */
588 if( pNode
->jnFlags
& JNODE_RAW
){
589 sqlite3_result_text(pCtx
, pNode
->u
.zJContent
, pNode
->n
,
593 assert( (pNode
->jnFlags
& JNODE_RAW
)==0 );
594 if( (pNode
->jnFlags
& JNODE_ESCAPE
)==0 ){
595 /* JSON formatted without any backslash-escapes */
596 sqlite3_result_text(pCtx
, pNode
->u
.zJContent
+1, pNode
->n
-2,
599 /* Translate JSON formatted string into raw text */
602 const char *z
= pNode
->u
.zJContent
;
605 zOut
= sqlite3_malloc( n
+1 );
607 sqlite3_result_error_nomem(pCtx
);
610 for(i
=1, j
=0; i
<n
-1; i
++){
618 for(k
=0; k
<4; i
++, k
++){
621 assert( safe_isxdigit(c
) );
622 if( c
<='9' ) v
= v
*16 + c
- '0';
623 else if( c
<='F' ) v
= v
*16 + c
- 'A' + 10;
624 else v
= v
*16 + c
- 'a' + 10;
629 }else if( v
<=0x7ff ){
630 zOut
[j
++] = (char)(0xc0 | (v
>>6));
631 zOut
[j
++] = 0x80 | (v
&0x3f);
633 zOut
[j
++] = (char)(0xe0 | (v
>>12));
634 zOut
[j
++] = 0x80 | ((v
>>6)&0x3f);
635 zOut
[j
++] = 0x80 | (v
&0x3f);
654 sqlite3_result_text(pCtx
, zOut
, j
, sqlite3_free
);
660 jsonReturnJson(pNode
, pCtx
, aReplace
);
666 /* Forward reference */
667 static int jsonParseAddNode(JsonParse
*,u32
,u32
,const char*);
670 ** A macro to hint to the compiler that a function should not be
673 #if defined(__GNUC__)
674 # define JSON_NOINLINE __attribute__((noinline))
675 #elif defined(_MSC_VER) && _MSC_VER>=1310
676 # define JSON_NOINLINE __declspec(noinline)
678 # define JSON_NOINLINE
682 static JSON_NOINLINE
int jsonParseAddNodeExpand(
683 JsonParse
*pParse
, /* Append the node to this object */
684 u32 eType
, /* Node type */
685 u32 n
, /* Content size or sub-node count */
686 const char *zContent
/* Content */
690 assert( pParse
->nNode
>=pParse
->nAlloc
);
691 if( pParse
->oom
) return -1;
692 nNew
= pParse
->nAlloc
*2 + 10;
693 pNew
= sqlite3_realloc(pParse
->aNode
, sizeof(JsonNode
)*nNew
);
698 pParse
->nAlloc
= nNew
;
699 pParse
->aNode
= pNew
;
700 assert( pParse
->nNode
<pParse
->nAlloc
);
701 return jsonParseAddNode(pParse
, eType
, n
, zContent
);
705 ** Create a new JsonNode instance based on the arguments and append that
706 ** instance to the JsonParse. Return the index in pParse->aNode[] of the
707 ** new node, or -1 if a memory allocation fails.
709 static int jsonParseAddNode(
710 JsonParse
*pParse
, /* Append the node to this object */
711 u32 eType
, /* Node type */
712 u32 n
, /* Content size or sub-node count */
713 const char *zContent
/* Content */
716 if( pParse
->nNode
>=pParse
->nAlloc
){
717 return jsonParseAddNodeExpand(pParse
, eType
, n
, zContent
);
719 p
= &pParse
->aNode
[pParse
->nNode
];
720 p
->eType
= (u8
)eType
;
723 p
->u
.zJContent
= zContent
;
724 return pParse
->nNode
++;
728 ** Return true if z[] begins with 4 (or more) hexadecimal digits
730 static int jsonIs4Hex(const char *z
){
732 for(i
=0; i
<4; i
++) if( !safe_isxdigit(z
[i
]) ) return 0;
737 ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
738 ** index of the first character past the end of the value parsed.
740 ** Return negative for a syntax error. Special cases: return -2 if the
741 ** first non-whitespace character is '}' and return -3 if the first
742 ** non-whitespace character is ']'.
744 static int jsonParseValue(JsonParse
*pParse
, u32 i
){
750 const char *z
= pParse
->zJson
;
751 while( safe_isspace(z
[i
]) ){ i
++; }
752 if( (c
= z
[i
])=='{' ){
754 iThis
= jsonParseAddNode(pParse
, JSON_OBJECT
, 0, 0);
755 if( iThis
<0 ) return -1;
757 while( safe_isspace(z
[j
]) ){ j
++; }
758 if( ++pParse
->iDepth
> JSON_MAX_DEPTH
) return -1;
759 x
= jsonParseValue(pParse
, j
);
762 if( x
==(-2) && pParse
->nNode
==(u32
)iThis
+1 ) return j
+1;
765 if( pParse
->oom
) return -1;
766 pNode
= &pParse
->aNode
[pParse
->nNode
-1];
767 if( pNode
->eType
!=JSON_STRING
) return -1;
768 pNode
->jnFlags
|= JNODE_LABEL
;
770 while( safe_isspace(z
[j
]) ){ j
++; }
771 if( z
[j
]!=':' ) return -1;
773 x
= jsonParseValue(pParse
, j
);
777 while( safe_isspace(z
[j
]) ){ j
++; }
779 if( c
==',' ) continue;
780 if( c
!='}' ) return -1;
783 pParse
->aNode
[iThis
].n
= pParse
->nNode
- (u32
)iThis
- 1;
787 iThis
= jsonParseAddNode(pParse
, JSON_ARRAY
, 0, 0);
788 if( iThis
<0 ) return -1;
790 while( safe_isspace(z
[j
]) ){ j
++; }
791 if( ++pParse
->iDepth
> JSON_MAX_DEPTH
) return -1;
792 x
= jsonParseValue(pParse
, j
);
795 if( x
==(-3) && pParse
->nNode
==(u32
)iThis
+1 ) return j
+1;
799 while( safe_isspace(z
[j
]) ){ j
++; }
801 if( c
==',' ) continue;
802 if( c
!=']' ) return -1;
805 pParse
->aNode
[iThis
].n
= pParse
->nNode
- (u32
)iThis
- 1;
813 if( (c
& ~0x1f)==0 ){
814 /* Control characters are not allowed in strings */
819 if( c
=='"' || c
=='\\' || c
=='/' || c
=='b' || c
=='f'
820 || c
=='n' || c
=='r' || c
=='t'
821 || (c
=='u' && jsonIs4Hex(z
+j
+1)) ){
822 jnFlags
= JNODE_ESCAPE
;
831 jsonParseAddNode(pParse
, JSON_STRING
, j
+1-i
, &z
[i
]);
832 if( !pParse
->oom
) pParse
->aNode
[pParse
->nNode
-1].jnFlags
= jnFlags
;
835 && strncmp(z
+i
,"null",4)==0
836 && !safe_isalnum(z
[i
+4]) ){
837 jsonParseAddNode(pParse
, JSON_NULL
, 0, 0);
840 && strncmp(z
+i
,"true",4)==0
841 && !safe_isalnum(z
[i
+4]) ){
842 jsonParseAddNode(pParse
, JSON_TRUE
, 0, 0);
845 && strncmp(z
+i
,"false",5)==0
846 && !safe_isalnum(z
[i
+5]) ){
847 jsonParseAddNode(pParse
, JSON_FALSE
, 0, 0);
849 }else if( c
=='-' || (c
>='0' && c
<='9') ){
855 j
= c
=='-' ? i
+1 : i
;
856 if( z
[j
]=='0' && z
[j
+1]>='0' && z
[j
+1]<='9' ) return -1;
861 if( c
>='0' && c
<='9' ) continue;
863 if( z
[j
-1]=='-' ) return -1;
864 if( seenDP
) return -1;
868 if( c
=='e' || c
=='E' ){
869 if( z
[j
-1]<'0' ) return -1;
870 if( seenE
) return -1;
873 if( c
=='+' || c
=='-' ){
877 if( c
<'0' || c
>'9' ) return -1;
882 if( z
[j
-1]<'0' ) return -1;
883 jsonParseAddNode(pParse
, seenDP
? JSON_REAL
: JSON_INT
,
887 return -2; /* End of {...} */
889 return -3; /* End of [...] */
891 return 0; /* End of file */
893 return -1; /* Syntax error */
898 ** Parse a complete JSON string. Return 0 on success or non-zero if there
899 ** are any errors. If an error occurs, free all memory associated with
902 ** pParse is uninitialized when this routine is called.
904 static int jsonParse(
905 JsonParse
*pParse
, /* Initialize and fill this JsonParse object */
906 sqlite3_context
*pCtx
, /* Report errors here */
907 const char *zJson
/* Input JSON text to be parsed */
910 memset(pParse
, 0, sizeof(*pParse
));
911 if( zJson
==0 ) return 1;
912 pParse
->zJson
= zJson
;
913 i
= jsonParseValue(pParse
, 0);
914 if( pParse
->oom
) i
= -1;
916 assert( pParse
->iDepth
==0 );
917 while( safe_isspace(zJson
[i
]) ) i
++;
918 if( zJson
[i
] ) i
= -1;
923 sqlite3_result_error_nomem(pCtx
);
925 sqlite3_result_error(pCtx
, "malformed JSON", -1);
928 jsonParseReset(pParse
);
934 /* Mark node i of pParse as being a child of iParent. Call recursively
935 ** to fill in all the descendants of node i.
937 static void jsonParseFillInParentage(JsonParse
*pParse
, u32 i
, u32 iParent
){
938 JsonNode
*pNode
= &pParse
->aNode
[i
];
940 pParse
->aUp
[i
] = iParent
;
941 switch( pNode
->eType
){
943 for(j
=1; j
<=pNode
->n
; j
+= jsonNodeSize(pNode
+j
)){
944 jsonParseFillInParentage(pParse
, i
+j
, i
);
949 for(j
=1; j
<=pNode
->n
; j
+= jsonNodeSize(pNode
+j
+1)+1){
950 pParse
->aUp
[i
+j
] = i
;
951 jsonParseFillInParentage(pParse
, i
+j
+1, i
);
962 ** Compute the parentage of all nodes in a completed parse.
964 static int jsonParseFindParents(JsonParse
*pParse
){
966 assert( pParse
->aUp
==0 );
967 aUp
= pParse
->aUp
= sqlite3_malloc( sizeof(u32
)*pParse
->nNode
);
972 jsonParseFillInParentage(pParse
, 0, 0);
977 ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
979 #define JSON_CACHE_ID (-429938)
982 ** Obtain a complete parse of the JSON found in the first argument
983 ** of the argv array. Use the sqlite3_get_auxdata() cache for this
984 ** parse if it is available. If the cache is not available or if it
985 ** is no longer valid, parse the JSON again and return the new parse,
986 ** and also register the new parse so that it will be available for
987 ** future sqlite3_get_auxdata() calls.
989 static JsonParse
*jsonParseCached(
990 sqlite3_context
*pCtx
,
993 const char *zJson
= (const char*)sqlite3_value_text(argv
[0]);
994 int nJson
= sqlite3_value_bytes(argv
[0]);
996 if( zJson
==0 ) return 0;
997 p
= (JsonParse
*)sqlite3_get_auxdata(pCtx
, JSON_CACHE_ID
);
998 if( p
&& p
->nJson
==nJson
&& memcmp(p
->zJson
,zJson
,nJson
)==0 ){
1000 return p
; /* The cached entry matches, so return it */
1002 p
= sqlite3_malloc( sizeof(*p
) + nJson
+ 1 );
1004 sqlite3_result_error_nomem(pCtx
);
1007 memset(p
, 0, sizeof(*p
));
1008 p
->zJson
= (char*)&p
[1];
1009 memcpy((char*)p
->zJson
, zJson
, nJson
+1);
1010 if( jsonParse(p
, pCtx
, p
->zJson
) ){
1015 sqlite3_set_auxdata(pCtx
, JSON_CACHE_ID
, p
, (void(*)(void*))jsonParseFree
);
1016 return (JsonParse
*)sqlite3_get_auxdata(pCtx
, JSON_CACHE_ID
);
1020 ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1023 static int jsonLabelCompare(JsonNode
*pNode
, const char *zKey
, u32 nKey
){
1024 if( pNode
->jnFlags
& JNODE_RAW
){
1025 if( pNode
->n
!=nKey
) return 0;
1026 return strncmp(pNode
->u
.zJContent
, zKey
, nKey
)==0;
1028 if( pNode
->n
!=nKey
+2 ) return 0;
1029 return strncmp(pNode
->u
.zJContent
+1, zKey
, nKey
)==0;
1033 /* forward declaration */
1034 static JsonNode
*jsonLookupAppend(JsonParse
*,const char*,int*,const char**);
1037 ** Search along zPath to find the node specified. Return a pointer
1038 ** to that node, or NULL if zPath is malformed or if there is no such
1041 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
1042 ** possible to do so and if no existing node corresponds to zPath. If
1043 ** new nodes are appended *pApnd is set to 1.
1045 static JsonNode
*jsonLookupStep(
1046 JsonParse
*pParse
, /* The JSON to search */
1047 u32 iRoot
, /* Begin the search at this node */
1048 const char *zPath
, /* The path to search */
1049 int *pApnd
, /* Append nodes to complete path if not NULL */
1050 const char **pzErr
/* Make *pzErr point to any syntax error in zPath */
1054 JsonNode
*pRoot
= &pParse
->aNode
[iRoot
];
1055 if( zPath
[0]==0 ) return pRoot
;
1056 if( zPath
[0]=='.' ){
1057 if( pRoot
->eType
!=JSON_OBJECT
) return 0;
1059 if( zPath
[0]=='"' ){
1061 for(i
=1; zPath
[i
] && zPath
[i
]!='"'; i
++){}
1071 for(i
=0; zPath
[i
] && zPath
[i
]!='.' && zPath
[i
]!='['; i
++){}
1080 while( j
<=pRoot
->n
){
1081 if( jsonLabelCompare(pRoot
+j
, zKey
, nKey
) ){
1082 return jsonLookupStep(pParse
, iRoot
+j
+1, &zPath
[i
], pApnd
, pzErr
);
1085 j
+= jsonNodeSize(&pRoot
[j
]);
1087 if( (pRoot
->jnFlags
& JNODE_APPEND
)==0 ) break;
1088 iRoot
+= pRoot
->u
.iAppend
;
1089 pRoot
= &pParse
->aNode
[iRoot
];
1095 iStart
= jsonParseAddNode(pParse
, JSON_OBJECT
, 2, 0);
1096 iLabel
= jsonParseAddNode(pParse
, JSON_STRING
, i
, zPath
);
1098 pNode
= jsonLookupAppend(pParse
, zPath
, pApnd
, pzErr
);
1099 if( pParse
->oom
) return 0;
1101 pRoot
= &pParse
->aNode
[iRoot
];
1102 pRoot
->u
.iAppend
= iStart
- iRoot
;
1103 pRoot
->jnFlags
|= JNODE_APPEND
;
1104 pParse
->aNode
[iLabel
].jnFlags
|= JNODE_RAW
;
1108 }else if( zPath
[0]=='[' && safe_isdigit(zPath
[1]) ){
1109 if( pRoot
->eType
!=JSON_ARRAY
) return 0;
1112 while( safe_isdigit(zPath
[j
]) ){
1113 i
= i
*10 + zPath
[j
] - '0';
1116 if( zPath
[j
]!=']' ){
1123 while( j
<=pRoot
->n
&& (i
>0 || (pRoot
[j
].jnFlags
& JNODE_REMOVE
)!=0) ){
1124 if( (pRoot
[j
].jnFlags
& JNODE_REMOVE
)==0 ) i
--;
1125 j
+= jsonNodeSize(&pRoot
[j
]);
1127 if( (pRoot
->jnFlags
& JNODE_APPEND
)==0 ) break;
1128 iRoot
+= pRoot
->u
.iAppend
;
1129 pRoot
= &pParse
->aNode
[iRoot
];
1133 return jsonLookupStep(pParse
, iRoot
+j
, zPath
, pApnd
, pzErr
);
1135 if( i
==0 && pApnd
){
1138 iStart
= jsonParseAddNode(pParse
, JSON_ARRAY
, 1, 0);
1139 pNode
= jsonLookupAppend(pParse
, zPath
, pApnd
, pzErr
);
1140 if( pParse
->oom
) return 0;
1142 pRoot
= &pParse
->aNode
[iRoot
];
1143 pRoot
->u
.iAppend
= iStart
- iRoot
;
1144 pRoot
->jnFlags
|= JNODE_APPEND
;
1155 ** Append content to pParse that will complete zPath. Return a pointer
1156 ** to the inserted node, or return NULL if the append fails.
1158 static JsonNode
*jsonLookupAppend(
1159 JsonParse
*pParse
, /* Append content to the JSON parse */
1160 const char *zPath
, /* Description of content to append */
1161 int *pApnd
, /* Set this flag to 1 */
1162 const char **pzErr
/* Make this point to any syntax error */
1166 jsonParseAddNode(pParse
, JSON_NULL
, 0, 0);
1167 return pParse
->oom
? 0 : &pParse
->aNode
[pParse
->nNode
-1];
1169 if( zPath
[0]=='.' ){
1170 jsonParseAddNode(pParse
, JSON_OBJECT
, 0, 0);
1171 }else if( strncmp(zPath
,"[0]",3)==0 ){
1172 jsonParseAddNode(pParse
, JSON_ARRAY
, 0, 0);
1176 if( pParse
->oom
) return 0;
1177 return jsonLookupStep(pParse
, pParse
->nNode
-1, zPath
, pApnd
, pzErr
);
1181 ** Return the text of a syntax error message on a JSON path. Space is
1182 ** obtained from sqlite3_malloc().
1184 static char *jsonPathSyntaxError(const char *zErr
){
1185 return sqlite3_mprintf("JSON path error near '%q'", zErr
);
1189 ** Do a node lookup using zPath. Return a pointer to the node on success.
1190 ** Return NULL if not found or if there is an error.
1192 ** On an error, write an error message into pCtx and increment the
1193 ** pParse->nErr counter.
1195 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1196 ** nodes are appended.
1198 static JsonNode
*jsonLookup(
1199 JsonParse
*pParse
, /* The JSON to search */
1200 const char *zPath
, /* The path to search */
1201 int *pApnd
, /* Append nodes to complete path if not NULL */
1202 sqlite3_context
*pCtx
/* Report errors here, if not NULL */
1204 const char *zErr
= 0;
1205 JsonNode
*pNode
= 0;
1208 if( zPath
==0 ) return 0;
1209 if( zPath
[0]!='$' ){
1214 pNode
= jsonLookupStep(pParse
, 0, zPath
, pApnd
, &zErr
);
1215 if( zErr
==0 ) return pNode
;
1219 assert( zErr
!=0 && pCtx
!=0 );
1220 zMsg
= jsonPathSyntaxError(zErr
);
1222 sqlite3_result_error(pCtx
, zMsg
, -1);
1225 sqlite3_result_error_nomem(pCtx
);
1232 ** Report the wrong number of arguments for json_insert(), json_replace()
1235 static void jsonWrongNumArgs(
1236 sqlite3_context
*pCtx
,
1237 const char *zFuncName
1239 char *zMsg
= sqlite3_mprintf("json_%s() needs an odd number of arguments",
1241 sqlite3_result_error(pCtx
, zMsg
, -1);
1246 ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1248 static void jsonRemoveAllNulls(JsonNode
*pNode
){
1250 assert( pNode
->eType
==JSON_OBJECT
);
1252 for(i
=2; i
<=n
; i
+= jsonNodeSize(&pNode
[i
])+1){
1253 switch( pNode
[i
].eType
){
1255 pNode
[i
].jnFlags
|= JNODE_REMOVE
;
1258 jsonRemoveAllNulls(&pNode
[i
]);
1265 /****************************************************************************
1266 ** SQL functions used for testing and debugging
1267 ****************************************************************************/
1271 ** The json_parse(JSON) function returns a string which describes
1272 ** a parse of the JSON provided. Or it returns NULL if JSON is not
1275 static void jsonParseFunc(
1276 sqlite3_context
*ctx
,
1278 sqlite3_value
**argv
1280 JsonString s
; /* Output string - not real JSON */
1281 JsonParse x
; /* The parse */
1285 if( jsonParse(&x
, ctx
, (const char*)sqlite3_value_text(argv
[0])) ) return;
1286 jsonParseFindParents(&x
);
1288 for(i
=0; i
<x
.nNode
; i
++){
1290 if( x
.aNode
[i
].jnFlags
& JNODE_LABEL
){
1291 assert( x
.aNode
[i
].eType
==JSON_STRING
);
1294 zType
= jsonType
[x
.aNode
[i
].eType
];
1296 jsonPrintf(100, &s
,"node %3u: %7s n=%-4d up=%-4d",
1297 i
, zType
, x
.aNode
[i
].n
, x
.aUp
[i
]);
1298 if( x
.aNode
[i
].u
.zJContent
!=0 ){
1299 jsonAppendRaw(&s
, " ", 1);
1300 jsonAppendRaw(&s
, x
.aNode
[i
].u
.zJContent
, x
.aNode
[i
].n
);
1302 jsonAppendRaw(&s
, "\n", 1);
1309 ** The json_test1(JSON) function return true (1) if the input is JSON
1310 ** text generated by another json function. It returns (0) if the input
1311 ** is not known to be JSON.
1313 static void jsonTest1Func(
1314 sqlite3_context
*ctx
,
1316 sqlite3_value
**argv
1319 sqlite3_result_int(ctx
, sqlite3_value_subtype(argv
[0])==JSON_SUBTYPE
);
1321 #endif /* SQLITE_DEBUG */
1323 /****************************************************************************
1324 ** Scalar SQL function implementations
1325 ****************************************************************************/
1328 ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1329 ** corresponding to the SQL value input. Mostly this means putting
1330 ** double-quotes around strings and returning the unquoted string "null"
1331 ** when given a NULL input.
1333 static void jsonQuoteFunc(
1334 sqlite3_context
*ctx
,
1336 sqlite3_value
**argv
1342 jsonAppendValue(&jx
, argv
[0]);
1344 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
1348 ** Implementation of the json_array(VALUE,...) function. Return a JSON
1349 ** array that contains all values given in arguments. Or if any argument
1350 ** is a BLOB, throw an error.
1352 static void jsonArrayFunc(
1353 sqlite3_context
*ctx
,
1355 sqlite3_value
**argv
1361 jsonAppendChar(&jx
, '[');
1362 for(i
=0; i
<argc
; i
++){
1363 jsonAppendSeparator(&jx
);
1364 jsonAppendValue(&jx
, argv
[i
]);
1366 jsonAppendChar(&jx
, ']');
1368 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
1373 ** json_array_length(JSON)
1374 ** json_array_length(JSON, PATH)
1376 ** Return the number of elements in the top-level JSON array.
1377 ** Return 0 if the input is not a well-formed JSON array.
1379 static void jsonArrayLengthFunc(
1380 sqlite3_context
*ctx
,
1382 sqlite3_value
**argv
1384 JsonParse
*p
; /* The parse */
1385 sqlite3_int64 n
= 0;
1389 p
= jsonParseCached(ctx
, argv
);
1393 const char *zPath
= (const char*)sqlite3_value_text(argv
[1]);
1394 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
1401 if( pNode
->eType
==JSON_ARRAY
){
1402 assert( (pNode
->jnFlags
& JNODE_APPEND
)==0 );
1403 for(i
=1; i
<=pNode
->n
; n
++){
1404 i
+= jsonNodeSize(&pNode
[i
]);
1407 sqlite3_result_int64(ctx
, n
);
1411 ** json_extract(JSON, PATH, ...)
1413 ** Return the element described by PATH. Return NULL if there is no
1414 ** PATH element. If there are multiple PATHs, then return a JSON array
1415 ** with the result from each path. Throw an error if the JSON or any PATH
1418 static void jsonExtractFunc(
1419 sqlite3_context
*ctx
,
1421 sqlite3_value
**argv
1423 JsonParse
*p
; /* The parse */
1429 if( argc
<2 ) return;
1430 p
= jsonParseCached(ctx
, argv
);
1433 jsonAppendChar(&jx
, '[');
1434 for(i
=1; i
<argc
; i
++){
1435 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
1436 pNode
= jsonLookup(p
, zPath
, 0, ctx
);
1437 if( p
->nErr
) break;
1439 jsonAppendSeparator(&jx
);
1441 jsonRenderNode(pNode
, &jx
, 0);
1443 jsonAppendRaw(&jx
, "null", 4);
1446 jsonReturn(pNode
, ctx
, 0);
1449 if( argc
>2 && i
==argc
){
1450 jsonAppendChar(&jx
, ']');
1452 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
1457 /* This is the RFC 7396 MergePatch algorithm.
1459 static JsonNode
*jsonMergePatch(
1460 JsonParse
*pParse
, /* The JSON parser that contains the TARGET */
1461 u32 iTarget
, /* Node of the TARGET in pParse */
1462 JsonNode
*pPatch
/* The PATCH */
1467 if( pPatch
->eType
!=JSON_OBJECT
){
1470 assert( iTarget
>=0 && iTarget
<pParse
->nNode
);
1471 pTarget
= &pParse
->aNode
[iTarget
];
1472 assert( (pPatch
->jnFlags
& JNODE_APPEND
)==0 );
1473 if( pTarget
->eType
!=JSON_OBJECT
){
1474 jsonRemoveAllNulls(pPatch
);
1478 for(i
=1; i
<pPatch
->n
; i
+= jsonNodeSize(&pPatch
[i
+1])+1){
1481 assert( pPatch
[i
].eType
==JSON_STRING
);
1482 assert( pPatch
[i
].jnFlags
& JNODE_LABEL
);
1484 zKey
= pPatch
[i
].u
.zJContent
;
1485 assert( (pPatch
[i
].jnFlags
& JNODE_RAW
)==0 );
1486 for(j
=1; j
<pTarget
->n
; j
+= jsonNodeSize(&pTarget
[j
+1])+1 ){
1487 assert( pTarget
[j
].eType
==JSON_STRING
);
1488 assert( pTarget
[j
].jnFlags
& JNODE_LABEL
);
1489 assert( (pPatch
[i
].jnFlags
& JNODE_RAW
)==0 );
1490 if( pTarget
[j
].n
==nKey
&& strncmp(pTarget
[j
].u
.zJContent
,zKey
,nKey
)==0 ){
1491 if( pTarget
[j
+1].jnFlags
& (JNODE_REMOVE
|JNODE_PATCH
) ) break;
1492 if( pPatch
[i
+1].eType
==JSON_NULL
){
1493 pTarget
[j
+1].jnFlags
|= JNODE_REMOVE
;
1495 JsonNode
*pNew
= jsonMergePatch(pParse
, iTarget
+j
+1, &pPatch
[i
+1]);
1496 if( pNew
==0 ) return 0;
1497 pTarget
= &pParse
->aNode
[iTarget
];
1498 if( pNew
!=&pTarget
[j
+1] ){
1499 pTarget
[j
+1].u
.pPatch
= pNew
;
1500 pTarget
[j
+1].jnFlags
|= JNODE_PATCH
;
1506 if( j
>=pTarget
->n
&& pPatch
[i
+1].eType
!=JSON_NULL
){
1508 iStart
= jsonParseAddNode(pParse
, JSON_OBJECT
, 2, 0);
1509 jsonParseAddNode(pParse
, JSON_STRING
, nKey
, zKey
);
1510 iPatch
= jsonParseAddNode(pParse
, JSON_TRUE
, 0, 0);
1511 if( pParse
->oom
) return 0;
1512 jsonRemoveAllNulls(pPatch
);
1513 pTarget
= &pParse
->aNode
[iTarget
];
1514 pParse
->aNode
[iRoot
].jnFlags
|= JNODE_APPEND
;
1515 pParse
->aNode
[iRoot
].u
.iAppend
= iStart
- iRoot
;
1517 pParse
->aNode
[iPatch
].jnFlags
|= JNODE_PATCH
;
1518 pParse
->aNode
[iPatch
].u
.pPatch
= &pPatch
[i
+1];
1525 ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1526 ** object that is the result of running the RFC 7396 MergePatch() algorithm
1527 ** on the two arguments.
1529 static void jsonPatchFunc(
1530 sqlite3_context
*ctx
,
1532 sqlite3_value
**argv
1534 JsonParse x
; /* The JSON that is being patched */
1535 JsonParse y
; /* The patch */
1536 JsonNode
*pResult
; /* The result of the merge */
1539 if( jsonParse(&x
, ctx
, (const char*)sqlite3_value_text(argv
[0])) ) return;
1540 if( jsonParse(&y
, ctx
, (const char*)sqlite3_value_text(argv
[1])) ){
1544 pResult
= jsonMergePatch(&x
, 0, y
.aNode
);
1545 assert( pResult
!=0 || x
.oom
);
1547 jsonReturnJson(pResult
, ctx
, 0);
1549 sqlite3_result_error_nomem(ctx
);
1557 ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1558 ** object that contains all name/value given in arguments. Or if any name
1559 ** is not a string or if any value is a BLOB, throw an error.
1561 static void jsonObjectFunc(
1562 sqlite3_context
*ctx
,
1564 sqlite3_value
**argv
1572 sqlite3_result_error(ctx
, "json_object() requires an even number "
1573 "of arguments", -1);
1577 jsonAppendChar(&jx
, '{');
1578 for(i
=0; i
<argc
; i
+=2){
1579 if( sqlite3_value_type(argv
[i
])!=SQLITE_TEXT
){
1580 sqlite3_result_error(ctx
, "json_object() labels must be TEXT", -1);
1584 jsonAppendSeparator(&jx
);
1585 z
= (const char*)sqlite3_value_text(argv
[i
]);
1586 n
= (u32
)sqlite3_value_bytes(argv
[i
]);
1587 jsonAppendString(&jx
, z
, n
);
1588 jsonAppendChar(&jx
, ':');
1589 jsonAppendValue(&jx
, argv
[i
+1]);
1591 jsonAppendChar(&jx
, '}');
1593 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
1598 ** json_remove(JSON, PATH, ...)
1600 ** Remove the named elements from JSON and return the result. malformed
1601 ** JSON or PATH arguments result in an error.
1603 static void jsonRemoveFunc(
1604 sqlite3_context
*ctx
,
1606 sqlite3_value
**argv
1608 JsonParse x
; /* The parse */
1613 if( argc
<1 ) return;
1614 if( jsonParse(&x
, ctx
, (const char*)sqlite3_value_text(argv
[0])) ) return;
1616 for(i
=1; i
<(u32
)argc
; i
++){
1617 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
1618 if( zPath
==0 ) goto remove_done
;
1619 pNode
= jsonLookup(&x
, zPath
, 0, ctx
);
1620 if( x
.nErr
) goto remove_done
;
1621 if( pNode
) pNode
->jnFlags
|= JNODE_REMOVE
;
1623 if( (x
.aNode
[0].jnFlags
& JNODE_REMOVE
)==0 ){
1624 jsonReturnJson(x
.aNode
, ctx
, 0);
1631 ** json_replace(JSON, PATH, VALUE, ...)
1633 ** Replace the value at PATH with VALUE. If PATH does not already exist,
1634 ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
1636 static void jsonReplaceFunc(
1637 sqlite3_context
*ctx
,
1639 sqlite3_value
**argv
1641 JsonParse x
; /* The parse */
1646 if( argc
<1 ) return;
1648 jsonWrongNumArgs(ctx
, "replace");
1651 if( jsonParse(&x
, ctx
, (const char*)sqlite3_value_text(argv
[0])) ) return;
1653 for(i
=1; i
<(u32
)argc
; i
+=2){
1654 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
1655 pNode
= jsonLookup(&x
, zPath
, 0, ctx
);
1656 if( x
.nErr
) goto replace_err
;
1658 pNode
->jnFlags
|= (u8
)JNODE_REPLACE
;
1659 pNode
->u
.iReplace
= i
+ 1;
1662 if( x
.aNode
[0].jnFlags
& JNODE_REPLACE
){
1663 sqlite3_result_value(ctx
, argv
[x
.aNode
[0].u
.iReplace
]);
1665 jsonReturnJson(x
.aNode
, ctx
, argv
);
1672 ** json_set(JSON, PATH, VALUE, ...)
1674 ** Set the value at PATH to VALUE. Create the PATH if it does not already
1675 ** exist. Overwrite existing values that do exist.
1676 ** If JSON or PATH is malformed, throw an error.
1678 ** json_insert(JSON, PATH, VALUE, ...)
1680 ** Create PATH and initialize it to VALUE. If PATH already exists, this
1681 ** routine is a no-op. If JSON or PATH is malformed, throw an error.
1683 static void jsonSetFunc(
1684 sqlite3_context
*ctx
,
1686 sqlite3_value
**argv
1688 JsonParse x
; /* The parse */
1693 int bIsSet
= *(int*)sqlite3_user_data(ctx
);
1695 if( argc
<1 ) return;
1697 jsonWrongNumArgs(ctx
, bIsSet
? "set" : "insert");
1700 if( jsonParse(&x
, ctx
, (const char*)sqlite3_value_text(argv
[0])) ) return;
1702 for(i
=1; i
<(u32
)argc
; i
+=2){
1703 zPath
= (const char*)sqlite3_value_text(argv
[i
]);
1705 pNode
= jsonLookup(&x
, zPath
, &bApnd
, ctx
);
1707 sqlite3_result_error_nomem(ctx
);
1711 }else if( pNode
&& (bApnd
|| bIsSet
) ){
1712 pNode
->jnFlags
|= (u8
)JNODE_REPLACE
;
1713 pNode
->u
.iReplace
= i
+ 1;
1716 if( x
.aNode
[0].jnFlags
& JNODE_REPLACE
){
1717 sqlite3_result_value(ctx
, argv
[x
.aNode
[0].u
.iReplace
]);
1719 jsonReturnJson(x
.aNode
, ctx
, argv
);
1727 ** json_type(JSON, PATH)
1729 ** Return the top-level "type" of a JSON string. Throw an error if
1730 ** either the JSON or PATH inputs are not well-formed.
1732 static void jsonTypeFunc(
1733 sqlite3_context
*ctx
,
1735 sqlite3_value
**argv
1737 JsonParse x
; /* The parse */
1741 if( jsonParse(&x
, ctx
, (const char*)sqlite3_value_text(argv
[0])) ) return;
1744 zPath
= (const char*)sqlite3_value_text(argv
[1]);
1745 pNode
= jsonLookup(&x
, zPath
, 0, ctx
);
1750 sqlite3_result_text(ctx
, jsonType
[pNode
->eType
], -1, SQLITE_STATIC
);
1758 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1759 ** Return 0 otherwise.
1761 static void jsonValidFunc(
1762 sqlite3_context
*ctx
,
1764 sqlite3_value
**argv
1766 JsonParse x
; /* The parse */
1770 if( jsonParse(&x
, 0, (const char*)sqlite3_value_text(argv
[0]))==0 ){
1774 sqlite3_result_int(ctx
, rc
);
1778 /****************************************************************************
1779 ** Aggregate SQL function implementations
1780 ****************************************************************************/
1782 ** json_group_array(VALUE)
1784 ** Return a JSON array composed of all values in the aggregate.
1786 static void jsonArrayStep(
1787 sqlite3_context
*ctx
,
1789 sqlite3_value
**argv
1793 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, sizeof(*pStr
));
1795 if( pStr
->zBuf
==0 ){
1796 jsonInit(pStr
, ctx
);
1797 jsonAppendChar(pStr
, '[');
1799 jsonAppendChar(pStr
, ',');
1802 jsonAppendValue(pStr
, argv
[0]);
1805 static void jsonArrayFinal(sqlite3_context
*ctx
){
1807 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, 0);
1810 jsonAppendChar(pStr
, ']');
1812 if( pStr
->bErr
==1 ) sqlite3_result_error_nomem(ctx
);
1813 assert( pStr
->bStatic
);
1815 sqlite3_result_text(ctx
, pStr
->zBuf
, pStr
->nUsed
,
1816 pStr
->bStatic
? SQLITE_TRANSIENT
: sqlite3_free
);
1820 sqlite3_result_text(ctx
, "[]", 2, SQLITE_STATIC
);
1822 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
1826 ** json_group_obj(NAME,VALUE)
1828 ** Return a JSON object composed of all names and values in the aggregate.
1830 static void jsonObjectStep(
1831 sqlite3_context
*ctx
,
1833 sqlite3_value
**argv
1839 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, sizeof(*pStr
));
1841 if( pStr
->zBuf
==0 ){
1842 jsonInit(pStr
, ctx
);
1843 jsonAppendChar(pStr
, '{');
1845 jsonAppendChar(pStr
, ',');
1848 z
= (const char*)sqlite3_value_text(argv
[0]);
1849 n
= (u32
)sqlite3_value_bytes(argv
[0]);
1850 jsonAppendString(pStr
, z
, n
);
1851 jsonAppendChar(pStr
, ':');
1852 jsonAppendValue(pStr
, argv
[1]);
1855 static void jsonObjectFinal(sqlite3_context
*ctx
){
1857 pStr
= (JsonString
*)sqlite3_aggregate_context(ctx
, 0);
1859 jsonAppendChar(pStr
, '}');
1861 if( pStr
->bErr
==1 ) sqlite3_result_error_nomem(ctx
);
1862 assert( pStr
->bStatic
);
1864 sqlite3_result_text(ctx
, pStr
->zBuf
, pStr
->nUsed
,
1865 pStr
->bStatic
? SQLITE_TRANSIENT
: sqlite3_free
);
1869 sqlite3_result_text(ctx
, "{}", 2, SQLITE_STATIC
);
1871 sqlite3_result_subtype(ctx
, JSON_SUBTYPE
);
1875 #ifndef SQLITE_OMIT_VIRTUALTABLE
1876 /****************************************************************************
1877 ** The json_each virtual table
1878 ****************************************************************************/
1879 typedef struct JsonEachCursor JsonEachCursor
;
1880 struct JsonEachCursor
{
1881 sqlite3_vtab_cursor base
; /* Base class - must be first */
1882 u32 iRowid
; /* The rowid */
1883 u32 iBegin
; /* The first node of the scan */
1884 u32 i
; /* Index in sParse.aNode[] of current row */
1885 u32 iEnd
; /* EOF when i equals or exceeds this value */
1886 u8 eType
; /* Type of top-level element */
1887 u8 bRecursive
; /* True for json_tree(). False for json_each() */
1888 char *zJson
; /* Input JSON */
1889 char *zRoot
; /* Path by which to filter zJson */
1890 JsonParse sParse
; /* Parse of the input JSON */
1893 /* Constructor for the json_each virtual table */
1894 static int jsonEachConnect(
1897 int argc
, const char *const*argv
,
1898 sqlite3_vtab
**ppVtab
,
1904 /* Column numbers */
1906 #define JEACH_VALUE 1
1907 #define JEACH_TYPE 2
1908 #define JEACH_ATOM 3
1910 #define JEACH_PARENT 5
1911 #define JEACH_FULLKEY 6
1912 #define JEACH_PATH 7
1913 #define JEACH_JSON 8
1914 #define JEACH_ROOT 9
1916 UNUSED_PARAM(pzErr
);
1920 rc
= sqlite3_declare_vtab(db
,
1921 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1922 "json HIDDEN,root HIDDEN)");
1923 if( rc
==SQLITE_OK
){
1924 pNew
= *ppVtab
= sqlite3_malloc( sizeof(*pNew
) );
1925 if( pNew
==0 ) return SQLITE_NOMEM
;
1926 memset(pNew
, 0, sizeof(*pNew
));
1931 /* destructor for json_each virtual table */
1932 static int jsonEachDisconnect(sqlite3_vtab
*pVtab
){
1933 sqlite3_free(pVtab
);
1937 /* constructor for a JsonEachCursor object for json_each(). */
1938 static int jsonEachOpenEach(sqlite3_vtab
*p
, sqlite3_vtab_cursor
**ppCursor
){
1939 JsonEachCursor
*pCur
;
1942 pCur
= sqlite3_malloc( sizeof(*pCur
) );
1943 if( pCur
==0 ) return SQLITE_NOMEM
;
1944 memset(pCur
, 0, sizeof(*pCur
));
1945 *ppCursor
= &pCur
->base
;
1949 /* constructor for a JsonEachCursor object for json_tree(). */
1950 static int jsonEachOpenTree(sqlite3_vtab
*p
, sqlite3_vtab_cursor
**ppCursor
){
1951 int rc
= jsonEachOpenEach(p
, ppCursor
);
1952 if( rc
==SQLITE_OK
){
1953 JsonEachCursor
*pCur
= (JsonEachCursor
*)*ppCursor
;
1954 pCur
->bRecursive
= 1;
1959 /* Reset a JsonEachCursor back to its original state. Free any memory
1961 static void jsonEachCursorReset(JsonEachCursor
*p
){
1962 sqlite3_free(p
->zJson
);
1963 sqlite3_free(p
->zRoot
);
1964 jsonParseReset(&p
->sParse
);
1973 /* Destructor for a jsonEachCursor object */
1974 static int jsonEachClose(sqlite3_vtab_cursor
*cur
){
1975 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
1976 jsonEachCursorReset(p
);
1981 /* Return TRUE if the jsonEachCursor object has been advanced off the end
1982 ** of the JSON object */
1983 static int jsonEachEof(sqlite3_vtab_cursor
*cur
){
1984 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
1985 return p
->i
>= p
->iEnd
;
1988 /* Advance the cursor to the next element for json_tree() */
1989 static int jsonEachNext(sqlite3_vtab_cursor
*cur
){
1990 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
1991 if( p
->bRecursive
){
1992 if( p
->sParse
.aNode
[p
->i
].jnFlags
& JNODE_LABEL
) p
->i
++;
1996 u32 iUp
= p
->sParse
.aUp
[p
->i
];
1997 JsonNode
*pUp
= &p
->sParse
.aNode
[iUp
];
1998 p
->eType
= pUp
->eType
;
1999 if( pUp
->eType
==JSON_ARRAY
){
2010 p
->i
+= jsonNodeSize(&p
->sParse
.aNode
[p
->i
]);
2015 p
->i
+= 1 + jsonNodeSize(&p
->sParse
.aNode
[p
->i
+1]);
2028 /* Append the name of the path for element i to pStr
2030 static void jsonEachComputePath(
2031 JsonEachCursor
*p
, /* The cursor */
2032 JsonString
*pStr
, /* Write the path here */
2033 u32 i
/* Path to this element */
2035 JsonNode
*pNode
, *pUp
;
2038 jsonAppendChar(pStr
, '$');
2041 iUp
= p
->sParse
.aUp
[i
];
2042 jsonEachComputePath(p
, pStr
, iUp
);
2043 pNode
= &p
->sParse
.aNode
[i
];
2044 pUp
= &p
->sParse
.aNode
[iUp
];
2045 if( pUp
->eType
==JSON_ARRAY
){
2046 jsonPrintf(30, pStr
, "[%d]", pUp
->u
.iKey
);
2048 assert( pUp
->eType
==JSON_OBJECT
);
2049 if( (pNode
->jnFlags
& JNODE_LABEL
)==0 ) pNode
--;
2050 assert( pNode
->eType
==JSON_STRING
);
2051 assert( pNode
->jnFlags
& JNODE_LABEL
);
2052 jsonPrintf(pNode
->n
+1, pStr
, ".%.*s", pNode
->n
-2, pNode
->u
.zJContent
+1);
2056 /* Return the value of a column */
2057 static int jsonEachColumn(
2058 sqlite3_vtab_cursor
*cur
, /* The cursor */
2059 sqlite3_context
*ctx
, /* First argument to sqlite3_result_...() */
2060 int i
/* Which column to return */
2062 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
2063 JsonNode
*pThis
= &p
->sParse
.aNode
[p
->i
];
2066 if( p
->i
==0 ) break;
2067 if( p
->eType
==JSON_OBJECT
){
2068 jsonReturn(pThis
, ctx
, 0);
2069 }else if( p
->eType
==JSON_ARRAY
){
2071 if( p
->bRecursive
){
2072 if( p
->iRowid
==0 ) break;
2073 iKey
= p
->sParse
.aNode
[p
->sParse
.aUp
[p
->i
]].u
.iKey
;
2077 sqlite3_result_int64(ctx
, (sqlite3_int64
)iKey
);
2082 if( pThis
->jnFlags
& JNODE_LABEL
) pThis
++;
2083 jsonReturn(pThis
, ctx
, 0);
2087 if( pThis
->jnFlags
& JNODE_LABEL
) pThis
++;
2088 sqlite3_result_text(ctx
, jsonType
[pThis
->eType
], -1, SQLITE_STATIC
);
2092 if( pThis
->jnFlags
& JNODE_LABEL
) pThis
++;
2093 if( pThis
->eType
>=JSON_ARRAY
) break;
2094 jsonReturn(pThis
, ctx
, 0);
2098 sqlite3_result_int64(ctx
,
2099 (sqlite3_int64
)p
->i
+ ((pThis
->jnFlags
& JNODE_LABEL
)!=0));
2102 case JEACH_PARENT
: {
2103 if( p
->i
>p
->iBegin
&& p
->bRecursive
){
2104 sqlite3_result_int64(ctx
, (sqlite3_int64
)p
->sParse
.aUp
[p
->i
]);
2108 case JEACH_FULLKEY
: {
2111 if( p
->bRecursive
){
2112 jsonEachComputePath(p
, &x
, p
->i
);
2115 jsonAppendRaw(&x
, p
->zRoot
, (int)strlen(p
->zRoot
));
2117 jsonAppendChar(&x
, '$');
2119 if( p
->eType
==JSON_ARRAY
){
2120 jsonPrintf(30, &x
, "[%d]", p
->iRowid
);
2122 jsonPrintf(pThis
->n
, &x
, ".%.*s", pThis
->n
-2, pThis
->u
.zJContent
+1);
2129 if( p
->bRecursive
){
2132 jsonEachComputePath(p
, &x
, p
->sParse
.aUp
[p
->i
]);
2136 /* For json_each() path and root are the same so fall through
2137 ** into the root case */
2140 const char *zRoot
= p
->zRoot
;
2141 if( zRoot
==0 ) zRoot
= "$";
2142 sqlite3_result_text(ctx
, zRoot
, -1, SQLITE_STATIC
);
2146 assert( i
==JEACH_JSON
);
2147 sqlite3_result_text(ctx
, p
->sParse
.zJson
, -1, SQLITE_STATIC
);
2154 /* Return the current rowid value */
2155 static int jsonEachRowid(sqlite3_vtab_cursor
*cur
, sqlite_int64
*pRowid
){
2156 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
2157 *pRowid
= p
->iRowid
;
2161 /* The query strategy is to look for an equality constraint on the json
2162 ** column. Without such a constraint, the table cannot operate. idxNum is
2163 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
2166 static int jsonEachBestIndex(
2168 sqlite3_index_info
*pIdxInfo
2173 const struct sqlite3_index_constraint
*pConstraint
;
2176 pConstraint
= pIdxInfo
->aConstraint
;
2177 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++, pConstraint
++){
2178 if( pConstraint
->usable
==0 ) continue;
2179 if( pConstraint
->op
!=SQLITE_INDEX_CONSTRAINT_EQ
) continue;
2180 switch( pConstraint
->iColumn
){
2181 case JEACH_JSON
: jsonIdx
= i
; break;
2182 case JEACH_ROOT
: rootIdx
= i
; break;
2183 default: /* no-op */ break;
2187 pIdxInfo
->idxNum
= 0;
2188 pIdxInfo
->estimatedCost
= 1e99
;
2190 pIdxInfo
->estimatedCost
= 1.0;
2191 pIdxInfo
->aConstraintUsage
[jsonIdx
].argvIndex
= 1;
2192 pIdxInfo
->aConstraintUsage
[jsonIdx
].omit
= 1;
2194 pIdxInfo
->idxNum
= 1;
2196 pIdxInfo
->aConstraintUsage
[rootIdx
].argvIndex
= 2;
2197 pIdxInfo
->aConstraintUsage
[rootIdx
].omit
= 1;
2198 pIdxInfo
->idxNum
= 3;
2204 /* Start a search on a new JSON string */
2205 static int jsonEachFilter(
2206 sqlite3_vtab_cursor
*cur
,
2207 int idxNum
, const char *idxStr
,
2208 int argc
, sqlite3_value
**argv
2210 JsonEachCursor
*p
= (JsonEachCursor
*)cur
;
2212 const char *zRoot
= 0;
2215 UNUSED_PARAM(idxStr
);
2217 jsonEachCursorReset(p
);
2218 if( idxNum
==0 ) return SQLITE_OK
;
2219 z
= (const char*)sqlite3_value_text(argv
[0]);
2220 if( z
==0 ) return SQLITE_OK
;
2221 n
= sqlite3_value_bytes(argv
[0]);
2222 p
->zJson
= sqlite3_malloc64( n
+1 );
2223 if( p
->zJson
==0 ) return SQLITE_NOMEM
;
2224 memcpy(p
->zJson
, z
, (size_t)n
+1);
2225 if( jsonParse(&p
->sParse
, 0, p
->zJson
) ){
2226 int rc
= SQLITE_NOMEM
;
2227 if( p
->sParse
.oom
==0 ){
2228 sqlite3_free(cur
->pVtab
->zErrMsg
);
2229 cur
->pVtab
->zErrMsg
= sqlite3_mprintf("malformed JSON");
2230 if( cur
->pVtab
->zErrMsg
) rc
= SQLITE_ERROR
;
2232 jsonEachCursorReset(p
);
2234 }else if( p
->bRecursive
&& jsonParseFindParents(&p
->sParse
) ){
2235 jsonEachCursorReset(p
);
2236 return SQLITE_NOMEM
;
2238 JsonNode
*pNode
= 0;
2240 const char *zErr
= 0;
2241 zRoot
= (const char*)sqlite3_value_text(argv
[1]);
2242 if( zRoot
==0 ) return SQLITE_OK
;
2243 n
= sqlite3_value_bytes(argv
[1]);
2244 p
->zRoot
= sqlite3_malloc64( n
+1 );
2245 if( p
->zRoot
==0 ) return SQLITE_NOMEM
;
2246 memcpy(p
->zRoot
, zRoot
, (size_t)n
+1);
2247 if( zRoot
[0]!='$' ){
2250 pNode
= jsonLookupStep(&p
->sParse
, 0, p
->zRoot
+1, 0, &zErr
);
2253 sqlite3_free(cur
->pVtab
->zErrMsg
);
2254 cur
->pVtab
->zErrMsg
= jsonPathSyntaxError(zErr
);
2255 jsonEachCursorReset(p
);
2256 return cur
->pVtab
->zErrMsg
? SQLITE_ERROR
: SQLITE_NOMEM
;
2257 }else if( pNode
==0 ){
2261 pNode
= p
->sParse
.aNode
;
2263 p
->iBegin
= p
->i
= (int)(pNode
- p
->sParse
.aNode
);
2264 p
->eType
= pNode
->eType
;
2265 if( p
->eType
>=JSON_ARRAY
){
2267 p
->iEnd
= p
->i
+ pNode
->n
+ 1;
2268 if( p
->bRecursive
){
2269 p
->eType
= p
->sParse
.aNode
[p
->sParse
.aUp
[p
->i
]].eType
;
2270 if( p
->i
>0 && (p
->sParse
.aNode
[p
->i
-1].jnFlags
& JNODE_LABEL
)!=0 ){
2283 /* The methods of the json_each virtual table */
2284 static sqlite3_module jsonEachModule
= {
2287 jsonEachConnect
, /* xConnect */
2288 jsonEachBestIndex
, /* xBestIndex */
2289 jsonEachDisconnect
, /* xDisconnect */
2291 jsonEachOpenEach
, /* xOpen - open a cursor */
2292 jsonEachClose
, /* xClose - close a cursor */
2293 jsonEachFilter
, /* xFilter - configure scan constraints */
2294 jsonEachNext
, /* xNext - advance a cursor */
2295 jsonEachEof
, /* xEof - check for end of scan */
2296 jsonEachColumn
, /* xColumn - read data */
2297 jsonEachRowid
, /* xRowid - read data */
2303 0, /* xFindMethod */
2310 /* The methods of the json_tree virtual table. */
2311 static sqlite3_module jsonTreeModule
= {
2314 jsonEachConnect
, /* xConnect */
2315 jsonEachBestIndex
, /* xBestIndex */
2316 jsonEachDisconnect
, /* xDisconnect */
2318 jsonEachOpenTree
, /* xOpen - open a cursor */
2319 jsonEachClose
, /* xClose - close a cursor */
2320 jsonEachFilter
, /* xFilter - configure scan constraints */
2321 jsonEachNext
, /* xNext - advance a cursor */
2322 jsonEachEof
, /* xEof - check for end of scan */
2323 jsonEachColumn
, /* xColumn - read data */
2324 jsonEachRowid
, /* xRowid - read data */
2330 0, /* xFindMethod */
2336 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2338 /****************************************************************************
2339 ** The following routines are the only publically visible identifiers in this
2340 ** file. Call the following routines in order to register the various SQL
2341 ** functions and the virtual table implemented by this file.
2342 ****************************************************************************/
2344 int sqlite3Json1Init(sqlite3
*db
){
2347 static const struct {
2351 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**);
2353 { "json", 1, 0, jsonRemoveFunc
},
2354 { "json_array", -1, 0, jsonArrayFunc
},
2355 { "json_array_length", 1, 0, jsonArrayLengthFunc
},
2356 { "json_array_length", 2, 0, jsonArrayLengthFunc
},
2357 { "json_extract", -1, 0, jsonExtractFunc
},
2358 { "json_insert", -1, 0, jsonSetFunc
},
2359 { "json_object", -1, 0, jsonObjectFunc
},
2360 { "json_patch", 2, 0, jsonPatchFunc
},
2361 { "json_quote", 1, 0, jsonQuoteFunc
},
2362 { "json_remove", -1, 0, jsonRemoveFunc
},
2363 { "json_replace", -1, 0, jsonReplaceFunc
},
2364 { "json_set", -1, 1, jsonSetFunc
},
2365 { "json_type", 1, 0, jsonTypeFunc
},
2366 { "json_type", 2, 0, jsonTypeFunc
},
2367 { "json_valid", 1, 0, jsonValidFunc
},
2370 /* DEBUG and TESTING functions */
2371 { "json_parse", 1, 0, jsonParseFunc
},
2372 { "json_test1", 1, 0, jsonTest1Func
},
2375 static const struct {
2378 void (*xStep
)(sqlite3_context
*,int,sqlite3_value
**);
2379 void (*xFinal
)(sqlite3_context
*);
2381 { "json_group_array", 1, jsonArrayStep
, jsonArrayFinal
},
2382 { "json_group_object", 2, jsonObjectStep
, jsonObjectFinal
},
2384 #ifndef SQLITE_OMIT_VIRTUALTABLE
2385 static const struct {
2387 sqlite3_module
*pModule
;
2389 { "json_each", &jsonEachModule
},
2390 { "json_tree", &jsonTreeModule
},
2393 for(i
=0; i
<sizeof(aFunc
)/sizeof(aFunc
[0]) && rc
==SQLITE_OK
; i
++){
2394 rc
= sqlite3_create_function(db
, aFunc
[i
].zName
, aFunc
[i
].nArg
,
2395 SQLITE_UTF8
| SQLITE_DETERMINISTIC
,
2396 (void*)&aFunc
[i
].flag
,
2397 aFunc
[i
].xFunc
, 0, 0);
2399 for(i
=0; i
<sizeof(aAgg
)/sizeof(aAgg
[0]) && rc
==SQLITE_OK
; i
++){
2400 rc
= sqlite3_create_function(db
, aAgg
[i
].zName
, aAgg
[i
].nArg
,
2401 SQLITE_UTF8
| SQLITE_DETERMINISTIC
, 0,
2402 0, aAgg
[i
].xStep
, aAgg
[i
].xFinal
);
2404 #ifndef SQLITE_OMIT_VIRTUALTABLE
2405 for(i
=0; i
<sizeof(aMod
)/sizeof(aMod
[0]) && rc
==SQLITE_OK
; i
++){
2406 rc
= sqlite3_create_module(db
, aMod
[i
].zName
, aMod
[i
].pModule
, 0);
2415 __declspec(dllexport
)
2417 int sqlite3_json_init(
2420 const sqlite3_api_routines
*pApi
2422 SQLITE_EXTENSION_INIT2(pApi
);
2423 (void)pzErrMsg
; /* Unused parameter */
2424 return sqlite3Json1Init(db
);
2427 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */