blob: 6aa4e97f9dd52384b358d2ae51bf81459b02dd9d [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**
13** This SQLite extension implements JSON functions. The interface is
14** modeled after MySQL JSON functions:
15**
16** https://dev.mysql.com/doc/refman/5.7/en/json.html
17**
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*/
drh50065652015-10-08 19:29:18 +000024#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
drh666d34c2017-01-25 13:54:27 +000025#if !defined(SQLITEINT_H)
drh5fa5c102015-08-12 16:49:40 +000026#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000027#endif
drh5fa5c102015-08-12 16:49:40 +000028SQLITE_EXTENSION_INIT1
29#include <assert.h>
30#include <string.h>
drh987eb1f2015-08-17 15:17:37 +000031#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000032#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000033
drhdf3a9072016-02-11 15:37:18 +000034/* Mark a function parameter as unused, to suppress nuisance compiler
35** warnings. */
36#ifndef UNUSED_PARAM
37# define UNUSED_PARAM(X) (void)(X)
38#endif
drh6fd5c1e2015-08-21 20:37:12 +000039
drh8deb4b82015-10-09 18:21:43 +000040#ifndef LARGEST_INT64
41# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
42# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
43#endif
44
drh08b92082020-08-10 14:18:00 +000045#ifndef deliberate_fall_through
46# define deliberate_fall_through
47#endif
48
dan2e8f5512015-09-17 17:21:09 +000049/*
50** Versions of isspace(), isalnum() and isdigit() to which it is safe
51** to pass signed char values.
52*/
drh49472652015-10-16 15:35:39 +000053#ifdef sqlite3Isdigit
54 /* Use the SQLite core versions if this routine is part of the
55 ** SQLite amalgamation */
drhad875e72016-11-07 13:37:28 +000056# define safe_isdigit(x) sqlite3Isdigit(x)
57# define safe_isalnum(x) sqlite3Isalnum(x)
58# define safe_isxdigit(x) sqlite3Isxdigit(x)
drh49472652015-10-16 15:35:39 +000059#else
60 /* Use the standard library for separate compilation */
61#include <ctype.h> /* amalgamator: keep */
drhad875e72016-11-07 13:37:28 +000062# define safe_isdigit(x) isdigit((unsigned char)(x))
63# define safe_isalnum(x) isalnum((unsigned char)(x))
64# define safe_isxdigit(x) isxdigit((unsigned char)(x))
drh49472652015-10-16 15:35:39 +000065#endif
dan2e8f5512015-09-17 17:21:09 +000066
drh95677942015-09-24 01:06:37 +000067/*
68** Growing our own isspace() routine this way is twice as fast as
69** the library isspace() function, resulting in a 7% overall performance
70** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
71*/
72static const char jsonIsSpace[] = {
drhb9e8f592015-10-16 15:16:06 +000073 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
drh95677942015-09-24 01:06:37 +000074 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
75 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
76 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
89};
90#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
91
drh9a4718f2015-10-10 14:00:37 +000092#ifndef SQLITE_AMALGAMATION
93 /* Unsigned integer types. These are already defined in the sqliteInt.h,
94 ** but the definitions need to be repeated for separate compilation. */
95 typedef sqlite3_uint64 u64;
96 typedef unsigned int u32;
drhff6d50e2017-04-11 18:55:05 +000097 typedef unsigned short int u16;
drh9a4718f2015-10-10 14:00:37 +000098 typedef unsigned char u8;
99#endif
drh5fa5c102015-08-12 16:49:40 +0000100
drh52216ad2015-08-18 02:28:03 +0000101/* Objects */
drh505ad2c2015-08-21 17:33:11 +0000102typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +0000103typedef struct JsonNode JsonNode;
104typedef struct JsonParse JsonParse;
105
drh5634cc02015-08-17 11:28:03 +0000106/* An instance of this object represents a JSON string
107** under construction. Really, this is a generic string accumulator
108** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +0000109*/
drh505ad2c2015-08-21 17:33:11 +0000110struct JsonString {
drh5fa5c102015-08-12 16:49:40 +0000111 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +0000112 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +0000113 u64 nAlloc; /* Bytes of storage available in zBuf[] */
114 u64 nUsed; /* Bytes of zBuf[] currently used */
115 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +0000116 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +0000117 char zSpace[100]; /* Initial static space */
118};
119
drhe9c37f32015-08-15 21:25:36 +0000120/* JSON type values
drhbd0621b2015-08-13 13:54:59 +0000121*/
drhe9c37f32015-08-15 21:25:36 +0000122#define JSON_NULL 0
123#define JSON_TRUE 1
124#define JSON_FALSE 2
125#define JSON_INT 3
126#define JSON_REAL 4
127#define JSON_STRING 5
128#define JSON_ARRAY 6
129#define JSON_OBJECT 7
130
drhf5ddb9c2015-09-11 00:06:41 +0000131/* The "subtype" set for JSON values */
132#define JSON_SUBTYPE 74 /* Ascii for "J" */
133
drh987eb1f2015-08-17 15:17:37 +0000134/*
135** Names of the various JSON types:
136*/
137static const char * const jsonType[] = {
138 "null", "true", "false", "integer", "real", "text", "array", "object"
139};
140
drh301eecc2015-08-17 20:14:19 +0000141/* Bit values for the JsonNode.jnFlag field
142*/
143#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
144#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
145#define JNODE_REMOVE 0x04 /* Do not output */
drh633647a2017-03-22 21:24:31 +0000146#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
147#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
148#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
149#define JNODE_LABEL 0x40 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000150
drh987eb1f2015-08-17 15:17:37 +0000151
drhe9c37f32015-08-15 21:25:36 +0000152/* A single node of parsed JSON
153*/
drhe9c37f32015-08-15 21:25:36 +0000154struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000155 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000156 u8 jnFlags; /* JNODE flags */
drhe9c37f32015-08-15 21:25:36 +0000157 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000158 union {
drh0042a972015-08-18 12:59:58 +0000159 const char *zJContent; /* Content for INT, REAL, and STRING */
160 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000161 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh633647a2017-03-22 21:24:31 +0000162 u32 iReplace; /* Replacement content for JNODE_REPLACE */
163 JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
drh52216ad2015-08-18 02:28:03 +0000164 } u;
drhe9c37f32015-08-15 21:25:36 +0000165};
166
167/* A completely parsed JSON string
168*/
drhe9c37f32015-08-15 21:25:36 +0000169struct JsonParse {
170 u32 nNode; /* Number of slots of aNode[] used */
171 u32 nAlloc; /* Number of slots of aNode[] allocated */
172 JsonNode *aNode; /* Array of nodes containing the parse */
173 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000174 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000175 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000176 u8 nErr; /* Number of errors seen */
drhff6d50e2017-04-11 18:55:05 +0000177 u16 iDepth; /* Nesting depth */
drh3fb153c2017-05-11 16:49:59 +0000178 int nJson; /* Length of the zJson string in bytes */
drhe35fc302018-08-30 01:52:10 +0000179 u32 iHold; /* Replace cache line with the lowest iHold value */
drhe9c37f32015-08-15 21:25:36 +0000180};
181
drhff6d50e2017-04-11 18:55:05 +0000182/*
183** Maximum nesting depth of JSON for this implementation.
184**
185** This limit is needed to avoid a stack overflow in the recursive
186** descent parser. A depth of 2000 is far deeper than any sane JSON
187** should go.
188*/
189#define JSON_MAX_DEPTH 2000
190
drh505ad2c2015-08-21 17:33:11 +0000191/**************************************************************************
192** Utility routines for dealing with JsonString objects
193**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000194
drh505ad2c2015-08-21 17:33:11 +0000195/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000196*/
drh505ad2c2015-08-21 17:33:11 +0000197static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000198 p->zBuf = p->zSpace;
199 p->nAlloc = sizeof(p->zSpace);
200 p->nUsed = 0;
201 p->bStatic = 1;
202}
203
drh505ad2c2015-08-21 17:33:11 +0000204/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000205*/
drh505ad2c2015-08-21 17:33:11 +0000206static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000207 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000208 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000209 jsonZero(p);
210}
211
212
drh505ad2c2015-08-21 17:33:11 +0000213/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000214** initial state.
215*/
drh505ad2c2015-08-21 17:33:11 +0000216static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000217 if( !p->bStatic ) sqlite3_free(p->zBuf);
218 jsonZero(p);
219}
220
221
222/* Report an out-of-memory (OOM) condition
223*/
drh505ad2c2015-08-21 17:33:11 +0000224static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000225 p->bErr = 1;
226 sqlite3_result_error_nomem(p->pCtx);
227 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000228}
229
230/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
231** Return zero on success. Return non-zero on an OOM error
232*/
drh505ad2c2015-08-21 17:33:11 +0000233static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000234 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000235 char *zNew;
236 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000237 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000238 zNew = sqlite3_malloc64(nTotal);
239 if( zNew==0 ){
240 jsonOom(p);
241 return SQLITE_NOMEM;
242 }
drh6fd5c1e2015-08-21 20:37:12 +0000243 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000244 p->zBuf = zNew;
245 p->bStatic = 0;
246 }else{
247 zNew = sqlite3_realloc64(p->zBuf, nTotal);
248 if( zNew==0 ){
249 jsonOom(p);
250 return SQLITE_NOMEM;
251 }
252 p->zBuf = zNew;
253 }
254 p->nAlloc = nTotal;
255 return SQLITE_OK;
256}
257
drh505ad2c2015-08-21 17:33:11 +0000258/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000259*/
drh505ad2c2015-08-21 17:33:11 +0000260static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drhc795e3d2020-05-17 13:47:28 +0000261 if( N==0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000262 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
263 memcpy(p->zBuf+p->nUsed, zIn, N);
264 p->nUsed += N;
265}
266
drh4af352d2015-08-21 20:02:48 +0000267/* Append formatted text (not to exceed N bytes) to the JsonString.
268*/
269static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
270 va_list ap;
271 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
272 va_start(ap, zFormat);
273 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
274 va_end(ap);
275 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
276}
277
drh5634cc02015-08-17 11:28:03 +0000278/* Append a single character
279*/
drh505ad2c2015-08-21 17:33:11 +0000280static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000281 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
282 p->zBuf[p->nUsed++] = c;
283}
284
drh301eecc2015-08-17 20:14:19 +0000285/* Append a comma separator to the output buffer, if the previous
286** character is not '[' or '{'.
287*/
drh505ad2c2015-08-21 17:33:11 +0000288static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000289 char c;
290 if( p->nUsed==0 ) return;
291 c = p->zBuf[p->nUsed-1];
292 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
293}
294
drh505ad2c2015-08-21 17:33:11 +0000295/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000296** under construction. Enclose the string in "..." and escape
297** any double-quotes or backslash characters contained within the
298** string.
299*/
drh505ad2c2015-08-21 17:33:11 +0000300static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000301 u32 i;
drh76baad92021-04-30 16:12:40 +0000302 if( zIn==0 || ((N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0) ) return;
drh5fa5c102015-08-12 16:49:40 +0000303 p->zBuf[p->nUsed++] = '"';
304 for(i=0; i<N; i++){
drh3b7f9a62016-02-04 10:28:57 +0000305 unsigned char c = ((unsigned const char*)zIn)[i];
drh5fa5c102015-08-12 16:49:40 +0000306 if( c=='"' || c=='\\' ){
drh3b7f9a62016-02-04 10:28:57 +0000307 json_simple_escape:
drh4977ccf2015-09-19 11:57:26 +0000308 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000309 p->zBuf[p->nUsed++] = '\\';
drh3b7f9a62016-02-04 10:28:57 +0000310 }else if( c<=0x1f ){
311 static const char aSpecial[] = {
312 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
314 };
315 assert( sizeof(aSpecial)==32 );
316 assert( aSpecial['\b']=='b' );
317 assert( aSpecial['\f']=='f' );
318 assert( aSpecial['\n']=='n' );
319 assert( aSpecial['\r']=='r' );
320 assert( aSpecial['\t']=='t' );
321 if( aSpecial[c] ){
322 c = aSpecial[c];
323 goto json_simple_escape;
324 }
325 if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
326 p->zBuf[p->nUsed++] = '\\';
327 p->zBuf[p->nUsed++] = 'u';
328 p->zBuf[p->nUsed++] = '0';
329 p->zBuf[p->nUsed++] = '0';
330 p->zBuf[p->nUsed++] = '0' + (c>>4);
331 c = "0123456789abcdef"[c&0xf];
drh5fa5c102015-08-12 16:49:40 +0000332 }
333 p->zBuf[p->nUsed++] = c;
334 }
335 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000336 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000337}
338
drhd0960592015-08-17 21:22:32 +0000339/*
340** Append a function parameter value to the JSON string under
341** construction.
342*/
343static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000344 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000345 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000346){
347 switch( sqlite3_value_type(pValue) ){
348 case SQLITE_NULL: {
349 jsonAppendRaw(p, "null", 4);
350 break;
351 }
352 case SQLITE_INTEGER:
353 case SQLITE_FLOAT: {
354 const char *z = (const char*)sqlite3_value_text(pValue);
355 u32 n = (u32)sqlite3_value_bytes(pValue);
356 jsonAppendRaw(p, z, n);
357 break;
358 }
359 case SQLITE_TEXT: {
360 const char *z = (const char*)sqlite3_value_text(pValue);
361 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000362 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000363 jsonAppendRaw(p, z, n);
364 }else{
365 jsonAppendString(p, z, n);
366 }
drhd0960592015-08-17 21:22:32 +0000367 break;
368 }
369 default: {
370 if( p->bErr==0 ){
371 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
drh4a642b62016-02-05 01:55:27 +0000372 p->bErr = 2;
drhd0960592015-08-17 21:22:32 +0000373 jsonReset(p);
374 }
375 break;
376 }
377 }
378}
379
380
drhbd0621b2015-08-13 13:54:59 +0000381/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000382*/
drh505ad2c2015-08-21 17:33:11 +0000383static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000384 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000385 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
386 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
387 SQLITE_UTF8);
388 jsonZero(p);
389 }
390 assert( p->bStatic );
391}
392
drh505ad2c2015-08-21 17:33:11 +0000393/**************************************************************************
394** Utility routines for dealing with JsonNode and JsonParse objects
395**************************************************************************/
396
397/*
398** Return the number of consecutive JsonNode slots need to represent
399** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
400** OBJECT types, the number might be larger.
401**
402** Appended elements are not counted. The value returned is the number
403** by which the JsonNode counter should increment in order to go to the
404** next peer value.
405*/
406static u32 jsonNodeSize(JsonNode *pNode){
407 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
408}
409
410/*
411** Reclaim all memory allocated by a JsonParse object. But do not
412** delete the JsonParse object itself.
413*/
414static void jsonParseReset(JsonParse *pParse){
415 sqlite3_free(pParse->aNode);
416 pParse->aNode = 0;
417 pParse->nNode = 0;
418 pParse->nAlloc = 0;
419 sqlite3_free(pParse->aUp);
420 pParse->aUp = 0;
421}
422
drh5634cc02015-08-17 11:28:03 +0000423/*
drh3fb153c2017-05-11 16:49:59 +0000424** Free a JsonParse object that was obtained from sqlite3_malloc().
425*/
426static void jsonParseFree(JsonParse *pParse){
427 jsonParseReset(pParse);
428 sqlite3_free(pParse);
429}
430
431/*
drh5634cc02015-08-17 11:28:03 +0000432** Convert the JsonNode pNode into a pure JSON string and
433** append to pOut. Subsubstructure is also included. Return
434** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000435*/
drh52216ad2015-08-18 02:28:03 +0000436static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000437 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000438 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000439 sqlite3_value **aReplace /* Replacement values */
440){
drh7d4c94b2021-10-04 22:34:38 +0000441 assert( pNode!=0 );
drh633647a2017-03-22 21:24:31 +0000442 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
drh7d4c94b2021-10-04 22:34:38 +0000443 if( (pNode->jnFlags & JNODE_REPLACE)!=0 && ALWAYS(aReplace!=0) ){
drh633647a2017-03-22 21:24:31 +0000444 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
445 return;
446 }
447 pNode = pNode->u.pPatch;
448 }
drh5634cc02015-08-17 11:28:03 +0000449 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000450 default: {
451 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000452 jsonAppendRaw(pOut, "null", 4);
453 break;
454 }
455 case JSON_TRUE: {
456 jsonAppendRaw(pOut, "true", 4);
457 break;
458 }
459 case JSON_FALSE: {
460 jsonAppendRaw(pOut, "false", 5);
461 break;
462 }
463 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000464 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000465 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000466 break;
467 }
drh08b92082020-08-10 14:18:00 +0000468 /* no break */ deliberate_fall_through
drh5634cc02015-08-17 11:28:03 +0000469 }
470 case JSON_REAL:
471 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000472 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000473 break;
474 }
475 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000476 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000477 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000478 for(;;){
479 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000480 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000481 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000482 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000483 }
drh505ad2c2015-08-21 17:33:11 +0000484 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000485 }
drh52216ad2015-08-18 02:28:03 +0000486 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
487 pNode = &pNode[pNode->u.iAppend];
488 j = 1;
drh5634cc02015-08-17 11:28:03 +0000489 }
490 jsonAppendChar(pOut, ']');
491 break;
492 }
493 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000494 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000495 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000496 for(;;){
497 while( j<=pNode->n ){
498 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
499 jsonAppendSeparator(pOut);
500 jsonRenderNode(&pNode[j], pOut, aReplace);
501 jsonAppendChar(pOut, ':');
drh633647a2017-03-22 21:24:31 +0000502 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000503 }
drh505ad2c2015-08-21 17:33:11 +0000504 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000505 }
drh52216ad2015-08-18 02:28:03 +0000506 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
507 pNode = &pNode[pNode->u.iAppend];
508 j = 1;
drh5634cc02015-08-17 11:28:03 +0000509 }
510 jsonAppendChar(pOut, '}');
511 break;
512 }
drhbd0621b2015-08-13 13:54:59 +0000513 }
drh5634cc02015-08-17 11:28:03 +0000514}
515
516/*
drhf2df7e72015-08-28 20:07:40 +0000517** Return a JsonNode and all its descendents as a JSON string.
518*/
519static void jsonReturnJson(
520 JsonNode *pNode, /* Node to return */
521 sqlite3_context *pCtx, /* Return value for this function */
522 sqlite3_value **aReplace /* Array of replacement values */
523){
524 JsonString s;
525 jsonInit(&s, pCtx);
526 jsonRenderNode(pNode, &s, aReplace);
527 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000528 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000529}
530
531/*
drh48eb03b2019-11-10 11:09:06 +0000532** Translate a single byte of Hex into an integer.
533** This routine only works if h really is a valid hexadecimal
534** character: 0..9a..fA..F
535*/
536static u8 jsonHexToInt(int h){
537 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
538#ifdef SQLITE_EBCDIC
539 h += 9*(1&~(h>>4));
540#else
541 h += 9*(1&(h>>6));
542#endif
543 return (u8)(h & 0xf);
544}
545
546/*
547** Convert a 4-byte hex string into an integer
548*/
549static u32 jsonHexToInt4(const char *z){
550 u32 v;
551 assert( safe_isxdigit(z[0]) );
552 assert( safe_isxdigit(z[1]) );
553 assert( safe_isxdigit(z[2]) );
554 assert( safe_isxdigit(z[3]) );
555 v = (jsonHexToInt(z[0])<<12)
556 + (jsonHexToInt(z[1])<<8)
557 + (jsonHexToInt(z[2])<<4)
558 + jsonHexToInt(z[3]);
559 return v;
560}
561
562/*
drh5634cc02015-08-17 11:28:03 +0000563** Make the JsonNode the return value of the function.
564*/
drhd0960592015-08-17 21:22:32 +0000565static void jsonReturn(
566 JsonNode *pNode, /* Node to return */
567 sqlite3_context *pCtx, /* Return value for this function */
568 sqlite3_value **aReplace /* Array of replacement values */
569){
drh5634cc02015-08-17 11:28:03 +0000570 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000571 default: {
572 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000573 sqlite3_result_null(pCtx);
574 break;
575 }
576 case JSON_TRUE: {
577 sqlite3_result_int(pCtx, 1);
578 break;
579 }
580 case JSON_FALSE: {
581 sqlite3_result_int(pCtx, 0);
582 break;
583 }
drh987eb1f2015-08-17 15:17:37 +0000584 case JSON_INT: {
585 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000586 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000587 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000588 while( z[0]>='0' && z[0]<='9' ){
589 unsigned v = *(z++) - '0';
590 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000591 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000592 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
593 if( v==9 ) goto int_as_real;
594 if( v==8 ){
595 if( pNode->u.zJContent[0]=='-' ){
596 sqlite3_result_int64(pCtx, SMALLEST_INT64);
597 goto int_done;
598 }else{
599 goto int_as_real;
600 }
601 }
602 }
603 i = i*10 + v;
604 }
drh52216ad2015-08-18 02:28:03 +0000605 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000606 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000607 int_done:
608 break;
drhe85e1da2021-10-01 21:01:07 +0000609 int_as_real: ; /* no break */ deliberate_fall_through
drh8deb4b82015-10-09 18:21:43 +0000610 }
611 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000612 double r;
613#ifdef SQLITE_AMALGAMATION
614 const char *z = pNode->u.zJContent;
615 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
616#else
617 r = strtod(pNode->u.zJContent, 0);
618#endif
drh8deb4b82015-10-09 18:21:43 +0000619 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000620 break;
621 }
drh5634cc02015-08-17 11:28:03 +0000622 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000623#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
624 ** json_insert() and json_replace() and those routines do not
625 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000626 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000627 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
628 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000629 }else
630#endif
631 assert( (pNode->jnFlags & JNODE_RAW)==0 );
632 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000633 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000634 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000635 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000636 }else{
637 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000638 u32 i;
639 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000640 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000641 char *zOut;
642 u32 j;
643 zOut = sqlite3_malloc( n+1 );
644 if( zOut==0 ){
645 sqlite3_result_error_nomem(pCtx);
646 break;
647 }
648 for(i=1, j=0; i<n-1; i++){
649 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000650 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000651 zOut[j++] = c;
652 }else{
653 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000654 if( c=='u' ){
drh48eb03b2019-11-10 11:09:06 +0000655 u32 v = jsonHexToInt4(z+i+1);
656 i += 4;
drh80d87402015-08-24 12:42:41 +0000657 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000658 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000659 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000660 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000661 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000662 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000663 }else{
drh48eb03b2019-11-10 11:09:06 +0000664 u32 vlo;
665 if( (v&0xfc00)==0xd800
666 && i<n-6
667 && z[i+1]=='\\'
668 && z[i+2]=='u'
669 && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
670 ){
671 /* We have a surrogate pair */
672 v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
673 i += 6;
674 zOut[j++] = 0xf0 | (v>>18);
675 zOut[j++] = 0x80 | ((v>>12)&0x3f);
676 zOut[j++] = 0x80 | ((v>>6)&0x3f);
677 zOut[j++] = 0x80 | (v&0x3f);
678 }else{
679 zOut[j++] = 0xe0 | (v>>12);
680 zOut[j++] = 0x80 | ((v>>6)&0x3f);
681 zOut[j++] = 0x80 | (v&0x3f);
682 }
drh987eb1f2015-08-17 15:17:37 +0000683 }
684 }else{
685 if( c=='b' ){
686 c = '\b';
687 }else if( c=='f' ){
688 c = '\f';
689 }else if( c=='n' ){
690 c = '\n';
691 }else if( c=='r' ){
692 c = '\r';
693 }else if( c=='t' ){
694 c = '\t';
695 }
696 zOut[j++] = c;
697 }
698 }
699 }
700 zOut[j] = 0;
701 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000702 }
703 break;
704 }
705 case JSON_ARRAY:
706 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000707 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000708 break;
709 }
710 }
drhbd0621b2015-08-13 13:54:59 +0000711}
712
drh95677942015-09-24 01:06:37 +0000713/* Forward reference */
714static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
715
716/*
717** A macro to hint to the compiler that a function should not be
718** inlined.
719*/
720#if defined(__GNUC__)
721# define JSON_NOINLINE __attribute__((noinline))
722#elif defined(_MSC_VER) && _MSC_VER>=1310
723# define JSON_NOINLINE __declspec(noinline)
724#else
725# define JSON_NOINLINE
726#endif
727
728
729static JSON_NOINLINE int jsonParseAddNodeExpand(
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 u32 nNew;
736 JsonNode *pNew;
737 assert( pParse->nNode>=pParse->nAlloc );
738 if( pParse->oom ) return -1;
739 nNew = pParse->nAlloc*2 + 10;
drh2d77d802019-01-08 20:02:48 +0000740 pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
drh95677942015-09-24 01:06:37 +0000741 if( pNew==0 ){
742 pParse->oom = 1;
743 return -1;
744 }
745 pParse->nAlloc = nNew;
746 pParse->aNode = pNew;
747 assert( pParse->nNode<pParse->nAlloc );
748 return jsonParseAddNode(pParse, eType, n, zContent);
749}
750
drh5fa5c102015-08-12 16:49:40 +0000751/*
drhe9c37f32015-08-15 21:25:36 +0000752** Create a new JsonNode instance based on the arguments and append that
753** instance to the JsonParse. Return the index in pParse->aNode[] of the
754** new node, or -1 if a memory allocation fails.
755*/
756static int jsonParseAddNode(
757 JsonParse *pParse, /* Append the node to this object */
758 u32 eType, /* Node type */
759 u32 n, /* Content size or sub-node count */
760 const char *zContent /* Content */
761){
762 JsonNode *p;
drhaa6fe5b2021-10-04 13:18:44 +0000763 if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000764 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000765 }
766 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000767 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000768 p->jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000769 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000770 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000771 return pParse->nNode++;
772}
773
774/*
drhad875e72016-11-07 13:37:28 +0000775** Return true if z[] begins with 4 (or more) hexadecimal digits
776*/
777static int jsonIs4Hex(const char *z){
778 int i;
779 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
780 return 1;
781}
782
783/*
drhe9c37f32015-08-15 21:25:36 +0000784** Parse a single JSON value which begins at pParse->zJson[i]. Return the
785** index of the first character past the end of the value parsed.
786**
787** Return negative for a syntax error. Special cases: return -2 if the
788** first non-whitespace character is '}' and return -3 if the first
789** non-whitespace character is ']'.
790*/
791static int jsonParseValue(JsonParse *pParse, u32 i){
792 char c;
793 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000794 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000795 int x;
drh852944e2015-09-10 03:29:11 +0000796 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000797 const char *z = pParse->zJson;
798 while( safe_isspace(z[i]) ){ i++; }
799 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000800 /* Parse object */
801 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000802 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000803 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000804 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000805 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000806 x = jsonParseValue(pParse, j);
807 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000808 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000809 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000810 return -1;
811 }
drhbe9474e2015-08-22 03:05:54 +0000812 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000813 pNode = &pParse->aNode[pParse->nNode-1];
814 if( pNode->eType!=JSON_STRING ) return -1;
815 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000816 j = x;
drh9fa866a2017-04-08 18:18:22 +0000817 while( safe_isspace(z[j]) ){ j++; }
818 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000819 j++;
820 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000821 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000822 if( x<0 ) return -1;
823 j = x;
drh9fa866a2017-04-08 18:18:22 +0000824 while( safe_isspace(z[j]) ){ j++; }
825 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000826 if( c==',' ) continue;
827 if( c!='}' ) return -1;
828 break;
829 }
drhbc8f0922015-08-22 19:39:04 +0000830 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000831 return j+1;
832 }else if( c=='[' ){
833 /* Parse array */
834 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000835 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000836 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000837 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000838 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000839 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000840 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000841 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000842 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000843 return -1;
844 }
845 j = x;
drh9fa866a2017-04-08 18:18:22 +0000846 while( safe_isspace(z[j]) ){ j++; }
847 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000848 if( c==',' ) continue;
849 if( c!=']' ) return -1;
850 break;
851 }
drhbc8f0922015-08-22 19:39:04 +0000852 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000853 return j+1;
854 }else if( c=='"' ){
855 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000856 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000857 j = i+1;
858 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000859 c = z[j];
drh86715382017-04-13 00:12:32 +0000860 if( (c & ~0x1f)==0 ){
861 /* Control characters are not allowed in strings */
862 return -1;
863 }
drhe9c37f32015-08-15 21:25:36 +0000864 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000865 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000866 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
867 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000868 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000869 jnFlags = JNODE_ESCAPE;
870 }else{
871 return -1;
872 }
drhe9c37f32015-08-15 21:25:36 +0000873 }else if( c=='"' ){
874 break;
875 }
876 j++;
877 }
drh9fa866a2017-04-08 18:18:22 +0000878 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000879 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000880 return j+1;
881 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000882 && strncmp(z+i,"null",4)==0
883 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000884 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
885 return i+4;
886 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000887 && strncmp(z+i,"true",4)==0
888 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000889 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
890 return i+4;
891 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000892 && strncmp(z+i,"false",5)==0
893 && !safe_isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000894 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
895 return i+5;
896 }else if( c=='-' || (c>='0' && c<='9') ){
897 /* Parse number */
898 u8 seenDP = 0;
899 u8 seenE = 0;
drh9fa866a2017-04-08 18:18:22 +0000900 assert( '-' < '0' );
901 if( c<='0' ){
902 j = c=='-' ? i+1 : i;
903 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
904 }
drhe9c37f32015-08-15 21:25:36 +0000905 j = i+1;
906 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000907 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000908 if( c>='0' && c<='9' ) continue;
909 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000910 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000911 if( seenDP ) return -1;
912 seenDP = 1;
913 continue;
914 }
915 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000916 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000917 if( seenE ) return -1;
918 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000919 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000920 if( c=='+' || c=='-' ){
921 j++;
drh9fa866a2017-04-08 18:18:22 +0000922 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000923 }
drhd1f00682015-08-29 16:02:37 +0000924 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000925 continue;
926 }
927 break;
928 }
drh9fa866a2017-04-08 18:18:22 +0000929 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000930 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000931 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000932 return j;
933 }else if( c=='}' ){
934 return -2; /* End of {...} */
935 }else if( c==']' ){
936 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000937 }else if( c==0 ){
938 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000939 }else{
940 return -1; /* Syntax error */
941 }
942}
943
944/*
945** Parse a complete JSON string. Return 0 on success or non-zero if there
946** are any errors. If an error occurs, free all memory associated with
947** pParse.
948**
949** pParse is uninitialized when this routine is called.
950*/
drhbc8f0922015-08-22 19:39:04 +0000951static int jsonParse(
952 JsonParse *pParse, /* Initialize and fill this JsonParse object */
953 sqlite3_context *pCtx, /* Report errors here */
954 const char *zJson /* Input JSON text to be parsed */
955){
drhe9c37f32015-08-15 21:25:36 +0000956 int i;
drhe9c37f32015-08-15 21:25:36 +0000957 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000958 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000959 pParse->zJson = zJson;
960 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000961 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000962 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000963 assert( pParse->iDepth==0 );
dan2e8f5512015-09-17 17:21:09 +0000964 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000965 if( zJson[i] ) i = -1;
966 }
drhd1f00682015-08-29 16:02:37 +0000967 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000968 if( pCtx!=0 ){
969 if( pParse->oom ){
970 sqlite3_result_error_nomem(pCtx);
971 }else{
972 sqlite3_result_error(pCtx, "malformed JSON", -1);
973 }
974 }
drh505ad2c2015-08-21 17:33:11 +0000975 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000976 return 1;
977 }
978 return 0;
979}
drh301eecc2015-08-17 20:14:19 +0000980
drh505ad2c2015-08-21 17:33:11 +0000981/* Mark node i of pParse as being a child of iParent. Call recursively
982** to fill in all the descendants of node i.
983*/
984static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
985 JsonNode *pNode = &pParse->aNode[i];
986 u32 j;
987 pParse->aUp[i] = iParent;
988 switch( pNode->eType ){
989 case JSON_ARRAY: {
990 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
991 jsonParseFillInParentage(pParse, i+j, i);
992 }
993 break;
994 }
995 case JSON_OBJECT: {
996 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
997 pParse->aUp[i+j] = i;
998 jsonParseFillInParentage(pParse, i+j+1, i);
999 }
1000 break;
1001 }
1002 default: {
1003 break;
1004 }
1005 }
1006}
1007
1008/*
1009** Compute the parentage of all nodes in a completed parse.
1010*/
1011static int jsonParseFindParents(JsonParse *pParse){
1012 u32 *aUp;
1013 assert( pParse->aUp==0 );
drh2d77d802019-01-08 20:02:48 +00001014 aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +00001015 if( aUp==0 ){
1016 pParse->oom = 1;
1017 return SQLITE_NOMEM;
1018 }
drh505ad2c2015-08-21 17:33:11 +00001019 jsonParseFillInParentage(pParse, 0, 0);
1020 return SQLITE_OK;
1021}
1022
drh8cb0c832015-09-22 00:21:03 +00001023/*
drh3fb153c2017-05-11 16:49:59 +00001024** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
1025*/
drhe35fc302018-08-30 01:52:10 +00001026#define JSON_CACHE_ID (-429938) /* First cache entry */
1027#define JSON_CACHE_SZ 4 /* Max number of cache entries */
drh3fb153c2017-05-11 16:49:59 +00001028
1029/*
1030** Obtain a complete parse of the JSON found in the first argument
1031** of the argv array. Use the sqlite3_get_auxdata() cache for this
1032** parse if it is available. If the cache is not available or if it
1033** is no longer valid, parse the JSON again and return the new parse,
1034** and also register the new parse so that it will be available for
1035** future sqlite3_get_auxdata() calls.
1036*/
1037static JsonParse *jsonParseCached(
1038 sqlite3_context *pCtx,
drhe35fc302018-08-30 01:52:10 +00001039 sqlite3_value **argv,
1040 sqlite3_context *pErrCtx
drh3fb153c2017-05-11 16:49:59 +00001041){
1042 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
1043 int nJson = sqlite3_value_bytes(argv[0]);
1044 JsonParse *p;
drhe35fc302018-08-30 01:52:10 +00001045 JsonParse *pMatch = 0;
1046 int iKey;
1047 int iMinKey = 0;
1048 u32 iMinHold = 0xffffffff;
1049 u32 iMaxHold = 0;
drh3fb153c2017-05-11 16:49:59 +00001050 if( zJson==0 ) return 0;
drhe35fc302018-08-30 01:52:10 +00001051 for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
1052 p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
1053 if( p==0 ){
1054 iMinKey = iKey;
1055 break;
1056 }
1057 if( pMatch==0
1058 && p->nJson==nJson
1059 && memcmp(p->zJson,zJson,nJson)==0
1060 ){
1061 p->nErr = 0;
1062 pMatch = p;
1063 }else if( p->iHold<iMinHold ){
1064 iMinHold = p->iHold;
1065 iMinKey = iKey;
1066 }
1067 if( p->iHold>iMaxHold ){
1068 iMaxHold = p->iHold;
1069 }
1070 }
1071 if( pMatch ){
1072 pMatch->nErr = 0;
1073 pMatch->iHold = iMaxHold+1;
1074 return pMatch;
drh3fb153c2017-05-11 16:49:59 +00001075 }
drh2d77d802019-01-08 20:02:48 +00001076 p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
drh3fb153c2017-05-11 16:49:59 +00001077 if( p==0 ){
1078 sqlite3_result_error_nomem(pCtx);
1079 return 0;
1080 }
1081 memset(p, 0, sizeof(*p));
1082 p->zJson = (char*)&p[1];
1083 memcpy((char*)p->zJson, zJson, nJson+1);
drhe35fc302018-08-30 01:52:10 +00001084 if( jsonParse(p, pErrCtx, p->zJson) ){
drh3fb153c2017-05-11 16:49:59 +00001085 sqlite3_free(p);
1086 return 0;
1087 }
1088 p->nJson = nJson;
drhe35fc302018-08-30 01:52:10 +00001089 p->iHold = iMaxHold+1;
1090 sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
1091 (void(*)(void*))jsonParseFree);
1092 return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
drh3fb153c2017-05-11 16:49:59 +00001093}
1094
1095/*
drh8cb0c832015-09-22 00:21:03 +00001096** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1097** a match.
1098*/
mistachkinf2c26ed2015-10-12 22:20:29 +00001099static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh8cb0c832015-09-22 00:21:03 +00001100 if( pNode->jnFlags & JNODE_RAW ){
1101 if( pNode->n!=nKey ) return 0;
1102 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
1103 }else{
1104 if( pNode->n!=nKey+2 ) return 0;
1105 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
1106 }
1107}
1108
drh52216ad2015-08-18 02:28:03 +00001109/* forward declaration */
drha7714022015-08-29 00:54:49 +00001110static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +00001111
drh987eb1f2015-08-17 15:17:37 +00001112/*
1113** Search along zPath to find the node specified. Return a pointer
1114** to that node, or NULL if zPath is malformed or if there is no such
1115** node.
drh52216ad2015-08-18 02:28:03 +00001116**
1117** If pApnd!=0, then try to append new nodes to complete zPath if it is
1118** possible to do so and if no existing node corresponds to zPath. If
1119** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +00001120*/
drha7714022015-08-29 00:54:49 +00001121static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +00001122 JsonParse *pParse, /* The JSON to search */
1123 u32 iRoot, /* Begin the search at this node */
1124 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +00001125 int *pApnd, /* Append nodes to complete path if not NULL */
1126 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +00001127){
drhbc8f0922015-08-22 19:39:04 +00001128 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001129 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001130 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001131 if( zPath[0]==0 ) return pRoot;
drh7e35e812019-07-31 12:13:58 +00001132 if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
drh987eb1f2015-08-17 15:17:37 +00001133 if( zPath[0]=='.' ){
1134 if( pRoot->eType!=JSON_OBJECT ) return 0;
1135 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001136 if( zPath[0]=='"' ){
1137 zKey = zPath + 1;
1138 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1139 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001140 if( zPath[i] ){
1141 i++;
1142 }else{
1143 *pzErr = zPath;
1144 return 0;
1145 }
drh6b43cc82015-08-19 23:02:49 +00001146 }else{
1147 zKey = zPath;
1148 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1149 nKey = i;
1150 }
drha7714022015-08-29 00:54:49 +00001151 if( nKey==0 ){
1152 *pzErr = zPath;
1153 return 0;
1154 }
drh987eb1f2015-08-17 15:17:37 +00001155 j = 1;
drh52216ad2015-08-18 02:28:03 +00001156 for(;;){
1157 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001158 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001159 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001160 }
1161 j++;
drh505ad2c2015-08-21 17:33:11 +00001162 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001163 }
drh52216ad2015-08-18 02:28:03 +00001164 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1165 iRoot += pRoot->u.iAppend;
1166 pRoot = &pParse->aNode[iRoot];
1167 j = 1;
1168 }
1169 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001170 u32 iStart, iLabel;
1171 JsonNode *pNode;
1172 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
danfe9a8322019-06-17 14:50:33 +00001173 iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
drh52216ad2015-08-18 02:28:03 +00001174 zPath += i;
drha7714022015-08-29 00:54:49 +00001175 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001176 if( pParse->oom ) return 0;
1177 if( pNode ){
1178 pRoot = &pParse->aNode[iRoot];
1179 pRoot->u.iAppend = iStart - iRoot;
1180 pRoot->jnFlags |= JNODE_APPEND;
1181 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1182 }
1183 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001184 }
drh52818642019-11-22 17:37:56 +00001185 }else if( zPath[0]=='[' ){
drh987eb1f2015-08-17 15:17:37 +00001186 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001187 j = 1;
1188 while( safe_isdigit(zPath[j]) ){
1189 i = i*10 + zPath[j] - '0';
1190 j++;
drh987eb1f2015-08-17 15:17:37 +00001191 }
drh52818642019-11-22 17:37:56 +00001192 if( j<2 || zPath[j]!=']' ){
1193 if( zPath[1]=='#' ){
1194 JsonNode *pBase = pRoot;
1195 int iBase = iRoot;
1196 if( pRoot->eType!=JSON_ARRAY ) return 0;
1197 for(;;){
1198 while( j<=pBase->n ){
1199 if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
1200 j += jsonNodeSize(&pBase[j]);
1201 }
1202 if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
1203 iBase += pBase->u.iAppend;
1204 pBase = &pParse->aNode[iBase];
1205 j = 1;
1206 }
1207 j = 2;
1208 if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
1209 unsigned int x = 0;
1210 j = 3;
1211 do{
1212 x = x*10 + zPath[j] - '0';
1213 j++;
1214 }while( safe_isdigit(zPath[j]) );
1215 if( x>i ) return 0;
1216 i -= x;
1217 }
1218 if( zPath[j]!=']' ){
1219 *pzErr = zPath;
1220 return 0;
1221 }
1222 }else{
1223 *pzErr = zPath;
1224 return 0;
1225 }
drha7714022015-08-29 00:54:49 +00001226 }
drh52818642019-11-22 17:37:56 +00001227 if( pRoot->eType!=JSON_ARRAY ) return 0;
drh3d1d2a92015-09-22 01:15:49 +00001228 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001229 j = 1;
drh52216ad2015-08-18 02:28:03 +00001230 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001231 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1232 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001233 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001234 }
1235 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1236 iRoot += pRoot->u.iAppend;
1237 pRoot = &pParse->aNode[iRoot];
1238 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001239 }
1240 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001241 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001242 }
1243 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001244 u32 iStart;
1245 JsonNode *pNode;
1246 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001247 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001248 if( pParse->oom ) return 0;
1249 if( pNode ){
1250 pRoot = &pParse->aNode[iRoot];
1251 pRoot->u.iAppend = iStart - iRoot;
1252 pRoot->jnFlags |= JNODE_APPEND;
1253 }
1254 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001255 }
drh3d1d2a92015-09-22 01:15:49 +00001256 }else{
drha7714022015-08-29 00:54:49 +00001257 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001258 }
1259 return 0;
1260}
1261
drh52216ad2015-08-18 02:28:03 +00001262/*
drhbc8f0922015-08-22 19:39:04 +00001263** Append content to pParse that will complete zPath. Return a pointer
1264** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001265*/
1266static JsonNode *jsonLookupAppend(
1267 JsonParse *pParse, /* Append content to the JSON parse */
1268 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001269 int *pApnd, /* Set this flag to 1 */
1270 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001271){
1272 *pApnd = 1;
1273 if( zPath[0]==0 ){
1274 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1275 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1276 }
1277 if( zPath[0]=='.' ){
1278 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1279 }else if( strncmp(zPath,"[0]",3)==0 ){
1280 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1281 }else{
1282 return 0;
1283 }
1284 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001285 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001286}
1287
drhbc8f0922015-08-22 19:39:04 +00001288/*
drha7714022015-08-29 00:54:49 +00001289** Return the text of a syntax error message on a JSON path. Space is
1290** obtained from sqlite3_malloc().
1291*/
1292static char *jsonPathSyntaxError(const char *zErr){
1293 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1294}
1295
1296/*
1297** Do a node lookup using zPath. Return a pointer to the node on success.
1298** Return NULL if not found or if there is an error.
1299**
1300** On an error, write an error message into pCtx and increment the
1301** pParse->nErr counter.
1302**
1303** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1304** nodes are appended.
drha7714022015-08-29 00:54:49 +00001305*/
1306static JsonNode *jsonLookup(
1307 JsonParse *pParse, /* The JSON to search */
1308 const char *zPath, /* The path to search */
1309 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001310 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001311){
1312 const char *zErr = 0;
1313 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001314 char *zMsg;
drha7714022015-08-29 00:54:49 +00001315
1316 if( zPath==0 ) return 0;
1317 if( zPath[0]!='$' ){
1318 zErr = zPath;
1319 goto lookup_err;
1320 }
1321 zPath++;
drha7714022015-08-29 00:54:49 +00001322 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001323 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001324
1325lookup_err:
1326 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001327 assert( zErr!=0 && pCtx!=0 );
1328 zMsg = jsonPathSyntaxError(zErr);
1329 if( zMsg ){
1330 sqlite3_result_error(pCtx, zMsg, -1);
1331 sqlite3_free(zMsg);
1332 }else{
1333 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001334 }
drha7714022015-08-29 00:54:49 +00001335 return 0;
1336}
1337
1338
1339/*
drhbc8f0922015-08-22 19:39:04 +00001340** Report the wrong number of arguments for json_insert(), json_replace()
1341** or json_set().
1342*/
1343static void jsonWrongNumArgs(
1344 sqlite3_context *pCtx,
1345 const char *zFuncName
1346){
1347 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1348 zFuncName);
1349 sqlite3_result_error(pCtx, zMsg, -1);
1350 sqlite3_free(zMsg);
1351}
drh52216ad2015-08-18 02:28:03 +00001352
drh29c99692017-03-24 12:35:17 +00001353/*
1354** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1355*/
1356static void jsonRemoveAllNulls(JsonNode *pNode){
1357 int i, n;
1358 assert( pNode->eType==JSON_OBJECT );
1359 n = pNode->n;
1360 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1361 switch( pNode[i].eType ){
1362 case JSON_NULL:
1363 pNode[i].jnFlags |= JNODE_REMOVE;
1364 break;
1365 case JSON_OBJECT:
1366 jsonRemoveAllNulls(&pNode[i]);
1367 break;
1368 }
1369 }
1370}
1371
drha7714022015-08-29 00:54:49 +00001372
drh987eb1f2015-08-17 15:17:37 +00001373/****************************************************************************
1374** SQL functions used for testing and debugging
1375****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001376
drh301eecc2015-08-17 20:14:19 +00001377#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001378/*
drh5634cc02015-08-17 11:28:03 +00001379** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001380** a parse of the JSON provided. Or it returns NULL if JSON is not
1381** well-formed.
1382*/
drh5634cc02015-08-17 11:28:03 +00001383static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001384 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001385 int argc,
1386 sqlite3_value **argv
1387){
drh505ad2c2015-08-21 17:33:11 +00001388 JsonString s; /* Output string - not real JSON */
1389 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001390 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001391
1392 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001393 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001394 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001395 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001396 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001397 const char *zType;
1398 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1399 assert( x.aNode[i].eType==JSON_STRING );
1400 zType = "label";
1401 }else{
1402 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001403 }
drh852944e2015-09-10 03:29:11 +00001404 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1405 i, zType, x.aNode[i].n, x.aUp[i]);
1406 if( x.aNode[i].u.zJContent!=0 ){
1407 jsonAppendRaw(&s, " ", 1);
1408 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1409 }
1410 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001411 }
drh505ad2c2015-08-21 17:33:11 +00001412 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001413 jsonResult(&s);
1414}
1415
drh5634cc02015-08-17 11:28:03 +00001416/*
drhf5ddb9c2015-09-11 00:06:41 +00001417** The json_test1(JSON) function return true (1) if the input is JSON
1418** text generated by another json function. It returns (0) if the input
1419** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001420*/
1421static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001422 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001423 int argc,
1424 sqlite3_value **argv
1425){
mistachkin16a93122015-09-11 18:05:01 +00001426 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001427 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001428}
drh301eecc2015-08-17 20:14:19 +00001429#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001430
drh987eb1f2015-08-17 15:17:37 +00001431/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001432** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001433****************************************************************************/
1434
1435/*
drh2ad96f52016-06-17 13:01:51 +00001436** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1437** corresponding to the SQL value input. Mostly this means putting
1438** double-quotes around strings and returning the unquoted string "null"
1439** when given a NULL input.
1440*/
1441static void jsonQuoteFunc(
1442 sqlite3_context *ctx,
1443 int argc,
1444 sqlite3_value **argv
1445){
1446 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001447 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001448
1449 jsonInit(&jx, ctx);
1450 jsonAppendValue(&jx, argv[0]);
1451 jsonResult(&jx);
1452 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1453}
1454
1455/*
drh987eb1f2015-08-17 15:17:37 +00001456** Implementation of the json_array(VALUE,...) function. Return a JSON
1457** array that contains all values given in arguments. Or if any argument
1458** is a BLOB, throw an error.
1459*/
1460static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001461 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001462 int argc,
1463 sqlite3_value **argv
1464){
1465 int i;
drh505ad2c2015-08-21 17:33:11 +00001466 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001467
drhbc8f0922015-08-22 19:39:04 +00001468 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001469 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001470 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001471 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001472 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001473 }
drhd0960592015-08-17 21:22:32 +00001474 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001475 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001476 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001477}
1478
1479
1480/*
1481** json_array_length(JSON)
1482** json_array_length(JSON, PATH)
1483**
1484** Return the number of elements in the top-level JSON array.
1485** Return 0 if the input is not a well-formed JSON array.
1486*/
1487static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001488 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001489 int argc,
1490 sqlite3_value **argv
1491){
drh3fb153c2017-05-11 16:49:59 +00001492 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001493 sqlite3_int64 n = 0;
1494 u32 i;
drha8f39a92015-09-21 22:53:16 +00001495 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001496
drhe35fc302018-08-30 01:52:10 +00001497 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001498 if( p==0 ) return;
1499 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001500 if( argc==2 ){
1501 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001502 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001503 }else{
drh3fb153c2017-05-11 16:49:59 +00001504 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001505 }
1506 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001507 return;
1508 }
1509 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001510 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1511 for(i=1; i<=pNode->n; n++){
1512 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001513 }
drh987eb1f2015-08-17 15:17:37 +00001514 }
drh3fb153c2017-05-11 16:49:59 +00001515 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001516}
1517
1518/*
drh3ad93bb2015-08-29 19:41:45 +00001519** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001520**
drh3ad93bb2015-08-29 19:41:45 +00001521** Return the element described by PATH. Return NULL if there is no
1522** PATH element. If there are multiple PATHs, then return a JSON array
1523** with the result from each path. Throw an error if the JSON or any PATH
1524** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001525*/
1526static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001527 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001528 int argc,
1529 sqlite3_value **argv
1530){
drh3fb153c2017-05-11 16:49:59 +00001531 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001532 JsonNode *pNode;
1533 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001534 JsonString jx;
1535 int i;
1536
1537 if( argc<2 ) return;
drhe35fc302018-08-30 01:52:10 +00001538 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001539 if( p==0 ) return;
drh3ad93bb2015-08-29 19:41:45 +00001540 jsonInit(&jx, ctx);
1541 jsonAppendChar(&jx, '[');
1542 for(i=1; i<argc; i++){
1543 zPath = (const char*)sqlite3_value_text(argv[i]);
drh3fb153c2017-05-11 16:49:59 +00001544 pNode = jsonLookup(p, zPath, 0, ctx);
1545 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001546 if( argc>2 ){
1547 jsonAppendSeparator(&jx);
1548 if( pNode ){
1549 jsonRenderNode(pNode, &jx, 0);
1550 }else{
1551 jsonAppendRaw(&jx, "null", 4);
1552 }
1553 }else if( pNode ){
1554 jsonReturn(pNode, ctx, 0);
1555 }
drh987eb1f2015-08-17 15:17:37 +00001556 }
drh3ad93bb2015-08-29 19:41:45 +00001557 if( argc>2 && i==argc ){
1558 jsonAppendChar(&jx, ']');
1559 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001560 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001561 }
1562 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001563}
1564
drh633647a2017-03-22 21:24:31 +00001565/* This is the RFC 7396 MergePatch algorithm.
1566*/
1567static JsonNode *jsonMergePatch(
1568 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001569 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001570 JsonNode *pPatch /* The PATCH */
1571){
drh0002d242017-03-23 00:46:15 +00001572 u32 i, j;
1573 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001574 JsonNode *pTarget;
1575 if( pPatch->eType!=JSON_OBJECT ){
1576 return pPatch;
1577 }
1578 assert( iTarget>=0 && iTarget<pParse->nNode );
1579 pTarget = &pParse->aNode[iTarget];
1580 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1581 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001582 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001583 return pPatch;
1584 }
drhbb7aa2d2017-03-23 00:13:52 +00001585 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001586 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001587 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001588 const char *zKey;
1589 assert( pPatch[i].eType==JSON_STRING );
1590 assert( pPatch[i].jnFlags & JNODE_LABEL );
1591 nKey = pPatch[i].n;
1592 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001593 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001594 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1595 assert( pTarget[j].eType==JSON_STRING );
1596 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001597 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001598 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1599 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001600 if( pPatch[i+1].eType==JSON_NULL ){
1601 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1602 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001603 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001604 if( pNew==0 ) return 0;
1605 pTarget = &pParse->aNode[iTarget];
1606 if( pNew!=&pTarget[j+1] ){
1607 pTarget[j+1].u.pPatch = pNew;
1608 pTarget[j+1].jnFlags |= JNODE_PATCH;
1609 }
1610 }
1611 break;
1612 }
1613 }
drhbb7aa2d2017-03-23 00:13:52 +00001614 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001615 int iStart, iPatch;
1616 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1617 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1618 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1619 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001620 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001621 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001622 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1623 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1624 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001625 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1626 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1627 }
1628 }
1629 return pTarget;
1630}
1631
1632/*
1633** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1634** object that is the result of running the RFC 7396 MergePatch() algorithm
1635** on the two arguments.
1636*/
drh37f03df2017-03-23 20:33:49 +00001637static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001638 sqlite3_context *ctx,
1639 int argc,
1640 sqlite3_value **argv
1641){
1642 JsonParse x; /* The JSON that is being patched */
1643 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001644 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001645
drh2fb79e92017-03-25 12:08:11 +00001646 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001647 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1648 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1649 jsonParseReset(&x);
1650 return;
1651 }
drhbb7aa2d2017-03-23 00:13:52 +00001652 pResult = jsonMergePatch(&x, 0, y.aNode);
1653 assert( pResult!=0 || x.oom );
1654 if( pResult ){
1655 jsonReturnJson(pResult, ctx, 0);
1656 }else{
1657 sqlite3_result_error_nomem(ctx);
1658 }
drh633647a2017-03-22 21:24:31 +00001659 jsonParseReset(&x);
1660 jsonParseReset(&y);
1661}
1662
1663
drh987eb1f2015-08-17 15:17:37 +00001664/*
1665** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1666** object that contains all name/value given in arguments. Or if any name
1667** is not a string or if any value is a BLOB, throw an error.
1668*/
1669static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001670 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001671 int argc,
1672 sqlite3_value **argv
1673){
1674 int i;
drh505ad2c2015-08-21 17:33:11 +00001675 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001676 const char *z;
1677 u32 n;
1678
1679 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001680 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001681 "of arguments", -1);
1682 return;
1683 }
drhbc8f0922015-08-22 19:39:04 +00001684 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001685 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001686 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001687 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001688 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001689 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001690 return;
1691 }
drhd0960592015-08-17 21:22:32 +00001692 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001693 z = (const char*)sqlite3_value_text(argv[i]);
1694 n = (u32)sqlite3_value_bytes(argv[i]);
1695 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001696 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001697 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001698 }
drhd0960592015-08-17 21:22:32 +00001699 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001700 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001701 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001702}
1703
1704
1705/*
drh301eecc2015-08-17 20:14:19 +00001706** json_remove(JSON, PATH, ...)
1707**
drh3ad93bb2015-08-29 19:41:45 +00001708** Remove the named elements from JSON and return the result. malformed
1709** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001710*/
1711static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001712 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001713 int argc,
1714 sqlite3_value **argv
1715){
1716 JsonParse x; /* The parse */
1717 JsonNode *pNode;
1718 const char *zPath;
1719 u32 i;
1720
1721 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001722 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001723 assert( x.nNode );
1724 for(i=1; i<(u32)argc; i++){
1725 zPath = (const char*)sqlite3_value_text(argv[i]);
1726 if( zPath==0 ) goto remove_done;
1727 pNode = jsonLookup(&x, zPath, 0, ctx);
1728 if( x.nErr ) goto remove_done;
1729 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1730 }
1731 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1732 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001733 }
drha7714022015-08-29 00:54:49 +00001734remove_done:
drh505ad2c2015-08-21 17:33:11 +00001735 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001736}
1737
1738/*
1739** json_replace(JSON, PATH, VALUE, ...)
1740**
1741** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001742** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001743*/
1744static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001745 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001746 int argc,
1747 sqlite3_value **argv
1748){
1749 JsonParse x; /* The parse */
1750 JsonNode *pNode;
1751 const char *zPath;
1752 u32 i;
1753
1754 if( argc<1 ) return;
1755 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001756 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001757 return;
1758 }
drhbc8f0922015-08-22 19:39:04 +00001759 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001760 assert( x.nNode );
1761 for(i=1; i<(u32)argc; i+=2){
1762 zPath = (const char*)sqlite3_value_text(argv[i]);
1763 pNode = jsonLookup(&x, zPath, 0, ctx);
1764 if( x.nErr ) goto replace_err;
1765 if( pNode ){
1766 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001767 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001768 }
drha8f39a92015-09-21 22:53:16 +00001769 }
1770 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001771 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001772 }else{
1773 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001774 }
drha7714022015-08-29 00:54:49 +00001775replace_err:
drh505ad2c2015-08-21 17:33:11 +00001776 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001777}
drh505ad2c2015-08-21 17:33:11 +00001778
drh52216ad2015-08-18 02:28:03 +00001779/*
1780** json_set(JSON, PATH, VALUE, ...)
1781**
1782** Set the value at PATH to VALUE. Create the PATH if it does not already
1783** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001784** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001785**
1786** json_insert(JSON, PATH, VALUE, ...)
1787**
1788** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001789** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001790*/
1791static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001792 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001793 int argc,
1794 sqlite3_value **argv
1795){
1796 JsonParse x; /* The parse */
1797 JsonNode *pNode;
1798 const char *zPath;
1799 u32 i;
1800 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001801 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001802
1803 if( argc<1 ) return;
1804 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001805 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001806 return;
1807 }
drhbc8f0922015-08-22 19:39:04 +00001808 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001809 assert( x.nNode );
1810 for(i=1; i<(u32)argc; i+=2){
1811 zPath = (const char*)sqlite3_value_text(argv[i]);
1812 bApnd = 0;
1813 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1814 if( x.oom ){
1815 sqlite3_result_error_nomem(ctx);
1816 goto jsonSetDone;
1817 }else if( x.nErr ){
1818 goto jsonSetDone;
1819 }else if( pNode && (bApnd || bIsSet) ){
1820 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001821 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001822 }
drha8f39a92015-09-21 22:53:16 +00001823 }
1824 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001825 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001826 }else{
1827 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001828 }
drhbc8f0922015-08-22 19:39:04 +00001829jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001830 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001831}
drh301eecc2015-08-17 20:14:19 +00001832
1833/*
drh987eb1f2015-08-17 15:17:37 +00001834** json_type(JSON)
1835** json_type(JSON, PATH)
1836**
drh3ad93bb2015-08-29 19:41:45 +00001837** Return the top-level "type" of a JSON string. Throw an error if
1838** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001839*/
1840static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001841 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001842 int argc,
1843 sqlite3_value **argv
1844){
drhe35fc302018-08-30 01:52:10 +00001845 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001846 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001847 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001848
drhe35fc302018-08-30 01:52:10 +00001849 p = jsonParseCached(ctx, argv, ctx);
1850 if( p==0 ) return;
drha8f39a92015-09-21 22:53:16 +00001851 if( argc==2 ){
1852 zPath = (const char*)sqlite3_value_text(argv[1]);
drhe35fc302018-08-30 01:52:10 +00001853 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001854 }else{
drhe35fc302018-08-30 01:52:10 +00001855 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001856 }
1857 if( pNode ){
1858 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001859 }
drh987eb1f2015-08-17 15:17:37 +00001860}
drh5634cc02015-08-17 11:28:03 +00001861
drhbc8f0922015-08-22 19:39:04 +00001862/*
1863** json_valid(JSON)
1864**
drh3ad93bb2015-08-29 19:41:45 +00001865** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1866** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001867*/
1868static void jsonValidFunc(
1869 sqlite3_context *ctx,
1870 int argc,
1871 sqlite3_value **argv
1872){
drhe35fc302018-08-30 01:52:10 +00001873 JsonParse *p; /* The parse */
mistachkin16a93122015-09-11 18:05:01 +00001874 UNUSED_PARAM(argc);
drhe35fc302018-08-30 01:52:10 +00001875 p = jsonParseCached(ctx, argv, 0);
1876 sqlite3_result_int(ctx, p!=0);
drhbc8f0922015-08-22 19:39:04 +00001877}
1878
drhff135ae2015-12-30 01:07:02 +00001879
1880/****************************************************************************
1881** Aggregate SQL function implementations
1882****************************************************************************/
1883/*
1884** json_group_array(VALUE)
1885**
1886** Return a JSON array composed of all values in the aggregate.
1887*/
1888static void jsonArrayStep(
1889 sqlite3_context *ctx,
1890 int argc,
1891 sqlite3_value **argv
1892){
1893 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001894 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001895 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1896 if( pStr ){
1897 if( pStr->zBuf==0 ){
1898 jsonInit(pStr, ctx);
1899 jsonAppendChar(pStr, '[');
drhfab5b072019-09-14 00:21:34 +00001900 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00001901 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00001902 }
dan8505d732021-04-14 12:11:39 +00001903 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00001904 jsonAppendValue(pStr, argv[0]);
1905 }
1906}
drh8be47a72018-07-05 20:05:29 +00001907static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001908 JsonString *pStr;
1909 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1910 if( pStr ){
1911 pStr->pCtx = ctx;
1912 jsonAppendChar(pStr, ']');
1913 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001914 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001915 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001916 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001917 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001918 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1919 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001920 }else{
mistachkined008ec2018-09-12 01:05:26 +00001921 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001922 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001923 }
1924 }else{
1925 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1926 }
1927 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1928}
drh8be47a72018-07-05 20:05:29 +00001929static void jsonArrayValue(sqlite3_context *ctx){
1930 jsonArrayCompute(ctx, 0);
1931}
1932static void jsonArrayFinal(sqlite3_context *ctx){
1933 jsonArrayCompute(ctx, 1);
1934}
1935
1936#ifndef SQLITE_OMIT_WINDOWFUNC
1937/*
1938** This method works for both json_group_array() and json_group_object().
1939** It works by removing the first element of the group by searching forward
1940** to the first comma (",") that is not within a string and deleting all
1941** text through that comma.
1942*/
1943static void jsonGroupInverse(
1944 sqlite3_context *ctx,
1945 int argc,
1946 sqlite3_value **argv
1947){
drhe39f3882019-09-21 17:31:03 +00001948 unsigned int i;
drh8be47a72018-07-05 20:05:29 +00001949 int inStr = 0;
drhfab5b072019-09-14 00:21:34 +00001950 int nNest = 0;
drh8be47a72018-07-05 20:05:29 +00001951 char *z;
drhfab5b072019-09-14 00:21:34 +00001952 char c;
drh8be47a72018-07-05 20:05:29 +00001953 JsonString *pStr;
drhc7bf5712018-07-09 22:49:01 +00001954 UNUSED_PARAM(argc);
1955 UNUSED_PARAM(argv);
drh8be47a72018-07-05 20:05:29 +00001956 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drh491d4c82018-07-07 20:23:46 +00001957#ifdef NEVER
drhfd4b7282018-07-07 19:47:21 +00001958 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1959 ** always have been called to initalize it */
1960 if( NEVER(!pStr) ) return;
drh491d4c82018-07-07 20:23:46 +00001961#endif
drh8be47a72018-07-05 20:05:29 +00001962 z = pStr->zBuf;
drh0e5cd342021-04-13 01:12:32 +00001963 for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
drhfab5b072019-09-14 00:21:34 +00001964 if( c=='"' ){
drh8be47a72018-07-05 20:05:29 +00001965 inStr = !inStr;
drhfab5b072019-09-14 00:21:34 +00001966 }else if( c=='\\' ){
drh8be47a72018-07-05 20:05:29 +00001967 i++;
drhfab5b072019-09-14 00:21:34 +00001968 }else if( !inStr ){
1969 if( c=='{' || c=='[' ) nNest++;
1970 if( c=='}' || c==']' ) nNest--;
drh8be47a72018-07-05 20:05:29 +00001971 }
1972 }
drh0e5cd342021-04-13 01:12:32 +00001973 if( i<pStr->nUsed ){
1974 pStr->nUsed -= i;
1975 memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
1976 z[pStr->nUsed] = 0;
1977 }else{
1978 pStr->nUsed = 1;
1979 }
drh8be47a72018-07-05 20:05:29 +00001980}
1981#else
1982# define jsonGroupInverse 0
1983#endif
1984
drhff135ae2015-12-30 01:07:02 +00001985
1986/*
1987** json_group_obj(NAME,VALUE)
1988**
1989** Return a JSON object composed of all names and values in the aggregate.
1990*/
1991static void jsonObjectStep(
1992 sqlite3_context *ctx,
1993 int argc,
1994 sqlite3_value **argv
1995){
1996 JsonString *pStr;
1997 const char *z;
1998 u32 n;
drhdf3a9072016-02-11 15:37:18 +00001999 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00002000 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
2001 if( pStr ){
2002 if( pStr->zBuf==0 ){
2003 jsonInit(pStr, ctx);
2004 jsonAppendChar(pStr, '{');
drhfab5b072019-09-14 00:21:34 +00002005 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00002006 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00002007 }
drhd2f55772021-05-28 12:15:19 +00002008 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00002009 z = (const char*)sqlite3_value_text(argv[0]);
2010 n = (u32)sqlite3_value_bytes(argv[0]);
2011 jsonAppendString(pStr, z, n);
2012 jsonAppendChar(pStr, ':');
2013 jsonAppendValue(pStr, argv[1]);
2014 }
2015}
drh8be47a72018-07-05 20:05:29 +00002016static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00002017 JsonString *pStr;
2018 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
2019 if( pStr ){
2020 jsonAppendChar(pStr, '}');
2021 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00002022 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00002023 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00002024 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00002025 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00002026 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
2027 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00002028 }else{
mistachkined008ec2018-09-12 01:05:26 +00002029 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00002030 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00002031 }
2032 }else{
2033 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
2034 }
2035 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
2036}
drh8be47a72018-07-05 20:05:29 +00002037static void jsonObjectValue(sqlite3_context *ctx){
2038 jsonObjectCompute(ctx, 0);
2039}
2040static void jsonObjectFinal(sqlite3_context *ctx){
2041 jsonObjectCompute(ctx, 1);
2042}
2043
drhff135ae2015-12-30 01:07:02 +00002044
2045
drhd2975922015-08-29 17:22:33 +00002046#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00002047/****************************************************************************
2048** The json_each virtual table
2049****************************************************************************/
2050typedef struct JsonEachCursor JsonEachCursor;
2051struct JsonEachCursor {
2052 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00002053 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00002054 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00002055 u32 i; /* Index in sParse.aNode[] of current row */
2056 u32 iEnd; /* EOF when i equals or exceeds this value */
2057 u8 eType; /* Type of top-level element */
2058 u8 bRecursive; /* True for json_tree(). False for json_each() */
2059 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00002060 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00002061 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00002062};
2063
2064/* Constructor for the json_each virtual table */
2065static int jsonEachConnect(
2066 sqlite3 *db,
2067 void *pAux,
2068 int argc, const char *const*argv,
2069 sqlite3_vtab **ppVtab,
2070 char **pzErr
2071){
2072 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00002073 int rc;
drhcb6c6c62015-08-19 22:47:17 +00002074
2075/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00002076#define JEACH_KEY 0
2077#define JEACH_VALUE 1
2078#define JEACH_TYPE 2
2079#define JEACH_ATOM 3
2080#define JEACH_ID 4
2081#define JEACH_PARENT 5
2082#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00002083#define JEACH_PATH 7
drh43579192018-11-16 16:04:50 +00002084/* The xBestIndex method assumes that the JSON and ROOT columns are
2085** the last two columns in the table. Should this ever changes, be
2086** sure to update the xBestIndex method. */
drh383de692015-09-10 17:20:57 +00002087#define JEACH_JSON 8
2088#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00002089
drh6fd5c1e2015-08-21 20:37:12 +00002090 UNUSED_PARAM(pzErr);
2091 UNUSED_PARAM(argv);
2092 UNUSED_PARAM(argc);
2093 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00002094 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00002095 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2096 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00002097 if( rc==SQLITE_OK ){
2098 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2099 if( pNew==0 ) return SQLITE_NOMEM;
2100 memset(pNew, 0, sizeof(*pNew));
drh2b1c2aa2020-01-07 19:45:40 +00002101 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
drh505ad2c2015-08-21 17:33:11 +00002102 }
2103 return rc;
drhcb6c6c62015-08-19 22:47:17 +00002104}
2105
2106/* destructor for json_each virtual table */
2107static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2108 sqlite3_free(pVtab);
2109 return SQLITE_OK;
2110}
2111
drh505ad2c2015-08-21 17:33:11 +00002112/* constructor for a JsonEachCursor object for json_each(). */
2113static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00002114 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00002115
2116 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00002117 pCur = sqlite3_malloc( sizeof(*pCur) );
2118 if( pCur==0 ) return SQLITE_NOMEM;
2119 memset(pCur, 0, sizeof(*pCur));
2120 *ppCursor = &pCur->base;
2121 return SQLITE_OK;
2122}
2123
drh505ad2c2015-08-21 17:33:11 +00002124/* constructor for a JsonEachCursor object for json_tree(). */
2125static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2126 int rc = jsonEachOpenEach(p, ppCursor);
2127 if( rc==SQLITE_OK ){
2128 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2129 pCur->bRecursive = 1;
2130 }
2131 return rc;
2132}
2133
drhcb6c6c62015-08-19 22:47:17 +00002134/* Reset a JsonEachCursor back to its original state. Free any memory
2135** held. */
2136static void jsonEachCursorReset(JsonEachCursor *p){
2137 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002138 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002139 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002140 p->iRowid = 0;
2141 p->i = 0;
2142 p->iEnd = 0;
2143 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002144 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002145 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002146}
2147
2148/* Destructor for a jsonEachCursor object */
2149static int jsonEachClose(sqlite3_vtab_cursor *cur){
2150 JsonEachCursor *p = (JsonEachCursor*)cur;
2151 jsonEachCursorReset(p);
2152 sqlite3_free(cur);
2153 return SQLITE_OK;
2154}
2155
2156/* Return TRUE if the jsonEachCursor object has been advanced off the end
2157** of the JSON object */
2158static int jsonEachEof(sqlite3_vtab_cursor *cur){
2159 JsonEachCursor *p = (JsonEachCursor*)cur;
2160 return p->i >= p->iEnd;
2161}
2162
drh505ad2c2015-08-21 17:33:11 +00002163/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002164static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002165 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002166 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002167 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2168 p->i++;
drh4af352d2015-08-21 20:02:48 +00002169 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002170 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002171 u32 iUp = p->sParse.aUp[p->i];
2172 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002173 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002174 if( pUp->eType==JSON_ARRAY ){
2175 if( iUp==p->i-1 ){
2176 pUp->u.iKey = 0;
2177 }else{
2178 pUp->u.iKey++;
2179 }
drh4af352d2015-08-21 20:02:48 +00002180 }
2181 }
drh505ad2c2015-08-21 17:33:11 +00002182 }else{
drh4af352d2015-08-21 20:02:48 +00002183 switch( p->eType ){
2184 case JSON_ARRAY: {
2185 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2186 p->iRowid++;
2187 break;
2188 }
2189 case JSON_OBJECT: {
2190 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2191 p->iRowid++;
2192 break;
2193 }
2194 default: {
2195 p->i = p->iEnd;
2196 break;
2197 }
drh505ad2c2015-08-21 17:33:11 +00002198 }
2199 }
2200 return SQLITE_OK;
2201}
2202
drh4af352d2015-08-21 20:02:48 +00002203/* Append the name of the path for element i to pStr
2204*/
2205static void jsonEachComputePath(
2206 JsonEachCursor *p, /* The cursor */
2207 JsonString *pStr, /* Write the path here */
2208 u32 i /* Path to this element */
2209){
2210 JsonNode *pNode, *pUp;
2211 u32 iUp;
2212 if( i==0 ){
2213 jsonAppendChar(pStr, '$');
2214 return;
drhcb6c6c62015-08-19 22:47:17 +00002215 }
drh4af352d2015-08-21 20:02:48 +00002216 iUp = p->sParse.aUp[i];
2217 jsonEachComputePath(p, pStr, iUp);
2218 pNode = &p->sParse.aNode[i];
2219 pUp = &p->sParse.aNode[iUp];
2220 if( pUp->eType==JSON_ARRAY ){
2221 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2222 }else{
2223 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002224 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002225 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002226 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00002227 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2228 }
drhcb6c6c62015-08-19 22:47:17 +00002229}
2230
2231/* Return the value of a column */
2232static int jsonEachColumn(
2233 sqlite3_vtab_cursor *cur, /* The cursor */
2234 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2235 int i /* Which column to return */
2236){
2237 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002238 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002239 switch( i ){
2240 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002241 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002242 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002243 jsonReturn(pThis, ctx, 0);
2244 }else if( p->eType==JSON_ARRAY ){
2245 u32 iKey;
2246 if( p->bRecursive ){
2247 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002248 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002249 }else{
2250 iKey = p->iRowid;
2251 }
drh6fd5c1e2015-08-21 20:37:12 +00002252 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002253 }
2254 break;
2255 }
2256 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002257 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002258 jsonReturn(pThis, ctx, 0);
2259 break;
2260 }
2261 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002262 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002263 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2264 break;
2265 }
2266 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002267 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002268 if( pThis->eType>=JSON_ARRAY ) break;
2269 jsonReturn(pThis, ctx, 0);
2270 break;
2271 }
2272 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002273 sqlite3_result_int64(ctx,
2274 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002275 break;
2276 }
2277 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002278 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002279 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002280 }
2281 break;
2282 }
drh4af352d2015-08-21 20:02:48 +00002283 case JEACH_FULLKEY: {
2284 JsonString x;
2285 jsonInit(&x, ctx);
2286 if( p->bRecursive ){
2287 jsonEachComputePath(p, &x, p->i);
2288 }else{
drh383de692015-09-10 17:20:57 +00002289 if( p->zRoot ){
2290 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002291 }else{
2292 jsonAppendChar(&x, '$');
2293 }
2294 if( p->eType==JSON_ARRAY ){
2295 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002296 }else if( p->eType==JSON_OBJECT ){
drh4af352d2015-08-21 20:02:48 +00002297 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2298 }
2299 }
2300 jsonResult(&x);
2301 break;
2302 }
drhcb6c6c62015-08-19 22:47:17 +00002303 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002304 if( p->bRecursive ){
2305 JsonString x;
2306 jsonInit(&x, ctx);
2307 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2308 jsonResult(&x);
2309 break;
drh4af352d2015-08-21 20:02:48 +00002310 }
drh383de692015-09-10 17:20:57 +00002311 /* For json_each() path and root are the same so fall through
2312 ** into the root case */
drh08b92082020-08-10 14:18:00 +00002313 /* no break */ deliberate_fall_through
drh383de692015-09-10 17:20:57 +00002314 }
drh6850a632016-11-07 18:18:08 +00002315 default: {
drh383de692015-09-10 17:20:57 +00002316 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002317 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002318 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002319 break;
2320 }
drh3d1d2a92015-09-22 01:15:49 +00002321 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002322 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002323 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2324 break;
2325 }
2326 }
2327 return SQLITE_OK;
2328}
2329
2330/* Return the current rowid value */
2331static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2332 JsonEachCursor *p = (JsonEachCursor*)cur;
2333 *pRowid = p->iRowid;
2334 return SQLITE_OK;
2335}
2336
2337/* The query strategy is to look for an equality constraint on the json
2338** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002339** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002340** and 0 otherwise.
2341*/
2342static int jsonEachBestIndex(
2343 sqlite3_vtab *tab,
2344 sqlite3_index_info *pIdxInfo
2345){
drh43579192018-11-16 16:04:50 +00002346 int i; /* Loop counter or computed array index */
2347 int aIdx[2]; /* Index of constraints for JSON and ROOT */
2348 int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
2349 int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
drhcb6c6c62015-08-19 22:47:17 +00002350 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002351
drh43579192018-11-16 16:04:50 +00002352 /* This implementation assumes that JSON and ROOT are the last two
2353 ** columns in the table */
2354 assert( JEACH_ROOT == JEACH_JSON+1 );
drh6fd5c1e2015-08-21 20:37:12 +00002355 UNUSED_PARAM(tab);
drh43579192018-11-16 16:04:50 +00002356 aIdx[0] = aIdx[1] = -1;
drhcb6c6c62015-08-19 22:47:17 +00002357 pConstraint = pIdxInfo->aConstraint;
2358 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
drh43579192018-11-16 16:04:50 +00002359 int iCol;
2360 int iMask;
2361 if( pConstraint->iColumn < JEACH_JSON ) continue;
2362 iCol = pConstraint->iColumn - JEACH_JSON;
2363 assert( iCol==0 || iCol==1 );
2364 iMask = 1 << iCol;
2365 if( pConstraint->usable==0 ){
2366 unusableMask |= iMask;
2367 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
2368 aIdx[iCol] = i;
2369 idxMask |= iMask;
drhcb6c6c62015-08-19 22:47:17 +00002370 }
2371 }
drh43579192018-11-16 16:04:50 +00002372 if( (unusableMask & ~idxMask)!=0 ){
2373 /* If there are any unusable constraints on JSON or ROOT, then reject
2374 ** this entire plan */
2375 return SQLITE_CONSTRAINT;
2376 }
2377 if( aIdx[0]<0 ){
2378 /* No JSON input. Leave estimatedCost at the huge value that it was
2379 ** initialized to to discourage the query planner from selecting this
2380 ** plan. */
drhcb6c6c62015-08-19 22:47:17 +00002381 pIdxInfo->idxNum = 0;
drhcb6c6c62015-08-19 22:47:17 +00002382 }else{
drh505ad2c2015-08-21 17:33:11 +00002383 pIdxInfo->estimatedCost = 1.0;
drh43579192018-11-16 16:04:50 +00002384 i = aIdx[0];
2385 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
2386 pIdxInfo->aConstraintUsage[i].omit = 1;
2387 if( aIdx[1]<0 ){
2388 pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
drhcb6c6c62015-08-19 22:47:17 +00002389 }else{
drh43579192018-11-16 16:04:50 +00002390 i = aIdx[1];
2391 pIdxInfo->aConstraintUsage[i].argvIndex = 2;
2392 pIdxInfo->aConstraintUsage[i].omit = 1;
2393 pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
drhcb6c6c62015-08-19 22:47:17 +00002394 }
2395 }
2396 return SQLITE_OK;
2397}
2398
2399/* Start a search on a new JSON string */
2400static int jsonEachFilter(
2401 sqlite3_vtab_cursor *cur,
2402 int idxNum, const char *idxStr,
2403 int argc, sqlite3_value **argv
2404){
2405 JsonEachCursor *p = (JsonEachCursor*)cur;
2406 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002407 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002408 sqlite3_int64 n;
2409
drh6fd5c1e2015-08-21 20:37:12 +00002410 UNUSED_PARAM(idxStr);
2411 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002412 jsonEachCursorReset(p);
2413 if( idxNum==0 ) return SQLITE_OK;
2414 z = (const char*)sqlite3_value_text(argv[0]);
2415 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002416 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002417 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002418 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002419 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002420 if( jsonParse(&p->sParse, 0, p->zJson) ){
2421 int rc = SQLITE_NOMEM;
2422 if( p->sParse.oom==0 ){
2423 sqlite3_free(cur->pVtab->zErrMsg);
2424 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2425 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2426 }
drhcb6c6c62015-08-19 22:47:17 +00002427 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002428 return rc;
2429 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2430 jsonEachCursorReset(p);
2431 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002432 }else{
drh95677942015-09-24 01:06:37 +00002433 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002434 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002435 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002436 zRoot = (const char*)sqlite3_value_text(argv[1]);
2437 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002438 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002439 p->zRoot = sqlite3_malloc64( n+1 );
2440 if( p->zRoot==0 ) return SQLITE_NOMEM;
2441 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002442 if( zRoot[0]!='$' ){
2443 zErr = zRoot;
2444 }else{
2445 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2446 }
2447 if( zErr ){
drha7714022015-08-29 00:54:49 +00002448 sqlite3_free(cur->pVtab->zErrMsg);
2449 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002450 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002451 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2452 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002453 return SQLITE_OK;
2454 }
2455 }else{
2456 pNode = p->sParse.aNode;
2457 }
drh852944e2015-09-10 03:29:11 +00002458 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002459 p->eType = pNode->eType;
2460 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002461 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002462 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002463 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002464 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002465 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2466 p->i--;
2467 }
2468 }else{
2469 p->i++;
2470 }
drhcb6c6c62015-08-19 22:47:17 +00002471 }else{
2472 p->iEnd = p->i+1;
2473 }
2474 }
drha8f39a92015-09-21 22:53:16 +00002475 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002476}
2477
2478/* The methods of the json_each virtual table */
2479static sqlite3_module jsonEachModule = {
2480 0, /* iVersion */
2481 0, /* xCreate */
2482 jsonEachConnect, /* xConnect */
2483 jsonEachBestIndex, /* xBestIndex */
2484 jsonEachDisconnect, /* xDisconnect */
2485 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002486 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002487 jsonEachClose, /* xClose - close a cursor */
2488 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002489 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002490 jsonEachEof, /* xEof - check for end of scan */
2491 jsonEachColumn, /* xColumn - read data */
2492 jsonEachRowid, /* xRowid - read data */
2493 0, /* xUpdate */
2494 0, /* xBegin */
2495 0, /* xSync */
2496 0, /* xCommit */
2497 0, /* xRollback */
2498 0, /* xFindMethod */
2499 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002500 0, /* xSavepoint */
2501 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002502 0, /* xRollbackTo */
2503 0 /* xShadowName */
drhcb6c6c62015-08-19 22:47:17 +00002504};
2505
drh505ad2c2015-08-21 17:33:11 +00002506/* The methods of the json_tree virtual table. */
2507static sqlite3_module jsonTreeModule = {
2508 0, /* iVersion */
2509 0, /* xCreate */
2510 jsonEachConnect, /* xConnect */
2511 jsonEachBestIndex, /* xBestIndex */
2512 jsonEachDisconnect, /* xDisconnect */
2513 0, /* xDestroy */
2514 jsonEachOpenTree, /* xOpen - open a cursor */
2515 jsonEachClose, /* xClose - close a cursor */
2516 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002517 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002518 jsonEachEof, /* xEof - check for end of scan */
2519 jsonEachColumn, /* xColumn - read data */
2520 jsonEachRowid, /* xRowid - read data */
2521 0, /* xUpdate */
2522 0, /* xBegin */
2523 0, /* xSync */
2524 0, /* xCommit */
2525 0, /* xRollback */
2526 0, /* xFindMethod */
2527 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002528 0, /* xSavepoint */
2529 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002530 0, /* xRollbackTo */
2531 0 /* xShadowName */
drh505ad2c2015-08-21 17:33:11 +00002532};
drhd2975922015-08-29 17:22:33 +00002533#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002534
2535/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002536** The following routines are the only publically visible identifiers in this
2537** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002538** functions and the virtual table implemented by this file.
2539****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002540
drh2f20e132015-09-26 17:44:59 +00002541int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002542 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002543 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002544 static const struct {
2545 const char *zName;
2546 int nArg;
drh52216ad2015-08-18 02:28:03 +00002547 int flag;
drh5fa5c102015-08-12 16:49:40 +00002548 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2549 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002550 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002551 { "json_array", -1, 0, jsonArrayFunc },
2552 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2553 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002554 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002555 { "json_insert", -1, 0, jsonSetFunc },
2556 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002557 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002558 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002559 { "json_remove", -1, 0, jsonRemoveFunc },
2560 { "json_replace", -1, 0, jsonReplaceFunc },
2561 { "json_set", -1, 1, jsonSetFunc },
2562 { "json_type", 1, 0, jsonTypeFunc },
2563 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002564 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002565
drh301eecc2015-08-17 20:14:19 +00002566#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002567 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002568 { "json_parse", 1, 0, jsonParseFunc },
2569 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002570#endif
drh5fa5c102015-08-12 16:49:40 +00002571 };
drhff135ae2015-12-30 01:07:02 +00002572 static const struct {
2573 const char *zName;
2574 int nArg;
2575 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2576 void (*xFinal)(sqlite3_context*);
drh8be47a72018-07-05 20:05:29 +00002577 void (*xValue)(sqlite3_context*);
drhff135ae2015-12-30 01:07:02 +00002578 } aAgg[] = {
drh8be47a72018-07-05 20:05:29 +00002579 { "json_group_array", 1,
2580 jsonArrayStep, jsonArrayFinal, jsonArrayValue },
2581 { "json_group_object", 2,
2582 jsonObjectStep, jsonObjectFinal, jsonObjectValue },
drhff135ae2015-12-30 01:07:02 +00002583 };
drhd2975922015-08-29 17:22:33 +00002584#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002585 static const struct {
2586 const char *zName;
2587 sqlite3_module *pModule;
2588 } aMod[] = {
2589 { "json_each", &jsonEachModule },
2590 { "json_tree", &jsonTreeModule },
2591 };
drhd2975922015-08-29 17:22:33 +00002592#endif
drh79d5bc82020-01-04 01:43:02 +00002593 static const int enc =
2594 SQLITE_UTF8 |
2595 SQLITE_DETERMINISTIC |
2596 SQLITE_INNOCUOUS;
drh5fa5c102015-08-12 16:49:40 +00002597 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
drh79d5bc82020-01-04 01:43:02 +00002598 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
dan01a3b6b2019-09-13 17:05:48 +00002599 (void*)&aFunc[i].flag,
2600 aFunc[i].xFunc, 0, 0);
drh5fa5c102015-08-12 16:49:40 +00002601 }
mistachkin5a193dd2018-07-24 13:57:44 +00002602#ifndef SQLITE_OMIT_WINDOWFUNC
drhff135ae2015-12-30 01:07:02 +00002603 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
drh8be47a72018-07-05 20:05:29 +00002604 rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
drh79d5bc82020-01-04 01:43:02 +00002605 SQLITE_SUBTYPE | enc, 0,
drh8be47a72018-07-05 20:05:29 +00002606 aAgg[i].xStep, aAgg[i].xFinal,
2607 aAgg[i].xValue, jsonGroupInverse, 0);
drhff135ae2015-12-30 01:07:02 +00002608 }
mistachkin5a193dd2018-07-24 13:57:44 +00002609#endif
drhd2975922015-08-29 17:22:33 +00002610#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002611 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2612 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002613 }
drhd2975922015-08-29 17:22:33 +00002614#endif
drh5fa5c102015-08-12 16:49:40 +00002615 return rc;
2616}
drh2f20e132015-09-26 17:44:59 +00002617
2618
dan8d32e802015-10-14 18:45:42 +00002619#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002620#ifdef _WIN32
2621__declspec(dllexport)
2622#endif
2623int sqlite3_json_init(
2624 sqlite3 *db,
2625 char **pzErrMsg,
2626 const sqlite3_api_routines *pApi
2627){
2628 SQLITE_EXTENSION_INIT2(pApi);
2629 (void)pzErrMsg; /* Unused parameter */
2630 return sqlite3Json1Init(db);
2631}
dan8d32e802015-10-14 18:45:42 +00002632#endif
drh50065652015-10-08 19:29:18 +00002633#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */