blob: 6fe3ab96768dfafc8974b083748fd7480e036192 [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){
drh633647a2017-03-22 21:24:31 +0000441 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
442 if( pNode->jnFlags & JNODE_REPLACE ){
443 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
444 return;
445 }
446 pNode = pNode->u.pPatch;
447 }
drh5634cc02015-08-17 11:28:03 +0000448 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000449 default: {
450 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000451 jsonAppendRaw(pOut, "null", 4);
452 break;
453 }
454 case JSON_TRUE: {
455 jsonAppendRaw(pOut, "true", 4);
456 break;
457 }
458 case JSON_FALSE: {
459 jsonAppendRaw(pOut, "false", 5);
460 break;
461 }
462 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000463 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000464 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000465 break;
466 }
drh08b92082020-08-10 14:18:00 +0000467 /* no break */ deliberate_fall_through
drh5634cc02015-08-17 11:28:03 +0000468 }
469 case JSON_REAL:
470 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000471 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000472 break;
473 }
474 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000475 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000476 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000477 for(;;){
478 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000479 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000480 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000481 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000482 }
drh505ad2c2015-08-21 17:33:11 +0000483 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000484 }
drh52216ad2015-08-18 02:28:03 +0000485 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
486 pNode = &pNode[pNode->u.iAppend];
487 j = 1;
drh5634cc02015-08-17 11:28:03 +0000488 }
489 jsonAppendChar(pOut, ']');
490 break;
491 }
492 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000493 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000494 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000495 for(;;){
496 while( j<=pNode->n ){
497 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
498 jsonAppendSeparator(pOut);
499 jsonRenderNode(&pNode[j], pOut, aReplace);
500 jsonAppendChar(pOut, ':');
drh633647a2017-03-22 21:24:31 +0000501 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000502 }
drh505ad2c2015-08-21 17:33:11 +0000503 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000504 }
drh52216ad2015-08-18 02:28:03 +0000505 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
506 pNode = &pNode[pNode->u.iAppend];
507 j = 1;
drh5634cc02015-08-17 11:28:03 +0000508 }
509 jsonAppendChar(pOut, '}');
510 break;
511 }
drhbd0621b2015-08-13 13:54:59 +0000512 }
drh5634cc02015-08-17 11:28:03 +0000513}
514
515/*
drhf2df7e72015-08-28 20:07:40 +0000516** Return a JsonNode and all its descendents as a JSON string.
517*/
518static void jsonReturnJson(
519 JsonNode *pNode, /* Node to return */
520 sqlite3_context *pCtx, /* Return value for this function */
521 sqlite3_value **aReplace /* Array of replacement values */
522){
523 JsonString s;
524 jsonInit(&s, pCtx);
525 jsonRenderNode(pNode, &s, aReplace);
526 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000527 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000528}
529
530/*
drh48eb03b2019-11-10 11:09:06 +0000531** Translate a single byte of Hex into an integer.
532** This routine only works if h really is a valid hexadecimal
533** character: 0..9a..fA..F
534*/
535static u8 jsonHexToInt(int h){
536 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
537#ifdef SQLITE_EBCDIC
538 h += 9*(1&~(h>>4));
539#else
540 h += 9*(1&(h>>6));
541#endif
542 return (u8)(h & 0xf);
543}
544
545/*
546** Convert a 4-byte hex string into an integer
547*/
548static u32 jsonHexToInt4(const char *z){
549 u32 v;
550 assert( safe_isxdigit(z[0]) );
551 assert( safe_isxdigit(z[1]) );
552 assert( safe_isxdigit(z[2]) );
553 assert( safe_isxdigit(z[3]) );
554 v = (jsonHexToInt(z[0])<<12)
555 + (jsonHexToInt(z[1])<<8)
556 + (jsonHexToInt(z[2])<<4)
557 + jsonHexToInt(z[3]);
558 return v;
559}
560
561/*
drh5634cc02015-08-17 11:28:03 +0000562** Make the JsonNode the return value of the function.
563*/
drhd0960592015-08-17 21:22:32 +0000564static void jsonReturn(
565 JsonNode *pNode, /* Node to return */
566 sqlite3_context *pCtx, /* Return value for this function */
567 sqlite3_value **aReplace /* Array of replacement values */
568){
drh5634cc02015-08-17 11:28:03 +0000569 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000570 default: {
571 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000572 sqlite3_result_null(pCtx);
573 break;
574 }
575 case JSON_TRUE: {
576 sqlite3_result_int(pCtx, 1);
577 break;
578 }
579 case JSON_FALSE: {
580 sqlite3_result_int(pCtx, 0);
581 break;
582 }
drh987eb1f2015-08-17 15:17:37 +0000583 case JSON_INT: {
584 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000585 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000586 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000587 while( z[0]>='0' && z[0]<='9' ){
588 unsigned v = *(z++) - '0';
589 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000590 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000591 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
592 if( v==9 ) goto int_as_real;
593 if( v==8 ){
594 if( pNode->u.zJContent[0]=='-' ){
595 sqlite3_result_int64(pCtx, SMALLEST_INT64);
596 goto int_done;
597 }else{
598 goto int_as_real;
599 }
600 }
601 }
602 i = i*10 + v;
603 }
drh52216ad2015-08-18 02:28:03 +0000604 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000605 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000606 int_done:
607 break;
drhe85e1da2021-10-01 21:01:07 +0000608 int_as_real: ; /* no break */ deliberate_fall_through
drh8deb4b82015-10-09 18:21:43 +0000609 }
610 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000611 double r;
612#ifdef SQLITE_AMALGAMATION
613 const char *z = pNode->u.zJContent;
614 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
615#else
616 r = strtod(pNode->u.zJContent, 0);
617#endif
drh8deb4b82015-10-09 18:21:43 +0000618 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000619 break;
620 }
drh5634cc02015-08-17 11:28:03 +0000621 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000622#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
623 ** json_insert() and json_replace() and those routines do not
624 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000625 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000626 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
627 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000628 }else
629#endif
630 assert( (pNode->jnFlags & JNODE_RAW)==0 );
631 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000632 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000633 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000634 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000635 }else{
636 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000637 u32 i;
638 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000639 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000640 char *zOut;
641 u32 j;
642 zOut = sqlite3_malloc( n+1 );
643 if( zOut==0 ){
644 sqlite3_result_error_nomem(pCtx);
645 break;
646 }
647 for(i=1, j=0; i<n-1; i++){
648 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000649 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000650 zOut[j++] = c;
651 }else{
652 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000653 if( c=='u' ){
drh48eb03b2019-11-10 11:09:06 +0000654 u32 v = jsonHexToInt4(z+i+1);
655 i += 4;
drh80d87402015-08-24 12:42:41 +0000656 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000657 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000658 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000659 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000660 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000661 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000662 }else{
drh48eb03b2019-11-10 11:09:06 +0000663 u32 vlo;
664 if( (v&0xfc00)==0xd800
665 && i<n-6
666 && z[i+1]=='\\'
667 && z[i+2]=='u'
668 && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
669 ){
670 /* We have a surrogate pair */
671 v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
672 i += 6;
673 zOut[j++] = 0xf0 | (v>>18);
674 zOut[j++] = 0x80 | ((v>>12)&0x3f);
675 zOut[j++] = 0x80 | ((v>>6)&0x3f);
676 zOut[j++] = 0x80 | (v&0x3f);
677 }else{
678 zOut[j++] = 0xe0 | (v>>12);
679 zOut[j++] = 0x80 | ((v>>6)&0x3f);
680 zOut[j++] = 0x80 | (v&0x3f);
681 }
drh987eb1f2015-08-17 15:17:37 +0000682 }
683 }else{
684 if( c=='b' ){
685 c = '\b';
686 }else if( c=='f' ){
687 c = '\f';
688 }else if( c=='n' ){
689 c = '\n';
690 }else if( c=='r' ){
691 c = '\r';
692 }else if( c=='t' ){
693 c = '\t';
694 }
695 zOut[j++] = c;
696 }
697 }
698 }
699 zOut[j] = 0;
700 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000701 }
702 break;
703 }
704 case JSON_ARRAY:
705 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000706 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000707 break;
708 }
709 }
drhbd0621b2015-08-13 13:54:59 +0000710}
711
drh95677942015-09-24 01:06:37 +0000712/* Forward reference */
713static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
714
715/*
716** A macro to hint to the compiler that a function should not be
717** inlined.
718*/
719#if defined(__GNUC__)
720# define JSON_NOINLINE __attribute__((noinline))
721#elif defined(_MSC_VER) && _MSC_VER>=1310
722# define JSON_NOINLINE __declspec(noinline)
723#else
724# define JSON_NOINLINE
725#endif
726
727
728static JSON_NOINLINE int jsonParseAddNodeExpand(
729 JsonParse *pParse, /* Append the node to this object */
730 u32 eType, /* Node type */
731 u32 n, /* Content size or sub-node count */
732 const char *zContent /* Content */
733){
734 u32 nNew;
735 JsonNode *pNew;
736 assert( pParse->nNode>=pParse->nAlloc );
737 if( pParse->oom ) return -1;
738 nNew = pParse->nAlloc*2 + 10;
drh2d77d802019-01-08 20:02:48 +0000739 pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
drh95677942015-09-24 01:06:37 +0000740 if( pNew==0 ){
741 pParse->oom = 1;
742 return -1;
743 }
744 pParse->nAlloc = nNew;
745 pParse->aNode = pNew;
746 assert( pParse->nNode<pParse->nAlloc );
747 return jsonParseAddNode(pParse, eType, n, zContent);
748}
749
drh5fa5c102015-08-12 16:49:40 +0000750/*
drhe9c37f32015-08-15 21:25:36 +0000751** Create a new JsonNode instance based on the arguments and append that
752** instance to the JsonParse. Return the index in pParse->aNode[] of the
753** new node, or -1 if a memory allocation fails.
754*/
755static int jsonParseAddNode(
756 JsonParse *pParse, /* Append the node to this object */
757 u32 eType, /* Node type */
758 u32 n, /* Content size or sub-node count */
759 const char *zContent /* Content */
760){
761 JsonNode *p;
762 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000763 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000764 }
765 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000766 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000767 p->jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000768 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000769 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000770 return pParse->nNode++;
771}
772
773/*
drhad875e72016-11-07 13:37:28 +0000774** Return true if z[] begins with 4 (or more) hexadecimal digits
775*/
776static int jsonIs4Hex(const char *z){
777 int i;
778 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
779 return 1;
780}
781
782/*
drhe9c37f32015-08-15 21:25:36 +0000783** Parse a single JSON value which begins at pParse->zJson[i]. Return the
784** index of the first character past the end of the value parsed.
785**
786** Return negative for a syntax error. Special cases: return -2 if the
787** first non-whitespace character is '}' and return -3 if the first
788** non-whitespace character is ']'.
789*/
790static int jsonParseValue(JsonParse *pParse, u32 i){
791 char c;
792 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000793 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000794 int x;
drh852944e2015-09-10 03:29:11 +0000795 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000796 const char *z = pParse->zJson;
797 while( safe_isspace(z[i]) ){ i++; }
798 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000799 /* Parse object */
800 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000801 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000802 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000803 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000804 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000805 x = jsonParseValue(pParse, j);
806 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000807 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000808 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000809 return -1;
810 }
drhbe9474e2015-08-22 03:05:54 +0000811 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000812 pNode = &pParse->aNode[pParse->nNode-1];
813 if( pNode->eType!=JSON_STRING ) return -1;
814 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000815 j = x;
drh9fa866a2017-04-08 18:18:22 +0000816 while( safe_isspace(z[j]) ){ j++; }
817 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000818 j++;
819 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000820 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000821 if( x<0 ) return -1;
822 j = x;
drh9fa866a2017-04-08 18:18:22 +0000823 while( safe_isspace(z[j]) ){ j++; }
824 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000825 if( c==',' ) continue;
826 if( c!='}' ) return -1;
827 break;
828 }
drhbc8f0922015-08-22 19:39:04 +0000829 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000830 return j+1;
831 }else if( c=='[' ){
832 /* Parse array */
833 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000834 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000835 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000836 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000837 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000838 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000839 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000840 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000841 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000842 return -1;
843 }
844 j = x;
drh9fa866a2017-04-08 18:18:22 +0000845 while( safe_isspace(z[j]) ){ j++; }
846 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000847 if( c==',' ) continue;
848 if( c!=']' ) return -1;
849 break;
850 }
drhbc8f0922015-08-22 19:39:04 +0000851 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000852 return j+1;
853 }else if( c=='"' ){
854 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000855 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000856 j = i+1;
857 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000858 c = z[j];
drh86715382017-04-13 00:12:32 +0000859 if( (c & ~0x1f)==0 ){
860 /* Control characters are not allowed in strings */
861 return -1;
862 }
drhe9c37f32015-08-15 21:25:36 +0000863 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000864 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000865 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
866 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000867 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000868 jnFlags = JNODE_ESCAPE;
869 }else{
870 return -1;
871 }
drhe9c37f32015-08-15 21:25:36 +0000872 }else if( c=='"' ){
873 break;
874 }
875 j++;
876 }
drh9fa866a2017-04-08 18:18:22 +0000877 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000878 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000879 return j+1;
880 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000881 && strncmp(z+i,"null",4)==0
882 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000883 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
884 return i+4;
885 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000886 && strncmp(z+i,"true",4)==0
887 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000888 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
889 return i+4;
890 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000891 && strncmp(z+i,"false",5)==0
892 && !safe_isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000893 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
894 return i+5;
895 }else if( c=='-' || (c>='0' && c<='9') ){
896 /* Parse number */
897 u8 seenDP = 0;
898 u8 seenE = 0;
drh9fa866a2017-04-08 18:18:22 +0000899 assert( '-' < '0' );
900 if( c<='0' ){
901 j = c=='-' ? i+1 : i;
902 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
903 }
drhe9c37f32015-08-15 21:25:36 +0000904 j = i+1;
905 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000906 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000907 if( c>='0' && c<='9' ) continue;
908 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000909 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000910 if( seenDP ) return -1;
911 seenDP = 1;
912 continue;
913 }
914 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000915 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000916 if( seenE ) return -1;
917 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000918 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000919 if( c=='+' || c=='-' ){
920 j++;
drh9fa866a2017-04-08 18:18:22 +0000921 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000922 }
drhd1f00682015-08-29 16:02:37 +0000923 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000924 continue;
925 }
926 break;
927 }
drh9fa866a2017-04-08 18:18:22 +0000928 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000929 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000930 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000931 return j;
932 }else if( c=='}' ){
933 return -2; /* End of {...} */
934 }else if( c==']' ){
935 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000936 }else if( c==0 ){
937 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000938 }else{
939 return -1; /* Syntax error */
940 }
941}
942
943/*
944** Parse a complete JSON string. Return 0 on success or non-zero if there
945** are any errors. If an error occurs, free all memory associated with
946** pParse.
947**
948** pParse is uninitialized when this routine is called.
949*/
drhbc8f0922015-08-22 19:39:04 +0000950static int jsonParse(
951 JsonParse *pParse, /* Initialize and fill this JsonParse object */
952 sqlite3_context *pCtx, /* Report errors here */
953 const char *zJson /* Input JSON text to be parsed */
954){
drhe9c37f32015-08-15 21:25:36 +0000955 int i;
drhe9c37f32015-08-15 21:25:36 +0000956 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000957 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000958 pParse->zJson = zJson;
959 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000960 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000961 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000962 assert( pParse->iDepth==0 );
dan2e8f5512015-09-17 17:21:09 +0000963 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000964 if( zJson[i] ) i = -1;
965 }
drhd1f00682015-08-29 16:02:37 +0000966 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000967 if( pCtx!=0 ){
968 if( pParse->oom ){
969 sqlite3_result_error_nomem(pCtx);
970 }else{
971 sqlite3_result_error(pCtx, "malformed JSON", -1);
972 }
973 }
drh505ad2c2015-08-21 17:33:11 +0000974 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000975 return 1;
976 }
977 return 0;
978}
drh301eecc2015-08-17 20:14:19 +0000979
drh505ad2c2015-08-21 17:33:11 +0000980/* Mark node i of pParse as being a child of iParent. Call recursively
981** to fill in all the descendants of node i.
982*/
983static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
984 JsonNode *pNode = &pParse->aNode[i];
985 u32 j;
986 pParse->aUp[i] = iParent;
987 switch( pNode->eType ){
988 case JSON_ARRAY: {
989 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
990 jsonParseFillInParentage(pParse, i+j, i);
991 }
992 break;
993 }
994 case JSON_OBJECT: {
995 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
996 pParse->aUp[i+j] = i;
997 jsonParseFillInParentage(pParse, i+j+1, i);
998 }
999 break;
1000 }
1001 default: {
1002 break;
1003 }
1004 }
1005}
1006
1007/*
1008** Compute the parentage of all nodes in a completed parse.
1009*/
1010static int jsonParseFindParents(JsonParse *pParse){
1011 u32 *aUp;
1012 assert( pParse->aUp==0 );
drh2d77d802019-01-08 20:02:48 +00001013 aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +00001014 if( aUp==0 ){
1015 pParse->oom = 1;
1016 return SQLITE_NOMEM;
1017 }
drh505ad2c2015-08-21 17:33:11 +00001018 jsonParseFillInParentage(pParse, 0, 0);
1019 return SQLITE_OK;
1020}
1021
drh8cb0c832015-09-22 00:21:03 +00001022/*
drh3fb153c2017-05-11 16:49:59 +00001023** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
1024*/
drhe35fc302018-08-30 01:52:10 +00001025#define JSON_CACHE_ID (-429938) /* First cache entry */
1026#define JSON_CACHE_SZ 4 /* Max number of cache entries */
drh3fb153c2017-05-11 16:49:59 +00001027
1028/*
1029** Obtain a complete parse of the JSON found in the first argument
1030** of the argv array. Use the sqlite3_get_auxdata() cache for this
1031** parse if it is available. If the cache is not available or if it
1032** is no longer valid, parse the JSON again and return the new parse,
1033** and also register the new parse so that it will be available for
1034** future sqlite3_get_auxdata() calls.
1035*/
1036static JsonParse *jsonParseCached(
1037 sqlite3_context *pCtx,
drhe35fc302018-08-30 01:52:10 +00001038 sqlite3_value **argv,
1039 sqlite3_context *pErrCtx
drh3fb153c2017-05-11 16:49:59 +00001040){
1041 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
1042 int nJson = sqlite3_value_bytes(argv[0]);
1043 JsonParse *p;
drhe35fc302018-08-30 01:52:10 +00001044 JsonParse *pMatch = 0;
1045 int iKey;
1046 int iMinKey = 0;
1047 u32 iMinHold = 0xffffffff;
1048 u32 iMaxHold = 0;
drh3fb153c2017-05-11 16:49:59 +00001049 if( zJson==0 ) return 0;
drhe35fc302018-08-30 01:52:10 +00001050 for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
1051 p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
1052 if( p==0 ){
1053 iMinKey = iKey;
1054 break;
1055 }
1056 if( pMatch==0
1057 && p->nJson==nJson
1058 && memcmp(p->zJson,zJson,nJson)==0
1059 ){
1060 p->nErr = 0;
1061 pMatch = p;
1062 }else if( p->iHold<iMinHold ){
1063 iMinHold = p->iHold;
1064 iMinKey = iKey;
1065 }
1066 if( p->iHold>iMaxHold ){
1067 iMaxHold = p->iHold;
1068 }
1069 }
1070 if( pMatch ){
1071 pMatch->nErr = 0;
1072 pMatch->iHold = iMaxHold+1;
1073 return pMatch;
drh3fb153c2017-05-11 16:49:59 +00001074 }
drh2d77d802019-01-08 20:02:48 +00001075 p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
drh3fb153c2017-05-11 16:49:59 +00001076 if( p==0 ){
1077 sqlite3_result_error_nomem(pCtx);
1078 return 0;
1079 }
1080 memset(p, 0, sizeof(*p));
1081 p->zJson = (char*)&p[1];
1082 memcpy((char*)p->zJson, zJson, nJson+1);
drhe35fc302018-08-30 01:52:10 +00001083 if( jsonParse(p, pErrCtx, p->zJson) ){
drh3fb153c2017-05-11 16:49:59 +00001084 sqlite3_free(p);
1085 return 0;
1086 }
1087 p->nJson = nJson;
drhe35fc302018-08-30 01:52:10 +00001088 p->iHold = iMaxHold+1;
1089 sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
1090 (void(*)(void*))jsonParseFree);
1091 return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
drh3fb153c2017-05-11 16:49:59 +00001092}
1093
1094/*
drh8cb0c832015-09-22 00:21:03 +00001095** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1096** a match.
1097*/
mistachkinf2c26ed2015-10-12 22:20:29 +00001098static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh8cb0c832015-09-22 00:21:03 +00001099 if( pNode->jnFlags & JNODE_RAW ){
1100 if( pNode->n!=nKey ) return 0;
1101 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
1102 }else{
1103 if( pNode->n!=nKey+2 ) return 0;
1104 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
1105 }
1106}
1107
drh52216ad2015-08-18 02:28:03 +00001108/* forward declaration */
drha7714022015-08-29 00:54:49 +00001109static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +00001110
drh987eb1f2015-08-17 15:17:37 +00001111/*
1112** Search along zPath to find the node specified. Return a pointer
1113** to that node, or NULL if zPath is malformed or if there is no such
1114** node.
drh52216ad2015-08-18 02:28:03 +00001115**
1116** If pApnd!=0, then try to append new nodes to complete zPath if it is
1117** possible to do so and if no existing node corresponds to zPath. If
1118** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +00001119*/
drha7714022015-08-29 00:54:49 +00001120static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +00001121 JsonParse *pParse, /* The JSON to search */
1122 u32 iRoot, /* Begin the search at this node */
1123 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +00001124 int *pApnd, /* Append nodes to complete path if not NULL */
1125 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +00001126){
drhbc8f0922015-08-22 19:39:04 +00001127 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001128 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001129 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001130 if( zPath[0]==0 ) return pRoot;
drh7e35e812019-07-31 12:13:58 +00001131 if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
drh987eb1f2015-08-17 15:17:37 +00001132 if( zPath[0]=='.' ){
1133 if( pRoot->eType!=JSON_OBJECT ) return 0;
1134 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001135 if( zPath[0]=='"' ){
1136 zKey = zPath + 1;
1137 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1138 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001139 if( zPath[i] ){
1140 i++;
1141 }else{
1142 *pzErr = zPath;
1143 return 0;
1144 }
drh6b43cc82015-08-19 23:02:49 +00001145 }else{
1146 zKey = zPath;
1147 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1148 nKey = i;
1149 }
drha7714022015-08-29 00:54:49 +00001150 if( nKey==0 ){
1151 *pzErr = zPath;
1152 return 0;
1153 }
drh987eb1f2015-08-17 15:17:37 +00001154 j = 1;
drh52216ad2015-08-18 02:28:03 +00001155 for(;;){
1156 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001157 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001158 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001159 }
1160 j++;
drh505ad2c2015-08-21 17:33:11 +00001161 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001162 }
drh52216ad2015-08-18 02:28:03 +00001163 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1164 iRoot += pRoot->u.iAppend;
1165 pRoot = &pParse->aNode[iRoot];
1166 j = 1;
1167 }
1168 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001169 u32 iStart, iLabel;
1170 JsonNode *pNode;
1171 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
danfe9a8322019-06-17 14:50:33 +00001172 iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
drh52216ad2015-08-18 02:28:03 +00001173 zPath += i;
drha7714022015-08-29 00:54:49 +00001174 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001175 if( pParse->oom ) return 0;
1176 if( pNode ){
1177 pRoot = &pParse->aNode[iRoot];
1178 pRoot->u.iAppend = iStart - iRoot;
1179 pRoot->jnFlags |= JNODE_APPEND;
1180 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1181 }
1182 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001183 }
drh52818642019-11-22 17:37:56 +00001184 }else if( zPath[0]=='[' ){
drh987eb1f2015-08-17 15:17:37 +00001185 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001186 j = 1;
1187 while( safe_isdigit(zPath[j]) ){
1188 i = i*10 + zPath[j] - '0';
1189 j++;
drh987eb1f2015-08-17 15:17:37 +00001190 }
drh52818642019-11-22 17:37:56 +00001191 if( j<2 || zPath[j]!=']' ){
1192 if( zPath[1]=='#' ){
1193 JsonNode *pBase = pRoot;
1194 int iBase = iRoot;
1195 if( pRoot->eType!=JSON_ARRAY ) return 0;
1196 for(;;){
1197 while( j<=pBase->n ){
1198 if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
1199 j += jsonNodeSize(&pBase[j]);
1200 }
1201 if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
1202 iBase += pBase->u.iAppend;
1203 pBase = &pParse->aNode[iBase];
1204 j = 1;
1205 }
1206 j = 2;
1207 if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
1208 unsigned int x = 0;
1209 j = 3;
1210 do{
1211 x = x*10 + zPath[j] - '0';
1212 j++;
1213 }while( safe_isdigit(zPath[j]) );
1214 if( x>i ) return 0;
1215 i -= x;
1216 }
1217 if( zPath[j]!=']' ){
1218 *pzErr = zPath;
1219 return 0;
1220 }
1221 }else{
1222 *pzErr = zPath;
1223 return 0;
1224 }
drha7714022015-08-29 00:54:49 +00001225 }
drh52818642019-11-22 17:37:56 +00001226 if( pRoot->eType!=JSON_ARRAY ) return 0;
drh3d1d2a92015-09-22 01:15:49 +00001227 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001228 j = 1;
drh52216ad2015-08-18 02:28:03 +00001229 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001230 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1231 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001232 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001233 }
1234 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1235 iRoot += pRoot->u.iAppend;
1236 pRoot = &pParse->aNode[iRoot];
1237 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001238 }
1239 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001240 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001241 }
1242 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001243 u32 iStart;
1244 JsonNode *pNode;
1245 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001246 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001247 if( pParse->oom ) return 0;
1248 if( pNode ){
1249 pRoot = &pParse->aNode[iRoot];
1250 pRoot->u.iAppend = iStart - iRoot;
1251 pRoot->jnFlags |= JNODE_APPEND;
1252 }
1253 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001254 }
drh3d1d2a92015-09-22 01:15:49 +00001255 }else{
drha7714022015-08-29 00:54:49 +00001256 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001257 }
1258 return 0;
1259}
1260
drh52216ad2015-08-18 02:28:03 +00001261/*
drhbc8f0922015-08-22 19:39:04 +00001262** Append content to pParse that will complete zPath. Return a pointer
1263** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001264*/
1265static JsonNode *jsonLookupAppend(
1266 JsonParse *pParse, /* Append content to the JSON parse */
1267 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001268 int *pApnd, /* Set this flag to 1 */
1269 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001270){
1271 *pApnd = 1;
1272 if( zPath[0]==0 ){
1273 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1274 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1275 }
1276 if( zPath[0]=='.' ){
1277 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1278 }else if( strncmp(zPath,"[0]",3)==0 ){
1279 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1280 }else{
1281 return 0;
1282 }
1283 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001284 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001285}
1286
drhbc8f0922015-08-22 19:39:04 +00001287/*
drha7714022015-08-29 00:54:49 +00001288** Return the text of a syntax error message on a JSON path. Space is
1289** obtained from sqlite3_malloc().
1290*/
1291static char *jsonPathSyntaxError(const char *zErr){
1292 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1293}
1294
1295/*
1296** Do a node lookup using zPath. Return a pointer to the node on success.
1297** Return NULL if not found or if there is an error.
1298**
1299** On an error, write an error message into pCtx and increment the
1300** pParse->nErr counter.
1301**
1302** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1303** nodes are appended.
drha7714022015-08-29 00:54:49 +00001304*/
1305static JsonNode *jsonLookup(
1306 JsonParse *pParse, /* The JSON to search */
1307 const char *zPath, /* The path to search */
1308 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001309 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001310){
1311 const char *zErr = 0;
1312 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001313 char *zMsg;
drha7714022015-08-29 00:54:49 +00001314
1315 if( zPath==0 ) return 0;
1316 if( zPath[0]!='$' ){
1317 zErr = zPath;
1318 goto lookup_err;
1319 }
1320 zPath++;
drha7714022015-08-29 00:54:49 +00001321 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001322 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001323
1324lookup_err:
1325 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001326 assert( zErr!=0 && pCtx!=0 );
1327 zMsg = jsonPathSyntaxError(zErr);
1328 if( zMsg ){
1329 sqlite3_result_error(pCtx, zMsg, -1);
1330 sqlite3_free(zMsg);
1331 }else{
1332 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001333 }
drha7714022015-08-29 00:54:49 +00001334 return 0;
1335}
1336
1337
1338/*
drhbc8f0922015-08-22 19:39:04 +00001339** Report the wrong number of arguments for json_insert(), json_replace()
1340** or json_set().
1341*/
1342static void jsonWrongNumArgs(
1343 sqlite3_context *pCtx,
1344 const char *zFuncName
1345){
1346 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1347 zFuncName);
1348 sqlite3_result_error(pCtx, zMsg, -1);
1349 sqlite3_free(zMsg);
1350}
drh52216ad2015-08-18 02:28:03 +00001351
drh29c99692017-03-24 12:35:17 +00001352/*
1353** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1354*/
1355static void jsonRemoveAllNulls(JsonNode *pNode){
1356 int i, n;
1357 assert( pNode->eType==JSON_OBJECT );
1358 n = pNode->n;
1359 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1360 switch( pNode[i].eType ){
1361 case JSON_NULL:
1362 pNode[i].jnFlags |= JNODE_REMOVE;
1363 break;
1364 case JSON_OBJECT:
1365 jsonRemoveAllNulls(&pNode[i]);
1366 break;
1367 }
1368 }
1369}
1370
drha7714022015-08-29 00:54:49 +00001371
drh987eb1f2015-08-17 15:17:37 +00001372/****************************************************************************
1373** SQL functions used for testing and debugging
1374****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001375
drh301eecc2015-08-17 20:14:19 +00001376#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001377/*
drh5634cc02015-08-17 11:28:03 +00001378** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001379** a parse of the JSON provided. Or it returns NULL if JSON is not
1380** well-formed.
1381*/
drh5634cc02015-08-17 11:28:03 +00001382static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001383 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001384 int argc,
1385 sqlite3_value **argv
1386){
drh505ad2c2015-08-21 17:33:11 +00001387 JsonString s; /* Output string - not real JSON */
1388 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001389 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001390
1391 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001392 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001393 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001394 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001395 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001396 const char *zType;
1397 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1398 assert( x.aNode[i].eType==JSON_STRING );
1399 zType = "label";
1400 }else{
1401 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001402 }
drh852944e2015-09-10 03:29:11 +00001403 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1404 i, zType, x.aNode[i].n, x.aUp[i]);
1405 if( x.aNode[i].u.zJContent!=0 ){
1406 jsonAppendRaw(&s, " ", 1);
1407 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1408 }
1409 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001410 }
drh505ad2c2015-08-21 17:33:11 +00001411 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001412 jsonResult(&s);
1413}
1414
drh5634cc02015-08-17 11:28:03 +00001415/*
drhf5ddb9c2015-09-11 00:06:41 +00001416** The json_test1(JSON) function return true (1) if the input is JSON
1417** text generated by another json function. It returns (0) if the input
1418** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001419*/
1420static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001421 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001422 int argc,
1423 sqlite3_value **argv
1424){
mistachkin16a93122015-09-11 18:05:01 +00001425 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001426 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001427}
drh301eecc2015-08-17 20:14:19 +00001428#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001429
drh987eb1f2015-08-17 15:17:37 +00001430/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001431** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001432****************************************************************************/
1433
1434/*
drh2ad96f52016-06-17 13:01:51 +00001435** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1436** corresponding to the SQL value input. Mostly this means putting
1437** double-quotes around strings and returning the unquoted string "null"
1438** when given a NULL input.
1439*/
1440static void jsonQuoteFunc(
1441 sqlite3_context *ctx,
1442 int argc,
1443 sqlite3_value **argv
1444){
1445 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001446 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001447
1448 jsonInit(&jx, ctx);
1449 jsonAppendValue(&jx, argv[0]);
1450 jsonResult(&jx);
1451 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1452}
1453
1454/*
drh987eb1f2015-08-17 15:17:37 +00001455** Implementation of the json_array(VALUE,...) function. Return a JSON
1456** array that contains all values given in arguments. Or if any argument
1457** is a BLOB, throw an error.
1458*/
1459static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001460 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001461 int argc,
1462 sqlite3_value **argv
1463){
1464 int i;
drh505ad2c2015-08-21 17:33:11 +00001465 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001466
drhbc8f0922015-08-22 19:39:04 +00001467 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001468 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001469 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001470 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001471 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001472 }
drhd0960592015-08-17 21:22:32 +00001473 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001474 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001475 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001476}
1477
1478
1479/*
1480** json_array_length(JSON)
1481** json_array_length(JSON, PATH)
1482**
1483** Return the number of elements in the top-level JSON array.
1484** Return 0 if the input is not a well-formed JSON array.
1485*/
1486static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001487 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001488 int argc,
1489 sqlite3_value **argv
1490){
drh3fb153c2017-05-11 16:49:59 +00001491 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001492 sqlite3_int64 n = 0;
1493 u32 i;
drha8f39a92015-09-21 22:53:16 +00001494 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001495
drhe35fc302018-08-30 01:52:10 +00001496 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001497 if( p==0 ) return;
1498 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001499 if( argc==2 ){
1500 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001501 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001502 }else{
drh3fb153c2017-05-11 16:49:59 +00001503 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001504 }
1505 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001506 return;
1507 }
1508 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001509 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1510 for(i=1; i<=pNode->n; n++){
1511 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001512 }
drh987eb1f2015-08-17 15:17:37 +00001513 }
drh3fb153c2017-05-11 16:49:59 +00001514 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001515}
1516
1517/*
drh3ad93bb2015-08-29 19:41:45 +00001518** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001519**
drh3ad93bb2015-08-29 19:41:45 +00001520** Return the element described by PATH. Return NULL if there is no
1521** PATH element. If there are multiple PATHs, then return a JSON array
1522** with the result from each path. Throw an error if the JSON or any PATH
1523** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001524*/
1525static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001526 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001527 int argc,
1528 sqlite3_value **argv
1529){
drh3fb153c2017-05-11 16:49:59 +00001530 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001531 JsonNode *pNode;
1532 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001533 JsonString jx;
1534 int i;
1535
1536 if( argc<2 ) return;
drhe35fc302018-08-30 01:52:10 +00001537 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001538 if( p==0 ) return;
drh3ad93bb2015-08-29 19:41:45 +00001539 jsonInit(&jx, ctx);
1540 jsonAppendChar(&jx, '[');
1541 for(i=1; i<argc; i++){
1542 zPath = (const char*)sqlite3_value_text(argv[i]);
drh3fb153c2017-05-11 16:49:59 +00001543 pNode = jsonLookup(p, zPath, 0, ctx);
1544 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001545 if( argc>2 ){
1546 jsonAppendSeparator(&jx);
1547 if( pNode ){
1548 jsonRenderNode(pNode, &jx, 0);
1549 }else{
1550 jsonAppendRaw(&jx, "null", 4);
1551 }
1552 }else if( pNode ){
1553 jsonReturn(pNode, ctx, 0);
1554 }
drh987eb1f2015-08-17 15:17:37 +00001555 }
drh3ad93bb2015-08-29 19:41:45 +00001556 if( argc>2 && i==argc ){
1557 jsonAppendChar(&jx, ']');
1558 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001559 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001560 }
1561 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001562}
1563
drh633647a2017-03-22 21:24:31 +00001564/* This is the RFC 7396 MergePatch algorithm.
1565*/
1566static JsonNode *jsonMergePatch(
1567 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001568 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001569 JsonNode *pPatch /* The PATCH */
1570){
drh0002d242017-03-23 00:46:15 +00001571 u32 i, j;
1572 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001573 JsonNode *pTarget;
1574 if( pPatch->eType!=JSON_OBJECT ){
1575 return pPatch;
1576 }
1577 assert( iTarget>=0 && iTarget<pParse->nNode );
1578 pTarget = &pParse->aNode[iTarget];
1579 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1580 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001581 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001582 return pPatch;
1583 }
drhbb7aa2d2017-03-23 00:13:52 +00001584 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001585 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001586 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001587 const char *zKey;
1588 assert( pPatch[i].eType==JSON_STRING );
1589 assert( pPatch[i].jnFlags & JNODE_LABEL );
1590 nKey = pPatch[i].n;
1591 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001592 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001593 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1594 assert( pTarget[j].eType==JSON_STRING );
1595 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001596 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001597 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1598 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001599 if( pPatch[i+1].eType==JSON_NULL ){
1600 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1601 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001602 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001603 if( pNew==0 ) return 0;
1604 pTarget = &pParse->aNode[iTarget];
1605 if( pNew!=&pTarget[j+1] ){
1606 pTarget[j+1].u.pPatch = pNew;
1607 pTarget[j+1].jnFlags |= JNODE_PATCH;
1608 }
1609 }
1610 break;
1611 }
1612 }
drhbb7aa2d2017-03-23 00:13:52 +00001613 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001614 int iStart, iPatch;
1615 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1616 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1617 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1618 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001619 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001620 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001621 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1622 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1623 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001624 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1625 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1626 }
1627 }
1628 return pTarget;
1629}
1630
1631/*
1632** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1633** object that is the result of running the RFC 7396 MergePatch() algorithm
1634** on the two arguments.
1635*/
drh37f03df2017-03-23 20:33:49 +00001636static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001637 sqlite3_context *ctx,
1638 int argc,
1639 sqlite3_value **argv
1640){
1641 JsonParse x; /* The JSON that is being patched */
1642 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001643 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001644
drh2fb79e92017-03-25 12:08:11 +00001645 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001646 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1647 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1648 jsonParseReset(&x);
1649 return;
1650 }
drhbb7aa2d2017-03-23 00:13:52 +00001651 pResult = jsonMergePatch(&x, 0, y.aNode);
1652 assert( pResult!=0 || x.oom );
1653 if( pResult ){
1654 jsonReturnJson(pResult, ctx, 0);
1655 }else{
1656 sqlite3_result_error_nomem(ctx);
1657 }
drh633647a2017-03-22 21:24:31 +00001658 jsonParseReset(&x);
1659 jsonParseReset(&y);
1660}
1661
1662
drh987eb1f2015-08-17 15:17:37 +00001663/*
1664** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1665** object that contains all name/value given in arguments. Or if any name
1666** is not a string or if any value is a BLOB, throw an error.
1667*/
1668static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001669 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001670 int argc,
1671 sqlite3_value **argv
1672){
1673 int i;
drh505ad2c2015-08-21 17:33:11 +00001674 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001675 const char *z;
1676 u32 n;
1677
1678 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001679 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001680 "of arguments", -1);
1681 return;
1682 }
drhbc8f0922015-08-22 19:39:04 +00001683 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001684 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001685 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001686 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001687 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001688 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001689 return;
1690 }
drhd0960592015-08-17 21:22:32 +00001691 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001692 z = (const char*)sqlite3_value_text(argv[i]);
1693 n = (u32)sqlite3_value_bytes(argv[i]);
1694 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001695 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001696 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001697 }
drhd0960592015-08-17 21:22:32 +00001698 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001699 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001700 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001701}
1702
1703
1704/*
drh301eecc2015-08-17 20:14:19 +00001705** json_remove(JSON, PATH, ...)
1706**
drh3ad93bb2015-08-29 19:41:45 +00001707** Remove the named elements from JSON and return the result. malformed
1708** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001709*/
1710static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001711 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001712 int argc,
1713 sqlite3_value **argv
1714){
1715 JsonParse x; /* The parse */
1716 JsonNode *pNode;
1717 const char *zPath;
1718 u32 i;
1719
1720 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001721 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001722 assert( x.nNode );
1723 for(i=1; i<(u32)argc; i++){
1724 zPath = (const char*)sqlite3_value_text(argv[i]);
1725 if( zPath==0 ) goto remove_done;
1726 pNode = jsonLookup(&x, zPath, 0, ctx);
1727 if( x.nErr ) goto remove_done;
1728 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1729 }
1730 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1731 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001732 }
drha7714022015-08-29 00:54:49 +00001733remove_done:
drh505ad2c2015-08-21 17:33:11 +00001734 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001735}
1736
1737/*
1738** json_replace(JSON, PATH, VALUE, ...)
1739**
1740** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001741** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001742*/
1743static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001744 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001745 int argc,
1746 sqlite3_value **argv
1747){
1748 JsonParse x; /* The parse */
1749 JsonNode *pNode;
1750 const char *zPath;
1751 u32 i;
1752
1753 if( argc<1 ) return;
1754 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001755 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001756 return;
1757 }
drhbc8f0922015-08-22 19:39:04 +00001758 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001759 assert( x.nNode );
1760 for(i=1; i<(u32)argc; i+=2){
1761 zPath = (const char*)sqlite3_value_text(argv[i]);
1762 pNode = jsonLookup(&x, zPath, 0, ctx);
1763 if( x.nErr ) goto replace_err;
1764 if( pNode ){
1765 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001766 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001767 }
drha8f39a92015-09-21 22:53:16 +00001768 }
1769 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001770 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001771 }else{
1772 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001773 }
drha7714022015-08-29 00:54:49 +00001774replace_err:
drh505ad2c2015-08-21 17:33:11 +00001775 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001776}
drh505ad2c2015-08-21 17:33:11 +00001777
drh52216ad2015-08-18 02:28:03 +00001778/*
1779** json_set(JSON, PATH, VALUE, ...)
1780**
1781** Set the value at PATH to VALUE. Create the PATH if it does not already
1782** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001783** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001784**
1785** json_insert(JSON, PATH, VALUE, ...)
1786**
1787** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001788** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001789*/
1790static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001791 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001792 int argc,
1793 sqlite3_value **argv
1794){
1795 JsonParse x; /* The parse */
1796 JsonNode *pNode;
1797 const char *zPath;
1798 u32 i;
1799 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001800 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001801
1802 if( argc<1 ) return;
1803 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001804 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001805 return;
1806 }
drhbc8f0922015-08-22 19:39:04 +00001807 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001808 assert( x.nNode );
1809 for(i=1; i<(u32)argc; i+=2){
1810 zPath = (const char*)sqlite3_value_text(argv[i]);
1811 bApnd = 0;
1812 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1813 if( x.oom ){
1814 sqlite3_result_error_nomem(ctx);
1815 goto jsonSetDone;
1816 }else if( x.nErr ){
1817 goto jsonSetDone;
1818 }else if( pNode && (bApnd || bIsSet) ){
1819 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001820 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001821 }
drha8f39a92015-09-21 22:53:16 +00001822 }
1823 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001824 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001825 }else{
1826 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001827 }
drhbc8f0922015-08-22 19:39:04 +00001828jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001829 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001830}
drh301eecc2015-08-17 20:14:19 +00001831
1832/*
drh987eb1f2015-08-17 15:17:37 +00001833** json_type(JSON)
1834** json_type(JSON, PATH)
1835**
drh3ad93bb2015-08-29 19:41:45 +00001836** Return the top-level "type" of a JSON string. Throw an error if
1837** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001838*/
1839static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001840 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001841 int argc,
1842 sqlite3_value **argv
1843){
drhe35fc302018-08-30 01:52:10 +00001844 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001845 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001846 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001847
drhe35fc302018-08-30 01:52:10 +00001848 p = jsonParseCached(ctx, argv, ctx);
1849 if( p==0 ) return;
drha8f39a92015-09-21 22:53:16 +00001850 if( argc==2 ){
1851 zPath = (const char*)sqlite3_value_text(argv[1]);
drhe35fc302018-08-30 01:52:10 +00001852 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001853 }else{
drhe35fc302018-08-30 01:52:10 +00001854 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001855 }
1856 if( pNode ){
1857 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001858 }
drh987eb1f2015-08-17 15:17:37 +00001859}
drh5634cc02015-08-17 11:28:03 +00001860
drhbc8f0922015-08-22 19:39:04 +00001861/*
1862** json_valid(JSON)
1863**
drh3ad93bb2015-08-29 19:41:45 +00001864** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1865** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001866*/
1867static void jsonValidFunc(
1868 sqlite3_context *ctx,
1869 int argc,
1870 sqlite3_value **argv
1871){
drhe35fc302018-08-30 01:52:10 +00001872 JsonParse *p; /* The parse */
mistachkin16a93122015-09-11 18:05:01 +00001873 UNUSED_PARAM(argc);
drhe35fc302018-08-30 01:52:10 +00001874 p = jsonParseCached(ctx, argv, 0);
1875 sqlite3_result_int(ctx, p!=0);
drhbc8f0922015-08-22 19:39:04 +00001876}
1877
drhff135ae2015-12-30 01:07:02 +00001878
1879/****************************************************************************
1880** Aggregate SQL function implementations
1881****************************************************************************/
1882/*
1883** json_group_array(VALUE)
1884**
1885** Return a JSON array composed of all values in the aggregate.
1886*/
1887static void jsonArrayStep(
1888 sqlite3_context *ctx,
1889 int argc,
1890 sqlite3_value **argv
1891){
1892 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001893 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001894 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1895 if( pStr ){
1896 if( pStr->zBuf==0 ){
1897 jsonInit(pStr, ctx);
1898 jsonAppendChar(pStr, '[');
drhfab5b072019-09-14 00:21:34 +00001899 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00001900 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00001901 }
dan8505d732021-04-14 12:11:39 +00001902 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00001903 jsonAppendValue(pStr, argv[0]);
1904 }
1905}
drh8be47a72018-07-05 20:05:29 +00001906static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001907 JsonString *pStr;
1908 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1909 if( pStr ){
1910 pStr->pCtx = ctx;
1911 jsonAppendChar(pStr, ']');
1912 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001913 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001914 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001915 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001916 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001917 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1918 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001919 }else{
mistachkined008ec2018-09-12 01:05:26 +00001920 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001921 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001922 }
1923 }else{
1924 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1925 }
1926 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1927}
drh8be47a72018-07-05 20:05:29 +00001928static void jsonArrayValue(sqlite3_context *ctx){
1929 jsonArrayCompute(ctx, 0);
1930}
1931static void jsonArrayFinal(sqlite3_context *ctx){
1932 jsonArrayCompute(ctx, 1);
1933}
1934
1935#ifndef SQLITE_OMIT_WINDOWFUNC
1936/*
1937** This method works for both json_group_array() and json_group_object().
1938** It works by removing the first element of the group by searching forward
1939** to the first comma (",") that is not within a string and deleting all
1940** text through that comma.
1941*/
1942static void jsonGroupInverse(
1943 sqlite3_context *ctx,
1944 int argc,
1945 sqlite3_value **argv
1946){
drhe39f3882019-09-21 17:31:03 +00001947 unsigned int i;
drh8be47a72018-07-05 20:05:29 +00001948 int inStr = 0;
drhfab5b072019-09-14 00:21:34 +00001949 int nNest = 0;
drh8be47a72018-07-05 20:05:29 +00001950 char *z;
drhfab5b072019-09-14 00:21:34 +00001951 char c;
drh8be47a72018-07-05 20:05:29 +00001952 JsonString *pStr;
drhc7bf5712018-07-09 22:49:01 +00001953 UNUSED_PARAM(argc);
1954 UNUSED_PARAM(argv);
drh8be47a72018-07-05 20:05:29 +00001955 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drh491d4c82018-07-07 20:23:46 +00001956#ifdef NEVER
drhfd4b7282018-07-07 19:47:21 +00001957 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1958 ** always have been called to initalize it */
1959 if( NEVER(!pStr) ) return;
drh491d4c82018-07-07 20:23:46 +00001960#endif
drh8be47a72018-07-05 20:05:29 +00001961 z = pStr->zBuf;
drh0e5cd342021-04-13 01:12:32 +00001962 for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
drhfab5b072019-09-14 00:21:34 +00001963 if( c=='"' ){
drh8be47a72018-07-05 20:05:29 +00001964 inStr = !inStr;
drhfab5b072019-09-14 00:21:34 +00001965 }else if( c=='\\' ){
drh8be47a72018-07-05 20:05:29 +00001966 i++;
drhfab5b072019-09-14 00:21:34 +00001967 }else if( !inStr ){
1968 if( c=='{' || c=='[' ) nNest++;
1969 if( c=='}' || c==']' ) nNest--;
drh8be47a72018-07-05 20:05:29 +00001970 }
1971 }
drh0e5cd342021-04-13 01:12:32 +00001972 if( i<pStr->nUsed ){
1973 pStr->nUsed -= i;
1974 memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
1975 z[pStr->nUsed] = 0;
1976 }else{
1977 pStr->nUsed = 1;
1978 }
drh8be47a72018-07-05 20:05:29 +00001979}
1980#else
1981# define jsonGroupInverse 0
1982#endif
1983
drhff135ae2015-12-30 01:07:02 +00001984
1985/*
1986** json_group_obj(NAME,VALUE)
1987**
1988** Return a JSON object composed of all names and values in the aggregate.
1989*/
1990static void jsonObjectStep(
1991 sqlite3_context *ctx,
1992 int argc,
1993 sqlite3_value **argv
1994){
1995 JsonString *pStr;
1996 const char *z;
1997 u32 n;
drhdf3a9072016-02-11 15:37:18 +00001998 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001999 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
2000 if( pStr ){
2001 if( pStr->zBuf==0 ){
2002 jsonInit(pStr, ctx);
2003 jsonAppendChar(pStr, '{');
drhfab5b072019-09-14 00:21:34 +00002004 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00002005 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00002006 }
drhd2f55772021-05-28 12:15:19 +00002007 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00002008 z = (const char*)sqlite3_value_text(argv[0]);
2009 n = (u32)sqlite3_value_bytes(argv[0]);
2010 jsonAppendString(pStr, z, n);
2011 jsonAppendChar(pStr, ':');
2012 jsonAppendValue(pStr, argv[1]);
2013 }
2014}
drh8be47a72018-07-05 20:05:29 +00002015static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00002016 JsonString *pStr;
2017 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
2018 if( pStr ){
2019 jsonAppendChar(pStr, '}');
2020 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00002021 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00002022 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00002023 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00002024 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00002025 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
2026 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00002027 }else{
mistachkined008ec2018-09-12 01:05:26 +00002028 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00002029 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00002030 }
2031 }else{
2032 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
2033 }
2034 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
2035}
drh8be47a72018-07-05 20:05:29 +00002036static void jsonObjectValue(sqlite3_context *ctx){
2037 jsonObjectCompute(ctx, 0);
2038}
2039static void jsonObjectFinal(sqlite3_context *ctx){
2040 jsonObjectCompute(ctx, 1);
2041}
2042
drhff135ae2015-12-30 01:07:02 +00002043
2044
drhd2975922015-08-29 17:22:33 +00002045#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00002046/****************************************************************************
2047** The json_each virtual table
2048****************************************************************************/
2049typedef struct JsonEachCursor JsonEachCursor;
2050struct JsonEachCursor {
2051 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00002052 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00002053 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00002054 u32 i; /* Index in sParse.aNode[] of current row */
2055 u32 iEnd; /* EOF when i equals or exceeds this value */
2056 u8 eType; /* Type of top-level element */
2057 u8 bRecursive; /* True for json_tree(). False for json_each() */
2058 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00002059 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00002060 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00002061};
2062
2063/* Constructor for the json_each virtual table */
2064static int jsonEachConnect(
2065 sqlite3 *db,
2066 void *pAux,
2067 int argc, const char *const*argv,
2068 sqlite3_vtab **ppVtab,
2069 char **pzErr
2070){
2071 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00002072 int rc;
drhcb6c6c62015-08-19 22:47:17 +00002073
2074/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00002075#define JEACH_KEY 0
2076#define JEACH_VALUE 1
2077#define JEACH_TYPE 2
2078#define JEACH_ATOM 3
2079#define JEACH_ID 4
2080#define JEACH_PARENT 5
2081#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00002082#define JEACH_PATH 7
drh43579192018-11-16 16:04:50 +00002083/* The xBestIndex method assumes that the JSON and ROOT columns are
2084** the last two columns in the table. Should this ever changes, be
2085** sure to update the xBestIndex method. */
drh383de692015-09-10 17:20:57 +00002086#define JEACH_JSON 8
2087#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00002088
drh6fd5c1e2015-08-21 20:37:12 +00002089 UNUSED_PARAM(pzErr);
2090 UNUSED_PARAM(argv);
2091 UNUSED_PARAM(argc);
2092 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00002093 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00002094 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2095 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00002096 if( rc==SQLITE_OK ){
2097 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2098 if( pNew==0 ) return SQLITE_NOMEM;
2099 memset(pNew, 0, sizeof(*pNew));
drh2b1c2aa2020-01-07 19:45:40 +00002100 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
drh505ad2c2015-08-21 17:33:11 +00002101 }
2102 return rc;
drhcb6c6c62015-08-19 22:47:17 +00002103}
2104
2105/* destructor for json_each virtual table */
2106static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2107 sqlite3_free(pVtab);
2108 return SQLITE_OK;
2109}
2110
drh505ad2c2015-08-21 17:33:11 +00002111/* constructor for a JsonEachCursor object for json_each(). */
2112static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00002113 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00002114
2115 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00002116 pCur = sqlite3_malloc( sizeof(*pCur) );
2117 if( pCur==0 ) return SQLITE_NOMEM;
2118 memset(pCur, 0, sizeof(*pCur));
2119 *ppCursor = &pCur->base;
2120 return SQLITE_OK;
2121}
2122
drh505ad2c2015-08-21 17:33:11 +00002123/* constructor for a JsonEachCursor object for json_tree(). */
2124static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2125 int rc = jsonEachOpenEach(p, ppCursor);
2126 if( rc==SQLITE_OK ){
2127 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2128 pCur->bRecursive = 1;
2129 }
2130 return rc;
2131}
2132
drhcb6c6c62015-08-19 22:47:17 +00002133/* Reset a JsonEachCursor back to its original state. Free any memory
2134** held. */
2135static void jsonEachCursorReset(JsonEachCursor *p){
2136 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002137 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002138 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002139 p->iRowid = 0;
2140 p->i = 0;
2141 p->iEnd = 0;
2142 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002143 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002144 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002145}
2146
2147/* Destructor for a jsonEachCursor object */
2148static int jsonEachClose(sqlite3_vtab_cursor *cur){
2149 JsonEachCursor *p = (JsonEachCursor*)cur;
2150 jsonEachCursorReset(p);
2151 sqlite3_free(cur);
2152 return SQLITE_OK;
2153}
2154
2155/* Return TRUE if the jsonEachCursor object has been advanced off the end
2156** of the JSON object */
2157static int jsonEachEof(sqlite3_vtab_cursor *cur){
2158 JsonEachCursor *p = (JsonEachCursor*)cur;
2159 return p->i >= p->iEnd;
2160}
2161
drh505ad2c2015-08-21 17:33:11 +00002162/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002163static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002164 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002165 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002166 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2167 p->i++;
drh4af352d2015-08-21 20:02:48 +00002168 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002169 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002170 u32 iUp = p->sParse.aUp[p->i];
2171 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002172 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002173 if( pUp->eType==JSON_ARRAY ){
2174 if( iUp==p->i-1 ){
2175 pUp->u.iKey = 0;
2176 }else{
2177 pUp->u.iKey++;
2178 }
drh4af352d2015-08-21 20:02:48 +00002179 }
2180 }
drh505ad2c2015-08-21 17:33:11 +00002181 }else{
drh4af352d2015-08-21 20:02:48 +00002182 switch( p->eType ){
2183 case JSON_ARRAY: {
2184 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2185 p->iRowid++;
2186 break;
2187 }
2188 case JSON_OBJECT: {
2189 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2190 p->iRowid++;
2191 break;
2192 }
2193 default: {
2194 p->i = p->iEnd;
2195 break;
2196 }
drh505ad2c2015-08-21 17:33:11 +00002197 }
2198 }
2199 return SQLITE_OK;
2200}
2201
drh4af352d2015-08-21 20:02:48 +00002202/* Append the name of the path for element i to pStr
2203*/
2204static void jsonEachComputePath(
2205 JsonEachCursor *p, /* The cursor */
2206 JsonString *pStr, /* Write the path here */
2207 u32 i /* Path to this element */
2208){
2209 JsonNode *pNode, *pUp;
2210 u32 iUp;
2211 if( i==0 ){
2212 jsonAppendChar(pStr, '$');
2213 return;
drhcb6c6c62015-08-19 22:47:17 +00002214 }
drh4af352d2015-08-21 20:02:48 +00002215 iUp = p->sParse.aUp[i];
2216 jsonEachComputePath(p, pStr, iUp);
2217 pNode = &p->sParse.aNode[i];
2218 pUp = &p->sParse.aNode[iUp];
2219 if( pUp->eType==JSON_ARRAY ){
2220 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2221 }else{
2222 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002223 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002224 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002225 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00002226 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2227 }
drhcb6c6c62015-08-19 22:47:17 +00002228}
2229
2230/* Return the value of a column */
2231static int jsonEachColumn(
2232 sqlite3_vtab_cursor *cur, /* The cursor */
2233 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2234 int i /* Which column to return */
2235){
2236 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002237 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002238 switch( i ){
2239 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002240 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002241 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002242 jsonReturn(pThis, ctx, 0);
2243 }else if( p->eType==JSON_ARRAY ){
2244 u32 iKey;
2245 if( p->bRecursive ){
2246 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002247 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002248 }else{
2249 iKey = p->iRowid;
2250 }
drh6fd5c1e2015-08-21 20:37:12 +00002251 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002252 }
2253 break;
2254 }
2255 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002256 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002257 jsonReturn(pThis, ctx, 0);
2258 break;
2259 }
2260 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002261 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002262 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2263 break;
2264 }
2265 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002266 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002267 if( pThis->eType>=JSON_ARRAY ) break;
2268 jsonReturn(pThis, ctx, 0);
2269 break;
2270 }
2271 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002272 sqlite3_result_int64(ctx,
2273 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002274 break;
2275 }
2276 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002277 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002278 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002279 }
2280 break;
2281 }
drh4af352d2015-08-21 20:02:48 +00002282 case JEACH_FULLKEY: {
2283 JsonString x;
2284 jsonInit(&x, ctx);
2285 if( p->bRecursive ){
2286 jsonEachComputePath(p, &x, p->i);
2287 }else{
drh383de692015-09-10 17:20:57 +00002288 if( p->zRoot ){
2289 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002290 }else{
2291 jsonAppendChar(&x, '$');
2292 }
2293 if( p->eType==JSON_ARRAY ){
2294 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002295 }else if( p->eType==JSON_OBJECT ){
drh4af352d2015-08-21 20:02:48 +00002296 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2297 }
2298 }
2299 jsonResult(&x);
2300 break;
2301 }
drhcb6c6c62015-08-19 22:47:17 +00002302 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002303 if( p->bRecursive ){
2304 JsonString x;
2305 jsonInit(&x, ctx);
2306 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2307 jsonResult(&x);
2308 break;
drh4af352d2015-08-21 20:02:48 +00002309 }
drh383de692015-09-10 17:20:57 +00002310 /* For json_each() path and root are the same so fall through
2311 ** into the root case */
drh08b92082020-08-10 14:18:00 +00002312 /* no break */ deliberate_fall_through
drh383de692015-09-10 17:20:57 +00002313 }
drh6850a632016-11-07 18:18:08 +00002314 default: {
drh383de692015-09-10 17:20:57 +00002315 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002316 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002317 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002318 break;
2319 }
drh3d1d2a92015-09-22 01:15:49 +00002320 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002321 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002322 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2323 break;
2324 }
2325 }
2326 return SQLITE_OK;
2327}
2328
2329/* Return the current rowid value */
2330static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2331 JsonEachCursor *p = (JsonEachCursor*)cur;
2332 *pRowid = p->iRowid;
2333 return SQLITE_OK;
2334}
2335
2336/* The query strategy is to look for an equality constraint on the json
2337** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002338** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002339** and 0 otherwise.
2340*/
2341static int jsonEachBestIndex(
2342 sqlite3_vtab *tab,
2343 sqlite3_index_info *pIdxInfo
2344){
drh43579192018-11-16 16:04:50 +00002345 int i; /* Loop counter or computed array index */
2346 int aIdx[2]; /* Index of constraints for JSON and ROOT */
2347 int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
2348 int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
drhcb6c6c62015-08-19 22:47:17 +00002349 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002350
drh43579192018-11-16 16:04:50 +00002351 /* This implementation assumes that JSON and ROOT are the last two
2352 ** columns in the table */
2353 assert( JEACH_ROOT == JEACH_JSON+1 );
drh6fd5c1e2015-08-21 20:37:12 +00002354 UNUSED_PARAM(tab);
drh43579192018-11-16 16:04:50 +00002355 aIdx[0] = aIdx[1] = -1;
drhcb6c6c62015-08-19 22:47:17 +00002356 pConstraint = pIdxInfo->aConstraint;
2357 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
drh43579192018-11-16 16:04:50 +00002358 int iCol;
2359 int iMask;
2360 if( pConstraint->iColumn < JEACH_JSON ) continue;
2361 iCol = pConstraint->iColumn - JEACH_JSON;
2362 assert( iCol==0 || iCol==1 );
2363 iMask = 1 << iCol;
2364 if( pConstraint->usable==0 ){
2365 unusableMask |= iMask;
2366 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
2367 aIdx[iCol] = i;
2368 idxMask |= iMask;
drhcb6c6c62015-08-19 22:47:17 +00002369 }
2370 }
drh43579192018-11-16 16:04:50 +00002371 if( (unusableMask & ~idxMask)!=0 ){
2372 /* If there are any unusable constraints on JSON or ROOT, then reject
2373 ** this entire plan */
2374 return SQLITE_CONSTRAINT;
2375 }
2376 if( aIdx[0]<0 ){
2377 /* No JSON input. Leave estimatedCost at the huge value that it was
2378 ** initialized to to discourage the query planner from selecting this
2379 ** plan. */
drhcb6c6c62015-08-19 22:47:17 +00002380 pIdxInfo->idxNum = 0;
drhcb6c6c62015-08-19 22:47:17 +00002381 }else{
drh505ad2c2015-08-21 17:33:11 +00002382 pIdxInfo->estimatedCost = 1.0;
drh43579192018-11-16 16:04:50 +00002383 i = aIdx[0];
2384 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
2385 pIdxInfo->aConstraintUsage[i].omit = 1;
2386 if( aIdx[1]<0 ){
2387 pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
drhcb6c6c62015-08-19 22:47:17 +00002388 }else{
drh43579192018-11-16 16:04:50 +00002389 i = aIdx[1];
2390 pIdxInfo->aConstraintUsage[i].argvIndex = 2;
2391 pIdxInfo->aConstraintUsage[i].omit = 1;
2392 pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
drhcb6c6c62015-08-19 22:47:17 +00002393 }
2394 }
2395 return SQLITE_OK;
2396}
2397
2398/* Start a search on a new JSON string */
2399static int jsonEachFilter(
2400 sqlite3_vtab_cursor *cur,
2401 int idxNum, const char *idxStr,
2402 int argc, sqlite3_value **argv
2403){
2404 JsonEachCursor *p = (JsonEachCursor*)cur;
2405 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002406 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002407 sqlite3_int64 n;
2408
drh6fd5c1e2015-08-21 20:37:12 +00002409 UNUSED_PARAM(idxStr);
2410 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002411 jsonEachCursorReset(p);
2412 if( idxNum==0 ) return SQLITE_OK;
2413 z = (const char*)sqlite3_value_text(argv[0]);
2414 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002415 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002416 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002417 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002418 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002419 if( jsonParse(&p->sParse, 0, p->zJson) ){
2420 int rc = SQLITE_NOMEM;
2421 if( p->sParse.oom==0 ){
2422 sqlite3_free(cur->pVtab->zErrMsg);
2423 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2424 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2425 }
drhcb6c6c62015-08-19 22:47:17 +00002426 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002427 return rc;
2428 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2429 jsonEachCursorReset(p);
2430 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002431 }else{
drh95677942015-09-24 01:06:37 +00002432 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002433 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002434 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002435 zRoot = (const char*)sqlite3_value_text(argv[1]);
2436 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002437 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002438 p->zRoot = sqlite3_malloc64( n+1 );
2439 if( p->zRoot==0 ) return SQLITE_NOMEM;
2440 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002441 if( zRoot[0]!='$' ){
2442 zErr = zRoot;
2443 }else{
2444 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2445 }
2446 if( zErr ){
drha7714022015-08-29 00:54:49 +00002447 sqlite3_free(cur->pVtab->zErrMsg);
2448 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002449 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002450 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2451 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002452 return SQLITE_OK;
2453 }
2454 }else{
2455 pNode = p->sParse.aNode;
2456 }
drh852944e2015-09-10 03:29:11 +00002457 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002458 p->eType = pNode->eType;
2459 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002460 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002461 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002462 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002463 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002464 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2465 p->i--;
2466 }
2467 }else{
2468 p->i++;
2469 }
drhcb6c6c62015-08-19 22:47:17 +00002470 }else{
2471 p->iEnd = p->i+1;
2472 }
2473 }
drha8f39a92015-09-21 22:53:16 +00002474 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002475}
2476
2477/* The methods of the json_each virtual table */
2478static sqlite3_module jsonEachModule = {
2479 0, /* iVersion */
2480 0, /* xCreate */
2481 jsonEachConnect, /* xConnect */
2482 jsonEachBestIndex, /* xBestIndex */
2483 jsonEachDisconnect, /* xDisconnect */
2484 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002485 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002486 jsonEachClose, /* xClose - close a cursor */
2487 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002488 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002489 jsonEachEof, /* xEof - check for end of scan */
2490 jsonEachColumn, /* xColumn - read data */
2491 jsonEachRowid, /* xRowid - read data */
2492 0, /* xUpdate */
2493 0, /* xBegin */
2494 0, /* xSync */
2495 0, /* xCommit */
2496 0, /* xRollback */
2497 0, /* xFindMethod */
2498 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002499 0, /* xSavepoint */
2500 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002501 0, /* xRollbackTo */
2502 0 /* xShadowName */
drhcb6c6c62015-08-19 22:47:17 +00002503};
2504
drh505ad2c2015-08-21 17:33:11 +00002505/* The methods of the json_tree virtual table. */
2506static sqlite3_module jsonTreeModule = {
2507 0, /* iVersion */
2508 0, /* xCreate */
2509 jsonEachConnect, /* xConnect */
2510 jsonEachBestIndex, /* xBestIndex */
2511 jsonEachDisconnect, /* xDisconnect */
2512 0, /* xDestroy */
2513 jsonEachOpenTree, /* xOpen - open a cursor */
2514 jsonEachClose, /* xClose - close a cursor */
2515 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002516 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002517 jsonEachEof, /* xEof - check for end of scan */
2518 jsonEachColumn, /* xColumn - read data */
2519 jsonEachRowid, /* xRowid - read data */
2520 0, /* xUpdate */
2521 0, /* xBegin */
2522 0, /* xSync */
2523 0, /* xCommit */
2524 0, /* xRollback */
2525 0, /* xFindMethod */
2526 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002527 0, /* xSavepoint */
2528 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002529 0, /* xRollbackTo */
2530 0 /* xShadowName */
drh505ad2c2015-08-21 17:33:11 +00002531};
drhd2975922015-08-29 17:22:33 +00002532#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002533
2534/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002535** The following routines are the only publically visible identifiers in this
2536** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002537** functions and the virtual table implemented by this file.
2538****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002539
drh2f20e132015-09-26 17:44:59 +00002540int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002541 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002542 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002543 static const struct {
2544 const char *zName;
2545 int nArg;
drh52216ad2015-08-18 02:28:03 +00002546 int flag;
drh5fa5c102015-08-12 16:49:40 +00002547 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2548 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002549 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002550 { "json_array", -1, 0, jsonArrayFunc },
2551 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2552 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002553 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002554 { "json_insert", -1, 0, jsonSetFunc },
2555 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002556 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002557 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002558 { "json_remove", -1, 0, jsonRemoveFunc },
2559 { "json_replace", -1, 0, jsonReplaceFunc },
2560 { "json_set", -1, 1, jsonSetFunc },
2561 { "json_type", 1, 0, jsonTypeFunc },
2562 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002563 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002564
drh301eecc2015-08-17 20:14:19 +00002565#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002566 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002567 { "json_parse", 1, 0, jsonParseFunc },
2568 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002569#endif
drh5fa5c102015-08-12 16:49:40 +00002570 };
drhff135ae2015-12-30 01:07:02 +00002571 static const struct {
2572 const char *zName;
2573 int nArg;
2574 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2575 void (*xFinal)(sqlite3_context*);
drh8be47a72018-07-05 20:05:29 +00002576 void (*xValue)(sqlite3_context*);
drhff135ae2015-12-30 01:07:02 +00002577 } aAgg[] = {
drh8be47a72018-07-05 20:05:29 +00002578 { "json_group_array", 1,
2579 jsonArrayStep, jsonArrayFinal, jsonArrayValue },
2580 { "json_group_object", 2,
2581 jsonObjectStep, jsonObjectFinal, jsonObjectValue },
drhff135ae2015-12-30 01:07:02 +00002582 };
drhd2975922015-08-29 17:22:33 +00002583#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002584 static const struct {
2585 const char *zName;
2586 sqlite3_module *pModule;
2587 } aMod[] = {
2588 { "json_each", &jsonEachModule },
2589 { "json_tree", &jsonTreeModule },
2590 };
drhd2975922015-08-29 17:22:33 +00002591#endif
drh79d5bc82020-01-04 01:43:02 +00002592 static const int enc =
2593 SQLITE_UTF8 |
2594 SQLITE_DETERMINISTIC |
2595 SQLITE_INNOCUOUS;
drh5fa5c102015-08-12 16:49:40 +00002596 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
drh79d5bc82020-01-04 01:43:02 +00002597 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
dan01a3b6b2019-09-13 17:05:48 +00002598 (void*)&aFunc[i].flag,
2599 aFunc[i].xFunc, 0, 0);
drh5fa5c102015-08-12 16:49:40 +00002600 }
mistachkin5a193dd2018-07-24 13:57:44 +00002601#ifndef SQLITE_OMIT_WINDOWFUNC
drhff135ae2015-12-30 01:07:02 +00002602 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
drh8be47a72018-07-05 20:05:29 +00002603 rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
drh79d5bc82020-01-04 01:43:02 +00002604 SQLITE_SUBTYPE | enc, 0,
drh8be47a72018-07-05 20:05:29 +00002605 aAgg[i].xStep, aAgg[i].xFinal,
2606 aAgg[i].xValue, jsonGroupInverse, 0);
drhff135ae2015-12-30 01:07:02 +00002607 }
mistachkin5a193dd2018-07-24 13:57:44 +00002608#endif
drhd2975922015-08-29 17:22:33 +00002609#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002610 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2611 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002612 }
drhd2975922015-08-29 17:22:33 +00002613#endif
drh5fa5c102015-08-12 16:49:40 +00002614 return rc;
2615}
drh2f20e132015-09-26 17:44:59 +00002616
2617
dan8d32e802015-10-14 18:45:42 +00002618#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002619#ifdef _WIN32
2620__declspec(dllexport)
2621#endif
2622int sqlite3_json_init(
2623 sqlite3 *db,
2624 char **pzErrMsg,
2625 const sqlite3_api_routines *pApi
2626){
2627 SQLITE_EXTENSION_INIT2(pApi);
2628 (void)pzErrMsg; /* Unused parameter */
2629 return sqlite3Json1Init(db);
2630}
dan8d32e802015-10-14 18:45:42 +00002631#endif
drh50065652015-10-08 19:29:18 +00002632#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */