blob: 3a9d10331cc19441c81f341ad99d1cbf9cd36c6f [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;
drh2d77d802019-01-08 20:02:48 +0000694 pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
drh95677942015-09-24 01:06:37 +0000695 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 );
drh2d77d802019-01-08 20:02:48 +0000968 aUp = pParse->aUp = sqlite3_malloc64( 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 }
drh2d77d802019-01-08 20:02:48 +00001030 p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
drh3fb153c2017-05-11 16:49:59 +00001031 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;
drh7e35e812019-07-31 12:13:58 +00001086 if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
drh987eb1f2015-08-17 15:17:37 +00001087 if( zPath[0]=='.' ){
1088 if( pRoot->eType!=JSON_OBJECT ) return 0;
1089 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001090 if( zPath[0]=='"' ){
1091 zKey = zPath + 1;
1092 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1093 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001094 if( zPath[i] ){
1095 i++;
1096 }else{
1097 *pzErr = zPath;
1098 return 0;
1099 }
drh6b43cc82015-08-19 23:02:49 +00001100 }else{
1101 zKey = zPath;
1102 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1103 nKey = i;
1104 }
drha7714022015-08-29 00:54:49 +00001105 if( nKey==0 ){
1106 *pzErr = zPath;
1107 return 0;
1108 }
drh987eb1f2015-08-17 15:17:37 +00001109 j = 1;
drh52216ad2015-08-18 02:28:03 +00001110 for(;;){
1111 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001112 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001113 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001114 }
1115 j++;
drh505ad2c2015-08-21 17:33:11 +00001116 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001117 }
drh52216ad2015-08-18 02:28:03 +00001118 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1119 iRoot += pRoot->u.iAppend;
1120 pRoot = &pParse->aNode[iRoot];
1121 j = 1;
1122 }
1123 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001124 u32 iStart, iLabel;
1125 JsonNode *pNode;
1126 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
danfe9a8322019-06-17 14:50:33 +00001127 iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
drh52216ad2015-08-18 02:28:03 +00001128 zPath += i;
drha7714022015-08-29 00:54:49 +00001129 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001130 if( pParse->oom ) return 0;
1131 if( pNode ){
1132 pRoot = &pParse->aNode[iRoot];
1133 pRoot->u.iAppend = iStart - iRoot;
1134 pRoot->jnFlags |= JNODE_APPEND;
1135 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1136 }
1137 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001138 }
dan2e8f5512015-09-17 17:21:09 +00001139 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +00001140 if( pRoot->eType!=JSON_ARRAY ) return 0;
1141 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001142 j = 1;
1143 while( safe_isdigit(zPath[j]) ){
1144 i = i*10 + zPath[j] - '0';
1145 j++;
drh987eb1f2015-08-17 15:17:37 +00001146 }
drh3d1d2a92015-09-22 01:15:49 +00001147 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +00001148 *pzErr = zPath;
1149 return 0;
1150 }
drh3d1d2a92015-09-22 01:15:49 +00001151 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001152 j = 1;
drh52216ad2015-08-18 02:28:03 +00001153 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001154 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1155 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001156 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001157 }
1158 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1159 iRoot += pRoot->u.iAppend;
1160 pRoot = &pParse->aNode[iRoot];
1161 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001162 }
1163 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001164 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001165 }
1166 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001167 u32 iStart;
1168 JsonNode *pNode;
1169 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001170 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001171 if( pParse->oom ) return 0;
1172 if( pNode ){
1173 pRoot = &pParse->aNode[iRoot];
1174 pRoot->u.iAppend = iStart - iRoot;
1175 pRoot->jnFlags |= JNODE_APPEND;
1176 }
1177 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001178 }
drh3d1d2a92015-09-22 01:15:49 +00001179 }else{
drha7714022015-08-29 00:54:49 +00001180 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001181 }
1182 return 0;
1183}
1184
drh52216ad2015-08-18 02:28:03 +00001185/*
drhbc8f0922015-08-22 19:39:04 +00001186** Append content to pParse that will complete zPath. Return a pointer
1187** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001188*/
1189static JsonNode *jsonLookupAppend(
1190 JsonParse *pParse, /* Append content to the JSON parse */
1191 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001192 int *pApnd, /* Set this flag to 1 */
1193 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001194){
1195 *pApnd = 1;
1196 if( zPath[0]==0 ){
1197 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1198 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1199 }
1200 if( zPath[0]=='.' ){
1201 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1202 }else if( strncmp(zPath,"[0]",3)==0 ){
1203 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1204 }else{
1205 return 0;
1206 }
1207 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001208 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001209}
1210
drhbc8f0922015-08-22 19:39:04 +00001211/*
drha7714022015-08-29 00:54:49 +00001212** Return the text of a syntax error message on a JSON path. Space is
1213** obtained from sqlite3_malloc().
1214*/
1215static char *jsonPathSyntaxError(const char *zErr){
1216 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1217}
1218
1219/*
1220** Do a node lookup using zPath. Return a pointer to the node on success.
1221** Return NULL if not found or if there is an error.
1222**
1223** On an error, write an error message into pCtx and increment the
1224** pParse->nErr counter.
1225**
1226** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1227** nodes are appended.
drha7714022015-08-29 00:54:49 +00001228*/
1229static JsonNode *jsonLookup(
1230 JsonParse *pParse, /* The JSON to search */
1231 const char *zPath, /* The path to search */
1232 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001233 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001234){
1235 const char *zErr = 0;
1236 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001237 char *zMsg;
drha7714022015-08-29 00:54:49 +00001238
1239 if( zPath==0 ) return 0;
1240 if( zPath[0]!='$' ){
1241 zErr = zPath;
1242 goto lookup_err;
1243 }
1244 zPath++;
drha7714022015-08-29 00:54:49 +00001245 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001246 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001247
1248lookup_err:
1249 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001250 assert( zErr!=0 && pCtx!=0 );
1251 zMsg = jsonPathSyntaxError(zErr);
1252 if( zMsg ){
1253 sqlite3_result_error(pCtx, zMsg, -1);
1254 sqlite3_free(zMsg);
1255 }else{
1256 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001257 }
drha7714022015-08-29 00:54:49 +00001258 return 0;
1259}
1260
1261
1262/*
drhbc8f0922015-08-22 19:39:04 +00001263** Report the wrong number of arguments for json_insert(), json_replace()
1264** or json_set().
1265*/
1266static void jsonWrongNumArgs(
1267 sqlite3_context *pCtx,
1268 const char *zFuncName
1269){
1270 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1271 zFuncName);
1272 sqlite3_result_error(pCtx, zMsg, -1);
1273 sqlite3_free(zMsg);
1274}
drh52216ad2015-08-18 02:28:03 +00001275
drh29c99692017-03-24 12:35:17 +00001276/*
1277** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1278*/
1279static void jsonRemoveAllNulls(JsonNode *pNode){
1280 int i, n;
1281 assert( pNode->eType==JSON_OBJECT );
1282 n = pNode->n;
1283 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1284 switch( pNode[i].eType ){
1285 case JSON_NULL:
1286 pNode[i].jnFlags |= JNODE_REMOVE;
1287 break;
1288 case JSON_OBJECT:
1289 jsonRemoveAllNulls(&pNode[i]);
1290 break;
1291 }
1292 }
1293}
1294
drha7714022015-08-29 00:54:49 +00001295
drh987eb1f2015-08-17 15:17:37 +00001296/****************************************************************************
1297** SQL functions used for testing and debugging
1298****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001299
drh301eecc2015-08-17 20:14:19 +00001300#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001301/*
drh5634cc02015-08-17 11:28:03 +00001302** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001303** a parse of the JSON provided. Or it returns NULL if JSON is not
1304** well-formed.
1305*/
drh5634cc02015-08-17 11:28:03 +00001306static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001307 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001308 int argc,
1309 sqlite3_value **argv
1310){
drh505ad2c2015-08-21 17:33:11 +00001311 JsonString s; /* Output string - not real JSON */
1312 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001313 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001314
1315 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001316 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001317 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001318 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001319 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001320 const char *zType;
1321 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1322 assert( x.aNode[i].eType==JSON_STRING );
1323 zType = "label";
1324 }else{
1325 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001326 }
drh852944e2015-09-10 03:29:11 +00001327 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1328 i, zType, x.aNode[i].n, x.aUp[i]);
1329 if( x.aNode[i].u.zJContent!=0 ){
1330 jsonAppendRaw(&s, " ", 1);
1331 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1332 }
1333 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001334 }
drh505ad2c2015-08-21 17:33:11 +00001335 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001336 jsonResult(&s);
1337}
1338
drh5634cc02015-08-17 11:28:03 +00001339/*
drhf5ddb9c2015-09-11 00:06:41 +00001340** The json_test1(JSON) function return true (1) if the input is JSON
1341** text generated by another json function. It returns (0) if the input
1342** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001343*/
1344static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001345 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001346 int argc,
1347 sqlite3_value **argv
1348){
mistachkin16a93122015-09-11 18:05:01 +00001349 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001350 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001351}
drh301eecc2015-08-17 20:14:19 +00001352#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001353
drh987eb1f2015-08-17 15:17:37 +00001354/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001355** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001356****************************************************************************/
1357
1358/*
drh2ad96f52016-06-17 13:01:51 +00001359** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1360** corresponding to the SQL value input. Mostly this means putting
1361** double-quotes around strings and returning the unquoted string "null"
1362** when given a NULL input.
1363*/
1364static void jsonQuoteFunc(
1365 sqlite3_context *ctx,
1366 int argc,
1367 sqlite3_value **argv
1368){
1369 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001370 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001371
1372 jsonInit(&jx, ctx);
1373 jsonAppendValue(&jx, argv[0]);
1374 jsonResult(&jx);
1375 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1376}
1377
1378/*
drh987eb1f2015-08-17 15:17:37 +00001379** Implementation of the json_array(VALUE,...) function. Return a JSON
1380** array that contains all values given in arguments. Or if any argument
1381** is a BLOB, throw an error.
1382*/
1383static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001384 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001385 int argc,
1386 sqlite3_value **argv
1387){
1388 int i;
drh505ad2c2015-08-21 17:33:11 +00001389 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001390
drhbc8f0922015-08-22 19:39:04 +00001391 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001392 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001393 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001394 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001395 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001396 }
drhd0960592015-08-17 21:22:32 +00001397 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001398 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001399 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001400}
1401
1402
1403/*
1404** json_array_length(JSON)
1405** json_array_length(JSON, PATH)
1406**
1407** Return the number of elements in the top-level JSON array.
1408** Return 0 if the input is not a well-formed JSON array.
1409*/
1410static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001411 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001412 int argc,
1413 sqlite3_value **argv
1414){
drh3fb153c2017-05-11 16:49:59 +00001415 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001416 sqlite3_int64 n = 0;
1417 u32 i;
drha8f39a92015-09-21 22:53:16 +00001418 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001419
drhe35fc302018-08-30 01:52:10 +00001420 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001421 if( p==0 ) return;
1422 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001423 if( argc==2 ){
1424 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001425 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001426 }else{
drh3fb153c2017-05-11 16:49:59 +00001427 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001428 }
1429 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001430 return;
1431 }
1432 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001433 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1434 for(i=1; i<=pNode->n; n++){
1435 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001436 }
drh987eb1f2015-08-17 15:17:37 +00001437 }
drh3fb153c2017-05-11 16:49:59 +00001438 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001439}
1440
1441/*
drh3ad93bb2015-08-29 19:41:45 +00001442** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001443**
drh3ad93bb2015-08-29 19:41:45 +00001444** Return the element described by PATH. Return NULL if there is no
1445** PATH element. If there are multiple PATHs, then return a JSON array
1446** with the result from each path. Throw an error if the JSON or any PATH
1447** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001448*/
1449static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001450 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001451 int argc,
1452 sqlite3_value **argv
1453){
drh3fb153c2017-05-11 16:49:59 +00001454 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001455 JsonNode *pNode;
1456 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001457 JsonString jx;
1458 int i;
1459
1460 if( argc<2 ) return;
drhe35fc302018-08-30 01:52:10 +00001461 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001462 if( p==0 ) return;
drh3ad93bb2015-08-29 19:41:45 +00001463 jsonInit(&jx, ctx);
1464 jsonAppendChar(&jx, '[');
1465 for(i=1; i<argc; i++){
1466 zPath = (const char*)sqlite3_value_text(argv[i]);
drh3fb153c2017-05-11 16:49:59 +00001467 pNode = jsonLookup(p, zPath, 0, ctx);
1468 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001469 if( argc>2 ){
1470 jsonAppendSeparator(&jx);
1471 if( pNode ){
1472 jsonRenderNode(pNode, &jx, 0);
1473 }else{
1474 jsonAppendRaw(&jx, "null", 4);
1475 }
1476 }else if( pNode ){
1477 jsonReturn(pNode, ctx, 0);
1478 }
drh987eb1f2015-08-17 15:17:37 +00001479 }
drh3ad93bb2015-08-29 19:41:45 +00001480 if( argc>2 && i==argc ){
1481 jsonAppendChar(&jx, ']');
1482 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001483 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001484 }
1485 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001486}
1487
drh633647a2017-03-22 21:24:31 +00001488/* This is the RFC 7396 MergePatch algorithm.
1489*/
1490static JsonNode *jsonMergePatch(
1491 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001492 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001493 JsonNode *pPatch /* The PATCH */
1494){
drh0002d242017-03-23 00:46:15 +00001495 u32 i, j;
1496 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001497 JsonNode *pTarget;
1498 if( pPatch->eType!=JSON_OBJECT ){
1499 return pPatch;
1500 }
1501 assert( iTarget>=0 && iTarget<pParse->nNode );
1502 pTarget = &pParse->aNode[iTarget];
1503 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1504 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001505 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001506 return pPatch;
1507 }
drhbb7aa2d2017-03-23 00:13:52 +00001508 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001509 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001510 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001511 const char *zKey;
1512 assert( pPatch[i].eType==JSON_STRING );
1513 assert( pPatch[i].jnFlags & JNODE_LABEL );
1514 nKey = pPatch[i].n;
1515 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001516 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001517 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1518 assert( pTarget[j].eType==JSON_STRING );
1519 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001520 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001521 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1522 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001523 if( pPatch[i+1].eType==JSON_NULL ){
1524 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1525 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001526 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001527 if( pNew==0 ) return 0;
1528 pTarget = &pParse->aNode[iTarget];
1529 if( pNew!=&pTarget[j+1] ){
1530 pTarget[j+1].u.pPatch = pNew;
1531 pTarget[j+1].jnFlags |= JNODE_PATCH;
1532 }
1533 }
1534 break;
1535 }
1536 }
drhbb7aa2d2017-03-23 00:13:52 +00001537 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001538 int iStart, iPatch;
1539 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1540 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1541 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1542 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001543 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001544 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001545 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1546 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1547 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001548 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1549 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1550 }
1551 }
1552 return pTarget;
1553}
1554
1555/*
1556** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1557** object that is the result of running the RFC 7396 MergePatch() algorithm
1558** on the two arguments.
1559*/
drh37f03df2017-03-23 20:33:49 +00001560static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001561 sqlite3_context *ctx,
1562 int argc,
1563 sqlite3_value **argv
1564){
1565 JsonParse x; /* The JSON that is being patched */
1566 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001567 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001568
drh2fb79e92017-03-25 12:08:11 +00001569 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001570 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1571 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1572 jsonParseReset(&x);
1573 return;
1574 }
drhbb7aa2d2017-03-23 00:13:52 +00001575 pResult = jsonMergePatch(&x, 0, y.aNode);
1576 assert( pResult!=0 || x.oom );
1577 if( pResult ){
1578 jsonReturnJson(pResult, ctx, 0);
1579 }else{
1580 sqlite3_result_error_nomem(ctx);
1581 }
drh633647a2017-03-22 21:24:31 +00001582 jsonParseReset(&x);
1583 jsonParseReset(&y);
1584}
1585
1586
drh987eb1f2015-08-17 15:17:37 +00001587/*
1588** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1589** object that contains all name/value given in arguments. Or if any name
1590** is not a string or if any value is a BLOB, throw an error.
1591*/
1592static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001593 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001594 int argc,
1595 sqlite3_value **argv
1596){
1597 int i;
drh505ad2c2015-08-21 17:33:11 +00001598 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001599 const char *z;
1600 u32 n;
1601
1602 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001603 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001604 "of arguments", -1);
1605 return;
1606 }
drhbc8f0922015-08-22 19:39:04 +00001607 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001608 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001609 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001610 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001611 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001612 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001613 return;
1614 }
drhd0960592015-08-17 21:22:32 +00001615 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001616 z = (const char*)sqlite3_value_text(argv[i]);
1617 n = (u32)sqlite3_value_bytes(argv[i]);
1618 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001619 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001620 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001621 }
drhd0960592015-08-17 21:22:32 +00001622 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001623 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001624 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001625}
1626
1627
1628/*
drh301eecc2015-08-17 20:14:19 +00001629** json_remove(JSON, PATH, ...)
1630**
drh3ad93bb2015-08-29 19:41:45 +00001631** Remove the named elements from JSON and return the result. malformed
1632** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001633*/
1634static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001635 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001636 int argc,
1637 sqlite3_value **argv
1638){
1639 JsonParse x; /* The parse */
1640 JsonNode *pNode;
1641 const char *zPath;
1642 u32 i;
1643
1644 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001645 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001646 assert( x.nNode );
1647 for(i=1; i<(u32)argc; i++){
1648 zPath = (const char*)sqlite3_value_text(argv[i]);
1649 if( zPath==0 ) goto remove_done;
1650 pNode = jsonLookup(&x, zPath, 0, ctx);
1651 if( x.nErr ) goto remove_done;
1652 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1653 }
1654 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1655 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001656 }
drha7714022015-08-29 00:54:49 +00001657remove_done:
drh505ad2c2015-08-21 17:33:11 +00001658 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001659}
1660
1661/*
1662** json_replace(JSON, PATH, VALUE, ...)
1663**
1664** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001665** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001666*/
1667static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001668 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001669 int argc,
1670 sqlite3_value **argv
1671){
1672 JsonParse x; /* The parse */
1673 JsonNode *pNode;
1674 const char *zPath;
1675 u32 i;
1676
1677 if( argc<1 ) return;
1678 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001679 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001680 return;
1681 }
drhbc8f0922015-08-22 19:39:04 +00001682 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001683 assert( x.nNode );
1684 for(i=1; i<(u32)argc; i+=2){
1685 zPath = (const char*)sqlite3_value_text(argv[i]);
1686 pNode = jsonLookup(&x, zPath, 0, ctx);
1687 if( x.nErr ) goto replace_err;
1688 if( pNode ){
1689 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001690 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001691 }
drha8f39a92015-09-21 22:53:16 +00001692 }
1693 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001694 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001695 }else{
1696 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001697 }
drha7714022015-08-29 00:54:49 +00001698replace_err:
drh505ad2c2015-08-21 17:33:11 +00001699 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001700}
drh505ad2c2015-08-21 17:33:11 +00001701
drh52216ad2015-08-18 02:28:03 +00001702/*
1703** json_set(JSON, PATH, VALUE, ...)
1704**
1705** Set the value at PATH to VALUE. Create the PATH if it does not already
1706** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001707** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001708**
1709** json_insert(JSON, PATH, VALUE, ...)
1710**
1711** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001712** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001713*/
1714static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001715 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001716 int argc,
1717 sqlite3_value **argv
1718){
1719 JsonParse x; /* The parse */
1720 JsonNode *pNode;
1721 const char *zPath;
1722 u32 i;
1723 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001724 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001725
1726 if( argc<1 ) return;
1727 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001728 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001729 return;
1730 }
drhbc8f0922015-08-22 19:39:04 +00001731 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001732 assert( x.nNode );
1733 for(i=1; i<(u32)argc; i+=2){
1734 zPath = (const char*)sqlite3_value_text(argv[i]);
1735 bApnd = 0;
1736 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1737 if( x.oom ){
1738 sqlite3_result_error_nomem(ctx);
1739 goto jsonSetDone;
1740 }else if( x.nErr ){
1741 goto jsonSetDone;
1742 }else if( pNode && (bApnd || bIsSet) ){
1743 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001744 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001745 }
drha8f39a92015-09-21 22:53:16 +00001746 }
1747 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001748 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001749 }else{
1750 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001751 }
drhbc8f0922015-08-22 19:39:04 +00001752jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001753 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001754}
drh301eecc2015-08-17 20:14:19 +00001755
1756/*
drh987eb1f2015-08-17 15:17:37 +00001757** json_type(JSON)
1758** json_type(JSON, PATH)
1759**
drh3ad93bb2015-08-29 19:41:45 +00001760** Return the top-level "type" of a JSON string. Throw an error if
1761** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001762*/
1763static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001764 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001765 int argc,
1766 sqlite3_value **argv
1767){
drhe35fc302018-08-30 01:52:10 +00001768 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001769 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001770 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001771
drhe35fc302018-08-30 01:52:10 +00001772 p = jsonParseCached(ctx, argv, ctx);
1773 if( p==0 ) return;
drha8f39a92015-09-21 22:53:16 +00001774 if( argc==2 ){
1775 zPath = (const char*)sqlite3_value_text(argv[1]);
drhe35fc302018-08-30 01:52:10 +00001776 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001777 }else{
drhe35fc302018-08-30 01:52:10 +00001778 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001779 }
1780 if( pNode ){
1781 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001782 }
drh987eb1f2015-08-17 15:17:37 +00001783}
drh5634cc02015-08-17 11:28:03 +00001784
drhbc8f0922015-08-22 19:39:04 +00001785/*
1786** json_valid(JSON)
1787**
drh3ad93bb2015-08-29 19:41:45 +00001788** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1789** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001790*/
1791static void jsonValidFunc(
1792 sqlite3_context *ctx,
1793 int argc,
1794 sqlite3_value **argv
1795){
drhe35fc302018-08-30 01:52:10 +00001796 JsonParse *p; /* The parse */
mistachkin16a93122015-09-11 18:05:01 +00001797 UNUSED_PARAM(argc);
drhe35fc302018-08-30 01:52:10 +00001798 p = jsonParseCached(ctx, argv, 0);
1799 sqlite3_result_int(ctx, p!=0);
drhbc8f0922015-08-22 19:39:04 +00001800}
1801
drhff135ae2015-12-30 01:07:02 +00001802
1803/****************************************************************************
1804** Aggregate SQL function implementations
1805****************************************************************************/
1806/*
1807** json_group_array(VALUE)
1808**
1809** Return a JSON array composed of all values in the aggregate.
1810*/
1811static void jsonArrayStep(
1812 sqlite3_context *ctx,
1813 int argc,
1814 sqlite3_value **argv
1815){
1816 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001817 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001818 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1819 if( pStr ){
1820 if( pStr->zBuf==0 ){
1821 jsonInit(pStr, ctx);
1822 jsonAppendChar(pStr, '[');
1823 }else{
1824 jsonAppendChar(pStr, ',');
1825 pStr->pCtx = ctx;
1826 }
1827 jsonAppendValue(pStr, argv[0]);
1828 }
1829}
drh8be47a72018-07-05 20:05:29 +00001830static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001831 JsonString *pStr;
1832 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1833 if( pStr ){
1834 pStr->pCtx = ctx;
1835 jsonAppendChar(pStr, ']');
1836 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001837 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001838 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001839 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001840 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001841 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1842 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001843 }else{
mistachkined008ec2018-09-12 01:05:26 +00001844 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001845 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001846 }
1847 }else{
1848 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1849 }
1850 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1851}
drh8be47a72018-07-05 20:05:29 +00001852static void jsonArrayValue(sqlite3_context *ctx){
1853 jsonArrayCompute(ctx, 0);
1854}
1855static void jsonArrayFinal(sqlite3_context *ctx){
1856 jsonArrayCompute(ctx, 1);
1857}
1858
1859#ifndef SQLITE_OMIT_WINDOWFUNC
1860/*
1861** This method works for both json_group_array() and json_group_object().
1862** It works by removing the first element of the group by searching forward
1863** to the first comma (",") that is not within a string and deleting all
1864** text through that comma.
1865*/
1866static void jsonGroupInverse(
1867 sqlite3_context *ctx,
1868 int argc,
1869 sqlite3_value **argv
1870){
1871 int i;
1872 int inStr = 0;
1873 char *z;
1874 JsonString *pStr;
drhc7bf5712018-07-09 22:49:01 +00001875 UNUSED_PARAM(argc);
1876 UNUSED_PARAM(argv);
drh8be47a72018-07-05 20:05:29 +00001877 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drh491d4c82018-07-07 20:23:46 +00001878#ifdef NEVER
drhfd4b7282018-07-07 19:47:21 +00001879 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1880 ** always have been called to initalize it */
1881 if( NEVER(!pStr) ) return;
drh491d4c82018-07-07 20:23:46 +00001882#endif
drh8be47a72018-07-05 20:05:29 +00001883 z = pStr->zBuf;
1884 for(i=1; z[i]!=',' || inStr; i++){
1885 assert( i<pStr->nUsed );
1886 if( z[i]=='"' ){
1887 inStr = !inStr;
1888 }else if( z[i]=='\\' ){
1889 i++;
1890 }
1891 }
1892 pStr->nUsed -= i;
mistachkined008ec2018-09-12 01:05:26 +00001893 memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
drh8be47a72018-07-05 20:05:29 +00001894}
1895#else
1896# define jsonGroupInverse 0
1897#endif
1898
drhff135ae2015-12-30 01:07:02 +00001899
1900/*
1901** json_group_obj(NAME,VALUE)
1902**
1903** Return a JSON object composed of all names and values in the aggregate.
1904*/
1905static void jsonObjectStep(
1906 sqlite3_context *ctx,
1907 int argc,
1908 sqlite3_value **argv
1909){
1910 JsonString *pStr;
1911 const char *z;
1912 u32 n;
drhdf3a9072016-02-11 15:37:18 +00001913 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001914 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1915 if( pStr ){
1916 if( pStr->zBuf==0 ){
1917 jsonInit(pStr, ctx);
1918 jsonAppendChar(pStr, '{');
1919 }else{
1920 jsonAppendChar(pStr, ',');
1921 pStr->pCtx = ctx;
1922 }
1923 z = (const char*)sqlite3_value_text(argv[0]);
1924 n = (u32)sqlite3_value_bytes(argv[0]);
1925 jsonAppendString(pStr, z, n);
1926 jsonAppendChar(pStr, ':');
1927 jsonAppendValue(pStr, argv[1]);
1928 }
1929}
drh8be47a72018-07-05 20:05:29 +00001930static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001931 JsonString *pStr;
1932 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1933 if( pStr ){
1934 jsonAppendChar(pStr, '}');
1935 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00001936 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001937 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001938 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001939 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001940 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1941 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001942 }else{
mistachkined008ec2018-09-12 01:05:26 +00001943 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001944 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001945 }
1946 }else{
1947 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
1948 }
1949 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1950}
drh8be47a72018-07-05 20:05:29 +00001951static void jsonObjectValue(sqlite3_context *ctx){
1952 jsonObjectCompute(ctx, 0);
1953}
1954static void jsonObjectFinal(sqlite3_context *ctx){
1955 jsonObjectCompute(ctx, 1);
1956}
1957
drhff135ae2015-12-30 01:07:02 +00001958
1959
drhd2975922015-08-29 17:22:33 +00001960#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001961/****************************************************************************
1962** The json_each virtual table
1963****************************************************************************/
1964typedef struct JsonEachCursor JsonEachCursor;
1965struct JsonEachCursor {
1966 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001967 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001968 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001969 u32 i; /* Index in sParse.aNode[] of current row */
1970 u32 iEnd; /* EOF when i equals or exceeds this value */
1971 u8 eType; /* Type of top-level element */
1972 u8 bRecursive; /* True for json_tree(). False for json_each() */
1973 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001974 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001975 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001976};
1977
1978/* Constructor for the json_each virtual table */
1979static int jsonEachConnect(
1980 sqlite3 *db,
1981 void *pAux,
1982 int argc, const char *const*argv,
1983 sqlite3_vtab **ppVtab,
1984 char **pzErr
1985){
1986 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001987 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001988
1989/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001990#define JEACH_KEY 0
1991#define JEACH_VALUE 1
1992#define JEACH_TYPE 2
1993#define JEACH_ATOM 3
1994#define JEACH_ID 4
1995#define JEACH_PARENT 5
1996#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001997#define JEACH_PATH 7
drh43579192018-11-16 16:04:50 +00001998/* The xBestIndex method assumes that the JSON and ROOT columns are
1999** the last two columns in the table. Should this ever changes, be
2000** sure to update the xBestIndex method. */
drh383de692015-09-10 17:20:57 +00002001#define JEACH_JSON 8
2002#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00002003
drh6fd5c1e2015-08-21 20:37:12 +00002004 UNUSED_PARAM(pzErr);
2005 UNUSED_PARAM(argv);
2006 UNUSED_PARAM(argc);
2007 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00002008 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00002009 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2010 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00002011 if( rc==SQLITE_OK ){
2012 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2013 if( pNew==0 ) return SQLITE_NOMEM;
2014 memset(pNew, 0, sizeof(*pNew));
2015 }
2016 return rc;
drhcb6c6c62015-08-19 22:47:17 +00002017}
2018
2019/* destructor for json_each virtual table */
2020static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2021 sqlite3_free(pVtab);
2022 return SQLITE_OK;
2023}
2024
drh505ad2c2015-08-21 17:33:11 +00002025/* constructor for a JsonEachCursor object for json_each(). */
2026static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00002027 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00002028
2029 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00002030 pCur = sqlite3_malloc( sizeof(*pCur) );
2031 if( pCur==0 ) return SQLITE_NOMEM;
2032 memset(pCur, 0, sizeof(*pCur));
2033 *ppCursor = &pCur->base;
2034 return SQLITE_OK;
2035}
2036
drh505ad2c2015-08-21 17:33:11 +00002037/* constructor for a JsonEachCursor object for json_tree(). */
2038static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2039 int rc = jsonEachOpenEach(p, ppCursor);
2040 if( rc==SQLITE_OK ){
2041 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2042 pCur->bRecursive = 1;
2043 }
2044 return rc;
2045}
2046
drhcb6c6c62015-08-19 22:47:17 +00002047/* Reset a JsonEachCursor back to its original state. Free any memory
2048** held. */
2049static void jsonEachCursorReset(JsonEachCursor *p){
2050 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002051 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002052 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002053 p->iRowid = 0;
2054 p->i = 0;
2055 p->iEnd = 0;
2056 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002057 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002058 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002059}
2060
2061/* Destructor for a jsonEachCursor object */
2062static int jsonEachClose(sqlite3_vtab_cursor *cur){
2063 JsonEachCursor *p = (JsonEachCursor*)cur;
2064 jsonEachCursorReset(p);
2065 sqlite3_free(cur);
2066 return SQLITE_OK;
2067}
2068
2069/* Return TRUE if the jsonEachCursor object has been advanced off the end
2070** of the JSON object */
2071static int jsonEachEof(sqlite3_vtab_cursor *cur){
2072 JsonEachCursor *p = (JsonEachCursor*)cur;
2073 return p->i >= p->iEnd;
2074}
2075
drh505ad2c2015-08-21 17:33:11 +00002076/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002077static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002078 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002079 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002080 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2081 p->i++;
drh4af352d2015-08-21 20:02:48 +00002082 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002083 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002084 u32 iUp = p->sParse.aUp[p->i];
2085 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002086 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002087 if( pUp->eType==JSON_ARRAY ){
2088 if( iUp==p->i-1 ){
2089 pUp->u.iKey = 0;
2090 }else{
2091 pUp->u.iKey++;
2092 }
drh4af352d2015-08-21 20:02:48 +00002093 }
2094 }
drh505ad2c2015-08-21 17:33:11 +00002095 }else{
drh4af352d2015-08-21 20:02:48 +00002096 switch( p->eType ){
2097 case JSON_ARRAY: {
2098 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2099 p->iRowid++;
2100 break;
2101 }
2102 case JSON_OBJECT: {
2103 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2104 p->iRowid++;
2105 break;
2106 }
2107 default: {
2108 p->i = p->iEnd;
2109 break;
2110 }
drh505ad2c2015-08-21 17:33:11 +00002111 }
2112 }
2113 return SQLITE_OK;
2114}
2115
drh4af352d2015-08-21 20:02:48 +00002116/* Append the name of the path for element i to pStr
2117*/
2118static void jsonEachComputePath(
2119 JsonEachCursor *p, /* The cursor */
2120 JsonString *pStr, /* Write the path here */
2121 u32 i /* Path to this element */
2122){
2123 JsonNode *pNode, *pUp;
2124 u32 iUp;
2125 if( i==0 ){
2126 jsonAppendChar(pStr, '$');
2127 return;
drhcb6c6c62015-08-19 22:47:17 +00002128 }
drh4af352d2015-08-21 20:02:48 +00002129 iUp = p->sParse.aUp[i];
2130 jsonEachComputePath(p, pStr, iUp);
2131 pNode = &p->sParse.aNode[i];
2132 pUp = &p->sParse.aNode[iUp];
2133 if( pUp->eType==JSON_ARRAY ){
2134 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2135 }else{
2136 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002137 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002138 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002139 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00002140 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2141 }
drhcb6c6c62015-08-19 22:47:17 +00002142}
2143
2144/* Return the value of a column */
2145static int jsonEachColumn(
2146 sqlite3_vtab_cursor *cur, /* The cursor */
2147 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2148 int i /* Which column to return */
2149){
2150 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002151 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002152 switch( i ){
2153 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002154 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002155 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002156 jsonReturn(pThis, ctx, 0);
2157 }else if( p->eType==JSON_ARRAY ){
2158 u32 iKey;
2159 if( p->bRecursive ){
2160 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002161 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002162 }else{
2163 iKey = p->iRowid;
2164 }
drh6fd5c1e2015-08-21 20:37:12 +00002165 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002166 }
2167 break;
2168 }
2169 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002170 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002171 jsonReturn(pThis, ctx, 0);
2172 break;
2173 }
2174 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002175 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002176 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2177 break;
2178 }
2179 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002180 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002181 if( pThis->eType>=JSON_ARRAY ) break;
2182 jsonReturn(pThis, ctx, 0);
2183 break;
2184 }
2185 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002186 sqlite3_result_int64(ctx,
2187 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002188 break;
2189 }
2190 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002191 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002192 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002193 }
2194 break;
2195 }
drh4af352d2015-08-21 20:02:48 +00002196 case JEACH_FULLKEY: {
2197 JsonString x;
2198 jsonInit(&x, ctx);
2199 if( p->bRecursive ){
2200 jsonEachComputePath(p, &x, p->i);
2201 }else{
drh383de692015-09-10 17:20:57 +00002202 if( p->zRoot ){
2203 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002204 }else{
2205 jsonAppendChar(&x, '$');
2206 }
2207 if( p->eType==JSON_ARRAY ){
2208 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002209 }else if( p->eType==JSON_OBJECT ){
drh4af352d2015-08-21 20:02:48 +00002210 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2211 }
2212 }
2213 jsonResult(&x);
2214 break;
2215 }
drhcb6c6c62015-08-19 22:47:17 +00002216 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002217 if( p->bRecursive ){
2218 JsonString x;
2219 jsonInit(&x, ctx);
2220 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2221 jsonResult(&x);
2222 break;
drh4af352d2015-08-21 20:02:48 +00002223 }
drh383de692015-09-10 17:20:57 +00002224 /* For json_each() path and root are the same so fall through
2225 ** into the root case */
2226 }
drh6850a632016-11-07 18:18:08 +00002227 default: {
drh383de692015-09-10 17:20:57 +00002228 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002229 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002230 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002231 break;
2232 }
drh3d1d2a92015-09-22 01:15:49 +00002233 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002234 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002235 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2236 break;
2237 }
2238 }
2239 return SQLITE_OK;
2240}
2241
2242/* Return the current rowid value */
2243static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2244 JsonEachCursor *p = (JsonEachCursor*)cur;
2245 *pRowid = p->iRowid;
2246 return SQLITE_OK;
2247}
2248
2249/* The query strategy is to look for an equality constraint on the json
2250** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002251** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002252** and 0 otherwise.
2253*/
2254static int jsonEachBestIndex(
2255 sqlite3_vtab *tab,
2256 sqlite3_index_info *pIdxInfo
2257){
drh43579192018-11-16 16:04:50 +00002258 int i; /* Loop counter or computed array index */
2259 int aIdx[2]; /* Index of constraints for JSON and ROOT */
2260 int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
2261 int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
drhcb6c6c62015-08-19 22:47:17 +00002262 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002263
drh43579192018-11-16 16:04:50 +00002264 /* This implementation assumes that JSON and ROOT are the last two
2265 ** columns in the table */
2266 assert( JEACH_ROOT == JEACH_JSON+1 );
drh6fd5c1e2015-08-21 20:37:12 +00002267 UNUSED_PARAM(tab);
drh43579192018-11-16 16:04:50 +00002268 aIdx[0] = aIdx[1] = -1;
drhcb6c6c62015-08-19 22:47:17 +00002269 pConstraint = pIdxInfo->aConstraint;
2270 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
drh43579192018-11-16 16:04:50 +00002271 int iCol;
2272 int iMask;
2273 if( pConstraint->iColumn < JEACH_JSON ) continue;
2274 iCol = pConstraint->iColumn - JEACH_JSON;
2275 assert( iCol==0 || iCol==1 );
2276 iMask = 1 << iCol;
2277 if( pConstraint->usable==0 ){
2278 unusableMask |= iMask;
2279 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
2280 aIdx[iCol] = i;
2281 idxMask |= iMask;
drhcb6c6c62015-08-19 22:47:17 +00002282 }
2283 }
drh43579192018-11-16 16:04:50 +00002284 if( (unusableMask & ~idxMask)!=0 ){
2285 /* If there are any unusable constraints on JSON or ROOT, then reject
2286 ** this entire plan */
2287 return SQLITE_CONSTRAINT;
2288 }
2289 if( aIdx[0]<0 ){
2290 /* No JSON input. Leave estimatedCost at the huge value that it was
2291 ** initialized to to discourage the query planner from selecting this
2292 ** plan. */
drhcb6c6c62015-08-19 22:47:17 +00002293 pIdxInfo->idxNum = 0;
drhcb6c6c62015-08-19 22:47:17 +00002294 }else{
drh505ad2c2015-08-21 17:33:11 +00002295 pIdxInfo->estimatedCost = 1.0;
drh43579192018-11-16 16:04:50 +00002296 i = aIdx[0];
2297 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
2298 pIdxInfo->aConstraintUsage[i].omit = 1;
2299 if( aIdx[1]<0 ){
2300 pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
drhcb6c6c62015-08-19 22:47:17 +00002301 }else{
drh43579192018-11-16 16:04:50 +00002302 i = aIdx[1];
2303 pIdxInfo->aConstraintUsage[i].argvIndex = 2;
2304 pIdxInfo->aConstraintUsage[i].omit = 1;
2305 pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
drhcb6c6c62015-08-19 22:47:17 +00002306 }
2307 }
2308 return SQLITE_OK;
2309}
2310
2311/* Start a search on a new JSON string */
2312static int jsonEachFilter(
2313 sqlite3_vtab_cursor *cur,
2314 int idxNum, const char *idxStr,
2315 int argc, sqlite3_value **argv
2316){
2317 JsonEachCursor *p = (JsonEachCursor*)cur;
2318 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002319 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002320 sqlite3_int64 n;
2321
drh6fd5c1e2015-08-21 20:37:12 +00002322 UNUSED_PARAM(idxStr);
2323 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002324 jsonEachCursorReset(p);
2325 if( idxNum==0 ) return SQLITE_OK;
2326 z = (const char*)sqlite3_value_text(argv[0]);
2327 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002328 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002329 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002330 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002331 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002332 if( jsonParse(&p->sParse, 0, p->zJson) ){
2333 int rc = SQLITE_NOMEM;
2334 if( p->sParse.oom==0 ){
2335 sqlite3_free(cur->pVtab->zErrMsg);
2336 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2337 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2338 }
drhcb6c6c62015-08-19 22:47:17 +00002339 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002340 return rc;
2341 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2342 jsonEachCursorReset(p);
2343 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002344 }else{
drh95677942015-09-24 01:06:37 +00002345 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002346 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002347 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002348 zRoot = (const char*)sqlite3_value_text(argv[1]);
2349 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002350 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002351 p->zRoot = sqlite3_malloc64( n+1 );
2352 if( p->zRoot==0 ) return SQLITE_NOMEM;
2353 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002354 if( zRoot[0]!='$' ){
2355 zErr = zRoot;
2356 }else{
2357 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2358 }
2359 if( zErr ){
drha7714022015-08-29 00:54:49 +00002360 sqlite3_free(cur->pVtab->zErrMsg);
2361 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002362 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002363 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2364 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002365 return SQLITE_OK;
2366 }
2367 }else{
2368 pNode = p->sParse.aNode;
2369 }
drh852944e2015-09-10 03:29:11 +00002370 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002371 p->eType = pNode->eType;
2372 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002373 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002374 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002375 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002376 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002377 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2378 p->i--;
2379 }
2380 }else{
2381 p->i++;
2382 }
drhcb6c6c62015-08-19 22:47:17 +00002383 }else{
2384 p->iEnd = p->i+1;
2385 }
2386 }
drha8f39a92015-09-21 22:53:16 +00002387 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002388}
2389
2390/* The methods of the json_each virtual table */
2391static sqlite3_module jsonEachModule = {
2392 0, /* iVersion */
2393 0, /* xCreate */
2394 jsonEachConnect, /* xConnect */
2395 jsonEachBestIndex, /* xBestIndex */
2396 jsonEachDisconnect, /* xDisconnect */
2397 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002398 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002399 jsonEachClose, /* xClose - close a cursor */
2400 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002401 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002402 jsonEachEof, /* xEof - check for end of scan */
2403 jsonEachColumn, /* xColumn - read data */
2404 jsonEachRowid, /* xRowid - read data */
2405 0, /* xUpdate */
2406 0, /* xBegin */
2407 0, /* xSync */
2408 0, /* xCommit */
2409 0, /* xRollback */
2410 0, /* xFindMethod */
2411 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002412 0, /* xSavepoint */
2413 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002414 0, /* xRollbackTo */
2415 0 /* xShadowName */
drhcb6c6c62015-08-19 22:47:17 +00002416};
2417
drh505ad2c2015-08-21 17:33:11 +00002418/* The methods of the json_tree virtual table. */
2419static sqlite3_module jsonTreeModule = {
2420 0, /* iVersion */
2421 0, /* xCreate */
2422 jsonEachConnect, /* xConnect */
2423 jsonEachBestIndex, /* xBestIndex */
2424 jsonEachDisconnect, /* xDisconnect */
2425 0, /* xDestroy */
2426 jsonEachOpenTree, /* xOpen - open a cursor */
2427 jsonEachClose, /* xClose - close a cursor */
2428 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002429 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002430 jsonEachEof, /* xEof - check for end of scan */
2431 jsonEachColumn, /* xColumn - read data */
2432 jsonEachRowid, /* xRowid - read data */
2433 0, /* xUpdate */
2434 0, /* xBegin */
2435 0, /* xSync */
2436 0, /* xCommit */
2437 0, /* xRollback */
2438 0, /* xFindMethod */
2439 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002440 0, /* xSavepoint */
2441 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002442 0, /* xRollbackTo */
2443 0 /* xShadowName */
drh505ad2c2015-08-21 17:33:11 +00002444};
drhd2975922015-08-29 17:22:33 +00002445#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002446
2447/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002448** The following routines are the only publically visible identifiers in this
2449** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002450** functions and the virtual table implemented by this file.
2451****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002452
drh2f20e132015-09-26 17:44:59 +00002453int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002454 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002455 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002456 static const struct {
2457 const char *zName;
2458 int nArg;
drh52216ad2015-08-18 02:28:03 +00002459 int flag;
drh5fa5c102015-08-12 16:49:40 +00002460 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2461 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002462 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002463 { "json_array", -1, 0, jsonArrayFunc },
2464 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2465 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002466 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002467 { "json_insert", -1, 0, jsonSetFunc },
2468 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002469 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002470 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002471 { "json_remove", -1, 0, jsonRemoveFunc },
2472 { "json_replace", -1, 0, jsonReplaceFunc },
2473 { "json_set", -1, 1, jsonSetFunc },
2474 { "json_type", 1, 0, jsonTypeFunc },
2475 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002476 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002477
drh301eecc2015-08-17 20:14:19 +00002478#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002479 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002480 { "json_parse", 1, 0, jsonParseFunc },
2481 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002482#endif
drh5fa5c102015-08-12 16:49:40 +00002483 };
drhff135ae2015-12-30 01:07:02 +00002484 static const struct {
2485 const char *zName;
2486 int nArg;
2487 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2488 void (*xFinal)(sqlite3_context*);
drh8be47a72018-07-05 20:05:29 +00002489 void (*xValue)(sqlite3_context*);
drhff135ae2015-12-30 01:07:02 +00002490 } aAgg[] = {
drh8be47a72018-07-05 20:05:29 +00002491 { "json_group_array", 1,
2492 jsonArrayStep, jsonArrayFinal, jsonArrayValue },
2493 { "json_group_object", 2,
2494 jsonObjectStep, jsonObjectFinal, jsonObjectValue },
drhff135ae2015-12-30 01:07:02 +00002495 };
drhd2975922015-08-29 17:22:33 +00002496#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002497 static const struct {
2498 const char *zName;
2499 sqlite3_module *pModule;
2500 } aMod[] = {
2501 { "json_each", &jsonEachModule },
2502 { "json_tree", &jsonTreeModule },
2503 };
drhd2975922015-08-29 17:22:33 +00002504#endif
drh5fa5c102015-08-12 16:49:40 +00002505 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2506 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002507 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2508 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002509 aFunc[i].xFunc, 0, 0);
2510 }
mistachkin5a193dd2018-07-24 13:57:44 +00002511#ifndef SQLITE_OMIT_WINDOWFUNC
drhff135ae2015-12-30 01:07:02 +00002512 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
drh8be47a72018-07-05 20:05:29 +00002513 rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
drhff135ae2015-12-30 01:07:02 +00002514 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
drh8be47a72018-07-05 20:05:29 +00002515 aAgg[i].xStep, aAgg[i].xFinal,
2516 aAgg[i].xValue, jsonGroupInverse, 0);
drhff135ae2015-12-30 01:07:02 +00002517 }
mistachkin5a193dd2018-07-24 13:57:44 +00002518#endif
drhd2975922015-08-29 17:22:33 +00002519#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002520 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2521 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002522 }
drhd2975922015-08-29 17:22:33 +00002523#endif
drh5fa5c102015-08-12 16:49:40 +00002524 return rc;
2525}
drh2f20e132015-09-26 17:44:59 +00002526
2527
dan8d32e802015-10-14 18:45:42 +00002528#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002529#ifdef _WIN32
2530__declspec(dllexport)
2531#endif
2532int sqlite3_json_init(
2533 sqlite3 *db,
2534 char **pzErrMsg,
2535 const sqlite3_api_routines *pApi
2536){
2537 SQLITE_EXTENSION_INIT2(pApi);
2538 (void)pzErrMsg; /* Unused parameter */
2539 return sqlite3Json1Init(db);
2540}
dan8d32e802015-10-14 18:45:42 +00002541#endif
drh50065652015-10-08 19:29:18 +00002542#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */