blob: 7cff3d28d80d973648b23a614153f159eca4ca61 [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
dan2e8f5512015-09-17 17:21:09 +000045/*
46** Versions of isspace(), isalnum() and isdigit() to which it is safe
47** to pass signed char values.
48*/
drh49472652015-10-16 15:35:39 +000049#ifdef sqlite3Isdigit
50 /* Use the SQLite core versions if this routine is part of the
51 ** SQLite amalgamation */
drhad875e72016-11-07 13:37:28 +000052# define safe_isdigit(x) sqlite3Isdigit(x)
53# define safe_isalnum(x) sqlite3Isalnum(x)
54# define safe_isxdigit(x) sqlite3Isxdigit(x)
drh49472652015-10-16 15:35:39 +000055#else
56 /* Use the standard library for separate compilation */
57#include <ctype.h> /* amalgamator: keep */
drhad875e72016-11-07 13:37:28 +000058# define safe_isdigit(x) isdigit((unsigned char)(x))
59# define safe_isalnum(x) isalnum((unsigned char)(x))
60# define safe_isxdigit(x) isxdigit((unsigned char)(x))
drh49472652015-10-16 15:35:39 +000061#endif
dan2e8f5512015-09-17 17:21:09 +000062
drh95677942015-09-24 01:06:37 +000063/*
64** Growing our own isspace() routine this way is twice as fast as
65** the library isspace() function, resulting in a 7% overall performance
66** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
67*/
68static const char jsonIsSpace[] = {
drhb9e8f592015-10-16 15:16:06 +000069 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
drh95677942015-09-24 01:06:37 +000070 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
74 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
75 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
76 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85};
86#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
87
drh9a4718f2015-10-10 14:00:37 +000088#ifndef SQLITE_AMALGAMATION
89 /* Unsigned integer types. These are already defined in the sqliteInt.h,
90 ** but the definitions need to be repeated for separate compilation. */
91 typedef sqlite3_uint64 u64;
92 typedef unsigned int u32;
drhff6d50e2017-04-11 18:55:05 +000093 typedef unsigned short int u16;
drh9a4718f2015-10-10 14:00:37 +000094 typedef unsigned char u8;
95#endif
drh5fa5c102015-08-12 16:49:40 +000096
drh52216ad2015-08-18 02:28:03 +000097/* Objects */
drh505ad2c2015-08-21 17:33:11 +000098typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000099typedef struct JsonNode JsonNode;
100typedef struct JsonParse JsonParse;
101
drh5634cc02015-08-17 11:28:03 +0000102/* An instance of this object represents a JSON string
103** under construction. Really, this is a generic string accumulator
104** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +0000105*/
drh505ad2c2015-08-21 17:33:11 +0000106struct JsonString {
drh5fa5c102015-08-12 16:49:40 +0000107 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +0000108 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +0000109 u64 nAlloc; /* Bytes of storage available in zBuf[] */
110 u64 nUsed; /* Bytes of zBuf[] currently used */
111 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +0000112 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +0000113 char zSpace[100]; /* Initial static space */
114};
115
drhe9c37f32015-08-15 21:25:36 +0000116/* JSON type values
drhbd0621b2015-08-13 13:54:59 +0000117*/
drhe9c37f32015-08-15 21:25:36 +0000118#define JSON_NULL 0
119#define JSON_TRUE 1
120#define JSON_FALSE 2
121#define JSON_INT 3
122#define JSON_REAL 4
123#define JSON_STRING 5
124#define JSON_ARRAY 6
125#define JSON_OBJECT 7
126
drhf5ddb9c2015-09-11 00:06:41 +0000127/* The "subtype" set for JSON values */
128#define JSON_SUBTYPE 74 /* Ascii for "J" */
129
drh987eb1f2015-08-17 15:17:37 +0000130/*
131** Names of the various JSON types:
132*/
133static const char * const jsonType[] = {
134 "null", "true", "false", "integer", "real", "text", "array", "object"
135};
136
drh301eecc2015-08-17 20:14:19 +0000137/* Bit values for the JsonNode.jnFlag field
138*/
139#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
140#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
141#define JNODE_REMOVE 0x04 /* Do not output */
drh633647a2017-03-22 21:24:31 +0000142#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
143#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
144#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
145#define JNODE_LABEL 0x40 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000146
drh987eb1f2015-08-17 15:17:37 +0000147
drhe9c37f32015-08-15 21:25:36 +0000148/* A single node of parsed JSON
149*/
drhe9c37f32015-08-15 21:25:36 +0000150struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000151 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000152 u8 jnFlags; /* JNODE flags */
drhe9c37f32015-08-15 21:25:36 +0000153 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000154 union {
drh0042a972015-08-18 12:59:58 +0000155 const char *zJContent; /* Content for INT, REAL, and STRING */
156 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000157 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh633647a2017-03-22 21:24:31 +0000158 u32 iReplace; /* Replacement content for JNODE_REPLACE */
159 JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
drh52216ad2015-08-18 02:28:03 +0000160 } u;
drhe9c37f32015-08-15 21:25:36 +0000161};
162
163/* A completely parsed JSON string
164*/
drhe9c37f32015-08-15 21:25:36 +0000165struct JsonParse {
166 u32 nNode; /* Number of slots of aNode[] used */
167 u32 nAlloc; /* Number of slots of aNode[] allocated */
168 JsonNode *aNode; /* Array of nodes containing the parse */
169 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000170 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000171 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000172 u8 nErr; /* Number of errors seen */
drhff6d50e2017-04-11 18:55:05 +0000173 u16 iDepth; /* Nesting depth */
drh3fb153c2017-05-11 16:49:59 +0000174 int nJson; /* Length of the zJson string in bytes */
drhe35fc302018-08-30 01:52:10 +0000175 u32 iHold; /* Replace cache line with the lowest iHold value */
drhe9c37f32015-08-15 21:25:36 +0000176};
177
drhff6d50e2017-04-11 18:55:05 +0000178/*
179** Maximum nesting depth of JSON for this implementation.
180**
181** This limit is needed to avoid a stack overflow in the recursive
182** descent parser. A depth of 2000 is far deeper than any sane JSON
183** should go.
184*/
185#define JSON_MAX_DEPTH 2000
186
drh505ad2c2015-08-21 17:33:11 +0000187/**************************************************************************
188** Utility routines for dealing with JsonString objects
189**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000190
drh505ad2c2015-08-21 17:33:11 +0000191/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000192*/
drh505ad2c2015-08-21 17:33:11 +0000193static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000194 p->zBuf = p->zSpace;
195 p->nAlloc = sizeof(p->zSpace);
196 p->nUsed = 0;
197 p->bStatic = 1;
198}
199
drh505ad2c2015-08-21 17:33:11 +0000200/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000201*/
drh505ad2c2015-08-21 17:33:11 +0000202static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000203 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000204 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000205 jsonZero(p);
206}
207
208
drh505ad2c2015-08-21 17:33:11 +0000209/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000210** initial state.
211*/
drh505ad2c2015-08-21 17:33:11 +0000212static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000213 if( !p->bStatic ) sqlite3_free(p->zBuf);
214 jsonZero(p);
215}
216
217
218/* Report an out-of-memory (OOM) condition
219*/
drh505ad2c2015-08-21 17:33:11 +0000220static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000221 p->bErr = 1;
222 sqlite3_result_error_nomem(p->pCtx);
223 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000224}
225
226/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
227** Return zero on success. Return non-zero on an OOM error
228*/
drh505ad2c2015-08-21 17:33:11 +0000229static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000230 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000231 char *zNew;
232 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000233 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000234 zNew = sqlite3_malloc64(nTotal);
235 if( zNew==0 ){
236 jsonOom(p);
237 return SQLITE_NOMEM;
238 }
drh6fd5c1e2015-08-21 20:37:12 +0000239 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000240 p->zBuf = zNew;
241 p->bStatic = 0;
242 }else{
243 zNew = sqlite3_realloc64(p->zBuf, nTotal);
244 if( zNew==0 ){
245 jsonOom(p);
246 return SQLITE_NOMEM;
247 }
248 p->zBuf = zNew;
249 }
250 p->nAlloc = nTotal;
251 return SQLITE_OK;
252}
253
drh505ad2c2015-08-21 17:33:11 +0000254/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000255*/
drh505ad2c2015-08-21 17:33:11 +0000256static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000257 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
258 memcpy(p->zBuf+p->nUsed, zIn, N);
259 p->nUsed += N;
260}
261
drh4af352d2015-08-21 20:02:48 +0000262/* Append formatted text (not to exceed N bytes) to the JsonString.
263*/
264static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
265 va_list ap;
266 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
267 va_start(ap, zFormat);
268 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
269 va_end(ap);
270 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
271}
272
drh5634cc02015-08-17 11:28:03 +0000273/* Append a single character
274*/
drh505ad2c2015-08-21 17:33:11 +0000275static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000276 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
277 p->zBuf[p->nUsed++] = c;
278}
279
drh301eecc2015-08-17 20:14:19 +0000280/* Append a comma separator to the output buffer, if the previous
281** character is not '[' or '{'.
282*/
drh505ad2c2015-08-21 17:33:11 +0000283static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000284 char c;
285 if( p->nUsed==0 ) return;
286 c = p->zBuf[p->nUsed-1];
287 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
288}
289
drh505ad2c2015-08-21 17:33:11 +0000290/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000291** under construction. Enclose the string in "..." and escape
292** any double-quotes or backslash characters contained within the
293** string.
294*/
drh505ad2c2015-08-21 17:33:11 +0000295static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000296 u32 i;
297 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
298 p->zBuf[p->nUsed++] = '"';
299 for(i=0; i<N; i++){
drh3b7f9a62016-02-04 10:28:57 +0000300 unsigned char c = ((unsigned const char*)zIn)[i];
drh5fa5c102015-08-12 16:49:40 +0000301 if( c=='"' || c=='\\' ){
drh3b7f9a62016-02-04 10:28:57 +0000302 json_simple_escape:
drh4977ccf2015-09-19 11:57:26 +0000303 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000304 p->zBuf[p->nUsed++] = '\\';
drh3b7f9a62016-02-04 10:28:57 +0000305 }else if( c<=0x1f ){
306 static const char aSpecial[] = {
307 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
309 };
310 assert( sizeof(aSpecial)==32 );
311 assert( aSpecial['\b']=='b' );
312 assert( aSpecial['\f']=='f' );
313 assert( aSpecial['\n']=='n' );
314 assert( aSpecial['\r']=='r' );
315 assert( aSpecial['\t']=='t' );
316 if( aSpecial[c] ){
317 c = aSpecial[c];
318 goto json_simple_escape;
319 }
320 if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
321 p->zBuf[p->nUsed++] = '\\';
322 p->zBuf[p->nUsed++] = 'u';
323 p->zBuf[p->nUsed++] = '0';
324 p->zBuf[p->nUsed++] = '0';
325 p->zBuf[p->nUsed++] = '0' + (c>>4);
326 c = "0123456789abcdef"[c&0xf];
drh5fa5c102015-08-12 16:49:40 +0000327 }
328 p->zBuf[p->nUsed++] = c;
329 }
330 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000331 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000332}
333
drhd0960592015-08-17 21:22:32 +0000334/*
335** Append a function parameter value to the JSON string under
336** construction.
337*/
338static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000339 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000340 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000341){
342 switch( sqlite3_value_type(pValue) ){
343 case SQLITE_NULL: {
344 jsonAppendRaw(p, "null", 4);
345 break;
346 }
347 case SQLITE_INTEGER:
348 case SQLITE_FLOAT: {
349 const char *z = (const char*)sqlite3_value_text(pValue);
350 u32 n = (u32)sqlite3_value_bytes(pValue);
351 jsonAppendRaw(p, z, n);
352 break;
353 }
354 case SQLITE_TEXT: {
355 const char *z = (const char*)sqlite3_value_text(pValue);
356 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000357 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000358 jsonAppendRaw(p, z, n);
359 }else{
360 jsonAppendString(p, z, n);
361 }
drhd0960592015-08-17 21:22:32 +0000362 break;
363 }
364 default: {
365 if( p->bErr==0 ){
366 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
drh4a642b62016-02-05 01:55:27 +0000367 p->bErr = 2;
drhd0960592015-08-17 21:22:32 +0000368 jsonReset(p);
369 }
370 break;
371 }
372 }
373}
374
375
drhbd0621b2015-08-13 13:54:59 +0000376/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000377*/
drh505ad2c2015-08-21 17:33:11 +0000378static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000379 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000380 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
381 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
382 SQLITE_UTF8);
383 jsonZero(p);
384 }
385 assert( p->bStatic );
386}
387
drh505ad2c2015-08-21 17:33:11 +0000388/**************************************************************************
389** Utility routines for dealing with JsonNode and JsonParse objects
390**************************************************************************/
391
392/*
393** Return the number of consecutive JsonNode slots need to represent
394** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
395** OBJECT types, the number might be larger.
396**
397** Appended elements are not counted. The value returned is the number
398** by which the JsonNode counter should increment in order to go to the
399** next peer value.
400*/
401static u32 jsonNodeSize(JsonNode *pNode){
402 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
403}
404
405/*
406** Reclaim all memory allocated by a JsonParse object. But do not
407** delete the JsonParse object itself.
408*/
409static void jsonParseReset(JsonParse *pParse){
410 sqlite3_free(pParse->aNode);
411 pParse->aNode = 0;
412 pParse->nNode = 0;
413 pParse->nAlloc = 0;
414 sqlite3_free(pParse->aUp);
415 pParse->aUp = 0;
416}
417
drh5634cc02015-08-17 11:28:03 +0000418/*
drh3fb153c2017-05-11 16:49:59 +0000419** Free a JsonParse object that was obtained from sqlite3_malloc().
420*/
421static void jsonParseFree(JsonParse *pParse){
422 jsonParseReset(pParse);
423 sqlite3_free(pParse);
424}
425
426/*
drh5634cc02015-08-17 11:28:03 +0000427** Convert the JsonNode pNode into a pure JSON string and
428** append to pOut. Subsubstructure is also included. Return
429** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000430*/
drh52216ad2015-08-18 02:28:03 +0000431static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000432 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000433 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000434 sqlite3_value **aReplace /* Replacement values */
435){
drh633647a2017-03-22 21:24:31 +0000436 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
437 if( pNode->jnFlags & JNODE_REPLACE ){
438 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
439 return;
440 }
441 pNode = pNode->u.pPatch;
442 }
drh5634cc02015-08-17 11:28:03 +0000443 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000444 default: {
445 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000446 jsonAppendRaw(pOut, "null", 4);
447 break;
448 }
449 case JSON_TRUE: {
450 jsonAppendRaw(pOut, "true", 4);
451 break;
452 }
453 case JSON_FALSE: {
454 jsonAppendRaw(pOut, "false", 5);
455 break;
456 }
457 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000458 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000459 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000460 break;
461 }
462 /* Fall through into the next case */
463 }
464 case JSON_REAL:
465 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000466 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000467 break;
468 }
469 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000470 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000471 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000472 for(;;){
473 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000474 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000475 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000476 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000477 }
drh505ad2c2015-08-21 17:33:11 +0000478 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000479 }
drh52216ad2015-08-18 02:28:03 +0000480 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
481 pNode = &pNode[pNode->u.iAppend];
482 j = 1;
drh5634cc02015-08-17 11:28:03 +0000483 }
484 jsonAppendChar(pOut, ']');
485 break;
486 }
487 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000488 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000489 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000490 for(;;){
491 while( j<=pNode->n ){
492 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
493 jsonAppendSeparator(pOut);
494 jsonRenderNode(&pNode[j], pOut, aReplace);
495 jsonAppendChar(pOut, ':');
drh633647a2017-03-22 21:24:31 +0000496 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000497 }
drh505ad2c2015-08-21 17:33:11 +0000498 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000499 }
drh52216ad2015-08-18 02:28:03 +0000500 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
501 pNode = &pNode[pNode->u.iAppend];
502 j = 1;
drh5634cc02015-08-17 11:28:03 +0000503 }
504 jsonAppendChar(pOut, '}');
505 break;
506 }
drhbd0621b2015-08-13 13:54:59 +0000507 }
drh5634cc02015-08-17 11:28:03 +0000508}
509
510/*
drhf2df7e72015-08-28 20:07:40 +0000511** Return a JsonNode and all its descendents as a JSON string.
512*/
513static void jsonReturnJson(
514 JsonNode *pNode, /* Node to return */
515 sqlite3_context *pCtx, /* Return value for this function */
516 sqlite3_value **aReplace /* Array of replacement values */
517){
518 JsonString s;
519 jsonInit(&s, pCtx);
520 jsonRenderNode(pNode, &s, aReplace);
521 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000522 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000523}
524
525/*
drh5634cc02015-08-17 11:28:03 +0000526** Make the JsonNode the return value of the function.
527*/
drhd0960592015-08-17 21:22:32 +0000528static void jsonReturn(
529 JsonNode *pNode, /* Node to return */
530 sqlite3_context *pCtx, /* Return value for this function */
531 sqlite3_value **aReplace /* Array of replacement values */
532){
drh5634cc02015-08-17 11:28:03 +0000533 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000534 default: {
535 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000536 sqlite3_result_null(pCtx);
537 break;
538 }
539 case JSON_TRUE: {
540 sqlite3_result_int(pCtx, 1);
541 break;
542 }
543 case JSON_FALSE: {
544 sqlite3_result_int(pCtx, 0);
545 break;
546 }
drh987eb1f2015-08-17 15:17:37 +0000547 case JSON_INT: {
548 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000549 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000550 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000551 while( z[0]>='0' && z[0]<='9' ){
552 unsigned v = *(z++) - '0';
553 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000554 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000555 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
556 if( v==9 ) goto int_as_real;
557 if( v==8 ){
558 if( pNode->u.zJContent[0]=='-' ){
559 sqlite3_result_int64(pCtx, SMALLEST_INT64);
560 goto int_done;
561 }else{
562 goto int_as_real;
563 }
564 }
565 }
566 i = i*10 + v;
567 }
drh52216ad2015-08-18 02:28:03 +0000568 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000569 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000570 int_done:
571 break;
572 int_as_real: /* fall through to real */;
573 }
574 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000575 double r;
576#ifdef SQLITE_AMALGAMATION
577 const char *z = pNode->u.zJContent;
578 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
579#else
580 r = strtod(pNode->u.zJContent, 0);
581#endif
drh8deb4b82015-10-09 18:21:43 +0000582 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000583 break;
584 }
drh5634cc02015-08-17 11:28:03 +0000585 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000586#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
587 ** json_insert() and json_replace() and those routines do not
588 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000589 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000590 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
591 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000592 }else
593#endif
594 assert( (pNode->jnFlags & JNODE_RAW)==0 );
595 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000596 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000597 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000598 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000599 }else{
600 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000601 u32 i;
602 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000603 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000604 char *zOut;
605 u32 j;
606 zOut = sqlite3_malloc( n+1 );
607 if( zOut==0 ){
608 sqlite3_result_error_nomem(pCtx);
609 break;
610 }
611 for(i=1, j=0; i<n-1; i++){
612 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000613 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000614 zOut[j++] = c;
615 }else{
616 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000617 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000618 u32 v = 0, k;
drh27b2d1b2016-11-07 15:15:42 +0000619 for(k=0; k<4; i++, k++){
620 assert( i<n-2 );
drh8784eca2015-08-23 02:42:30 +0000621 c = z[i+1];
drh27b2d1b2016-11-07 15:15:42 +0000622 assert( safe_isxdigit(c) );
623 if( c<='9' ) v = v*16 + c - '0';
624 else if( c<='F' ) v = v*16 + c - 'A' + 10;
625 else v = v*16 + c - 'a' + 10;
drh987eb1f2015-08-17 15:17:37 +0000626 }
drh80d87402015-08-24 12:42:41 +0000627 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000628 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000629 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000630 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000631 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000632 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000633 }else{
mistachkin16a93122015-09-11 18:05:01 +0000634 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000635 zOut[j++] = 0x80 | ((v>>6)&0x3f);
636 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000637 }
638 }else{
639 if( c=='b' ){
640 c = '\b';
641 }else if( c=='f' ){
642 c = '\f';
643 }else if( c=='n' ){
644 c = '\n';
645 }else if( c=='r' ){
646 c = '\r';
647 }else if( c=='t' ){
648 c = '\t';
649 }
650 zOut[j++] = c;
651 }
652 }
653 }
654 zOut[j] = 0;
655 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000656 }
657 break;
658 }
659 case JSON_ARRAY:
660 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000661 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000662 break;
663 }
664 }
drhbd0621b2015-08-13 13:54:59 +0000665}
666
drh95677942015-09-24 01:06:37 +0000667/* Forward reference */
668static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
669
670/*
671** A macro to hint to the compiler that a function should not be
672** inlined.
673*/
674#if defined(__GNUC__)
675# define JSON_NOINLINE __attribute__((noinline))
676#elif defined(_MSC_VER) && _MSC_VER>=1310
677# define JSON_NOINLINE __declspec(noinline)
678#else
679# define JSON_NOINLINE
680#endif
681
682
683static JSON_NOINLINE int jsonParseAddNodeExpand(
684 JsonParse *pParse, /* Append the node to this object */
685 u32 eType, /* Node type */
686 u32 n, /* Content size or sub-node count */
687 const char *zContent /* Content */
688){
689 u32 nNew;
690 JsonNode *pNew;
691 assert( pParse->nNode>=pParse->nAlloc );
692 if( pParse->oom ) return -1;
693 nNew = pParse->nAlloc*2 + 10;
694 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
695 if( pNew==0 ){
696 pParse->oom = 1;
697 return -1;
698 }
699 pParse->nAlloc = nNew;
700 pParse->aNode = pNew;
701 assert( pParse->nNode<pParse->nAlloc );
702 return jsonParseAddNode(pParse, eType, n, zContent);
703}
704
drh5fa5c102015-08-12 16:49:40 +0000705/*
drhe9c37f32015-08-15 21:25:36 +0000706** Create a new JsonNode instance based on the arguments and append that
707** instance to the JsonParse. Return the index in pParse->aNode[] of the
708** new node, or -1 if a memory allocation fails.
709*/
710static int jsonParseAddNode(
711 JsonParse *pParse, /* Append the node to this object */
712 u32 eType, /* Node type */
713 u32 n, /* Content size or sub-node count */
714 const char *zContent /* Content */
715){
716 JsonNode *p;
717 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000718 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000719 }
720 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000721 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000722 p->jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000723 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000724 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000725 return pParse->nNode++;
726}
727
728/*
drhad875e72016-11-07 13:37:28 +0000729** Return true if z[] begins with 4 (or more) hexadecimal digits
730*/
731static int jsonIs4Hex(const char *z){
732 int i;
733 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
734 return 1;
735}
736
737/*
drhe9c37f32015-08-15 21:25:36 +0000738** Parse a single JSON value which begins at pParse->zJson[i]. Return the
739** index of the first character past the end of the value parsed.
740**
741** Return negative for a syntax error. Special cases: return -2 if the
742** first non-whitespace character is '}' and return -3 if the first
743** non-whitespace character is ']'.
744*/
745static int jsonParseValue(JsonParse *pParse, u32 i){
746 char c;
747 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000748 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000749 int x;
drh852944e2015-09-10 03:29:11 +0000750 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000751 const char *z = pParse->zJson;
752 while( safe_isspace(z[i]) ){ i++; }
753 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000754 /* Parse object */
755 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000756 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000757 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000758 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000759 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000760 x = jsonParseValue(pParse, j);
761 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000762 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000763 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000764 return -1;
765 }
drhbe9474e2015-08-22 03:05:54 +0000766 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000767 pNode = &pParse->aNode[pParse->nNode-1];
768 if( pNode->eType!=JSON_STRING ) return -1;
769 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000770 j = x;
drh9fa866a2017-04-08 18:18:22 +0000771 while( safe_isspace(z[j]) ){ j++; }
772 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000773 j++;
774 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000775 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000776 if( x<0 ) return -1;
777 j = x;
drh9fa866a2017-04-08 18:18:22 +0000778 while( safe_isspace(z[j]) ){ j++; }
779 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000780 if( c==',' ) continue;
781 if( c!='}' ) return -1;
782 break;
783 }
drhbc8f0922015-08-22 19:39:04 +0000784 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000785 return j+1;
786 }else if( c=='[' ){
787 /* Parse array */
788 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000789 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000790 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000791 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000792 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000793 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000794 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000795 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000796 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000797 return -1;
798 }
799 j = x;
drh9fa866a2017-04-08 18:18:22 +0000800 while( safe_isspace(z[j]) ){ j++; }
801 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000802 if( c==',' ) continue;
803 if( c!=']' ) return -1;
804 break;
805 }
drhbc8f0922015-08-22 19:39:04 +0000806 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000807 return j+1;
808 }else if( c=='"' ){
809 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000810 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000811 j = i+1;
812 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000813 c = z[j];
drh86715382017-04-13 00:12:32 +0000814 if( (c & ~0x1f)==0 ){
815 /* Control characters are not allowed in strings */
816 return -1;
817 }
drhe9c37f32015-08-15 21:25:36 +0000818 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000819 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000820 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
821 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000822 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000823 jnFlags = JNODE_ESCAPE;
824 }else{
825 return -1;
826 }
drhe9c37f32015-08-15 21:25:36 +0000827 }else if( c=='"' ){
828 break;
829 }
830 j++;
831 }
drh9fa866a2017-04-08 18:18:22 +0000832 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000833 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000834 return j+1;
835 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000836 && strncmp(z+i,"null",4)==0
837 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000838 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
839 return i+4;
840 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000841 && strncmp(z+i,"true",4)==0
842 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000843 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
844 return i+4;
845 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000846 && strncmp(z+i,"false",5)==0
847 && !safe_isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000848 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
849 return i+5;
850 }else if( c=='-' || (c>='0' && c<='9') ){
851 /* Parse number */
852 u8 seenDP = 0;
853 u8 seenE = 0;
drh9fa866a2017-04-08 18:18:22 +0000854 assert( '-' < '0' );
855 if( c<='0' ){
856 j = c=='-' ? i+1 : i;
857 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
858 }
drhe9c37f32015-08-15 21:25:36 +0000859 j = i+1;
860 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000861 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000862 if( c>='0' && c<='9' ) continue;
863 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000864 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000865 if( seenDP ) return -1;
866 seenDP = 1;
867 continue;
868 }
869 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000870 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000871 if( seenE ) return -1;
872 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000873 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000874 if( c=='+' || c=='-' ){
875 j++;
drh9fa866a2017-04-08 18:18:22 +0000876 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000877 }
drhd1f00682015-08-29 16:02:37 +0000878 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000879 continue;
880 }
881 break;
882 }
drh9fa866a2017-04-08 18:18:22 +0000883 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000884 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000885 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000886 return j;
887 }else if( c=='}' ){
888 return -2; /* End of {...} */
889 }else if( c==']' ){
890 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000891 }else if( c==0 ){
892 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000893 }else{
894 return -1; /* Syntax error */
895 }
896}
897
898/*
899** Parse a complete JSON string. Return 0 on success or non-zero if there
900** are any errors. If an error occurs, free all memory associated with
901** pParse.
902**
903** pParse is uninitialized when this routine is called.
904*/
drhbc8f0922015-08-22 19:39:04 +0000905static int jsonParse(
906 JsonParse *pParse, /* Initialize and fill this JsonParse object */
907 sqlite3_context *pCtx, /* Report errors here */
908 const char *zJson /* Input JSON text to be parsed */
909){
drhe9c37f32015-08-15 21:25:36 +0000910 int i;
drhe9c37f32015-08-15 21:25:36 +0000911 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000912 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000913 pParse->zJson = zJson;
914 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000915 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000916 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000917 assert( pParse->iDepth==0 );
dan2e8f5512015-09-17 17:21:09 +0000918 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000919 if( zJson[i] ) i = -1;
920 }
drhd1f00682015-08-29 16:02:37 +0000921 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000922 if( pCtx!=0 ){
923 if( pParse->oom ){
924 sqlite3_result_error_nomem(pCtx);
925 }else{
926 sqlite3_result_error(pCtx, "malformed JSON", -1);
927 }
928 }
drh505ad2c2015-08-21 17:33:11 +0000929 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000930 return 1;
931 }
932 return 0;
933}
drh301eecc2015-08-17 20:14:19 +0000934
drh505ad2c2015-08-21 17:33:11 +0000935/* Mark node i of pParse as being a child of iParent. Call recursively
936** to fill in all the descendants of node i.
937*/
938static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
939 JsonNode *pNode = &pParse->aNode[i];
940 u32 j;
941 pParse->aUp[i] = iParent;
942 switch( pNode->eType ){
943 case JSON_ARRAY: {
944 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
945 jsonParseFillInParentage(pParse, i+j, i);
946 }
947 break;
948 }
949 case JSON_OBJECT: {
950 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
951 pParse->aUp[i+j] = i;
952 jsonParseFillInParentage(pParse, i+j+1, i);
953 }
954 break;
955 }
956 default: {
957 break;
958 }
959 }
960}
961
962/*
963** Compute the parentage of all nodes in a completed parse.
964*/
965static int jsonParseFindParents(JsonParse *pParse){
966 u32 *aUp;
967 assert( pParse->aUp==0 );
968 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000969 if( aUp==0 ){
970 pParse->oom = 1;
971 return SQLITE_NOMEM;
972 }
drh505ad2c2015-08-21 17:33:11 +0000973 jsonParseFillInParentage(pParse, 0, 0);
974 return SQLITE_OK;
975}
976
drh8cb0c832015-09-22 00:21:03 +0000977/*
drh3fb153c2017-05-11 16:49:59 +0000978** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
979*/
drhe35fc302018-08-30 01:52:10 +0000980#define JSON_CACHE_ID (-429938) /* First cache entry */
981#define JSON_CACHE_SZ 4 /* Max number of cache entries */
drh3fb153c2017-05-11 16:49:59 +0000982
983/*
984** Obtain a complete parse of the JSON found in the first argument
985** of the argv array. Use the sqlite3_get_auxdata() cache for this
986** parse if it is available. If the cache is not available or if it
987** is no longer valid, parse the JSON again and return the new parse,
988** and also register the new parse so that it will be available for
989** future sqlite3_get_auxdata() calls.
990*/
991static JsonParse *jsonParseCached(
992 sqlite3_context *pCtx,
drhe35fc302018-08-30 01:52:10 +0000993 sqlite3_value **argv,
994 sqlite3_context *pErrCtx
drh3fb153c2017-05-11 16:49:59 +0000995){
996 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
997 int nJson = sqlite3_value_bytes(argv[0]);
998 JsonParse *p;
drhe35fc302018-08-30 01:52:10 +0000999 JsonParse *pMatch = 0;
1000 int iKey;
1001 int iMinKey = 0;
1002 u32 iMinHold = 0xffffffff;
1003 u32 iMaxHold = 0;
drh3fb153c2017-05-11 16:49:59 +00001004 if( zJson==0 ) return 0;
drhe35fc302018-08-30 01:52:10 +00001005 for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
1006 p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
1007 if( p==0 ){
1008 iMinKey = iKey;
1009 break;
1010 }
1011 if( pMatch==0
1012 && p->nJson==nJson
1013 && memcmp(p->zJson,zJson,nJson)==0
1014 ){
1015 p->nErr = 0;
1016 pMatch = p;
1017 }else if( p->iHold<iMinHold ){
1018 iMinHold = p->iHold;
1019 iMinKey = iKey;
1020 }
1021 if( p->iHold>iMaxHold ){
1022 iMaxHold = p->iHold;
1023 }
1024 }
1025 if( pMatch ){
1026 pMatch->nErr = 0;
1027 pMatch->iHold = iMaxHold+1;
1028 return pMatch;
drh3fb153c2017-05-11 16:49:59 +00001029 }
1030 p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
1031 if( p==0 ){
1032 sqlite3_result_error_nomem(pCtx);
1033 return 0;
1034 }
1035 memset(p, 0, sizeof(*p));
1036 p->zJson = (char*)&p[1];
1037 memcpy((char*)p->zJson, zJson, nJson+1);
drhe35fc302018-08-30 01:52:10 +00001038 if( jsonParse(p, pErrCtx, p->zJson) ){
drh3fb153c2017-05-11 16:49:59 +00001039 sqlite3_free(p);
1040 return 0;
1041 }
1042 p->nJson = nJson;
drhe35fc302018-08-30 01:52:10 +00001043 p->iHold = iMaxHold+1;
1044 sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
1045 (void(*)(void*))jsonParseFree);
1046 return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
drh3fb153c2017-05-11 16:49:59 +00001047}
1048
1049/*
drh8cb0c832015-09-22 00:21:03 +00001050** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1051** a match.
1052*/
mistachkinf2c26ed2015-10-12 22:20:29 +00001053static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh8cb0c832015-09-22 00:21:03 +00001054 if( pNode->jnFlags & JNODE_RAW ){
1055 if( pNode->n!=nKey ) return 0;
1056 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
1057 }else{
1058 if( pNode->n!=nKey+2 ) return 0;
1059 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
1060 }
1061}
1062
drh52216ad2015-08-18 02:28:03 +00001063/* forward declaration */
drha7714022015-08-29 00:54:49 +00001064static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +00001065
drh987eb1f2015-08-17 15:17:37 +00001066/*
1067** Search along zPath to find the node specified. Return a pointer
1068** to that node, or NULL if zPath is malformed or if there is no such
1069** node.
drh52216ad2015-08-18 02:28:03 +00001070**
1071** If pApnd!=0, then try to append new nodes to complete zPath if it is
1072** possible to do so and if no existing node corresponds to zPath. If
1073** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +00001074*/
drha7714022015-08-29 00:54:49 +00001075static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +00001076 JsonParse *pParse, /* The JSON to search */
1077 u32 iRoot, /* Begin the search at this node */
1078 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +00001079 int *pApnd, /* Append nodes to complete path if not NULL */
1080 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +00001081){
drhbc8f0922015-08-22 19:39:04 +00001082 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001083 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001084 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001085 if( zPath[0]==0 ) return pRoot;
1086 if( zPath[0]=='.' ){
1087 if( pRoot->eType!=JSON_OBJECT ) return 0;
1088 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001089 if( zPath[0]=='"' ){
1090 zKey = zPath + 1;
1091 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1092 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001093 if( zPath[i] ){
1094 i++;
1095 }else{
1096 *pzErr = zPath;
1097 return 0;
1098 }
drh6b43cc82015-08-19 23:02:49 +00001099 }else{
1100 zKey = zPath;
1101 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1102 nKey = i;
1103 }
drha7714022015-08-29 00:54:49 +00001104 if( nKey==0 ){
1105 *pzErr = zPath;
1106 return 0;
1107 }
drh987eb1f2015-08-17 15:17:37 +00001108 j = 1;
drh52216ad2015-08-18 02:28:03 +00001109 for(;;){
1110 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001111 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001112 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001113 }
1114 j++;
drh505ad2c2015-08-21 17:33:11 +00001115 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001116 }
drh52216ad2015-08-18 02:28:03 +00001117 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1118 iRoot += pRoot->u.iAppend;
1119 pRoot = &pParse->aNode[iRoot];
1120 j = 1;
1121 }
1122 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001123 u32 iStart, iLabel;
1124 JsonNode *pNode;
1125 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1126 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +00001127 zPath += i;
drha7714022015-08-29 00:54:49 +00001128 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001129 if( pParse->oom ) return 0;
1130 if( pNode ){
1131 pRoot = &pParse->aNode[iRoot];
1132 pRoot->u.iAppend = iStart - iRoot;
1133 pRoot->jnFlags |= JNODE_APPEND;
1134 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1135 }
1136 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001137 }
dan2e8f5512015-09-17 17:21:09 +00001138 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +00001139 if( pRoot->eType!=JSON_ARRAY ) return 0;
1140 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001141 j = 1;
1142 while( safe_isdigit(zPath[j]) ){
1143 i = i*10 + zPath[j] - '0';
1144 j++;
drh987eb1f2015-08-17 15:17:37 +00001145 }
drh3d1d2a92015-09-22 01:15:49 +00001146 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +00001147 *pzErr = zPath;
1148 return 0;
1149 }
drh3d1d2a92015-09-22 01:15:49 +00001150 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001151 j = 1;
drh52216ad2015-08-18 02:28:03 +00001152 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001153 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1154 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001155 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001156 }
1157 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1158 iRoot += pRoot->u.iAppend;
1159 pRoot = &pParse->aNode[iRoot];
1160 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001161 }
1162 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001163 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001164 }
1165 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001166 u32 iStart;
1167 JsonNode *pNode;
1168 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001169 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001170 if( pParse->oom ) return 0;
1171 if( pNode ){
1172 pRoot = &pParse->aNode[iRoot];
1173 pRoot->u.iAppend = iStart - iRoot;
1174 pRoot->jnFlags |= JNODE_APPEND;
1175 }
1176 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001177 }
drh3d1d2a92015-09-22 01:15:49 +00001178 }else{
drha7714022015-08-29 00:54:49 +00001179 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001180 }
1181 return 0;
1182}
1183
drh52216ad2015-08-18 02:28:03 +00001184/*
drhbc8f0922015-08-22 19:39:04 +00001185** Append content to pParse that will complete zPath. Return a pointer
1186** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001187*/
1188static JsonNode *jsonLookupAppend(
1189 JsonParse *pParse, /* Append content to the JSON parse */
1190 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001191 int *pApnd, /* Set this flag to 1 */
1192 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001193){
1194 *pApnd = 1;
1195 if( zPath[0]==0 ){
1196 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1197 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1198 }
1199 if( zPath[0]=='.' ){
1200 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1201 }else if( strncmp(zPath,"[0]",3)==0 ){
1202 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1203 }else{
1204 return 0;
1205 }
1206 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001207 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001208}
1209
drhbc8f0922015-08-22 19:39:04 +00001210/*
drha7714022015-08-29 00:54:49 +00001211** Return the text of a syntax error message on a JSON path. Space is
1212** obtained from sqlite3_malloc().
1213*/
1214static char *jsonPathSyntaxError(const char *zErr){
1215 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1216}
1217
1218/*
1219** Do a node lookup using zPath. Return a pointer to the node on success.
1220** Return NULL if not found or if there is an error.
1221**
1222** On an error, write an error message into pCtx and increment the
1223** pParse->nErr counter.
1224**
1225** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1226** nodes are appended.
drha7714022015-08-29 00:54:49 +00001227*/
1228static JsonNode *jsonLookup(
1229 JsonParse *pParse, /* The JSON to search */
1230 const char *zPath, /* The path to search */
1231 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001232 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001233){
1234 const char *zErr = 0;
1235 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001236 char *zMsg;
drha7714022015-08-29 00:54:49 +00001237
1238 if( zPath==0 ) return 0;
1239 if( zPath[0]!='$' ){
1240 zErr = zPath;
1241 goto lookup_err;
1242 }
1243 zPath++;
drha7714022015-08-29 00:54:49 +00001244 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001245 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001246
1247lookup_err:
1248 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001249 assert( zErr!=0 && pCtx!=0 );
1250 zMsg = jsonPathSyntaxError(zErr);
1251 if( zMsg ){
1252 sqlite3_result_error(pCtx, zMsg, -1);
1253 sqlite3_free(zMsg);
1254 }else{
1255 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001256 }
drha7714022015-08-29 00:54:49 +00001257 return 0;
1258}
1259
1260
1261/*
drhbc8f0922015-08-22 19:39:04 +00001262** Report the wrong number of arguments for json_insert(), json_replace()
1263** or json_set().
1264*/
1265static void jsonWrongNumArgs(
1266 sqlite3_context *pCtx,
1267 const char *zFuncName
1268){
1269 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1270 zFuncName);
1271 sqlite3_result_error(pCtx, zMsg, -1);
1272 sqlite3_free(zMsg);
1273}
drh52216ad2015-08-18 02:28:03 +00001274
drh29c99692017-03-24 12:35:17 +00001275/*
1276** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1277*/
1278static void jsonRemoveAllNulls(JsonNode *pNode){
1279 int i, n;
1280 assert( pNode->eType==JSON_OBJECT );
1281 n = pNode->n;
1282 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1283 switch( pNode[i].eType ){
1284 case JSON_NULL:
1285 pNode[i].jnFlags |= JNODE_REMOVE;
1286 break;
1287 case JSON_OBJECT:
1288 jsonRemoveAllNulls(&pNode[i]);
1289 break;
1290 }
1291 }
1292}
1293
drha7714022015-08-29 00:54:49 +00001294
drh987eb1f2015-08-17 15:17:37 +00001295/****************************************************************************
1296** SQL functions used for testing and debugging
1297****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001298
drh301eecc2015-08-17 20:14:19 +00001299#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001300/*
drh5634cc02015-08-17 11:28:03 +00001301** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001302** a parse of the JSON provided. Or it returns NULL if JSON is not
1303** well-formed.
1304*/
drh5634cc02015-08-17 11:28:03 +00001305static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001306 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001307 int argc,
1308 sqlite3_value **argv
1309){
drh505ad2c2015-08-21 17:33:11 +00001310 JsonString s; /* Output string - not real JSON */
1311 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001312 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001313
1314 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001315 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001316 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001317 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001318 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001319 const char *zType;
1320 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1321 assert( x.aNode[i].eType==JSON_STRING );
1322 zType = "label";
1323 }else{
1324 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001325 }
drh852944e2015-09-10 03:29:11 +00001326 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1327 i, zType, x.aNode[i].n, x.aUp[i]);
1328 if( x.aNode[i].u.zJContent!=0 ){
1329 jsonAppendRaw(&s, " ", 1);
1330 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1331 }
1332 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001333 }
drh505ad2c2015-08-21 17:33:11 +00001334 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001335 jsonResult(&s);
1336}
1337
drh5634cc02015-08-17 11:28:03 +00001338/*
drhf5ddb9c2015-09-11 00:06:41 +00001339** The json_test1(JSON) function return true (1) if the input is JSON
1340** text generated by another json function. It returns (0) if the input
1341** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001342*/
1343static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001344 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001345 int argc,
1346 sqlite3_value **argv
1347){
mistachkin16a93122015-09-11 18:05:01 +00001348 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001349 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001350}
drh301eecc2015-08-17 20:14:19 +00001351#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001352
drh987eb1f2015-08-17 15:17:37 +00001353/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001354** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001355****************************************************************************/
1356
1357/*
drh2ad96f52016-06-17 13:01:51 +00001358** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1359** corresponding to the SQL value input. Mostly this means putting
1360** double-quotes around strings and returning the unquoted string "null"
1361** when given a NULL input.
1362*/
1363static void jsonQuoteFunc(
1364 sqlite3_context *ctx,
1365 int argc,
1366 sqlite3_value **argv
1367){
1368 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001369 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001370
1371 jsonInit(&jx, ctx);
1372 jsonAppendValue(&jx, argv[0]);
1373 jsonResult(&jx);
1374 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1375}
1376
1377/*
drh987eb1f2015-08-17 15:17:37 +00001378** Implementation of the json_array(VALUE,...) function. Return a JSON
1379** array that contains all values given in arguments. Or if any argument
1380** is a BLOB, throw an error.
1381*/
1382static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001383 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001384 int argc,
1385 sqlite3_value **argv
1386){
1387 int i;
drh505ad2c2015-08-21 17:33:11 +00001388 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001389
drhbc8f0922015-08-22 19:39:04 +00001390 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001391 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001392 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001393 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001394 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001395 }
drhd0960592015-08-17 21:22:32 +00001396 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001397 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001398 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001399}
1400
1401
1402/*
1403** json_array_length(JSON)
1404** json_array_length(JSON, PATH)
1405**
1406** Return the number of elements in the top-level JSON array.
1407** Return 0 if the input is not a well-formed JSON array.
1408*/
1409static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001410 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001411 int argc,
1412 sqlite3_value **argv
1413){
drh3fb153c2017-05-11 16:49:59 +00001414 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001415 sqlite3_int64 n = 0;
1416 u32 i;
drha8f39a92015-09-21 22:53:16 +00001417 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001418
drhe35fc302018-08-30 01:52:10 +00001419 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001420 if( p==0 ) return;
1421 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001422 if( argc==2 ){
1423 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001424 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001425 }else{
drh3fb153c2017-05-11 16:49:59 +00001426 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001427 }
1428 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001429 return;
1430 }
1431 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001432 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1433 for(i=1; i<=pNode->n; n++){
1434 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001435 }
drh987eb1f2015-08-17 15:17:37 +00001436 }
drh3fb153c2017-05-11 16:49:59 +00001437 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001438}
1439
1440/*
drh3ad93bb2015-08-29 19:41:45 +00001441** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001442**
drh3ad93bb2015-08-29 19:41:45 +00001443** Return the element described by PATH. Return NULL if there is no
1444** PATH element. If there are multiple PATHs, then return a JSON array
1445** with the result from each path. Throw an error if the JSON or any PATH
1446** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001447*/
1448static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001449 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001450 int argc,
1451 sqlite3_value **argv
1452){
drh3fb153c2017-05-11 16:49:59 +00001453 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001454 JsonNode *pNode;
1455 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001456 JsonString jx;
1457 int i;
1458
1459 if( argc<2 ) return;
drhe35fc302018-08-30 01:52:10 +00001460 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001461 if( p==0 ) return;
drh3ad93bb2015-08-29 19:41:45 +00001462 jsonInit(&jx, ctx);
1463 jsonAppendChar(&jx, '[');
1464 for(i=1; i<argc; i++){
1465 zPath = (const char*)sqlite3_value_text(argv[i]);
drh3fb153c2017-05-11 16:49:59 +00001466 pNode = jsonLookup(p, zPath, 0, ctx);
1467 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001468 if( argc>2 ){
1469 jsonAppendSeparator(&jx);
1470 if( pNode ){
1471 jsonRenderNode(pNode, &jx, 0);
1472 }else{
1473 jsonAppendRaw(&jx, "null", 4);
1474 }
1475 }else if( pNode ){
1476 jsonReturn(pNode, ctx, 0);
1477 }
drh987eb1f2015-08-17 15:17:37 +00001478 }
drh3ad93bb2015-08-29 19:41:45 +00001479 if( argc>2 && i==argc ){
1480 jsonAppendChar(&jx, ']');
1481 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001482 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001483 }
1484 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001485}
1486
drh633647a2017-03-22 21:24:31 +00001487/* This is the RFC 7396 MergePatch algorithm.
1488*/
1489static JsonNode *jsonMergePatch(
1490 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001491 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001492 JsonNode *pPatch /* The PATCH */
1493){
drh0002d242017-03-23 00:46:15 +00001494 u32 i, j;
1495 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001496 JsonNode *pTarget;
1497 if( pPatch->eType!=JSON_OBJECT ){
1498 return pPatch;
1499 }
1500 assert( iTarget>=0 && iTarget<pParse->nNode );
1501 pTarget = &pParse->aNode[iTarget];
1502 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1503 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001504 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001505 return pPatch;
1506 }
drhbb7aa2d2017-03-23 00:13:52 +00001507 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001508 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001509 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001510 const char *zKey;
1511 assert( pPatch[i].eType==JSON_STRING );
1512 assert( pPatch[i].jnFlags & JNODE_LABEL );
1513 nKey = pPatch[i].n;
1514 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001515 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001516 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1517 assert( pTarget[j].eType==JSON_STRING );
1518 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001519 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001520 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1521 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001522 if( pPatch[i+1].eType==JSON_NULL ){
1523 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1524 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001525 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001526 if( pNew==0 ) return 0;
1527 pTarget = &pParse->aNode[iTarget];
1528 if( pNew!=&pTarget[j+1] ){
1529 pTarget[j+1].u.pPatch = pNew;
1530 pTarget[j+1].jnFlags |= JNODE_PATCH;
1531 }
1532 }
1533 break;
1534 }
1535 }
drhbb7aa2d2017-03-23 00:13:52 +00001536 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001537 int iStart, iPatch;
1538 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1539 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1540 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1541 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001542 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001543 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001544 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1545 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1546 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001547 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1548 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1549 }
1550 }
1551 return pTarget;
1552}
1553
1554/*
1555** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1556** object that is the result of running the RFC 7396 MergePatch() algorithm
1557** on the two arguments.
1558*/
drh37f03df2017-03-23 20:33:49 +00001559static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001560 sqlite3_context *ctx,
1561 int argc,
1562 sqlite3_value **argv
1563){
1564 JsonParse x; /* The JSON that is being patched */
1565 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001566 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001567
drh2fb79e92017-03-25 12:08:11 +00001568 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001569 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1570 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1571 jsonParseReset(&x);
1572 return;
1573 }
drhbb7aa2d2017-03-23 00:13:52 +00001574 pResult = jsonMergePatch(&x, 0, y.aNode);
1575 assert( pResult!=0 || x.oom );
1576 if( pResult ){
1577 jsonReturnJson(pResult, ctx, 0);
1578 }else{
1579 sqlite3_result_error_nomem(ctx);
1580 }
drh633647a2017-03-22 21:24:31 +00001581 jsonParseReset(&x);
1582 jsonParseReset(&y);
1583}
1584
1585
drh987eb1f2015-08-17 15:17:37 +00001586/*
1587** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1588** object that contains all name/value given in arguments. Or if any name
1589** is not a string or if any value is a BLOB, throw an error.
1590*/
1591static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001592 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001593 int argc,
1594 sqlite3_value **argv
1595){
1596 int i;
drh505ad2c2015-08-21 17:33:11 +00001597 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001598 const char *z;
1599 u32 n;
1600
1601 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001602 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001603 "of arguments", -1);
1604 return;
1605 }
drhbc8f0922015-08-22 19:39:04 +00001606 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001607 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001608 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001609 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001610 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001611 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001612 return;
1613 }
drhd0960592015-08-17 21:22:32 +00001614 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001615 z = (const char*)sqlite3_value_text(argv[i]);
1616 n = (u32)sqlite3_value_bytes(argv[i]);
1617 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001618 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001619 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001620 }
drhd0960592015-08-17 21:22:32 +00001621 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001622 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001623 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001624}
1625
1626
1627/*
drh301eecc2015-08-17 20:14:19 +00001628** json_remove(JSON, PATH, ...)
1629**
drh3ad93bb2015-08-29 19:41:45 +00001630** Remove the named elements from JSON and return the result. malformed
1631** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001632*/
1633static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001634 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001635 int argc,
1636 sqlite3_value **argv
1637){
1638 JsonParse x; /* The parse */
1639 JsonNode *pNode;
1640 const char *zPath;
1641 u32 i;
1642
1643 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001644 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001645 assert( x.nNode );
1646 for(i=1; i<(u32)argc; i++){
1647 zPath = (const char*)sqlite3_value_text(argv[i]);
1648 if( zPath==0 ) goto remove_done;
1649 pNode = jsonLookup(&x, zPath, 0, ctx);
1650 if( x.nErr ) goto remove_done;
1651 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1652 }
1653 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1654 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001655 }
drha7714022015-08-29 00:54:49 +00001656remove_done:
drh505ad2c2015-08-21 17:33:11 +00001657 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001658}
1659
1660/*
1661** json_replace(JSON, PATH, VALUE, ...)
1662**
1663** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001664** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001665*/
1666static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001667 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001668 int argc,
1669 sqlite3_value **argv
1670){
1671 JsonParse x; /* The parse */
1672 JsonNode *pNode;
1673 const char *zPath;
1674 u32 i;
1675
1676 if( argc<1 ) return;
1677 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001678 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001679 return;
1680 }
drhbc8f0922015-08-22 19:39:04 +00001681 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001682 assert( x.nNode );
1683 for(i=1; i<(u32)argc; i+=2){
1684 zPath = (const char*)sqlite3_value_text(argv[i]);
1685 pNode = jsonLookup(&x, zPath, 0, ctx);
1686 if( x.nErr ) goto replace_err;
1687 if( pNode ){
1688 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001689 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001690 }
drha8f39a92015-09-21 22:53:16 +00001691 }
1692 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001693 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001694 }else{
1695 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001696 }
drha7714022015-08-29 00:54:49 +00001697replace_err:
drh505ad2c2015-08-21 17:33:11 +00001698 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001699}
drh505ad2c2015-08-21 17:33:11 +00001700
drh52216ad2015-08-18 02:28:03 +00001701/*
1702** json_set(JSON, PATH, VALUE, ...)
1703**
1704** Set the value at PATH to VALUE. Create the PATH if it does not already
1705** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001706** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001707**
1708** json_insert(JSON, PATH, VALUE, ...)
1709**
1710** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001711** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001712*/
1713static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001714 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001715 int argc,
1716 sqlite3_value **argv
1717){
1718 JsonParse x; /* The parse */
1719 JsonNode *pNode;
1720 const char *zPath;
1721 u32 i;
1722 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001723 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001724
1725 if( argc<1 ) return;
1726 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001727 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001728 return;
1729 }
drhbc8f0922015-08-22 19:39:04 +00001730 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001731 assert( x.nNode );
1732 for(i=1; i<(u32)argc; i+=2){
1733 zPath = (const char*)sqlite3_value_text(argv[i]);
1734 bApnd = 0;
1735 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1736 if( x.oom ){
1737 sqlite3_result_error_nomem(ctx);
1738 goto jsonSetDone;
1739 }else if( x.nErr ){
1740 goto jsonSetDone;
1741 }else if( pNode && (bApnd || bIsSet) ){
1742 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001743 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001744 }
drha8f39a92015-09-21 22:53:16 +00001745 }
1746 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001747 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001748 }else{
1749 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001750 }
drhbc8f0922015-08-22 19:39:04 +00001751jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001752 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001753}
drh301eecc2015-08-17 20:14:19 +00001754
1755/*
drh987eb1f2015-08-17 15:17:37 +00001756** json_type(JSON)
1757** json_type(JSON, PATH)
1758**
drh3ad93bb2015-08-29 19:41:45 +00001759** Return the top-level "type" of a JSON string. Throw an error if
1760** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001761*/
1762static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001763 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001764 int argc,
1765 sqlite3_value **argv
1766){
drhe35fc302018-08-30 01:52:10 +00001767 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001768 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001769 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001770
drhe35fc302018-08-30 01:52:10 +00001771 p = jsonParseCached(ctx, argv, ctx);
1772 if( p==0 ) return;
drha8f39a92015-09-21 22:53:16 +00001773 if( argc==2 ){
1774 zPath = (const char*)sqlite3_value_text(argv[1]);
drhe35fc302018-08-30 01:52:10 +00001775 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001776 }else{
drhe35fc302018-08-30 01:52:10 +00001777 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001778 }
1779 if( pNode ){
1780 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001781 }
drh987eb1f2015-08-17 15:17:37 +00001782}
drh5634cc02015-08-17 11:28:03 +00001783
drhbc8f0922015-08-22 19:39:04 +00001784/*
1785** json_valid(JSON)
1786**
drh3ad93bb2015-08-29 19:41:45 +00001787** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1788** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001789*/
1790static void jsonValidFunc(
1791 sqlite3_context *ctx,
1792 int argc,
1793 sqlite3_value **argv
1794){
drhe35fc302018-08-30 01:52:10 +00001795 JsonParse *p; /* The parse */
mistachkin16a93122015-09-11 18:05:01 +00001796 UNUSED_PARAM(argc);
drhe35fc302018-08-30 01:52:10 +00001797 p = jsonParseCached(ctx, argv, 0);
1798 sqlite3_result_int(ctx, p!=0);
drhbc8f0922015-08-22 19:39:04 +00001799}
1800
drhff135ae2015-12-30 01:07:02 +00001801
1802/****************************************************************************
1803** Aggregate SQL function implementations
1804****************************************************************************/
1805/*
1806** json_group_array(VALUE)
1807**
1808** Return a JSON array composed of all values in the aggregate.
1809*/
1810static void jsonArrayStep(
1811 sqlite3_context *ctx,
1812 int argc,
1813 sqlite3_value **argv
1814){
1815 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001816 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001817 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1818 if( pStr ){
1819 if( pStr->zBuf==0 ){
1820 jsonInit(pStr, ctx);
1821 jsonAppendChar(pStr, '[');
1822 }else{
1823 jsonAppendChar(pStr, ',');
1824 pStr->pCtx = ctx;
1825 }
1826 jsonAppendValue(pStr, argv[0]);
1827 }
1828}
drh8be47a72018-07-05 20:05:29 +00001829static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001830 JsonString *pStr;
1831 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1832 if( pStr ){
1833 pStr->pCtx = ctx;
1834 jsonAppendChar(pStr, ']');
1835 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001836 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001837 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001838 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001839 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001840 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1841 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001842 }else{
mistachkined008ec2018-09-12 01:05:26 +00001843 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001844 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001845 }
1846 }else{
1847 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1848 }
1849 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1850}
drh8be47a72018-07-05 20:05:29 +00001851static void jsonArrayValue(sqlite3_context *ctx){
1852 jsonArrayCompute(ctx, 0);
1853}
1854static void jsonArrayFinal(sqlite3_context *ctx){
1855 jsonArrayCompute(ctx, 1);
1856}
1857
1858#ifndef SQLITE_OMIT_WINDOWFUNC
1859/*
1860** This method works for both json_group_array() and json_group_object().
1861** It works by removing the first element of the group by searching forward
1862** to the first comma (",") that is not within a string and deleting all
1863** text through that comma.
1864*/
1865static void jsonGroupInverse(
1866 sqlite3_context *ctx,
1867 int argc,
1868 sqlite3_value **argv
1869){
1870 int i;
1871 int inStr = 0;
1872 char *z;
1873 JsonString *pStr;
drhc7bf5712018-07-09 22:49:01 +00001874 UNUSED_PARAM(argc);
1875 UNUSED_PARAM(argv);
drh8be47a72018-07-05 20:05:29 +00001876 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drh491d4c82018-07-07 20:23:46 +00001877#ifdef NEVER
drhfd4b7282018-07-07 19:47:21 +00001878 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1879 ** always have been called to initalize it */
1880 if( NEVER(!pStr) ) return;
drh491d4c82018-07-07 20:23:46 +00001881#endif
drh8be47a72018-07-05 20:05:29 +00001882 z = pStr->zBuf;
1883 for(i=1; z[i]!=',' || inStr; i++){
1884 assert( i<pStr->nUsed );
1885 if( z[i]=='"' ){
1886 inStr = !inStr;
1887 }else if( z[i]=='\\' ){
1888 i++;
1889 }
1890 }
1891 pStr->nUsed -= i;
mistachkined008ec2018-09-12 01:05:26 +00001892 memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
drh8be47a72018-07-05 20:05:29 +00001893}
1894#else
1895# define jsonGroupInverse 0
1896#endif
1897
drhff135ae2015-12-30 01:07:02 +00001898
1899/*
1900** json_group_obj(NAME,VALUE)
1901**
1902** Return a JSON object composed of all names and values in the aggregate.
1903*/
1904static void jsonObjectStep(
1905 sqlite3_context *ctx,
1906 int argc,
1907 sqlite3_value **argv
1908){
1909 JsonString *pStr;
1910 const char *z;
1911 u32 n;
drhdf3a9072016-02-11 15:37:18 +00001912 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001913 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1914 if( pStr ){
1915 if( pStr->zBuf==0 ){
1916 jsonInit(pStr, ctx);
1917 jsonAppendChar(pStr, '{');
1918 }else{
1919 jsonAppendChar(pStr, ',');
1920 pStr->pCtx = ctx;
1921 }
1922 z = (const char*)sqlite3_value_text(argv[0]);
1923 n = (u32)sqlite3_value_bytes(argv[0]);
1924 jsonAppendString(pStr, z, n);
1925 jsonAppendChar(pStr, ':');
1926 jsonAppendValue(pStr, argv[1]);
1927 }
1928}
drh8be47a72018-07-05 20:05:29 +00001929static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001930 JsonString *pStr;
1931 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1932 if( pStr ){
1933 jsonAppendChar(pStr, '}');
1934 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00001935 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001936 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001937 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001938 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001939 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1940 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001941 }else{
mistachkined008ec2018-09-12 01:05:26 +00001942 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001943 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001944 }
1945 }else{
1946 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
1947 }
1948 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1949}
drh8be47a72018-07-05 20:05:29 +00001950static void jsonObjectValue(sqlite3_context *ctx){
1951 jsonObjectCompute(ctx, 0);
1952}
1953static void jsonObjectFinal(sqlite3_context *ctx){
1954 jsonObjectCompute(ctx, 1);
1955}
1956
drhff135ae2015-12-30 01:07:02 +00001957
1958
drhd2975922015-08-29 17:22:33 +00001959#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001960/****************************************************************************
1961** The json_each virtual table
1962****************************************************************************/
1963typedef struct JsonEachCursor JsonEachCursor;
1964struct JsonEachCursor {
1965 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001966 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001967 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001968 u32 i; /* Index in sParse.aNode[] of current row */
1969 u32 iEnd; /* EOF when i equals or exceeds this value */
1970 u8 eType; /* Type of top-level element */
1971 u8 bRecursive; /* True for json_tree(). False for json_each() */
1972 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001973 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001974 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001975};
1976
1977/* Constructor for the json_each virtual table */
1978static int jsonEachConnect(
1979 sqlite3 *db,
1980 void *pAux,
1981 int argc, const char *const*argv,
1982 sqlite3_vtab **ppVtab,
1983 char **pzErr
1984){
1985 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001986 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001987
1988/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001989#define JEACH_KEY 0
1990#define JEACH_VALUE 1
1991#define JEACH_TYPE 2
1992#define JEACH_ATOM 3
1993#define JEACH_ID 4
1994#define JEACH_PARENT 5
1995#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001996#define JEACH_PATH 7
1997#define JEACH_JSON 8
1998#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001999
drh6fd5c1e2015-08-21 20:37:12 +00002000 UNUSED_PARAM(pzErr);
2001 UNUSED_PARAM(argv);
2002 UNUSED_PARAM(argc);
2003 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00002004 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00002005 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2006 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00002007 if( rc==SQLITE_OK ){
2008 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2009 if( pNew==0 ) return SQLITE_NOMEM;
2010 memset(pNew, 0, sizeof(*pNew));
2011 }
2012 return rc;
drhcb6c6c62015-08-19 22:47:17 +00002013}
2014
2015/* destructor for json_each virtual table */
2016static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2017 sqlite3_free(pVtab);
2018 return SQLITE_OK;
2019}
2020
drh505ad2c2015-08-21 17:33:11 +00002021/* constructor for a JsonEachCursor object for json_each(). */
2022static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00002023 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00002024
2025 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00002026 pCur = sqlite3_malloc( sizeof(*pCur) );
2027 if( pCur==0 ) return SQLITE_NOMEM;
2028 memset(pCur, 0, sizeof(*pCur));
2029 *ppCursor = &pCur->base;
2030 return SQLITE_OK;
2031}
2032
drh505ad2c2015-08-21 17:33:11 +00002033/* constructor for a JsonEachCursor object for json_tree(). */
2034static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2035 int rc = jsonEachOpenEach(p, ppCursor);
2036 if( rc==SQLITE_OK ){
2037 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2038 pCur->bRecursive = 1;
2039 }
2040 return rc;
2041}
2042
drhcb6c6c62015-08-19 22:47:17 +00002043/* Reset a JsonEachCursor back to its original state. Free any memory
2044** held. */
2045static void jsonEachCursorReset(JsonEachCursor *p){
2046 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002047 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002048 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002049 p->iRowid = 0;
2050 p->i = 0;
2051 p->iEnd = 0;
2052 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002053 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002054 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002055}
2056
2057/* Destructor for a jsonEachCursor object */
2058static int jsonEachClose(sqlite3_vtab_cursor *cur){
2059 JsonEachCursor *p = (JsonEachCursor*)cur;
2060 jsonEachCursorReset(p);
2061 sqlite3_free(cur);
2062 return SQLITE_OK;
2063}
2064
2065/* Return TRUE if the jsonEachCursor object has been advanced off the end
2066** of the JSON object */
2067static int jsonEachEof(sqlite3_vtab_cursor *cur){
2068 JsonEachCursor *p = (JsonEachCursor*)cur;
2069 return p->i >= p->iEnd;
2070}
2071
drh505ad2c2015-08-21 17:33:11 +00002072/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002073static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002074 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002075 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002076 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2077 p->i++;
drh4af352d2015-08-21 20:02:48 +00002078 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002079 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002080 u32 iUp = p->sParse.aUp[p->i];
2081 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002082 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002083 if( pUp->eType==JSON_ARRAY ){
2084 if( iUp==p->i-1 ){
2085 pUp->u.iKey = 0;
2086 }else{
2087 pUp->u.iKey++;
2088 }
drh4af352d2015-08-21 20:02:48 +00002089 }
2090 }
drh505ad2c2015-08-21 17:33:11 +00002091 }else{
drh4af352d2015-08-21 20:02:48 +00002092 switch( p->eType ){
2093 case JSON_ARRAY: {
2094 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2095 p->iRowid++;
2096 break;
2097 }
2098 case JSON_OBJECT: {
2099 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2100 p->iRowid++;
2101 break;
2102 }
2103 default: {
2104 p->i = p->iEnd;
2105 break;
2106 }
drh505ad2c2015-08-21 17:33:11 +00002107 }
2108 }
2109 return SQLITE_OK;
2110}
2111
drh4af352d2015-08-21 20:02:48 +00002112/* Append the name of the path for element i to pStr
2113*/
2114static void jsonEachComputePath(
2115 JsonEachCursor *p, /* The cursor */
2116 JsonString *pStr, /* Write the path here */
2117 u32 i /* Path to this element */
2118){
2119 JsonNode *pNode, *pUp;
2120 u32 iUp;
2121 if( i==0 ){
2122 jsonAppendChar(pStr, '$');
2123 return;
drhcb6c6c62015-08-19 22:47:17 +00002124 }
drh4af352d2015-08-21 20:02:48 +00002125 iUp = p->sParse.aUp[i];
2126 jsonEachComputePath(p, pStr, iUp);
2127 pNode = &p->sParse.aNode[i];
2128 pUp = &p->sParse.aNode[iUp];
2129 if( pUp->eType==JSON_ARRAY ){
2130 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2131 }else{
2132 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002133 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002134 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002135 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00002136 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2137 }
drhcb6c6c62015-08-19 22:47:17 +00002138}
2139
2140/* Return the value of a column */
2141static int jsonEachColumn(
2142 sqlite3_vtab_cursor *cur, /* The cursor */
2143 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2144 int i /* Which column to return */
2145){
2146 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002147 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002148 switch( i ){
2149 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002150 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002151 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002152 jsonReturn(pThis, ctx, 0);
2153 }else if( p->eType==JSON_ARRAY ){
2154 u32 iKey;
2155 if( p->bRecursive ){
2156 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002157 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002158 }else{
2159 iKey = p->iRowid;
2160 }
drh6fd5c1e2015-08-21 20:37:12 +00002161 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002162 }
2163 break;
2164 }
2165 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002166 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002167 jsonReturn(pThis, ctx, 0);
2168 break;
2169 }
2170 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002171 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002172 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2173 break;
2174 }
2175 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002176 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002177 if( pThis->eType>=JSON_ARRAY ) break;
2178 jsonReturn(pThis, ctx, 0);
2179 break;
2180 }
2181 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002182 sqlite3_result_int64(ctx,
2183 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002184 break;
2185 }
2186 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002187 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002188 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002189 }
2190 break;
2191 }
drh4af352d2015-08-21 20:02:48 +00002192 case JEACH_FULLKEY: {
2193 JsonString x;
2194 jsonInit(&x, ctx);
2195 if( p->bRecursive ){
2196 jsonEachComputePath(p, &x, p->i);
2197 }else{
drh383de692015-09-10 17:20:57 +00002198 if( p->zRoot ){
2199 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002200 }else{
2201 jsonAppendChar(&x, '$');
2202 }
2203 if( p->eType==JSON_ARRAY ){
2204 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002205 }else if( p->eType==JSON_OBJECT ){
drh4af352d2015-08-21 20:02:48 +00002206 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2207 }
2208 }
2209 jsonResult(&x);
2210 break;
2211 }
drhcb6c6c62015-08-19 22:47:17 +00002212 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002213 if( p->bRecursive ){
2214 JsonString x;
2215 jsonInit(&x, ctx);
2216 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2217 jsonResult(&x);
2218 break;
drh4af352d2015-08-21 20:02:48 +00002219 }
drh383de692015-09-10 17:20:57 +00002220 /* For json_each() path and root are the same so fall through
2221 ** into the root case */
2222 }
drh6850a632016-11-07 18:18:08 +00002223 default: {
drh383de692015-09-10 17:20:57 +00002224 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002225 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002226 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002227 break;
2228 }
drh3d1d2a92015-09-22 01:15:49 +00002229 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002230 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002231 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2232 break;
2233 }
2234 }
2235 return SQLITE_OK;
2236}
2237
2238/* Return the current rowid value */
2239static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2240 JsonEachCursor *p = (JsonEachCursor*)cur;
2241 *pRowid = p->iRowid;
2242 return SQLITE_OK;
2243}
2244
2245/* The query strategy is to look for an equality constraint on the json
2246** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002247** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002248** and 0 otherwise.
2249*/
2250static int jsonEachBestIndex(
2251 sqlite3_vtab *tab,
2252 sqlite3_index_info *pIdxInfo
2253){
2254 int i;
2255 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00002256 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00002257 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002258
2259 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00002260 pConstraint = pIdxInfo->aConstraint;
2261 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2262 if( pConstraint->usable==0 ) continue;
2263 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2264 switch( pConstraint->iColumn ){
2265 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00002266 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00002267 default: /* no-op */ break;
2268 }
2269 }
2270 if( jsonIdx<0 ){
2271 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00002272 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00002273 }else{
drh505ad2c2015-08-21 17:33:11 +00002274 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00002275 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
2276 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00002277 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00002278 pIdxInfo->idxNum = 1;
2279 }else{
drh383de692015-09-10 17:20:57 +00002280 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
2281 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00002282 pIdxInfo->idxNum = 3;
2283 }
2284 }
2285 return SQLITE_OK;
2286}
2287
2288/* Start a search on a new JSON string */
2289static int jsonEachFilter(
2290 sqlite3_vtab_cursor *cur,
2291 int idxNum, const char *idxStr,
2292 int argc, sqlite3_value **argv
2293){
2294 JsonEachCursor *p = (JsonEachCursor*)cur;
2295 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002296 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002297 sqlite3_int64 n;
2298
drh6fd5c1e2015-08-21 20:37:12 +00002299 UNUSED_PARAM(idxStr);
2300 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002301 jsonEachCursorReset(p);
2302 if( idxNum==0 ) return SQLITE_OK;
2303 z = (const char*)sqlite3_value_text(argv[0]);
2304 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002305 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002306 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002307 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002308 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002309 if( jsonParse(&p->sParse, 0, p->zJson) ){
2310 int rc = SQLITE_NOMEM;
2311 if( p->sParse.oom==0 ){
2312 sqlite3_free(cur->pVtab->zErrMsg);
2313 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2314 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2315 }
drhcb6c6c62015-08-19 22:47:17 +00002316 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002317 return rc;
2318 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2319 jsonEachCursorReset(p);
2320 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002321 }else{
drh95677942015-09-24 01:06:37 +00002322 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002323 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002324 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002325 zRoot = (const char*)sqlite3_value_text(argv[1]);
2326 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002327 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002328 p->zRoot = sqlite3_malloc64( n+1 );
2329 if( p->zRoot==0 ) return SQLITE_NOMEM;
2330 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002331 if( zRoot[0]!='$' ){
2332 zErr = zRoot;
2333 }else{
2334 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2335 }
2336 if( zErr ){
drha7714022015-08-29 00:54:49 +00002337 sqlite3_free(cur->pVtab->zErrMsg);
2338 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002339 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002340 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2341 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002342 return SQLITE_OK;
2343 }
2344 }else{
2345 pNode = p->sParse.aNode;
2346 }
drh852944e2015-09-10 03:29:11 +00002347 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002348 p->eType = pNode->eType;
2349 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002350 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002351 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002352 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002353 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002354 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2355 p->i--;
2356 }
2357 }else{
2358 p->i++;
2359 }
drhcb6c6c62015-08-19 22:47:17 +00002360 }else{
2361 p->iEnd = p->i+1;
2362 }
2363 }
drha8f39a92015-09-21 22:53:16 +00002364 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002365}
2366
2367/* The methods of the json_each virtual table */
2368static sqlite3_module jsonEachModule = {
2369 0, /* iVersion */
2370 0, /* xCreate */
2371 jsonEachConnect, /* xConnect */
2372 jsonEachBestIndex, /* xBestIndex */
2373 jsonEachDisconnect, /* xDisconnect */
2374 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002375 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002376 jsonEachClose, /* xClose - close a cursor */
2377 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002378 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002379 jsonEachEof, /* xEof - check for end of scan */
2380 jsonEachColumn, /* xColumn - read data */
2381 jsonEachRowid, /* xRowid - read data */
2382 0, /* xUpdate */
2383 0, /* xBegin */
2384 0, /* xSync */
2385 0, /* xCommit */
2386 0, /* xRollback */
2387 0, /* xFindMethod */
2388 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002389 0, /* xSavepoint */
2390 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002391 0, /* xRollbackTo */
2392 0 /* xShadowName */
drhcb6c6c62015-08-19 22:47:17 +00002393};
2394
drh505ad2c2015-08-21 17:33:11 +00002395/* The methods of the json_tree virtual table. */
2396static sqlite3_module jsonTreeModule = {
2397 0, /* iVersion */
2398 0, /* xCreate */
2399 jsonEachConnect, /* xConnect */
2400 jsonEachBestIndex, /* xBestIndex */
2401 jsonEachDisconnect, /* xDisconnect */
2402 0, /* xDestroy */
2403 jsonEachOpenTree, /* xOpen - open a cursor */
2404 jsonEachClose, /* xClose - close a cursor */
2405 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002406 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002407 jsonEachEof, /* xEof - check for end of scan */
2408 jsonEachColumn, /* xColumn - read data */
2409 jsonEachRowid, /* xRowid - read data */
2410 0, /* xUpdate */
2411 0, /* xBegin */
2412 0, /* xSync */
2413 0, /* xCommit */
2414 0, /* xRollback */
2415 0, /* xFindMethod */
2416 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002417 0, /* xSavepoint */
2418 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002419 0, /* xRollbackTo */
2420 0 /* xShadowName */
drh505ad2c2015-08-21 17:33:11 +00002421};
drhd2975922015-08-29 17:22:33 +00002422#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002423
2424/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002425** The following routines are the only publically visible identifiers in this
2426** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002427** functions and the virtual table implemented by this file.
2428****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002429
drh2f20e132015-09-26 17:44:59 +00002430int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002431 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002432 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002433 static const struct {
2434 const char *zName;
2435 int nArg;
drh52216ad2015-08-18 02:28:03 +00002436 int flag;
drh5fa5c102015-08-12 16:49:40 +00002437 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2438 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002439 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002440 { "json_array", -1, 0, jsonArrayFunc },
2441 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2442 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002443 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002444 { "json_insert", -1, 0, jsonSetFunc },
2445 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002446 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002447 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002448 { "json_remove", -1, 0, jsonRemoveFunc },
2449 { "json_replace", -1, 0, jsonReplaceFunc },
2450 { "json_set", -1, 1, jsonSetFunc },
2451 { "json_type", 1, 0, jsonTypeFunc },
2452 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002453 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002454
drh301eecc2015-08-17 20:14:19 +00002455#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002456 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002457 { "json_parse", 1, 0, jsonParseFunc },
2458 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002459#endif
drh5fa5c102015-08-12 16:49:40 +00002460 };
drhff135ae2015-12-30 01:07:02 +00002461 static const struct {
2462 const char *zName;
2463 int nArg;
2464 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2465 void (*xFinal)(sqlite3_context*);
drh8be47a72018-07-05 20:05:29 +00002466 void (*xValue)(sqlite3_context*);
drhff135ae2015-12-30 01:07:02 +00002467 } aAgg[] = {
drh8be47a72018-07-05 20:05:29 +00002468 { "json_group_array", 1,
2469 jsonArrayStep, jsonArrayFinal, jsonArrayValue },
2470 { "json_group_object", 2,
2471 jsonObjectStep, jsonObjectFinal, jsonObjectValue },
drhff135ae2015-12-30 01:07:02 +00002472 };
drhd2975922015-08-29 17:22:33 +00002473#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002474 static const struct {
2475 const char *zName;
2476 sqlite3_module *pModule;
2477 } aMod[] = {
2478 { "json_each", &jsonEachModule },
2479 { "json_tree", &jsonTreeModule },
2480 };
drhd2975922015-08-29 17:22:33 +00002481#endif
drh5fa5c102015-08-12 16:49:40 +00002482 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2483 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002484 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2485 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002486 aFunc[i].xFunc, 0, 0);
2487 }
mistachkin5a193dd2018-07-24 13:57:44 +00002488#ifndef SQLITE_OMIT_WINDOWFUNC
drhff135ae2015-12-30 01:07:02 +00002489 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
drh8be47a72018-07-05 20:05:29 +00002490 rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
drhff135ae2015-12-30 01:07:02 +00002491 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
drh8be47a72018-07-05 20:05:29 +00002492 aAgg[i].xStep, aAgg[i].xFinal,
2493 aAgg[i].xValue, jsonGroupInverse, 0);
drhff135ae2015-12-30 01:07:02 +00002494 }
mistachkin5a193dd2018-07-24 13:57:44 +00002495#endif
drhd2975922015-08-29 17:22:33 +00002496#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002497 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2498 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002499 }
drhd2975922015-08-29 17:22:33 +00002500#endif
drh5fa5c102015-08-12 16:49:40 +00002501 return rc;
2502}
drh2f20e132015-09-26 17:44:59 +00002503
2504
dan8d32e802015-10-14 18:45:42 +00002505#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002506#ifdef _WIN32
2507__declspec(dllexport)
2508#endif
2509int sqlite3_json_init(
2510 sqlite3 *db,
2511 char **pzErrMsg,
2512 const sqlite3_api_routines *pApi
2513){
2514 SQLITE_EXTENSION_INIT2(pApi);
2515 (void)pzErrMsg; /* Unused parameter */
2516 return sqlite3Json1Init(db);
2517}
dan8d32e802015-10-14 18:45:42 +00002518#endif
drh50065652015-10-08 19:29:18 +00002519#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */