blob: 60a34539a0fcd07f9ada8e5f44dbc368b5745a25 [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 */
drhe9c37f32015-08-15 21:25:36 +0000174};
175
drhff6d50e2017-04-11 18:55:05 +0000176/*
177** Maximum nesting depth of JSON for this implementation.
178**
179** This limit is needed to avoid a stack overflow in the recursive
180** descent parser. A depth of 2000 is far deeper than any sane JSON
181** should go.
182*/
183#define JSON_MAX_DEPTH 2000
184
drh505ad2c2015-08-21 17:33:11 +0000185/**************************************************************************
186** Utility routines for dealing with JsonString objects
187**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000188
drh505ad2c2015-08-21 17:33:11 +0000189/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000190*/
drh505ad2c2015-08-21 17:33:11 +0000191static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000192 p->zBuf = p->zSpace;
193 p->nAlloc = sizeof(p->zSpace);
194 p->nUsed = 0;
195 p->bStatic = 1;
196}
197
drh505ad2c2015-08-21 17:33:11 +0000198/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000199*/
drh505ad2c2015-08-21 17:33:11 +0000200static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000201 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000202 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000203 jsonZero(p);
204}
205
206
drh505ad2c2015-08-21 17:33:11 +0000207/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000208** initial state.
209*/
drh505ad2c2015-08-21 17:33:11 +0000210static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000211 if( !p->bStatic ) sqlite3_free(p->zBuf);
212 jsonZero(p);
213}
214
215
216/* Report an out-of-memory (OOM) condition
217*/
drh505ad2c2015-08-21 17:33:11 +0000218static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000219 p->bErr = 1;
220 sqlite3_result_error_nomem(p->pCtx);
221 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000222}
223
224/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
225** Return zero on success. Return non-zero on an OOM error
226*/
drh505ad2c2015-08-21 17:33:11 +0000227static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000228 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000229 char *zNew;
230 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000231 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000232 zNew = sqlite3_malloc64(nTotal);
233 if( zNew==0 ){
234 jsonOom(p);
235 return SQLITE_NOMEM;
236 }
drh6fd5c1e2015-08-21 20:37:12 +0000237 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000238 p->zBuf = zNew;
239 p->bStatic = 0;
240 }else{
241 zNew = sqlite3_realloc64(p->zBuf, nTotal);
242 if( zNew==0 ){
243 jsonOom(p);
244 return SQLITE_NOMEM;
245 }
246 p->zBuf = zNew;
247 }
248 p->nAlloc = nTotal;
249 return SQLITE_OK;
250}
251
drh505ad2c2015-08-21 17:33:11 +0000252/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000253*/
drh505ad2c2015-08-21 17:33:11 +0000254static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000255 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
256 memcpy(p->zBuf+p->nUsed, zIn, N);
257 p->nUsed += N;
258}
259
drh4af352d2015-08-21 20:02:48 +0000260/* Append formatted text (not to exceed N bytes) to the JsonString.
261*/
262static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
263 va_list ap;
264 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
265 va_start(ap, zFormat);
266 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
267 va_end(ap);
268 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
269}
270
drh5634cc02015-08-17 11:28:03 +0000271/* Append a single character
272*/
drh505ad2c2015-08-21 17:33:11 +0000273static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000274 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
275 p->zBuf[p->nUsed++] = c;
276}
277
drh301eecc2015-08-17 20:14:19 +0000278/* Append a comma separator to the output buffer, if the previous
279** character is not '[' or '{'.
280*/
drh505ad2c2015-08-21 17:33:11 +0000281static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000282 char c;
283 if( p->nUsed==0 ) return;
284 c = p->zBuf[p->nUsed-1];
285 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
286}
287
drh505ad2c2015-08-21 17:33:11 +0000288/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000289** under construction. Enclose the string in "..." and escape
290** any double-quotes or backslash characters contained within the
291** string.
292*/
drh505ad2c2015-08-21 17:33:11 +0000293static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000294 u32 i;
295 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
296 p->zBuf[p->nUsed++] = '"';
297 for(i=0; i<N; i++){
drh3b7f9a62016-02-04 10:28:57 +0000298 unsigned char c = ((unsigned const char*)zIn)[i];
drh5fa5c102015-08-12 16:49:40 +0000299 if( c=='"' || c=='\\' ){
drh3b7f9a62016-02-04 10:28:57 +0000300 json_simple_escape:
drh4977ccf2015-09-19 11:57:26 +0000301 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000302 p->zBuf[p->nUsed++] = '\\';
drh3b7f9a62016-02-04 10:28:57 +0000303 }else if( c<=0x1f ){
304 static const char aSpecial[] = {
305 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
306 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
307 };
308 assert( sizeof(aSpecial)==32 );
309 assert( aSpecial['\b']=='b' );
310 assert( aSpecial['\f']=='f' );
311 assert( aSpecial['\n']=='n' );
312 assert( aSpecial['\r']=='r' );
313 assert( aSpecial['\t']=='t' );
314 if( aSpecial[c] ){
315 c = aSpecial[c];
316 goto json_simple_escape;
317 }
318 if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
319 p->zBuf[p->nUsed++] = '\\';
320 p->zBuf[p->nUsed++] = 'u';
321 p->zBuf[p->nUsed++] = '0';
322 p->zBuf[p->nUsed++] = '0';
323 p->zBuf[p->nUsed++] = '0' + (c>>4);
324 c = "0123456789abcdef"[c&0xf];
drh5fa5c102015-08-12 16:49:40 +0000325 }
326 p->zBuf[p->nUsed++] = c;
327 }
328 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000329 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000330}
331
drhd0960592015-08-17 21:22:32 +0000332/*
333** Append a function parameter value to the JSON string under
334** construction.
335*/
336static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000337 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000338 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000339){
340 switch( sqlite3_value_type(pValue) ){
341 case SQLITE_NULL: {
342 jsonAppendRaw(p, "null", 4);
343 break;
344 }
345 case SQLITE_INTEGER:
346 case SQLITE_FLOAT: {
347 const char *z = (const char*)sqlite3_value_text(pValue);
348 u32 n = (u32)sqlite3_value_bytes(pValue);
349 jsonAppendRaw(p, z, n);
350 break;
351 }
352 case SQLITE_TEXT: {
353 const char *z = (const char*)sqlite3_value_text(pValue);
354 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000355 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000356 jsonAppendRaw(p, z, n);
357 }else{
358 jsonAppendString(p, z, n);
359 }
drhd0960592015-08-17 21:22:32 +0000360 break;
361 }
362 default: {
363 if( p->bErr==0 ){
364 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
drh4a642b62016-02-05 01:55:27 +0000365 p->bErr = 2;
drhd0960592015-08-17 21:22:32 +0000366 jsonReset(p);
367 }
368 break;
369 }
370 }
371}
372
373
drhbd0621b2015-08-13 13:54:59 +0000374/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000375*/
drh505ad2c2015-08-21 17:33:11 +0000376static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000377 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000378 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
379 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
380 SQLITE_UTF8);
381 jsonZero(p);
382 }
383 assert( p->bStatic );
384}
385
drh505ad2c2015-08-21 17:33:11 +0000386/**************************************************************************
387** Utility routines for dealing with JsonNode and JsonParse objects
388**************************************************************************/
389
390/*
391** Return the number of consecutive JsonNode slots need to represent
392** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
393** OBJECT types, the number might be larger.
394**
395** Appended elements are not counted. The value returned is the number
396** by which the JsonNode counter should increment in order to go to the
397** next peer value.
398*/
399static u32 jsonNodeSize(JsonNode *pNode){
400 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
401}
402
403/*
404** Reclaim all memory allocated by a JsonParse object. But do not
405** delete the JsonParse object itself.
406*/
407static void jsonParseReset(JsonParse *pParse){
408 sqlite3_free(pParse->aNode);
409 pParse->aNode = 0;
410 pParse->nNode = 0;
411 pParse->nAlloc = 0;
412 sqlite3_free(pParse->aUp);
413 pParse->aUp = 0;
414}
415
drh5634cc02015-08-17 11:28:03 +0000416/*
417** Convert the JsonNode pNode into a pure JSON string and
418** append to pOut. Subsubstructure is also included. Return
419** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000420*/
drh52216ad2015-08-18 02:28:03 +0000421static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000422 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000423 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000424 sqlite3_value **aReplace /* Replacement values */
425){
drh633647a2017-03-22 21:24:31 +0000426 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
427 if( pNode->jnFlags & JNODE_REPLACE ){
428 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
429 return;
430 }
431 pNode = pNode->u.pPatch;
432 }
drh5634cc02015-08-17 11:28:03 +0000433 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000434 default: {
435 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000436 jsonAppendRaw(pOut, "null", 4);
437 break;
438 }
439 case JSON_TRUE: {
440 jsonAppendRaw(pOut, "true", 4);
441 break;
442 }
443 case JSON_FALSE: {
444 jsonAppendRaw(pOut, "false", 5);
445 break;
446 }
447 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000448 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000449 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000450 break;
451 }
452 /* Fall through into the next case */
453 }
454 case JSON_REAL:
455 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000456 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000457 break;
458 }
459 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000460 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000461 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000462 for(;;){
463 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000464 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000465 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000466 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000467 }
drh505ad2c2015-08-21 17:33:11 +0000468 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000469 }
drh52216ad2015-08-18 02:28:03 +0000470 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
471 pNode = &pNode[pNode->u.iAppend];
472 j = 1;
drh5634cc02015-08-17 11:28:03 +0000473 }
474 jsonAppendChar(pOut, ']');
475 break;
476 }
477 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000478 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000479 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000480 for(;;){
481 while( j<=pNode->n ){
482 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
483 jsonAppendSeparator(pOut);
484 jsonRenderNode(&pNode[j], pOut, aReplace);
485 jsonAppendChar(pOut, ':');
drh633647a2017-03-22 21:24:31 +0000486 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000487 }
drh505ad2c2015-08-21 17:33:11 +0000488 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000489 }
drh52216ad2015-08-18 02:28:03 +0000490 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
491 pNode = &pNode[pNode->u.iAppend];
492 j = 1;
drh5634cc02015-08-17 11:28:03 +0000493 }
494 jsonAppendChar(pOut, '}');
495 break;
496 }
drhbd0621b2015-08-13 13:54:59 +0000497 }
drh5634cc02015-08-17 11:28:03 +0000498}
499
500/*
drhf2df7e72015-08-28 20:07:40 +0000501** Return a JsonNode and all its descendents as a JSON string.
502*/
503static void jsonReturnJson(
504 JsonNode *pNode, /* Node to return */
505 sqlite3_context *pCtx, /* Return value for this function */
506 sqlite3_value **aReplace /* Array of replacement values */
507){
508 JsonString s;
509 jsonInit(&s, pCtx);
510 jsonRenderNode(pNode, &s, aReplace);
511 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000512 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000513}
514
515/*
drh5634cc02015-08-17 11:28:03 +0000516** Make the JsonNode the return value of the function.
517*/
drhd0960592015-08-17 21:22:32 +0000518static void jsonReturn(
519 JsonNode *pNode, /* Node to return */
520 sqlite3_context *pCtx, /* Return value for this function */
521 sqlite3_value **aReplace /* Array of replacement values */
522){
drh5634cc02015-08-17 11:28:03 +0000523 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000524 default: {
525 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000526 sqlite3_result_null(pCtx);
527 break;
528 }
529 case JSON_TRUE: {
530 sqlite3_result_int(pCtx, 1);
531 break;
532 }
533 case JSON_FALSE: {
534 sqlite3_result_int(pCtx, 0);
535 break;
536 }
drh987eb1f2015-08-17 15:17:37 +0000537 case JSON_INT: {
538 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000539 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000540 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000541 while( z[0]>='0' && z[0]<='9' ){
542 unsigned v = *(z++) - '0';
543 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000544 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000545 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
546 if( v==9 ) goto int_as_real;
547 if( v==8 ){
548 if( pNode->u.zJContent[0]=='-' ){
549 sqlite3_result_int64(pCtx, SMALLEST_INT64);
550 goto int_done;
551 }else{
552 goto int_as_real;
553 }
554 }
555 }
556 i = i*10 + v;
557 }
drh52216ad2015-08-18 02:28:03 +0000558 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000559 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000560 int_done:
561 break;
562 int_as_real: /* fall through to real */;
563 }
564 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000565 double r;
566#ifdef SQLITE_AMALGAMATION
567 const char *z = pNode->u.zJContent;
568 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
569#else
570 r = strtod(pNode->u.zJContent, 0);
571#endif
drh8deb4b82015-10-09 18:21:43 +0000572 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000573 break;
574 }
drh5634cc02015-08-17 11:28:03 +0000575 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000576#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
577 ** json_insert() and json_replace() and those routines do not
578 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000579 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000580 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
581 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000582 }else
583#endif
584 assert( (pNode->jnFlags & JNODE_RAW)==0 );
585 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000586 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000587 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000588 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000589 }else{
590 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000591 u32 i;
592 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000593 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000594 char *zOut;
595 u32 j;
596 zOut = sqlite3_malloc( n+1 );
597 if( zOut==0 ){
598 sqlite3_result_error_nomem(pCtx);
599 break;
600 }
601 for(i=1, j=0; i<n-1; i++){
602 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000603 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000604 zOut[j++] = c;
605 }else{
606 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000607 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000608 u32 v = 0, k;
drh27b2d1b2016-11-07 15:15:42 +0000609 for(k=0; k<4; i++, k++){
610 assert( i<n-2 );
drh8784eca2015-08-23 02:42:30 +0000611 c = z[i+1];
drh27b2d1b2016-11-07 15:15:42 +0000612 assert( safe_isxdigit(c) );
613 if( c<='9' ) v = v*16 + c - '0';
614 else if( c<='F' ) v = v*16 + c - 'A' + 10;
615 else v = v*16 + c - 'a' + 10;
drh987eb1f2015-08-17 15:17:37 +0000616 }
drh80d87402015-08-24 12:42:41 +0000617 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000618 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000619 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000620 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000621 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000622 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000623 }else{
mistachkin16a93122015-09-11 18:05:01 +0000624 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000625 zOut[j++] = 0x80 | ((v>>6)&0x3f);
626 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000627 }
628 }else{
629 if( c=='b' ){
630 c = '\b';
631 }else if( c=='f' ){
632 c = '\f';
633 }else if( c=='n' ){
634 c = '\n';
635 }else if( c=='r' ){
636 c = '\r';
637 }else if( c=='t' ){
638 c = '\t';
639 }
640 zOut[j++] = c;
641 }
642 }
643 }
644 zOut[j] = 0;
645 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000646 }
647 break;
648 }
649 case JSON_ARRAY:
650 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000651 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000652 break;
653 }
654 }
drhbd0621b2015-08-13 13:54:59 +0000655}
656
drh95677942015-09-24 01:06:37 +0000657/* Forward reference */
658static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
659
660/*
661** A macro to hint to the compiler that a function should not be
662** inlined.
663*/
664#if defined(__GNUC__)
665# define JSON_NOINLINE __attribute__((noinline))
666#elif defined(_MSC_VER) && _MSC_VER>=1310
667# define JSON_NOINLINE __declspec(noinline)
668#else
669# define JSON_NOINLINE
670#endif
671
672
673static JSON_NOINLINE int jsonParseAddNodeExpand(
674 JsonParse *pParse, /* Append the node to this object */
675 u32 eType, /* Node type */
676 u32 n, /* Content size or sub-node count */
677 const char *zContent /* Content */
678){
679 u32 nNew;
680 JsonNode *pNew;
681 assert( pParse->nNode>=pParse->nAlloc );
682 if( pParse->oom ) return -1;
683 nNew = pParse->nAlloc*2 + 10;
684 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
685 if( pNew==0 ){
686 pParse->oom = 1;
687 return -1;
688 }
689 pParse->nAlloc = nNew;
690 pParse->aNode = pNew;
691 assert( pParse->nNode<pParse->nAlloc );
692 return jsonParseAddNode(pParse, eType, n, zContent);
693}
694
drh5fa5c102015-08-12 16:49:40 +0000695/*
drhe9c37f32015-08-15 21:25:36 +0000696** Create a new JsonNode instance based on the arguments and append that
697** instance to the JsonParse. Return the index in pParse->aNode[] of the
698** new node, or -1 if a memory allocation fails.
699*/
700static int jsonParseAddNode(
701 JsonParse *pParse, /* Append the node to this object */
702 u32 eType, /* Node type */
703 u32 n, /* Content size or sub-node count */
704 const char *zContent /* Content */
705){
706 JsonNode *p;
707 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000708 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000709 }
710 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000711 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000712 p->jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000713 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000714 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000715 return pParse->nNode++;
716}
717
718/*
drhad875e72016-11-07 13:37:28 +0000719** Return true if z[] begins with 4 (or more) hexadecimal digits
720*/
721static int jsonIs4Hex(const char *z){
722 int i;
723 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
724 return 1;
725}
726
727/*
drhe9c37f32015-08-15 21:25:36 +0000728** Parse a single JSON value which begins at pParse->zJson[i]. Return the
729** index of the first character past the end of the value parsed.
730**
731** Return negative for a syntax error. Special cases: return -2 if the
732** first non-whitespace character is '}' and return -3 if the first
733** non-whitespace character is ']'.
734*/
735static int jsonParseValue(JsonParse *pParse, u32 i){
736 char c;
737 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000738 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000739 int x;
drh852944e2015-09-10 03:29:11 +0000740 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000741 const char *z = pParse->zJson;
742 while( safe_isspace(z[i]) ){ i++; }
743 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000744 /* Parse object */
745 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000746 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000747 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000748 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000749 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000750 x = jsonParseValue(pParse, j);
751 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000752 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000753 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000754 return -1;
755 }
drhbe9474e2015-08-22 03:05:54 +0000756 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000757 pNode = &pParse->aNode[pParse->nNode-1];
758 if( pNode->eType!=JSON_STRING ) return -1;
759 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000760 j = x;
drh9fa866a2017-04-08 18:18:22 +0000761 while( safe_isspace(z[j]) ){ j++; }
762 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000763 j++;
764 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000765 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000766 if( x<0 ) return -1;
767 j = x;
drh9fa866a2017-04-08 18:18:22 +0000768 while( safe_isspace(z[j]) ){ j++; }
769 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000770 if( c==',' ) continue;
771 if( c!='}' ) return -1;
772 break;
773 }
drhbc8f0922015-08-22 19:39:04 +0000774 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000775 return j+1;
776 }else if( c=='[' ){
777 /* Parse array */
778 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000779 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000780 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000781 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000782 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000783 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000784 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000785 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000786 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000787 return -1;
788 }
789 j = x;
drh9fa866a2017-04-08 18:18:22 +0000790 while( safe_isspace(z[j]) ){ j++; }
791 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000792 if( c==',' ) continue;
793 if( c!=']' ) return -1;
794 break;
795 }
drhbc8f0922015-08-22 19:39:04 +0000796 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000797 return j+1;
798 }else if( c=='"' ){
799 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000800 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000801 j = i+1;
802 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000803 c = z[j];
drh86715382017-04-13 00:12:32 +0000804 if( (c & ~0x1f)==0 ){
805 /* Control characters are not allowed in strings */
806 return -1;
807 }
drhe9c37f32015-08-15 21:25:36 +0000808 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000809 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000810 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
811 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000812 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000813 jnFlags = JNODE_ESCAPE;
814 }else{
815 return -1;
816 }
drhe9c37f32015-08-15 21:25:36 +0000817 }else if( c=='"' ){
818 break;
819 }
820 j++;
821 }
drh9fa866a2017-04-08 18:18:22 +0000822 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000823 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000824 return j+1;
825 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000826 && strncmp(z+i,"null",4)==0
827 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000828 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
829 return i+4;
830 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000831 && strncmp(z+i,"true",4)==0
832 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000833 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
834 return i+4;
835 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000836 && strncmp(z+i,"false",5)==0
837 && !safe_isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000838 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
839 return i+5;
840 }else if( c=='-' || (c>='0' && c<='9') ){
841 /* Parse number */
842 u8 seenDP = 0;
843 u8 seenE = 0;
drh9fa866a2017-04-08 18:18:22 +0000844 assert( '-' < '0' );
845 if( c<='0' ){
846 j = c=='-' ? i+1 : i;
847 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
848 }
drhe9c37f32015-08-15 21:25:36 +0000849 j = i+1;
850 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000851 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000852 if( c>='0' && c<='9' ) continue;
853 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000854 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000855 if( seenDP ) return -1;
856 seenDP = 1;
857 continue;
858 }
859 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000860 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000861 if( seenE ) return -1;
862 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000863 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000864 if( c=='+' || c=='-' ){
865 j++;
drh9fa866a2017-04-08 18:18:22 +0000866 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000867 }
drhd1f00682015-08-29 16:02:37 +0000868 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000869 continue;
870 }
871 break;
872 }
drh9fa866a2017-04-08 18:18:22 +0000873 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000874 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000875 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000876 return j;
877 }else if( c=='}' ){
878 return -2; /* End of {...} */
879 }else if( c==']' ){
880 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000881 }else if( c==0 ){
882 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000883 }else{
884 return -1; /* Syntax error */
885 }
886}
887
888/*
889** Parse a complete JSON string. Return 0 on success or non-zero if there
890** are any errors. If an error occurs, free all memory associated with
891** pParse.
892**
893** pParse is uninitialized when this routine is called.
894*/
drhbc8f0922015-08-22 19:39:04 +0000895static int jsonParse(
896 JsonParse *pParse, /* Initialize and fill this JsonParse object */
897 sqlite3_context *pCtx, /* Report errors here */
898 const char *zJson /* Input JSON text to be parsed */
899){
drhe9c37f32015-08-15 21:25:36 +0000900 int i;
drhe9c37f32015-08-15 21:25:36 +0000901 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000902 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000903 pParse->zJson = zJson;
904 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000905 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000906 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000907 assert( pParse->iDepth==0 );
dan2e8f5512015-09-17 17:21:09 +0000908 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000909 if( zJson[i] ) i = -1;
910 }
drhd1f00682015-08-29 16:02:37 +0000911 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000912 if( pCtx!=0 ){
913 if( pParse->oom ){
914 sqlite3_result_error_nomem(pCtx);
915 }else{
916 sqlite3_result_error(pCtx, "malformed JSON", -1);
917 }
918 }
drh505ad2c2015-08-21 17:33:11 +0000919 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000920 return 1;
921 }
922 return 0;
923}
drh301eecc2015-08-17 20:14:19 +0000924
drh505ad2c2015-08-21 17:33:11 +0000925/* Mark node i of pParse as being a child of iParent. Call recursively
926** to fill in all the descendants of node i.
927*/
928static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
929 JsonNode *pNode = &pParse->aNode[i];
930 u32 j;
931 pParse->aUp[i] = iParent;
932 switch( pNode->eType ){
933 case JSON_ARRAY: {
934 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
935 jsonParseFillInParentage(pParse, i+j, i);
936 }
937 break;
938 }
939 case JSON_OBJECT: {
940 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
941 pParse->aUp[i+j] = i;
942 jsonParseFillInParentage(pParse, i+j+1, i);
943 }
944 break;
945 }
946 default: {
947 break;
948 }
949 }
950}
951
952/*
953** Compute the parentage of all nodes in a completed parse.
954*/
955static int jsonParseFindParents(JsonParse *pParse){
956 u32 *aUp;
957 assert( pParse->aUp==0 );
958 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000959 if( aUp==0 ){
960 pParse->oom = 1;
961 return SQLITE_NOMEM;
962 }
drh505ad2c2015-08-21 17:33:11 +0000963 jsonParseFillInParentage(pParse, 0, 0);
964 return SQLITE_OK;
965}
966
drh8cb0c832015-09-22 00:21:03 +0000967/*
968** Compare the OBJECT label at pNode against zKey,nKey. Return true on
969** a match.
970*/
mistachkinf2c26ed2015-10-12 22:20:29 +0000971static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh8cb0c832015-09-22 00:21:03 +0000972 if( pNode->jnFlags & JNODE_RAW ){
973 if( pNode->n!=nKey ) return 0;
974 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
975 }else{
976 if( pNode->n!=nKey+2 ) return 0;
977 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
978 }
979}
980
drh52216ad2015-08-18 02:28:03 +0000981/* forward declaration */
drha7714022015-08-29 00:54:49 +0000982static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000983
drh987eb1f2015-08-17 15:17:37 +0000984/*
985** Search along zPath to find the node specified. Return a pointer
986** to that node, or NULL if zPath is malformed or if there is no such
987** node.
drh52216ad2015-08-18 02:28:03 +0000988**
989** If pApnd!=0, then try to append new nodes to complete zPath if it is
990** possible to do so and if no existing node corresponds to zPath. If
991** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000992*/
drha7714022015-08-29 00:54:49 +0000993static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000994 JsonParse *pParse, /* The JSON to search */
995 u32 iRoot, /* Begin the search at this node */
996 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000997 int *pApnd, /* Append nodes to complete path if not NULL */
998 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000999){
drhbc8f0922015-08-22 19:39:04 +00001000 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001001 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001002 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001003 if( zPath[0]==0 ) return pRoot;
1004 if( zPath[0]=='.' ){
1005 if( pRoot->eType!=JSON_OBJECT ) return 0;
1006 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001007 if( zPath[0]=='"' ){
1008 zKey = zPath + 1;
1009 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1010 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001011 if( zPath[i] ){
1012 i++;
1013 }else{
1014 *pzErr = zPath;
1015 return 0;
1016 }
drh6b43cc82015-08-19 23:02:49 +00001017 }else{
1018 zKey = zPath;
1019 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1020 nKey = i;
1021 }
drha7714022015-08-29 00:54:49 +00001022 if( nKey==0 ){
1023 *pzErr = zPath;
1024 return 0;
1025 }
drh987eb1f2015-08-17 15:17:37 +00001026 j = 1;
drh52216ad2015-08-18 02:28:03 +00001027 for(;;){
1028 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001029 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001030 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001031 }
1032 j++;
drh505ad2c2015-08-21 17:33:11 +00001033 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001034 }
drh52216ad2015-08-18 02:28:03 +00001035 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1036 iRoot += pRoot->u.iAppend;
1037 pRoot = &pParse->aNode[iRoot];
1038 j = 1;
1039 }
1040 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001041 u32 iStart, iLabel;
1042 JsonNode *pNode;
1043 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1044 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +00001045 zPath += i;
drha7714022015-08-29 00:54:49 +00001046 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001047 if( pParse->oom ) return 0;
1048 if( pNode ){
1049 pRoot = &pParse->aNode[iRoot];
1050 pRoot->u.iAppend = iStart - iRoot;
1051 pRoot->jnFlags |= JNODE_APPEND;
1052 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1053 }
1054 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001055 }
dan2e8f5512015-09-17 17:21:09 +00001056 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +00001057 if( pRoot->eType!=JSON_ARRAY ) return 0;
1058 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001059 j = 1;
1060 while( safe_isdigit(zPath[j]) ){
1061 i = i*10 + zPath[j] - '0';
1062 j++;
drh987eb1f2015-08-17 15:17:37 +00001063 }
drh3d1d2a92015-09-22 01:15:49 +00001064 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +00001065 *pzErr = zPath;
1066 return 0;
1067 }
drh3d1d2a92015-09-22 01:15:49 +00001068 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001069 j = 1;
drh52216ad2015-08-18 02:28:03 +00001070 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001071 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1072 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001073 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001074 }
1075 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1076 iRoot += pRoot->u.iAppend;
1077 pRoot = &pParse->aNode[iRoot];
1078 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001079 }
1080 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001081 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001082 }
1083 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001084 u32 iStart;
1085 JsonNode *pNode;
1086 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001087 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001088 if( pParse->oom ) return 0;
1089 if( pNode ){
1090 pRoot = &pParse->aNode[iRoot];
1091 pRoot->u.iAppend = iStart - iRoot;
1092 pRoot->jnFlags |= JNODE_APPEND;
1093 }
1094 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001095 }
drh3d1d2a92015-09-22 01:15:49 +00001096 }else{
drha7714022015-08-29 00:54:49 +00001097 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001098 }
1099 return 0;
1100}
1101
drh52216ad2015-08-18 02:28:03 +00001102/*
drhbc8f0922015-08-22 19:39:04 +00001103** Append content to pParse that will complete zPath. Return a pointer
1104** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001105*/
1106static JsonNode *jsonLookupAppend(
1107 JsonParse *pParse, /* Append content to the JSON parse */
1108 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001109 int *pApnd, /* Set this flag to 1 */
1110 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001111){
1112 *pApnd = 1;
1113 if( zPath[0]==0 ){
1114 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1115 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1116 }
1117 if( zPath[0]=='.' ){
1118 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1119 }else if( strncmp(zPath,"[0]",3)==0 ){
1120 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1121 }else{
1122 return 0;
1123 }
1124 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001125 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001126}
1127
drhbc8f0922015-08-22 19:39:04 +00001128/*
drha7714022015-08-29 00:54:49 +00001129** Return the text of a syntax error message on a JSON path. Space is
1130** obtained from sqlite3_malloc().
1131*/
1132static char *jsonPathSyntaxError(const char *zErr){
1133 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1134}
1135
1136/*
1137** Do a node lookup using zPath. Return a pointer to the node on success.
1138** Return NULL if not found or if there is an error.
1139**
1140** On an error, write an error message into pCtx and increment the
1141** pParse->nErr counter.
1142**
1143** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1144** nodes are appended.
drha7714022015-08-29 00:54:49 +00001145*/
1146static JsonNode *jsonLookup(
1147 JsonParse *pParse, /* The JSON to search */
1148 const char *zPath, /* The path to search */
1149 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001150 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001151){
1152 const char *zErr = 0;
1153 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001154 char *zMsg;
drha7714022015-08-29 00:54:49 +00001155
1156 if( zPath==0 ) return 0;
1157 if( zPath[0]!='$' ){
1158 zErr = zPath;
1159 goto lookup_err;
1160 }
1161 zPath++;
drha7714022015-08-29 00:54:49 +00001162 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001163 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001164
1165lookup_err:
1166 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001167 assert( zErr!=0 && pCtx!=0 );
1168 zMsg = jsonPathSyntaxError(zErr);
1169 if( zMsg ){
1170 sqlite3_result_error(pCtx, zMsg, -1);
1171 sqlite3_free(zMsg);
1172 }else{
1173 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001174 }
drha7714022015-08-29 00:54:49 +00001175 return 0;
1176}
1177
1178
1179/*
drhbc8f0922015-08-22 19:39:04 +00001180** Report the wrong number of arguments for json_insert(), json_replace()
1181** or json_set().
1182*/
1183static void jsonWrongNumArgs(
1184 sqlite3_context *pCtx,
1185 const char *zFuncName
1186){
1187 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1188 zFuncName);
1189 sqlite3_result_error(pCtx, zMsg, -1);
1190 sqlite3_free(zMsg);
1191}
drh52216ad2015-08-18 02:28:03 +00001192
drh29c99692017-03-24 12:35:17 +00001193/*
1194** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1195*/
1196static void jsonRemoveAllNulls(JsonNode *pNode){
1197 int i, n;
1198 assert( pNode->eType==JSON_OBJECT );
1199 n = pNode->n;
1200 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1201 switch( pNode[i].eType ){
1202 case JSON_NULL:
1203 pNode[i].jnFlags |= JNODE_REMOVE;
1204 break;
1205 case JSON_OBJECT:
1206 jsonRemoveAllNulls(&pNode[i]);
1207 break;
1208 }
1209 }
1210}
1211
drha7714022015-08-29 00:54:49 +00001212
drh987eb1f2015-08-17 15:17:37 +00001213/****************************************************************************
1214** SQL functions used for testing and debugging
1215****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001216
drh301eecc2015-08-17 20:14:19 +00001217#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001218/*
drh5634cc02015-08-17 11:28:03 +00001219** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001220** a parse of the JSON provided. Or it returns NULL if JSON is not
1221** well-formed.
1222*/
drh5634cc02015-08-17 11:28:03 +00001223static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001224 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001225 int argc,
1226 sqlite3_value **argv
1227){
drh505ad2c2015-08-21 17:33:11 +00001228 JsonString s; /* Output string - not real JSON */
1229 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001230 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001231
1232 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001233 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001234 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001235 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001236 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001237 const char *zType;
1238 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1239 assert( x.aNode[i].eType==JSON_STRING );
1240 zType = "label";
1241 }else{
1242 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001243 }
drh852944e2015-09-10 03:29:11 +00001244 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1245 i, zType, x.aNode[i].n, x.aUp[i]);
1246 if( x.aNode[i].u.zJContent!=0 ){
1247 jsonAppendRaw(&s, " ", 1);
1248 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1249 }
1250 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001251 }
drh505ad2c2015-08-21 17:33:11 +00001252 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001253 jsonResult(&s);
1254}
1255
drh5634cc02015-08-17 11:28:03 +00001256/*
drhf5ddb9c2015-09-11 00:06:41 +00001257** The json_test1(JSON) function return true (1) if the input is JSON
1258** text generated by another json function. It returns (0) if the input
1259** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001260*/
1261static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001262 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001263 int argc,
1264 sqlite3_value **argv
1265){
mistachkin16a93122015-09-11 18:05:01 +00001266 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001267 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001268}
drh301eecc2015-08-17 20:14:19 +00001269#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001270
drh987eb1f2015-08-17 15:17:37 +00001271/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001272** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001273****************************************************************************/
1274
1275/*
drh2ad96f52016-06-17 13:01:51 +00001276** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1277** corresponding to the SQL value input. Mostly this means putting
1278** double-quotes around strings and returning the unquoted string "null"
1279** when given a NULL input.
1280*/
1281static void jsonQuoteFunc(
1282 sqlite3_context *ctx,
1283 int argc,
1284 sqlite3_value **argv
1285){
1286 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001287 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001288
1289 jsonInit(&jx, ctx);
1290 jsonAppendValue(&jx, argv[0]);
1291 jsonResult(&jx);
1292 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1293}
1294
1295/*
drh987eb1f2015-08-17 15:17:37 +00001296** Implementation of the json_array(VALUE,...) function. Return a JSON
1297** array that contains all values given in arguments. Or if any argument
1298** is a BLOB, throw an error.
1299*/
1300static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001301 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001302 int argc,
1303 sqlite3_value **argv
1304){
1305 int i;
drh505ad2c2015-08-21 17:33:11 +00001306 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001307
drhbc8f0922015-08-22 19:39:04 +00001308 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001309 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001310 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001311 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001312 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001313 }
drhd0960592015-08-17 21:22:32 +00001314 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001315 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001316 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001317}
1318
1319
1320/*
1321** json_array_length(JSON)
1322** json_array_length(JSON, PATH)
1323**
1324** Return the number of elements in the top-level JSON array.
1325** Return 0 if the input is not a well-formed JSON array.
1326*/
1327static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001328 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001329 int argc,
1330 sqlite3_value **argv
1331){
1332 JsonParse x; /* The parse */
1333 sqlite3_int64 n = 0;
1334 u32 i;
drha8f39a92015-09-21 22:53:16 +00001335 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001336
drhf2df7e72015-08-28 20:07:40 +00001337 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001338 assert( x.nNode );
1339 if( argc==2 ){
1340 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1341 pNode = jsonLookup(&x, zPath, 0, ctx);
1342 }else{
1343 pNode = x.aNode;
1344 }
1345 if( pNode==0 ){
1346 x.nErr = 1;
1347 }else if( pNode->eType==JSON_ARRAY ){
1348 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1349 for(i=1; i<=pNode->n; n++){
1350 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001351 }
drh987eb1f2015-08-17 15:17:37 +00001352 }
drha7714022015-08-29 00:54:49 +00001353 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001354 jsonParseReset(&x);
1355}
1356
1357/*
drh3ad93bb2015-08-29 19:41:45 +00001358** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001359**
drh3ad93bb2015-08-29 19:41:45 +00001360** Return the element described by PATH. Return NULL if there is no
1361** PATH element. If there are multiple PATHs, then return a JSON array
1362** with the result from each path. Throw an error if the JSON or any PATH
1363** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001364*/
1365static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001366 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001367 int argc,
1368 sqlite3_value **argv
1369){
1370 JsonParse x; /* The parse */
1371 JsonNode *pNode;
1372 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001373 JsonString jx;
1374 int i;
1375
1376 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001377 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001378 jsonInit(&jx, ctx);
1379 jsonAppendChar(&jx, '[');
1380 for(i=1; i<argc; i++){
1381 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001382 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001383 if( x.nErr ) break;
1384 if( argc>2 ){
1385 jsonAppendSeparator(&jx);
1386 if( pNode ){
1387 jsonRenderNode(pNode, &jx, 0);
1388 }else{
1389 jsonAppendRaw(&jx, "null", 4);
1390 }
1391 }else if( pNode ){
1392 jsonReturn(pNode, ctx, 0);
1393 }
drh987eb1f2015-08-17 15:17:37 +00001394 }
drh3ad93bb2015-08-29 19:41:45 +00001395 if( argc>2 && i==argc ){
1396 jsonAppendChar(&jx, ']');
1397 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001398 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001399 }
1400 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001401 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001402}
1403
drh633647a2017-03-22 21:24:31 +00001404/* This is the RFC 7396 MergePatch algorithm.
1405*/
1406static JsonNode *jsonMergePatch(
1407 JsonParse *pParse, /* The JSON parser that contains the TARGET */
1408 int iTarget, /* Node of the TARGET in pParse */
1409 JsonNode *pPatch /* The PATCH */
1410){
drh0002d242017-03-23 00:46:15 +00001411 u32 i, j;
1412 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001413 JsonNode *pTarget;
1414 if( pPatch->eType!=JSON_OBJECT ){
1415 return pPatch;
1416 }
1417 assert( iTarget>=0 && iTarget<pParse->nNode );
1418 pTarget = &pParse->aNode[iTarget];
1419 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1420 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001421 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001422 return pPatch;
1423 }
drhbb7aa2d2017-03-23 00:13:52 +00001424 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001425 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001426 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001427 const char *zKey;
1428 assert( pPatch[i].eType==JSON_STRING );
1429 assert( pPatch[i].jnFlags & JNODE_LABEL );
1430 nKey = pPatch[i].n;
1431 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001432 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001433 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1434 assert( pTarget[j].eType==JSON_STRING );
1435 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001436 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001437 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1438 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001439 if( pPatch[i+1].eType==JSON_NULL ){
1440 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1441 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001442 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001443 if( pNew==0 ) return 0;
1444 pTarget = &pParse->aNode[iTarget];
1445 if( pNew!=&pTarget[j+1] ){
1446 pTarget[j+1].u.pPatch = pNew;
1447 pTarget[j+1].jnFlags |= JNODE_PATCH;
1448 }
1449 }
1450 break;
1451 }
1452 }
drhbb7aa2d2017-03-23 00:13:52 +00001453 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001454 int iStart, iPatch;
1455 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1456 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1457 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1458 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001459 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001460 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001461 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1462 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1463 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001464 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1465 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1466 }
1467 }
1468 return pTarget;
1469}
1470
1471/*
1472** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1473** object that is the result of running the RFC 7396 MergePatch() algorithm
1474** on the two arguments.
1475*/
drh37f03df2017-03-23 20:33:49 +00001476static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001477 sqlite3_context *ctx,
1478 int argc,
1479 sqlite3_value **argv
1480){
1481 JsonParse x; /* The JSON that is being patched */
1482 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001483 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001484
drh2fb79e92017-03-25 12:08:11 +00001485 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001486 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1487 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1488 jsonParseReset(&x);
1489 return;
1490 }
drhbb7aa2d2017-03-23 00:13:52 +00001491 pResult = jsonMergePatch(&x, 0, y.aNode);
1492 assert( pResult!=0 || x.oom );
1493 if( pResult ){
1494 jsonReturnJson(pResult, ctx, 0);
1495 }else{
1496 sqlite3_result_error_nomem(ctx);
1497 }
drh633647a2017-03-22 21:24:31 +00001498 jsonParseReset(&x);
1499 jsonParseReset(&y);
1500}
1501
1502
drh987eb1f2015-08-17 15:17:37 +00001503/*
1504** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1505** object that contains all name/value given in arguments. Or if any name
1506** is not a string or if any value is a BLOB, throw an error.
1507*/
1508static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001509 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001510 int argc,
1511 sqlite3_value **argv
1512){
1513 int i;
drh505ad2c2015-08-21 17:33:11 +00001514 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001515 const char *z;
1516 u32 n;
1517
1518 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001519 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001520 "of arguments", -1);
1521 return;
1522 }
drhbc8f0922015-08-22 19:39:04 +00001523 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001524 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001525 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001526 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001527 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001528 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001529 return;
1530 }
drhd0960592015-08-17 21:22:32 +00001531 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001532 z = (const char*)sqlite3_value_text(argv[i]);
1533 n = (u32)sqlite3_value_bytes(argv[i]);
1534 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001535 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001536 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001537 }
drhd0960592015-08-17 21:22:32 +00001538 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001539 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001540 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001541}
1542
1543
1544/*
drh301eecc2015-08-17 20:14:19 +00001545** json_remove(JSON, PATH, ...)
1546**
drh3ad93bb2015-08-29 19:41:45 +00001547** Remove the named elements from JSON and return the result. malformed
1548** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001549*/
1550static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001551 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001552 int argc,
1553 sqlite3_value **argv
1554){
1555 JsonParse x; /* The parse */
1556 JsonNode *pNode;
1557 const char *zPath;
1558 u32 i;
1559
1560 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001561 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001562 assert( x.nNode );
1563 for(i=1; i<(u32)argc; i++){
1564 zPath = (const char*)sqlite3_value_text(argv[i]);
1565 if( zPath==0 ) goto remove_done;
1566 pNode = jsonLookup(&x, zPath, 0, ctx);
1567 if( x.nErr ) goto remove_done;
1568 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1569 }
1570 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1571 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001572 }
drha7714022015-08-29 00:54:49 +00001573remove_done:
drh505ad2c2015-08-21 17:33:11 +00001574 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001575}
1576
1577/*
1578** json_replace(JSON, PATH, VALUE, ...)
1579**
1580** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001581** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001582*/
1583static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001584 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001585 int argc,
1586 sqlite3_value **argv
1587){
1588 JsonParse x; /* The parse */
1589 JsonNode *pNode;
1590 const char *zPath;
1591 u32 i;
1592
1593 if( argc<1 ) return;
1594 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001595 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001596 return;
1597 }
drhbc8f0922015-08-22 19:39:04 +00001598 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001599 assert( x.nNode );
1600 for(i=1; i<(u32)argc; i+=2){
1601 zPath = (const char*)sqlite3_value_text(argv[i]);
1602 pNode = jsonLookup(&x, zPath, 0, ctx);
1603 if( x.nErr ) goto replace_err;
1604 if( pNode ){
1605 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001606 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001607 }
drha8f39a92015-09-21 22:53:16 +00001608 }
1609 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001610 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001611 }else{
1612 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001613 }
drha7714022015-08-29 00:54:49 +00001614replace_err:
drh505ad2c2015-08-21 17:33:11 +00001615 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001616}
drh505ad2c2015-08-21 17:33:11 +00001617
drh52216ad2015-08-18 02:28:03 +00001618/*
1619** json_set(JSON, PATH, VALUE, ...)
1620**
1621** Set the value at PATH to VALUE. Create the PATH if it does not already
1622** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001623** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001624**
1625** json_insert(JSON, PATH, VALUE, ...)
1626**
1627** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001628** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001629*/
1630static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001631 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001632 int argc,
1633 sqlite3_value **argv
1634){
1635 JsonParse x; /* The parse */
1636 JsonNode *pNode;
1637 const char *zPath;
1638 u32 i;
1639 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001640 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001641
1642 if( argc<1 ) return;
1643 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001644 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001645 return;
1646 }
drhbc8f0922015-08-22 19:39:04 +00001647 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001648 assert( x.nNode );
1649 for(i=1; i<(u32)argc; i+=2){
1650 zPath = (const char*)sqlite3_value_text(argv[i]);
1651 bApnd = 0;
1652 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1653 if( x.oom ){
1654 sqlite3_result_error_nomem(ctx);
1655 goto jsonSetDone;
1656 }else if( x.nErr ){
1657 goto jsonSetDone;
1658 }else if( pNode && (bApnd || bIsSet) ){
1659 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001660 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001661 }
drha8f39a92015-09-21 22:53:16 +00001662 }
1663 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001664 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001665 }else{
1666 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001667 }
drhbc8f0922015-08-22 19:39:04 +00001668jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001669 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001670}
drh301eecc2015-08-17 20:14:19 +00001671
1672/*
drh987eb1f2015-08-17 15:17:37 +00001673** json_type(JSON)
1674** json_type(JSON, PATH)
1675**
drh3ad93bb2015-08-29 19:41:45 +00001676** Return the top-level "type" of a JSON string. Throw an error if
1677** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001678*/
1679static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001680 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001681 int argc,
1682 sqlite3_value **argv
1683){
1684 JsonParse x; /* The parse */
1685 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001686 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001687
drhbc8f0922015-08-22 19:39:04 +00001688 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001689 assert( x.nNode );
1690 if( argc==2 ){
1691 zPath = (const char*)sqlite3_value_text(argv[1]);
1692 pNode = jsonLookup(&x, zPath, 0, ctx);
1693 }else{
1694 pNode = x.aNode;
1695 }
1696 if( pNode ){
1697 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001698 }
drh505ad2c2015-08-21 17:33:11 +00001699 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001700}
drh5634cc02015-08-17 11:28:03 +00001701
drhbc8f0922015-08-22 19:39:04 +00001702/*
1703** json_valid(JSON)
1704**
drh3ad93bb2015-08-29 19:41:45 +00001705** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1706** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001707*/
1708static void jsonValidFunc(
1709 sqlite3_context *ctx,
1710 int argc,
1711 sqlite3_value **argv
1712){
1713 JsonParse x; /* The parse */
1714 int rc = 0;
1715
mistachkin16a93122015-09-11 18:05:01 +00001716 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001717 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001718 rc = 1;
1719 }
1720 jsonParseReset(&x);
1721 sqlite3_result_int(ctx, rc);
1722}
1723
drhff135ae2015-12-30 01:07:02 +00001724
1725/****************************************************************************
1726** Aggregate SQL function implementations
1727****************************************************************************/
1728/*
1729** json_group_array(VALUE)
1730**
1731** Return a JSON array composed of all values in the aggregate.
1732*/
1733static void jsonArrayStep(
1734 sqlite3_context *ctx,
1735 int argc,
1736 sqlite3_value **argv
1737){
1738 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001739 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001740 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1741 if( pStr ){
1742 if( pStr->zBuf==0 ){
1743 jsonInit(pStr, ctx);
1744 jsonAppendChar(pStr, '[');
1745 }else{
1746 jsonAppendChar(pStr, ',');
1747 pStr->pCtx = ctx;
1748 }
1749 jsonAppendValue(pStr, argv[0]);
1750 }
1751}
1752static void jsonArrayFinal(sqlite3_context *ctx){
1753 JsonString *pStr;
1754 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1755 if( pStr ){
1756 pStr->pCtx = ctx;
1757 jsonAppendChar(pStr, ']');
1758 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001759 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001760 assert( pStr->bStatic );
drhff135ae2015-12-30 01:07:02 +00001761 }else{
1762 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
1763 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1764 pStr->bStatic = 1;
1765 }
1766 }else{
1767 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1768 }
1769 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1770}
1771
1772/*
1773** json_group_obj(NAME,VALUE)
1774**
1775** Return a JSON object composed of all names and values in the aggregate.
1776*/
1777static void jsonObjectStep(
1778 sqlite3_context *ctx,
1779 int argc,
1780 sqlite3_value **argv
1781){
1782 JsonString *pStr;
1783 const char *z;
1784 u32 n;
drhdf3a9072016-02-11 15:37:18 +00001785 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001786 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1787 if( pStr ){
1788 if( pStr->zBuf==0 ){
1789 jsonInit(pStr, ctx);
1790 jsonAppendChar(pStr, '{');
1791 }else{
1792 jsonAppendChar(pStr, ',');
1793 pStr->pCtx = ctx;
1794 }
1795 z = (const char*)sqlite3_value_text(argv[0]);
1796 n = (u32)sqlite3_value_bytes(argv[0]);
1797 jsonAppendString(pStr, z, n);
1798 jsonAppendChar(pStr, ':');
1799 jsonAppendValue(pStr, argv[1]);
1800 }
1801}
1802static void jsonObjectFinal(sqlite3_context *ctx){
1803 JsonString *pStr;
1804 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1805 if( pStr ){
1806 jsonAppendChar(pStr, '}');
1807 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00001808 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001809 assert( pStr->bStatic );
drhff135ae2015-12-30 01:07:02 +00001810 }else{
1811 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
1812 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1813 pStr->bStatic = 1;
1814 }
1815 }else{
1816 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
1817 }
1818 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1819}
1820
1821
drhd2975922015-08-29 17:22:33 +00001822#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001823/****************************************************************************
1824** The json_each virtual table
1825****************************************************************************/
1826typedef struct JsonEachCursor JsonEachCursor;
1827struct JsonEachCursor {
1828 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001829 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001830 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001831 u32 i; /* Index in sParse.aNode[] of current row */
1832 u32 iEnd; /* EOF when i equals or exceeds this value */
1833 u8 eType; /* Type of top-level element */
1834 u8 bRecursive; /* True for json_tree(). False for json_each() */
1835 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001836 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001837 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001838};
1839
1840/* Constructor for the json_each virtual table */
1841static int jsonEachConnect(
1842 sqlite3 *db,
1843 void *pAux,
1844 int argc, const char *const*argv,
1845 sqlite3_vtab **ppVtab,
1846 char **pzErr
1847){
1848 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001849 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001850
1851/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001852#define JEACH_KEY 0
1853#define JEACH_VALUE 1
1854#define JEACH_TYPE 2
1855#define JEACH_ATOM 3
1856#define JEACH_ID 4
1857#define JEACH_PARENT 5
1858#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001859#define JEACH_PATH 7
1860#define JEACH_JSON 8
1861#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001862
drh6fd5c1e2015-08-21 20:37:12 +00001863 UNUSED_PARAM(pzErr);
1864 UNUSED_PARAM(argv);
1865 UNUSED_PARAM(argc);
1866 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001867 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001868 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1869 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001870 if( rc==SQLITE_OK ){
1871 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1872 if( pNew==0 ) return SQLITE_NOMEM;
1873 memset(pNew, 0, sizeof(*pNew));
1874 }
1875 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001876}
1877
1878/* destructor for json_each virtual table */
1879static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1880 sqlite3_free(pVtab);
1881 return SQLITE_OK;
1882}
1883
drh505ad2c2015-08-21 17:33:11 +00001884/* constructor for a JsonEachCursor object for json_each(). */
1885static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001886 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001887
1888 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001889 pCur = sqlite3_malloc( sizeof(*pCur) );
1890 if( pCur==0 ) return SQLITE_NOMEM;
1891 memset(pCur, 0, sizeof(*pCur));
1892 *ppCursor = &pCur->base;
1893 return SQLITE_OK;
1894}
1895
drh505ad2c2015-08-21 17:33:11 +00001896/* constructor for a JsonEachCursor object for json_tree(). */
1897static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1898 int rc = jsonEachOpenEach(p, ppCursor);
1899 if( rc==SQLITE_OK ){
1900 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1901 pCur->bRecursive = 1;
1902 }
1903 return rc;
1904}
1905
drhcb6c6c62015-08-19 22:47:17 +00001906/* Reset a JsonEachCursor back to its original state. Free any memory
1907** held. */
1908static void jsonEachCursorReset(JsonEachCursor *p){
1909 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001910 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001911 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001912 p->iRowid = 0;
1913 p->i = 0;
1914 p->iEnd = 0;
1915 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001916 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001917 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001918}
1919
1920/* Destructor for a jsonEachCursor object */
1921static int jsonEachClose(sqlite3_vtab_cursor *cur){
1922 JsonEachCursor *p = (JsonEachCursor*)cur;
1923 jsonEachCursorReset(p);
1924 sqlite3_free(cur);
1925 return SQLITE_OK;
1926}
1927
1928/* Return TRUE if the jsonEachCursor object has been advanced off the end
1929** of the JSON object */
1930static int jsonEachEof(sqlite3_vtab_cursor *cur){
1931 JsonEachCursor *p = (JsonEachCursor*)cur;
1932 return p->i >= p->iEnd;
1933}
1934
drh505ad2c2015-08-21 17:33:11 +00001935/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001936static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001937 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001938 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001939 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1940 p->i++;
drh4af352d2015-08-21 20:02:48 +00001941 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001942 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001943 u32 iUp = p->sParse.aUp[p->i];
1944 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001945 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001946 if( pUp->eType==JSON_ARRAY ){
1947 if( iUp==p->i-1 ){
1948 pUp->u.iKey = 0;
1949 }else{
1950 pUp->u.iKey++;
1951 }
drh4af352d2015-08-21 20:02:48 +00001952 }
1953 }
drh505ad2c2015-08-21 17:33:11 +00001954 }else{
drh4af352d2015-08-21 20:02:48 +00001955 switch( p->eType ){
1956 case JSON_ARRAY: {
1957 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1958 p->iRowid++;
1959 break;
1960 }
1961 case JSON_OBJECT: {
1962 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1963 p->iRowid++;
1964 break;
1965 }
1966 default: {
1967 p->i = p->iEnd;
1968 break;
1969 }
drh505ad2c2015-08-21 17:33:11 +00001970 }
1971 }
1972 return SQLITE_OK;
1973}
1974
drh4af352d2015-08-21 20:02:48 +00001975/* Append the name of the path for element i to pStr
1976*/
1977static void jsonEachComputePath(
1978 JsonEachCursor *p, /* The cursor */
1979 JsonString *pStr, /* Write the path here */
1980 u32 i /* Path to this element */
1981){
1982 JsonNode *pNode, *pUp;
1983 u32 iUp;
1984 if( i==0 ){
1985 jsonAppendChar(pStr, '$');
1986 return;
drhcb6c6c62015-08-19 22:47:17 +00001987 }
drh4af352d2015-08-21 20:02:48 +00001988 iUp = p->sParse.aUp[i];
1989 jsonEachComputePath(p, pStr, iUp);
1990 pNode = &p->sParse.aNode[i];
1991 pUp = &p->sParse.aNode[iUp];
1992 if( pUp->eType==JSON_ARRAY ){
1993 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1994 }else{
1995 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001996 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001997 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001998 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001999 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2000 }
drhcb6c6c62015-08-19 22:47:17 +00002001}
2002
2003/* Return the value of a column */
2004static int jsonEachColumn(
2005 sqlite3_vtab_cursor *cur, /* The cursor */
2006 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2007 int i /* Which column to return */
2008){
2009 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002010 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002011 switch( i ){
2012 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002013 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002014 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002015 jsonReturn(pThis, ctx, 0);
2016 }else if( p->eType==JSON_ARRAY ){
2017 u32 iKey;
2018 if( p->bRecursive ){
2019 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002020 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002021 }else{
2022 iKey = p->iRowid;
2023 }
drh6fd5c1e2015-08-21 20:37:12 +00002024 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002025 }
2026 break;
2027 }
2028 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002029 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002030 jsonReturn(pThis, ctx, 0);
2031 break;
2032 }
2033 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002034 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002035 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2036 break;
2037 }
2038 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002039 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002040 if( pThis->eType>=JSON_ARRAY ) break;
2041 jsonReturn(pThis, ctx, 0);
2042 break;
2043 }
2044 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002045 sqlite3_result_int64(ctx,
2046 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002047 break;
2048 }
2049 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002050 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002051 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002052 }
2053 break;
2054 }
drh4af352d2015-08-21 20:02:48 +00002055 case JEACH_FULLKEY: {
2056 JsonString x;
2057 jsonInit(&x, ctx);
2058 if( p->bRecursive ){
2059 jsonEachComputePath(p, &x, p->i);
2060 }else{
drh383de692015-09-10 17:20:57 +00002061 if( p->zRoot ){
2062 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002063 }else{
2064 jsonAppendChar(&x, '$');
2065 }
2066 if( p->eType==JSON_ARRAY ){
2067 jsonPrintf(30, &x, "[%d]", p->iRowid);
2068 }else{
2069 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2070 }
2071 }
2072 jsonResult(&x);
2073 break;
2074 }
drhcb6c6c62015-08-19 22:47:17 +00002075 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002076 if( p->bRecursive ){
2077 JsonString x;
2078 jsonInit(&x, ctx);
2079 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2080 jsonResult(&x);
2081 break;
drh4af352d2015-08-21 20:02:48 +00002082 }
drh383de692015-09-10 17:20:57 +00002083 /* For json_each() path and root are the same so fall through
2084 ** into the root case */
2085 }
drh6850a632016-11-07 18:18:08 +00002086 default: {
drh383de692015-09-10 17:20:57 +00002087 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002088 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002089 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002090 break;
2091 }
drh3d1d2a92015-09-22 01:15:49 +00002092 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002093 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002094 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2095 break;
2096 }
2097 }
2098 return SQLITE_OK;
2099}
2100
2101/* Return the current rowid value */
2102static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2103 JsonEachCursor *p = (JsonEachCursor*)cur;
2104 *pRowid = p->iRowid;
2105 return SQLITE_OK;
2106}
2107
2108/* The query strategy is to look for an equality constraint on the json
2109** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002110** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002111** and 0 otherwise.
2112*/
2113static int jsonEachBestIndex(
2114 sqlite3_vtab *tab,
2115 sqlite3_index_info *pIdxInfo
2116){
2117 int i;
2118 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00002119 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00002120 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002121
2122 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00002123 pConstraint = pIdxInfo->aConstraint;
2124 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2125 if( pConstraint->usable==0 ) continue;
2126 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2127 switch( pConstraint->iColumn ){
2128 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00002129 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00002130 default: /* no-op */ break;
2131 }
2132 }
2133 if( jsonIdx<0 ){
2134 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00002135 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00002136 }else{
drh505ad2c2015-08-21 17:33:11 +00002137 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00002138 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
2139 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00002140 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00002141 pIdxInfo->idxNum = 1;
2142 }else{
drh383de692015-09-10 17:20:57 +00002143 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
2144 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00002145 pIdxInfo->idxNum = 3;
2146 }
2147 }
2148 return SQLITE_OK;
2149}
2150
2151/* Start a search on a new JSON string */
2152static int jsonEachFilter(
2153 sqlite3_vtab_cursor *cur,
2154 int idxNum, const char *idxStr,
2155 int argc, sqlite3_value **argv
2156){
2157 JsonEachCursor *p = (JsonEachCursor*)cur;
2158 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002159 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002160 sqlite3_int64 n;
2161
drh6fd5c1e2015-08-21 20:37:12 +00002162 UNUSED_PARAM(idxStr);
2163 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002164 jsonEachCursorReset(p);
2165 if( idxNum==0 ) return SQLITE_OK;
2166 z = (const char*)sqlite3_value_text(argv[0]);
2167 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002168 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002169 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002170 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002171 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002172 if( jsonParse(&p->sParse, 0, p->zJson) ){
2173 int rc = SQLITE_NOMEM;
2174 if( p->sParse.oom==0 ){
2175 sqlite3_free(cur->pVtab->zErrMsg);
2176 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2177 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2178 }
drhcb6c6c62015-08-19 22:47:17 +00002179 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002180 return rc;
2181 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2182 jsonEachCursorReset(p);
2183 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002184 }else{
drh95677942015-09-24 01:06:37 +00002185 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002186 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002187 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002188 zRoot = (const char*)sqlite3_value_text(argv[1]);
2189 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002190 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002191 p->zRoot = sqlite3_malloc64( n+1 );
2192 if( p->zRoot==0 ) return SQLITE_NOMEM;
2193 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002194 if( zRoot[0]!='$' ){
2195 zErr = zRoot;
2196 }else{
2197 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2198 }
2199 if( zErr ){
drha7714022015-08-29 00:54:49 +00002200 sqlite3_free(cur->pVtab->zErrMsg);
2201 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002202 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002203 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2204 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002205 return SQLITE_OK;
2206 }
2207 }else{
2208 pNode = p->sParse.aNode;
2209 }
drh852944e2015-09-10 03:29:11 +00002210 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002211 p->eType = pNode->eType;
2212 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002213 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002214 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002215 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002216 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002217 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2218 p->i--;
2219 }
2220 }else{
2221 p->i++;
2222 }
drhcb6c6c62015-08-19 22:47:17 +00002223 }else{
2224 p->iEnd = p->i+1;
2225 }
2226 }
drha8f39a92015-09-21 22:53:16 +00002227 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002228}
2229
2230/* The methods of the json_each virtual table */
2231static sqlite3_module jsonEachModule = {
2232 0, /* iVersion */
2233 0, /* xCreate */
2234 jsonEachConnect, /* xConnect */
2235 jsonEachBestIndex, /* xBestIndex */
2236 jsonEachDisconnect, /* xDisconnect */
2237 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002238 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002239 jsonEachClose, /* xClose - close a cursor */
2240 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002241 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002242 jsonEachEof, /* xEof - check for end of scan */
2243 jsonEachColumn, /* xColumn - read data */
2244 jsonEachRowid, /* xRowid - read data */
2245 0, /* xUpdate */
2246 0, /* xBegin */
2247 0, /* xSync */
2248 0, /* xCommit */
2249 0, /* xRollback */
2250 0, /* xFindMethod */
2251 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002252 0, /* xSavepoint */
2253 0, /* xRelease */
2254 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00002255};
2256
drh505ad2c2015-08-21 17:33:11 +00002257/* The methods of the json_tree virtual table. */
2258static sqlite3_module jsonTreeModule = {
2259 0, /* iVersion */
2260 0, /* xCreate */
2261 jsonEachConnect, /* xConnect */
2262 jsonEachBestIndex, /* xBestIndex */
2263 jsonEachDisconnect, /* xDisconnect */
2264 0, /* xDestroy */
2265 jsonEachOpenTree, /* xOpen - open a cursor */
2266 jsonEachClose, /* xClose - close a cursor */
2267 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002268 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002269 jsonEachEof, /* xEof - check for end of scan */
2270 jsonEachColumn, /* xColumn - read data */
2271 jsonEachRowid, /* xRowid - read data */
2272 0, /* xUpdate */
2273 0, /* xBegin */
2274 0, /* xSync */
2275 0, /* xCommit */
2276 0, /* xRollback */
2277 0, /* xFindMethod */
2278 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002279 0, /* xSavepoint */
2280 0, /* xRelease */
2281 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00002282};
drhd2975922015-08-29 17:22:33 +00002283#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002284
2285/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002286** The following routines are the only publically visible identifiers in this
2287** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002288** functions and the virtual table implemented by this file.
2289****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002290
drh2f20e132015-09-26 17:44:59 +00002291int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002292 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002293 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002294 static const struct {
2295 const char *zName;
2296 int nArg;
drh52216ad2015-08-18 02:28:03 +00002297 int flag;
drh5fa5c102015-08-12 16:49:40 +00002298 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2299 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002300 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002301 { "json_array", -1, 0, jsonArrayFunc },
2302 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2303 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002304 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002305 { "json_insert", -1, 0, jsonSetFunc },
2306 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002307 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002308 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002309 { "json_remove", -1, 0, jsonRemoveFunc },
2310 { "json_replace", -1, 0, jsonReplaceFunc },
2311 { "json_set", -1, 1, jsonSetFunc },
2312 { "json_type", 1, 0, jsonTypeFunc },
2313 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002314 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002315
drh301eecc2015-08-17 20:14:19 +00002316#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002317 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002318 { "json_parse", 1, 0, jsonParseFunc },
2319 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002320#endif
drh5fa5c102015-08-12 16:49:40 +00002321 };
drhff135ae2015-12-30 01:07:02 +00002322 static const struct {
2323 const char *zName;
2324 int nArg;
2325 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2326 void (*xFinal)(sqlite3_context*);
2327 } aAgg[] = {
2328 { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
2329 { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
2330 };
drhd2975922015-08-29 17:22:33 +00002331#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002332 static const struct {
2333 const char *zName;
2334 sqlite3_module *pModule;
2335 } aMod[] = {
2336 { "json_each", &jsonEachModule },
2337 { "json_tree", &jsonTreeModule },
2338 };
drhd2975922015-08-29 17:22:33 +00002339#endif
drh5fa5c102015-08-12 16:49:40 +00002340 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2341 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002342 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2343 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002344 aFunc[i].xFunc, 0, 0);
2345 }
drhff135ae2015-12-30 01:07:02 +00002346 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
2347 rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
2348 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
2349 0, aAgg[i].xStep, aAgg[i].xFinal);
2350 }
drhd2975922015-08-29 17:22:33 +00002351#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002352 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2353 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002354 }
drhd2975922015-08-29 17:22:33 +00002355#endif
drh5fa5c102015-08-12 16:49:40 +00002356 return rc;
2357}
drh2f20e132015-09-26 17:44:59 +00002358
2359
dan8d32e802015-10-14 18:45:42 +00002360#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002361#ifdef _WIN32
2362__declspec(dllexport)
2363#endif
2364int sqlite3_json_init(
2365 sqlite3 *db,
2366 char **pzErrMsg,
2367 const sqlite3_api_routines *pApi
2368){
2369 SQLITE_EXTENSION_INIT2(pApi);
2370 (void)pzErrMsg; /* Unused parameter */
2371 return sqlite3Json1Init(db);
2372}
dan8d32e802015-10-14 18:45:42 +00002373#endif
drh50065652015-10-08 19:29:18 +00002374#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */