blob: aad45077672d986fb9c65da988613574c2212e51 [file] [log] [blame]
drh5fa5c102015-08-12 16:49:40 +00001/*
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**
drh9dbf96b2022-01-06 01:40:09 +000013** This SQLite JSON functions.
drh5fa5c102015-08-12 16:49:40 +000014**
drh9dbf96b2022-01-06 01:40:09 +000015** 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.
drh5fa5c102015-08-12 16:49:40 +000017**
drh5634cc02015-08-17 11:28:03 +000018** 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
drhcb6c6c62015-08-19 22:47:17 +000020** 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.)
drh5fa5c102015-08-12 16:49:40 +000023*/
drh9dbf96b2022-01-06 01:40:09 +000024#ifndef SQLITE_OMIT_JSON
25#include "sqliteInt.h"
dan2e8f5512015-09-17 17:21:09 +000026
drh95677942015-09-24 01:06:37 +000027/*
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*/
32static const char jsonIsSpace[] = {
drhb9e8f592015-10-16 15:16:06 +000033 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
drh95677942015-09-24 01:06:37 +000034 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};
drh9dbf96b2022-01-06 01:40:09 +000050#define fast_isspace(x) (jsonIsSpace[(unsigned char)x])
drh95677942015-09-24 01:06:37 +000051
drh16fc5e62021-11-01 12:53:01 +000052#if !defined(SQLITE_DEBUG) && !defined(SQLITE_COVERAGE_TEST)
drh285f2ef2021-10-15 16:15:04 +000053# define VVA(X)
54#else
55# define VVA(X) X
56#endif
57
drh52216ad2015-08-18 02:28:03 +000058/* Objects */
drh505ad2c2015-08-21 17:33:11 +000059typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000060typedef struct JsonNode JsonNode;
61typedef struct JsonParse JsonParse;
62
drh5634cc02015-08-17 11:28:03 +000063/* 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.
drh5fa5c102015-08-12 16:49:40 +000066*/
drh505ad2c2015-08-21 17:33:11 +000067struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000068 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000069 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000070 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 */
drhd0960592015-08-17 21:22:32 +000073 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000074 char zSpace[100]; /* Initial static space */
75};
76
drhe9c37f32015-08-15 21:25:36 +000077/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000078*/
drhe9c37f32015-08-15 21:25:36 +000079#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
drhf5ddb9c2015-09-11 00:06:41 +000088/* The "subtype" set for JSON values */
89#define JSON_SUBTYPE 74 /* Ascii for "J" */
90
drh987eb1f2015-08-17 15:17:37 +000091/*
92** Names of the various JSON types:
93*/
94static const char * const jsonType[] = {
95 "null", "true", "false", "integer", "real", "text", "array", "object"
96};
97
drh301eecc2015-08-17 20:14:19 +000098/* 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 */
drh633647a2017-03-22 21:24:31 +0000103#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 */
drh301eecc2015-08-17 20:14:19 +0000107
drh987eb1f2015-08-17 15:17:37 +0000108
drhe9c37f32015-08-15 21:25:36 +0000109/* A single node of parsed JSON
110*/
drhe9c37f32015-08-15 21:25:36 +0000111struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000112 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000113 u8 jnFlags; /* JNODE flags */
drh285f2ef2021-10-15 16:15:04 +0000114 u8 eU; /* Which union element to use */
drhe9c37f32015-08-15 21:25:36 +0000115 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000116 union {
drh285f2ef2021-10-15 16:15:04 +0000117 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 */
drh52216ad2015-08-18 02:28:03 +0000122 } u;
drhe9c37f32015-08-15 21:25:36 +0000123};
124
125/* A completely parsed JSON string
126*/
drhe9c37f32015-08-15 21:25:36 +0000127struct 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 */
drh505ad2c2015-08-21 17:33:11 +0000132 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000133 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000134 u8 nErr; /* Number of errors seen */
drhff6d50e2017-04-11 18:55:05 +0000135 u16 iDepth; /* Nesting depth */
drh3fb153c2017-05-11 16:49:59 +0000136 int nJson; /* Length of the zJson string in bytes */
drhe35fc302018-08-30 01:52:10 +0000137 u32 iHold; /* Replace cache line with the lowest iHold value */
drhe9c37f32015-08-15 21:25:36 +0000138};
139
drhff6d50e2017-04-11 18:55:05 +0000140/*
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
drh505ad2c2015-08-21 17:33:11 +0000149/**************************************************************************
150** Utility routines for dealing with JsonString objects
151**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000152
drh505ad2c2015-08-21 17:33:11 +0000153/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000154*/
drh505ad2c2015-08-21 17:33:11 +0000155static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000156 p->zBuf = p->zSpace;
157 p->nAlloc = sizeof(p->zSpace);
158 p->nUsed = 0;
159 p->bStatic = 1;
160}
161
drh505ad2c2015-08-21 17:33:11 +0000162/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000163*/
drh505ad2c2015-08-21 17:33:11 +0000164static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000165 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000166 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000167 jsonZero(p);
168}
169
170
drh505ad2c2015-08-21 17:33:11 +0000171/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000172** initial state.
173*/
drh505ad2c2015-08-21 17:33:11 +0000174static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000175 if( !p->bStatic ) sqlite3_free(p->zBuf);
176 jsonZero(p);
177}
178
179
180/* Report an out-of-memory (OOM) condition
181*/
drh505ad2c2015-08-21 17:33:11 +0000182static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000183 p->bErr = 1;
184 sqlite3_result_error_nomem(p->pCtx);
185 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000186}
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*/
drh505ad2c2015-08-21 17:33:11 +0000191static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000192 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000193 char *zNew;
194 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000195 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000196 zNew = sqlite3_malloc64(nTotal);
197 if( zNew==0 ){
198 jsonOom(p);
199 return SQLITE_NOMEM;
200 }
drh6fd5c1e2015-08-21 20:37:12 +0000201 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000202 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
drh505ad2c2015-08-21 17:33:11 +0000216/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000217*/
drh505ad2c2015-08-21 17:33:11 +0000218static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drhc795e3d2020-05-17 13:47:28 +0000219 if( N==0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000220 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
drh4af352d2015-08-21 20:02:48 +0000225/* Append formatted text (not to exceed N bytes) to the JsonString.
226*/
227static 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
drh5634cc02015-08-17 11:28:03 +0000236/* Append a single character
237*/
drh505ad2c2015-08-21 17:33:11 +0000238static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000239 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
240 p->zBuf[p->nUsed++] = c;
241}
242
drh301eecc2015-08-17 20:14:19 +0000243/* Append a comma separator to the output buffer, if the previous
244** character is not '[' or '{'.
245*/
drh505ad2c2015-08-21 17:33:11 +0000246static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000247 char c;
248 if( p->nUsed==0 ) return;
249 c = p->zBuf[p->nUsed-1];
250 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
251}
252
drh505ad2c2015-08-21 17:33:11 +0000253/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000254** under construction. Enclose the string in "..." and escape
255** any double-quotes or backslash characters contained within the
256** string.
257*/
drh505ad2c2015-08-21 17:33:11 +0000258static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000259 u32 i;
drh76baad92021-04-30 16:12:40 +0000260 if( zIn==0 || ((N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0) ) return;
drh5fa5c102015-08-12 16:49:40 +0000261 p->zBuf[p->nUsed++] = '"';
262 for(i=0; i<N; i++){
drh3b7f9a62016-02-04 10:28:57 +0000263 unsigned char c = ((unsigned const char*)zIn)[i];
drh5fa5c102015-08-12 16:49:40 +0000264 if( c=='"' || c=='\\' ){
drh3b7f9a62016-02-04 10:28:57 +0000265 json_simple_escape:
drh4977ccf2015-09-19 11:57:26 +0000266 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000267 p->zBuf[p->nUsed++] = '\\';
drh3b7f9a62016-02-04 10:28:57 +0000268 }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];
drh5fa5c102015-08-12 16:49:40 +0000290 }
291 p->zBuf[p->nUsed++] = c;
292 }
293 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000294 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000295}
296
drhd0960592015-08-17 21:22:32 +0000297/*
298** Append a function parameter value to the JSON string under
299** construction.
300*/
301static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000302 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000303 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000304){
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);
drhf5ddb9c2015-09-11 00:06:41 +0000320 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000321 jsonAppendRaw(p, z, n);
322 }else{
323 jsonAppendString(p, z, n);
324 }
drhd0960592015-08-17 21:22:32 +0000325 break;
326 }
327 default: {
328 if( p->bErr==0 ){
329 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
drh4a642b62016-02-05 01:55:27 +0000330 p->bErr = 2;
drhd0960592015-08-17 21:22:32 +0000331 jsonReset(p);
332 }
333 break;
334 }
335 }
336}
337
338
drhbd0621b2015-08-13 13:54:59 +0000339/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000340*/
drh505ad2c2015-08-21 17:33:11 +0000341static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000342 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000343 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
drh505ad2c2015-08-21 17:33:11 +0000351/**************************************************************************
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*/
364static 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*/
372static 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
drh5634cc02015-08-17 11:28:03 +0000381/*
drh3fb153c2017-05-11 16:49:59 +0000382** Free a JsonParse object that was obtained from sqlite3_malloc().
383*/
384static void jsonParseFree(JsonParse *pParse){
385 jsonParseReset(pParse);
386 sqlite3_free(pParse);
387}
388
389/*
drh5634cc02015-08-17 11:28:03 +0000390** 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.
drhbd0621b2015-08-13 13:54:59 +0000393*/
drh52216ad2015-08-18 02:28:03 +0000394static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000395 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000396 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000397 sqlite3_value **aReplace /* Replacement values */
398){
drh7d4c94b2021-10-04 22:34:38 +0000399 assert( pNode!=0 );
drh633647a2017-03-22 21:24:31 +0000400 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
drh7d4c94b2021-10-04 22:34:38 +0000401 if( (pNode->jnFlags & JNODE_REPLACE)!=0 && ALWAYS(aReplace!=0) ){
drh285f2ef2021-10-15 16:15:04 +0000402 assert( pNode->eU==4 );
drh633647a2017-03-22 21:24:31 +0000403 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
404 return;
405 }
drh285f2ef2021-10-15 16:15:04 +0000406 assert( pNode->eU==5 );
drh633647a2017-03-22 21:24:31 +0000407 pNode = pNode->u.pPatch;
408 }
drh5634cc02015-08-17 11:28:03 +0000409 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000410 default: {
411 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000412 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: {
drh301eecc2015-08-17 20:14:19 +0000424 if( pNode->jnFlags & JNODE_RAW ){
drh285f2ef2021-10-15 16:15:04 +0000425 assert( pNode->eU==1 );
drh52216ad2015-08-18 02:28:03 +0000426 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000427 break;
428 }
drh08b92082020-08-10 14:18:00 +0000429 /* no break */ deliberate_fall_through
drh5634cc02015-08-17 11:28:03 +0000430 }
431 case JSON_REAL:
432 case JSON_INT: {
drh285f2ef2021-10-15 16:15:04 +0000433 assert( pNode->eU==1 );
drh52216ad2015-08-18 02:28:03 +0000434 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000435 break;
436 }
437 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000438 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000439 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000440 for(;;){
441 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000442 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000443 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000444 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000445 }
drh505ad2c2015-08-21 17:33:11 +0000446 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000447 }
drh52216ad2015-08-18 02:28:03 +0000448 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
drh285f2ef2021-10-15 16:15:04 +0000449 assert( pNode->eU==2 );
drh52216ad2015-08-18 02:28:03 +0000450 pNode = &pNode[pNode->u.iAppend];
451 j = 1;
drh5634cc02015-08-17 11:28:03 +0000452 }
453 jsonAppendChar(pOut, ']');
454 break;
455 }
456 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000457 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000458 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000459 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, ':');
drh633647a2017-03-22 21:24:31 +0000465 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000466 }
drh505ad2c2015-08-21 17:33:11 +0000467 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000468 }
drh52216ad2015-08-18 02:28:03 +0000469 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
drh285f2ef2021-10-15 16:15:04 +0000470 assert( pNode->eU==2 );
drh52216ad2015-08-18 02:28:03 +0000471 pNode = &pNode[pNode->u.iAppend];
472 j = 1;
drh5634cc02015-08-17 11:28:03 +0000473 }
474 jsonAppendChar(pOut, '}');
475 break;
476 }
drhbd0621b2015-08-13 13:54:59 +0000477 }
drh5634cc02015-08-17 11:28:03 +0000478}
479
480/*
drhf2df7e72015-08-28 20:07:40 +0000481** Return a JsonNode and all its descendents as a JSON string.
482*/
483static 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);
drhf5ddb9c2015-09-11 00:06:41 +0000492 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000493}
494
495/*
drh48eb03b2019-11-10 11:09:06 +0000496** 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*/
500static 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*/
513static u32 jsonHexToInt4(const char *z){
514 u32 v;
drh9dbf96b2022-01-06 01:40:09 +0000515 assert( sqlite3Isxdigit(z[0]) );
516 assert( sqlite3Isxdigit(z[1]) );
517 assert( sqlite3Isxdigit(z[2]) );
518 assert( sqlite3Isxdigit(z[3]) );
drh48eb03b2019-11-10 11:09:06 +0000519 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/*
drh5634cc02015-08-17 11:28:03 +0000527** Make the JsonNode the return value of the function.
528*/
drhd0960592015-08-17 21:22:32 +0000529static 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){
drh5634cc02015-08-17 11:28:03 +0000534 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000535 default: {
536 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000537 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 }
drh987eb1f2015-08-17 15:17:37 +0000548 case JSON_INT: {
549 sqlite3_int64 i = 0;
drh285f2ef2021-10-15 16:15:04 +0000550 const char *z;
551 assert( pNode->eU==1 );
552 z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000553 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000554 while( z[0]>='0' && z[0]<='9' ){
555 unsigned v = *(z++) - '0';
556 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000557 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000558 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 }
drh52216ad2015-08-18 02:28:03 +0000571 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000572 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000573 int_done:
574 break;
drhe85e1da2021-10-01 21:01:07 +0000575 int_as_real: ; /* no break */ deliberate_fall_through
drh8deb4b82015-10-09 18:21:43 +0000576 }
577 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000578 double r;
579#ifdef SQLITE_AMALGAMATION
drh285f2ef2021-10-15 16:15:04 +0000580 const char *z;
581 assert( pNode->eU==1 );
582 z = pNode->u.zJContent;
drh49472652015-10-16 15:35:39 +0000583 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
584#else
drh285f2ef2021-10-15 16:15:04 +0000585 assert( pNode->eU==1 );
drh49472652015-10-16 15:35:39 +0000586 r = strtod(pNode->u.zJContent, 0);
587#endif
drh8deb4b82015-10-09 18:21:43 +0000588 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000589 break;
590 }
drh5634cc02015-08-17 11:28:03 +0000591 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000592#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() */
drh301eecc2015-08-17 20:14:19 +0000595 if( pNode->jnFlags & JNODE_RAW ){
drh285f2ef2021-10-15 16:15:04 +0000596 assert( pNode->eU==1 );
drh52216ad2015-08-18 02:28:03 +0000597 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
598 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000599 }else
600#endif
601 assert( (pNode->jnFlags & JNODE_RAW)==0 );
602 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000603 /* JSON formatted without any backslash-escapes */
drh285f2ef2021-10-15 16:15:04 +0000604 assert( pNode->eU==1 );
drh52216ad2015-08-18 02:28:03 +0000605 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000606 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000607 }else{
608 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000609 u32 i;
610 u32 n = pNode->n;
drh285f2ef2021-10-15 16:15:04 +0000611 const char *z;
drh987eb1f2015-08-17 15:17:37 +0000612 char *zOut;
613 u32 j;
drh285f2ef2021-10-15 16:15:04 +0000614 assert( pNode->eU==1 );
615 z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000616 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];
drh80d87402015-08-24 12:42:41 +0000623 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000624 zOut[j++] = c;
625 }else{
626 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000627 if( c=='u' ){
drh48eb03b2019-11-10 11:09:06 +0000628 u32 v = jsonHexToInt4(z+i+1);
629 i += 4;
drh80d87402015-08-24 12:42:41 +0000630 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000631 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000632 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000633 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000634 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000635 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000636 }else{
drh48eb03b2019-11-10 11:09:06 +0000637 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 }
drh987eb1f2015-08-17 15:17:37 +0000656 }
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);
drh5634cc02015-08-17 11:28:03 +0000675 }
676 break;
677 }
678 case JSON_ARRAY:
679 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000680 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000681 break;
682 }
683 }
drhbd0621b2015-08-13 13:54:59 +0000684}
685
drh95677942015-09-24 01:06:37 +0000686/* Forward reference */
687static 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
702static 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;
drh2d77d802019-01-08 20:02:48 +0000713 pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
drh95677942015-09-24 01:06:37 +0000714 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
drh5fa5c102015-08-12 16:49:40 +0000724/*
drhe9c37f32015-08-15 21:25:36 +0000725** 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*/
729static 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;
drhaa6fe5b2021-10-04 13:18:44 +0000736 if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000737 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000738 }
739 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000740 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000741 p->jnFlags = 0;
drh285f2ef2021-10-15 16:15:04 +0000742 VVA( p->eU = zContent ? 1 : 0 );
drhe9c37f32015-08-15 21:25:36 +0000743 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000744 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000745 return pParse->nNode++;
746}
747
748/*
drhad875e72016-11-07 13:37:28 +0000749** Return true if z[] begins with 4 (or more) hexadecimal digits
750*/
751static int jsonIs4Hex(const char *z){
752 int i;
drh9dbf96b2022-01-06 01:40:09 +0000753 for(i=0; i<4; i++) if( !sqlite3Isxdigit(z[i]) ) return 0;
drhad875e72016-11-07 13:37:28 +0000754 return 1;
755}
756
757/*
drhe9c37f32015-08-15 21:25:36 +0000758** 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*/
765static int jsonParseValue(JsonParse *pParse, u32 i){
766 char c;
767 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000768 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000769 int x;
drh852944e2015-09-10 03:29:11 +0000770 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000771 const char *z = pParse->zJson;
drh9dbf96b2022-01-06 01:40:09 +0000772 while( fast_isspace(z[i]) ){ i++; }
drh9fa866a2017-04-08 18:18:22 +0000773 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000774 /* Parse object */
775 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000776 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000777 for(j=i+1;;j++){
drh9dbf96b2022-01-06 01:40:09 +0000778 while( fast_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000779 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000780 x = jsonParseValue(pParse, j);
781 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000782 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000783 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000784 return -1;
785 }
drhbe9474e2015-08-22 03:05:54 +0000786 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000787 pNode = &pParse->aNode[pParse->nNode-1];
788 if( pNode->eType!=JSON_STRING ) return -1;
789 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000790 j = x;
drh9dbf96b2022-01-06 01:40:09 +0000791 while( fast_isspace(z[j]) ){ j++; }
drh9fa866a2017-04-08 18:18:22 +0000792 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000793 j++;
794 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000795 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000796 if( x<0 ) return -1;
797 j = x;
drh9dbf96b2022-01-06 01:40:09 +0000798 while( fast_isspace(z[j]) ){ j++; }
drh9fa866a2017-04-08 18:18:22 +0000799 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000800 if( c==',' ) continue;
801 if( c!='}' ) return -1;
802 break;
803 }
drhbc8f0922015-08-22 19:39:04 +0000804 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000805 return j+1;
806 }else if( c=='[' ){
807 /* Parse array */
808 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000809 if( iThis<0 ) return -1;
drh285f2ef2021-10-15 16:15:04 +0000810 memset(&pParse->aNode[iThis].u, 0, sizeof(pParse->aNode[iThis].u));
drhe9c37f32015-08-15 21:25:36 +0000811 for(j=i+1;;j++){
drh9dbf96b2022-01-06 01:40:09 +0000812 while( fast_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000813 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000814 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000815 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000816 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000817 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000818 return -1;
819 }
820 j = x;
drh9dbf96b2022-01-06 01:40:09 +0000821 while( fast_isspace(z[j]) ){ j++; }
drh9fa866a2017-04-08 18:18:22 +0000822 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000823 if( c==',' ) continue;
824 if( c!=']' ) return -1;
825 break;
826 }
drhbc8f0922015-08-22 19:39:04 +0000827 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000828 return j+1;
829 }else if( c=='"' ){
830 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000831 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000832 j = i+1;
833 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000834 c = z[j];
drh86715382017-04-13 00:12:32 +0000835 if( (c & ~0x1f)==0 ){
836 /* Control characters are not allowed in strings */
837 return -1;
838 }
drhe9c37f32015-08-15 21:25:36 +0000839 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000840 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000841 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
842 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000843 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000844 jnFlags = JNODE_ESCAPE;
845 }else{
846 return -1;
847 }
drhe9c37f32015-08-15 21:25:36 +0000848 }else if( c=='"' ){
849 break;
850 }
851 j++;
852 }
drh9fa866a2017-04-08 18:18:22 +0000853 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000854 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000855 return j+1;
856 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000857 && strncmp(z+i,"null",4)==0
drh9dbf96b2022-01-06 01:40:09 +0000858 && !sqlite3Isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000859 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
860 return i+4;
861 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000862 && strncmp(z+i,"true",4)==0
drh9dbf96b2022-01-06 01:40:09 +0000863 && !sqlite3Isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000864 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
865 return i+4;
866 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000867 && strncmp(z+i,"false",5)==0
drh9dbf96b2022-01-06 01:40:09 +0000868 && !sqlite3Isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000869 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;
drh9fa866a2017-04-08 18:18:22 +0000875 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 }
drhe9c37f32015-08-15 21:25:36 +0000880 j = i+1;
881 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000882 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000883 if( c>='0' && c<='9' ) continue;
884 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000885 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000886 if( seenDP ) return -1;
887 seenDP = 1;
888 continue;
889 }
890 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000891 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000892 if( seenE ) return -1;
893 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000894 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000895 if( c=='+' || c=='-' ){
896 j++;
drh9fa866a2017-04-08 18:18:22 +0000897 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000898 }
drhd1f00682015-08-29 16:02:37 +0000899 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000900 continue;
901 }
902 break;
903 }
drh9fa866a2017-04-08 18:18:22 +0000904 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000905 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000906 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000907 return j;
908 }else if( c=='}' ){
909 return -2; /* End of {...} */
910 }else if( c==']' ){
911 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000912 }else if( c==0 ){
913 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000914 }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*/
drhbc8f0922015-08-22 19:39:04 +0000926static 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){
drhe9c37f32015-08-15 21:25:36 +0000931 int i;
drhe9c37f32015-08-15 21:25:36 +0000932 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000933 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000934 pParse->zJson = zJson;
935 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000936 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000937 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000938 assert( pParse->iDepth==0 );
drh9dbf96b2022-01-06 01:40:09 +0000939 while( fast_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000940 if( zJson[i] ) i = -1;
941 }
drhd1f00682015-08-29 16:02:37 +0000942 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000943 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 }
drh505ad2c2015-08-21 17:33:11 +0000950 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000951 return 1;
952 }
953 return 0;
954}
drh301eecc2015-08-17 20:14:19 +0000955
drh505ad2c2015-08-21 17:33:11 +0000956/* Mark node i of pParse as being a child of iParent. Call recursively
957** to fill in all the descendants of node i.
958*/
959static 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*/
986static int jsonParseFindParents(JsonParse *pParse){
987 u32 *aUp;
988 assert( pParse->aUp==0 );
drh2d77d802019-01-08 20:02:48 +0000989 aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000990 if( aUp==0 ){
991 pParse->oom = 1;
992 return SQLITE_NOMEM;
993 }
drh505ad2c2015-08-21 17:33:11 +0000994 jsonParseFillInParentage(pParse, 0, 0);
995 return SQLITE_OK;
996}
997
drh8cb0c832015-09-22 00:21:03 +0000998/*
drh3fb153c2017-05-11 16:49:59 +0000999** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
1000*/
drhe35fc302018-08-30 01:52:10 +00001001#define JSON_CACHE_ID (-429938) /* First cache entry */
1002#define JSON_CACHE_SZ 4 /* Max number of cache entries */
drh3fb153c2017-05-11 16:49:59 +00001003
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*/
1012static JsonParse *jsonParseCached(
1013 sqlite3_context *pCtx,
drhe35fc302018-08-30 01:52:10 +00001014 sqlite3_value **argv,
1015 sqlite3_context *pErrCtx
drh3fb153c2017-05-11 16:49:59 +00001016){
1017 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
1018 int nJson = sqlite3_value_bytes(argv[0]);
1019 JsonParse *p;
drhe35fc302018-08-30 01:52:10 +00001020 JsonParse *pMatch = 0;
1021 int iKey;
1022 int iMinKey = 0;
1023 u32 iMinHold = 0xffffffff;
1024 u32 iMaxHold = 0;
drh3fb153c2017-05-11 16:49:59 +00001025 if( zJson==0 ) return 0;
drhe35fc302018-08-30 01:52:10 +00001026 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;
drh3fb153c2017-05-11 16:49:59 +00001050 }
drh2d77d802019-01-08 20:02:48 +00001051 p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
drh3fb153c2017-05-11 16:49:59 +00001052 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);
drhe35fc302018-08-30 01:52:10 +00001059 if( jsonParse(p, pErrCtx, p->zJson) ){
drh3fb153c2017-05-11 16:49:59 +00001060 sqlite3_free(p);
1061 return 0;
1062 }
1063 p->nJson = nJson;
drhe35fc302018-08-30 01:52:10 +00001064 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);
drh3fb153c2017-05-11 16:49:59 +00001068}
1069
1070/*
drh8cb0c832015-09-22 00:21:03 +00001071** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1072** a match.
1073*/
mistachkinf2c26ed2015-10-12 22:20:29 +00001074static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh285f2ef2021-10-15 16:15:04 +00001075 assert( pNode->eU==1 );
drh8cb0c832015-09-22 00:21:03 +00001076 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
drh52216ad2015-08-18 02:28:03 +00001085/* forward declaration */
drha7714022015-08-29 00:54:49 +00001086static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +00001087
drh987eb1f2015-08-17 15:17:37 +00001088/*
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.
drh52216ad2015-08-18 02:28:03 +00001092**
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.
drh987eb1f2015-08-17 15:17:37 +00001096*/
drha7714022015-08-29 00:54:49 +00001097static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +00001098 JsonParse *pParse, /* The JSON to search */
1099 u32 iRoot, /* Begin the search at this node */
1100 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +00001101 int *pApnd, /* Append nodes to complete path if not NULL */
1102 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +00001103){
drhbc8f0922015-08-22 19:39:04 +00001104 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001105 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001106 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001107 if( zPath[0]==0 ) return pRoot;
drh7e35e812019-07-31 12:13:58 +00001108 if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
drh987eb1f2015-08-17 15:17:37 +00001109 if( zPath[0]=='.' ){
1110 if( pRoot->eType!=JSON_OBJECT ) return 0;
1111 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001112 if( zPath[0]=='"' ){
1113 zKey = zPath + 1;
1114 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1115 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001116 if( zPath[i] ){
1117 i++;
1118 }else{
1119 *pzErr = zPath;
1120 return 0;
1121 }
drh6b43cc82015-08-19 23:02:49 +00001122 }else{
1123 zKey = zPath;
1124 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1125 nKey = i;
1126 }
drha7714022015-08-29 00:54:49 +00001127 if( nKey==0 ){
1128 *pzErr = zPath;
1129 return 0;
1130 }
drh987eb1f2015-08-17 15:17:37 +00001131 j = 1;
drh52216ad2015-08-18 02:28:03 +00001132 for(;;){
1133 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001134 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001135 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001136 }
1137 j++;
drh505ad2c2015-08-21 17:33:11 +00001138 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001139 }
drh52216ad2015-08-18 02:28:03 +00001140 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
drh285f2ef2021-10-15 16:15:04 +00001141 assert( pRoot->eU==2 );
drh52216ad2015-08-18 02:28:03 +00001142 iRoot += pRoot->u.iAppend;
1143 pRoot = &pParse->aNode[iRoot];
1144 j = 1;
1145 }
1146 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001147 u32 iStart, iLabel;
1148 JsonNode *pNode;
1149 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
danfe9a8322019-06-17 14:50:33 +00001150 iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
drh52216ad2015-08-18 02:28:03 +00001151 zPath += i;
drha7714022015-08-29 00:54:49 +00001152 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001153 if( pParse->oom ) return 0;
1154 if( pNode ){
1155 pRoot = &pParse->aNode[iRoot];
drh285f2ef2021-10-15 16:15:04 +00001156 assert( pRoot->eU==0 );
drhbc8f0922015-08-22 19:39:04 +00001157 pRoot->u.iAppend = iStart - iRoot;
1158 pRoot->jnFlags |= JNODE_APPEND;
drh285f2ef2021-10-15 16:15:04 +00001159 VVA( pRoot->eU = 2 );
drhbc8f0922015-08-22 19:39:04 +00001160 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1161 }
1162 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001163 }
drh52818642019-11-22 17:37:56 +00001164 }else if( zPath[0]=='[' ){
drh987eb1f2015-08-17 15:17:37 +00001165 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001166 j = 1;
drh9dbf96b2022-01-06 01:40:09 +00001167 while( sqlite3Isdigit(zPath[j]) ){
drh3d1d2a92015-09-22 01:15:49 +00001168 i = i*10 + zPath[j] - '0';
1169 j++;
drh987eb1f2015-08-17 15:17:37 +00001170 }
drh52818642019-11-22 17:37:56 +00001171 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;
drh285f2ef2021-10-15 16:15:04 +00001182 assert( pBase->eU==2 );
drh52818642019-11-22 17:37:56 +00001183 iBase += pBase->u.iAppend;
1184 pBase = &pParse->aNode[iBase];
1185 j = 1;
1186 }
1187 j = 2;
drh9dbf96b2022-01-06 01:40:09 +00001188 if( zPath[2]=='-' && sqlite3Isdigit(zPath[3]) ){
drh52818642019-11-22 17:37:56 +00001189 unsigned int x = 0;
1190 j = 3;
1191 do{
1192 x = x*10 + zPath[j] - '0';
1193 j++;
drh9dbf96b2022-01-06 01:40:09 +00001194 }while( sqlite3Isdigit(zPath[j]) );
drh52818642019-11-22 17:37:56 +00001195 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 }
drha7714022015-08-29 00:54:49 +00001206 }
drh52818642019-11-22 17:37:56 +00001207 if( pRoot->eType!=JSON_ARRAY ) return 0;
drh3d1d2a92015-09-22 01:15:49 +00001208 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001209 j = 1;
drh52216ad2015-08-18 02:28:03 +00001210 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001211 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1212 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001213 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001214 }
1215 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
drh285f2ef2021-10-15 16:15:04 +00001216 assert( pRoot->eU==2 );
drh52216ad2015-08-18 02:28:03 +00001217 iRoot += pRoot->u.iAppend;
1218 pRoot = &pParse->aNode[iRoot];
1219 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001220 }
1221 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001222 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001223 }
1224 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001225 u32 iStart;
1226 JsonNode *pNode;
1227 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001228 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001229 if( pParse->oom ) return 0;
1230 if( pNode ){
1231 pRoot = &pParse->aNode[iRoot];
drh285f2ef2021-10-15 16:15:04 +00001232 assert( pRoot->eU==0 );
drhbc8f0922015-08-22 19:39:04 +00001233 pRoot->u.iAppend = iStart - iRoot;
1234 pRoot->jnFlags |= JNODE_APPEND;
drh285f2ef2021-10-15 16:15:04 +00001235 VVA( pRoot->eU = 2 );
drhbc8f0922015-08-22 19:39:04 +00001236 }
1237 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001238 }
drh3d1d2a92015-09-22 01:15:49 +00001239 }else{
drha7714022015-08-29 00:54:49 +00001240 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001241 }
1242 return 0;
1243}
1244
drh52216ad2015-08-18 02:28:03 +00001245/*
drhbc8f0922015-08-22 19:39:04 +00001246** Append content to pParse that will complete zPath. Return a pointer
1247** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001248*/
1249static JsonNode *jsonLookupAppend(
1250 JsonParse *pParse, /* Append content to the JSON parse */
1251 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001252 int *pApnd, /* Set this flag to 1 */
1253 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001254){
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;
drha7714022015-08-29 00:54:49 +00001268 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001269}
1270
drhbc8f0922015-08-22 19:39:04 +00001271/*
drha7714022015-08-29 00:54:49 +00001272** Return the text of a syntax error message on a JSON path. Space is
1273** obtained from sqlite3_malloc().
1274*/
1275static 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.
drha7714022015-08-29 00:54:49 +00001288*/
1289static 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 */
drhf5ddb9c2015-09-11 00:06:41 +00001293 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001294){
1295 const char *zErr = 0;
1296 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001297 char *zMsg;
drha7714022015-08-29 00:54:49 +00001298
1299 if( zPath==0 ) return 0;
1300 if( zPath[0]!='$' ){
1301 zErr = zPath;
1302 goto lookup_err;
1303 }
1304 zPath++;
drha7714022015-08-29 00:54:49 +00001305 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001306 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001307
1308lookup_err:
1309 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001310 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);
drha7714022015-08-29 00:54:49 +00001317 }
drha7714022015-08-29 00:54:49 +00001318 return 0;
1319}
1320
1321
1322/*
drhbc8f0922015-08-22 19:39:04 +00001323** Report the wrong number of arguments for json_insert(), json_replace()
1324** or json_set().
1325*/
1326static 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}
drh52216ad2015-08-18 02:28:03 +00001335
drh29c99692017-03-24 12:35:17 +00001336/*
1337** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1338*/
1339static 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
drha7714022015-08-29 00:54:49 +00001355
drh987eb1f2015-08-17 15:17:37 +00001356/****************************************************************************
1357** SQL functions used for testing and debugging
1358****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001359
drh301eecc2015-08-17 20:14:19 +00001360#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001361/*
drh5634cc02015-08-17 11:28:03 +00001362** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001363** a parse of the JSON provided. Or it returns NULL if JSON is not
1364** well-formed.
1365*/
drh5634cc02015-08-17 11:28:03 +00001366static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001367 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001368 int argc,
1369 sqlite3_value **argv
1370){
drh505ad2c2015-08-21 17:33:11 +00001371 JsonString s; /* Output string - not real JSON */
1372 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001373 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001374
1375 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001376 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001377 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001378 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001379 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001380 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];
drhe9c37f32015-08-15 21:25:36 +00001386 }
drh852944e2015-09-10 03:29:11 +00001387 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1388 i, zType, x.aNode[i].n, x.aUp[i]);
drh285f2ef2021-10-15 16:15:04 +00001389 assert( x.aNode[i].eU==0 || x.aNode[i].eU==1 );
drh852944e2015-09-10 03:29:11 +00001390 if( x.aNode[i].u.zJContent!=0 ){
drh285f2ef2021-10-15 16:15:04 +00001391 assert( x.aNode[i].eU==1 );
drh852944e2015-09-10 03:29:11 +00001392 jsonAppendRaw(&s, " ", 1);
1393 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
drh285f2ef2021-10-15 16:15:04 +00001394 }else{
1395 assert( x.aNode[i].eU==0 );
drh852944e2015-09-10 03:29:11 +00001396 }
1397 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001398 }
drh505ad2c2015-08-21 17:33:11 +00001399 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001400 jsonResult(&s);
1401}
1402
drh5634cc02015-08-17 11:28:03 +00001403/*
drhf5ddb9c2015-09-11 00:06:41 +00001404** 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.
drh5634cc02015-08-17 11:28:03 +00001407*/
1408static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001409 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001410 int argc,
1411 sqlite3_value **argv
1412){
drh9dbf96b2022-01-06 01:40:09 +00001413 UNUSED_PARAMETER(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001414 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001415}
drh301eecc2015-08-17 20:14:19 +00001416#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001417
drh987eb1f2015-08-17 15:17:37 +00001418/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001419** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001420****************************************************************************/
1421
1422/*
drh2ad96f52016-06-17 13:01:51 +00001423** 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*/
1428static void jsonQuoteFunc(
1429 sqlite3_context *ctx,
1430 int argc,
1431 sqlite3_value **argv
1432){
1433 JsonString jx;
drh9dbf96b2022-01-06 01:40:09 +00001434 UNUSED_PARAMETER(argc);
drh2ad96f52016-06-17 13:01:51 +00001435
1436 jsonInit(&jx, ctx);
1437 jsonAppendValue(&jx, argv[0]);
1438 jsonResult(&jx);
1439 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1440}
1441
1442/*
drh987eb1f2015-08-17 15:17:37 +00001443** 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*/
1447static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001448 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001449 int argc,
1450 sqlite3_value **argv
1451){
1452 int i;
drh505ad2c2015-08-21 17:33:11 +00001453 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001454
drhbc8f0922015-08-22 19:39:04 +00001455 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001456 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001457 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001458 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001459 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001460 }
drhd0960592015-08-17 21:22:32 +00001461 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001462 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001463 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001464}
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*/
1474static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001475 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001476 int argc,
1477 sqlite3_value **argv
1478){
drh3fb153c2017-05-11 16:49:59 +00001479 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001480 sqlite3_int64 n = 0;
1481 u32 i;
drha8f39a92015-09-21 22:53:16 +00001482 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001483
drhe35fc302018-08-30 01:52:10 +00001484 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001485 if( p==0 ) return;
1486 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001487 if( argc==2 ){
1488 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001489 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001490 }else{
drh3fb153c2017-05-11 16:49:59 +00001491 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001492 }
1493 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001494 return;
1495 }
1496 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001497 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1498 for(i=1; i<=pNode->n; n++){
1499 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001500 }
drh987eb1f2015-08-17 15:17:37 +00001501 }
drh3fb153c2017-05-11 16:49:59 +00001502 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001503}
1504
1505/*
drhdc60c682022-01-08 15:05:53 +00001506** Bit values for the flags passed into jsonExtractFunc() or
1507** jsonSetFunc() via the user-data value.
1508*/
1509#define JSON_NULLERR 0x01 /* Return NULL if input is not JSON */
1510#define JSON_ABPATH 0x02 /* Allow abbreviated JSON path specs */
1511#define JSON_ISSET 0x04 /* json_set(), not json_insert() */
1512
1513/*
drh3ad93bb2015-08-29 19:41:45 +00001514** json_extract(JSON, PATH, ...)
drhdc60c682022-01-08 15:05:53 +00001515** json_nextract(JSON, PATH, ...)
1516** "->"(JSON,PATH)
1517** "->>"(JSON,PATH)
drh987eb1f2015-08-17 15:17:37 +00001518**
drhdc60c682022-01-08 15:05:53 +00001519** Return the element described by PATH. Return NULL if that PATH element
1520** is not found. For leaf nodes of the JSON, the value returned is a pure
1521** SQL value. In other words, quotes have been removed from strings.
1522**
1523** If there are multiple PATHs, then the value returned is a JSON array
1524** with one entry in the array for each PATH term.
1525**
1526** Throw an error if any PATH is malformed.
1527**
1528** If JSON is not well-formed JSON then:
1529**
1530** (1) raise an error if the JSON_NULLERR flag is not set.
1531**
1532** (2) Otherwise (if the JSON_NULLERR flags is set and) if there
1533** is a single PATH argument with the value '$', simply quote
1534** the JSON input as if by json_quote(). In other words, treat
1535** the JSON input as a string and convert it into a valid JSON
1536** string.
1537**
1538** (3) Otherwise (if JSON_NULLERR is set and the PATH is not '$')
1539** return NULL
1540**
1541** If the JSON_ABPATH flag is set and there is only a single PATH, then
1542** allow abbreviated PATH specs that omit the leading "$".
drh987eb1f2015-08-17 15:17:37 +00001543*/
1544static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001545 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001546 int argc,
1547 sqlite3_value **argv
1548){
drh3fb153c2017-05-11 16:49:59 +00001549 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001550 JsonNode *pNode;
1551 const char *zPath;
drhdaefcd92022-01-08 15:37:13 +00001552 int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx));
drh3ad93bb2015-08-29 19:41:45 +00001553 JsonString jx;
drh3ad93bb2015-08-29 19:41:45 +00001554
1555 if( argc<2 ) return;
drhdc60c682022-01-08 15:05:53 +00001556 p = jsonParseCached(ctx, argv, (flags & JSON_NULLERR)!=0 ? 0 : ctx);
drh338b1fd2022-01-07 17:08:48 +00001557 if( p==0 ){
1558 /* If the form is "json_nextract(IN,'$')" and IN is not well-formed JSON,
1559 ** then return IN as a quoted JSON string. */
drhdc60c682022-01-08 15:05:53 +00001560 if( (flags & JSON_NULLERR)!=0
drh338b1fd2022-01-07 17:08:48 +00001561 && argc==2
1562 && (zPath = (const char*)sqlite3_value_text(argv[1]))!=0
1563 && zPath[0]=='$' && zPath[1]==0
1564 ){
1565 jsonQuoteFunc(ctx, argc, argv);
1566 }
1567 return;
1568 }
drh12b9fa92022-01-07 15:47:12 +00001569 if( argc==2 ){
1570 /* With a single PATH argument, the return is the unquoted SQL value */
1571 zPath = (const char*)sqlite3_value_text(argv[1]);
drhdc60c682022-01-08 15:05:53 +00001572 if( zPath && zPath[0]!='$' && zPath[0]!=0 && (flags & JSON_ABPATH)!=0 ){
1573 /* The -> and ->> operators accept abbreviated PATH arguments. This
1574 ** is mostly for compatibility with PostgreSQL, but also for convenience.
1575 **
1576 ** NUMBER ==> $[NUMBER] // PG compatible
1577 ** LABEL ==> $.LABEL // PG compatible
1578 ** [NUMBER] ==> $[NUMBER] // Not PG. Purely for convenience
drh12b9fa92022-01-07 15:47:12 +00001579 */
1580 jsonInit(&jx, ctx);
drhdaefcd92022-01-08 15:37:13 +00001581 if( sqlite3Isdigit(zPath[0]) ){
drh12b9fa92022-01-07 15:47:12 +00001582 jsonAppendRaw(&jx, "$[", 2);
1583 jsonAppendRaw(&jx, zPath, (int)strlen(zPath));
1584 jsonAppendRaw(&jx, "]", 2);
1585 }else{
1586 jsonAppendRaw(&jx, "$.", 1 + (zPath[0]!='['));
1587 jsonAppendRaw(&jx, zPath, (int)strlen(zPath));
1588 jsonAppendChar(&jx, 0);
1589 }
drhdc60c682022-01-08 15:05:53 +00001590 pNode = jx.bErr ? 0 : jsonLookup(p, jx.zBuf, 0, ctx);
drh12b9fa92022-01-07 15:47:12 +00001591 jsonReset(&jx);
1592 }else{
1593 pNode = jsonLookup(p, zPath, 0, ctx);
1594 }
1595 if( p->nErr ) return;
1596 if( pNode ) jsonReturn(pNode, ctx, 0);
1597 }else{
1598 /* Two or more PATH arguments results in a JSON array with each
1599 ** element of the array being the value selected by one of the PATHs */
1600 int i;
1601 jsonInit(&jx, ctx);
1602 jsonAppendChar(&jx, '[');
1603 for(i=1; i<argc; i++){
1604 zPath = (const char*)sqlite3_value_text(argv[i]);
1605 pNode = jsonLookup(p, zPath, 0, ctx);
1606 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001607 jsonAppendSeparator(&jx);
1608 if( pNode ){
1609 jsonRenderNode(pNode, &jx, 0);
1610 }else{
1611 jsonAppendRaw(&jx, "null", 4);
1612 }
drh3ad93bb2015-08-29 19:41:45 +00001613 }
drh12b9fa92022-01-07 15:47:12 +00001614 if( i==argc ){
1615 jsonAppendChar(&jx, ']');
1616 jsonResult(&jx);
1617 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1618 }
1619 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001620 }
drh987eb1f2015-08-17 15:17:37 +00001621}
1622
drh633647a2017-03-22 21:24:31 +00001623/* This is the RFC 7396 MergePatch algorithm.
1624*/
1625static JsonNode *jsonMergePatch(
1626 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001627 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001628 JsonNode *pPatch /* The PATCH */
1629){
drh0002d242017-03-23 00:46:15 +00001630 u32 i, j;
1631 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001632 JsonNode *pTarget;
1633 if( pPatch->eType!=JSON_OBJECT ){
1634 return pPatch;
1635 }
1636 assert( iTarget>=0 && iTarget<pParse->nNode );
1637 pTarget = &pParse->aNode[iTarget];
1638 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1639 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001640 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001641 return pPatch;
1642 }
drhbb7aa2d2017-03-23 00:13:52 +00001643 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001644 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001645 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001646 const char *zKey;
1647 assert( pPatch[i].eType==JSON_STRING );
1648 assert( pPatch[i].jnFlags & JNODE_LABEL );
drh285f2ef2021-10-15 16:15:04 +00001649 assert( pPatch[i].eU==1 );
drh633647a2017-03-22 21:24:31 +00001650 nKey = pPatch[i].n;
1651 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001652 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001653 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1654 assert( pTarget[j].eType==JSON_STRING );
1655 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001656 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001657 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1658 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001659 if( pPatch[i+1].eType==JSON_NULL ){
1660 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1661 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001662 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001663 if( pNew==0 ) return 0;
1664 pTarget = &pParse->aNode[iTarget];
1665 if( pNew!=&pTarget[j+1] ){
drha2852ac2021-11-15 01:45:11 +00001666 assert( pTarget[j+1].eU==0
1667 || pTarget[j+1].eU==1
1668 || pTarget[j+1].eU==2 );
drh285f2ef2021-10-15 16:15:04 +00001669 testcase( pTarget[j+1].eU==1 );
drha2852ac2021-11-15 01:45:11 +00001670 testcase( pTarget[j+1].eU==2 );
drh285f2ef2021-10-15 16:15:04 +00001671 VVA( pTarget[j+1].eU = 5 );
drh633647a2017-03-22 21:24:31 +00001672 pTarget[j+1].u.pPatch = pNew;
1673 pTarget[j+1].jnFlags |= JNODE_PATCH;
1674 }
1675 }
1676 break;
1677 }
1678 }
drhbb7aa2d2017-03-23 00:13:52 +00001679 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001680 int iStart, iPatch;
1681 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1682 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1683 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1684 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001685 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001686 pTarget = &pParse->aNode[iTarget];
drh8b554e22021-10-20 20:22:37 +00001687 assert( pParse->aNode[iRoot].eU==0 || pParse->aNode[iRoot].eU==2 );
1688 testcase( pParse->aNode[iRoot].eU==2 );
drhbb7aa2d2017-03-23 00:13:52 +00001689 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
drh285f2ef2021-10-15 16:15:04 +00001690 VVA( pParse->aNode[iRoot].eU = 2 );
drhbb7aa2d2017-03-23 00:13:52 +00001691 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1692 iRoot = iStart;
drh285f2ef2021-10-15 16:15:04 +00001693 assert( pParse->aNode[iPatch].eU==0 );
1694 VVA( pParse->aNode[iPatch].eU = 5 );
drh633647a2017-03-22 21:24:31 +00001695 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1696 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1697 }
1698 }
1699 return pTarget;
1700}
1701
1702/*
1703** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1704** object that is the result of running the RFC 7396 MergePatch() algorithm
1705** on the two arguments.
1706*/
drh37f03df2017-03-23 20:33:49 +00001707static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001708 sqlite3_context *ctx,
1709 int argc,
1710 sqlite3_value **argv
1711){
1712 JsonParse x; /* The JSON that is being patched */
1713 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001714 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001715
drh9dbf96b2022-01-06 01:40:09 +00001716 UNUSED_PARAMETER(argc);
drh633647a2017-03-22 21:24:31 +00001717 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1718 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1719 jsonParseReset(&x);
1720 return;
1721 }
drhbb7aa2d2017-03-23 00:13:52 +00001722 pResult = jsonMergePatch(&x, 0, y.aNode);
1723 assert( pResult!=0 || x.oom );
1724 if( pResult ){
1725 jsonReturnJson(pResult, ctx, 0);
1726 }else{
1727 sqlite3_result_error_nomem(ctx);
1728 }
drh633647a2017-03-22 21:24:31 +00001729 jsonParseReset(&x);
1730 jsonParseReset(&y);
1731}
1732
1733
drh987eb1f2015-08-17 15:17:37 +00001734/*
1735** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1736** object that contains all name/value given in arguments. Or if any name
1737** is not a string or if any value is a BLOB, throw an error.
1738*/
1739static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001740 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001741 int argc,
1742 sqlite3_value **argv
1743){
1744 int i;
drh505ad2c2015-08-21 17:33:11 +00001745 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001746 const char *z;
1747 u32 n;
1748
1749 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001750 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001751 "of arguments", -1);
1752 return;
1753 }
drhbc8f0922015-08-22 19:39:04 +00001754 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001755 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001756 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001757 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001758 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001759 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001760 return;
1761 }
drhd0960592015-08-17 21:22:32 +00001762 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001763 z = (const char*)sqlite3_value_text(argv[i]);
1764 n = (u32)sqlite3_value_bytes(argv[i]);
1765 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001766 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001767 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001768 }
drhd0960592015-08-17 21:22:32 +00001769 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001770 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001771 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001772}
1773
1774
1775/*
drh301eecc2015-08-17 20:14:19 +00001776** json_remove(JSON, PATH, ...)
1777**
drh3ad93bb2015-08-29 19:41:45 +00001778** Remove the named elements from JSON and return the result. malformed
1779** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001780*/
1781static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001782 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001783 int argc,
1784 sqlite3_value **argv
1785){
1786 JsonParse x; /* The parse */
1787 JsonNode *pNode;
1788 const char *zPath;
1789 u32 i;
1790
1791 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001792 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001793 assert( x.nNode );
1794 for(i=1; i<(u32)argc; i++){
1795 zPath = (const char*)sqlite3_value_text(argv[i]);
1796 if( zPath==0 ) goto remove_done;
1797 pNode = jsonLookup(&x, zPath, 0, ctx);
1798 if( x.nErr ) goto remove_done;
1799 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1800 }
1801 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1802 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001803 }
drha7714022015-08-29 00:54:49 +00001804remove_done:
drh505ad2c2015-08-21 17:33:11 +00001805 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001806}
1807
1808/*
1809** json_replace(JSON, PATH, VALUE, ...)
1810**
1811** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001812** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001813*/
1814static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001815 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001816 int argc,
1817 sqlite3_value **argv
1818){
1819 JsonParse x; /* The parse */
1820 JsonNode *pNode;
1821 const char *zPath;
1822 u32 i;
1823
1824 if( argc<1 ) return;
1825 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001826 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001827 return;
1828 }
drhbc8f0922015-08-22 19:39:04 +00001829 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001830 assert( x.nNode );
1831 for(i=1; i<(u32)argc; i+=2){
1832 zPath = (const char*)sqlite3_value_text(argv[i]);
1833 pNode = jsonLookup(&x, zPath, 0, ctx);
1834 if( x.nErr ) goto replace_err;
1835 if( pNode ){
drh285f2ef2021-10-15 16:15:04 +00001836 assert( pNode->eU==0 || pNode->eU==1 || pNode->eU==4 );
drh9dbf96b2022-01-06 01:40:09 +00001837 testcase( pNode->eU!=0 && pNode->eU!=1 );
drha8f39a92015-09-21 22:53:16 +00001838 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh285f2ef2021-10-15 16:15:04 +00001839 VVA( pNode->eU = 4 );
drh633647a2017-03-22 21:24:31 +00001840 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001841 }
drha8f39a92015-09-21 22:53:16 +00001842 }
1843 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh285f2ef2021-10-15 16:15:04 +00001844 assert( x.aNode[0].eU==4 );
drh633647a2017-03-22 21:24:31 +00001845 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001846 }else{
1847 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001848 }
drha7714022015-08-29 00:54:49 +00001849replace_err:
drh505ad2c2015-08-21 17:33:11 +00001850 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001851}
drh505ad2c2015-08-21 17:33:11 +00001852
drhdc60c682022-01-08 15:05:53 +00001853
drh52216ad2015-08-18 02:28:03 +00001854/*
1855** json_set(JSON, PATH, VALUE, ...)
1856**
1857** Set the value at PATH to VALUE. Create the PATH if it does not already
1858** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001859** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001860**
1861** json_insert(JSON, PATH, VALUE, ...)
1862**
1863** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001864** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001865*/
1866static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001867 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001868 int argc,
1869 sqlite3_value **argv
1870){
1871 JsonParse x; /* The parse */
1872 JsonNode *pNode;
1873 const char *zPath;
1874 u32 i;
1875 int bApnd;
drh9dbf96b2022-01-06 01:40:09 +00001876 int bIsSet = sqlite3_user_data(ctx)!=0;
drh52216ad2015-08-18 02:28:03 +00001877
1878 if( argc<1 ) return;
1879 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001880 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001881 return;
1882 }
drhbc8f0922015-08-22 19:39:04 +00001883 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001884 assert( x.nNode );
1885 for(i=1; i<(u32)argc; i+=2){
1886 zPath = (const char*)sqlite3_value_text(argv[i]);
1887 bApnd = 0;
1888 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1889 if( x.oom ){
1890 sqlite3_result_error_nomem(ctx);
1891 goto jsonSetDone;
1892 }else if( x.nErr ){
1893 goto jsonSetDone;
1894 }else if( pNode && (bApnd || bIsSet) ){
drh9dbf96b2022-01-06 01:40:09 +00001895 testcase( pNode->eU!=0 && pNode->eU!=1 && pNode->eU!=4 );
drh285f2ef2021-10-15 16:15:04 +00001896 assert( pNode->eU!=3 || pNode->eU!=5 );
1897 VVA( pNode->eU = 4 );
drha8f39a92015-09-21 22:53:16 +00001898 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001899 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001900 }
drha8f39a92015-09-21 22:53:16 +00001901 }
1902 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh285f2ef2021-10-15 16:15:04 +00001903 assert( x.aNode[0].eU==4 );
drh633647a2017-03-22 21:24:31 +00001904 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001905 }else{
1906 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001907 }
drhbc8f0922015-08-22 19:39:04 +00001908jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001909 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001910}
drh301eecc2015-08-17 20:14:19 +00001911
1912/*
drh987eb1f2015-08-17 15:17:37 +00001913** json_type(JSON)
drha4e4e182022-01-07 16:03:00 +00001914** json_ntype(JSON)
drh987eb1f2015-08-17 15:17:37 +00001915** json_type(JSON, PATH)
1916**
drha4e4e182022-01-07 16:03:00 +00001917** Return the top-level "type" of a JSON string. json_type() raises an
1918** error if either the JSON or PATH inputs are not well-formed. json_ntype()
1919** works like the one-argument version of json_type() except that it
1920** returns NULL if the JSON argument is not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001921*/
1922static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001923 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001924 int argc,
1925 sqlite3_value **argv
1926){
drhe35fc302018-08-30 01:52:10 +00001927 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001928 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001929 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001930
drhdaefcd92022-01-08 15:37:13 +00001931 p = jsonParseCached(ctx, argv, sqlite3_user_data(ctx)!=0 ? 0 : ctx);
drhe35fc302018-08-30 01:52:10 +00001932 if( p==0 ) return;
drha8f39a92015-09-21 22:53:16 +00001933 if( argc==2 ){
1934 zPath = (const char*)sqlite3_value_text(argv[1]);
drhe35fc302018-08-30 01:52:10 +00001935 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001936 }else{
drhe35fc302018-08-30 01:52:10 +00001937 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001938 }
1939 if( pNode ){
1940 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001941 }
drh987eb1f2015-08-17 15:17:37 +00001942}
drh5634cc02015-08-17 11:28:03 +00001943
drhbc8f0922015-08-22 19:39:04 +00001944/*
1945** json_valid(JSON)
1946**
drh3ad93bb2015-08-29 19:41:45 +00001947** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1948** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001949*/
1950static void jsonValidFunc(
1951 sqlite3_context *ctx,
1952 int argc,
1953 sqlite3_value **argv
1954){
drhe35fc302018-08-30 01:52:10 +00001955 JsonParse *p; /* The parse */
drh9dbf96b2022-01-06 01:40:09 +00001956 UNUSED_PARAMETER(argc);
drhe35fc302018-08-30 01:52:10 +00001957 p = jsonParseCached(ctx, argv, 0);
1958 sqlite3_result_int(ctx, p!=0);
drhbc8f0922015-08-22 19:39:04 +00001959}
1960
drhff135ae2015-12-30 01:07:02 +00001961
1962/****************************************************************************
1963** Aggregate SQL function implementations
1964****************************************************************************/
1965/*
1966** json_group_array(VALUE)
1967**
1968** Return a JSON array composed of all values in the aggregate.
1969*/
1970static void jsonArrayStep(
1971 sqlite3_context *ctx,
1972 int argc,
1973 sqlite3_value **argv
1974){
1975 JsonString *pStr;
drh9dbf96b2022-01-06 01:40:09 +00001976 UNUSED_PARAMETER(argc);
drhff135ae2015-12-30 01:07:02 +00001977 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1978 if( pStr ){
1979 if( pStr->zBuf==0 ){
1980 jsonInit(pStr, ctx);
1981 jsonAppendChar(pStr, '[');
drhfab5b072019-09-14 00:21:34 +00001982 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00001983 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00001984 }
dan8505d732021-04-14 12:11:39 +00001985 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00001986 jsonAppendValue(pStr, argv[0]);
1987 }
1988}
drh8be47a72018-07-05 20:05:29 +00001989static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001990 JsonString *pStr;
1991 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1992 if( pStr ){
1993 pStr->pCtx = ctx;
1994 jsonAppendChar(pStr, ']');
1995 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001996 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001997 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001998 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001999 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00002000 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
2001 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00002002 }else{
mistachkined008ec2018-09-12 01:05:26 +00002003 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00002004 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00002005 }
2006 }else{
2007 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
2008 }
2009 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
2010}
drh8be47a72018-07-05 20:05:29 +00002011static void jsonArrayValue(sqlite3_context *ctx){
2012 jsonArrayCompute(ctx, 0);
2013}
2014static void jsonArrayFinal(sqlite3_context *ctx){
2015 jsonArrayCompute(ctx, 1);
2016}
2017
2018#ifndef SQLITE_OMIT_WINDOWFUNC
2019/*
2020** This method works for both json_group_array() and json_group_object().
2021** It works by removing the first element of the group by searching forward
2022** to the first comma (",") that is not within a string and deleting all
2023** text through that comma.
2024*/
2025static void jsonGroupInverse(
2026 sqlite3_context *ctx,
2027 int argc,
2028 sqlite3_value **argv
2029){
drhe39f3882019-09-21 17:31:03 +00002030 unsigned int i;
drh8be47a72018-07-05 20:05:29 +00002031 int inStr = 0;
drhfab5b072019-09-14 00:21:34 +00002032 int nNest = 0;
drh8be47a72018-07-05 20:05:29 +00002033 char *z;
drhfab5b072019-09-14 00:21:34 +00002034 char c;
drh8be47a72018-07-05 20:05:29 +00002035 JsonString *pStr;
drh9dbf96b2022-01-06 01:40:09 +00002036 UNUSED_PARAMETER(argc);
2037 UNUSED_PARAMETER(argv);
drh8be47a72018-07-05 20:05:29 +00002038 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drh491d4c82018-07-07 20:23:46 +00002039#ifdef NEVER
drhfd4b7282018-07-07 19:47:21 +00002040 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
2041 ** always have been called to initalize it */
2042 if( NEVER(!pStr) ) return;
drh491d4c82018-07-07 20:23:46 +00002043#endif
drh8be47a72018-07-05 20:05:29 +00002044 z = pStr->zBuf;
drh0e5cd342021-04-13 01:12:32 +00002045 for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
drhfab5b072019-09-14 00:21:34 +00002046 if( c=='"' ){
drh8be47a72018-07-05 20:05:29 +00002047 inStr = !inStr;
drhfab5b072019-09-14 00:21:34 +00002048 }else if( c=='\\' ){
drh8be47a72018-07-05 20:05:29 +00002049 i++;
drhfab5b072019-09-14 00:21:34 +00002050 }else if( !inStr ){
2051 if( c=='{' || c=='[' ) nNest++;
2052 if( c=='}' || c==']' ) nNest--;
drh8be47a72018-07-05 20:05:29 +00002053 }
2054 }
drh0e5cd342021-04-13 01:12:32 +00002055 if( i<pStr->nUsed ){
2056 pStr->nUsed -= i;
2057 memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
2058 z[pStr->nUsed] = 0;
2059 }else{
2060 pStr->nUsed = 1;
2061 }
drh8be47a72018-07-05 20:05:29 +00002062}
2063#else
2064# define jsonGroupInverse 0
2065#endif
2066
drhff135ae2015-12-30 01:07:02 +00002067
2068/*
2069** json_group_obj(NAME,VALUE)
2070**
2071** Return a JSON object composed of all names and values in the aggregate.
2072*/
2073static void jsonObjectStep(
2074 sqlite3_context *ctx,
2075 int argc,
2076 sqlite3_value **argv
2077){
2078 JsonString *pStr;
2079 const char *z;
2080 u32 n;
drh9dbf96b2022-01-06 01:40:09 +00002081 UNUSED_PARAMETER(argc);
drhff135ae2015-12-30 01:07:02 +00002082 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
2083 if( pStr ){
2084 if( pStr->zBuf==0 ){
2085 jsonInit(pStr, ctx);
2086 jsonAppendChar(pStr, '{');
drhfab5b072019-09-14 00:21:34 +00002087 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00002088 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00002089 }
drhd2f55772021-05-28 12:15:19 +00002090 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00002091 z = (const char*)sqlite3_value_text(argv[0]);
2092 n = (u32)sqlite3_value_bytes(argv[0]);
2093 jsonAppendString(pStr, z, n);
2094 jsonAppendChar(pStr, ':');
2095 jsonAppendValue(pStr, argv[1]);
2096 }
2097}
drh8be47a72018-07-05 20:05:29 +00002098static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00002099 JsonString *pStr;
2100 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
2101 if( pStr ){
2102 jsonAppendChar(pStr, '}');
2103 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00002104 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00002105 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00002106 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00002107 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00002108 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
2109 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00002110 }else{
mistachkined008ec2018-09-12 01:05:26 +00002111 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00002112 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00002113 }
2114 }else{
2115 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
2116 }
2117 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
2118}
drh8be47a72018-07-05 20:05:29 +00002119static void jsonObjectValue(sqlite3_context *ctx){
2120 jsonObjectCompute(ctx, 0);
2121}
2122static void jsonObjectFinal(sqlite3_context *ctx){
2123 jsonObjectCompute(ctx, 1);
2124}
2125
drhff135ae2015-12-30 01:07:02 +00002126
2127
drhd2975922015-08-29 17:22:33 +00002128#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00002129/****************************************************************************
2130** The json_each virtual table
2131****************************************************************************/
2132typedef struct JsonEachCursor JsonEachCursor;
2133struct JsonEachCursor {
2134 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00002135 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00002136 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00002137 u32 i; /* Index in sParse.aNode[] of current row */
2138 u32 iEnd; /* EOF when i equals or exceeds this value */
2139 u8 eType; /* Type of top-level element */
2140 u8 bRecursive; /* True for json_tree(). False for json_each() */
2141 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00002142 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00002143 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00002144};
2145
2146/* Constructor for the json_each virtual table */
2147static int jsonEachConnect(
2148 sqlite3 *db,
2149 void *pAux,
2150 int argc, const char *const*argv,
2151 sqlite3_vtab **ppVtab,
2152 char **pzErr
2153){
2154 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00002155 int rc;
drhcb6c6c62015-08-19 22:47:17 +00002156
2157/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00002158#define JEACH_KEY 0
2159#define JEACH_VALUE 1
2160#define JEACH_TYPE 2
2161#define JEACH_ATOM 3
2162#define JEACH_ID 4
2163#define JEACH_PARENT 5
2164#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00002165#define JEACH_PATH 7
drh43579192018-11-16 16:04:50 +00002166/* The xBestIndex method assumes that the JSON and ROOT columns are
2167** the last two columns in the table. Should this ever changes, be
2168** sure to update the xBestIndex method. */
drh383de692015-09-10 17:20:57 +00002169#define JEACH_JSON 8
2170#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00002171
drh9dbf96b2022-01-06 01:40:09 +00002172 UNUSED_PARAMETER(pzErr);
2173 UNUSED_PARAMETER(argv);
2174 UNUSED_PARAMETER(argc);
2175 UNUSED_PARAMETER(pAux);
drh505ad2c2015-08-21 17:33:11 +00002176 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00002177 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2178 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00002179 if( rc==SQLITE_OK ){
2180 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2181 if( pNew==0 ) return SQLITE_NOMEM;
2182 memset(pNew, 0, sizeof(*pNew));
drh2b1c2aa2020-01-07 19:45:40 +00002183 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
drh505ad2c2015-08-21 17:33:11 +00002184 }
2185 return rc;
drhcb6c6c62015-08-19 22:47:17 +00002186}
2187
2188/* destructor for json_each virtual table */
2189static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2190 sqlite3_free(pVtab);
2191 return SQLITE_OK;
2192}
2193
drh505ad2c2015-08-21 17:33:11 +00002194/* constructor for a JsonEachCursor object for json_each(). */
2195static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00002196 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00002197
drh9dbf96b2022-01-06 01:40:09 +00002198 UNUSED_PARAMETER(p);
drhcb6c6c62015-08-19 22:47:17 +00002199 pCur = sqlite3_malloc( sizeof(*pCur) );
2200 if( pCur==0 ) return SQLITE_NOMEM;
2201 memset(pCur, 0, sizeof(*pCur));
2202 *ppCursor = &pCur->base;
2203 return SQLITE_OK;
2204}
2205
drh505ad2c2015-08-21 17:33:11 +00002206/* constructor for a JsonEachCursor object for json_tree(). */
2207static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2208 int rc = jsonEachOpenEach(p, ppCursor);
2209 if( rc==SQLITE_OK ){
2210 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2211 pCur->bRecursive = 1;
2212 }
2213 return rc;
2214}
2215
drhcb6c6c62015-08-19 22:47:17 +00002216/* Reset a JsonEachCursor back to its original state. Free any memory
2217** held. */
2218static void jsonEachCursorReset(JsonEachCursor *p){
2219 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002220 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002221 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002222 p->iRowid = 0;
2223 p->i = 0;
2224 p->iEnd = 0;
2225 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002226 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002227 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002228}
2229
2230/* Destructor for a jsonEachCursor object */
2231static int jsonEachClose(sqlite3_vtab_cursor *cur){
2232 JsonEachCursor *p = (JsonEachCursor*)cur;
2233 jsonEachCursorReset(p);
2234 sqlite3_free(cur);
2235 return SQLITE_OK;
2236}
2237
2238/* Return TRUE if the jsonEachCursor object has been advanced off the end
2239** of the JSON object */
2240static int jsonEachEof(sqlite3_vtab_cursor *cur){
2241 JsonEachCursor *p = (JsonEachCursor*)cur;
2242 return p->i >= p->iEnd;
2243}
2244
drh505ad2c2015-08-21 17:33:11 +00002245/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002246static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002247 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002248 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002249 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2250 p->i++;
drh4af352d2015-08-21 20:02:48 +00002251 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002252 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002253 u32 iUp = p->sParse.aUp[p->i];
2254 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002255 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002256 if( pUp->eType==JSON_ARRAY ){
drh285f2ef2021-10-15 16:15:04 +00002257 assert( pUp->eU==0 || pUp->eU==3 );
drh9dbf96b2022-01-06 01:40:09 +00002258 testcase( pUp->eU==3 );
drh285f2ef2021-10-15 16:15:04 +00002259 VVA( pUp->eU = 3 );
drh8784eca2015-08-23 02:42:30 +00002260 if( iUp==p->i-1 ){
2261 pUp->u.iKey = 0;
2262 }else{
2263 pUp->u.iKey++;
2264 }
drh4af352d2015-08-21 20:02:48 +00002265 }
2266 }
drh505ad2c2015-08-21 17:33:11 +00002267 }else{
drh4af352d2015-08-21 20:02:48 +00002268 switch( p->eType ){
2269 case JSON_ARRAY: {
2270 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2271 p->iRowid++;
2272 break;
2273 }
2274 case JSON_OBJECT: {
2275 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2276 p->iRowid++;
2277 break;
2278 }
2279 default: {
2280 p->i = p->iEnd;
2281 break;
2282 }
drh505ad2c2015-08-21 17:33:11 +00002283 }
2284 }
2285 return SQLITE_OK;
2286}
2287
drh4af352d2015-08-21 20:02:48 +00002288/* Append the name of the path for element i to pStr
2289*/
2290static void jsonEachComputePath(
2291 JsonEachCursor *p, /* The cursor */
2292 JsonString *pStr, /* Write the path here */
2293 u32 i /* Path to this element */
2294){
2295 JsonNode *pNode, *pUp;
2296 u32 iUp;
2297 if( i==0 ){
2298 jsonAppendChar(pStr, '$');
2299 return;
drhcb6c6c62015-08-19 22:47:17 +00002300 }
drh4af352d2015-08-21 20:02:48 +00002301 iUp = p->sParse.aUp[i];
2302 jsonEachComputePath(p, pStr, iUp);
2303 pNode = &p->sParse.aNode[i];
2304 pUp = &p->sParse.aNode[iUp];
2305 if( pUp->eType==JSON_ARRAY ){
drh285f2ef2021-10-15 16:15:04 +00002306 assert( pUp->eU==3 || (pUp->eU==0 && pUp->u.iKey==0) );
2307 testcase( pUp->eU==0 );
drh4af352d2015-08-21 20:02:48 +00002308 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2309 }else{
2310 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002311 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002312 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002313 assert( pNode->jnFlags & JNODE_LABEL );
drh285f2ef2021-10-15 16:15:04 +00002314 assert( pNode->eU==1 );
drh4af352d2015-08-21 20:02:48 +00002315 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2316 }
drhcb6c6c62015-08-19 22:47:17 +00002317}
2318
2319/* Return the value of a column */
2320static int jsonEachColumn(
2321 sqlite3_vtab_cursor *cur, /* The cursor */
2322 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2323 int i /* Which column to return */
2324){
2325 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002326 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002327 switch( i ){
2328 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002329 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002330 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002331 jsonReturn(pThis, ctx, 0);
2332 }else if( p->eType==JSON_ARRAY ){
2333 u32 iKey;
2334 if( p->bRecursive ){
2335 if( p->iRowid==0 ) break;
drh285f2ef2021-10-15 16:15:04 +00002336 assert( p->sParse.aNode[p->sParse.aUp[p->i]].eU==3 );
drh8784eca2015-08-23 02:42:30 +00002337 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002338 }else{
2339 iKey = p->iRowid;
2340 }
drh6fd5c1e2015-08-21 20:37:12 +00002341 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002342 }
2343 break;
2344 }
2345 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002346 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002347 jsonReturn(pThis, ctx, 0);
2348 break;
2349 }
2350 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002351 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002352 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2353 break;
2354 }
2355 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002356 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002357 if( pThis->eType>=JSON_ARRAY ) break;
2358 jsonReturn(pThis, ctx, 0);
2359 break;
2360 }
2361 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002362 sqlite3_result_int64(ctx,
2363 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002364 break;
2365 }
2366 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002367 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002368 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002369 }
2370 break;
2371 }
drh4af352d2015-08-21 20:02:48 +00002372 case JEACH_FULLKEY: {
2373 JsonString x;
2374 jsonInit(&x, ctx);
2375 if( p->bRecursive ){
2376 jsonEachComputePath(p, &x, p->i);
2377 }else{
drh383de692015-09-10 17:20:57 +00002378 if( p->zRoot ){
2379 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002380 }else{
2381 jsonAppendChar(&x, '$');
2382 }
2383 if( p->eType==JSON_ARRAY ){
2384 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002385 }else if( p->eType==JSON_OBJECT ){
drh285f2ef2021-10-15 16:15:04 +00002386 assert( pThis->eU==1 );
drh4af352d2015-08-21 20:02:48 +00002387 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2388 }
2389 }
2390 jsonResult(&x);
2391 break;
2392 }
drhcb6c6c62015-08-19 22:47:17 +00002393 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002394 if( p->bRecursive ){
2395 JsonString x;
2396 jsonInit(&x, ctx);
2397 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2398 jsonResult(&x);
2399 break;
drh4af352d2015-08-21 20:02:48 +00002400 }
drh383de692015-09-10 17:20:57 +00002401 /* For json_each() path and root are the same so fall through
2402 ** into the root case */
drh08b92082020-08-10 14:18:00 +00002403 /* no break */ deliberate_fall_through
drh383de692015-09-10 17:20:57 +00002404 }
drh6850a632016-11-07 18:18:08 +00002405 default: {
drh383de692015-09-10 17:20:57 +00002406 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002407 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002408 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002409 break;
2410 }
drh3d1d2a92015-09-22 01:15:49 +00002411 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002412 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002413 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2414 break;
2415 }
2416 }
2417 return SQLITE_OK;
2418}
2419
2420/* Return the current rowid value */
2421static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2422 JsonEachCursor *p = (JsonEachCursor*)cur;
2423 *pRowid = p->iRowid;
2424 return SQLITE_OK;
2425}
2426
2427/* The query strategy is to look for an equality constraint on the json
2428** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002429** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002430** and 0 otherwise.
2431*/
2432static int jsonEachBestIndex(
2433 sqlite3_vtab *tab,
2434 sqlite3_index_info *pIdxInfo
2435){
drh43579192018-11-16 16:04:50 +00002436 int i; /* Loop counter or computed array index */
2437 int aIdx[2]; /* Index of constraints for JSON and ROOT */
2438 int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
2439 int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
drhcb6c6c62015-08-19 22:47:17 +00002440 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002441
drh43579192018-11-16 16:04:50 +00002442 /* This implementation assumes that JSON and ROOT are the last two
2443 ** columns in the table */
2444 assert( JEACH_ROOT == JEACH_JSON+1 );
drh9dbf96b2022-01-06 01:40:09 +00002445 UNUSED_PARAMETER(tab);
drh43579192018-11-16 16:04:50 +00002446 aIdx[0] = aIdx[1] = -1;
drhcb6c6c62015-08-19 22:47:17 +00002447 pConstraint = pIdxInfo->aConstraint;
2448 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
drh43579192018-11-16 16:04:50 +00002449 int iCol;
2450 int iMask;
2451 if( pConstraint->iColumn < JEACH_JSON ) continue;
2452 iCol = pConstraint->iColumn - JEACH_JSON;
2453 assert( iCol==0 || iCol==1 );
drh285f2ef2021-10-15 16:15:04 +00002454 testcase( iCol==0 );
drh43579192018-11-16 16:04:50 +00002455 iMask = 1 << iCol;
2456 if( pConstraint->usable==0 ){
2457 unusableMask |= iMask;
2458 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
2459 aIdx[iCol] = i;
2460 idxMask |= iMask;
drhcb6c6c62015-08-19 22:47:17 +00002461 }
2462 }
drh43579192018-11-16 16:04:50 +00002463 if( (unusableMask & ~idxMask)!=0 ){
2464 /* If there are any unusable constraints on JSON or ROOT, then reject
2465 ** this entire plan */
2466 return SQLITE_CONSTRAINT;
2467 }
2468 if( aIdx[0]<0 ){
2469 /* No JSON input. Leave estimatedCost at the huge value that it was
2470 ** initialized to to discourage the query planner from selecting this
2471 ** plan. */
drhcb6c6c62015-08-19 22:47:17 +00002472 pIdxInfo->idxNum = 0;
drhcb6c6c62015-08-19 22:47:17 +00002473 }else{
drh505ad2c2015-08-21 17:33:11 +00002474 pIdxInfo->estimatedCost = 1.0;
drh43579192018-11-16 16:04:50 +00002475 i = aIdx[0];
2476 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
2477 pIdxInfo->aConstraintUsage[i].omit = 1;
2478 if( aIdx[1]<0 ){
2479 pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
drhcb6c6c62015-08-19 22:47:17 +00002480 }else{
drh43579192018-11-16 16:04:50 +00002481 i = aIdx[1];
2482 pIdxInfo->aConstraintUsage[i].argvIndex = 2;
2483 pIdxInfo->aConstraintUsage[i].omit = 1;
2484 pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
drhcb6c6c62015-08-19 22:47:17 +00002485 }
2486 }
2487 return SQLITE_OK;
2488}
2489
2490/* Start a search on a new JSON string */
2491static int jsonEachFilter(
2492 sqlite3_vtab_cursor *cur,
2493 int idxNum, const char *idxStr,
2494 int argc, sqlite3_value **argv
2495){
2496 JsonEachCursor *p = (JsonEachCursor*)cur;
2497 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002498 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002499 sqlite3_int64 n;
2500
drh9dbf96b2022-01-06 01:40:09 +00002501 UNUSED_PARAMETER(idxStr);
2502 UNUSED_PARAMETER(argc);
drhcb6c6c62015-08-19 22:47:17 +00002503 jsonEachCursorReset(p);
2504 if( idxNum==0 ) return SQLITE_OK;
2505 z = (const char*)sqlite3_value_text(argv[0]);
2506 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002507 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002508 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002509 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002510 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002511 if( jsonParse(&p->sParse, 0, p->zJson) ){
2512 int rc = SQLITE_NOMEM;
2513 if( p->sParse.oom==0 ){
2514 sqlite3_free(cur->pVtab->zErrMsg);
2515 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2516 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2517 }
drhcb6c6c62015-08-19 22:47:17 +00002518 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002519 return rc;
2520 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2521 jsonEachCursorReset(p);
2522 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002523 }else{
drh95677942015-09-24 01:06:37 +00002524 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002525 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002526 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002527 zRoot = (const char*)sqlite3_value_text(argv[1]);
2528 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002529 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002530 p->zRoot = sqlite3_malloc64( n+1 );
2531 if( p->zRoot==0 ) return SQLITE_NOMEM;
2532 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002533 if( zRoot[0]!='$' ){
2534 zErr = zRoot;
2535 }else{
2536 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2537 }
2538 if( zErr ){
drha7714022015-08-29 00:54:49 +00002539 sqlite3_free(cur->pVtab->zErrMsg);
2540 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002541 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002542 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2543 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002544 return SQLITE_OK;
2545 }
2546 }else{
2547 pNode = p->sParse.aNode;
2548 }
drh852944e2015-09-10 03:29:11 +00002549 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002550 p->eType = pNode->eType;
2551 if( p->eType>=JSON_ARRAY ){
drh285f2ef2021-10-15 16:15:04 +00002552 assert( pNode->eU==0 );
2553 VVA( pNode->eU = 3 );
drh8784eca2015-08-23 02:42:30 +00002554 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002555 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002556 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002557 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002558 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2559 p->i--;
2560 }
2561 }else{
2562 p->i++;
2563 }
drhcb6c6c62015-08-19 22:47:17 +00002564 }else{
2565 p->iEnd = p->i+1;
2566 }
2567 }
drha8f39a92015-09-21 22:53:16 +00002568 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002569}
2570
2571/* The methods of the json_each virtual table */
2572static sqlite3_module jsonEachModule = {
2573 0, /* iVersion */
2574 0, /* xCreate */
2575 jsonEachConnect, /* xConnect */
2576 jsonEachBestIndex, /* xBestIndex */
2577 jsonEachDisconnect, /* xDisconnect */
2578 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002579 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002580 jsonEachClose, /* xClose - close a cursor */
2581 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002582 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002583 jsonEachEof, /* xEof - check for end of scan */
2584 jsonEachColumn, /* xColumn - read data */
2585 jsonEachRowid, /* xRowid - read data */
2586 0, /* xUpdate */
2587 0, /* xBegin */
2588 0, /* xSync */
2589 0, /* xCommit */
2590 0, /* xRollback */
2591 0, /* xFindMethod */
2592 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002593 0, /* xSavepoint */
2594 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002595 0, /* xRollbackTo */
2596 0 /* xShadowName */
drhcb6c6c62015-08-19 22:47:17 +00002597};
2598
drh505ad2c2015-08-21 17:33:11 +00002599/* The methods of the json_tree virtual table. */
2600static sqlite3_module jsonTreeModule = {
2601 0, /* iVersion */
2602 0, /* xCreate */
2603 jsonEachConnect, /* xConnect */
2604 jsonEachBestIndex, /* xBestIndex */
2605 jsonEachDisconnect, /* xDisconnect */
2606 0, /* xDestroy */
2607 jsonEachOpenTree, /* xOpen - open a cursor */
2608 jsonEachClose, /* xClose - close a cursor */
2609 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002610 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002611 jsonEachEof, /* xEof - check for end of scan */
2612 jsonEachColumn, /* xColumn - read data */
2613 jsonEachRowid, /* xRowid - read data */
2614 0, /* xUpdate */
2615 0, /* xBegin */
2616 0, /* xSync */
2617 0, /* xCommit */
2618 0, /* xRollback */
2619 0, /* xFindMethod */
2620 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002621 0, /* xSavepoint */
2622 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002623 0, /* xRollbackTo */
2624 0 /* xShadowName */
drh505ad2c2015-08-21 17:33:11 +00002625};
drhd2975922015-08-29 17:22:33 +00002626#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh9dbf96b2022-01-06 01:40:09 +00002627#endif /* !defined(SQLITE_OMIT_JSON) */
drh505ad2c2015-08-21 17:33:11 +00002628
drh9dbf96b2022-01-06 01:40:09 +00002629/*
2630** Register JSON functions.
2631*/
2632void sqlite3RegisterJsonFunctions(void){
2633#ifndef SQLITE_OMIT_JSON
2634 static FuncDef aJsonFunc[] = {
drhdaefcd92022-01-08 15:37:13 +00002635 JFUNCTION(json, 1, 0, jsonRemoveFunc),
2636 JFUNCTION(json_array, -1, 0, jsonArrayFunc),
2637 JFUNCTION(json_array_length, 1, 0, jsonArrayLengthFunc),
2638 JFUNCTION(json_array_length, 2, 0, jsonArrayLengthFunc),
2639 JFUNCTION(json_extract, -1, 0, jsonExtractFunc),
2640 JFUNCTION(json_nextract, -1, JSON_NULLERR, jsonExtractFunc),
2641 JFUNCTION(->, 2, JSON_NULLERR|JSON_ABPATH, jsonExtractFunc),
2642 JFUNCTION(->>, 2, JSON_ABPATH, jsonExtractFunc),
2643 JFUNCTION(json_insert, -1, 0, jsonSetFunc),
2644 JFUNCTION(json_ntype, 1, JSON_NULLERR, jsonTypeFunc),
2645 JFUNCTION(json_object, -1, 0, jsonObjectFunc),
2646 JFUNCTION(json_patch, 2, 0, jsonPatchFunc),
2647 JFUNCTION(json_quote, 1, 0, jsonQuoteFunc),
2648 JFUNCTION(json_remove, -1, 0, jsonRemoveFunc),
2649 JFUNCTION(json_replace, -1, 0, jsonReplaceFunc),
2650 JFUNCTION(json_set, -1, JSON_ISSET, jsonSetFunc),
2651 JFUNCTION(json_type, 1, 0, jsonTypeFunc),
2652 JFUNCTION(json_type, 2, 0, jsonTypeFunc),
2653 JFUNCTION(json_valid, 1, 0, jsonValidFunc),
drh301eecc2015-08-17 20:14:19 +00002654#if SQLITE_DEBUG
drhdaefcd92022-01-08 15:37:13 +00002655 JFUNCTION(json_parse, 1, 0, jsonParseFunc),
2656 JFUNCTION(json_test1, 1, 0, jsonTest1Func),
drh301eecc2015-08-17 20:14:19 +00002657#endif
drhdaefcd92022-01-08 15:37:13 +00002658 WAGGREGATE(json_group_array, 1, 0, 0,
drh9dbf96b2022-01-06 01:40:09 +00002659 jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse,
2660 SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS),
drhdaefcd92022-01-08 15:37:13 +00002661 WAGGREGATE(json_group_object, 2, 0, 0,
drh9dbf96b2022-01-06 01:40:09 +00002662 jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse,
2663 SQLITE_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
drh5fa5c102015-08-12 16:49:40 +00002664 };
drh9dbf96b2022-01-06 01:40:09 +00002665 sqlite3InsertBuiltinFuncs(aJsonFunc, ArraySize(aJsonFunc));
2666#endif
2667}
2668
2669#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
2670/*
2671** Register the JSON table-valued functions
2672*/
2673int sqlite3JsonTableFunctions(sqlite3 *db){
2674 int rc = SQLITE_OK;
drh505ad2c2015-08-21 17:33:11 +00002675 static const struct {
drhdaefcd92022-01-08 15:37:13 +00002676 const char *zName;
2677 sqlite3_module *pModule;
drh505ad2c2015-08-21 17:33:11 +00002678 } aMod[] = {
2679 { "json_each", &jsonEachModule },
2680 { "json_tree", &jsonTreeModule },
2681 };
drh9dbf96b2022-01-06 01:40:09 +00002682 int i;
drh505ad2c2015-08-21 17:33:11 +00002683 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2684 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002685 }
drh5fa5c102015-08-12 16:49:40 +00002686 return rc;
2687}
drh9dbf96b2022-01-06 01:40:09 +00002688#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */