xref: /sqlite-3.40.0/src/json.c (revision 9dbf96bd)
1 /*
2 ** 2015-08-12
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
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.
10 **
11 ******************************************************************************
12 **
13 ** This SQLite JSON functions.
14 **
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.
17 **
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.)
23 */
24 #ifndef SQLITE_OMIT_JSON
25 #include "sqliteInt.h"
26 
27 /*
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).
31 */
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,
41   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 };
50 #define fast_isspace(x) (jsonIsSpace[(unsigned char)x])
51 
52 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_COVERAGE_TEST)
53 #  define VVA(X)
54 #else
55 #  define VVA(X) X
56 #endif
57 
58 /* Objects */
59 typedef struct JsonString JsonString;
60 typedef struct JsonNode JsonNode;
61 typedef struct JsonParse JsonParse;
62 
63 /* An instance of this object represents a JSON string
64 ** under construction.  Really, this is a generic string accumulator
65 ** that can be and is used to create strings other than JSON.
66 */
67 struct JsonString {
68   sqlite3_context *pCtx;   /* Function context - put error messages here */
69   char *zBuf;              /* Append JSON content here */
70   u64 nAlloc;              /* Bytes of storage available in zBuf[] */
71   u64 nUsed;               /* Bytes of zBuf[] currently used */
72   u8 bStatic;              /* True if zBuf is static space */
73   u8 bErr;                 /* True if an error has been encountered */
74   char zSpace[100];        /* Initial static space */
75 };
76 
77 /* JSON type values
78 */
79 #define JSON_NULL     0
80 #define JSON_TRUE     1
81 #define JSON_FALSE    2
82 #define JSON_INT      3
83 #define JSON_REAL     4
84 #define JSON_STRING   5
85 #define JSON_ARRAY    6
86 #define JSON_OBJECT   7
87 
88 /* The "subtype" set for JSON values */
89 #define JSON_SUBTYPE  74    /* Ascii for "J" */
90 
91 /*
92 ** Names of the various JSON types:
93 */
94 static const char * const jsonType[] = {
95   "null", "true", "false", "integer", "real", "text", "array", "object"
96 };
97 
98 /* Bit values for the JsonNode.jnFlag field
99 */
100 #define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
101 #define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
102 #define JNODE_REMOVE  0x04         /* Do not output */
103 #define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
104 #define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
105 #define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
106 #define JNODE_LABEL   0x40         /* Is a label of an object */
107 
108 
109 /* A single node of parsed JSON
110 */
111 struct JsonNode {
112   u8 eType;              /* One of the JSON_ type values */
113   u8 jnFlags;            /* JNODE flags */
114   u8 eU;                 /* Which union element to use */
115   u32 n;                 /* Bytes of content, or number of sub-nodes */
116   union {
117     const char *zJContent; /* 1: Content for INT, REAL, and STRING */
118     u32 iAppend;           /* 2: More terms for ARRAY and OBJECT */
119     u32 iKey;              /* 3: Key for ARRAY objects in json_tree() */
120     u32 iReplace;          /* 4: Replacement content for JNODE_REPLACE */
121     JsonNode *pPatch;      /* 5: Node chain of patch for JNODE_PATCH */
122   } u;
123 };
124 
125 /* A completely parsed JSON string
126 */
127 struct JsonParse {
128   u32 nNode;         /* Number of slots of aNode[] used */
129   u32 nAlloc;        /* Number of slots of aNode[] allocated */
130   JsonNode *aNode;   /* Array of nodes containing the parse */
131   const char *zJson; /* Original JSON string */
132   u32 *aUp;          /* Index of parent of each node */
133   u8 oom;            /* Set to true if out of memory */
134   u8 nErr;           /* Number of errors seen */
135   u16 iDepth;        /* Nesting depth */
136   int nJson;         /* Length of the zJson string in bytes */
137   u32 iHold;         /* Replace cache line with the lowest iHold value */
138 };
139 
140 /*
141 ** Maximum nesting depth of JSON for this implementation.
142 **
143 ** This limit is needed to avoid a stack overflow in the recursive
144 ** descent parser.  A depth of 2000 is far deeper than any sane JSON
145 ** should go.
146 */
147 #define JSON_MAX_DEPTH  2000
148 
149 /**************************************************************************
150 ** Utility routines for dealing with JsonString objects
151 **************************************************************************/
152 
153 /* Set the JsonString object to an empty string
154 */
155 static void jsonZero(JsonString *p){
156   p->zBuf = p->zSpace;
157   p->nAlloc = sizeof(p->zSpace);
158   p->nUsed = 0;
159   p->bStatic = 1;
160 }
161 
162 /* Initialize the JsonString object
163 */
164 static void jsonInit(JsonString *p, sqlite3_context *pCtx){
165   p->pCtx = pCtx;
166   p->bErr = 0;
167   jsonZero(p);
168 }
169 
170 
171 /* Free all allocated memory and reset the JsonString object back to its
172 ** initial state.
173 */
174 static void jsonReset(JsonString *p){
175   if( !p->bStatic ) sqlite3_free(p->zBuf);
176   jsonZero(p);
177 }
178 
179 
180 /* Report an out-of-memory (OOM) condition
181 */
182 static void jsonOom(JsonString *p){
183   p->bErr = 1;
184   sqlite3_result_error_nomem(p->pCtx);
185   jsonReset(p);
186 }
187 
188 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
189 ** Return zero on success.  Return non-zero on an OOM error
190 */
191 static int jsonGrow(JsonString *p, u32 N){
192   u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
193   char *zNew;
194   if( p->bStatic ){
195     if( p->bErr ) return 1;
196     zNew = sqlite3_malloc64(nTotal);
197     if( zNew==0 ){
198       jsonOom(p);
199       return SQLITE_NOMEM;
200     }
201     memcpy(zNew, p->zBuf, (size_t)p->nUsed);
202     p->zBuf = zNew;
203     p->bStatic = 0;
204   }else{
205     zNew = sqlite3_realloc64(p->zBuf, nTotal);
206     if( zNew==0 ){
207       jsonOom(p);
208       return SQLITE_NOMEM;
209     }
210     p->zBuf = zNew;
211   }
212   p->nAlloc = nTotal;
213   return SQLITE_OK;
214 }
215 
216 /* Append N bytes from zIn onto the end of the JsonString string.
217 */
218 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
219   if( N==0 ) return;
220   if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
221   memcpy(p->zBuf+p->nUsed, zIn, N);
222   p->nUsed += N;
223 }
224 
225 /* Append formatted text (not to exceed N bytes) to the JsonString.
226 */
227 static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
228   va_list ap;
229   if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
230   va_start(ap, zFormat);
231   sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
232   va_end(ap);
233   p->nUsed += (int)strlen(p->zBuf+p->nUsed);
234 }
235 
236 /* Append a single character
237 */
238 static void jsonAppendChar(JsonString *p, char c){
239   if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
240   p->zBuf[p->nUsed++] = c;
241 }
242 
243 /* Append a comma separator to the output buffer, if the previous
244 ** character is not '[' or '{'.
245 */
246 static void jsonAppendSeparator(JsonString *p){
247   char c;
248   if( p->nUsed==0 ) return;
249   c = p->zBuf[p->nUsed-1];
250   if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
251 }
252 
253 /* Append the N-byte string in zIn to the end of the JsonString string
254 ** under construction.  Enclose the string in "..." and escape
255 ** any double-quotes or backslash characters contained within the
256 ** string.
257 */
258 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
259   u32 i;
260   if( zIn==0 || ((N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0) ) return;
261   p->zBuf[p->nUsed++] = '"';
262   for(i=0; i<N; i++){
263     unsigned char c = ((unsigned const char*)zIn)[i];
264     if( c=='"' || c=='\\' ){
265       json_simple_escape:
266       if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
267       p->zBuf[p->nUsed++] = '\\';
268     }else if( c<=0x1f ){
269       static const char aSpecial[] = {
270          0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
271          0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
272       };
273       assert( sizeof(aSpecial)==32 );
274       assert( aSpecial['\b']=='b' );
275       assert( aSpecial['\f']=='f' );
276       assert( aSpecial['\n']=='n' );
277       assert( aSpecial['\r']=='r' );
278       assert( aSpecial['\t']=='t' );
279       if( aSpecial[c] ){
280         c = aSpecial[c];
281         goto json_simple_escape;
282       }
283       if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
284       p->zBuf[p->nUsed++] = '\\';
285       p->zBuf[p->nUsed++] = 'u';
286       p->zBuf[p->nUsed++] = '0';
287       p->zBuf[p->nUsed++] = '0';
288       p->zBuf[p->nUsed++] = '0' + (c>>4);
289       c = "0123456789abcdef"[c&0xf];
290     }
291     p->zBuf[p->nUsed++] = c;
292   }
293   p->zBuf[p->nUsed++] = '"';
294   assert( p->nUsed<p->nAlloc );
295 }
296 
297 /*
298 ** Append a function parameter value to the JSON string under
299 ** construction.
300 */
301 static void jsonAppendValue(
302   JsonString *p,                 /* Append to this JSON string */
303   sqlite3_value *pValue          /* Value to append */
304 ){
305   switch( sqlite3_value_type(pValue) ){
306     case SQLITE_NULL: {
307       jsonAppendRaw(p, "null", 4);
308       break;
309     }
310     case SQLITE_INTEGER:
311     case SQLITE_FLOAT: {
312       const char *z = (const char*)sqlite3_value_text(pValue);
313       u32 n = (u32)sqlite3_value_bytes(pValue);
314       jsonAppendRaw(p, z, n);
315       break;
316     }
317     case SQLITE_TEXT: {
318       const char *z = (const char*)sqlite3_value_text(pValue);
319       u32 n = (u32)sqlite3_value_bytes(pValue);
320       if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
321         jsonAppendRaw(p, z, n);
322       }else{
323         jsonAppendString(p, z, n);
324       }
325       break;
326     }
327     default: {
328       if( p->bErr==0 ){
329         sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
330         p->bErr = 2;
331         jsonReset(p);
332       }
333       break;
334     }
335   }
336 }
337 
338 
339 /* Make the JSON in p the result of the SQL function.
340 */
341 static void jsonResult(JsonString *p){
342   if( p->bErr==0 ){
343     sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
344                           p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
345                           SQLITE_UTF8);
346     jsonZero(p);
347   }
348   assert( p->bStatic );
349 }
350 
351 /**************************************************************************
352 ** Utility routines for dealing with JsonNode and JsonParse objects
353 **************************************************************************/
354 
355 /*
356 ** Return the number of consecutive JsonNode slots need to represent
357 ** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
358 ** OBJECT types, the number might be larger.
359 **
360 ** Appended elements are not counted.  The value returned is the number
361 ** by which the JsonNode counter should increment in order to go to the
362 ** next peer value.
363 */
364 static u32 jsonNodeSize(JsonNode *pNode){
365   return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
366 }
367 
368 /*
369 ** Reclaim all memory allocated by a JsonParse object.  But do not
370 ** delete the JsonParse object itself.
371 */
372 static void jsonParseReset(JsonParse *pParse){
373   sqlite3_free(pParse->aNode);
374   pParse->aNode = 0;
375   pParse->nNode = 0;
376   pParse->nAlloc = 0;
377   sqlite3_free(pParse->aUp);
378   pParse->aUp = 0;
379 }
380 
381 /*
382 ** Free a JsonParse object that was obtained from sqlite3_malloc().
383 */
384 static void jsonParseFree(JsonParse *pParse){
385   jsonParseReset(pParse);
386   sqlite3_free(pParse);
387 }
388 
389 /*
390 ** Convert the JsonNode pNode into a pure JSON string and
391 ** append to pOut.  Subsubstructure is also included.  Return
392 ** the number of JsonNode objects that are encoded.
393 */
394 static void jsonRenderNode(
395   JsonNode *pNode,               /* The node to render */
396   JsonString *pOut,              /* Write JSON here */
397   sqlite3_value **aReplace       /* Replacement values */
398 ){
399   assert( pNode!=0 );
400   if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
401     if( (pNode->jnFlags & JNODE_REPLACE)!=0 && ALWAYS(aReplace!=0) ){
402       assert( pNode->eU==4 );
403       jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
404       return;
405     }
406     assert( pNode->eU==5 );
407     pNode = pNode->u.pPatch;
408   }
409   switch( pNode->eType ){
410     default: {
411       assert( pNode->eType==JSON_NULL );
412       jsonAppendRaw(pOut, "null", 4);
413       break;
414     }
415     case JSON_TRUE: {
416       jsonAppendRaw(pOut, "true", 4);
417       break;
418     }
419     case JSON_FALSE: {
420       jsonAppendRaw(pOut, "false", 5);
421       break;
422     }
423     case JSON_STRING: {
424       if( pNode->jnFlags & JNODE_RAW ){
425         assert( pNode->eU==1 );
426         jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
427         break;
428       }
429       /* no break */ deliberate_fall_through
430     }
431     case JSON_REAL:
432     case JSON_INT: {
433       assert( pNode->eU==1 );
434       jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
435       break;
436     }
437     case JSON_ARRAY: {
438       u32 j = 1;
439       jsonAppendChar(pOut, '[');
440       for(;;){
441         while( j<=pNode->n ){
442           if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
443             jsonAppendSeparator(pOut);
444             jsonRenderNode(&pNode[j], pOut, aReplace);
445           }
446           j += jsonNodeSize(&pNode[j]);
447         }
448         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
449         assert( pNode->eU==2 );
450         pNode = &pNode[pNode->u.iAppend];
451         j = 1;
452       }
453       jsonAppendChar(pOut, ']');
454       break;
455     }
456     case JSON_OBJECT: {
457       u32 j = 1;
458       jsonAppendChar(pOut, '{');
459       for(;;){
460         while( j<=pNode->n ){
461           if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
462             jsonAppendSeparator(pOut);
463             jsonRenderNode(&pNode[j], pOut, aReplace);
464             jsonAppendChar(pOut, ':');
465             jsonRenderNode(&pNode[j+1], pOut, aReplace);
466           }
467           j += 1 + jsonNodeSize(&pNode[j+1]);
468         }
469         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
470         assert( pNode->eU==2 );
471         pNode = &pNode[pNode->u.iAppend];
472         j = 1;
473       }
474       jsonAppendChar(pOut, '}');
475       break;
476     }
477   }
478 }
479 
480 /*
481 ** Return a JsonNode and all its descendents as a JSON string.
482 */
483 static void jsonReturnJson(
484   JsonNode *pNode,            /* Node to return */
485   sqlite3_context *pCtx,      /* Return value for this function */
486   sqlite3_value **aReplace    /* Array of replacement values */
487 ){
488   JsonString s;
489   jsonInit(&s, pCtx);
490   jsonRenderNode(pNode, &s, aReplace);
491   jsonResult(&s);
492   sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
493 }
494 
495 /*
496 ** Translate a single byte of Hex into an integer.
497 ** This routine only works if h really is a valid hexadecimal
498 ** character:  0..9a..fA..F
499 */
500 static u8 jsonHexToInt(int h){
501   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
502 #ifdef SQLITE_EBCDIC
503   h += 9*(1&~(h>>4));
504 #else
505   h += 9*(1&(h>>6));
506 #endif
507   return (u8)(h & 0xf);
508 }
509 
510 /*
511 ** Convert a 4-byte hex string into an integer
512 */
513 static u32 jsonHexToInt4(const char *z){
514   u32 v;
515   assert( sqlite3Isxdigit(z[0]) );
516   assert( sqlite3Isxdigit(z[1]) );
517   assert( sqlite3Isxdigit(z[2]) );
518   assert( sqlite3Isxdigit(z[3]) );
519   v = (jsonHexToInt(z[0])<<12)
520     + (jsonHexToInt(z[1])<<8)
521     + (jsonHexToInt(z[2])<<4)
522     + jsonHexToInt(z[3]);
523   return v;
524 }
525 
526 /*
527 ** Make the JsonNode the return value of the function.
528 */
529 static void jsonReturn(
530   JsonNode *pNode,            /* Node to return */
531   sqlite3_context *pCtx,      /* Return value for this function */
532   sqlite3_value **aReplace    /* Array of replacement values */
533 ){
534   switch( pNode->eType ){
535     default: {
536       assert( pNode->eType==JSON_NULL );
537       sqlite3_result_null(pCtx);
538       break;
539     }
540     case JSON_TRUE: {
541       sqlite3_result_int(pCtx, 1);
542       break;
543     }
544     case JSON_FALSE: {
545       sqlite3_result_int(pCtx, 0);
546       break;
547     }
548     case JSON_INT: {
549       sqlite3_int64 i = 0;
550       const char *z;
551       assert( pNode->eU==1 );
552       z = pNode->u.zJContent;
553       if( z[0]=='-' ){ z++; }
554       while( z[0]>='0' && z[0]<='9' ){
555         unsigned v = *(z++) - '0';
556         if( i>=LARGEST_INT64/10 ){
557           if( i>LARGEST_INT64/10 ) goto int_as_real;
558           if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
559           if( v==9 ) goto int_as_real;
560           if( v==8 ){
561             if( pNode->u.zJContent[0]=='-' ){
562               sqlite3_result_int64(pCtx, SMALLEST_INT64);
563               goto int_done;
564             }else{
565               goto int_as_real;
566             }
567           }
568         }
569         i = i*10 + v;
570       }
571       if( pNode->u.zJContent[0]=='-' ){ i = -i; }
572       sqlite3_result_int64(pCtx, i);
573       int_done:
574       break;
575       int_as_real: ; /* no break */ deliberate_fall_through
576     }
577     case JSON_REAL: {
578       double r;
579 #ifdef SQLITE_AMALGAMATION
580       const char *z;
581       assert( pNode->eU==1 );
582       z = pNode->u.zJContent;
583       sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
584 #else
585       assert( pNode->eU==1 );
586       r = strtod(pNode->u.zJContent, 0);
587 #endif
588       sqlite3_result_double(pCtx, r);
589       break;
590     }
591     case JSON_STRING: {
592 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
593       ** json_insert() and json_replace() and those routines do not
594       ** call jsonReturn() */
595       if( pNode->jnFlags & JNODE_RAW ){
596         assert( pNode->eU==1 );
597         sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
598                             SQLITE_TRANSIENT);
599       }else
600 #endif
601       assert( (pNode->jnFlags & JNODE_RAW)==0 );
602       if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
603         /* JSON formatted without any backslash-escapes */
604         assert( pNode->eU==1 );
605         sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
606                             SQLITE_TRANSIENT);
607       }else{
608         /* Translate JSON formatted string into raw text */
609         u32 i;
610         u32 n = pNode->n;
611         const char *z;
612         char *zOut;
613         u32 j;
614         assert( pNode->eU==1 );
615         z = pNode->u.zJContent;
616         zOut = sqlite3_malloc( n+1 );
617         if( zOut==0 ){
618           sqlite3_result_error_nomem(pCtx);
619           break;
620         }
621         for(i=1, j=0; i<n-1; i++){
622           char c = z[i];
623           if( c!='\\' ){
624             zOut[j++] = c;
625           }else{
626             c = z[++i];
627             if( c=='u' ){
628               u32 v = jsonHexToInt4(z+i+1);
629               i += 4;
630               if( v==0 ) break;
631               if( v<=0x7f ){
632                 zOut[j++] = (char)v;
633               }else if( v<=0x7ff ){
634                 zOut[j++] = (char)(0xc0 | (v>>6));
635                 zOut[j++] = 0x80 | (v&0x3f);
636               }else{
637                 u32 vlo;
638                 if( (v&0xfc00)==0xd800
639                   && i<n-6
640                   && z[i+1]=='\\'
641                   && z[i+2]=='u'
642                   && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
643                 ){
644                   /* We have a surrogate pair */
645                   v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
646                   i += 6;
647                   zOut[j++] = 0xf0 | (v>>18);
648                   zOut[j++] = 0x80 | ((v>>12)&0x3f);
649                   zOut[j++] = 0x80 | ((v>>6)&0x3f);
650                   zOut[j++] = 0x80 | (v&0x3f);
651                 }else{
652                   zOut[j++] = 0xe0 | (v>>12);
653                   zOut[j++] = 0x80 | ((v>>6)&0x3f);
654                   zOut[j++] = 0x80 | (v&0x3f);
655                 }
656               }
657             }else{
658               if( c=='b' ){
659                 c = '\b';
660               }else if( c=='f' ){
661                 c = '\f';
662               }else if( c=='n' ){
663                 c = '\n';
664               }else if( c=='r' ){
665                 c = '\r';
666               }else if( c=='t' ){
667                 c = '\t';
668               }
669               zOut[j++] = c;
670             }
671           }
672         }
673         zOut[j] = 0;
674         sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
675       }
676       break;
677     }
678     case JSON_ARRAY:
679     case JSON_OBJECT: {
680       jsonReturnJson(pNode, pCtx, aReplace);
681       break;
682     }
683   }
684 }
685 
686 /* Forward reference */
687 static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
688 
689 /*
690 ** A macro to hint to the compiler that a function should not be
691 ** inlined.
692 */
693 #if defined(__GNUC__)
694 #  define JSON_NOINLINE  __attribute__((noinline))
695 #elif defined(_MSC_VER) && _MSC_VER>=1310
696 #  define JSON_NOINLINE  __declspec(noinline)
697 #else
698 #  define JSON_NOINLINE
699 #endif
700 
701 
702 static JSON_NOINLINE int jsonParseAddNodeExpand(
703   JsonParse *pParse,        /* Append the node to this object */
704   u32 eType,                /* Node type */
705   u32 n,                    /* Content size or sub-node count */
706   const char *zContent      /* Content */
707 ){
708   u32 nNew;
709   JsonNode *pNew;
710   assert( pParse->nNode>=pParse->nAlloc );
711   if( pParse->oom ) return -1;
712   nNew = pParse->nAlloc*2 + 10;
713   pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
714   if( pNew==0 ){
715     pParse->oom = 1;
716     return -1;
717   }
718   pParse->nAlloc = nNew;
719   pParse->aNode = pNew;
720   assert( pParse->nNode<pParse->nAlloc );
721   return jsonParseAddNode(pParse, eType, n, zContent);
722 }
723 
724 /*
725 ** Create a new JsonNode instance based on the arguments and append that
726 ** instance to the JsonParse.  Return the index in pParse->aNode[] of the
727 ** new node, or -1 if a memory allocation fails.
728 */
729 static int jsonParseAddNode(
730   JsonParse *pParse,        /* Append the node to this object */
731   u32 eType,                /* Node type */
732   u32 n,                    /* Content size or sub-node count */
733   const char *zContent      /* Content */
734 ){
735   JsonNode *p;
736   if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
737     return jsonParseAddNodeExpand(pParse, eType, n, zContent);
738   }
739   p = &pParse->aNode[pParse->nNode];
740   p->eType = (u8)eType;
741   p->jnFlags = 0;
742   VVA( p->eU = zContent ? 1 : 0 );
743   p->n = n;
744   p->u.zJContent = zContent;
745   return pParse->nNode++;
746 }
747 
748 /*
749 ** Return true if z[] begins with 4 (or more) hexadecimal digits
750 */
751 static int jsonIs4Hex(const char *z){
752   int i;
753   for(i=0; i<4; i++) if( !sqlite3Isxdigit(z[i]) ) return 0;
754   return 1;
755 }
756 
757 /*
758 ** Parse a single JSON value which begins at pParse->zJson[i].  Return the
759 ** index of the first character past the end of the value parsed.
760 **
761 ** Return negative for a syntax error.  Special cases:  return -2 if the
762 ** first non-whitespace character is '}' and return -3 if the first
763 ** non-whitespace character is ']'.
764 */
765 static int jsonParseValue(JsonParse *pParse, u32 i){
766   char c;
767   u32 j;
768   int iThis;
769   int x;
770   JsonNode *pNode;
771   const char *z = pParse->zJson;
772   while( fast_isspace(z[i]) ){ i++; }
773   if( (c = z[i])=='{' ){
774     /* Parse object */
775     iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
776     if( iThis<0 ) return -1;
777     for(j=i+1;;j++){
778       while( fast_isspace(z[j]) ){ j++; }
779       if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
780       x = jsonParseValue(pParse, j);
781       if( x<0 ){
782         pParse->iDepth--;
783         if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
784         return -1;
785       }
786       if( pParse->oom ) return -1;
787       pNode = &pParse->aNode[pParse->nNode-1];
788       if( pNode->eType!=JSON_STRING ) return -1;
789       pNode->jnFlags |= JNODE_LABEL;
790       j = x;
791       while( fast_isspace(z[j]) ){ j++; }
792       if( z[j]!=':' ) return -1;
793       j++;
794       x = jsonParseValue(pParse, j);
795       pParse->iDepth--;
796       if( x<0 ) return -1;
797       j = x;
798       while( fast_isspace(z[j]) ){ j++; }
799       c = z[j];
800       if( c==',' ) continue;
801       if( c!='}' ) return -1;
802       break;
803     }
804     pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
805     return j+1;
806   }else if( c=='[' ){
807     /* Parse array */
808     iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
809     if( iThis<0 ) return -1;
810     memset(&pParse->aNode[iThis].u, 0, sizeof(pParse->aNode[iThis].u));
811     for(j=i+1;;j++){
812       while( fast_isspace(z[j]) ){ j++; }
813       if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
814       x = jsonParseValue(pParse, j);
815       pParse->iDepth--;
816       if( x<0 ){
817         if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
818         return -1;
819       }
820       j = x;
821       while( fast_isspace(z[j]) ){ j++; }
822       c = z[j];
823       if( c==',' ) continue;
824       if( c!=']' ) return -1;
825       break;
826     }
827     pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
828     return j+1;
829   }else if( c=='"' ){
830     /* Parse string */
831     u8 jnFlags = 0;
832     j = i+1;
833     for(;;){
834       c = z[j];
835       if( (c & ~0x1f)==0 ){
836         /* Control characters are not allowed in strings */
837         return -1;
838       }
839       if( c=='\\' ){
840         c = z[++j];
841         if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
842            || c=='n' || c=='r' || c=='t'
843            || (c=='u' && jsonIs4Hex(z+j+1)) ){
844           jnFlags = JNODE_ESCAPE;
845         }else{
846           return -1;
847         }
848       }else if( c=='"' ){
849         break;
850       }
851       j++;
852     }
853     jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
854     if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
855     return j+1;
856   }else if( c=='n'
857          && strncmp(z+i,"null",4)==0
858          && !sqlite3Isalnum(z[i+4]) ){
859     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
860     return i+4;
861   }else if( c=='t'
862          && strncmp(z+i,"true",4)==0
863          && !sqlite3Isalnum(z[i+4]) ){
864     jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
865     return i+4;
866   }else if( c=='f'
867          && strncmp(z+i,"false",5)==0
868          && !sqlite3Isalnum(z[i+5]) ){
869     jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
870     return i+5;
871   }else if( c=='-' || (c>='0' && c<='9') ){
872     /* Parse number */
873     u8 seenDP = 0;
874     u8 seenE = 0;
875     assert( '-' < '0' );
876     if( c<='0' ){
877       j = c=='-' ? i+1 : i;
878       if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
879     }
880     j = i+1;
881     for(;; j++){
882       c = z[j];
883       if( c>='0' && c<='9' ) continue;
884       if( c=='.' ){
885         if( z[j-1]=='-' ) return -1;
886         if( seenDP ) return -1;
887         seenDP = 1;
888         continue;
889       }
890       if( c=='e' || c=='E' ){
891         if( z[j-1]<'0' ) return -1;
892         if( seenE ) return -1;
893         seenDP = seenE = 1;
894         c = z[j+1];
895         if( c=='+' || c=='-' ){
896           j++;
897           c = z[j+1];
898         }
899         if( c<'0' || c>'9' ) return -1;
900         continue;
901       }
902       break;
903     }
904     if( z[j-1]<'0' ) return -1;
905     jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
906                         j - i, &z[i]);
907     return j;
908   }else if( c=='}' ){
909     return -2;  /* End of {...} */
910   }else if( c==']' ){
911     return -3;  /* End of [...] */
912   }else if( c==0 ){
913     return 0;   /* End of file */
914   }else{
915     return -1;  /* Syntax error */
916   }
917 }
918 
919 /*
920 ** Parse a complete JSON string.  Return 0 on success or non-zero if there
921 ** are any errors.  If an error occurs, free all memory associated with
922 ** pParse.
923 **
924 ** pParse is uninitialized when this routine is called.
925 */
926 static int jsonParse(
927   JsonParse *pParse,           /* Initialize and fill this JsonParse object */
928   sqlite3_context *pCtx,       /* Report errors here */
929   const char *zJson            /* Input JSON text to be parsed */
930 ){
931   int i;
932   memset(pParse, 0, sizeof(*pParse));
933   if( zJson==0 ) return 1;
934   pParse->zJson = zJson;
935   i = jsonParseValue(pParse, 0);
936   if( pParse->oom ) i = -1;
937   if( i>0 ){
938     assert( pParse->iDepth==0 );
939     while( fast_isspace(zJson[i]) ) i++;
940     if( zJson[i] ) i = -1;
941   }
942   if( i<=0 ){
943     if( pCtx!=0 ){
944       if( pParse->oom ){
945         sqlite3_result_error_nomem(pCtx);
946       }else{
947         sqlite3_result_error(pCtx, "malformed JSON", -1);
948       }
949     }
950     jsonParseReset(pParse);
951     return 1;
952   }
953   return 0;
954 }
955 
956 /* Mark node i of pParse as being a child of iParent.  Call recursively
957 ** to fill in all the descendants of node i.
958 */
959 static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
960   JsonNode *pNode = &pParse->aNode[i];
961   u32 j;
962   pParse->aUp[i] = iParent;
963   switch( pNode->eType ){
964     case JSON_ARRAY: {
965       for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
966         jsonParseFillInParentage(pParse, i+j, i);
967       }
968       break;
969     }
970     case JSON_OBJECT: {
971       for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
972         pParse->aUp[i+j] = i;
973         jsonParseFillInParentage(pParse, i+j+1, i);
974       }
975       break;
976     }
977     default: {
978       break;
979     }
980   }
981 }
982 
983 /*
984 ** Compute the parentage of all nodes in a completed parse.
985 */
986 static int jsonParseFindParents(JsonParse *pParse){
987   u32 *aUp;
988   assert( pParse->aUp==0 );
989   aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
990   if( aUp==0 ){
991     pParse->oom = 1;
992     return SQLITE_NOMEM;
993   }
994   jsonParseFillInParentage(pParse, 0, 0);
995   return SQLITE_OK;
996 }
997 
998 /*
999 ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
1000 */
1001 #define JSON_CACHE_ID  (-429938)  /* First cache entry */
1002 #define JSON_CACHE_SZ  4          /* Max number of cache entries */
1003 
1004 /*
1005 ** Obtain a complete parse of the JSON found in the first argument
1006 ** of the argv array.  Use the sqlite3_get_auxdata() cache for this
1007 ** parse if it is available.  If the cache is not available or if it
1008 ** is no longer valid, parse the JSON again and return the new parse,
1009 ** and also register the new parse so that it will be available for
1010 ** future sqlite3_get_auxdata() calls.
1011 */
1012 static JsonParse *jsonParseCached(
1013   sqlite3_context *pCtx,
1014   sqlite3_value **argv,
1015   sqlite3_context *pErrCtx
1016 ){
1017   const char *zJson = (const char*)sqlite3_value_text(argv[0]);
1018   int nJson = sqlite3_value_bytes(argv[0]);
1019   JsonParse *p;
1020   JsonParse *pMatch = 0;
1021   int iKey;
1022   int iMinKey = 0;
1023   u32 iMinHold = 0xffffffff;
1024   u32 iMaxHold = 0;
1025   if( zJson==0 ) return 0;
1026   for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
1027     p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
1028     if( p==0 ){
1029       iMinKey = iKey;
1030       break;
1031     }
1032     if( pMatch==0
1033      && p->nJson==nJson
1034      && memcmp(p->zJson,zJson,nJson)==0
1035     ){
1036       p->nErr = 0;
1037       pMatch = p;
1038     }else if( p->iHold<iMinHold ){
1039       iMinHold = p->iHold;
1040       iMinKey = iKey;
1041     }
1042     if( p->iHold>iMaxHold ){
1043       iMaxHold = p->iHold;
1044     }
1045   }
1046   if( pMatch ){
1047     pMatch->nErr = 0;
1048     pMatch->iHold = iMaxHold+1;
1049     return pMatch;
1050   }
1051   p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
1052   if( p==0 ){
1053     sqlite3_result_error_nomem(pCtx);
1054     return 0;
1055   }
1056   memset(p, 0, sizeof(*p));
1057   p->zJson = (char*)&p[1];
1058   memcpy((char*)p->zJson, zJson, nJson+1);
1059   if( jsonParse(p, pErrCtx, p->zJson) ){
1060     sqlite3_free(p);
1061     return 0;
1062   }
1063   p->nJson = nJson;
1064   p->iHold = iMaxHold+1;
1065   sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
1066                       (void(*)(void*))jsonParseFree);
1067   return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
1068 }
1069 
1070 /*
1071 ** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
1072 ** a match.
1073 */
1074 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
1075   assert( pNode->eU==1 );
1076   if( pNode->jnFlags & JNODE_RAW ){
1077     if( pNode->n!=nKey ) return 0;
1078     return strncmp(pNode->u.zJContent, zKey, nKey)==0;
1079   }else{
1080     if( pNode->n!=nKey+2 ) return 0;
1081     return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
1082   }
1083 }
1084 
1085 /* forward declaration */
1086 static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
1087 
1088 /*
1089 ** Search along zPath to find the node specified.  Return a pointer
1090 ** to that node, or NULL if zPath is malformed or if there is no such
1091 ** node.
1092 **
1093 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
1094 ** possible to do so and if no existing node corresponds to zPath.  If
1095 ** new nodes are appended *pApnd is set to 1.
1096 */
1097 static JsonNode *jsonLookupStep(
1098   JsonParse *pParse,      /* The JSON to search */
1099   u32 iRoot,              /* Begin the search at this node */
1100   const char *zPath,      /* The path to search */
1101   int *pApnd,             /* Append nodes to complete path if not NULL */
1102   const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
1103 ){
1104   u32 i, j, nKey;
1105   const char *zKey;
1106   JsonNode *pRoot = &pParse->aNode[iRoot];
1107   if( zPath[0]==0 ) return pRoot;
1108   if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
1109   if( zPath[0]=='.' ){
1110     if( pRoot->eType!=JSON_OBJECT ) return 0;
1111     zPath++;
1112     if( zPath[0]=='"' ){
1113       zKey = zPath + 1;
1114       for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1115       nKey = i-1;
1116       if( zPath[i] ){
1117         i++;
1118       }else{
1119         *pzErr = zPath;
1120         return 0;
1121       }
1122     }else{
1123       zKey = zPath;
1124       for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1125       nKey = i;
1126     }
1127     if( nKey==0 ){
1128       *pzErr = zPath;
1129       return 0;
1130     }
1131     j = 1;
1132     for(;;){
1133       while( j<=pRoot->n ){
1134         if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
1135           return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
1136         }
1137         j++;
1138         j += jsonNodeSize(&pRoot[j]);
1139       }
1140       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1141       assert( pRoot->eU==2 );
1142       iRoot += pRoot->u.iAppend;
1143       pRoot = &pParse->aNode[iRoot];
1144       j = 1;
1145     }
1146     if( pApnd ){
1147       u32 iStart, iLabel;
1148       JsonNode *pNode;
1149       iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1150       iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1151       zPath += i;
1152       pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
1153       if( pParse->oom ) return 0;
1154       if( pNode ){
1155         pRoot = &pParse->aNode[iRoot];
1156         assert( pRoot->eU==0 );
1157         pRoot->u.iAppend = iStart - iRoot;
1158         pRoot->jnFlags |= JNODE_APPEND;
1159         VVA( pRoot->eU = 2 );
1160         pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1161       }
1162       return pNode;
1163     }
1164   }else if( zPath[0]=='[' ){
1165     i = 0;
1166     j = 1;
1167     while( sqlite3Isdigit(zPath[j]) ){
1168       i = i*10 + zPath[j] - '0';
1169       j++;
1170     }
1171     if( j<2 || zPath[j]!=']' ){
1172       if( zPath[1]=='#' ){
1173         JsonNode *pBase = pRoot;
1174         int iBase = iRoot;
1175         if( pRoot->eType!=JSON_ARRAY ) return 0;
1176         for(;;){
1177           while( j<=pBase->n ){
1178             if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
1179             j += jsonNodeSize(&pBase[j]);
1180           }
1181           if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
1182           assert( pBase->eU==2 );
1183           iBase += pBase->u.iAppend;
1184           pBase = &pParse->aNode[iBase];
1185           j = 1;
1186         }
1187         j = 2;
1188         if( zPath[2]=='-' && sqlite3Isdigit(zPath[3]) ){
1189           unsigned int x = 0;
1190           j = 3;
1191           do{
1192             x = x*10 + zPath[j] - '0';
1193             j++;
1194           }while( sqlite3Isdigit(zPath[j]) );
1195           if( x>i ) return 0;
1196           i -= x;
1197         }
1198         if( zPath[j]!=']' ){
1199           *pzErr = zPath;
1200           return 0;
1201         }
1202       }else{
1203         *pzErr = zPath;
1204         return 0;
1205       }
1206     }
1207     if( pRoot->eType!=JSON_ARRAY ) return 0;
1208     zPath += j + 1;
1209     j = 1;
1210     for(;;){
1211       while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1212         if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
1213         j += jsonNodeSize(&pRoot[j]);
1214       }
1215       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1216       assert( pRoot->eU==2 );
1217       iRoot += pRoot->u.iAppend;
1218       pRoot = &pParse->aNode[iRoot];
1219       j = 1;
1220     }
1221     if( j<=pRoot->n ){
1222       return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
1223     }
1224     if( i==0 && pApnd ){
1225       u32 iStart;
1226       JsonNode *pNode;
1227       iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
1228       pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
1229       if( pParse->oom ) return 0;
1230       if( pNode ){
1231         pRoot = &pParse->aNode[iRoot];
1232         assert( pRoot->eU==0 );
1233         pRoot->u.iAppend = iStart - iRoot;
1234         pRoot->jnFlags |= JNODE_APPEND;
1235         VVA( pRoot->eU = 2 );
1236       }
1237       return pNode;
1238     }
1239   }else{
1240     *pzErr = zPath;
1241   }
1242   return 0;
1243 }
1244 
1245 /*
1246 ** Append content to pParse that will complete zPath.  Return a pointer
1247 ** to the inserted node, or return NULL if the append fails.
1248 */
1249 static JsonNode *jsonLookupAppend(
1250   JsonParse *pParse,     /* Append content to the JSON parse */
1251   const char *zPath,     /* Description of content to append */
1252   int *pApnd,            /* Set this flag to 1 */
1253   const char **pzErr     /* Make this point to any syntax error */
1254 ){
1255   *pApnd = 1;
1256   if( zPath[0]==0 ){
1257     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1258     return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1259   }
1260   if( zPath[0]=='.' ){
1261     jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1262   }else if( strncmp(zPath,"[0]",3)==0 ){
1263     jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1264   }else{
1265     return 0;
1266   }
1267   if( pParse->oom ) return 0;
1268   return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
1269 }
1270 
1271 /*
1272 ** Return the text of a syntax error message on a JSON path.  Space is
1273 ** obtained from sqlite3_malloc().
1274 */
1275 static char *jsonPathSyntaxError(const char *zErr){
1276   return sqlite3_mprintf("JSON path error near '%q'", zErr);
1277 }
1278 
1279 /*
1280 ** Do a node lookup using zPath.  Return a pointer to the node on success.
1281 ** Return NULL if not found or if there is an error.
1282 **
1283 ** On an error, write an error message into pCtx and increment the
1284 ** pParse->nErr counter.
1285 **
1286 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1287 ** nodes are appended.
1288 */
1289 static JsonNode *jsonLookup(
1290   JsonParse *pParse,      /* The JSON to search */
1291   const char *zPath,      /* The path to search */
1292   int *pApnd,             /* Append nodes to complete path if not NULL */
1293   sqlite3_context *pCtx   /* Report errors here, if not NULL */
1294 ){
1295   const char *zErr = 0;
1296   JsonNode *pNode = 0;
1297   char *zMsg;
1298 
1299   if( zPath==0 ) return 0;
1300   if( zPath[0]!='$' ){
1301     zErr = zPath;
1302     goto lookup_err;
1303   }
1304   zPath++;
1305   pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
1306   if( zErr==0 ) return pNode;
1307 
1308 lookup_err:
1309   pParse->nErr++;
1310   assert( zErr!=0 && pCtx!=0 );
1311   zMsg = jsonPathSyntaxError(zErr);
1312   if( zMsg ){
1313     sqlite3_result_error(pCtx, zMsg, -1);
1314     sqlite3_free(zMsg);
1315   }else{
1316     sqlite3_result_error_nomem(pCtx);
1317   }
1318   return 0;
1319 }
1320 
1321 
1322 /*
1323 ** Report the wrong number of arguments for json_insert(), json_replace()
1324 ** or json_set().
1325 */
1326 static void jsonWrongNumArgs(
1327   sqlite3_context *pCtx,
1328   const char *zFuncName
1329 ){
1330   char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1331                                zFuncName);
1332   sqlite3_result_error(pCtx, zMsg, -1);
1333   sqlite3_free(zMsg);
1334 }
1335 
1336 /*
1337 ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1338 */
1339 static void jsonRemoveAllNulls(JsonNode *pNode){
1340   int i, n;
1341   assert( pNode->eType==JSON_OBJECT );
1342   n = pNode->n;
1343   for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1344     switch( pNode[i].eType ){
1345       case JSON_NULL:
1346         pNode[i].jnFlags |= JNODE_REMOVE;
1347         break;
1348       case JSON_OBJECT:
1349         jsonRemoveAllNulls(&pNode[i]);
1350         break;
1351     }
1352   }
1353 }
1354 
1355 
1356 /****************************************************************************
1357 ** SQL functions used for testing and debugging
1358 ****************************************************************************/
1359 
1360 #ifdef SQLITE_DEBUG
1361 /*
1362 ** The json_parse(JSON) function returns a string which describes
1363 ** a parse of the JSON provided.  Or it returns NULL if JSON is not
1364 ** well-formed.
1365 */
1366 static void jsonParseFunc(
1367   sqlite3_context *ctx,
1368   int argc,
1369   sqlite3_value **argv
1370 ){
1371   JsonString s;       /* Output string - not real JSON */
1372   JsonParse x;        /* The parse */
1373   u32 i;
1374 
1375   assert( argc==1 );
1376   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1377   jsonParseFindParents(&x);
1378   jsonInit(&s, ctx);
1379   for(i=0; i<x.nNode; i++){
1380     const char *zType;
1381     if( x.aNode[i].jnFlags & JNODE_LABEL ){
1382       assert( x.aNode[i].eType==JSON_STRING );
1383       zType = "label";
1384     }else{
1385       zType = jsonType[x.aNode[i].eType];
1386     }
1387     jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1388                i, zType, x.aNode[i].n, x.aUp[i]);
1389     assert( x.aNode[i].eU==0 || x.aNode[i].eU==1 );
1390     if( x.aNode[i].u.zJContent!=0 ){
1391       assert( x.aNode[i].eU==1 );
1392       jsonAppendRaw(&s, " ", 1);
1393       jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1394     }else{
1395       assert( x.aNode[i].eU==0 );
1396     }
1397     jsonAppendRaw(&s, "\n", 1);
1398   }
1399   jsonParseReset(&x);
1400   jsonResult(&s);
1401 }
1402 
1403 /*
1404 ** The json_test1(JSON) function return true (1) if the input is JSON
1405 ** text generated by another json function.  It returns (0) if the input
1406 ** is not known to be JSON.
1407 */
1408 static void jsonTest1Func(
1409   sqlite3_context *ctx,
1410   int argc,
1411   sqlite3_value **argv
1412 ){
1413   UNUSED_PARAMETER(argc);
1414   sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
1415 }
1416 #endif /* SQLITE_DEBUG */
1417 
1418 /****************************************************************************
1419 ** Scalar SQL function implementations
1420 ****************************************************************************/
1421 
1422 /*
1423 ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
1424 ** corresponding to the SQL value input.  Mostly this means putting
1425 ** double-quotes around strings and returning the unquoted string "null"
1426 ** when given a NULL input.
1427 */
1428 static void jsonQuoteFunc(
1429   sqlite3_context *ctx,
1430   int argc,
1431   sqlite3_value **argv
1432 ){
1433   JsonString jx;
1434   UNUSED_PARAMETER(argc);
1435 
1436   jsonInit(&jx, ctx);
1437   jsonAppendValue(&jx, argv[0]);
1438   jsonResult(&jx);
1439   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1440 }
1441 
1442 /*
1443 ** Implementation of the json_array(VALUE,...) function.  Return a JSON
1444 ** array that contains all values given in arguments.  Or if any argument
1445 ** is a BLOB, throw an error.
1446 */
1447 static void jsonArrayFunc(
1448   sqlite3_context *ctx,
1449   int argc,
1450   sqlite3_value **argv
1451 ){
1452   int i;
1453   JsonString jx;
1454 
1455   jsonInit(&jx, ctx);
1456   jsonAppendChar(&jx, '[');
1457   for(i=0; i<argc; i++){
1458     jsonAppendSeparator(&jx);
1459     jsonAppendValue(&jx, argv[i]);
1460   }
1461   jsonAppendChar(&jx, ']');
1462   jsonResult(&jx);
1463   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1464 }
1465 
1466 
1467 /*
1468 ** json_array_length(JSON)
1469 ** json_array_length(JSON, PATH)
1470 **
1471 ** Return the number of elements in the top-level JSON array.
1472 ** Return 0 if the input is not a well-formed JSON array.
1473 */
1474 static void jsonArrayLengthFunc(
1475   sqlite3_context *ctx,
1476   int argc,
1477   sqlite3_value **argv
1478 ){
1479   JsonParse *p;          /* The parse */
1480   sqlite3_int64 n = 0;
1481   u32 i;
1482   JsonNode *pNode;
1483 
1484   p = jsonParseCached(ctx, argv, ctx);
1485   if( p==0 ) return;
1486   assert( p->nNode );
1487   if( argc==2 ){
1488     const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1489     pNode = jsonLookup(p, zPath, 0, ctx);
1490   }else{
1491     pNode = p->aNode;
1492   }
1493   if( pNode==0 ){
1494     return;
1495   }
1496   if( pNode->eType==JSON_ARRAY ){
1497     assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1498     for(i=1; i<=pNode->n; n++){
1499       i += jsonNodeSize(&pNode[i]);
1500     }
1501   }
1502   sqlite3_result_int64(ctx, n);
1503 }
1504 
1505 /*
1506 ** json_extract(JSON, PATH, ...)
1507 **
1508 ** Return the element described by PATH.  Return NULL if there is no
1509 ** PATH element.  If there are multiple PATHs, then return a JSON array
1510 ** with the result from each path.  Throw an error if the JSON or any PATH
1511 ** is malformed.
1512 */
1513 static void jsonExtractFunc(
1514   sqlite3_context *ctx,
1515   int argc,
1516   sqlite3_value **argv
1517 ){
1518   JsonParse *p;          /* The parse */
1519   JsonNode *pNode;
1520   const char *zPath;
1521   JsonString jx;
1522   int i;
1523 
1524   if( argc<2 ) return;
1525   p = jsonParseCached(ctx, argv, ctx);
1526   if( p==0 ) return;
1527   jsonInit(&jx, ctx);
1528   jsonAppendChar(&jx, '[');
1529   for(i=1; i<argc; i++){
1530     zPath = (const char*)sqlite3_value_text(argv[i]);
1531     pNode = jsonLookup(p, zPath, 0, ctx);
1532     if( p->nErr ) break;
1533     if( argc>2 ){
1534       jsonAppendSeparator(&jx);
1535       if( pNode ){
1536         jsonRenderNode(pNode, &jx, 0);
1537       }else{
1538         jsonAppendRaw(&jx, "null", 4);
1539       }
1540     }else if( pNode ){
1541       jsonReturn(pNode, ctx, 0);
1542     }
1543   }
1544   if( argc>2 && i==argc ){
1545     jsonAppendChar(&jx, ']');
1546     jsonResult(&jx);
1547     sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1548   }
1549   jsonReset(&jx);
1550 }
1551 
1552 /* This is the RFC 7396 MergePatch algorithm.
1553 */
1554 static JsonNode *jsonMergePatch(
1555   JsonParse *pParse,   /* The JSON parser that contains the TARGET */
1556   u32 iTarget,         /* Node of the TARGET in pParse */
1557   JsonNode *pPatch     /* The PATCH */
1558 ){
1559   u32 i, j;
1560   u32 iRoot;
1561   JsonNode *pTarget;
1562   if( pPatch->eType!=JSON_OBJECT ){
1563     return pPatch;
1564   }
1565   assert( iTarget>=0 && iTarget<pParse->nNode );
1566   pTarget = &pParse->aNode[iTarget];
1567   assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1568   if( pTarget->eType!=JSON_OBJECT ){
1569     jsonRemoveAllNulls(pPatch);
1570     return pPatch;
1571   }
1572   iRoot = iTarget;
1573   for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
1574     u32 nKey;
1575     const char *zKey;
1576     assert( pPatch[i].eType==JSON_STRING );
1577     assert( pPatch[i].jnFlags & JNODE_LABEL );
1578     assert( pPatch[i].eU==1 );
1579     nKey = pPatch[i].n;
1580     zKey = pPatch[i].u.zJContent;
1581     assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
1582     for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1583       assert( pTarget[j].eType==JSON_STRING );
1584       assert( pTarget[j].jnFlags & JNODE_LABEL );
1585       assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
1586       if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1587         if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
1588         if( pPatch[i+1].eType==JSON_NULL ){
1589           pTarget[j+1].jnFlags |= JNODE_REMOVE;
1590         }else{
1591           JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
1592           if( pNew==0 ) return 0;
1593           pTarget = &pParse->aNode[iTarget];
1594           if( pNew!=&pTarget[j+1] ){
1595             assert( pTarget[j+1].eU==0
1596                  || pTarget[j+1].eU==1
1597                  || pTarget[j+1].eU==2 );
1598             testcase( pTarget[j+1].eU==1 );
1599             testcase( pTarget[j+1].eU==2 );
1600             VVA( pTarget[j+1].eU = 5 );
1601             pTarget[j+1].u.pPatch = pNew;
1602             pTarget[j+1].jnFlags |= JNODE_PATCH;
1603           }
1604         }
1605         break;
1606       }
1607     }
1608     if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
1609       int iStart, iPatch;
1610       iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1611       jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1612       iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1613       if( pParse->oom ) return 0;
1614       jsonRemoveAllNulls(pPatch);
1615       pTarget = &pParse->aNode[iTarget];
1616       assert( pParse->aNode[iRoot].eU==0 || pParse->aNode[iRoot].eU==2 );
1617       testcase( pParse->aNode[iRoot].eU==2 );
1618       pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1619       VVA( pParse->aNode[iRoot].eU = 2 );
1620       pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1621       iRoot = iStart;
1622       assert( pParse->aNode[iPatch].eU==0 );
1623       VVA( pParse->aNode[iPatch].eU = 5 );
1624       pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1625       pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1626     }
1627   }
1628   return pTarget;
1629 }
1630 
1631 /*
1632 ** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
1633 ** object that is the result of running the RFC 7396 MergePatch() algorithm
1634 ** on the two arguments.
1635 */
1636 static void jsonPatchFunc(
1637   sqlite3_context *ctx,
1638   int argc,
1639   sqlite3_value **argv
1640 ){
1641   JsonParse x;     /* The JSON that is being patched */
1642   JsonParse y;     /* The patch */
1643   JsonNode *pResult;   /* The result of the merge */
1644 
1645   UNUSED_PARAMETER(argc);
1646   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1647   if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1648     jsonParseReset(&x);
1649     return;
1650   }
1651   pResult = jsonMergePatch(&x, 0, y.aNode);
1652   assert( pResult!=0 || x.oom );
1653   if( pResult ){
1654     jsonReturnJson(pResult, ctx, 0);
1655   }else{
1656     sqlite3_result_error_nomem(ctx);
1657   }
1658   jsonParseReset(&x);
1659   jsonParseReset(&y);
1660 }
1661 
1662 
1663 /*
1664 ** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
1665 ** object that contains all name/value given in arguments.  Or if any name
1666 ** is not a string or if any value is a BLOB, throw an error.
1667 */
1668 static void jsonObjectFunc(
1669   sqlite3_context *ctx,
1670   int argc,
1671   sqlite3_value **argv
1672 ){
1673   int i;
1674   JsonString jx;
1675   const char *z;
1676   u32 n;
1677 
1678   if( argc&1 ){
1679     sqlite3_result_error(ctx, "json_object() requires an even number "
1680                                   "of arguments", -1);
1681     return;
1682   }
1683   jsonInit(&jx, ctx);
1684   jsonAppendChar(&jx, '{');
1685   for(i=0; i<argc; i+=2){
1686     if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
1687       sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
1688       jsonReset(&jx);
1689       return;
1690     }
1691     jsonAppendSeparator(&jx);
1692     z = (const char*)sqlite3_value_text(argv[i]);
1693     n = (u32)sqlite3_value_bytes(argv[i]);
1694     jsonAppendString(&jx, z, n);
1695     jsonAppendChar(&jx, ':');
1696     jsonAppendValue(&jx, argv[i+1]);
1697   }
1698   jsonAppendChar(&jx, '}');
1699   jsonResult(&jx);
1700   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1701 }
1702 
1703 
1704 /*
1705 ** json_remove(JSON, PATH, ...)
1706 **
1707 ** Remove the named elements from JSON and return the result.  malformed
1708 ** JSON or PATH arguments result in an error.
1709 */
1710 static void jsonRemoveFunc(
1711   sqlite3_context *ctx,
1712   int argc,
1713   sqlite3_value **argv
1714 ){
1715   JsonParse x;          /* The parse */
1716   JsonNode *pNode;
1717   const char *zPath;
1718   u32 i;
1719 
1720   if( argc<1 ) return;
1721   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1722   assert( x.nNode );
1723   for(i=1; i<(u32)argc; i++){
1724     zPath = (const char*)sqlite3_value_text(argv[i]);
1725     if( zPath==0 ) goto remove_done;
1726     pNode = jsonLookup(&x, zPath, 0, ctx);
1727     if( x.nErr ) goto remove_done;
1728     if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1729   }
1730   if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1731     jsonReturnJson(x.aNode, ctx, 0);
1732   }
1733 remove_done:
1734   jsonParseReset(&x);
1735 }
1736 
1737 /*
1738 ** json_replace(JSON, PATH, VALUE, ...)
1739 **
1740 ** Replace the value at PATH with VALUE.  If PATH does not already exist,
1741 ** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
1742 */
1743 static void jsonReplaceFunc(
1744   sqlite3_context *ctx,
1745   int argc,
1746   sqlite3_value **argv
1747 ){
1748   JsonParse x;          /* The parse */
1749   JsonNode *pNode;
1750   const char *zPath;
1751   u32 i;
1752 
1753   if( argc<1 ) return;
1754   if( (argc&1)==0 ) {
1755     jsonWrongNumArgs(ctx, "replace");
1756     return;
1757   }
1758   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1759   assert( x.nNode );
1760   for(i=1; i<(u32)argc; i+=2){
1761     zPath = (const char*)sqlite3_value_text(argv[i]);
1762     pNode = jsonLookup(&x, zPath, 0, ctx);
1763     if( x.nErr ) goto replace_err;
1764     if( pNode ){
1765       assert( pNode->eU==0 || pNode->eU==1 || pNode->eU==4 );
1766       testcase( pNode->eU!=0 && pNode->eU!=1 );
1767       pNode->jnFlags |= (u8)JNODE_REPLACE;
1768       VVA( pNode->eU =  4 );
1769       pNode->u.iReplace = i + 1;
1770     }
1771   }
1772   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1773     assert( x.aNode[0].eU==4 );
1774     sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
1775   }else{
1776     jsonReturnJson(x.aNode, ctx, argv);
1777   }
1778 replace_err:
1779   jsonParseReset(&x);
1780 }
1781 
1782 /*
1783 ** json_set(JSON, PATH, VALUE, ...)
1784 **
1785 ** Set the value at PATH to VALUE.  Create the PATH if it does not already
1786 ** exist.  Overwrite existing values that do exist.
1787 ** If JSON or PATH is malformed, throw an error.
1788 **
1789 ** json_insert(JSON, PATH, VALUE, ...)
1790 **
1791 ** Create PATH and initialize it to VALUE.  If PATH already exists, this
1792 ** routine is a no-op.  If JSON or PATH is malformed, throw an error.
1793 */
1794 static void jsonSetFunc(
1795   sqlite3_context *ctx,
1796   int argc,
1797   sqlite3_value **argv
1798 ){
1799   JsonParse x;          /* The parse */
1800   JsonNode *pNode;
1801   const char *zPath;
1802   u32 i;
1803   int bApnd;
1804   int bIsSet = sqlite3_user_data(ctx)!=0;
1805 
1806   if( argc<1 ) return;
1807   if( (argc&1)==0 ) {
1808     jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
1809     return;
1810   }
1811   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1812   assert( x.nNode );
1813   for(i=1; i<(u32)argc; i+=2){
1814     zPath = (const char*)sqlite3_value_text(argv[i]);
1815     bApnd = 0;
1816     pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1817     if( x.oom ){
1818       sqlite3_result_error_nomem(ctx);
1819       goto jsonSetDone;
1820     }else if( x.nErr ){
1821       goto jsonSetDone;
1822     }else if( pNode && (bApnd || bIsSet) ){
1823       testcase( pNode->eU!=0 && pNode->eU!=1 && pNode->eU!=4 );
1824       assert( pNode->eU!=3 || pNode->eU!=5 );
1825       VVA( pNode->eU = 4 );
1826       pNode->jnFlags |= (u8)JNODE_REPLACE;
1827       pNode->u.iReplace = i + 1;
1828     }
1829   }
1830   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1831     assert( x.aNode[0].eU==4 );
1832     sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
1833   }else{
1834     jsonReturnJson(x.aNode, ctx, argv);
1835   }
1836 jsonSetDone:
1837   jsonParseReset(&x);
1838 }
1839 
1840 /*
1841 ** json_type(JSON)
1842 ** json_type(JSON, PATH)
1843 **
1844 ** Return the top-level "type" of a JSON string.  Throw an error if
1845 ** either the JSON or PATH inputs are not well-formed.
1846 */
1847 static void jsonTypeFunc(
1848   sqlite3_context *ctx,
1849   int argc,
1850   sqlite3_value **argv
1851 ){
1852   JsonParse *p;          /* The parse */
1853   const char *zPath;
1854   JsonNode *pNode;
1855 
1856   p = jsonParseCached(ctx, argv, ctx);
1857   if( p==0 ) return;
1858   if( argc==2 ){
1859     zPath = (const char*)sqlite3_value_text(argv[1]);
1860     pNode = jsonLookup(p, zPath, 0, ctx);
1861   }else{
1862     pNode = p->aNode;
1863   }
1864   if( pNode ){
1865     sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
1866   }
1867 }
1868 
1869 /*
1870 ** json_valid(JSON)
1871 **
1872 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1873 ** Return 0 otherwise.
1874 */
1875 static void jsonValidFunc(
1876   sqlite3_context *ctx,
1877   int argc,
1878   sqlite3_value **argv
1879 ){
1880   JsonParse *p;          /* The parse */
1881   UNUSED_PARAMETER(argc);
1882   p = jsonParseCached(ctx, argv, 0);
1883   sqlite3_result_int(ctx, p!=0);
1884 }
1885 
1886 
1887 /****************************************************************************
1888 ** Aggregate SQL function implementations
1889 ****************************************************************************/
1890 /*
1891 ** json_group_array(VALUE)
1892 **
1893 ** Return a JSON array composed of all values in the aggregate.
1894 */
1895 static void jsonArrayStep(
1896   sqlite3_context *ctx,
1897   int argc,
1898   sqlite3_value **argv
1899 ){
1900   JsonString *pStr;
1901   UNUSED_PARAMETER(argc);
1902   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1903   if( pStr ){
1904     if( pStr->zBuf==0 ){
1905       jsonInit(pStr, ctx);
1906       jsonAppendChar(pStr, '[');
1907     }else if( pStr->nUsed>1 ){
1908       jsonAppendChar(pStr, ',');
1909     }
1910     pStr->pCtx = ctx;
1911     jsonAppendValue(pStr, argv[0]);
1912   }
1913 }
1914 static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
1915   JsonString *pStr;
1916   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1917   if( pStr ){
1918     pStr->pCtx = ctx;
1919     jsonAppendChar(pStr, ']');
1920     if( pStr->bErr ){
1921       if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
1922       assert( pStr->bStatic );
1923     }else if( isFinal ){
1924       sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
1925                           pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1926       pStr->bStatic = 1;
1927     }else{
1928       sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
1929       pStr->nUsed--;
1930     }
1931   }else{
1932     sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1933   }
1934   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1935 }
1936 static void jsonArrayValue(sqlite3_context *ctx){
1937   jsonArrayCompute(ctx, 0);
1938 }
1939 static void jsonArrayFinal(sqlite3_context *ctx){
1940   jsonArrayCompute(ctx, 1);
1941 }
1942 
1943 #ifndef SQLITE_OMIT_WINDOWFUNC
1944 /*
1945 ** This method works for both json_group_array() and json_group_object().
1946 ** It works by removing the first element of the group by searching forward
1947 ** to the first comma (",") that is not within a string and deleting all
1948 ** text through that comma.
1949 */
1950 static void jsonGroupInverse(
1951   sqlite3_context *ctx,
1952   int argc,
1953   sqlite3_value **argv
1954 ){
1955   unsigned int i;
1956   int inStr = 0;
1957   int nNest = 0;
1958   char *z;
1959   char c;
1960   JsonString *pStr;
1961   UNUSED_PARAMETER(argc);
1962   UNUSED_PARAMETER(argv);
1963   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1964 #ifdef NEVER
1965   /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1966   ** always have been called to initalize it */
1967   if( NEVER(!pStr) ) return;
1968 #endif
1969   z = pStr->zBuf;
1970   for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
1971     if( c=='"' ){
1972       inStr = !inStr;
1973     }else if( c=='\\' ){
1974       i++;
1975     }else if( !inStr ){
1976       if( c=='{' || c=='[' ) nNest++;
1977       if( c=='}' || c==']' ) nNest--;
1978     }
1979   }
1980   if( i<pStr->nUsed ){
1981     pStr->nUsed -= i;
1982     memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
1983     z[pStr->nUsed] = 0;
1984   }else{
1985     pStr->nUsed = 1;
1986   }
1987 }
1988 #else
1989 # define jsonGroupInverse 0
1990 #endif
1991 
1992 
1993 /*
1994 ** json_group_obj(NAME,VALUE)
1995 **
1996 ** Return a JSON object composed of all names and values in the aggregate.
1997 */
1998 static void jsonObjectStep(
1999   sqlite3_context *ctx,
2000   int argc,
2001   sqlite3_value **argv
2002 ){
2003   JsonString *pStr;
2004   const char *z;
2005   u32 n;
2006   UNUSED_PARAMETER(argc);
2007   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
2008   if( pStr ){
2009     if( pStr->zBuf==0 ){
2010       jsonInit(pStr, ctx);
2011       jsonAppendChar(pStr, '{');
2012     }else if( pStr->nUsed>1 ){
2013       jsonAppendChar(pStr, ',');
2014     }
2015     pStr->pCtx = ctx;
2016     z = (const char*)sqlite3_value_text(argv[0]);
2017     n = (u32)sqlite3_value_bytes(argv[0]);
2018     jsonAppendString(pStr, z, n);
2019     jsonAppendChar(pStr, ':');
2020     jsonAppendValue(pStr, argv[1]);
2021   }
2022 }
2023 static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
2024   JsonString *pStr;
2025   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
2026   if( pStr ){
2027     jsonAppendChar(pStr, '}');
2028     if( pStr->bErr ){
2029       if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
2030       assert( pStr->bStatic );
2031     }else if( isFinal ){
2032       sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
2033                           pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
2034       pStr->bStatic = 1;
2035     }else{
2036       sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
2037       pStr->nUsed--;
2038     }
2039   }else{
2040     sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
2041   }
2042   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
2043 }
2044 static void jsonObjectValue(sqlite3_context *ctx){
2045   jsonObjectCompute(ctx, 0);
2046 }
2047 static void jsonObjectFinal(sqlite3_context *ctx){
2048   jsonObjectCompute(ctx, 1);
2049 }
2050 
2051 
2052 
2053 #ifndef SQLITE_OMIT_VIRTUALTABLE
2054 /****************************************************************************
2055 ** The json_each virtual table
2056 ****************************************************************************/
2057 typedef struct JsonEachCursor JsonEachCursor;
2058 struct JsonEachCursor {
2059   sqlite3_vtab_cursor base;  /* Base class - must be first */
2060   u32 iRowid;                /* The rowid */
2061   u32 iBegin;                /* The first node of the scan */
2062   u32 i;                     /* Index in sParse.aNode[] of current row */
2063   u32 iEnd;                  /* EOF when i equals or exceeds this value */
2064   u8 eType;                  /* Type of top-level element */
2065   u8 bRecursive;             /* True for json_tree().  False for json_each() */
2066   char *zJson;               /* Input JSON */
2067   char *zRoot;               /* Path by which to filter zJson */
2068   JsonParse sParse;          /* Parse of the input JSON */
2069 };
2070 
2071 /* Constructor for the json_each virtual table */
2072 static int jsonEachConnect(
2073   sqlite3 *db,
2074   void *pAux,
2075   int argc, const char *const*argv,
2076   sqlite3_vtab **ppVtab,
2077   char **pzErr
2078 ){
2079   sqlite3_vtab *pNew;
2080   int rc;
2081 
2082 /* Column numbers */
2083 #define JEACH_KEY     0
2084 #define JEACH_VALUE   1
2085 #define JEACH_TYPE    2
2086 #define JEACH_ATOM    3
2087 #define JEACH_ID      4
2088 #define JEACH_PARENT  5
2089 #define JEACH_FULLKEY 6
2090 #define JEACH_PATH    7
2091 /* The xBestIndex method assumes that the JSON and ROOT columns are
2092 ** the last two columns in the table.  Should this ever changes, be
2093 ** sure to update the xBestIndex method. */
2094 #define JEACH_JSON    8
2095 #define JEACH_ROOT    9
2096 
2097   UNUSED_PARAMETER(pzErr);
2098   UNUSED_PARAMETER(argv);
2099   UNUSED_PARAMETER(argc);
2100   UNUSED_PARAMETER(pAux);
2101   rc = sqlite3_declare_vtab(db,
2102      "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2103                     "json HIDDEN,root HIDDEN)");
2104   if( rc==SQLITE_OK ){
2105     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2106     if( pNew==0 ) return SQLITE_NOMEM;
2107     memset(pNew, 0, sizeof(*pNew));
2108     sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
2109   }
2110   return rc;
2111 }
2112 
2113 /* destructor for json_each virtual table */
2114 static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2115   sqlite3_free(pVtab);
2116   return SQLITE_OK;
2117 }
2118 
2119 /* constructor for a JsonEachCursor object for json_each(). */
2120 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2121   JsonEachCursor *pCur;
2122 
2123   UNUSED_PARAMETER(p);
2124   pCur = sqlite3_malloc( sizeof(*pCur) );
2125   if( pCur==0 ) return SQLITE_NOMEM;
2126   memset(pCur, 0, sizeof(*pCur));
2127   *ppCursor = &pCur->base;
2128   return SQLITE_OK;
2129 }
2130 
2131 /* constructor for a JsonEachCursor object for json_tree(). */
2132 static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2133   int rc = jsonEachOpenEach(p, ppCursor);
2134   if( rc==SQLITE_OK ){
2135     JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2136     pCur->bRecursive = 1;
2137   }
2138   return rc;
2139 }
2140 
2141 /* Reset a JsonEachCursor back to its original state.  Free any memory
2142 ** held. */
2143 static void jsonEachCursorReset(JsonEachCursor *p){
2144   sqlite3_free(p->zJson);
2145   sqlite3_free(p->zRoot);
2146   jsonParseReset(&p->sParse);
2147   p->iRowid = 0;
2148   p->i = 0;
2149   p->iEnd = 0;
2150   p->eType = 0;
2151   p->zJson = 0;
2152   p->zRoot = 0;
2153 }
2154 
2155 /* Destructor for a jsonEachCursor object */
2156 static int jsonEachClose(sqlite3_vtab_cursor *cur){
2157   JsonEachCursor *p = (JsonEachCursor*)cur;
2158   jsonEachCursorReset(p);
2159   sqlite3_free(cur);
2160   return SQLITE_OK;
2161 }
2162 
2163 /* Return TRUE if the jsonEachCursor object has been advanced off the end
2164 ** of the JSON object */
2165 static int jsonEachEof(sqlite3_vtab_cursor *cur){
2166   JsonEachCursor *p = (JsonEachCursor*)cur;
2167   return p->i >= p->iEnd;
2168 }
2169 
2170 /* Advance the cursor to the next element for json_tree() */
2171 static int jsonEachNext(sqlite3_vtab_cursor *cur){
2172   JsonEachCursor *p = (JsonEachCursor*)cur;
2173   if( p->bRecursive ){
2174     if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2175     p->i++;
2176     p->iRowid++;
2177     if( p->i<p->iEnd ){
2178       u32 iUp = p->sParse.aUp[p->i];
2179       JsonNode *pUp = &p->sParse.aNode[iUp];
2180       p->eType = pUp->eType;
2181       if( pUp->eType==JSON_ARRAY ){
2182         assert( pUp->eU==0 || pUp->eU==3 );
2183         testcase( pUp->eU==3 );
2184         VVA( pUp->eU = 3 );
2185         if( iUp==p->i-1 ){
2186           pUp->u.iKey = 0;
2187         }else{
2188           pUp->u.iKey++;
2189         }
2190       }
2191     }
2192   }else{
2193     switch( p->eType ){
2194       case JSON_ARRAY: {
2195         p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2196         p->iRowid++;
2197         break;
2198       }
2199       case JSON_OBJECT: {
2200         p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2201         p->iRowid++;
2202         break;
2203       }
2204       default: {
2205         p->i = p->iEnd;
2206         break;
2207       }
2208     }
2209   }
2210   return SQLITE_OK;
2211 }
2212 
2213 /* Append the name of the path for element i to pStr
2214 */
2215 static void jsonEachComputePath(
2216   JsonEachCursor *p,       /* The cursor */
2217   JsonString *pStr,        /* Write the path here */
2218   u32 i                    /* Path to this element */
2219 ){
2220   JsonNode *pNode, *pUp;
2221   u32 iUp;
2222   if( i==0 ){
2223     jsonAppendChar(pStr, '$');
2224     return;
2225   }
2226   iUp = p->sParse.aUp[i];
2227   jsonEachComputePath(p, pStr, iUp);
2228   pNode = &p->sParse.aNode[i];
2229   pUp = &p->sParse.aNode[iUp];
2230   if( pUp->eType==JSON_ARRAY ){
2231     assert( pUp->eU==3 || (pUp->eU==0 && pUp->u.iKey==0) );
2232     testcase( pUp->eU==0 );
2233     jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2234   }else{
2235     assert( pUp->eType==JSON_OBJECT );
2236     if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
2237     assert( pNode->eType==JSON_STRING );
2238     assert( pNode->jnFlags & JNODE_LABEL );
2239     assert( pNode->eU==1 );
2240     jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2241   }
2242 }
2243 
2244 /* Return the value of a column */
2245 static int jsonEachColumn(
2246   sqlite3_vtab_cursor *cur,   /* The cursor */
2247   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
2248   int i                       /* Which column to return */
2249 ){
2250   JsonEachCursor *p = (JsonEachCursor*)cur;
2251   JsonNode *pThis = &p->sParse.aNode[p->i];
2252   switch( i ){
2253     case JEACH_KEY: {
2254       if( p->i==0 ) break;
2255       if( p->eType==JSON_OBJECT ){
2256         jsonReturn(pThis, ctx, 0);
2257       }else if( p->eType==JSON_ARRAY ){
2258         u32 iKey;
2259         if( p->bRecursive ){
2260           if( p->iRowid==0 ) break;
2261           assert( p->sParse.aNode[p->sParse.aUp[p->i]].eU==3 );
2262           iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
2263         }else{
2264           iKey = p->iRowid;
2265         }
2266         sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
2267       }
2268       break;
2269     }
2270     case JEACH_VALUE: {
2271       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
2272       jsonReturn(pThis, ctx, 0);
2273       break;
2274     }
2275     case JEACH_TYPE: {
2276       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
2277       sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2278       break;
2279     }
2280     case JEACH_ATOM: {
2281       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
2282       if( pThis->eType>=JSON_ARRAY ) break;
2283       jsonReturn(pThis, ctx, 0);
2284       break;
2285     }
2286     case JEACH_ID: {
2287       sqlite3_result_int64(ctx,
2288          (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
2289       break;
2290     }
2291     case JEACH_PARENT: {
2292       if( p->i>p->iBegin && p->bRecursive ){
2293         sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
2294       }
2295       break;
2296     }
2297     case JEACH_FULLKEY: {
2298       JsonString x;
2299       jsonInit(&x, ctx);
2300       if( p->bRecursive ){
2301         jsonEachComputePath(p, &x, p->i);
2302       }else{
2303         if( p->zRoot ){
2304           jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
2305         }else{
2306           jsonAppendChar(&x, '$');
2307         }
2308         if( p->eType==JSON_ARRAY ){
2309           jsonPrintf(30, &x, "[%d]", p->iRowid);
2310         }else if( p->eType==JSON_OBJECT ){
2311           assert( pThis->eU==1 );
2312           jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2313         }
2314       }
2315       jsonResult(&x);
2316       break;
2317     }
2318     case JEACH_PATH: {
2319       if( p->bRecursive ){
2320         JsonString x;
2321         jsonInit(&x, ctx);
2322         jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2323         jsonResult(&x);
2324         break;
2325       }
2326       /* For json_each() path and root are the same so fall through
2327       ** into the root case */
2328       /* no break */ deliberate_fall_through
2329     }
2330     default: {
2331       const char *zRoot = p->zRoot;
2332       if( zRoot==0 ) zRoot = "$";
2333       sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
2334       break;
2335     }
2336     case JEACH_JSON: {
2337       assert( i==JEACH_JSON );
2338       sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2339       break;
2340     }
2341   }
2342   return SQLITE_OK;
2343 }
2344 
2345 /* Return the current rowid value */
2346 static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2347   JsonEachCursor *p = (JsonEachCursor*)cur;
2348   *pRowid = p->iRowid;
2349   return SQLITE_OK;
2350 }
2351 
2352 /* The query strategy is to look for an equality constraint on the json
2353 ** column.  Without such a constraint, the table cannot operate.  idxNum is
2354 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
2355 ** and 0 otherwise.
2356 */
2357 static int jsonEachBestIndex(
2358   sqlite3_vtab *tab,
2359   sqlite3_index_info *pIdxInfo
2360 ){
2361   int i;                     /* Loop counter or computed array index */
2362   int aIdx[2];               /* Index of constraints for JSON and ROOT */
2363   int unusableMask = 0;      /* Mask of unusable JSON and ROOT constraints */
2364   int idxMask = 0;           /* Mask of usable == constraints JSON and ROOT */
2365   const struct sqlite3_index_constraint *pConstraint;
2366 
2367   /* This implementation assumes that JSON and ROOT are the last two
2368   ** columns in the table */
2369   assert( JEACH_ROOT == JEACH_JSON+1 );
2370   UNUSED_PARAMETER(tab);
2371   aIdx[0] = aIdx[1] = -1;
2372   pConstraint = pIdxInfo->aConstraint;
2373   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2374     int iCol;
2375     int iMask;
2376     if( pConstraint->iColumn < JEACH_JSON ) continue;
2377     iCol = pConstraint->iColumn - JEACH_JSON;
2378     assert( iCol==0 || iCol==1 );
2379     testcase( iCol==0 );
2380     iMask = 1 << iCol;
2381     if( pConstraint->usable==0 ){
2382       unusableMask |= iMask;
2383     }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
2384       aIdx[iCol] = i;
2385       idxMask |= iMask;
2386     }
2387   }
2388   if( (unusableMask & ~idxMask)!=0 ){
2389     /* If there are any unusable constraints on JSON or ROOT, then reject
2390     ** this entire plan */
2391     return SQLITE_CONSTRAINT;
2392   }
2393   if( aIdx[0]<0 ){
2394     /* No JSON input.  Leave estimatedCost at the huge value that it was
2395     ** initialized to to discourage the query planner from selecting this
2396     ** plan. */
2397     pIdxInfo->idxNum = 0;
2398   }else{
2399     pIdxInfo->estimatedCost = 1.0;
2400     i = aIdx[0];
2401     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
2402     pIdxInfo->aConstraintUsage[i].omit = 1;
2403     if( aIdx[1]<0 ){
2404       pIdxInfo->idxNum = 1;  /* Only JSON supplied.  Plan 1 */
2405     }else{
2406       i = aIdx[1];
2407       pIdxInfo->aConstraintUsage[i].argvIndex = 2;
2408       pIdxInfo->aConstraintUsage[i].omit = 1;
2409       pIdxInfo->idxNum = 3;  /* Both JSON and ROOT are supplied.  Plan 3 */
2410     }
2411   }
2412   return SQLITE_OK;
2413 }
2414 
2415 /* Start a search on a new JSON string */
2416 static int jsonEachFilter(
2417   sqlite3_vtab_cursor *cur,
2418   int idxNum, const char *idxStr,
2419   int argc, sqlite3_value **argv
2420 ){
2421   JsonEachCursor *p = (JsonEachCursor*)cur;
2422   const char *z;
2423   const char *zRoot = 0;
2424   sqlite3_int64 n;
2425 
2426   UNUSED_PARAMETER(idxStr);
2427   UNUSED_PARAMETER(argc);
2428   jsonEachCursorReset(p);
2429   if( idxNum==0 ) return SQLITE_OK;
2430   z = (const char*)sqlite3_value_text(argv[0]);
2431   if( z==0 ) return SQLITE_OK;
2432   n = sqlite3_value_bytes(argv[0]);
2433   p->zJson = sqlite3_malloc64( n+1 );
2434   if( p->zJson==0 ) return SQLITE_NOMEM;
2435   memcpy(p->zJson, z, (size_t)n+1);
2436   if( jsonParse(&p->sParse, 0, p->zJson) ){
2437     int rc = SQLITE_NOMEM;
2438     if( p->sParse.oom==0 ){
2439       sqlite3_free(cur->pVtab->zErrMsg);
2440       cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2441       if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2442     }
2443     jsonEachCursorReset(p);
2444     return rc;
2445   }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2446     jsonEachCursorReset(p);
2447     return SQLITE_NOMEM;
2448   }else{
2449     JsonNode *pNode = 0;
2450     if( idxNum==3 ){
2451       const char *zErr = 0;
2452       zRoot = (const char*)sqlite3_value_text(argv[1]);
2453       if( zRoot==0 ) return SQLITE_OK;
2454       n = sqlite3_value_bytes(argv[1]);
2455       p->zRoot = sqlite3_malloc64( n+1 );
2456       if( p->zRoot==0 ) return SQLITE_NOMEM;
2457       memcpy(p->zRoot, zRoot, (size_t)n+1);
2458       if( zRoot[0]!='$' ){
2459         zErr = zRoot;
2460       }else{
2461         pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2462       }
2463       if( zErr ){
2464         sqlite3_free(cur->pVtab->zErrMsg);
2465         cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
2466         jsonEachCursorReset(p);
2467         return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2468       }else if( pNode==0 ){
2469         return SQLITE_OK;
2470       }
2471     }else{
2472       pNode = p->sParse.aNode;
2473     }
2474     p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
2475     p->eType = pNode->eType;
2476     if( p->eType>=JSON_ARRAY ){
2477       assert( pNode->eU==0 );
2478       VVA( pNode->eU = 3 );
2479       pNode->u.iKey = 0;
2480       p->iEnd = p->i + pNode->n + 1;
2481       if( p->bRecursive ){
2482         p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
2483         if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2484           p->i--;
2485         }
2486       }else{
2487         p->i++;
2488       }
2489     }else{
2490       p->iEnd = p->i+1;
2491     }
2492   }
2493   return SQLITE_OK;
2494 }
2495 
2496 /* The methods of the json_each virtual table */
2497 static sqlite3_module jsonEachModule = {
2498   0,                         /* iVersion */
2499   0,                         /* xCreate */
2500   jsonEachConnect,           /* xConnect */
2501   jsonEachBestIndex,         /* xBestIndex */
2502   jsonEachDisconnect,        /* xDisconnect */
2503   0,                         /* xDestroy */
2504   jsonEachOpenEach,          /* xOpen - open a cursor */
2505   jsonEachClose,             /* xClose - close a cursor */
2506   jsonEachFilter,            /* xFilter - configure scan constraints */
2507   jsonEachNext,              /* xNext - advance a cursor */
2508   jsonEachEof,               /* xEof - check for end of scan */
2509   jsonEachColumn,            /* xColumn - read data */
2510   jsonEachRowid,             /* xRowid - read data */
2511   0,                         /* xUpdate */
2512   0,                         /* xBegin */
2513   0,                         /* xSync */
2514   0,                         /* xCommit */
2515   0,                         /* xRollback */
2516   0,                         /* xFindMethod */
2517   0,                         /* xRename */
2518   0,                         /* xSavepoint */
2519   0,                         /* xRelease */
2520   0,                         /* xRollbackTo */
2521   0                          /* xShadowName */
2522 };
2523 
2524 /* The methods of the json_tree virtual table. */
2525 static sqlite3_module jsonTreeModule = {
2526   0,                         /* iVersion */
2527   0,                         /* xCreate */
2528   jsonEachConnect,           /* xConnect */
2529   jsonEachBestIndex,         /* xBestIndex */
2530   jsonEachDisconnect,        /* xDisconnect */
2531   0,                         /* xDestroy */
2532   jsonEachOpenTree,          /* xOpen - open a cursor */
2533   jsonEachClose,             /* xClose - close a cursor */
2534   jsonEachFilter,            /* xFilter - configure scan constraints */
2535   jsonEachNext,              /* xNext - advance a cursor */
2536   jsonEachEof,               /* xEof - check for end of scan */
2537   jsonEachColumn,            /* xColumn - read data */
2538   jsonEachRowid,             /* xRowid - read data */
2539   0,                         /* xUpdate */
2540   0,                         /* xBegin */
2541   0,                         /* xSync */
2542   0,                         /* xCommit */
2543   0,                         /* xRollback */
2544   0,                         /* xFindMethod */
2545   0,                         /* xRename */
2546   0,                         /* xSavepoint */
2547   0,                         /* xRelease */
2548   0,                         /* xRollbackTo */
2549   0                          /* xShadowName */
2550 };
2551 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2552 #endif /* !defined(SQLITE_OMIT_JSON) */
2553 
2554 /*
2555 ** Register JSON functions.
2556 */
2557 void sqlite3RegisterJsonFunctions(void){
2558 #ifndef SQLITE_OMIT_JSON
2559   static FuncDef aJsonFunc[] = {
2560     JFUNCTION(json,                1, 0,  jsonRemoveFunc),
2561     JFUNCTION(json_array,         -1, 0,  jsonArrayFunc),
2562     JFUNCTION(json_array_length,   1, 0,  jsonArrayLengthFunc),
2563     JFUNCTION(json_array_length,   2, 0,  jsonArrayLengthFunc),
2564     JFUNCTION(json_extract,       -1, 0,  jsonExtractFunc),
2565     JFUNCTION(json_insert,        -1, 0,  jsonSetFunc),
2566     JFUNCTION(json_object,        -1, 0,  jsonObjectFunc),
2567     JFUNCTION(json_patch,          2, 0,  jsonPatchFunc),
2568     JFUNCTION(json_quote,          1, 0,  jsonQuoteFunc),
2569     JFUNCTION(json_remove,        -1, 0,  jsonRemoveFunc),
2570     JFUNCTION(json_replace,       -1, 0,  jsonReplaceFunc),
2571     JFUNCTION(json_set,           -1, 1,  jsonSetFunc),
2572     JFUNCTION(json_type,           1, 0,  jsonTypeFunc),
2573     JFUNCTION(json_type,           2, 0,  jsonTypeFunc),
2574     JFUNCTION(json_valid,          1, 0,  jsonValidFunc),
2575 #if SQLITE_DEBUG
2576     JFUNCTION(json_parse,          1, 0,  jsonParseFunc),
2577     JFUNCTION(json_test1,          1, 0,  jsonTest1Func),
2578 #endif
2579     WAGGREGATE(json_group_array,   1, 0, 0,
2580        jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse,
2581        SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS),
2582     WAGGREGATE(json_group_object,  2, 0, 0,
2583        jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse,
2584        SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
2585   };
2586   sqlite3InsertBuiltinFuncs(aJsonFunc, ArraySize(aJsonFunc));
2587 #endif
2588 }
2589 
2590 #if  !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
2591 /*
2592 ** Register the JSON table-valued functions
2593 */
2594 int sqlite3JsonTableFunctions(sqlite3 *db){
2595   int rc = SQLITE_OK;
2596   static const struct {
2597      const char *zName;
2598      sqlite3_module *pModule;
2599   } aMod[] = {
2600     { "json_each",            &jsonEachModule               },
2601     { "json_tree",            &jsonTreeModule               },
2602   };
2603   int i;
2604   for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2605     rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
2606   }
2607   return rc;
2608 }
2609 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */
2610