blob: f4f3507eb2a6786b3cddc6afe5217a09f008f56b [file] [log] [blame]
drh5fa5c102015-08-12 16:49:40 +00001/*
2** 2015-08-12
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This SQLite extension implements JSON functions. The interface is
14** modeled after MySQL JSON functions:
15**
16** https://dev.mysql.com/doc/refman/5.7/en/json.html
17**
drh5634cc02015-08-17 11:28:03 +000018** For the time being, all JSON is stored as pure text. (We might add
19** a JSONB type in the future which stores a binary encoding of JSON in
drhcb6c6c62015-08-19 22:47:17 +000020** a BLOB, but there is no support for JSONB in the current implementation.
21** This implementation parses JSON text at 250 MB/s, so it is hard to see
22** how JSONB might improve on that.)
drh5fa5c102015-08-12 16:49:40 +000023*/
drh50065652015-10-08 19:29:18 +000024#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
drh666d34c2017-01-25 13:54:27 +000025#if !defined(SQLITEINT_H)
drh5fa5c102015-08-12 16:49:40 +000026#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000027#endif
drh5fa5c102015-08-12 16:49:40 +000028SQLITE_EXTENSION_INIT1
29#include <assert.h>
30#include <string.h>
drh987eb1f2015-08-17 15:17:37 +000031#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000032#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000033
drhdf3a9072016-02-11 15:37:18 +000034/* Mark a function parameter as unused, to suppress nuisance compiler
35** warnings. */
36#ifndef UNUSED_PARAM
37# define UNUSED_PARAM(X) (void)(X)
38#endif
drh6fd5c1e2015-08-21 20:37:12 +000039
drh8deb4b82015-10-09 18:21:43 +000040#ifndef LARGEST_INT64
41# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
42# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
43#endif
44
dan2e8f5512015-09-17 17:21:09 +000045/*
46** Versions of isspace(), isalnum() and isdigit() to which it is safe
47** to pass signed char values.
48*/
drh49472652015-10-16 15:35:39 +000049#ifdef sqlite3Isdigit
50 /* Use the SQLite core versions if this routine is part of the
51 ** SQLite amalgamation */
drhad875e72016-11-07 13:37:28 +000052# define safe_isdigit(x) sqlite3Isdigit(x)
53# define safe_isalnum(x) sqlite3Isalnum(x)
54# define safe_isxdigit(x) sqlite3Isxdigit(x)
drh49472652015-10-16 15:35:39 +000055#else
56 /* Use the standard library for separate compilation */
57#include <ctype.h> /* amalgamator: keep */
drhad875e72016-11-07 13:37:28 +000058# define safe_isdigit(x) isdigit((unsigned char)(x))
59# define safe_isalnum(x) isalnum((unsigned char)(x))
60# define safe_isxdigit(x) isxdigit((unsigned char)(x))
drh49472652015-10-16 15:35:39 +000061#endif
dan2e8f5512015-09-17 17:21:09 +000062
drh95677942015-09-24 01:06:37 +000063/*
64** Growing our own isspace() routine this way is twice as fast as
65** the library isspace() function, resulting in a 7% overall performance
66** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
67*/
68static const char jsonIsSpace[] = {
drhb9e8f592015-10-16 15:16:06 +000069 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
drh95677942015-09-24 01:06:37 +000070 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
74 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
75 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
76 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85};
86#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
87
drh9a4718f2015-10-10 14:00:37 +000088#ifndef SQLITE_AMALGAMATION
89 /* Unsigned integer types. These are already defined in the sqliteInt.h,
90 ** but the definitions need to be repeated for separate compilation. */
91 typedef sqlite3_uint64 u64;
92 typedef unsigned int u32;
drhff6d50e2017-04-11 18:55:05 +000093 typedef unsigned short int u16;
drh9a4718f2015-10-10 14:00:37 +000094 typedef unsigned char u8;
95#endif
drh5fa5c102015-08-12 16:49:40 +000096
drh52216ad2015-08-18 02:28:03 +000097/* Objects */
drh505ad2c2015-08-21 17:33:11 +000098typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000099typedef struct JsonNode JsonNode;
100typedef struct JsonParse JsonParse;
101
drh5634cc02015-08-17 11:28:03 +0000102/* An instance of this object represents a JSON string
103** under construction. Really, this is a generic string accumulator
104** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +0000105*/
drh505ad2c2015-08-21 17:33:11 +0000106struct JsonString {
drh5fa5c102015-08-12 16:49:40 +0000107 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +0000108 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +0000109 u64 nAlloc; /* Bytes of storage available in zBuf[] */
110 u64 nUsed; /* Bytes of zBuf[] currently used */
111 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +0000112 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +0000113 char zSpace[100]; /* Initial static space */
114};
115
drhe9c37f32015-08-15 21:25:36 +0000116/* JSON type values
drhbd0621b2015-08-13 13:54:59 +0000117*/
drhe9c37f32015-08-15 21:25:36 +0000118#define JSON_NULL 0
119#define JSON_TRUE 1
120#define JSON_FALSE 2
121#define JSON_INT 3
122#define JSON_REAL 4
123#define JSON_STRING 5
124#define JSON_ARRAY 6
125#define JSON_OBJECT 7
126
drhf5ddb9c2015-09-11 00:06:41 +0000127/* The "subtype" set for JSON values */
128#define JSON_SUBTYPE 74 /* Ascii for "J" */
129
drh987eb1f2015-08-17 15:17:37 +0000130/*
131** Names of the various JSON types:
132*/
133static const char * const jsonType[] = {
134 "null", "true", "false", "integer", "real", "text", "array", "object"
135};
136
drh301eecc2015-08-17 20:14:19 +0000137/* Bit values for the JsonNode.jnFlag field
138*/
139#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
140#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
141#define JNODE_REMOVE 0x04 /* Do not output */
drh633647a2017-03-22 21:24:31 +0000142#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
143#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
144#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
145#define JNODE_LABEL 0x40 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000146
drh987eb1f2015-08-17 15:17:37 +0000147
drhe9c37f32015-08-15 21:25:36 +0000148/* A single node of parsed JSON
149*/
drhe9c37f32015-08-15 21:25:36 +0000150struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000151 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000152 u8 jnFlags; /* JNODE flags */
drhe9c37f32015-08-15 21:25:36 +0000153 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000154 union {
drh0042a972015-08-18 12:59:58 +0000155 const char *zJContent; /* Content for INT, REAL, and STRING */
156 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000157 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh633647a2017-03-22 21:24:31 +0000158 u32 iReplace; /* Replacement content for JNODE_REPLACE */
159 JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
drh52216ad2015-08-18 02:28:03 +0000160 } u;
drhe9c37f32015-08-15 21:25:36 +0000161};
162
163/* A completely parsed JSON string
164*/
drhe9c37f32015-08-15 21:25:36 +0000165struct JsonParse {
166 u32 nNode; /* Number of slots of aNode[] used */
167 u32 nAlloc; /* Number of slots of aNode[] allocated */
168 JsonNode *aNode; /* Array of nodes containing the parse */
169 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000170 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000171 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000172 u8 nErr; /* Number of errors seen */
drhff6d50e2017-04-11 18:55:05 +0000173 u16 iDepth; /* Nesting depth */
drh3fb153c2017-05-11 16:49:59 +0000174 int nJson; /* Length of the zJson string in bytes */
drhe9c37f32015-08-15 21:25:36 +0000175};
176
drhff6d50e2017-04-11 18:55:05 +0000177/*
178** Maximum nesting depth of JSON for this implementation.
179**
180** This limit is needed to avoid a stack overflow in the recursive
181** descent parser. A depth of 2000 is far deeper than any sane JSON
182** should go.
183*/
184#define JSON_MAX_DEPTH 2000
185
drh505ad2c2015-08-21 17:33:11 +0000186/**************************************************************************
187** Utility routines for dealing with JsonString objects
188**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000189
drh505ad2c2015-08-21 17:33:11 +0000190/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000191*/
drh505ad2c2015-08-21 17:33:11 +0000192static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000193 p->zBuf = p->zSpace;
194 p->nAlloc = sizeof(p->zSpace);
195 p->nUsed = 0;
196 p->bStatic = 1;
197}
198
drh505ad2c2015-08-21 17:33:11 +0000199/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000200*/
drh505ad2c2015-08-21 17:33:11 +0000201static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000202 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000203 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000204 jsonZero(p);
205}
206
207
drh505ad2c2015-08-21 17:33:11 +0000208/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000209** initial state.
210*/
drh505ad2c2015-08-21 17:33:11 +0000211static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000212 if( !p->bStatic ) sqlite3_free(p->zBuf);
213 jsonZero(p);
214}
215
216
217/* Report an out-of-memory (OOM) condition
218*/
drh505ad2c2015-08-21 17:33:11 +0000219static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000220 p->bErr = 1;
221 sqlite3_result_error_nomem(p->pCtx);
222 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000223}
224
225/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
226** Return zero on success. Return non-zero on an OOM error
227*/
drh505ad2c2015-08-21 17:33:11 +0000228static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000229 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000230 char *zNew;
231 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000232 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000233 zNew = sqlite3_malloc64(nTotal);
234 if( zNew==0 ){
235 jsonOom(p);
236 return SQLITE_NOMEM;
237 }
drh6fd5c1e2015-08-21 20:37:12 +0000238 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000239 p->zBuf = zNew;
240 p->bStatic = 0;
241 }else{
242 zNew = sqlite3_realloc64(p->zBuf, nTotal);
243 if( zNew==0 ){
244 jsonOom(p);
245 return SQLITE_NOMEM;
246 }
247 p->zBuf = zNew;
248 }
249 p->nAlloc = nTotal;
250 return SQLITE_OK;
251}
252
drh505ad2c2015-08-21 17:33:11 +0000253/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000254*/
drh505ad2c2015-08-21 17:33:11 +0000255static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000256 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
257 memcpy(p->zBuf+p->nUsed, zIn, N);
258 p->nUsed += N;
259}
260
drh4af352d2015-08-21 20:02:48 +0000261/* Append formatted text (not to exceed N bytes) to the JsonString.
262*/
263static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
264 va_list ap;
265 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
266 va_start(ap, zFormat);
267 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
268 va_end(ap);
269 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
270}
271
drh5634cc02015-08-17 11:28:03 +0000272/* Append a single character
273*/
drh505ad2c2015-08-21 17:33:11 +0000274static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000275 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
276 p->zBuf[p->nUsed++] = c;
277}
278
drh301eecc2015-08-17 20:14:19 +0000279/* Append a comma separator to the output buffer, if the previous
280** character is not '[' or '{'.
281*/
drh505ad2c2015-08-21 17:33:11 +0000282static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000283 char c;
284 if( p->nUsed==0 ) return;
285 c = p->zBuf[p->nUsed-1];
286 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
287}
288
drh505ad2c2015-08-21 17:33:11 +0000289/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000290** under construction. Enclose the string in "..." and escape
291** any double-quotes or backslash characters contained within the
292** string.
293*/
drh505ad2c2015-08-21 17:33:11 +0000294static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000295 u32 i;
296 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
297 p->zBuf[p->nUsed++] = '"';
298 for(i=0; i<N; i++){
drh3b7f9a62016-02-04 10:28:57 +0000299 unsigned char c = ((unsigned const char*)zIn)[i];
drh5fa5c102015-08-12 16:49:40 +0000300 if( c=='"' || c=='\\' ){
drh3b7f9a62016-02-04 10:28:57 +0000301 json_simple_escape:
drh4977ccf2015-09-19 11:57:26 +0000302 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000303 p->zBuf[p->nUsed++] = '\\';
drh3b7f9a62016-02-04 10:28:57 +0000304 }else if( c<=0x1f ){
305 static const char aSpecial[] = {
306 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
307 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
308 };
309 assert( sizeof(aSpecial)==32 );
310 assert( aSpecial['\b']=='b' );
311 assert( aSpecial['\f']=='f' );
312 assert( aSpecial['\n']=='n' );
313 assert( aSpecial['\r']=='r' );
314 assert( aSpecial['\t']=='t' );
315 if( aSpecial[c] ){
316 c = aSpecial[c];
317 goto json_simple_escape;
318 }
319 if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
320 p->zBuf[p->nUsed++] = '\\';
321 p->zBuf[p->nUsed++] = 'u';
322 p->zBuf[p->nUsed++] = '0';
323 p->zBuf[p->nUsed++] = '0';
324 p->zBuf[p->nUsed++] = '0' + (c>>4);
325 c = "0123456789abcdef"[c&0xf];
drh5fa5c102015-08-12 16:49:40 +0000326 }
327 p->zBuf[p->nUsed++] = c;
328 }
329 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000330 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000331}
332
drhd0960592015-08-17 21:22:32 +0000333/*
334** Append a function parameter value to the JSON string under
335** construction.
336*/
337static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000338 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000339 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000340){
341 switch( sqlite3_value_type(pValue) ){
342 case SQLITE_NULL: {
343 jsonAppendRaw(p, "null", 4);
344 break;
345 }
346 case SQLITE_INTEGER:
347 case SQLITE_FLOAT: {
348 const char *z = (const char*)sqlite3_value_text(pValue);
349 u32 n = (u32)sqlite3_value_bytes(pValue);
350 jsonAppendRaw(p, z, n);
351 break;
352 }
353 case SQLITE_TEXT: {
354 const char *z = (const char*)sqlite3_value_text(pValue);
355 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000356 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000357 jsonAppendRaw(p, z, n);
358 }else{
359 jsonAppendString(p, z, n);
360 }
drhd0960592015-08-17 21:22:32 +0000361 break;
362 }
363 default: {
364 if( p->bErr==0 ){
365 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
drh4a642b62016-02-05 01:55:27 +0000366 p->bErr = 2;
drhd0960592015-08-17 21:22:32 +0000367 jsonReset(p);
368 }
369 break;
370 }
371 }
372}
373
374
drhbd0621b2015-08-13 13:54:59 +0000375/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000376*/
drh505ad2c2015-08-21 17:33:11 +0000377static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000378 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000379 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
380 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
381 SQLITE_UTF8);
382 jsonZero(p);
383 }
384 assert( p->bStatic );
385}
386
drh505ad2c2015-08-21 17:33:11 +0000387/**************************************************************************
388** Utility routines for dealing with JsonNode and JsonParse objects
389**************************************************************************/
390
391/*
392** Return the number of consecutive JsonNode slots need to represent
393** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
394** OBJECT types, the number might be larger.
395**
396** Appended elements are not counted. The value returned is the number
397** by which the JsonNode counter should increment in order to go to the
398** next peer value.
399*/
400static u32 jsonNodeSize(JsonNode *pNode){
401 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
402}
403
404/*
405** Reclaim all memory allocated by a JsonParse object. But do not
406** delete the JsonParse object itself.
407*/
408static void jsonParseReset(JsonParse *pParse){
409 sqlite3_free(pParse->aNode);
410 pParse->aNode = 0;
411 pParse->nNode = 0;
412 pParse->nAlloc = 0;
413 sqlite3_free(pParse->aUp);
414 pParse->aUp = 0;
415}
416
drh5634cc02015-08-17 11:28:03 +0000417/*
drh3fb153c2017-05-11 16:49:59 +0000418** Free a JsonParse object that was obtained from sqlite3_malloc().
419*/
420static void jsonParseFree(JsonParse *pParse){
421 jsonParseReset(pParse);
422 sqlite3_free(pParse);
423}
424
425/*
drh5634cc02015-08-17 11:28:03 +0000426** Convert the JsonNode pNode into a pure JSON string and
427** append to pOut. Subsubstructure is also included. Return
428** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000429*/
drh52216ad2015-08-18 02:28:03 +0000430static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000431 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000432 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000433 sqlite3_value **aReplace /* Replacement values */
434){
drh633647a2017-03-22 21:24:31 +0000435 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
436 if( pNode->jnFlags & JNODE_REPLACE ){
437 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
438 return;
439 }
440 pNode = pNode->u.pPatch;
441 }
drh5634cc02015-08-17 11:28:03 +0000442 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000443 default: {
444 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000445 jsonAppendRaw(pOut, "null", 4);
446 break;
447 }
448 case JSON_TRUE: {
449 jsonAppendRaw(pOut, "true", 4);
450 break;
451 }
452 case JSON_FALSE: {
453 jsonAppendRaw(pOut, "false", 5);
454 break;
455 }
456 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000457 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000458 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000459 break;
460 }
461 /* Fall through into the next case */
462 }
463 case JSON_REAL:
464 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000465 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000466 break;
467 }
468 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000469 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000470 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000471 for(;;){
472 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000473 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000474 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000475 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000476 }
drh505ad2c2015-08-21 17:33:11 +0000477 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000478 }
drh52216ad2015-08-18 02:28:03 +0000479 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
480 pNode = &pNode[pNode->u.iAppend];
481 j = 1;
drh5634cc02015-08-17 11:28:03 +0000482 }
483 jsonAppendChar(pOut, ']');
484 break;
485 }
486 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000487 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000488 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000489 for(;;){
490 while( j<=pNode->n ){
491 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
492 jsonAppendSeparator(pOut);
493 jsonRenderNode(&pNode[j], pOut, aReplace);
494 jsonAppendChar(pOut, ':');
drh633647a2017-03-22 21:24:31 +0000495 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000496 }
drh505ad2c2015-08-21 17:33:11 +0000497 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000498 }
drh52216ad2015-08-18 02:28:03 +0000499 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
500 pNode = &pNode[pNode->u.iAppend];
501 j = 1;
drh5634cc02015-08-17 11:28:03 +0000502 }
503 jsonAppendChar(pOut, '}');
504 break;
505 }
drhbd0621b2015-08-13 13:54:59 +0000506 }
drh5634cc02015-08-17 11:28:03 +0000507}
508
509/*
drhf2df7e72015-08-28 20:07:40 +0000510** Return a JsonNode and all its descendents as a JSON string.
511*/
512static void jsonReturnJson(
513 JsonNode *pNode, /* Node to return */
514 sqlite3_context *pCtx, /* Return value for this function */
515 sqlite3_value **aReplace /* Array of replacement values */
516){
517 JsonString s;
518 jsonInit(&s, pCtx);
519 jsonRenderNode(pNode, &s, aReplace);
520 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000521 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000522}
523
524/*
drh5634cc02015-08-17 11:28:03 +0000525** Make the JsonNode the return value of the function.
526*/
drhd0960592015-08-17 21:22:32 +0000527static void jsonReturn(
528 JsonNode *pNode, /* Node to return */
529 sqlite3_context *pCtx, /* Return value for this function */
530 sqlite3_value **aReplace /* Array of replacement values */
531){
drh5634cc02015-08-17 11:28:03 +0000532 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000533 default: {
534 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000535 sqlite3_result_null(pCtx);
536 break;
537 }
538 case JSON_TRUE: {
539 sqlite3_result_int(pCtx, 1);
540 break;
541 }
542 case JSON_FALSE: {
543 sqlite3_result_int(pCtx, 0);
544 break;
545 }
drh987eb1f2015-08-17 15:17:37 +0000546 case JSON_INT: {
547 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000548 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000549 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000550 while( z[0]>='0' && z[0]<='9' ){
551 unsigned v = *(z++) - '0';
552 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000553 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000554 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
555 if( v==9 ) goto int_as_real;
556 if( v==8 ){
557 if( pNode->u.zJContent[0]=='-' ){
558 sqlite3_result_int64(pCtx, SMALLEST_INT64);
559 goto int_done;
560 }else{
561 goto int_as_real;
562 }
563 }
564 }
565 i = i*10 + v;
566 }
drh52216ad2015-08-18 02:28:03 +0000567 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000568 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000569 int_done:
570 break;
571 int_as_real: /* fall through to real */;
572 }
573 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000574 double r;
575#ifdef SQLITE_AMALGAMATION
576 const char *z = pNode->u.zJContent;
577 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
578#else
579 r = strtod(pNode->u.zJContent, 0);
580#endif
drh8deb4b82015-10-09 18:21:43 +0000581 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000582 break;
583 }
drh5634cc02015-08-17 11:28:03 +0000584 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000585#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
586 ** json_insert() and json_replace() and those routines do not
587 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000588 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000589 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
590 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000591 }else
592#endif
593 assert( (pNode->jnFlags & JNODE_RAW)==0 );
594 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000595 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000596 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000597 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000598 }else{
599 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000600 u32 i;
601 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000602 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000603 char *zOut;
604 u32 j;
605 zOut = sqlite3_malloc( n+1 );
606 if( zOut==0 ){
607 sqlite3_result_error_nomem(pCtx);
608 break;
609 }
610 for(i=1, j=0; i<n-1; i++){
611 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000612 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000613 zOut[j++] = c;
614 }else{
615 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000616 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000617 u32 v = 0, k;
drh27b2d1b2016-11-07 15:15:42 +0000618 for(k=0; k<4; i++, k++){
619 assert( i<n-2 );
drh8784eca2015-08-23 02:42:30 +0000620 c = z[i+1];
drh27b2d1b2016-11-07 15:15:42 +0000621 assert( safe_isxdigit(c) );
622 if( c<='9' ) v = v*16 + c - '0';
623 else if( c<='F' ) v = v*16 + c - 'A' + 10;
624 else v = v*16 + c - 'a' + 10;
drh987eb1f2015-08-17 15:17:37 +0000625 }
drh80d87402015-08-24 12:42:41 +0000626 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000627 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000628 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000629 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000630 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000631 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000632 }else{
mistachkin16a93122015-09-11 18:05:01 +0000633 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000634 zOut[j++] = 0x80 | ((v>>6)&0x3f);
635 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000636 }
637 }else{
638 if( c=='b' ){
639 c = '\b';
640 }else if( c=='f' ){
641 c = '\f';
642 }else if( c=='n' ){
643 c = '\n';
644 }else if( c=='r' ){
645 c = '\r';
646 }else if( c=='t' ){
647 c = '\t';
648 }
649 zOut[j++] = c;
650 }
651 }
652 }
653 zOut[j] = 0;
654 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000655 }
656 break;
657 }
658 case JSON_ARRAY:
659 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000660 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000661 break;
662 }
663 }
drhbd0621b2015-08-13 13:54:59 +0000664}
665
drh95677942015-09-24 01:06:37 +0000666/* Forward reference */
667static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
668
669/*
670** A macro to hint to the compiler that a function should not be
671** inlined.
672*/
673#if defined(__GNUC__)
674# define JSON_NOINLINE __attribute__((noinline))
675#elif defined(_MSC_VER) && _MSC_VER>=1310
676# define JSON_NOINLINE __declspec(noinline)
677#else
678# define JSON_NOINLINE
679#endif
680
681
682static JSON_NOINLINE int jsonParseAddNodeExpand(
683 JsonParse *pParse, /* Append the node to this object */
684 u32 eType, /* Node type */
685 u32 n, /* Content size or sub-node count */
686 const char *zContent /* Content */
687){
688 u32 nNew;
689 JsonNode *pNew;
690 assert( pParse->nNode>=pParse->nAlloc );
691 if( pParse->oom ) return -1;
692 nNew = pParse->nAlloc*2 + 10;
693 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
694 if( pNew==0 ){
695 pParse->oom = 1;
696 return -1;
697 }
698 pParse->nAlloc = nNew;
699 pParse->aNode = pNew;
700 assert( pParse->nNode<pParse->nAlloc );
701 return jsonParseAddNode(pParse, eType, n, zContent);
702}
703
drh5fa5c102015-08-12 16:49:40 +0000704/*
drhe9c37f32015-08-15 21:25:36 +0000705** Create a new JsonNode instance based on the arguments and append that
706** instance to the JsonParse. Return the index in pParse->aNode[] of the
707** new node, or -1 if a memory allocation fails.
708*/
709static int jsonParseAddNode(
710 JsonParse *pParse, /* Append the node to this object */
711 u32 eType, /* Node type */
712 u32 n, /* Content size or sub-node count */
713 const char *zContent /* Content */
714){
715 JsonNode *p;
716 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000717 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000718 }
719 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000720 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000721 p->jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000722 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000723 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000724 return pParse->nNode++;
725}
726
727/*
drhad875e72016-11-07 13:37:28 +0000728** Return true if z[] begins with 4 (or more) hexadecimal digits
729*/
730static int jsonIs4Hex(const char *z){
731 int i;
732 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
733 return 1;
734}
735
736/*
drhe9c37f32015-08-15 21:25:36 +0000737** Parse a single JSON value which begins at pParse->zJson[i]. Return the
738** index of the first character past the end of the value parsed.
739**
740** Return negative for a syntax error. Special cases: return -2 if the
741** first non-whitespace character is '}' and return -3 if the first
742** non-whitespace character is ']'.
743*/
744static int jsonParseValue(JsonParse *pParse, u32 i){
745 char c;
746 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000747 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000748 int x;
drh852944e2015-09-10 03:29:11 +0000749 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000750 const char *z = pParse->zJson;
751 while( safe_isspace(z[i]) ){ i++; }
752 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000753 /* Parse object */
754 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000755 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000756 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000757 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000758 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000759 x = jsonParseValue(pParse, j);
760 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000761 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000762 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000763 return -1;
764 }
drhbe9474e2015-08-22 03:05:54 +0000765 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000766 pNode = &pParse->aNode[pParse->nNode-1];
767 if( pNode->eType!=JSON_STRING ) return -1;
768 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000769 j = x;
drh9fa866a2017-04-08 18:18:22 +0000770 while( safe_isspace(z[j]) ){ j++; }
771 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000772 j++;
773 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000774 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000775 if( x<0 ) return -1;
776 j = x;
drh9fa866a2017-04-08 18:18:22 +0000777 while( safe_isspace(z[j]) ){ j++; }
778 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000779 if( c==',' ) continue;
780 if( c!='}' ) return -1;
781 break;
782 }
drhbc8f0922015-08-22 19:39:04 +0000783 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000784 return j+1;
785 }else if( c=='[' ){
786 /* Parse array */
787 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000788 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000789 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000790 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000791 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000792 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000793 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000794 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000795 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000796 return -1;
797 }
798 j = x;
drh9fa866a2017-04-08 18:18:22 +0000799 while( safe_isspace(z[j]) ){ j++; }
800 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000801 if( c==',' ) continue;
802 if( c!=']' ) return -1;
803 break;
804 }
drhbc8f0922015-08-22 19:39:04 +0000805 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000806 return j+1;
807 }else if( c=='"' ){
808 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000809 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000810 j = i+1;
811 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000812 c = z[j];
drh86715382017-04-13 00:12:32 +0000813 if( (c & ~0x1f)==0 ){
814 /* Control characters are not allowed in strings */
815 return -1;
816 }
drhe9c37f32015-08-15 21:25:36 +0000817 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000818 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000819 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
820 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000821 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000822 jnFlags = JNODE_ESCAPE;
823 }else{
824 return -1;
825 }
drhe9c37f32015-08-15 21:25:36 +0000826 }else if( c=='"' ){
827 break;
828 }
829 j++;
830 }
drh9fa866a2017-04-08 18:18:22 +0000831 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000832 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000833 return j+1;
834 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000835 && strncmp(z+i,"null",4)==0
836 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000837 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
838 return i+4;
839 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000840 && strncmp(z+i,"true",4)==0
841 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000842 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
843 return i+4;
844 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000845 && strncmp(z+i,"false",5)==0
846 && !safe_isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000847 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
848 return i+5;
849 }else if( c=='-' || (c>='0' && c<='9') ){
850 /* Parse number */
851 u8 seenDP = 0;
852 u8 seenE = 0;
drh9fa866a2017-04-08 18:18:22 +0000853 assert( '-' < '0' );
854 if( c<='0' ){
855 j = c=='-' ? i+1 : i;
856 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
857 }
drhe9c37f32015-08-15 21:25:36 +0000858 j = i+1;
859 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000860 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000861 if( c>='0' && c<='9' ) continue;
862 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000863 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000864 if( seenDP ) return -1;
865 seenDP = 1;
866 continue;
867 }
868 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000869 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000870 if( seenE ) return -1;
871 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000872 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000873 if( c=='+' || c=='-' ){
874 j++;
drh9fa866a2017-04-08 18:18:22 +0000875 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000876 }
drhd1f00682015-08-29 16:02:37 +0000877 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000878 continue;
879 }
880 break;
881 }
drh9fa866a2017-04-08 18:18:22 +0000882 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000883 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000884 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000885 return j;
886 }else if( c=='}' ){
887 return -2; /* End of {...} */
888 }else if( c==']' ){
889 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000890 }else if( c==0 ){
891 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000892 }else{
893 return -1; /* Syntax error */
894 }
895}
896
897/*
898** Parse a complete JSON string. Return 0 on success or non-zero if there
899** are any errors. If an error occurs, free all memory associated with
900** pParse.
901**
902** pParse is uninitialized when this routine is called.
903*/
drhbc8f0922015-08-22 19:39:04 +0000904static int jsonParse(
905 JsonParse *pParse, /* Initialize and fill this JsonParse object */
906 sqlite3_context *pCtx, /* Report errors here */
907 const char *zJson /* Input JSON text to be parsed */
908){
drhe9c37f32015-08-15 21:25:36 +0000909 int i;
drhe9c37f32015-08-15 21:25:36 +0000910 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000911 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000912 pParse->zJson = zJson;
913 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000914 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000915 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000916 assert( pParse->iDepth==0 );
dan2e8f5512015-09-17 17:21:09 +0000917 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000918 if( zJson[i] ) i = -1;
919 }
drhd1f00682015-08-29 16:02:37 +0000920 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000921 if( pCtx!=0 ){
922 if( pParse->oom ){
923 sqlite3_result_error_nomem(pCtx);
924 }else{
925 sqlite3_result_error(pCtx, "malformed JSON", -1);
926 }
927 }
drh505ad2c2015-08-21 17:33:11 +0000928 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000929 return 1;
930 }
931 return 0;
932}
drh301eecc2015-08-17 20:14:19 +0000933
drh505ad2c2015-08-21 17:33:11 +0000934/* Mark node i of pParse as being a child of iParent. Call recursively
935** to fill in all the descendants of node i.
936*/
937static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
938 JsonNode *pNode = &pParse->aNode[i];
939 u32 j;
940 pParse->aUp[i] = iParent;
941 switch( pNode->eType ){
942 case JSON_ARRAY: {
943 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
944 jsonParseFillInParentage(pParse, i+j, i);
945 }
946 break;
947 }
948 case JSON_OBJECT: {
949 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
950 pParse->aUp[i+j] = i;
951 jsonParseFillInParentage(pParse, i+j+1, i);
952 }
953 break;
954 }
955 default: {
956 break;
957 }
958 }
959}
960
961/*
962** Compute the parentage of all nodes in a completed parse.
963*/
964static int jsonParseFindParents(JsonParse *pParse){
965 u32 *aUp;
966 assert( pParse->aUp==0 );
967 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000968 if( aUp==0 ){
969 pParse->oom = 1;
970 return SQLITE_NOMEM;
971 }
drh505ad2c2015-08-21 17:33:11 +0000972 jsonParseFillInParentage(pParse, 0, 0);
973 return SQLITE_OK;
974}
975
drh8cb0c832015-09-22 00:21:03 +0000976/*
drh3fb153c2017-05-11 16:49:59 +0000977** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
978*/
979#define JSON_CACHE_ID (-429938)
980
981/*
982** Obtain a complete parse of the JSON found in the first argument
983** of the argv array. Use the sqlite3_get_auxdata() cache for this
984** parse if it is available. If the cache is not available or if it
985** is no longer valid, parse the JSON again and return the new parse,
986** and also register the new parse so that it will be available for
987** future sqlite3_get_auxdata() calls.
988*/
989static JsonParse *jsonParseCached(
990 sqlite3_context *pCtx,
991 sqlite3_value **argv
992){
993 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
994 int nJson = sqlite3_value_bytes(argv[0]);
995 JsonParse *p;
996 if( zJson==0 ) return 0;
997 p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
998 if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
999 p->nErr = 0;
1000 return p; /* The cached entry matches, so return it */
1001 }
1002 p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
1003 if( p==0 ){
1004 sqlite3_result_error_nomem(pCtx);
1005 return 0;
1006 }
1007 memset(p, 0, sizeof(*p));
1008 p->zJson = (char*)&p[1];
1009 memcpy((char*)p->zJson, zJson, nJson+1);
1010 if( jsonParse(p, pCtx, p->zJson) ){
1011 sqlite3_free(p);
1012 return 0;
1013 }
1014 p->nJson = nJson;
1015 sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
1016 return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
1017}
1018
1019/*
drh8cb0c832015-09-22 00:21:03 +00001020** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1021** a match.
1022*/
mistachkinf2c26ed2015-10-12 22:20:29 +00001023static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh8cb0c832015-09-22 00:21:03 +00001024 if( pNode->jnFlags & JNODE_RAW ){
1025 if( pNode->n!=nKey ) return 0;
1026 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
1027 }else{
1028 if( pNode->n!=nKey+2 ) return 0;
1029 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
1030 }
1031}
1032
drh52216ad2015-08-18 02:28:03 +00001033/* forward declaration */
drha7714022015-08-29 00:54:49 +00001034static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +00001035
drh987eb1f2015-08-17 15:17:37 +00001036/*
1037** Search along zPath to find the node specified. Return a pointer
1038** to that node, or NULL if zPath is malformed or if there is no such
1039** node.
drh52216ad2015-08-18 02:28:03 +00001040**
1041** If pApnd!=0, then try to append new nodes to complete zPath if it is
1042** possible to do so and if no existing node corresponds to zPath. If
1043** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +00001044*/
drha7714022015-08-29 00:54:49 +00001045static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +00001046 JsonParse *pParse, /* The JSON to search */
1047 u32 iRoot, /* Begin the search at this node */
1048 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +00001049 int *pApnd, /* Append nodes to complete path if not NULL */
1050 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +00001051){
drhbc8f0922015-08-22 19:39:04 +00001052 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001053 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001054 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001055 if( zPath[0]==0 ) return pRoot;
1056 if( zPath[0]=='.' ){
1057 if( pRoot->eType!=JSON_OBJECT ) return 0;
1058 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001059 if( zPath[0]=='"' ){
1060 zKey = zPath + 1;
1061 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1062 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001063 if( zPath[i] ){
1064 i++;
1065 }else{
1066 *pzErr = zPath;
1067 return 0;
1068 }
drh6b43cc82015-08-19 23:02:49 +00001069 }else{
1070 zKey = zPath;
1071 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1072 nKey = i;
1073 }
drha7714022015-08-29 00:54:49 +00001074 if( nKey==0 ){
1075 *pzErr = zPath;
1076 return 0;
1077 }
drh987eb1f2015-08-17 15:17:37 +00001078 j = 1;
drh52216ad2015-08-18 02:28:03 +00001079 for(;;){
1080 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001081 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001082 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001083 }
1084 j++;
drh505ad2c2015-08-21 17:33:11 +00001085 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001086 }
drh52216ad2015-08-18 02:28:03 +00001087 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1088 iRoot += pRoot->u.iAppend;
1089 pRoot = &pParse->aNode[iRoot];
1090 j = 1;
1091 }
1092 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001093 u32 iStart, iLabel;
1094 JsonNode *pNode;
1095 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1096 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +00001097 zPath += i;
drha7714022015-08-29 00:54:49 +00001098 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001099 if( pParse->oom ) return 0;
1100 if( pNode ){
1101 pRoot = &pParse->aNode[iRoot];
1102 pRoot->u.iAppend = iStart - iRoot;
1103 pRoot->jnFlags |= JNODE_APPEND;
1104 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1105 }
1106 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001107 }
dan2e8f5512015-09-17 17:21:09 +00001108 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +00001109 if( pRoot->eType!=JSON_ARRAY ) return 0;
1110 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001111 j = 1;
1112 while( safe_isdigit(zPath[j]) ){
1113 i = i*10 + zPath[j] - '0';
1114 j++;
drh987eb1f2015-08-17 15:17:37 +00001115 }
drh3d1d2a92015-09-22 01:15:49 +00001116 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +00001117 *pzErr = zPath;
1118 return 0;
1119 }
drh3d1d2a92015-09-22 01:15:49 +00001120 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001121 j = 1;
drh52216ad2015-08-18 02:28:03 +00001122 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001123 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1124 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001125 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001126 }
1127 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1128 iRoot += pRoot->u.iAppend;
1129 pRoot = &pParse->aNode[iRoot];
1130 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001131 }
1132 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001133 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001134 }
1135 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001136 u32 iStart;
1137 JsonNode *pNode;
1138 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001139 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001140 if( pParse->oom ) return 0;
1141 if( pNode ){
1142 pRoot = &pParse->aNode[iRoot];
1143 pRoot->u.iAppend = iStart - iRoot;
1144 pRoot->jnFlags |= JNODE_APPEND;
1145 }
1146 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001147 }
drh3d1d2a92015-09-22 01:15:49 +00001148 }else{
drha7714022015-08-29 00:54:49 +00001149 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001150 }
1151 return 0;
1152}
1153
drh52216ad2015-08-18 02:28:03 +00001154/*
drhbc8f0922015-08-22 19:39:04 +00001155** Append content to pParse that will complete zPath. Return a pointer
1156** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001157*/
1158static JsonNode *jsonLookupAppend(
1159 JsonParse *pParse, /* Append content to the JSON parse */
1160 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001161 int *pApnd, /* Set this flag to 1 */
1162 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001163){
1164 *pApnd = 1;
1165 if( zPath[0]==0 ){
1166 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1167 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1168 }
1169 if( zPath[0]=='.' ){
1170 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1171 }else if( strncmp(zPath,"[0]",3)==0 ){
1172 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1173 }else{
1174 return 0;
1175 }
1176 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001177 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001178}
1179
drhbc8f0922015-08-22 19:39:04 +00001180/*
drha7714022015-08-29 00:54:49 +00001181** Return the text of a syntax error message on a JSON path. Space is
1182** obtained from sqlite3_malloc().
1183*/
1184static char *jsonPathSyntaxError(const char *zErr){
1185 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1186}
1187
1188/*
1189** Do a node lookup using zPath. Return a pointer to the node on success.
1190** Return NULL if not found or if there is an error.
1191**
1192** On an error, write an error message into pCtx and increment the
1193** pParse->nErr counter.
1194**
1195** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1196** nodes are appended.
drha7714022015-08-29 00:54:49 +00001197*/
1198static JsonNode *jsonLookup(
1199 JsonParse *pParse, /* The JSON to search */
1200 const char *zPath, /* The path to search */
1201 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001202 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001203){
1204 const char *zErr = 0;
1205 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001206 char *zMsg;
drha7714022015-08-29 00:54:49 +00001207
1208 if( zPath==0 ) return 0;
1209 if( zPath[0]!='$' ){
1210 zErr = zPath;
1211 goto lookup_err;
1212 }
1213 zPath++;
drha7714022015-08-29 00:54:49 +00001214 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001215 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001216
1217lookup_err:
1218 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001219 assert( zErr!=0 && pCtx!=0 );
1220 zMsg = jsonPathSyntaxError(zErr);
1221 if( zMsg ){
1222 sqlite3_result_error(pCtx, zMsg, -1);
1223 sqlite3_free(zMsg);
1224 }else{
1225 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001226 }
drha7714022015-08-29 00:54:49 +00001227 return 0;
1228}
1229
1230
1231/*
drhbc8f0922015-08-22 19:39:04 +00001232** Report the wrong number of arguments for json_insert(), json_replace()
1233** or json_set().
1234*/
1235static void jsonWrongNumArgs(
1236 sqlite3_context *pCtx,
1237 const char *zFuncName
1238){
1239 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1240 zFuncName);
1241 sqlite3_result_error(pCtx, zMsg, -1);
1242 sqlite3_free(zMsg);
1243}
drh52216ad2015-08-18 02:28:03 +00001244
drh29c99692017-03-24 12:35:17 +00001245/*
1246** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1247*/
1248static void jsonRemoveAllNulls(JsonNode *pNode){
1249 int i, n;
1250 assert( pNode->eType==JSON_OBJECT );
1251 n = pNode->n;
1252 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1253 switch( pNode[i].eType ){
1254 case JSON_NULL:
1255 pNode[i].jnFlags |= JNODE_REMOVE;
1256 break;
1257 case JSON_OBJECT:
1258 jsonRemoveAllNulls(&pNode[i]);
1259 break;
1260 }
1261 }
1262}
1263
drha7714022015-08-29 00:54:49 +00001264
drh987eb1f2015-08-17 15:17:37 +00001265/****************************************************************************
1266** SQL functions used for testing and debugging
1267****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001268
drh301eecc2015-08-17 20:14:19 +00001269#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001270/*
drh5634cc02015-08-17 11:28:03 +00001271** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001272** a parse of the JSON provided. Or it returns NULL if JSON is not
1273** well-formed.
1274*/
drh5634cc02015-08-17 11:28:03 +00001275static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001276 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001277 int argc,
1278 sqlite3_value **argv
1279){
drh505ad2c2015-08-21 17:33:11 +00001280 JsonString s; /* Output string - not real JSON */
1281 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001282 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001283
1284 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001285 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001286 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001287 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001288 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001289 const char *zType;
1290 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1291 assert( x.aNode[i].eType==JSON_STRING );
1292 zType = "label";
1293 }else{
1294 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001295 }
drh852944e2015-09-10 03:29:11 +00001296 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1297 i, zType, x.aNode[i].n, x.aUp[i]);
1298 if( x.aNode[i].u.zJContent!=0 ){
1299 jsonAppendRaw(&s, " ", 1);
1300 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1301 }
1302 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001303 }
drh505ad2c2015-08-21 17:33:11 +00001304 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001305 jsonResult(&s);
1306}
1307
drh5634cc02015-08-17 11:28:03 +00001308/*
drhf5ddb9c2015-09-11 00:06:41 +00001309** The json_test1(JSON) function return true (1) if the input is JSON
1310** text generated by another json function. It returns (0) if the input
1311** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001312*/
1313static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001314 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001315 int argc,
1316 sqlite3_value **argv
1317){
mistachkin16a93122015-09-11 18:05:01 +00001318 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001319 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001320}
drh301eecc2015-08-17 20:14:19 +00001321#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001322
drh987eb1f2015-08-17 15:17:37 +00001323/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001324** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001325****************************************************************************/
1326
1327/*
drh2ad96f52016-06-17 13:01:51 +00001328** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1329** corresponding to the SQL value input. Mostly this means putting
1330** double-quotes around strings and returning the unquoted string "null"
1331** when given a NULL input.
1332*/
1333static void jsonQuoteFunc(
1334 sqlite3_context *ctx,
1335 int argc,
1336 sqlite3_value **argv
1337){
1338 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001339 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001340
1341 jsonInit(&jx, ctx);
1342 jsonAppendValue(&jx, argv[0]);
1343 jsonResult(&jx);
1344 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1345}
1346
1347/*
drh987eb1f2015-08-17 15:17:37 +00001348** Implementation of the json_array(VALUE,...) function. Return a JSON
1349** array that contains all values given in arguments. Or if any argument
1350** is a BLOB, throw an error.
1351*/
1352static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001353 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001354 int argc,
1355 sqlite3_value **argv
1356){
1357 int i;
drh505ad2c2015-08-21 17:33:11 +00001358 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001359
drhbc8f0922015-08-22 19:39:04 +00001360 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001361 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001362 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001363 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001364 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001365 }
drhd0960592015-08-17 21:22:32 +00001366 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001367 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001368 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001369}
1370
1371
1372/*
1373** json_array_length(JSON)
1374** json_array_length(JSON, PATH)
1375**
1376** Return the number of elements in the top-level JSON array.
1377** Return 0 if the input is not a well-formed JSON array.
1378*/
1379static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001380 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001381 int argc,
1382 sqlite3_value **argv
1383){
drh3fb153c2017-05-11 16:49:59 +00001384 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001385 sqlite3_int64 n = 0;
1386 u32 i;
drha8f39a92015-09-21 22:53:16 +00001387 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001388
drh3fb153c2017-05-11 16:49:59 +00001389 p = jsonParseCached(ctx, argv);
1390 if( p==0 ) return;
1391 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001392 if( argc==2 ){
1393 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001394 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001395 }else{
drh3fb153c2017-05-11 16:49:59 +00001396 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001397 }
1398 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001399 return;
1400 }
1401 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001402 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1403 for(i=1; i<=pNode->n; n++){
1404 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001405 }
drh987eb1f2015-08-17 15:17:37 +00001406 }
drh3fb153c2017-05-11 16:49:59 +00001407 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001408}
1409
1410/*
drh3ad93bb2015-08-29 19:41:45 +00001411** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001412**
drh3ad93bb2015-08-29 19:41:45 +00001413** Return the element described by PATH. Return NULL if there is no
1414** PATH element. If there are multiple PATHs, then return a JSON array
1415** with the result from each path. Throw an error if the JSON or any PATH
1416** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001417*/
1418static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001419 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001420 int argc,
1421 sqlite3_value **argv
1422){
drh3fb153c2017-05-11 16:49:59 +00001423 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001424 JsonNode *pNode;
1425 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001426 JsonString jx;
1427 int i;
1428
1429 if( argc<2 ) return;
drh3fb153c2017-05-11 16:49:59 +00001430 p = jsonParseCached(ctx, argv);
1431 if( p==0 ) return;
drh3ad93bb2015-08-29 19:41:45 +00001432 jsonInit(&jx, ctx);
1433 jsonAppendChar(&jx, '[');
1434 for(i=1; i<argc; i++){
1435 zPath = (const char*)sqlite3_value_text(argv[i]);
drh3fb153c2017-05-11 16:49:59 +00001436 pNode = jsonLookup(p, zPath, 0, ctx);
1437 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001438 if( argc>2 ){
1439 jsonAppendSeparator(&jx);
1440 if( pNode ){
1441 jsonRenderNode(pNode, &jx, 0);
1442 }else{
1443 jsonAppendRaw(&jx, "null", 4);
1444 }
1445 }else if( pNode ){
1446 jsonReturn(pNode, ctx, 0);
1447 }
drh987eb1f2015-08-17 15:17:37 +00001448 }
drh3ad93bb2015-08-29 19:41:45 +00001449 if( argc>2 && i==argc ){
1450 jsonAppendChar(&jx, ']');
1451 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001452 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001453 }
1454 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001455}
1456
drh633647a2017-03-22 21:24:31 +00001457/* This is the RFC 7396 MergePatch algorithm.
1458*/
1459static JsonNode *jsonMergePatch(
1460 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001461 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001462 JsonNode *pPatch /* The PATCH */
1463){
drh0002d242017-03-23 00:46:15 +00001464 u32 i, j;
1465 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001466 JsonNode *pTarget;
1467 if( pPatch->eType!=JSON_OBJECT ){
1468 return pPatch;
1469 }
1470 assert( iTarget>=0 && iTarget<pParse->nNode );
1471 pTarget = &pParse->aNode[iTarget];
1472 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1473 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001474 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001475 return pPatch;
1476 }
drhbb7aa2d2017-03-23 00:13:52 +00001477 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001478 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001479 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001480 const char *zKey;
1481 assert( pPatch[i].eType==JSON_STRING );
1482 assert( pPatch[i].jnFlags & JNODE_LABEL );
1483 nKey = pPatch[i].n;
1484 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001485 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001486 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1487 assert( pTarget[j].eType==JSON_STRING );
1488 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001489 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001490 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1491 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001492 if( pPatch[i+1].eType==JSON_NULL ){
1493 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1494 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001495 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001496 if( pNew==0 ) return 0;
1497 pTarget = &pParse->aNode[iTarget];
1498 if( pNew!=&pTarget[j+1] ){
1499 pTarget[j+1].u.pPatch = pNew;
1500 pTarget[j+1].jnFlags |= JNODE_PATCH;
1501 }
1502 }
1503 break;
1504 }
1505 }
drhbb7aa2d2017-03-23 00:13:52 +00001506 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001507 int iStart, iPatch;
1508 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1509 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1510 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1511 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001512 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001513 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001514 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1515 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1516 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001517 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1518 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1519 }
1520 }
1521 return pTarget;
1522}
1523
1524/*
1525** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1526** object that is the result of running the RFC 7396 MergePatch() algorithm
1527** on the two arguments.
1528*/
drh37f03df2017-03-23 20:33:49 +00001529static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001530 sqlite3_context *ctx,
1531 int argc,
1532 sqlite3_value **argv
1533){
1534 JsonParse x; /* The JSON that is being patched */
1535 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001536 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001537
drh2fb79e92017-03-25 12:08:11 +00001538 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001539 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1540 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1541 jsonParseReset(&x);
1542 return;
1543 }
drhbb7aa2d2017-03-23 00:13:52 +00001544 pResult = jsonMergePatch(&x, 0, y.aNode);
1545 assert( pResult!=0 || x.oom );
1546 if( pResult ){
1547 jsonReturnJson(pResult, ctx, 0);
1548 }else{
1549 sqlite3_result_error_nomem(ctx);
1550 }
drh633647a2017-03-22 21:24:31 +00001551 jsonParseReset(&x);
1552 jsonParseReset(&y);
1553}
1554
1555
drh987eb1f2015-08-17 15:17:37 +00001556/*
1557** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1558** object that contains all name/value given in arguments. Or if any name
1559** is not a string or if any value is a BLOB, throw an error.
1560*/
1561static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001562 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001563 int argc,
1564 sqlite3_value **argv
1565){
1566 int i;
drh505ad2c2015-08-21 17:33:11 +00001567 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001568 const char *z;
1569 u32 n;
1570
1571 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001572 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001573 "of arguments", -1);
1574 return;
1575 }
drhbc8f0922015-08-22 19:39:04 +00001576 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001577 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001578 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001579 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001580 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001581 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001582 return;
1583 }
drhd0960592015-08-17 21:22:32 +00001584 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001585 z = (const char*)sqlite3_value_text(argv[i]);
1586 n = (u32)sqlite3_value_bytes(argv[i]);
1587 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001588 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001589 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001590 }
drhd0960592015-08-17 21:22:32 +00001591 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001592 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001593 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001594}
1595
1596
1597/*
drh301eecc2015-08-17 20:14:19 +00001598** json_remove(JSON, PATH, ...)
1599**
drh3ad93bb2015-08-29 19:41:45 +00001600** Remove the named elements from JSON and return the result. malformed
1601** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001602*/
1603static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001604 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001605 int argc,
1606 sqlite3_value **argv
1607){
1608 JsonParse x; /* The parse */
1609 JsonNode *pNode;
1610 const char *zPath;
1611 u32 i;
1612
1613 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001614 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001615 assert( x.nNode );
1616 for(i=1; i<(u32)argc; i++){
1617 zPath = (const char*)sqlite3_value_text(argv[i]);
1618 if( zPath==0 ) goto remove_done;
1619 pNode = jsonLookup(&x, zPath, 0, ctx);
1620 if( x.nErr ) goto remove_done;
1621 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1622 }
1623 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1624 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001625 }
drha7714022015-08-29 00:54:49 +00001626remove_done:
drh505ad2c2015-08-21 17:33:11 +00001627 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001628}
1629
1630/*
1631** json_replace(JSON, PATH, VALUE, ...)
1632**
1633** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001634** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001635*/
1636static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001637 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001638 int argc,
1639 sqlite3_value **argv
1640){
1641 JsonParse x; /* The parse */
1642 JsonNode *pNode;
1643 const char *zPath;
1644 u32 i;
1645
1646 if( argc<1 ) return;
1647 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001648 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001649 return;
1650 }
drhbc8f0922015-08-22 19:39:04 +00001651 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001652 assert( x.nNode );
1653 for(i=1; i<(u32)argc; i+=2){
1654 zPath = (const char*)sqlite3_value_text(argv[i]);
1655 pNode = jsonLookup(&x, zPath, 0, ctx);
1656 if( x.nErr ) goto replace_err;
1657 if( pNode ){
1658 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001659 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001660 }
drha8f39a92015-09-21 22:53:16 +00001661 }
1662 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001663 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001664 }else{
1665 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001666 }
drha7714022015-08-29 00:54:49 +00001667replace_err:
drh505ad2c2015-08-21 17:33:11 +00001668 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001669}
drh505ad2c2015-08-21 17:33:11 +00001670
drh52216ad2015-08-18 02:28:03 +00001671/*
1672** json_set(JSON, PATH, VALUE, ...)
1673**
1674** Set the value at PATH to VALUE. Create the PATH if it does not already
1675** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001676** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001677**
1678** json_insert(JSON, PATH, VALUE, ...)
1679**
1680** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001681** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001682*/
1683static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001684 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001685 int argc,
1686 sqlite3_value **argv
1687){
1688 JsonParse x; /* The parse */
1689 JsonNode *pNode;
1690 const char *zPath;
1691 u32 i;
1692 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001693 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001694
1695 if( argc<1 ) return;
1696 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001697 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001698 return;
1699 }
drhbc8f0922015-08-22 19:39:04 +00001700 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001701 assert( x.nNode );
1702 for(i=1; i<(u32)argc; i+=2){
1703 zPath = (const char*)sqlite3_value_text(argv[i]);
1704 bApnd = 0;
1705 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1706 if( x.oom ){
1707 sqlite3_result_error_nomem(ctx);
1708 goto jsonSetDone;
1709 }else if( x.nErr ){
1710 goto jsonSetDone;
1711 }else if( pNode && (bApnd || bIsSet) ){
1712 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001713 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001714 }
drha8f39a92015-09-21 22:53:16 +00001715 }
1716 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001717 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001718 }else{
1719 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001720 }
drhbc8f0922015-08-22 19:39:04 +00001721jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001722 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001723}
drh301eecc2015-08-17 20:14:19 +00001724
1725/*
drh987eb1f2015-08-17 15:17:37 +00001726** json_type(JSON)
1727** json_type(JSON, PATH)
1728**
drh3ad93bb2015-08-29 19:41:45 +00001729** Return the top-level "type" of a JSON string. Throw an error if
1730** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001731*/
1732static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001733 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001734 int argc,
1735 sqlite3_value **argv
1736){
1737 JsonParse x; /* The parse */
1738 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001739 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001740
drhbc8f0922015-08-22 19:39:04 +00001741 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001742 assert( x.nNode );
1743 if( argc==2 ){
1744 zPath = (const char*)sqlite3_value_text(argv[1]);
1745 pNode = jsonLookup(&x, zPath, 0, ctx);
1746 }else{
1747 pNode = x.aNode;
1748 }
1749 if( pNode ){
1750 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001751 }
drh505ad2c2015-08-21 17:33:11 +00001752 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001753}
drh5634cc02015-08-17 11:28:03 +00001754
drhbc8f0922015-08-22 19:39:04 +00001755/*
1756** json_valid(JSON)
1757**
drh3ad93bb2015-08-29 19:41:45 +00001758** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1759** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001760*/
1761static void jsonValidFunc(
1762 sqlite3_context *ctx,
1763 int argc,
1764 sqlite3_value **argv
1765){
1766 JsonParse x; /* The parse */
1767 int rc = 0;
1768
mistachkin16a93122015-09-11 18:05:01 +00001769 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001770 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001771 rc = 1;
1772 }
1773 jsonParseReset(&x);
1774 sqlite3_result_int(ctx, rc);
1775}
1776
drhff135ae2015-12-30 01:07:02 +00001777
1778/****************************************************************************
1779** Aggregate SQL function implementations
1780****************************************************************************/
1781/*
1782** json_group_array(VALUE)
1783**
1784** Return a JSON array composed of all values in the aggregate.
1785*/
1786static void jsonArrayStep(
1787 sqlite3_context *ctx,
1788 int argc,
1789 sqlite3_value **argv
1790){
1791 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001792 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001793 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1794 if( pStr ){
1795 if( pStr->zBuf==0 ){
1796 jsonInit(pStr, ctx);
1797 jsonAppendChar(pStr, '[');
1798 }else{
1799 jsonAppendChar(pStr, ',');
1800 pStr->pCtx = ctx;
1801 }
1802 jsonAppendValue(pStr, argv[0]);
1803 }
1804}
drh8be47a72018-07-05 20:05:29 +00001805static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001806 JsonString *pStr;
1807 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1808 if( pStr ){
1809 pStr->pCtx = ctx;
1810 jsonAppendChar(pStr, ']');
1811 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001812 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001813 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001814 }else if( isFinal ){
drhff135ae2015-12-30 01:07:02 +00001815 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
1816 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1817 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001818 }else{
1819 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed, SQLITE_TRANSIENT);
1820 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001821 }
1822 }else{
1823 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1824 }
1825 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1826}
drh8be47a72018-07-05 20:05:29 +00001827static void jsonArrayValue(sqlite3_context *ctx){
1828 jsonArrayCompute(ctx, 0);
1829}
1830static void jsonArrayFinal(sqlite3_context *ctx){
1831 jsonArrayCompute(ctx, 1);
1832}
1833
1834#ifndef SQLITE_OMIT_WINDOWFUNC
1835/*
1836** This method works for both json_group_array() and json_group_object().
1837** It works by removing the first element of the group by searching forward
1838** to the first comma (",") that is not within a string and deleting all
1839** text through that comma.
1840*/
1841static void jsonGroupInverse(
1842 sqlite3_context *ctx,
1843 int argc,
1844 sqlite3_value **argv
1845){
1846 int i;
1847 int inStr = 0;
1848 char *z;
1849 JsonString *pStr;
1850 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drhfd4b7282018-07-07 19:47:21 +00001851 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1852 ** always have been called to initalize it */
1853 if( NEVER(!pStr) ) return;
drh8be47a72018-07-05 20:05:29 +00001854 z = pStr->zBuf;
1855 for(i=1; z[i]!=',' || inStr; i++){
1856 assert( i<pStr->nUsed );
1857 if( z[i]=='"' ){
1858 inStr = !inStr;
1859 }else if( z[i]=='\\' ){
1860 i++;
1861 }
1862 }
1863 pStr->nUsed -= i;
1864 memmove(&z[1], &z[i+1], pStr->nUsed-1);
1865}
1866#else
1867# define jsonGroupInverse 0
1868#endif
1869
drhff135ae2015-12-30 01:07:02 +00001870
1871/*
1872** json_group_obj(NAME,VALUE)
1873**
1874** Return a JSON object composed of all names and values in the aggregate.
1875*/
1876static void jsonObjectStep(
1877 sqlite3_context *ctx,
1878 int argc,
1879 sqlite3_value **argv
1880){
1881 JsonString *pStr;
1882 const char *z;
1883 u32 n;
drhdf3a9072016-02-11 15:37:18 +00001884 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001885 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1886 if( pStr ){
1887 if( pStr->zBuf==0 ){
1888 jsonInit(pStr, ctx);
1889 jsonAppendChar(pStr, '{');
1890 }else{
1891 jsonAppendChar(pStr, ',');
1892 pStr->pCtx = ctx;
1893 }
1894 z = (const char*)sqlite3_value_text(argv[0]);
1895 n = (u32)sqlite3_value_bytes(argv[0]);
1896 jsonAppendString(pStr, z, n);
1897 jsonAppendChar(pStr, ':');
1898 jsonAppendValue(pStr, argv[1]);
1899 }
1900}
drh8be47a72018-07-05 20:05:29 +00001901static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001902 JsonString *pStr;
1903 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1904 if( pStr ){
1905 jsonAppendChar(pStr, '}');
1906 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00001907 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001908 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001909 }else if( isFinal ){
drhff135ae2015-12-30 01:07:02 +00001910 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
1911 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1912 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001913 }else{
1914 sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed, SQLITE_TRANSIENT);
1915 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001916 }
1917 }else{
1918 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
1919 }
1920 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1921}
drh8be47a72018-07-05 20:05:29 +00001922static void jsonObjectValue(sqlite3_context *ctx){
1923 jsonObjectCompute(ctx, 0);
1924}
1925static void jsonObjectFinal(sqlite3_context *ctx){
1926 jsonObjectCompute(ctx, 1);
1927}
1928
drhff135ae2015-12-30 01:07:02 +00001929
1930
drhd2975922015-08-29 17:22:33 +00001931#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001932/****************************************************************************
1933** The json_each virtual table
1934****************************************************************************/
1935typedef struct JsonEachCursor JsonEachCursor;
1936struct JsonEachCursor {
1937 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001938 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001939 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001940 u32 i; /* Index in sParse.aNode[] of current row */
1941 u32 iEnd; /* EOF when i equals or exceeds this value */
1942 u8 eType; /* Type of top-level element */
1943 u8 bRecursive; /* True for json_tree(). False for json_each() */
1944 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001945 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001946 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001947};
1948
1949/* Constructor for the json_each virtual table */
1950static int jsonEachConnect(
1951 sqlite3 *db,
1952 void *pAux,
1953 int argc, const char *const*argv,
1954 sqlite3_vtab **ppVtab,
1955 char **pzErr
1956){
1957 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001958 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001959
1960/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001961#define JEACH_KEY 0
1962#define JEACH_VALUE 1
1963#define JEACH_TYPE 2
1964#define JEACH_ATOM 3
1965#define JEACH_ID 4
1966#define JEACH_PARENT 5
1967#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001968#define JEACH_PATH 7
1969#define JEACH_JSON 8
1970#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001971
drh6fd5c1e2015-08-21 20:37:12 +00001972 UNUSED_PARAM(pzErr);
1973 UNUSED_PARAM(argv);
1974 UNUSED_PARAM(argc);
1975 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001976 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001977 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1978 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001979 if( rc==SQLITE_OK ){
1980 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1981 if( pNew==0 ) return SQLITE_NOMEM;
1982 memset(pNew, 0, sizeof(*pNew));
1983 }
1984 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001985}
1986
1987/* destructor for json_each virtual table */
1988static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1989 sqlite3_free(pVtab);
1990 return SQLITE_OK;
1991}
1992
drh505ad2c2015-08-21 17:33:11 +00001993/* constructor for a JsonEachCursor object for json_each(). */
1994static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001995 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001996
1997 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001998 pCur = sqlite3_malloc( sizeof(*pCur) );
1999 if( pCur==0 ) return SQLITE_NOMEM;
2000 memset(pCur, 0, sizeof(*pCur));
2001 *ppCursor = &pCur->base;
2002 return SQLITE_OK;
2003}
2004
drh505ad2c2015-08-21 17:33:11 +00002005/* constructor for a JsonEachCursor object for json_tree(). */
2006static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2007 int rc = jsonEachOpenEach(p, ppCursor);
2008 if( rc==SQLITE_OK ){
2009 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2010 pCur->bRecursive = 1;
2011 }
2012 return rc;
2013}
2014
drhcb6c6c62015-08-19 22:47:17 +00002015/* Reset a JsonEachCursor back to its original state. Free any memory
2016** held. */
2017static void jsonEachCursorReset(JsonEachCursor *p){
2018 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002019 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002020 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002021 p->iRowid = 0;
2022 p->i = 0;
2023 p->iEnd = 0;
2024 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002025 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002026 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002027}
2028
2029/* Destructor for a jsonEachCursor object */
2030static int jsonEachClose(sqlite3_vtab_cursor *cur){
2031 JsonEachCursor *p = (JsonEachCursor*)cur;
2032 jsonEachCursorReset(p);
2033 sqlite3_free(cur);
2034 return SQLITE_OK;
2035}
2036
2037/* Return TRUE if the jsonEachCursor object has been advanced off the end
2038** of the JSON object */
2039static int jsonEachEof(sqlite3_vtab_cursor *cur){
2040 JsonEachCursor *p = (JsonEachCursor*)cur;
2041 return p->i >= p->iEnd;
2042}
2043
drh505ad2c2015-08-21 17:33:11 +00002044/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002045static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002046 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002047 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002048 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2049 p->i++;
drh4af352d2015-08-21 20:02:48 +00002050 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002051 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002052 u32 iUp = p->sParse.aUp[p->i];
2053 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002054 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002055 if( pUp->eType==JSON_ARRAY ){
2056 if( iUp==p->i-1 ){
2057 pUp->u.iKey = 0;
2058 }else{
2059 pUp->u.iKey++;
2060 }
drh4af352d2015-08-21 20:02:48 +00002061 }
2062 }
drh505ad2c2015-08-21 17:33:11 +00002063 }else{
drh4af352d2015-08-21 20:02:48 +00002064 switch( p->eType ){
2065 case JSON_ARRAY: {
2066 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2067 p->iRowid++;
2068 break;
2069 }
2070 case JSON_OBJECT: {
2071 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2072 p->iRowid++;
2073 break;
2074 }
2075 default: {
2076 p->i = p->iEnd;
2077 break;
2078 }
drh505ad2c2015-08-21 17:33:11 +00002079 }
2080 }
2081 return SQLITE_OK;
2082}
2083
drh4af352d2015-08-21 20:02:48 +00002084/* Append the name of the path for element i to pStr
2085*/
2086static void jsonEachComputePath(
2087 JsonEachCursor *p, /* The cursor */
2088 JsonString *pStr, /* Write the path here */
2089 u32 i /* Path to this element */
2090){
2091 JsonNode *pNode, *pUp;
2092 u32 iUp;
2093 if( i==0 ){
2094 jsonAppendChar(pStr, '$');
2095 return;
drhcb6c6c62015-08-19 22:47:17 +00002096 }
drh4af352d2015-08-21 20:02:48 +00002097 iUp = p->sParse.aUp[i];
2098 jsonEachComputePath(p, pStr, iUp);
2099 pNode = &p->sParse.aNode[i];
2100 pUp = &p->sParse.aNode[iUp];
2101 if( pUp->eType==JSON_ARRAY ){
2102 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2103 }else{
2104 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002105 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002106 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002107 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00002108 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2109 }
drhcb6c6c62015-08-19 22:47:17 +00002110}
2111
2112/* Return the value of a column */
2113static int jsonEachColumn(
2114 sqlite3_vtab_cursor *cur, /* The cursor */
2115 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2116 int i /* Which column to return */
2117){
2118 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002119 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002120 switch( i ){
2121 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002122 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002123 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002124 jsonReturn(pThis, ctx, 0);
2125 }else if( p->eType==JSON_ARRAY ){
2126 u32 iKey;
2127 if( p->bRecursive ){
2128 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002129 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002130 }else{
2131 iKey = p->iRowid;
2132 }
drh6fd5c1e2015-08-21 20:37:12 +00002133 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002134 }
2135 break;
2136 }
2137 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002138 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002139 jsonReturn(pThis, ctx, 0);
2140 break;
2141 }
2142 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002143 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002144 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2145 break;
2146 }
2147 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002148 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002149 if( pThis->eType>=JSON_ARRAY ) break;
2150 jsonReturn(pThis, ctx, 0);
2151 break;
2152 }
2153 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002154 sqlite3_result_int64(ctx,
2155 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002156 break;
2157 }
2158 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002159 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002160 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002161 }
2162 break;
2163 }
drh4af352d2015-08-21 20:02:48 +00002164 case JEACH_FULLKEY: {
2165 JsonString x;
2166 jsonInit(&x, ctx);
2167 if( p->bRecursive ){
2168 jsonEachComputePath(p, &x, p->i);
2169 }else{
drh383de692015-09-10 17:20:57 +00002170 if( p->zRoot ){
2171 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002172 }else{
2173 jsonAppendChar(&x, '$');
2174 }
2175 if( p->eType==JSON_ARRAY ){
2176 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002177 }else if( p->eType==JSON_OBJECT ){
drh4af352d2015-08-21 20:02:48 +00002178 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2179 }
2180 }
2181 jsonResult(&x);
2182 break;
2183 }
drhcb6c6c62015-08-19 22:47:17 +00002184 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002185 if( p->bRecursive ){
2186 JsonString x;
2187 jsonInit(&x, ctx);
2188 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2189 jsonResult(&x);
2190 break;
drh4af352d2015-08-21 20:02:48 +00002191 }
drh383de692015-09-10 17:20:57 +00002192 /* For json_each() path and root are the same so fall through
2193 ** into the root case */
2194 }
drh6850a632016-11-07 18:18:08 +00002195 default: {
drh383de692015-09-10 17:20:57 +00002196 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002197 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002198 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002199 break;
2200 }
drh3d1d2a92015-09-22 01:15:49 +00002201 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002202 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002203 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2204 break;
2205 }
2206 }
2207 return SQLITE_OK;
2208}
2209
2210/* Return the current rowid value */
2211static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2212 JsonEachCursor *p = (JsonEachCursor*)cur;
2213 *pRowid = p->iRowid;
2214 return SQLITE_OK;
2215}
2216
2217/* The query strategy is to look for an equality constraint on the json
2218** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002219** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002220** and 0 otherwise.
2221*/
2222static int jsonEachBestIndex(
2223 sqlite3_vtab *tab,
2224 sqlite3_index_info *pIdxInfo
2225){
2226 int i;
2227 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00002228 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00002229 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002230
2231 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00002232 pConstraint = pIdxInfo->aConstraint;
2233 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2234 if( pConstraint->usable==0 ) continue;
2235 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2236 switch( pConstraint->iColumn ){
2237 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00002238 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00002239 default: /* no-op */ break;
2240 }
2241 }
2242 if( jsonIdx<0 ){
2243 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00002244 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00002245 }else{
drh505ad2c2015-08-21 17:33:11 +00002246 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00002247 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
2248 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00002249 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00002250 pIdxInfo->idxNum = 1;
2251 }else{
drh383de692015-09-10 17:20:57 +00002252 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
2253 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00002254 pIdxInfo->idxNum = 3;
2255 }
2256 }
2257 return SQLITE_OK;
2258}
2259
2260/* Start a search on a new JSON string */
2261static int jsonEachFilter(
2262 sqlite3_vtab_cursor *cur,
2263 int idxNum, const char *idxStr,
2264 int argc, sqlite3_value **argv
2265){
2266 JsonEachCursor *p = (JsonEachCursor*)cur;
2267 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002268 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002269 sqlite3_int64 n;
2270
drh6fd5c1e2015-08-21 20:37:12 +00002271 UNUSED_PARAM(idxStr);
2272 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002273 jsonEachCursorReset(p);
2274 if( idxNum==0 ) return SQLITE_OK;
2275 z = (const char*)sqlite3_value_text(argv[0]);
2276 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002277 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002278 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002279 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002280 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002281 if( jsonParse(&p->sParse, 0, p->zJson) ){
2282 int rc = SQLITE_NOMEM;
2283 if( p->sParse.oom==0 ){
2284 sqlite3_free(cur->pVtab->zErrMsg);
2285 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2286 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2287 }
drhcb6c6c62015-08-19 22:47:17 +00002288 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002289 return rc;
2290 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2291 jsonEachCursorReset(p);
2292 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002293 }else{
drh95677942015-09-24 01:06:37 +00002294 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002295 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002296 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002297 zRoot = (const char*)sqlite3_value_text(argv[1]);
2298 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002299 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002300 p->zRoot = sqlite3_malloc64( n+1 );
2301 if( p->zRoot==0 ) return SQLITE_NOMEM;
2302 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002303 if( zRoot[0]!='$' ){
2304 zErr = zRoot;
2305 }else{
2306 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2307 }
2308 if( zErr ){
drha7714022015-08-29 00:54:49 +00002309 sqlite3_free(cur->pVtab->zErrMsg);
2310 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002311 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002312 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2313 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002314 return SQLITE_OK;
2315 }
2316 }else{
2317 pNode = p->sParse.aNode;
2318 }
drh852944e2015-09-10 03:29:11 +00002319 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002320 p->eType = pNode->eType;
2321 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002322 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002323 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002324 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002325 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002326 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2327 p->i--;
2328 }
2329 }else{
2330 p->i++;
2331 }
drhcb6c6c62015-08-19 22:47:17 +00002332 }else{
2333 p->iEnd = p->i+1;
2334 }
2335 }
drha8f39a92015-09-21 22:53:16 +00002336 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002337}
2338
2339/* The methods of the json_each virtual table */
2340static sqlite3_module jsonEachModule = {
2341 0, /* iVersion */
2342 0, /* xCreate */
2343 jsonEachConnect, /* xConnect */
2344 jsonEachBestIndex, /* xBestIndex */
2345 jsonEachDisconnect, /* xDisconnect */
2346 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002347 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002348 jsonEachClose, /* xClose - close a cursor */
2349 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002350 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002351 jsonEachEof, /* xEof - check for end of scan */
2352 jsonEachColumn, /* xColumn - read data */
2353 jsonEachRowid, /* xRowid - read data */
2354 0, /* xUpdate */
2355 0, /* xBegin */
2356 0, /* xSync */
2357 0, /* xCommit */
2358 0, /* xRollback */
2359 0, /* xFindMethod */
2360 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002361 0, /* xSavepoint */
2362 0, /* xRelease */
2363 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00002364};
2365
drh505ad2c2015-08-21 17:33:11 +00002366/* The methods of the json_tree virtual table. */
2367static sqlite3_module jsonTreeModule = {
2368 0, /* iVersion */
2369 0, /* xCreate */
2370 jsonEachConnect, /* xConnect */
2371 jsonEachBestIndex, /* xBestIndex */
2372 jsonEachDisconnect, /* xDisconnect */
2373 0, /* xDestroy */
2374 jsonEachOpenTree, /* xOpen - open a cursor */
2375 jsonEachClose, /* xClose - close a cursor */
2376 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002377 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002378 jsonEachEof, /* xEof - check for end of scan */
2379 jsonEachColumn, /* xColumn - read data */
2380 jsonEachRowid, /* xRowid - read data */
2381 0, /* xUpdate */
2382 0, /* xBegin */
2383 0, /* xSync */
2384 0, /* xCommit */
2385 0, /* xRollback */
2386 0, /* xFindMethod */
2387 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002388 0, /* xSavepoint */
2389 0, /* xRelease */
2390 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00002391};
drhd2975922015-08-29 17:22:33 +00002392#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002393
2394/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002395** The following routines are the only publically visible identifiers in this
2396** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002397** functions and the virtual table implemented by this file.
2398****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002399
drh2f20e132015-09-26 17:44:59 +00002400int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002401 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002402 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002403 static const struct {
2404 const char *zName;
2405 int nArg;
drh52216ad2015-08-18 02:28:03 +00002406 int flag;
drh5fa5c102015-08-12 16:49:40 +00002407 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2408 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002409 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002410 { "json_array", -1, 0, jsonArrayFunc },
2411 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2412 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002413 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002414 { "json_insert", -1, 0, jsonSetFunc },
2415 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002416 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002417 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002418 { "json_remove", -1, 0, jsonRemoveFunc },
2419 { "json_replace", -1, 0, jsonReplaceFunc },
2420 { "json_set", -1, 1, jsonSetFunc },
2421 { "json_type", 1, 0, jsonTypeFunc },
2422 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002423 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002424
drh301eecc2015-08-17 20:14:19 +00002425#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002426 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002427 { "json_parse", 1, 0, jsonParseFunc },
2428 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002429#endif
drh5fa5c102015-08-12 16:49:40 +00002430 };
drhff135ae2015-12-30 01:07:02 +00002431 static const struct {
2432 const char *zName;
2433 int nArg;
2434 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2435 void (*xFinal)(sqlite3_context*);
drh8be47a72018-07-05 20:05:29 +00002436 void (*xValue)(sqlite3_context*);
drhff135ae2015-12-30 01:07:02 +00002437 } aAgg[] = {
drh8be47a72018-07-05 20:05:29 +00002438 { "json_group_array", 1,
2439 jsonArrayStep, jsonArrayFinal, jsonArrayValue },
2440 { "json_group_object", 2,
2441 jsonObjectStep, jsonObjectFinal, jsonObjectValue },
drhff135ae2015-12-30 01:07:02 +00002442 };
drhd2975922015-08-29 17:22:33 +00002443#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002444 static const struct {
2445 const char *zName;
2446 sqlite3_module *pModule;
2447 } aMod[] = {
2448 { "json_each", &jsonEachModule },
2449 { "json_tree", &jsonTreeModule },
2450 };
drhd2975922015-08-29 17:22:33 +00002451#endif
drh5fa5c102015-08-12 16:49:40 +00002452 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2453 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002454 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2455 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002456 aFunc[i].xFunc, 0, 0);
2457 }
drhff135ae2015-12-30 01:07:02 +00002458 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
drh8be47a72018-07-05 20:05:29 +00002459 rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
drhff135ae2015-12-30 01:07:02 +00002460 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
drh8be47a72018-07-05 20:05:29 +00002461 aAgg[i].xStep, aAgg[i].xFinal,
2462 aAgg[i].xValue, jsonGroupInverse, 0);
drhff135ae2015-12-30 01:07:02 +00002463 }
drhd2975922015-08-29 17:22:33 +00002464#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002465 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2466 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002467 }
drhd2975922015-08-29 17:22:33 +00002468#endif
drh5fa5c102015-08-12 16:49:40 +00002469 return rc;
2470}
drh2f20e132015-09-26 17:44:59 +00002471
2472
dan8d32e802015-10-14 18:45:42 +00002473#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002474#ifdef _WIN32
2475__declspec(dllexport)
2476#endif
2477int sqlite3_json_init(
2478 sqlite3 *db,
2479 char **pzErrMsg,
2480 const sqlite3_api_routines *pApi
2481){
2482 SQLITE_EXTENSION_INIT2(pApi);
2483 (void)pzErrMsg; /* Unused parameter */
2484 return sqlite3Json1Init(db);
2485}
dan8d32e802015-10-14 18:45:42 +00002486#endif
drh50065652015-10-08 19:29:18 +00002487#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */