blob: 0a3e907be6f65088fb2b1dbe7632ddfd30e2e8b7 [file] [log] [blame]
drh5fa5c102015-08-12 16:49:40 +00001/*
2** 2015-08-12
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This SQLite extension implements JSON functions. The interface is
14** modeled after MySQL JSON functions:
15**
16** https://dev.mysql.com/doc/refman/5.7/en/json.html
17**
drh5634cc02015-08-17 11:28:03 +000018** For the time being, all JSON is stored as pure text. (We might add
19** a JSONB type in the future which stores a binary encoding of JSON in
drhcb6c6c62015-08-19 22:47:17 +000020** a BLOB, but there is no support for JSONB in the current implementation.
21** This implementation parses JSON text at 250 MB/s, so it is hard to see
22** how JSONB might improve on that.)
drh5fa5c102015-08-12 16:49:40 +000023*/
drh50065652015-10-08 19:29:18 +000024#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
drh666d34c2017-01-25 13:54:27 +000025#if !defined(SQLITEINT_H)
drh5fa5c102015-08-12 16:49:40 +000026#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000027#endif
drh5fa5c102015-08-12 16:49:40 +000028SQLITE_EXTENSION_INIT1
29#include <assert.h>
30#include <string.h>
drh987eb1f2015-08-17 15:17:37 +000031#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000032#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000033
drhdf3a9072016-02-11 15:37:18 +000034/* Mark a function parameter as unused, to suppress nuisance compiler
35** warnings. */
36#ifndef UNUSED_PARAM
37# define UNUSED_PARAM(X) (void)(X)
38#endif
drh6fd5c1e2015-08-21 20:37:12 +000039
drh8deb4b82015-10-09 18:21:43 +000040#ifndef LARGEST_INT64
41# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
42# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
43#endif
44
drh08b92082020-08-10 14:18:00 +000045#ifndef deliberate_fall_through
46# define deliberate_fall_through
47#endif
48
dan2e8f5512015-09-17 17:21:09 +000049/*
50** Versions of isspace(), isalnum() and isdigit() to which it is safe
51** to pass signed char values.
52*/
drh49472652015-10-16 15:35:39 +000053#ifdef sqlite3Isdigit
54 /* Use the SQLite core versions if this routine is part of the
55 ** SQLite amalgamation */
drhad875e72016-11-07 13:37:28 +000056# define safe_isdigit(x) sqlite3Isdigit(x)
57# define safe_isalnum(x) sqlite3Isalnum(x)
58# define safe_isxdigit(x) sqlite3Isxdigit(x)
drh49472652015-10-16 15:35:39 +000059#else
60 /* Use the standard library for separate compilation */
61#include <ctype.h> /* amalgamator: keep */
drhad875e72016-11-07 13:37:28 +000062# define safe_isdigit(x) isdigit((unsigned char)(x))
63# define safe_isalnum(x) isalnum((unsigned char)(x))
64# define safe_isxdigit(x) isxdigit((unsigned char)(x))
drh49472652015-10-16 15:35:39 +000065#endif
dan2e8f5512015-09-17 17:21:09 +000066
drh95677942015-09-24 01:06:37 +000067/*
68** Growing our own isspace() routine this way is twice as fast as
69** the library isspace() function, resulting in a 7% overall performance
70** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
71*/
72static const char jsonIsSpace[] = {
drhb9e8f592015-10-16 15:16:06 +000073 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
drh95677942015-09-24 01:06:37 +000074 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
75 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
76 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
89};
90#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
91
drh9a4718f2015-10-10 14:00:37 +000092#ifndef SQLITE_AMALGAMATION
93 /* Unsigned integer types. These are already defined in the sqliteInt.h,
94 ** but the definitions need to be repeated for separate compilation. */
95 typedef sqlite3_uint64 u64;
96 typedef unsigned int u32;
drhff6d50e2017-04-11 18:55:05 +000097 typedef unsigned short int u16;
drh9a4718f2015-10-10 14:00:37 +000098 typedef unsigned char u8;
drh6a726fa2021-10-05 15:30:52 +000099# if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
100# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
101# endif
102# if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
103# define ALWAYS(X) (1)
104# define NEVER(X) (0)
105# elif !defined(NDEBUG)
106# define ALWAYS(X) ((X)?1:(assert(0),0))
107# define NEVER(X) ((X)?(assert(0),1):0)
108# else
109# define ALWAYS(X) (X)
110# define NEVER(X) (X)
111# endif
drh9a4718f2015-10-10 14:00:37 +0000112#endif
drh5fa5c102015-08-12 16:49:40 +0000113
drh52216ad2015-08-18 02:28:03 +0000114/* Objects */
drh505ad2c2015-08-21 17:33:11 +0000115typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +0000116typedef struct JsonNode JsonNode;
117typedef struct JsonParse JsonParse;
118
drh5634cc02015-08-17 11:28:03 +0000119/* An instance of this object represents a JSON string
120** under construction. Really, this is a generic string accumulator
121** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +0000122*/
drh505ad2c2015-08-21 17:33:11 +0000123struct JsonString {
drh5fa5c102015-08-12 16:49:40 +0000124 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +0000125 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +0000126 u64 nAlloc; /* Bytes of storage available in zBuf[] */
127 u64 nUsed; /* Bytes of zBuf[] currently used */
128 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +0000129 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +0000130 char zSpace[100]; /* Initial static space */
131};
132
drhe9c37f32015-08-15 21:25:36 +0000133/* JSON type values
drhbd0621b2015-08-13 13:54:59 +0000134*/
drhe9c37f32015-08-15 21:25:36 +0000135#define JSON_NULL 0
136#define JSON_TRUE 1
137#define JSON_FALSE 2
138#define JSON_INT 3
139#define JSON_REAL 4
140#define JSON_STRING 5
141#define JSON_ARRAY 6
142#define JSON_OBJECT 7
143
drhf5ddb9c2015-09-11 00:06:41 +0000144/* The "subtype" set for JSON values */
145#define JSON_SUBTYPE 74 /* Ascii for "J" */
146
drh987eb1f2015-08-17 15:17:37 +0000147/*
148** Names of the various JSON types:
149*/
150static const char * const jsonType[] = {
151 "null", "true", "false", "integer", "real", "text", "array", "object"
152};
153
drh301eecc2015-08-17 20:14:19 +0000154/* Bit values for the JsonNode.jnFlag field
155*/
156#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
157#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
158#define JNODE_REMOVE 0x04 /* Do not output */
drh633647a2017-03-22 21:24:31 +0000159#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
160#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
161#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
162#define JNODE_LABEL 0x40 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000163
drh987eb1f2015-08-17 15:17:37 +0000164
drhe9c37f32015-08-15 21:25:36 +0000165/* A single node of parsed JSON
166*/
drhe9c37f32015-08-15 21:25:36 +0000167struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000168 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000169 u8 jnFlags; /* JNODE flags */
drhe9c37f32015-08-15 21:25:36 +0000170 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000171 union {
drh0042a972015-08-18 12:59:58 +0000172 const char *zJContent; /* Content for INT, REAL, and STRING */
173 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000174 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh633647a2017-03-22 21:24:31 +0000175 u32 iReplace; /* Replacement content for JNODE_REPLACE */
176 JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
drh52216ad2015-08-18 02:28:03 +0000177 } u;
drhe9c37f32015-08-15 21:25:36 +0000178};
179
180/* A completely parsed JSON string
181*/
drhe9c37f32015-08-15 21:25:36 +0000182struct JsonParse {
183 u32 nNode; /* Number of slots of aNode[] used */
184 u32 nAlloc; /* Number of slots of aNode[] allocated */
185 JsonNode *aNode; /* Array of nodes containing the parse */
186 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000187 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000188 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000189 u8 nErr; /* Number of errors seen */
drhff6d50e2017-04-11 18:55:05 +0000190 u16 iDepth; /* Nesting depth */
drh3fb153c2017-05-11 16:49:59 +0000191 int nJson; /* Length of the zJson string in bytes */
drhe35fc302018-08-30 01:52:10 +0000192 u32 iHold; /* Replace cache line with the lowest iHold value */
drhe9c37f32015-08-15 21:25:36 +0000193};
194
drhff6d50e2017-04-11 18:55:05 +0000195/*
196** Maximum nesting depth of JSON for this implementation.
197**
198** This limit is needed to avoid a stack overflow in the recursive
199** descent parser. A depth of 2000 is far deeper than any sane JSON
200** should go.
201*/
202#define JSON_MAX_DEPTH 2000
203
drh505ad2c2015-08-21 17:33:11 +0000204/**************************************************************************
205** Utility routines for dealing with JsonString objects
206**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000207
drh505ad2c2015-08-21 17:33:11 +0000208/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000209*/
drh505ad2c2015-08-21 17:33:11 +0000210static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000211 p->zBuf = p->zSpace;
212 p->nAlloc = sizeof(p->zSpace);
213 p->nUsed = 0;
214 p->bStatic = 1;
215}
216
drh505ad2c2015-08-21 17:33:11 +0000217/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000218*/
drh505ad2c2015-08-21 17:33:11 +0000219static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000220 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000221 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000222 jsonZero(p);
223}
224
225
drh505ad2c2015-08-21 17:33:11 +0000226/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000227** initial state.
228*/
drh505ad2c2015-08-21 17:33:11 +0000229static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000230 if( !p->bStatic ) sqlite3_free(p->zBuf);
231 jsonZero(p);
232}
233
234
235/* Report an out-of-memory (OOM) condition
236*/
drh505ad2c2015-08-21 17:33:11 +0000237static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000238 p->bErr = 1;
239 sqlite3_result_error_nomem(p->pCtx);
240 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000241}
242
243/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
244** Return zero on success. Return non-zero on an OOM error
245*/
drh505ad2c2015-08-21 17:33:11 +0000246static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000247 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000248 char *zNew;
249 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000250 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000251 zNew = sqlite3_malloc64(nTotal);
252 if( zNew==0 ){
253 jsonOom(p);
254 return SQLITE_NOMEM;
255 }
drh6fd5c1e2015-08-21 20:37:12 +0000256 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000257 p->zBuf = zNew;
258 p->bStatic = 0;
259 }else{
260 zNew = sqlite3_realloc64(p->zBuf, nTotal);
261 if( zNew==0 ){
262 jsonOom(p);
263 return SQLITE_NOMEM;
264 }
265 p->zBuf = zNew;
266 }
267 p->nAlloc = nTotal;
268 return SQLITE_OK;
269}
270
drh505ad2c2015-08-21 17:33:11 +0000271/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000272*/
drh505ad2c2015-08-21 17:33:11 +0000273static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drhc795e3d2020-05-17 13:47:28 +0000274 if( N==0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000275 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
276 memcpy(p->zBuf+p->nUsed, zIn, N);
277 p->nUsed += N;
278}
279
drh4af352d2015-08-21 20:02:48 +0000280/* Append formatted text (not to exceed N bytes) to the JsonString.
281*/
282static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
283 va_list ap;
284 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
285 va_start(ap, zFormat);
286 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
287 va_end(ap);
288 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
289}
290
drh5634cc02015-08-17 11:28:03 +0000291/* Append a single character
292*/
drh505ad2c2015-08-21 17:33:11 +0000293static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000294 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
295 p->zBuf[p->nUsed++] = c;
296}
297
drh301eecc2015-08-17 20:14:19 +0000298/* Append a comma separator to the output buffer, if the previous
299** character is not '[' or '{'.
300*/
drh505ad2c2015-08-21 17:33:11 +0000301static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000302 char c;
303 if( p->nUsed==0 ) return;
304 c = p->zBuf[p->nUsed-1];
305 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
306}
307
drh505ad2c2015-08-21 17:33:11 +0000308/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000309** under construction. Enclose the string in "..." and escape
310** any double-quotes or backslash characters contained within the
311** string.
312*/
drh505ad2c2015-08-21 17:33:11 +0000313static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000314 u32 i;
drh76baad92021-04-30 16:12:40 +0000315 if( zIn==0 || ((N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0) ) return;
drh5fa5c102015-08-12 16:49:40 +0000316 p->zBuf[p->nUsed++] = '"';
317 for(i=0; i<N; i++){
drh3b7f9a62016-02-04 10:28:57 +0000318 unsigned char c = ((unsigned const char*)zIn)[i];
drh5fa5c102015-08-12 16:49:40 +0000319 if( c=='"' || c=='\\' ){
drh3b7f9a62016-02-04 10:28:57 +0000320 json_simple_escape:
drh4977ccf2015-09-19 11:57:26 +0000321 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000322 p->zBuf[p->nUsed++] = '\\';
drh3b7f9a62016-02-04 10:28:57 +0000323 }else if( c<=0x1f ){
324 static const char aSpecial[] = {
325 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
326 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
327 };
328 assert( sizeof(aSpecial)==32 );
329 assert( aSpecial['\b']=='b' );
330 assert( aSpecial['\f']=='f' );
331 assert( aSpecial['\n']=='n' );
332 assert( aSpecial['\r']=='r' );
333 assert( aSpecial['\t']=='t' );
334 if( aSpecial[c] ){
335 c = aSpecial[c];
336 goto json_simple_escape;
337 }
338 if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
339 p->zBuf[p->nUsed++] = '\\';
340 p->zBuf[p->nUsed++] = 'u';
341 p->zBuf[p->nUsed++] = '0';
342 p->zBuf[p->nUsed++] = '0';
343 p->zBuf[p->nUsed++] = '0' + (c>>4);
344 c = "0123456789abcdef"[c&0xf];
drh5fa5c102015-08-12 16:49:40 +0000345 }
346 p->zBuf[p->nUsed++] = c;
347 }
348 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000349 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000350}
351
drhd0960592015-08-17 21:22:32 +0000352/*
353** Append a function parameter value to the JSON string under
354** construction.
355*/
356static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000357 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000358 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000359){
360 switch( sqlite3_value_type(pValue) ){
361 case SQLITE_NULL: {
362 jsonAppendRaw(p, "null", 4);
363 break;
364 }
365 case SQLITE_INTEGER:
366 case SQLITE_FLOAT: {
367 const char *z = (const char*)sqlite3_value_text(pValue);
368 u32 n = (u32)sqlite3_value_bytes(pValue);
369 jsonAppendRaw(p, z, n);
370 break;
371 }
372 case SQLITE_TEXT: {
373 const char *z = (const char*)sqlite3_value_text(pValue);
374 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000375 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000376 jsonAppendRaw(p, z, n);
377 }else{
378 jsonAppendString(p, z, n);
379 }
drhd0960592015-08-17 21:22:32 +0000380 break;
381 }
382 default: {
383 if( p->bErr==0 ){
384 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
drh4a642b62016-02-05 01:55:27 +0000385 p->bErr = 2;
drhd0960592015-08-17 21:22:32 +0000386 jsonReset(p);
387 }
388 break;
389 }
390 }
391}
392
393
drhbd0621b2015-08-13 13:54:59 +0000394/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000395*/
drh505ad2c2015-08-21 17:33:11 +0000396static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000397 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000398 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
399 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
400 SQLITE_UTF8);
401 jsonZero(p);
402 }
403 assert( p->bStatic );
404}
405
drh505ad2c2015-08-21 17:33:11 +0000406/**************************************************************************
407** Utility routines for dealing with JsonNode and JsonParse objects
408**************************************************************************/
409
410/*
411** Return the number of consecutive JsonNode slots need to represent
412** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
413** OBJECT types, the number might be larger.
414**
415** Appended elements are not counted. The value returned is the number
416** by which the JsonNode counter should increment in order to go to the
417** next peer value.
418*/
419static u32 jsonNodeSize(JsonNode *pNode){
420 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
421}
422
423/*
424** Reclaim all memory allocated by a JsonParse object. But do not
425** delete the JsonParse object itself.
426*/
427static void jsonParseReset(JsonParse *pParse){
428 sqlite3_free(pParse->aNode);
429 pParse->aNode = 0;
430 pParse->nNode = 0;
431 pParse->nAlloc = 0;
432 sqlite3_free(pParse->aUp);
433 pParse->aUp = 0;
434}
435
drh5634cc02015-08-17 11:28:03 +0000436/*
drh3fb153c2017-05-11 16:49:59 +0000437** Free a JsonParse object that was obtained from sqlite3_malloc().
438*/
439static void jsonParseFree(JsonParse *pParse){
440 jsonParseReset(pParse);
441 sqlite3_free(pParse);
442}
443
444/*
drh5634cc02015-08-17 11:28:03 +0000445** Convert the JsonNode pNode into a pure JSON string and
446** append to pOut. Subsubstructure is also included. Return
447** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000448*/
drh52216ad2015-08-18 02:28:03 +0000449static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000450 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000451 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000452 sqlite3_value **aReplace /* Replacement values */
453){
drh7d4c94b2021-10-04 22:34:38 +0000454 assert( pNode!=0 );
drh633647a2017-03-22 21:24:31 +0000455 if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
drh7d4c94b2021-10-04 22:34:38 +0000456 if( (pNode->jnFlags & JNODE_REPLACE)!=0 && ALWAYS(aReplace!=0) ){
drh633647a2017-03-22 21:24:31 +0000457 jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
458 return;
459 }
460 pNode = pNode->u.pPatch;
461 }
drh5634cc02015-08-17 11:28:03 +0000462 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000463 default: {
464 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000465 jsonAppendRaw(pOut, "null", 4);
466 break;
467 }
468 case JSON_TRUE: {
469 jsonAppendRaw(pOut, "true", 4);
470 break;
471 }
472 case JSON_FALSE: {
473 jsonAppendRaw(pOut, "false", 5);
474 break;
475 }
476 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000477 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000478 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000479 break;
480 }
drh08b92082020-08-10 14:18:00 +0000481 /* no break */ deliberate_fall_through
drh5634cc02015-08-17 11:28:03 +0000482 }
483 case JSON_REAL:
484 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000485 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000486 break;
487 }
488 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000489 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000490 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000491 for(;;){
492 while( j<=pNode->n ){
drh633647a2017-03-22 21:24:31 +0000493 if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
drhd0960592015-08-17 21:22:32 +0000494 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000495 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000496 }
drh505ad2c2015-08-21 17:33:11 +0000497 j += jsonNodeSize(&pNode[j]);
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 }
506 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000507 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000508 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000509 for(;;){
510 while( j<=pNode->n ){
511 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
512 jsonAppendSeparator(pOut);
513 jsonRenderNode(&pNode[j], pOut, aReplace);
514 jsonAppendChar(pOut, ':');
drh633647a2017-03-22 21:24:31 +0000515 jsonRenderNode(&pNode[j+1], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000516 }
drh505ad2c2015-08-21 17:33:11 +0000517 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000518 }
drh52216ad2015-08-18 02:28:03 +0000519 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
520 pNode = &pNode[pNode->u.iAppend];
521 j = 1;
drh5634cc02015-08-17 11:28:03 +0000522 }
523 jsonAppendChar(pOut, '}');
524 break;
525 }
drhbd0621b2015-08-13 13:54:59 +0000526 }
drh5634cc02015-08-17 11:28:03 +0000527}
528
529/*
drhf2df7e72015-08-28 20:07:40 +0000530** Return a JsonNode and all its descendents as a JSON string.
531*/
532static void jsonReturnJson(
533 JsonNode *pNode, /* Node to return */
534 sqlite3_context *pCtx, /* Return value for this function */
535 sqlite3_value **aReplace /* Array of replacement values */
536){
537 JsonString s;
538 jsonInit(&s, pCtx);
539 jsonRenderNode(pNode, &s, aReplace);
540 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000541 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000542}
543
544/*
drh48eb03b2019-11-10 11:09:06 +0000545** Translate a single byte of Hex into an integer.
546** This routine only works if h really is a valid hexadecimal
547** character: 0..9a..fA..F
548*/
549static u8 jsonHexToInt(int h){
550 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
551#ifdef SQLITE_EBCDIC
552 h += 9*(1&~(h>>4));
553#else
554 h += 9*(1&(h>>6));
555#endif
556 return (u8)(h & 0xf);
557}
558
559/*
560** Convert a 4-byte hex string into an integer
561*/
562static u32 jsonHexToInt4(const char *z){
563 u32 v;
564 assert( safe_isxdigit(z[0]) );
565 assert( safe_isxdigit(z[1]) );
566 assert( safe_isxdigit(z[2]) );
567 assert( safe_isxdigit(z[3]) );
568 v = (jsonHexToInt(z[0])<<12)
569 + (jsonHexToInt(z[1])<<8)
570 + (jsonHexToInt(z[2])<<4)
571 + jsonHexToInt(z[3]);
572 return v;
573}
574
575/*
drh5634cc02015-08-17 11:28:03 +0000576** Make the JsonNode the return value of the function.
577*/
drhd0960592015-08-17 21:22:32 +0000578static void jsonReturn(
579 JsonNode *pNode, /* Node to return */
580 sqlite3_context *pCtx, /* Return value for this function */
581 sqlite3_value **aReplace /* Array of replacement values */
582){
drh5634cc02015-08-17 11:28:03 +0000583 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000584 default: {
585 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000586 sqlite3_result_null(pCtx);
587 break;
588 }
589 case JSON_TRUE: {
590 sqlite3_result_int(pCtx, 1);
591 break;
592 }
593 case JSON_FALSE: {
594 sqlite3_result_int(pCtx, 0);
595 break;
596 }
drh987eb1f2015-08-17 15:17:37 +0000597 case JSON_INT: {
598 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000599 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000600 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000601 while( z[0]>='0' && z[0]<='9' ){
602 unsigned v = *(z++) - '0';
603 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000604 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000605 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
606 if( v==9 ) goto int_as_real;
607 if( v==8 ){
608 if( pNode->u.zJContent[0]=='-' ){
609 sqlite3_result_int64(pCtx, SMALLEST_INT64);
610 goto int_done;
611 }else{
612 goto int_as_real;
613 }
614 }
615 }
616 i = i*10 + v;
617 }
drh52216ad2015-08-18 02:28:03 +0000618 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000619 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000620 int_done:
621 break;
drhe85e1da2021-10-01 21:01:07 +0000622 int_as_real: ; /* no break */ deliberate_fall_through
drh8deb4b82015-10-09 18:21:43 +0000623 }
624 case JSON_REAL: {
drh49472652015-10-16 15:35:39 +0000625 double r;
626#ifdef SQLITE_AMALGAMATION
627 const char *z = pNode->u.zJContent;
628 sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
629#else
630 r = strtod(pNode->u.zJContent, 0);
631#endif
drh8deb4b82015-10-09 18:21:43 +0000632 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000633 break;
634 }
drh5634cc02015-08-17 11:28:03 +0000635 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000636#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
637 ** json_insert() and json_replace() and those routines do not
638 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000639 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000640 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
641 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000642 }else
643#endif
644 assert( (pNode->jnFlags & JNODE_RAW)==0 );
645 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000646 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000647 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000648 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000649 }else{
650 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000651 u32 i;
652 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000653 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000654 char *zOut;
655 u32 j;
656 zOut = sqlite3_malloc( n+1 );
657 if( zOut==0 ){
658 sqlite3_result_error_nomem(pCtx);
659 break;
660 }
661 for(i=1, j=0; i<n-1; i++){
662 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000663 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000664 zOut[j++] = c;
665 }else{
666 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000667 if( c=='u' ){
drh48eb03b2019-11-10 11:09:06 +0000668 u32 v = jsonHexToInt4(z+i+1);
669 i += 4;
drh80d87402015-08-24 12:42:41 +0000670 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000671 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000672 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000673 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000674 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000675 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000676 }else{
drh48eb03b2019-11-10 11:09:06 +0000677 u32 vlo;
678 if( (v&0xfc00)==0xd800
679 && i<n-6
680 && z[i+1]=='\\'
681 && z[i+2]=='u'
682 && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
683 ){
684 /* We have a surrogate pair */
685 v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
686 i += 6;
687 zOut[j++] = 0xf0 | (v>>18);
688 zOut[j++] = 0x80 | ((v>>12)&0x3f);
689 zOut[j++] = 0x80 | ((v>>6)&0x3f);
690 zOut[j++] = 0x80 | (v&0x3f);
691 }else{
692 zOut[j++] = 0xe0 | (v>>12);
693 zOut[j++] = 0x80 | ((v>>6)&0x3f);
694 zOut[j++] = 0x80 | (v&0x3f);
695 }
drh987eb1f2015-08-17 15:17:37 +0000696 }
697 }else{
698 if( c=='b' ){
699 c = '\b';
700 }else if( c=='f' ){
701 c = '\f';
702 }else if( c=='n' ){
703 c = '\n';
704 }else if( c=='r' ){
705 c = '\r';
706 }else if( c=='t' ){
707 c = '\t';
708 }
709 zOut[j++] = c;
710 }
711 }
712 }
713 zOut[j] = 0;
714 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000715 }
716 break;
717 }
718 case JSON_ARRAY:
719 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000720 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000721 break;
722 }
723 }
drhbd0621b2015-08-13 13:54:59 +0000724}
725
drh95677942015-09-24 01:06:37 +0000726/* Forward reference */
727static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
728
729/*
730** A macro to hint to the compiler that a function should not be
731** inlined.
732*/
733#if defined(__GNUC__)
734# define JSON_NOINLINE __attribute__((noinline))
735#elif defined(_MSC_VER) && _MSC_VER>=1310
736# define JSON_NOINLINE __declspec(noinline)
737#else
738# define JSON_NOINLINE
739#endif
740
741
742static JSON_NOINLINE int jsonParseAddNodeExpand(
743 JsonParse *pParse, /* Append the node to this object */
744 u32 eType, /* Node type */
745 u32 n, /* Content size or sub-node count */
746 const char *zContent /* Content */
747){
748 u32 nNew;
749 JsonNode *pNew;
750 assert( pParse->nNode>=pParse->nAlloc );
751 if( pParse->oom ) return -1;
752 nNew = pParse->nAlloc*2 + 10;
drh2d77d802019-01-08 20:02:48 +0000753 pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
drh95677942015-09-24 01:06:37 +0000754 if( pNew==0 ){
755 pParse->oom = 1;
756 return -1;
757 }
758 pParse->nAlloc = nNew;
759 pParse->aNode = pNew;
760 assert( pParse->nNode<pParse->nAlloc );
761 return jsonParseAddNode(pParse, eType, n, zContent);
762}
763
drh5fa5c102015-08-12 16:49:40 +0000764/*
drhe9c37f32015-08-15 21:25:36 +0000765** Create a new JsonNode instance based on the arguments and append that
766** instance to the JsonParse. Return the index in pParse->aNode[] of the
767** new node, or -1 if a memory allocation fails.
768*/
769static int jsonParseAddNode(
770 JsonParse *pParse, /* Append the node to this object */
771 u32 eType, /* Node type */
772 u32 n, /* Content size or sub-node count */
773 const char *zContent /* Content */
774){
775 JsonNode *p;
drhaa6fe5b2021-10-04 13:18:44 +0000776 if( pParse->aNode==0 || pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000777 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000778 }
779 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000780 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000781 p->jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000782 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000783 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000784 return pParse->nNode++;
785}
786
787/*
drhad875e72016-11-07 13:37:28 +0000788** Return true if z[] begins with 4 (or more) hexadecimal digits
789*/
790static int jsonIs4Hex(const char *z){
791 int i;
792 for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
793 return 1;
794}
795
796/*
drhe9c37f32015-08-15 21:25:36 +0000797** Parse a single JSON value which begins at pParse->zJson[i]. Return the
798** index of the first character past the end of the value parsed.
799**
800** Return negative for a syntax error. Special cases: return -2 if the
801** first non-whitespace character is '}' and return -3 if the first
802** non-whitespace character is ']'.
803*/
804static int jsonParseValue(JsonParse *pParse, u32 i){
805 char c;
806 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000807 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000808 int x;
drh852944e2015-09-10 03:29:11 +0000809 JsonNode *pNode;
drh9fa866a2017-04-08 18:18:22 +0000810 const char *z = pParse->zJson;
811 while( safe_isspace(z[i]) ){ i++; }
812 if( (c = z[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000813 /* Parse object */
814 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000815 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000816 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000817 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000818 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000819 x = jsonParseValue(pParse, j);
820 if( x<0 ){
drhff6d50e2017-04-11 18:55:05 +0000821 pParse->iDepth--;
drhf27cd1f2015-09-23 01:10:29 +0000822 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000823 return -1;
824 }
drhbe9474e2015-08-22 03:05:54 +0000825 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000826 pNode = &pParse->aNode[pParse->nNode-1];
827 if( pNode->eType!=JSON_STRING ) return -1;
828 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000829 j = x;
drh9fa866a2017-04-08 18:18:22 +0000830 while( safe_isspace(z[j]) ){ j++; }
831 if( z[j]!=':' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000832 j++;
833 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000834 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000835 if( x<0 ) return -1;
836 j = x;
drh9fa866a2017-04-08 18:18:22 +0000837 while( safe_isspace(z[j]) ){ j++; }
838 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000839 if( c==',' ) continue;
840 if( c!='}' ) return -1;
841 break;
842 }
drhbc8f0922015-08-22 19:39:04 +0000843 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000844 return j+1;
845 }else if( c=='[' ){
846 /* Parse array */
847 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000848 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000849 for(j=i+1;;j++){
drh9fa866a2017-04-08 18:18:22 +0000850 while( safe_isspace(z[j]) ){ j++; }
drhff6d50e2017-04-11 18:55:05 +0000851 if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000852 x = jsonParseValue(pParse, j);
drhff6d50e2017-04-11 18:55:05 +0000853 pParse->iDepth--;
drhe9c37f32015-08-15 21:25:36 +0000854 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000855 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000856 return -1;
857 }
858 j = x;
drh9fa866a2017-04-08 18:18:22 +0000859 while( safe_isspace(z[j]) ){ j++; }
860 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000861 if( c==',' ) continue;
862 if( c!=']' ) return -1;
863 break;
864 }
drhbc8f0922015-08-22 19:39:04 +0000865 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000866 return j+1;
867 }else if( c=='"' ){
868 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000869 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000870 j = i+1;
871 for(;;){
drh9fa866a2017-04-08 18:18:22 +0000872 c = z[j];
drh86715382017-04-13 00:12:32 +0000873 if( (c & ~0x1f)==0 ){
874 /* Control characters are not allowed in strings */
875 return -1;
876 }
drhe9c37f32015-08-15 21:25:36 +0000877 if( c=='\\' ){
drh9fa866a2017-04-08 18:18:22 +0000878 c = z[++j];
drhad875e72016-11-07 13:37:28 +0000879 if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
880 || c=='n' || c=='r' || c=='t'
drh9fa866a2017-04-08 18:18:22 +0000881 || (c=='u' && jsonIs4Hex(z+j+1)) ){
drhad875e72016-11-07 13:37:28 +0000882 jnFlags = JNODE_ESCAPE;
883 }else{
884 return -1;
885 }
drhe9c37f32015-08-15 21:25:36 +0000886 }else if( c=='"' ){
887 break;
888 }
889 j++;
890 }
drh9fa866a2017-04-08 18:18:22 +0000891 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
drhbe9474e2015-08-22 03:05:54 +0000892 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000893 return j+1;
894 }else if( c=='n'
drh9fa866a2017-04-08 18:18:22 +0000895 && strncmp(z+i,"null",4)==0
896 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000897 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
898 return i+4;
899 }else if( c=='t'
drh9fa866a2017-04-08 18:18:22 +0000900 && strncmp(z+i,"true",4)==0
901 && !safe_isalnum(z[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000902 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
903 return i+4;
904 }else if( c=='f'
drh9fa866a2017-04-08 18:18:22 +0000905 && strncmp(z+i,"false",5)==0
906 && !safe_isalnum(z[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000907 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
908 return i+5;
909 }else if( c=='-' || (c>='0' && c<='9') ){
910 /* Parse number */
911 u8 seenDP = 0;
912 u8 seenE = 0;
drh9fa866a2017-04-08 18:18:22 +0000913 assert( '-' < '0' );
914 if( c<='0' ){
915 j = c=='-' ? i+1 : i;
916 if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
917 }
drhe9c37f32015-08-15 21:25:36 +0000918 j = i+1;
919 for(;; j++){
drh9fa866a2017-04-08 18:18:22 +0000920 c = z[j];
drhe9c37f32015-08-15 21:25:36 +0000921 if( c>='0' && c<='9' ) continue;
922 if( c=='.' ){
drh9fa866a2017-04-08 18:18:22 +0000923 if( z[j-1]=='-' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000924 if( seenDP ) return -1;
925 seenDP = 1;
926 continue;
927 }
928 if( c=='e' || c=='E' ){
drh9fa866a2017-04-08 18:18:22 +0000929 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000930 if( seenE ) return -1;
931 seenDP = seenE = 1;
drh9fa866a2017-04-08 18:18:22 +0000932 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000933 if( c=='+' || c=='-' ){
934 j++;
drh9fa866a2017-04-08 18:18:22 +0000935 c = z[j+1];
drh8784eca2015-08-23 02:42:30 +0000936 }
drhd1f00682015-08-29 16:02:37 +0000937 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000938 continue;
939 }
940 break;
941 }
drh9fa866a2017-04-08 18:18:22 +0000942 if( z[j-1]<'0' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000943 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
drh9fa866a2017-04-08 18:18:22 +0000944 j - i, &z[i]);
drhe9c37f32015-08-15 21:25:36 +0000945 return j;
946 }else if( c=='}' ){
947 return -2; /* End of {...} */
948 }else if( c==']' ){
949 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000950 }else if( c==0 ){
951 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000952 }else{
953 return -1; /* Syntax error */
954 }
955}
956
957/*
958** Parse a complete JSON string. Return 0 on success or non-zero if there
959** are any errors. If an error occurs, free all memory associated with
960** pParse.
961**
962** pParse is uninitialized when this routine is called.
963*/
drhbc8f0922015-08-22 19:39:04 +0000964static int jsonParse(
965 JsonParse *pParse, /* Initialize and fill this JsonParse object */
966 sqlite3_context *pCtx, /* Report errors here */
967 const char *zJson /* Input JSON text to be parsed */
968){
drhe9c37f32015-08-15 21:25:36 +0000969 int i;
drhe9c37f32015-08-15 21:25:36 +0000970 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000971 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000972 pParse->zJson = zJson;
973 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000974 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000975 if( i>0 ){
drhff6d50e2017-04-11 18:55:05 +0000976 assert( pParse->iDepth==0 );
dan2e8f5512015-09-17 17:21:09 +0000977 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000978 if( zJson[i] ) i = -1;
979 }
drhd1f00682015-08-29 16:02:37 +0000980 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000981 if( pCtx!=0 ){
982 if( pParse->oom ){
983 sqlite3_result_error_nomem(pCtx);
984 }else{
985 sqlite3_result_error(pCtx, "malformed JSON", -1);
986 }
987 }
drh505ad2c2015-08-21 17:33:11 +0000988 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000989 return 1;
990 }
991 return 0;
992}
drh301eecc2015-08-17 20:14:19 +0000993
drh505ad2c2015-08-21 17:33:11 +0000994/* Mark node i of pParse as being a child of iParent. Call recursively
995** to fill in all the descendants of node i.
996*/
997static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
998 JsonNode *pNode = &pParse->aNode[i];
999 u32 j;
1000 pParse->aUp[i] = iParent;
1001 switch( pNode->eType ){
1002 case JSON_ARRAY: {
1003 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
1004 jsonParseFillInParentage(pParse, i+j, i);
1005 }
1006 break;
1007 }
1008 case JSON_OBJECT: {
1009 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
1010 pParse->aUp[i+j] = i;
1011 jsonParseFillInParentage(pParse, i+j+1, i);
1012 }
1013 break;
1014 }
1015 default: {
1016 break;
1017 }
1018 }
1019}
1020
1021/*
1022** Compute the parentage of all nodes in a completed parse.
1023*/
1024static int jsonParseFindParents(JsonParse *pParse){
1025 u32 *aUp;
1026 assert( pParse->aUp==0 );
drh2d77d802019-01-08 20:02:48 +00001027 aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +00001028 if( aUp==0 ){
1029 pParse->oom = 1;
1030 return SQLITE_NOMEM;
1031 }
drh505ad2c2015-08-21 17:33:11 +00001032 jsonParseFillInParentage(pParse, 0, 0);
1033 return SQLITE_OK;
1034}
1035
drh8cb0c832015-09-22 00:21:03 +00001036/*
drh3fb153c2017-05-11 16:49:59 +00001037** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
1038*/
drhe35fc302018-08-30 01:52:10 +00001039#define JSON_CACHE_ID (-429938) /* First cache entry */
1040#define JSON_CACHE_SZ 4 /* Max number of cache entries */
drh3fb153c2017-05-11 16:49:59 +00001041
1042/*
1043** Obtain a complete parse of the JSON found in the first argument
1044** of the argv array. Use the sqlite3_get_auxdata() cache for this
1045** parse if it is available. If the cache is not available or if it
1046** is no longer valid, parse the JSON again and return the new parse,
1047** and also register the new parse so that it will be available for
1048** future sqlite3_get_auxdata() calls.
1049*/
1050static JsonParse *jsonParseCached(
1051 sqlite3_context *pCtx,
drhe35fc302018-08-30 01:52:10 +00001052 sqlite3_value **argv,
1053 sqlite3_context *pErrCtx
drh3fb153c2017-05-11 16:49:59 +00001054){
1055 const char *zJson = (const char*)sqlite3_value_text(argv[0]);
1056 int nJson = sqlite3_value_bytes(argv[0]);
1057 JsonParse *p;
drhe35fc302018-08-30 01:52:10 +00001058 JsonParse *pMatch = 0;
1059 int iKey;
1060 int iMinKey = 0;
1061 u32 iMinHold = 0xffffffff;
1062 u32 iMaxHold = 0;
drh3fb153c2017-05-11 16:49:59 +00001063 if( zJson==0 ) return 0;
drhe35fc302018-08-30 01:52:10 +00001064 for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
1065 p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
1066 if( p==0 ){
1067 iMinKey = iKey;
1068 break;
1069 }
1070 if( pMatch==0
1071 && p->nJson==nJson
1072 && memcmp(p->zJson,zJson,nJson)==0
1073 ){
1074 p->nErr = 0;
1075 pMatch = p;
1076 }else if( p->iHold<iMinHold ){
1077 iMinHold = p->iHold;
1078 iMinKey = iKey;
1079 }
1080 if( p->iHold>iMaxHold ){
1081 iMaxHold = p->iHold;
1082 }
1083 }
1084 if( pMatch ){
1085 pMatch->nErr = 0;
1086 pMatch->iHold = iMaxHold+1;
1087 return pMatch;
drh3fb153c2017-05-11 16:49:59 +00001088 }
drh2d77d802019-01-08 20:02:48 +00001089 p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
drh3fb153c2017-05-11 16:49:59 +00001090 if( p==0 ){
1091 sqlite3_result_error_nomem(pCtx);
1092 return 0;
1093 }
1094 memset(p, 0, sizeof(*p));
1095 p->zJson = (char*)&p[1];
1096 memcpy((char*)p->zJson, zJson, nJson+1);
drhe35fc302018-08-30 01:52:10 +00001097 if( jsonParse(p, pErrCtx, p->zJson) ){
drh3fb153c2017-05-11 16:49:59 +00001098 sqlite3_free(p);
1099 return 0;
1100 }
1101 p->nJson = nJson;
drhe35fc302018-08-30 01:52:10 +00001102 p->iHold = iMaxHold+1;
1103 sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
1104 (void(*)(void*))jsonParseFree);
1105 return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
drh3fb153c2017-05-11 16:49:59 +00001106}
1107
1108/*
drh8cb0c832015-09-22 00:21:03 +00001109** Compare the OBJECT label at pNode against zKey,nKey. Return true on
1110** a match.
1111*/
mistachkinf2c26ed2015-10-12 22:20:29 +00001112static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
drh8cb0c832015-09-22 00:21:03 +00001113 if( pNode->jnFlags & JNODE_RAW ){
1114 if( pNode->n!=nKey ) return 0;
1115 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
1116 }else{
1117 if( pNode->n!=nKey+2 ) return 0;
1118 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
1119 }
1120}
1121
drh52216ad2015-08-18 02:28:03 +00001122/* forward declaration */
drha7714022015-08-29 00:54:49 +00001123static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +00001124
drh987eb1f2015-08-17 15:17:37 +00001125/*
1126** Search along zPath to find the node specified. Return a pointer
1127** to that node, or NULL if zPath is malformed or if there is no such
1128** node.
drh52216ad2015-08-18 02:28:03 +00001129**
1130** If pApnd!=0, then try to append new nodes to complete zPath if it is
1131** possible to do so and if no existing node corresponds to zPath. If
1132** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +00001133*/
drha7714022015-08-29 00:54:49 +00001134static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +00001135 JsonParse *pParse, /* The JSON to search */
1136 u32 iRoot, /* Begin the search at this node */
1137 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +00001138 int *pApnd, /* Append nodes to complete path if not NULL */
1139 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +00001140){
drhbc8f0922015-08-22 19:39:04 +00001141 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +00001142 const char *zKey;
drh52216ad2015-08-18 02:28:03 +00001143 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +00001144 if( zPath[0]==0 ) return pRoot;
drh7e35e812019-07-31 12:13:58 +00001145 if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
drh987eb1f2015-08-17 15:17:37 +00001146 if( zPath[0]=='.' ){
1147 if( pRoot->eType!=JSON_OBJECT ) return 0;
1148 zPath++;
drh6b43cc82015-08-19 23:02:49 +00001149 if( zPath[0]=='"' ){
1150 zKey = zPath + 1;
1151 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
1152 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +00001153 if( zPath[i] ){
1154 i++;
1155 }else{
1156 *pzErr = zPath;
1157 return 0;
1158 }
drh6b43cc82015-08-19 23:02:49 +00001159 }else{
1160 zKey = zPath;
1161 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
1162 nKey = i;
1163 }
drha7714022015-08-29 00:54:49 +00001164 if( nKey==0 ){
1165 *pzErr = zPath;
1166 return 0;
1167 }
drh987eb1f2015-08-17 15:17:37 +00001168 j = 1;
drh52216ad2015-08-18 02:28:03 +00001169 for(;;){
1170 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +00001171 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +00001172 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001173 }
1174 j++;
drh505ad2c2015-08-21 17:33:11 +00001175 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +00001176 }
drh52216ad2015-08-18 02:28:03 +00001177 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1178 iRoot += pRoot->u.iAppend;
1179 pRoot = &pParse->aNode[iRoot];
1180 j = 1;
1181 }
1182 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001183 u32 iStart, iLabel;
1184 JsonNode *pNode;
1185 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
danfe9a8322019-06-17 14:50:33 +00001186 iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
drh52216ad2015-08-18 02:28:03 +00001187 zPath += i;
drha7714022015-08-29 00:54:49 +00001188 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001189 if( pParse->oom ) return 0;
1190 if( pNode ){
1191 pRoot = &pParse->aNode[iRoot];
1192 pRoot->u.iAppend = iStart - iRoot;
1193 pRoot->jnFlags |= JNODE_APPEND;
1194 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
1195 }
1196 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001197 }
drh52818642019-11-22 17:37:56 +00001198 }else if( zPath[0]=='[' ){
drh987eb1f2015-08-17 15:17:37 +00001199 i = 0;
drh3d1d2a92015-09-22 01:15:49 +00001200 j = 1;
1201 while( safe_isdigit(zPath[j]) ){
1202 i = i*10 + zPath[j] - '0';
1203 j++;
drh987eb1f2015-08-17 15:17:37 +00001204 }
drh52818642019-11-22 17:37:56 +00001205 if( j<2 || zPath[j]!=']' ){
1206 if( zPath[1]=='#' ){
1207 JsonNode *pBase = pRoot;
1208 int iBase = iRoot;
1209 if( pRoot->eType!=JSON_ARRAY ) return 0;
1210 for(;;){
1211 while( j<=pBase->n ){
1212 if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
1213 j += jsonNodeSize(&pBase[j]);
1214 }
1215 if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
1216 iBase += pBase->u.iAppend;
1217 pBase = &pParse->aNode[iBase];
1218 j = 1;
1219 }
1220 j = 2;
1221 if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
1222 unsigned int x = 0;
1223 j = 3;
1224 do{
1225 x = x*10 + zPath[j] - '0';
1226 j++;
1227 }while( safe_isdigit(zPath[j]) );
1228 if( x>i ) return 0;
1229 i -= x;
1230 }
1231 if( zPath[j]!=']' ){
1232 *pzErr = zPath;
1233 return 0;
1234 }
1235 }else{
1236 *pzErr = zPath;
1237 return 0;
1238 }
drha7714022015-08-29 00:54:49 +00001239 }
drh52818642019-11-22 17:37:56 +00001240 if( pRoot->eType!=JSON_ARRAY ) return 0;
drh3d1d2a92015-09-22 01:15:49 +00001241 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +00001242 j = 1;
drh52216ad2015-08-18 02:28:03 +00001243 for(;;){
drhbc8f0922015-08-22 19:39:04 +00001244 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
1245 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +00001246 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +00001247 }
1248 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
1249 iRoot += pRoot->u.iAppend;
1250 pRoot = &pParse->aNode[iRoot];
1251 j = 1;
drh987eb1f2015-08-17 15:17:37 +00001252 }
1253 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +00001254 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001255 }
1256 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001257 u32 iStart;
1258 JsonNode *pNode;
1259 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001260 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001261 if( pParse->oom ) return 0;
1262 if( pNode ){
1263 pRoot = &pParse->aNode[iRoot];
1264 pRoot->u.iAppend = iStart - iRoot;
1265 pRoot->jnFlags |= JNODE_APPEND;
1266 }
1267 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001268 }
drh3d1d2a92015-09-22 01:15:49 +00001269 }else{
drha7714022015-08-29 00:54:49 +00001270 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001271 }
1272 return 0;
1273}
1274
drh52216ad2015-08-18 02:28:03 +00001275/*
drhbc8f0922015-08-22 19:39:04 +00001276** Append content to pParse that will complete zPath. Return a pointer
1277** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001278*/
1279static JsonNode *jsonLookupAppend(
1280 JsonParse *pParse, /* Append content to the JSON parse */
1281 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001282 int *pApnd, /* Set this flag to 1 */
1283 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001284){
1285 *pApnd = 1;
1286 if( zPath[0]==0 ){
1287 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1288 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1289 }
1290 if( zPath[0]=='.' ){
1291 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1292 }else if( strncmp(zPath,"[0]",3)==0 ){
1293 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1294 }else{
1295 return 0;
1296 }
1297 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001298 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001299}
1300
drhbc8f0922015-08-22 19:39:04 +00001301/*
drha7714022015-08-29 00:54:49 +00001302** Return the text of a syntax error message on a JSON path. Space is
1303** obtained from sqlite3_malloc().
1304*/
1305static char *jsonPathSyntaxError(const char *zErr){
1306 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1307}
1308
1309/*
1310** Do a node lookup using zPath. Return a pointer to the node on success.
1311** Return NULL if not found or if there is an error.
1312**
1313** On an error, write an error message into pCtx and increment the
1314** pParse->nErr counter.
1315**
1316** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1317** nodes are appended.
drha7714022015-08-29 00:54:49 +00001318*/
1319static JsonNode *jsonLookup(
1320 JsonParse *pParse, /* The JSON to search */
1321 const char *zPath, /* The path to search */
1322 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001323 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001324){
1325 const char *zErr = 0;
1326 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001327 char *zMsg;
drha7714022015-08-29 00:54:49 +00001328
1329 if( zPath==0 ) return 0;
1330 if( zPath[0]!='$' ){
1331 zErr = zPath;
1332 goto lookup_err;
1333 }
1334 zPath++;
drha7714022015-08-29 00:54:49 +00001335 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001336 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001337
1338lookup_err:
1339 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001340 assert( zErr!=0 && pCtx!=0 );
1341 zMsg = jsonPathSyntaxError(zErr);
1342 if( zMsg ){
1343 sqlite3_result_error(pCtx, zMsg, -1);
1344 sqlite3_free(zMsg);
1345 }else{
1346 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001347 }
drha7714022015-08-29 00:54:49 +00001348 return 0;
1349}
1350
1351
1352/*
drhbc8f0922015-08-22 19:39:04 +00001353** Report the wrong number of arguments for json_insert(), json_replace()
1354** or json_set().
1355*/
1356static void jsonWrongNumArgs(
1357 sqlite3_context *pCtx,
1358 const char *zFuncName
1359){
1360 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1361 zFuncName);
1362 sqlite3_result_error(pCtx, zMsg, -1);
1363 sqlite3_free(zMsg);
1364}
drh52216ad2015-08-18 02:28:03 +00001365
drh29c99692017-03-24 12:35:17 +00001366/*
1367** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
1368*/
1369static void jsonRemoveAllNulls(JsonNode *pNode){
1370 int i, n;
1371 assert( pNode->eType==JSON_OBJECT );
1372 n = pNode->n;
1373 for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
1374 switch( pNode[i].eType ){
1375 case JSON_NULL:
1376 pNode[i].jnFlags |= JNODE_REMOVE;
1377 break;
1378 case JSON_OBJECT:
1379 jsonRemoveAllNulls(&pNode[i]);
1380 break;
1381 }
1382 }
1383}
1384
drha7714022015-08-29 00:54:49 +00001385
drh987eb1f2015-08-17 15:17:37 +00001386/****************************************************************************
1387** SQL functions used for testing and debugging
1388****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001389
drh301eecc2015-08-17 20:14:19 +00001390#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001391/*
drh5634cc02015-08-17 11:28:03 +00001392** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001393** a parse of the JSON provided. Or it returns NULL if JSON is not
1394** well-formed.
1395*/
drh5634cc02015-08-17 11:28:03 +00001396static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001397 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001398 int argc,
1399 sqlite3_value **argv
1400){
drh505ad2c2015-08-21 17:33:11 +00001401 JsonString s; /* Output string - not real JSON */
1402 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001403 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001404
1405 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001406 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001407 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001408 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001409 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001410 const char *zType;
1411 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1412 assert( x.aNode[i].eType==JSON_STRING );
1413 zType = "label";
1414 }else{
1415 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001416 }
drh852944e2015-09-10 03:29:11 +00001417 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1418 i, zType, x.aNode[i].n, x.aUp[i]);
1419 if( x.aNode[i].u.zJContent!=0 ){
1420 jsonAppendRaw(&s, " ", 1);
1421 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1422 }
1423 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001424 }
drh505ad2c2015-08-21 17:33:11 +00001425 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001426 jsonResult(&s);
1427}
1428
drh5634cc02015-08-17 11:28:03 +00001429/*
drhf5ddb9c2015-09-11 00:06:41 +00001430** The json_test1(JSON) function return true (1) if the input is JSON
1431** text generated by another json function. It returns (0) if the input
1432** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001433*/
1434static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001435 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001436 int argc,
1437 sqlite3_value **argv
1438){
mistachkin16a93122015-09-11 18:05:01 +00001439 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001440 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001441}
drh301eecc2015-08-17 20:14:19 +00001442#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001443
drh987eb1f2015-08-17 15:17:37 +00001444/****************************************************************************
drhff135ae2015-12-30 01:07:02 +00001445** Scalar SQL function implementations
drh987eb1f2015-08-17 15:17:37 +00001446****************************************************************************/
1447
1448/*
drh2ad96f52016-06-17 13:01:51 +00001449** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
1450** corresponding to the SQL value input. Mostly this means putting
1451** double-quotes around strings and returning the unquoted string "null"
1452** when given a NULL input.
1453*/
1454static void jsonQuoteFunc(
1455 sqlite3_context *ctx,
1456 int argc,
1457 sqlite3_value **argv
1458){
1459 JsonString jx;
drhb0df5402016-08-01 17:06:44 +00001460 UNUSED_PARAM(argc);
drh2ad96f52016-06-17 13:01:51 +00001461
1462 jsonInit(&jx, ctx);
1463 jsonAppendValue(&jx, argv[0]);
1464 jsonResult(&jx);
1465 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1466}
1467
1468/*
drh987eb1f2015-08-17 15:17:37 +00001469** Implementation of the json_array(VALUE,...) function. Return a JSON
1470** array that contains all values given in arguments. Or if any argument
1471** is a BLOB, throw an error.
1472*/
1473static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001474 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001475 int argc,
1476 sqlite3_value **argv
1477){
1478 int i;
drh505ad2c2015-08-21 17:33:11 +00001479 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001480
drhbc8f0922015-08-22 19:39:04 +00001481 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001482 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001483 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001484 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001485 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001486 }
drhd0960592015-08-17 21:22:32 +00001487 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001488 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001489 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001490}
1491
1492
1493/*
1494** json_array_length(JSON)
1495** json_array_length(JSON, PATH)
1496**
1497** Return the number of elements in the top-level JSON array.
1498** Return 0 if the input is not a well-formed JSON array.
1499*/
1500static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001501 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001502 int argc,
1503 sqlite3_value **argv
1504){
drh3fb153c2017-05-11 16:49:59 +00001505 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001506 sqlite3_int64 n = 0;
1507 u32 i;
drha8f39a92015-09-21 22:53:16 +00001508 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001509
drhe35fc302018-08-30 01:52:10 +00001510 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001511 if( p==0 ) return;
1512 assert( p->nNode );
drha8f39a92015-09-21 22:53:16 +00001513 if( argc==2 ){
1514 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drh3fb153c2017-05-11 16:49:59 +00001515 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001516 }else{
drh3fb153c2017-05-11 16:49:59 +00001517 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001518 }
1519 if( pNode==0 ){
drh3fb153c2017-05-11 16:49:59 +00001520 return;
1521 }
1522 if( pNode->eType==JSON_ARRAY ){
drha8f39a92015-09-21 22:53:16 +00001523 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1524 for(i=1; i<=pNode->n; n++){
1525 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001526 }
drh987eb1f2015-08-17 15:17:37 +00001527 }
drh3fb153c2017-05-11 16:49:59 +00001528 sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001529}
1530
1531/*
drh3ad93bb2015-08-29 19:41:45 +00001532** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001533**
drh3ad93bb2015-08-29 19:41:45 +00001534** Return the element described by PATH. Return NULL if there is no
1535** PATH element. If there are multiple PATHs, then return a JSON array
1536** with the result from each path. Throw an error if the JSON or any PATH
1537** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001538*/
1539static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001540 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001541 int argc,
1542 sqlite3_value **argv
1543){
drh3fb153c2017-05-11 16:49:59 +00001544 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001545 JsonNode *pNode;
1546 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001547 JsonString jx;
1548 int i;
1549
1550 if( argc<2 ) return;
drhe35fc302018-08-30 01:52:10 +00001551 p = jsonParseCached(ctx, argv, ctx);
drh3fb153c2017-05-11 16:49:59 +00001552 if( p==0 ) return;
drh3ad93bb2015-08-29 19:41:45 +00001553 jsonInit(&jx, ctx);
1554 jsonAppendChar(&jx, '[');
1555 for(i=1; i<argc; i++){
1556 zPath = (const char*)sqlite3_value_text(argv[i]);
drh3fb153c2017-05-11 16:49:59 +00001557 pNode = jsonLookup(p, zPath, 0, ctx);
1558 if( p->nErr ) break;
drh3ad93bb2015-08-29 19:41:45 +00001559 if( argc>2 ){
1560 jsonAppendSeparator(&jx);
1561 if( pNode ){
1562 jsonRenderNode(pNode, &jx, 0);
1563 }else{
1564 jsonAppendRaw(&jx, "null", 4);
1565 }
1566 }else if( pNode ){
1567 jsonReturn(pNode, ctx, 0);
1568 }
drh987eb1f2015-08-17 15:17:37 +00001569 }
drh3ad93bb2015-08-29 19:41:45 +00001570 if( argc>2 && i==argc ){
1571 jsonAppendChar(&jx, ']');
1572 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001573 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001574 }
1575 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001576}
1577
drh633647a2017-03-22 21:24:31 +00001578/* This is the RFC 7396 MergePatch algorithm.
1579*/
1580static JsonNode *jsonMergePatch(
1581 JsonParse *pParse, /* The JSON parser that contains the TARGET */
mistachkinb1ed7172017-04-14 14:50:34 +00001582 u32 iTarget, /* Node of the TARGET in pParse */
drh633647a2017-03-22 21:24:31 +00001583 JsonNode *pPatch /* The PATCH */
1584){
drh0002d242017-03-23 00:46:15 +00001585 u32 i, j;
1586 u32 iRoot;
drh633647a2017-03-22 21:24:31 +00001587 JsonNode *pTarget;
1588 if( pPatch->eType!=JSON_OBJECT ){
1589 return pPatch;
1590 }
1591 assert( iTarget>=0 && iTarget<pParse->nNode );
1592 pTarget = &pParse->aNode[iTarget];
1593 assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
1594 if( pTarget->eType!=JSON_OBJECT ){
drh29c99692017-03-24 12:35:17 +00001595 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001596 return pPatch;
1597 }
drhbb7aa2d2017-03-23 00:13:52 +00001598 iRoot = iTarget;
drh633647a2017-03-22 21:24:31 +00001599 for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
drhba7cce32017-03-24 19:45:05 +00001600 u32 nKey;
drh633647a2017-03-22 21:24:31 +00001601 const char *zKey;
1602 assert( pPatch[i].eType==JSON_STRING );
1603 assert( pPatch[i].jnFlags & JNODE_LABEL );
1604 nKey = pPatch[i].n;
1605 zKey = pPatch[i].u.zJContent;
drhbb7aa2d2017-03-23 00:13:52 +00001606 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh633647a2017-03-22 21:24:31 +00001607 for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
1608 assert( pTarget[j].eType==JSON_STRING );
1609 assert( pTarget[j].jnFlags & JNODE_LABEL );
drhbb7aa2d2017-03-23 00:13:52 +00001610 assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
drh1fe162f2017-03-23 12:56:44 +00001611 if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
1612 if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
drh633647a2017-03-22 21:24:31 +00001613 if( pPatch[i+1].eType==JSON_NULL ){
1614 pTarget[j+1].jnFlags |= JNODE_REMOVE;
1615 }else{
drhbb7aa2d2017-03-23 00:13:52 +00001616 JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
drh633647a2017-03-22 21:24:31 +00001617 if( pNew==0 ) return 0;
1618 pTarget = &pParse->aNode[iTarget];
1619 if( pNew!=&pTarget[j+1] ){
1620 pTarget[j+1].u.pPatch = pNew;
1621 pTarget[j+1].jnFlags |= JNODE_PATCH;
1622 }
1623 }
1624 break;
1625 }
1626 }
drhbb7aa2d2017-03-23 00:13:52 +00001627 if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
drh633647a2017-03-22 21:24:31 +00001628 int iStart, iPatch;
1629 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
1630 jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
1631 iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
1632 if( pParse->oom ) return 0;
drh29c99692017-03-24 12:35:17 +00001633 jsonRemoveAllNulls(pPatch);
drh633647a2017-03-22 21:24:31 +00001634 pTarget = &pParse->aNode[iTarget];
drhbb7aa2d2017-03-23 00:13:52 +00001635 pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
1636 pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
1637 iRoot = iStart;
drh633647a2017-03-22 21:24:31 +00001638 pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
1639 pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
1640 }
1641 }
1642 return pTarget;
1643}
1644
1645/*
1646** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
1647** object that is the result of running the RFC 7396 MergePatch() algorithm
1648** on the two arguments.
1649*/
drh37f03df2017-03-23 20:33:49 +00001650static void jsonPatchFunc(
drh633647a2017-03-22 21:24:31 +00001651 sqlite3_context *ctx,
1652 int argc,
1653 sqlite3_value **argv
1654){
1655 JsonParse x; /* The JSON that is being patched */
1656 JsonParse y; /* The patch */
drhbb7aa2d2017-03-23 00:13:52 +00001657 JsonNode *pResult; /* The result of the merge */
drh633647a2017-03-22 21:24:31 +00001658
drh2fb79e92017-03-25 12:08:11 +00001659 UNUSED_PARAM(argc);
drh633647a2017-03-22 21:24:31 +00001660 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1661 if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
1662 jsonParseReset(&x);
1663 return;
1664 }
drhbb7aa2d2017-03-23 00:13:52 +00001665 pResult = jsonMergePatch(&x, 0, y.aNode);
1666 assert( pResult!=0 || x.oom );
1667 if( pResult ){
1668 jsonReturnJson(pResult, ctx, 0);
1669 }else{
1670 sqlite3_result_error_nomem(ctx);
1671 }
drh633647a2017-03-22 21:24:31 +00001672 jsonParseReset(&x);
1673 jsonParseReset(&y);
1674}
1675
1676
drh987eb1f2015-08-17 15:17:37 +00001677/*
1678** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1679** object that contains all name/value given in arguments. Or if any name
1680** is not a string or if any value is a BLOB, throw an error.
1681*/
1682static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001683 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001684 int argc,
1685 sqlite3_value **argv
1686){
1687 int i;
drh505ad2c2015-08-21 17:33:11 +00001688 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001689 const char *z;
1690 u32 n;
1691
1692 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001693 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001694 "of arguments", -1);
1695 return;
1696 }
drhbc8f0922015-08-22 19:39:04 +00001697 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001698 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001699 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001700 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001701 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001702 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001703 return;
1704 }
drhd0960592015-08-17 21:22:32 +00001705 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001706 z = (const char*)sqlite3_value_text(argv[i]);
1707 n = (u32)sqlite3_value_bytes(argv[i]);
1708 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001709 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001710 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001711 }
drhd0960592015-08-17 21:22:32 +00001712 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001713 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001714 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001715}
1716
1717
1718/*
drh301eecc2015-08-17 20:14:19 +00001719** json_remove(JSON, PATH, ...)
1720**
drh3ad93bb2015-08-29 19:41:45 +00001721** Remove the named elements from JSON and return the result. malformed
1722** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001723*/
1724static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001725 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001726 int argc,
1727 sqlite3_value **argv
1728){
1729 JsonParse x; /* The parse */
1730 JsonNode *pNode;
1731 const char *zPath;
1732 u32 i;
1733
1734 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001735 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001736 assert( x.nNode );
1737 for(i=1; i<(u32)argc; i++){
1738 zPath = (const char*)sqlite3_value_text(argv[i]);
1739 if( zPath==0 ) goto remove_done;
1740 pNode = jsonLookup(&x, zPath, 0, ctx);
1741 if( x.nErr ) goto remove_done;
1742 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1743 }
1744 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1745 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001746 }
drha7714022015-08-29 00:54:49 +00001747remove_done:
drh505ad2c2015-08-21 17:33:11 +00001748 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001749}
1750
1751/*
1752** json_replace(JSON, PATH, VALUE, ...)
1753**
1754** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001755** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001756*/
1757static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001758 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001759 int argc,
1760 sqlite3_value **argv
1761){
1762 JsonParse x; /* The parse */
1763 JsonNode *pNode;
1764 const char *zPath;
1765 u32 i;
1766
1767 if( argc<1 ) return;
1768 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001769 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001770 return;
1771 }
drhbc8f0922015-08-22 19:39:04 +00001772 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001773 assert( x.nNode );
1774 for(i=1; i<(u32)argc; i+=2){
1775 zPath = (const char*)sqlite3_value_text(argv[i]);
1776 pNode = jsonLookup(&x, zPath, 0, ctx);
1777 if( x.nErr ) goto replace_err;
1778 if( pNode ){
1779 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001780 pNode->u.iReplace = i + 1;
drhd0960592015-08-17 21:22:32 +00001781 }
drha8f39a92015-09-21 22:53:16 +00001782 }
1783 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001784 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001785 }else{
1786 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001787 }
drha7714022015-08-29 00:54:49 +00001788replace_err:
drh505ad2c2015-08-21 17:33:11 +00001789 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001790}
drh505ad2c2015-08-21 17:33:11 +00001791
drh52216ad2015-08-18 02:28:03 +00001792/*
1793** json_set(JSON, PATH, VALUE, ...)
1794**
1795** Set the value at PATH to VALUE. Create the PATH if it does not already
1796** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001797** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001798**
1799** json_insert(JSON, PATH, VALUE, ...)
1800**
1801** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001802** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001803*/
1804static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001805 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001806 int argc,
1807 sqlite3_value **argv
1808){
1809 JsonParse x; /* The parse */
1810 JsonNode *pNode;
1811 const char *zPath;
1812 u32 i;
1813 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001814 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001815
1816 if( argc<1 ) return;
1817 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001818 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001819 return;
1820 }
drhbc8f0922015-08-22 19:39:04 +00001821 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001822 assert( x.nNode );
1823 for(i=1; i<(u32)argc; i+=2){
1824 zPath = (const char*)sqlite3_value_text(argv[i]);
1825 bApnd = 0;
1826 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1827 if( x.oom ){
1828 sqlite3_result_error_nomem(ctx);
1829 goto jsonSetDone;
1830 }else if( x.nErr ){
1831 goto jsonSetDone;
1832 }else if( pNode && (bApnd || bIsSet) ){
1833 pNode->jnFlags |= (u8)JNODE_REPLACE;
drh633647a2017-03-22 21:24:31 +00001834 pNode->u.iReplace = i + 1;
drh52216ad2015-08-18 02:28:03 +00001835 }
drha8f39a92015-09-21 22:53:16 +00001836 }
1837 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drh633647a2017-03-22 21:24:31 +00001838 sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
drha8f39a92015-09-21 22:53:16 +00001839 }else{
1840 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001841 }
drhbc8f0922015-08-22 19:39:04 +00001842jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001843 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001844}
drh301eecc2015-08-17 20:14:19 +00001845
1846/*
drh987eb1f2015-08-17 15:17:37 +00001847** json_type(JSON)
1848** json_type(JSON, PATH)
1849**
drh3ad93bb2015-08-29 19:41:45 +00001850** Return the top-level "type" of a JSON string. Throw an error if
1851** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001852*/
1853static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001854 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001855 int argc,
1856 sqlite3_value **argv
1857){
drhe35fc302018-08-30 01:52:10 +00001858 JsonParse *p; /* The parse */
drh987eb1f2015-08-17 15:17:37 +00001859 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001860 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001861
drhe35fc302018-08-30 01:52:10 +00001862 p = jsonParseCached(ctx, argv, ctx);
1863 if( p==0 ) return;
drha8f39a92015-09-21 22:53:16 +00001864 if( argc==2 ){
1865 zPath = (const char*)sqlite3_value_text(argv[1]);
drhe35fc302018-08-30 01:52:10 +00001866 pNode = jsonLookup(p, zPath, 0, ctx);
drha8f39a92015-09-21 22:53:16 +00001867 }else{
drhe35fc302018-08-30 01:52:10 +00001868 pNode = p->aNode;
drha8f39a92015-09-21 22:53:16 +00001869 }
1870 if( pNode ){
1871 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001872 }
drh987eb1f2015-08-17 15:17:37 +00001873}
drh5634cc02015-08-17 11:28:03 +00001874
drhbc8f0922015-08-22 19:39:04 +00001875/*
1876** json_valid(JSON)
1877**
drh3ad93bb2015-08-29 19:41:45 +00001878** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1879** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001880*/
1881static void jsonValidFunc(
1882 sqlite3_context *ctx,
1883 int argc,
1884 sqlite3_value **argv
1885){
drhe35fc302018-08-30 01:52:10 +00001886 JsonParse *p; /* The parse */
mistachkin16a93122015-09-11 18:05:01 +00001887 UNUSED_PARAM(argc);
drhe35fc302018-08-30 01:52:10 +00001888 p = jsonParseCached(ctx, argv, 0);
1889 sqlite3_result_int(ctx, p!=0);
drhbc8f0922015-08-22 19:39:04 +00001890}
1891
drhff135ae2015-12-30 01:07:02 +00001892
1893/****************************************************************************
1894** Aggregate SQL function implementations
1895****************************************************************************/
1896/*
1897** json_group_array(VALUE)
1898**
1899** Return a JSON array composed of all values in the aggregate.
1900*/
1901static void jsonArrayStep(
1902 sqlite3_context *ctx,
1903 int argc,
1904 sqlite3_value **argv
1905){
1906 JsonString *pStr;
drhdf3a9072016-02-11 15:37:18 +00001907 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00001908 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
1909 if( pStr ){
1910 if( pStr->zBuf==0 ){
1911 jsonInit(pStr, ctx);
1912 jsonAppendChar(pStr, '[');
drhfab5b072019-09-14 00:21:34 +00001913 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00001914 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00001915 }
dan8505d732021-04-14 12:11:39 +00001916 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00001917 jsonAppendValue(pStr, argv[0]);
1918 }
1919}
drh8be47a72018-07-05 20:05:29 +00001920static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00001921 JsonString *pStr;
1922 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
1923 if( pStr ){
1924 pStr->pCtx = ctx;
1925 jsonAppendChar(pStr, ']');
1926 if( pStr->bErr ){
drh4a642b62016-02-05 01:55:27 +00001927 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00001928 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00001929 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00001930 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00001931 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
1932 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00001933 }else{
mistachkined008ec2018-09-12 01:05:26 +00001934 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00001935 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00001936 }
1937 }else{
1938 sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
1939 }
1940 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
1941}
drh8be47a72018-07-05 20:05:29 +00001942static void jsonArrayValue(sqlite3_context *ctx){
1943 jsonArrayCompute(ctx, 0);
1944}
1945static void jsonArrayFinal(sqlite3_context *ctx){
1946 jsonArrayCompute(ctx, 1);
1947}
1948
1949#ifndef SQLITE_OMIT_WINDOWFUNC
1950/*
1951** This method works for both json_group_array() and json_group_object().
1952** It works by removing the first element of the group by searching forward
1953** to the first comma (",") that is not within a string and deleting all
1954** text through that comma.
1955*/
1956static void jsonGroupInverse(
1957 sqlite3_context *ctx,
1958 int argc,
1959 sqlite3_value **argv
1960){
drhe39f3882019-09-21 17:31:03 +00001961 unsigned int i;
drh8be47a72018-07-05 20:05:29 +00001962 int inStr = 0;
drhfab5b072019-09-14 00:21:34 +00001963 int nNest = 0;
drh8be47a72018-07-05 20:05:29 +00001964 char *z;
drhfab5b072019-09-14 00:21:34 +00001965 char c;
drh8be47a72018-07-05 20:05:29 +00001966 JsonString *pStr;
drhc7bf5712018-07-09 22:49:01 +00001967 UNUSED_PARAM(argc);
1968 UNUSED_PARAM(argv);
drh8be47a72018-07-05 20:05:29 +00001969 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
drh491d4c82018-07-07 20:23:46 +00001970#ifdef NEVER
drhfd4b7282018-07-07 19:47:21 +00001971 /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
1972 ** always have been called to initalize it */
1973 if( NEVER(!pStr) ) return;
drh491d4c82018-07-07 20:23:46 +00001974#endif
drh8be47a72018-07-05 20:05:29 +00001975 z = pStr->zBuf;
drh0e5cd342021-04-13 01:12:32 +00001976 for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){
drhfab5b072019-09-14 00:21:34 +00001977 if( c=='"' ){
drh8be47a72018-07-05 20:05:29 +00001978 inStr = !inStr;
drhfab5b072019-09-14 00:21:34 +00001979 }else if( c=='\\' ){
drh8be47a72018-07-05 20:05:29 +00001980 i++;
drhfab5b072019-09-14 00:21:34 +00001981 }else if( !inStr ){
1982 if( c=='{' || c=='[' ) nNest++;
1983 if( c=='}' || c==']' ) nNest--;
drh8be47a72018-07-05 20:05:29 +00001984 }
1985 }
drh0e5cd342021-04-13 01:12:32 +00001986 if( i<pStr->nUsed ){
1987 pStr->nUsed -= i;
1988 memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
1989 z[pStr->nUsed] = 0;
1990 }else{
1991 pStr->nUsed = 1;
1992 }
drh8be47a72018-07-05 20:05:29 +00001993}
1994#else
1995# define jsonGroupInverse 0
1996#endif
1997
drhff135ae2015-12-30 01:07:02 +00001998
1999/*
2000** json_group_obj(NAME,VALUE)
2001**
2002** Return a JSON object composed of all names and values in the aggregate.
2003*/
2004static void jsonObjectStep(
2005 sqlite3_context *ctx,
2006 int argc,
2007 sqlite3_value **argv
2008){
2009 JsonString *pStr;
2010 const char *z;
2011 u32 n;
drhdf3a9072016-02-11 15:37:18 +00002012 UNUSED_PARAM(argc);
drhff135ae2015-12-30 01:07:02 +00002013 pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
2014 if( pStr ){
2015 if( pStr->zBuf==0 ){
2016 jsonInit(pStr, ctx);
2017 jsonAppendChar(pStr, '{');
drhfab5b072019-09-14 00:21:34 +00002018 }else if( pStr->nUsed>1 ){
drhff135ae2015-12-30 01:07:02 +00002019 jsonAppendChar(pStr, ',');
drhff135ae2015-12-30 01:07:02 +00002020 }
drhd2f55772021-05-28 12:15:19 +00002021 pStr->pCtx = ctx;
drhff135ae2015-12-30 01:07:02 +00002022 z = (const char*)sqlite3_value_text(argv[0]);
2023 n = (u32)sqlite3_value_bytes(argv[0]);
2024 jsonAppendString(pStr, z, n);
2025 jsonAppendChar(pStr, ':');
2026 jsonAppendValue(pStr, argv[1]);
2027 }
2028}
drh8be47a72018-07-05 20:05:29 +00002029static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
drhff135ae2015-12-30 01:07:02 +00002030 JsonString *pStr;
2031 pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
2032 if( pStr ){
2033 jsonAppendChar(pStr, '}');
2034 if( pStr->bErr ){
drh6850a632016-11-07 18:18:08 +00002035 if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
drh23079262016-01-01 00:15:59 +00002036 assert( pStr->bStatic );
drh8be47a72018-07-05 20:05:29 +00002037 }else if( isFinal ){
mistachkined008ec2018-09-12 01:05:26 +00002038 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
drhff135ae2015-12-30 01:07:02 +00002039 pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
2040 pStr->bStatic = 1;
drh8be47a72018-07-05 20:05:29 +00002041 }else{
mistachkined008ec2018-09-12 01:05:26 +00002042 sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
drh8be47a72018-07-05 20:05:29 +00002043 pStr->nUsed--;
drhff135ae2015-12-30 01:07:02 +00002044 }
2045 }else{
2046 sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
2047 }
2048 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
2049}
drh8be47a72018-07-05 20:05:29 +00002050static void jsonObjectValue(sqlite3_context *ctx){
2051 jsonObjectCompute(ctx, 0);
2052}
2053static void jsonObjectFinal(sqlite3_context *ctx){
2054 jsonObjectCompute(ctx, 1);
2055}
2056
drhff135ae2015-12-30 01:07:02 +00002057
2058
drhd2975922015-08-29 17:22:33 +00002059#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00002060/****************************************************************************
2061** The json_each virtual table
2062****************************************************************************/
2063typedef struct JsonEachCursor JsonEachCursor;
2064struct JsonEachCursor {
2065 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00002066 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00002067 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00002068 u32 i; /* Index in sParse.aNode[] of current row */
2069 u32 iEnd; /* EOF when i equals or exceeds this value */
2070 u8 eType; /* Type of top-level element */
2071 u8 bRecursive; /* True for json_tree(). False for json_each() */
2072 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00002073 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00002074 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00002075};
2076
2077/* Constructor for the json_each virtual table */
2078static int jsonEachConnect(
2079 sqlite3 *db,
2080 void *pAux,
2081 int argc, const char *const*argv,
2082 sqlite3_vtab **ppVtab,
2083 char **pzErr
2084){
2085 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00002086 int rc;
drhcb6c6c62015-08-19 22:47:17 +00002087
2088/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00002089#define JEACH_KEY 0
2090#define JEACH_VALUE 1
2091#define JEACH_TYPE 2
2092#define JEACH_ATOM 3
2093#define JEACH_ID 4
2094#define JEACH_PARENT 5
2095#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00002096#define JEACH_PATH 7
drh43579192018-11-16 16:04:50 +00002097/* The xBestIndex method assumes that the JSON and ROOT columns are
2098** the last two columns in the table. Should this ever changes, be
2099** sure to update the xBestIndex method. */
drh383de692015-09-10 17:20:57 +00002100#define JEACH_JSON 8
2101#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00002102
drh6fd5c1e2015-08-21 20:37:12 +00002103 UNUSED_PARAM(pzErr);
2104 UNUSED_PARAM(argv);
2105 UNUSED_PARAM(argc);
2106 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00002107 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00002108 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
2109 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00002110 if( rc==SQLITE_OK ){
2111 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
2112 if( pNew==0 ) return SQLITE_NOMEM;
2113 memset(pNew, 0, sizeof(*pNew));
drh2b1c2aa2020-01-07 19:45:40 +00002114 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
drh505ad2c2015-08-21 17:33:11 +00002115 }
2116 return rc;
drhcb6c6c62015-08-19 22:47:17 +00002117}
2118
2119/* destructor for json_each virtual table */
2120static int jsonEachDisconnect(sqlite3_vtab *pVtab){
2121 sqlite3_free(pVtab);
2122 return SQLITE_OK;
2123}
2124
drh505ad2c2015-08-21 17:33:11 +00002125/* constructor for a JsonEachCursor object for json_each(). */
2126static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00002127 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00002128
2129 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00002130 pCur = sqlite3_malloc( sizeof(*pCur) );
2131 if( pCur==0 ) return SQLITE_NOMEM;
2132 memset(pCur, 0, sizeof(*pCur));
2133 *ppCursor = &pCur->base;
2134 return SQLITE_OK;
2135}
2136
drh505ad2c2015-08-21 17:33:11 +00002137/* constructor for a JsonEachCursor object for json_tree(). */
2138static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2139 int rc = jsonEachOpenEach(p, ppCursor);
2140 if( rc==SQLITE_OK ){
2141 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
2142 pCur->bRecursive = 1;
2143 }
2144 return rc;
2145}
2146
drhcb6c6c62015-08-19 22:47:17 +00002147/* Reset a JsonEachCursor back to its original state. Free any memory
2148** held. */
2149static void jsonEachCursorReset(JsonEachCursor *p){
2150 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00002151 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00002152 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00002153 p->iRowid = 0;
2154 p->i = 0;
2155 p->iEnd = 0;
2156 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00002157 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00002158 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002159}
2160
2161/* Destructor for a jsonEachCursor object */
2162static int jsonEachClose(sqlite3_vtab_cursor *cur){
2163 JsonEachCursor *p = (JsonEachCursor*)cur;
2164 jsonEachCursorReset(p);
2165 sqlite3_free(cur);
2166 return SQLITE_OK;
2167}
2168
2169/* Return TRUE if the jsonEachCursor object has been advanced off the end
2170** of the JSON object */
2171static int jsonEachEof(sqlite3_vtab_cursor *cur){
2172 JsonEachCursor *p = (JsonEachCursor*)cur;
2173 return p->i >= p->iEnd;
2174}
2175
drh505ad2c2015-08-21 17:33:11 +00002176/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00002177static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00002178 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00002179 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00002180 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
2181 p->i++;
drh4af352d2015-08-21 20:02:48 +00002182 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00002183 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00002184 u32 iUp = p->sParse.aUp[p->i];
2185 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00002186 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00002187 if( pUp->eType==JSON_ARRAY ){
2188 if( iUp==p->i-1 ){
2189 pUp->u.iKey = 0;
2190 }else{
2191 pUp->u.iKey++;
2192 }
drh4af352d2015-08-21 20:02:48 +00002193 }
2194 }
drh505ad2c2015-08-21 17:33:11 +00002195 }else{
drh4af352d2015-08-21 20:02:48 +00002196 switch( p->eType ){
2197 case JSON_ARRAY: {
2198 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
2199 p->iRowid++;
2200 break;
2201 }
2202 case JSON_OBJECT: {
2203 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
2204 p->iRowid++;
2205 break;
2206 }
2207 default: {
2208 p->i = p->iEnd;
2209 break;
2210 }
drh505ad2c2015-08-21 17:33:11 +00002211 }
2212 }
2213 return SQLITE_OK;
2214}
2215
drh4af352d2015-08-21 20:02:48 +00002216/* Append the name of the path for element i to pStr
2217*/
2218static void jsonEachComputePath(
2219 JsonEachCursor *p, /* The cursor */
2220 JsonString *pStr, /* Write the path here */
2221 u32 i /* Path to this element */
2222){
2223 JsonNode *pNode, *pUp;
2224 u32 iUp;
2225 if( i==0 ){
2226 jsonAppendChar(pStr, '$');
2227 return;
drhcb6c6c62015-08-19 22:47:17 +00002228 }
drh4af352d2015-08-21 20:02:48 +00002229 iUp = p->sParse.aUp[i];
2230 jsonEachComputePath(p, pStr, iUp);
2231 pNode = &p->sParse.aNode[i];
2232 pUp = &p->sParse.aNode[iUp];
2233 if( pUp->eType==JSON_ARRAY ){
2234 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
2235 }else{
2236 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00002237 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00002238 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00002239 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00002240 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
2241 }
drhcb6c6c62015-08-19 22:47:17 +00002242}
2243
2244/* Return the value of a column */
2245static int jsonEachColumn(
2246 sqlite3_vtab_cursor *cur, /* The cursor */
2247 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2248 int i /* Which column to return */
2249){
2250 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00002251 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00002252 switch( i ){
2253 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00002254 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00002255 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00002256 jsonReturn(pThis, ctx, 0);
2257 }else if( p->eType==JSON_ARRAY ){
2258 u32 iKey;
2259 if( p->bRecursive ){
2260 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00002261 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00002262 }else{
2263 iKey = p->iRowid;
2264 }
drh6fd5c1e2015-08-21 20:37:12 +00002265 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00002266 }
2267 break;
2268 }
2269 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00002270 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002271 jsonReturn(pThis, ctx, 0);
2272 break;
2273 }
2274 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00002275 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002276 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
2277 break;
2278 }
2279 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00002280 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00002281 if( pThis->eType>=JSON_ARRAY ) break;
2282 jsonReturn(pThis, ctx, 0);
2283 break;
2284 }
2285 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00002286 sqlite3_result_int64(ctx,
2287 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00002288 break;
2289 }
2290 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00002291 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00002292 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00002293 }
2294 break;
2295 }
drh4af352d2015-08-21 20:02:48 +00002296 case JEACH_FULLKEY: {
2297 JsonString x;
2298 jsonInit(&x, ctx);
2299 if( p->bRecursive ){
2300 jsonEachComputePath(p, &x, p->i);
2301 }else{
drh383de692015-09-10 17:20:57 +00002302 if( p->zRoot ){
2303 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00002304 }else{
2305 jsonAppendChar(&x, '$');
2306 }
2307 if( p->eType==JSON_ARRAY ){
2308 jsonPrintf(30, &x, "[%d]", p->iRowid);
drhdd7460f2018-05-16 12:19:11 +00002309 }else if( p->eType==JSON_OBJECT ){
drh4af352d2015-08-21 20:02:48 +00002310 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
2311 }
2312 }
2313 jsonResult(&x);
2314 break;
2315 }
drhcb6c6c62015-08-19 22:47:17 +00002316 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00002317 if( p->bRecursive ){
2318 JsonString x;
2319 jsonInit(&x, ctx);
2320 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
2321 jsonResult(&x);
2322 break;
drh4af352d2015-08-21 20:02:48 +00002323 }
drh383de692015-09-10 17:20:57 +00002324 /* For json_each() path and root are the same so fall through
2325 ** into the root case */
drh08b92082020-08-10 14:18:00 +00002326 /* no break */ deliberate_fall_through
drh383de692015-09-10 17:20:57 +00002327 }
drh6850a632016-11-07 18:18:08 +00002328 default: {
drh383de692015-09-10 17:20:57 +00002329 const char *zRoot = p->zRoot;
drh6850a632016-11-07 18:18:08 +00002330 if( zRoot==0 ) zRoot = "$";
drh383de692015-09-10 17:20:57 +00002331 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00002332 break;
2333 }
drh3d1d2a92015-09-22 01:15:49 +00002334 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00002335 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00002336 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
2337 break;
2338 }
2339 }
2340 return SQLITE_OK;
2341}
2342
2343/* Return the current rowid value */
2344static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2345 JsonEachCursor *p = (JsonEachCursor*)cur;
2346 *pRowid = p->iRowid;
2347 return SQLITE_OK;
2348}
2349
2350/* The query strategy is to look for an equality constraint on the json
2351** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00002352** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00002353** and 0 otherwise.
2354*/
2355static int jsonEachBestIndex(
2356 sqlite3_vtab *tab,
2357 sqlite3_index_info *pIdxInfo
2358){
drh43579192018-11-16 16:04:50 +00002359 int i; /* Loop counter or computed array index */
2360 int aIdx[2]; /* Index of constraints for JSON and ROOT */
2361 int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
2362 int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
drhcb6c6c62015-08-19 22:47:17 +00002363 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00002364
drh43579192018-11-16 16:04:50 +00002365 /* This implementation assumes that JSON and ROOT are the last two
2366 ** columns in the table */
2367 assert( JEACH_ROOT == JEACH_JSON+1 );
drh6fd5c1e2015-08-21 20:37:12 +00002368 UNUSED_PARAM(tab);
drh43579192018-11-16 16:04:50 +00002369 aIdx[0] = aIdx[1] = -1;
drhcb6c6c62015-08-19 22:47:17 +00002370 pConstraint = pIdxInfo->aConstraint;
2371 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
drh43579192018-11-16 16:04:50 +00002372 int iCol;
2373 int iMask;
2374 if( pConstraint->iColumn < JEACH_JSON ) continue;
2375 iCol = pConstraint->iColumn - JEACH_JSON;
2376 assert( iCol==0 || iCol==1 );
2377 iMask = 1 << iCol;
2378 if( pConstraint->usable==0 ){
2379 unusableMask |= iMask;
2380 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
2381 aIdx[iCol] = i;
2382 idxMask |= iMask;
drhcb6c6c62015-08-19 22:47:17 +00002383 }
2384 }
drh43579192018-11-16 16:04:50 +00002385 if( (unusableMask & ~idxMask)!=0 ){
2386 /* If there are any unusable constraints on JSON or ROOT, then reject
2387 ** this entire plan */
2388 return SQLITE_CONSTRAINT;
2389 }
2390 if( aIdx[0]<0 ){
2391 /* No JSON input. Leave estimatedCost at the huge value that it was
2392 ** initialized to to discourage the query planner from selecting this
2393 ** plan. */
drhcb6c6c62015-08-19 22:47:17 +00002394 pIdxInfo->idxNum = 0;
drhcb6c6c62015-08-19 22:47:17 +00002395 }else{
drh505ad2c2015-08-21 17:33:11 +00002396 pIdxInfo->estimatedCost = 1.0;
drh43579192018-11-16 16:04:50 +00002397 i = aIdx[0];
2398 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
2399 pIdxInfo->aConstraintUsage[i].omit = 1;
2400 if( aIdx[1]<0 ){
2401 pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
drhcb6c6c62015-08-19 22:47:17 +00002402 }else{
drh43579192018-11-16 16:04:50 +00002403 i = aIdx[1];
2404 pIdxInfo->aConstraintUsage[i].argvIndex = 2;
2405 pIdxInfo->aConstraintUsage[i].omit = 1;
2406 pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
drhcb6c6c62015-08-19 22:47:17 +00002407 }
2408 }
2409 return SQLITE_OK;
2410}
2411
2412/* Start a search on a new JSON string */
2413static int jsonEachFilter(
2414 sqlite3_vtab_cursor *cur,
2415 int idxNum, const char *idxStr,
2416 int argc, sqlite3_value **argv
2417){
2418 JsonEachCursor *p = (JsonEachCursor*)cur;
2419 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00002420 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00002421 sqlite3_int64 n;
2422
drh6fd5c1e2015-08-21 20:37:12 +00002423 UNUSED_PARAM(idxStr);
2424 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00002425 jsonEachCursorReset(p);
2426 if( idxNum==0 ) return SQLITE_OK;
2427 z = (const char*)sqlite3_value_text(argv[0]);
2428 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002429 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00002430 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00002431 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00002432 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00002433 if( jsonParse(&p->sParse, 0, p->zJson) ){
2434 int rc = SQLITE_NOMEM;
2435 if( p->sParse.oom==0 ){
2436 sqlite3_free(cur->pVtab->zErrMsg);
2437 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
2438 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
2439 }
drhcb6c6c62015-08-19 22:47:17 +00002440 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002441 return rc;
2442 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
2443 jsonEachCursorReset(p);
2444 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00002445 }else{
drh95677942015-09-24 01:06:37 +00002446 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00002447 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00002448 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00002449 zRoot = (const char*)sqlite3_value_text(argv[1]);
2450 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002451 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00002452 p->zRoot = sqlite3_malloc64( n+1 );
2453 if( p->zRoot==0 ) return SQLITE_NOMEM;
2454 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00002455 if( zRoot[0]!='$' ){
2456 zErr = zRoot;
2457 }else{
2458 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
2459 }
2460 if( zErr ){
drha7714022015-08-29 00:54:49 +00002461 sqlite3_free(cur->pVtab->zErrMsg);
2462 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00002463 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00002464 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
2465 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00002466 return SQLITE_OK;
2467 }
2468 }else{
2469 pNode = p->sParse.aNode;
2470 }
drh852944e2015-09-10 03:29:11 +00002471 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00002472 p->eType = pNode->eType;
2473 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00002474 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00002475 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00002476 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00002477 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00002478 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
2479 p->i--;
2480 }
2481 }else{
2482 p->i++;
2483 }
drhcb6c6c62015-08-19 22:47:17 +00002484 }else{
2485 p->iEnd = p->i+1;
2486 }
2487 }
drha8f39a92015-09-21 22:53:16 +00002488 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00002489}
2490
2491/* The methods of the json_each virtual table */
2492static sqlite3_module jsonEachModule = {
2493 0, /* iVersion */
2494 0, /* xCreate */
2495 jsonEachConnect, /* xConnect */
2496 jsonEachBestIndex, /* xBestIndex */
2497 jsonEachDisconnect, /* xDisconnect */
2498 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00002499 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002500 jsonEachClose, /* xClose - close a cursor */
2501 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002502 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00002503 jsonEachEof, /* xEof - check for end of scan */
2504 jsonEachColumn, /* xColumn - read data */
2505 jsonEachRowid, /* xRowid - read data */
2506 0, /* xUpdate */
2507 0, /* xBegin */
2508 0, /* xSync */
2509 0, /* xCommit */
2510 0, /* xRollback */
2511 0, /* xFindMethod */
2512 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002513 0, /* xSavepoint */
2514 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002515 0, /* xRollbackTo */
2516 0 /* xShadowName */
drhcb6c6c62015-08-19 22:47:17 +00002517};
2518
drh505ad2c2015-08-21 17:33:11 +00002519/* The methods of the json_tree virtual table. */
2520static sqlite3_module jsonTreeModule = {
2521 0, /* iVersion */
2522 0, /* xCreate */
2523 jsonEachConnect, /* xConnect */
2524 jsonEachBestIndex, /* xBestIndex */
2525 jsonEachDisconnect, /* xDisconnect */
2526 0, /* xDestroy */
2527 jsonEachOpenTree, /* xOpen - open a cursor */
2528 jsonEachClose, /* xClose - close a cursor */
2529 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00002530 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00002531 jsonEachEof, /* xEof - check for end of scan */
2532 jsonEachColumn, /* xColumn - read data */
2533 jsonEachRowid, /* xRowid - read data */
2534 0, /* xUpdate */
2535 0, /* xBegin */
2536 0, /* xSync */
2537 0, /* xCommit */
2538 0, /* xRollback */
2539 0, /* xFindMethod */
2540 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00002541 0, /* xSavepoint */
2542 0, /* xRelease */
drh84c501b2018-11-05 23:01:45 +00002543 0, /* xRollbackTo */
2544 0 /* xShadowName */
drh505ad2c2015-08-21 17:33:11 +00002545};
drhd2975922015-08-29 17:22:33 +00002546#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00002547
2548/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00002549** The following routines are the only publically visible identifiers in this
2550** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00002551** functions and the virtual table implemented by this file.
2552****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00002553
drh2f20e132015-09-26 17:44:59 +00002554int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00002555 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00002556 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00002557 static const struct {
2558 const char *zName;
2559 int nArg;
drh52216ad2015-08-18 02:28:03 +00002560 int flag;
drh5fa5c102015-08-12 16:49:40 +00002561 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
2562 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00002563 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00002564 { "json_array", -1, 0, jsonArrayFunc },
2565 { "json_array_length", 1, 0, jsonArrayLengthFunc },
2566 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00002567 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00002568 { "json_insert", -1, 0, jsonSetFunc },
2569 { "json_object", -1, 0, jsonObjectFunc },
drh37f03df2017-03-23 20:33:49 +00002570 { "json_patch", 2, 0, jsonPatchFunc },
drh2ad96f52016-06-17 13:01:51 +00002571 { "json_quote", 1, 0, jsonQuoteFunc },
drh52216ad2015-08-18 02:28:03 +00002572 { "json_remove", -1, 0, jsonRemoveFunc },
2573 { "json_replace", -1, 0, jsonReplaceFunc },
2574 { "json_set", -1, 1, jsonSetFunc },
2575 { "json_type", 1, 0, jsonTypeFunc },
2576 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00002577 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00002578
drh301eecc2015-08-17 20:14:19 +00002579#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00002580 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00002581 { "json_parse", 1, 0, jsonParseFunc },
2582 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00002583#endif
drh5fa5c102015-08-12 16:49:40 +00002584 };
drhff135ae2015-12-30 01:07:02 +00002585 static const struct {
2586 const char *zName;
2587 int nArg;
2588 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
2589 void (*xFinal)(sqlite3_context*);
drh8be47a72018-07-05 20:05:29 +00002590 void (*xValue)(sqlite3_context*);
drhff135ae2015-12-30 01:07:02 +00002591 } aAgg[] = {
drh8be47a72018-07-05 20:05:29 +00002592 { "json_group_array", 1,
2593 jsonArrayStep, jsonArrayFinal, jsonArrayValue },
2594 { "json_group_object", 2,
2595 jsonObjectStep, jsonObjectFinal, jsonObjectValue },
drhff135ae2015-12-30 01:07:02 +00002596 };
drhd2975922015-08-29 17:22:33 +00002597#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002598 static const struct {
2599 const char *zName;
2600 sqlite3_module *pModule;
2601 } aMod[] = {
2602 { "json_each", &jsonEachModule },
2603 { "json_tree", &jsonTreeModule },
2604 };
drhd2975922015-08-29 17:22:33 +00002605#endif
drh79d5bc82020-01-04 01:43:02 +00002606 static const int enc =
2607 SQLITE_UTF8 |
2608 SQLITE_DETERMINISTIC |
2609 SQLITE_INNOCUOUS;
drh5fa5c102015-08-12 16:49:40 +00002610 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
drh79d5bc82020-01-04 01:43:02 +00002611 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
dan01a3b6b2019-09-13 17:05:48 +00002612 (void*)&aFunc[i].flag,
2613 aFunc[i].xFunc, 0, 0);
drh5fa5c102015-08-12 16:49:40 +00002614 }
mistachkin5a193dd2018-07-24 13:57:44 +00002615#ifndef SQLITE_OMIT_WINDOWFUNC
drhff135ae2015-12-30 01:07:02 +00002616 for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
drh8be47a72018-07-05 20:05:29 +00002617 rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
drh79d5bc82020-01-04 01:43:02 +00002618 SQLITE_SUBTYPE | enc, 0,
drh8be47a72018-07-05 20:05:29 +00002619 aAgg[i].xStep, aAgg[i].xFinal,
2620 aAgg[i].xValue, jsonGroupInverse, 0);
drhff135ae2015-12-30 01:07:02 +00002621 }
mistachkin5a193dd2018-07-24 13:57:44 +00002622#endif
drhd2975922015-08-29 17:22:33 +00002623#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002624 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2625 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002626 }
drhd2975922015-08-29 17:22:33 +00002627#endif
drh5fa5c102015-08-12 16:49:40 +00002628 return rc;
2629}
drh2f20e132015-09-26 17:44:59 +00002630
2631
dan8d32e802015-10-14 18:45:42 +00002632#ifndef SQLITE_CORE
drh2f20e132015-09-26 17:44:59 +00002633#ifdef _WIN32
2634__declspec(dllexport)
2635#endif
2636int sqlite3_json_init(
2637 sqlite3 *db,
2638 char **pzErrMsg,
2639 const sqlite3_api_routines *pApi
2640){
2641 SQLITE_EXTENSION_INIT2(pApi);
2642 (void)pzErrMsg; /* Unused parameter */
2643 return sqlite3Json1Init(db);
2644}
dan8d32e802015-10-14 18:45:42 +00002645#endif
drh50065652015-10-08 19:29:18 +00002646#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */