blob: 3dd831f9c572989c5adda6de54671a9066be6870 [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*/
drhf2df7e72015-08-28 20:07:40 +000024#if !defined(_SQLITEINT_H_)
drh5fa5c102015-08-12 16:49:40 +000025#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000026#endif
drh5fa5c102015-08-12 16:49:40 +000027SQLITE_EXTENSION_INIT1
28#include <assert.h>
29#include <string.h>
drhe9c37f32015-08-15 21:25:36 +000030#include <ctype.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
drh6fd5c1e2015-08-21 20:37:12 +000034#define UNUSED_PARAM(X) (void)(X)
35
dan2e8f5512015-09-17 17:21:09 +000036/*
37** Versions of isspace(), isalnum() and isdigit() to which it is safe
38** to pass signed char values.
39*/
40#define safe_isspace(x) isspace((unsigned char)(x))
41#define safe_isdigit(x) isdigit((unsigned char)(x))
42#define safe_isalnum(x) isalnum((unsigned char)(x))
43
drh5fa5c102015-08-12 16:49:40 +000044/* Unsigned integer types */
45typedef sqlite3_uint64 u64;
46typedef unsigned int u32;
47typedef unsigned char u8;
48
drh52216ad2015-08-18 02:28:03 +000049/* Objects */
drh505ad2c2015-08-21 17:33:11 +000050typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000051typedef struct JsonNode JsonNode;
52typedef struct JsonParse JsonParse;
53
drh5634cc02015-08-17 11:28:03 +000054/* An instance of this object represents a JSON string
55** under construction. Really, this is a generic string accumulator
56** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000057*/
drh505ad2c2015-08-21 17:33:11 +000058struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000059 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000060 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000061 u64 nAlloc; /* Bytes of storage available in zBuf[] */
62 u64 nUsed; /* Bytes of zBuf[] currently used */
63 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000064 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000065 char zSpace[100]; /* Initial static space */
66};
67
drhe9c37f32015-08-15 21:25:36 +000068/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000069*/
drhe9c37f32015-08-15 21:25:36 +000070#define JSON_NULL 0
71#define JSON_TRUE 1
72#define JSON_FALSE 2
73#define JSON_INT 3
74#define JSON_REAL 4
75#define JSON_STRING 5
76#define JSON_ARRAY 6
77#define JSON_OBJECT 7
78
drhf5ddb9c2015-09-11 00:06:41 +000079/* The "subtype" set for JSON values */
80#define JSON_SUBTYPE 74 /* Ascii for "J" */
81
drh987eb1f2015-08-17 15:17:37 +000082/*
83** Names of the various JSON types:
84*/
85static const char * const jsonType[] = {
86 "null", "true", "false", "integer", "real", "text", "array", "object"
87};
88
drh301eecc2015-08-17 20:14:19 +000089/* Bit values for the JsonNode.jnFlag field
90*/
91#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
92#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
93#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +000094#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +000095#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drhf5ddb9c2015-09-11 00:06:41 +000096#define JNODE_LABEL 0x20 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +000097
drh987eb1f2015-08-17 15:17:37 +000098
drhe9c37f32015-08-15 21:25:36 +000099/* A single node of parsed JSON
100*/
drhe9c37f32015-08-15 21:25:36 +0000101struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000102 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000103 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +0000104 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +0000105 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000106 union {
drh0042a972015-08-18 12:59:58 +0000107 const char *zJContent; /* Content for INT, REAL, and STRING */
108 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000109 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +0000110 } u;
drhe9c37f32015-08-15 21:25:36 +0000111};
112
113/* A completely parsed JSON string
114*/
drhe9c37f32015-08-15 21:25:36 +0000115struct JsonParse {
116 u32 nNode; /* Number of slots of aNode[] used */
117 u32 nAlloc; /* Number of slots of aNode[] allocated */
118 JsonNode *aNode; /* Array of nodes containing the parse */
119 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000120 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000121 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000122 u8 nErr; /* Number of errors seen */
drhe9c37f32015-08-15 21:25:36 +0000123};
124
drh505ad2c2015-08-21 17:33:11 +0000125/**************************************************************************
126** Utility routines for dealing with JsonString objects
127**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000128
drh505ad2c2015-08-21 17:33:11 +0000129/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000130*/
drh505ad2c2015-08-21 17:33:11 +0000131static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000132 p->zBuf = p->zSpace;
133 p->nAlloc = sizeof(p->zSpace);
134 p->nUsed = 0;
135 p->bStatic = 1;
136}
137
drh505ad2c2015-08-21 17:33:11 +0000138/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000139*/
drh505ad2c2015-08-21 17:33:11 +0000140static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000141 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000142 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000143 jsonZero(p);
144}
145
146
drh505ad2c2015-08-21 17:33:11 +0000147/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000148** initial state.
149*/
drh505ad2c2015-08-21 17:33:11 +0000150static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000151 if( !p->bStatic ) sqlite3_free(p->zBuf);
152 jsonZero(p);
153}
154
155
156/* Report an out-of-memory (OOM) condition
157*/
drh505ad2c2015-08-21 17:33:11 +0000158static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000159 p->bErr = 1;
160 sqlite3_result_error_nomem(p->pCtx);
161 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000162}
163
164/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
165** Return zero on success. Return non-zero on an OOM error
166*/
drh505ad2c2015-08-21 17:33:11 +0000167static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000168 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000169 char *zNew;
170 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000171 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000172 zNew = sqlite3_malloc64(nTotal);
173 if( zNew==0 ){
174 jsonOom(p);
175 return SQLITE_NOMEM;
176 }
drh6fd5c1e2015-08-21 20:37:12 +0000177 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000178 p->zBuf = zNew;
179 p->bStatic = 0;
180 }else{
181 zNew = sqlite3_realloc64(p->zBuf, nTotal);
182 if( zNew==0 ){
183 jsonOom(p);
184 return SQLITE_NOMEM;
185 }
186 p->zBuf = zNew;
187 }
188 p->nAlloc = nTotal;
189 return SQLITE_OK;
190}
191
drh505ad2c2015-08-21 17:33:11 +0000192/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000193*/
drh505ad2c2015-08-21 17:33:11 +0000194static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000195 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
196 memcpy(p->zBuf+p->nUsed, zIn, N);
197 p->nUsed += N;
198}
199
drh4af352d2015-08-21 20:02:48 +0000200/* Append formatted text (not to exceed N bytes) to the JsonString.
201*/
202static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
203 va_list ap;
204 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
205 va_start(ap, zFormat);
206 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
207 va_end(ap);
208 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
209}
210
drh5634cc02015-08-17 11:28:03 +0000211/* Append a single character
212*/
drh505ad2c2015-08-21 17:33:11 +0000213static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000214 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
215 p->zBuf[p->nUsed++] = c;
216}
217
drh301eecc2015-08-17 20:14:19 +0000218/* Append a comma separator to the output buffer, if the previous
219** character is not '[' or '{'.
220*/
drh505ad2c2015-08-21 17:33:11 +0000221static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000222 char c;
223 if( p->nUsed==0 ) return;
224 c = p->zBuf[p->nUsed-1];
225 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
226}
227
drh505ad2c2015-08-21 17:33:11 +0000228/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000229** under construction. Enclose the string in "..." and escape
230** any double-quotes or backslash characters contained within the
231** string.
232*/
drh505ad2c2015-08-21 17:33:11 +0000233static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000234 u32 i;
235 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
236 p->zBuf[p->nUsed++] = '"';
237 for(i=0; i<N; i++){
238 char c = zIn[i];
239 if( c=='"' || c=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000240 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000241 p->zBuf[p->nUsed++] = '\\';
242 }
243 p->zBuf[p->nUsed++] = c;
244 }
245 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000246 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000247}
248
drhd0960592015-08-17 21:22:32 +0000249/*
250** Append a function parameter value to the JSON string under
251** construction.
252*/
253static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000254 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000255 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000256){
257 switch( sqlite3_value_type(pValue) ){
258 case SQLITE_NULL: {
259 jsonAppendRaw(p, "null", 4);
260 break;
261 }
262 case SQLITE_INTEGER:
263 case SQLITE_FLOAT: {
264 const char *z = (const char*)sqlite3_value_text(pValue);
265 u32 n = (u32)sqlite3_value_bytes(pValue);
266 jsonAppendRaw(p, z, n);
267 break;
268 }
269 case SQLITE_TEXT: {
270 const char *z = (const char*)sqlite3_value_text(pValue);
271 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000272 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000273 jsonAppendRaw(p, z, n);
274 }else{
275 jsonAppendString(p, z, n);
276 }
drhd0960592015-08-17 21:22:32 +0000277 break;
278 }
279 default: {
280 if( p->bErr==0 ){
281 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
282 p->bErr = 1;
283 jsonReset(p);
284 }
285 break;
286 }
287 }
288}
289
290
drhbd0621b2015-08-13 13:54:59 +0000291/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000292*/
drh505ad2c2015-08-21 17:33:11 +0000293static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000294 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000295 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
296 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
297 SQLITE_UTF8);
298 jsonZero(p);
299 }
300 assert( p->bStatic );
301}
302
drh505ad2c2015-08-21 17:33:11 +0000303/**************************************************************************
304** Utility routines for dealing with JsonNode and JsonParse objects
305**************************************************************************/
306
307/*
308** Return the number of consecutive JsonNode slots need to represent
309** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
310** OBJECT types, the number might be larger.
311**
312** Appended elements are not counted. The value returned is the number
313** by which the JsonNode counter should increment in order to go to the
314** next peer value.
315*/
316static u32 jsonNodeSize(JsonNode *pNode){
317 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
318}
319
320/*
321** Reclaim all memory allocated by a JsonParse object. But do not
322** delete the JsonParse object itself.
323*/
324static void jsonParseReset(JsonParse *pParse){
325 sqlite3_free(pParse->aNode);
326 pParse->aNode = 0;
327 pParse->nNode = 0;
328 pParse->nAlloc = 0;
329 sqlite3_free(pParse->aUp);
330 pParse->aUp = 0;
331}
332
drh5634cc02015-08-17 11:28:03 +0000333/*
334** Convert the JsonNode pNode into a pure JSON string and
335** append to pOut. Subsubstructure is also included. Return
336** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000337*/
drh52216ad2015-08-18 02:28:03 +0000338static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000339 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000340 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000341 sqlite3_value **aReplace /* Replacement values */
342){
drh5634cc02015-08-17 11:28:03 +0000343 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000344 default: {
345 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000346 jsonAppendRaw(pOut, "null", 4);
347 break;
348 }
349 case JSON_TRUE: {
350 jsonAppendRaw(pOut, "true", 4);
351 break;
352 }
353 case JSON_FALSE: {
354 jsonAppendRaw(pOut, "false", 5);
355 break;
356 }
357 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000358 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000359 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000360 break;
361 }
362 /* Fall through into the next case */
363 }
364 case JSON_REAL:
365 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000366 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000367 break;
368 }
369 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000370 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000371 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000372 for(;;){
373 while( j<=pNode->n ){
374 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
375 if( pNode[j].jnFlags & JNODE_REPLACE ){
376 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000377 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000378 }
379 }else{
drhd0960592015-08-17 21:22:32 +0000380 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000381 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000382 }
drh505ad2c2015-08-21 17:33:11 +0000383 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000384 }
drh52216ad2015-08-18 02:28:03 +0000385 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
386 pNode = &pNode[pNode->u.iAppend];
387 j = 1;
drh5634cc02015-08-17 11:28:03 +0000388 }
389 jsonAppendChar(pOut, ']');
390 break;
391 }
392 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000393 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000394 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000395 for(;;){
396 while( j<=pNode->n ){
397 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
398 jsonAppendSeparator(pOut);
399 jsonRenderNode(&pNode[j], pOut, aReplace);
400 jsonAppendChar(pOut, ':');
401 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000402 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000403 }else{
404 jsonRenderNode(&pNode[j+1], pOut, aReplace);
405 }
drhd0960592015-08-17 21:22:32 +0000406 }
drh505ad2c2015-08-21 17:33:11 +0000407 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000408 }
drh52216ad2015-08-18 02:28:03 +0000409 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
410 pNode = &pNode[pNode->u.iAppend];
411 j = 1;
drh5634cc02015-08-17 11:28:03 +0000412 }
413 jsonAppendChar(pOut, '}');
414 break;
415 }
drhbd0621b2015-08-13 13:54:59 +0000416 }
drh5634cc02015-08-17 11:28:03 +0000417}
418
419/*
drhf2df7e72015-08-28 20:07:40 +0000420** Return a JsonNode and all its descendents as a JSON string.
421*/
422static void jsonReturnJson(
423 JsonNode *pNode, /* Node to return */
424 sqlite3_context *pCtx, /* Return value for this function */
425 sqlite3_value **aReplace /* Array of replacement values */
426){
427 JsonString s;
428 jsonInit(&s, pCtx);
429 jsonRenderNode(pNode, &s, aReplace);
430 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000431 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000432}
433
434/*
drh5634cc02015-08-17 11:28:03 +0000435** Make the JsonNode the return value of the function.
436*/
drhd0960592015-08-17 21:22:32 +0000437static void jsonReturn(
438 JsonNode *pNode, /* Node to return */
439 sqlite3_context *pCtx, /* Return value for this function */
440 sqlite3_value **aReplace /* Array of replacement values */
441){
drh5634cc02015-08-17 11:28:03 +0000442 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000443 default: {
444 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000445 sqlite3_result_null(pCtx);
446 break;
447 }
448 case JSON_TRUE: {
449 sqlite3_result_int(pCtx, 1);
450 break;
451 }
452 case JSON_FALSE: {
453 sqlite3_result_int(pCtx, 0);
454 break;
455 }
drh987eb1f2015-08-17 15:17:37 +0000456 case JSON_REAL: {
drh52216ad2015-08-18 02:28:03 +0000457 double r = strtod(pNode->u.zJContent, 0);
drh987eb1f2015-08-17 15:17:37 +0000458 sqlite3_result_double(pCtx, r);
drh5634cc02015-08-17 11:28:03 +0000459 break;
460 }
drh987eb1f2015-08-17 15:17:37 +0000461 case JSON_INT: {
462 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000463 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000464 if( z[0]=='-' ){ z++; }
465 while( z[0]>='0' && z[0]<='9' ){ i = i*10 + *(z++) - '0'; }
drh52216ad2015-08-18 02:28:03 +0000466 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000467 sqlite3_result_int64(pCtx, i);
468 break;
469 }
drh5634cc02015-08-17 11:28:03 +0000470 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000471#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
472 ** json_insert() and json_replace() and those routines do not
473 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000474 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000475 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
476 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000477 }else
478#endif
479 assert( (pNode->jnFlags & JNODE_RAW)==0 );
480 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000481 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000482 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000483 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000484 }else{
485 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000486 u32 i;
487 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000488 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000489 char *zOut;
490 u32 j;
491 zOut = sqlite3_malloc( n+1 );
492 if( zOut==0 ){
493 sqlite3_result_error_nomem(pCtx);
494 break;
495 }
496 for(i=1, j=0; i<n-1; i++){
497 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000498 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000499 zOut[j++] = c;
500 }else{
501 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000502 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000503 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000504 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000505 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000506 if( c>='0' && c<='9' ) v = v*16 + c - '0';
507 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
508 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
509 else break;
drh987eb1f2015-08-17 15:17:37 +0000510 }
drh80d87402015-08-24 12:42:41 +0000511 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000512 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000513 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000514 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000515 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000516 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000517 }else{
mistachkin16a93122015-09-11 18:05:01 +0000518 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000519 zOut[j++] = 0x80 | ((v>>6)&0x3f);
520 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000521 }
522 }else{
523 if( c=='b' ){
524 c = '\b';
525 }else if( c=='f' ){
526 c = '\f';
527 }else if( c=='n' ){
528 c = '\n';
529 }else if( c=='r' ){
530 c = '\r';
531 }else if( c=='t' ){
532 c = '\t';
533 }
534 zOut[j++] = c;
535 }
536 }
537 }
538 zOut[j] = 0;
539 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000540 }
541 break;
542 }
543 case JSON_ARRAY:
544 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000545 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000546 break;
547 }
548 }
drhbd0621b2015-08-13 13:54:59 +0000549}
550
drh5fa5c102015-08-12 16:49:40 +0000551/*
drhe9c37f32015-08-15 21:25:36 +0000552** Create a new JsonNode instance based on the arguments and append that
553** instance to the JsonParse. Return the index in pParse->aNode[] of the
554** new node, or -1 if a memory allocation fails.
555*/
556static int jsonParseAddNode(
557 JsonParse *pParse, /* Append the node to this object */
558 u32 eType, /* Node type */
559 u32 n, /* Content size or sub-node count */
560 const char *zContent /* Content */
561){
562 JsonNode *p;
563 if( pParse->nNode>=pParse->nAlloc ){
564 u32 nNew;
565 JsonNode *pNew;
566 if( pParse->oom ) return -1;
567 nNew = pParse->nAlloc*2 + 10;
drhe9c37f32015-08-15 21:25:36 +0000568 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
569 if( pNew==0 ){
570 pParse->oom = 1;
571 return -1;
572 }
573 pParse->nAlloc = nNew;
574 pParse->aNode = pNew;
575 }
576 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000577 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000578 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000579 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000580 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000581 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000582 return pParse->nNode++;
583}
584
585/*
586** Parse a single JSON value which begins at pParse->zJson[i]. Return the
587** index of the first character past the end of the value parsed.
588**
589** Return negative for a syntax error. Special cases: return -2 if the
590** first non-whitespace character is '}' and return -3 if the first
591** non-whitespace character is ']'.
592*/
593static int jsonParseValue(JsonParse *pParse, u32 i){
594 char c;
595 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000596 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000597 int x;
drh852944e2015-09-10 03:29:11 +0000598 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000599 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drhe9c37f32015-08-15 21:25:36 +0000600 if( (c = pParse->zJson[i])==0 ) return 0;
601 if( c=='{' ){
602 /* Parse object */
603 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000604 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000605 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000606 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000607 x = jsonParseValue(pParse, j);
608 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000609 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000610 return -1;
611 }
drhbe9474e2015-08-22 03:05:54 +0000612 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000613 pNode = &pParse->aNode[pParse->nNode-1];
614 if( pNode->eType!=JSON_STRING ) return -1;
615 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000616 j = x;
dan2e8f5512015-09-17 17:21:09 +0000617 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000618 if( pParse->zJson[j]!=':' ) return -1;
619 j++;
620 x = jsonParseValue(pParse, j);
621 if( x<0 ) return -1;
622 j = x;
dan2e8f5512015-09-17 17:21:09 +0000623 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000624 c = pParse->zJson[j];
625 if( c==',' ) continue;
626 if( c!='}' ) return -1;
627 break;
628 }
drhbc8f0922015-08-22 19:39:04 +0000629 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000630 return j+1;
631 }else if( c=='[' ){
632 /* Parse array */
633 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000634 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000635 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000636 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000637 x = jsonParseValue(pParse, j);
638 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000639 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000640 return -1;
641 }
642 j = x;
dan2e8f5512015-09-17 17:21:09 +0000643 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000644 c = pParse->zJson[j];
645 if( c==',' ) continue;
646 if( c!=']' ) return -1;
647 break;
648 }
drhbc8f0922015-08-22 19:39:04 +0000649 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000650 return j+1;
651 }else if( c=='"' ){
652 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000653 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000654 j = i+1;
655 for(;;){
656 c = pParse->zJson[j];
657 if( c==0 ) return -1;
658 if( c=='\\' ){
659 c = pParse->zJson[++j];
660 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000661 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000662 }else if( c=='"' ){
663 break;
664 }
665 j++;
666 }
667 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000668 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000669 return j+1;
670 }else if( c=='n'
671 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000672 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000673 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
674 return i+4;
675 }else if( c=='t'
676 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000677 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000678 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
679 return i+4;
680 }else if( c=='f'
681 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000682 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000683 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
684 return i+5;
685 }else if( c=='-' || (c>='0' && c<='9') ){
686 /* Parse number */
687 u8 seenDP = 0;
688 u8 seenE = 0;
689 j = i+1;
690 for(;; j++){
691 c = pParse->zJson[j];
692 if( c>='0' && c<='9' ) continue;
693 if( c=='.' ){
694 if( pParse->zJson[j-1]=='-' ) return -1;
695 if( seenDP ) return -1;
696 seenDP = 1;
697 continue;
698 }
699 if( c=='e' || c=='E' ){
700 if( pParse->zJson[j-1]<'0' ) return -1;
701 if( seenE ) return -1;
702 seenDP = seenE = 1;
703 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000704 if( c=='+' || c=='-' ){
705 j++;
706 c = pParse->zJson[j+1];
707 }
drhd1f00682015-08-29 16:02:37 +0000708 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000709 continue;
710 }
711 break;
712 }
713 if( pParse->zJson[j-1]<'0' ) return -1;
714 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
715 j - i, &pParse->zJson[i]);
716 return j;
717 }else if( c=='}' ){
718 return -2; /* End of {...} */
719 }else if( c==']' ){
720 return -3; /* End of [...] */
721 }else{
722 return -1; /* Syntax error */
723 }
724}
725
726/*
727** Parse a complete JSON string. Return 0 on success or non-zero if there
728** are any errors. If an error occurs, free all memory associated with
729** pParse.
730**
731** pParse is uninitialized when this routine is called.
732*/
drhbc8f0922015-08-22 19:39:04 +0000733static int jsonParse(
734 JsonParse *pParse, /* Initialize and fill this JsonParse object */
735 sqlite3_context *pCtx, /* Report errors here */
736 const char *zJson /* Input JSON text to be parsed */
737){
drhe9c37f32015-08-15 21:25:36 +0000738 int i;
drhe9c37f32015-08-15 21:25:36 +0000739 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000740 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000741 pParse->zJson = zJson;
742 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000743 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000744 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000745 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000746 if( zJson[i] ) i = -1;
747 }
drhd1f00682015-08-29 16:02:37 +0000748 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000749 if( pCtx!=0 ){
750 if( pParse->oom ){
751 sqlite3_result_error_nomem(pCtx);
752 }else{
753 sqlite3_result_error(pCtx, "malformed JSON", -1);
754 }
755 }
drh505ad2c2015-08-21 17:33:11 +0000756 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000757 return 1;
758 }
759 return 0;
760}
drh301eecc2015-08-17 20:14:19 +0000761
drh505ad2c2015-08-21 17:33:11 +0000762/* Mark node i of pParse as being a child of iParent. Call recursively
763** to fill in all the descendants of node i.
764*/
765static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
766 JsonNode *pNode = &pParse->aNode[i];
767 u32 j;
768 pParse->aUp[i] = iParent;
769 switch( pNode->eType ){
770 case JSON_ARRAY: {
771 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
772 jsonParseFillInParentage(pParse, i+j, i);
773 }
774 break;
775 }
776 case JSON_OBJECT: {
777 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
778 pParse->aUp[i+j] = i;
779 jsonParseFillInParentage(pParse, i+j+1, i);
780 }
781 break;
782 }
783 default: {
784 break;
785 }
786 }
787}
788
789/*
790** Compute the parentage of all nodes in a completed parse.
791*/
792static int jsonParseFindParents(JsonParse *pParse){
793 u32 *aUp;
794 assert( pParse->aUp==0 );
795 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000796 if( aUp==0 ){
797 pParse->oom = 1;
798 return SQLITE_NOMEM;
799 }
drh505ad2c2015-08-21 17:33:11 +0000800 jsonParseFillInParentage(pParse, 0, 0);
801 return SQLITE_OK;
802}
803
drh8cb0c832015-09-22 00:21:03 +0000804/*
805** Compare the OBJECT label at pNode against zKey,nKey. Return true on
806** a match.
807*/
808static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
809 if( pNode->jnFlags & JNODE_RAW ){
810 if( pNode->n!=nKey ) return 0;
811 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
812 }else{
813 if( pNode->n!=nKey+2 ) return 0;
814 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
815 }
816}
817
drh52216ad2015-08-18 02:28:03 +0000818/* forward declaration */
drha7714022015-08-29 00:54:49 +0000819static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000820
drh987eb1f2015-08-17 15:17:37 +0000821/*
822** Search along zPath to find the node specified. Return a pointer
823** to that node, or NULL if zPath is malformed or if there is no such
824** node.
drh52216ad2015-08-18 02:28:03 +0000825**
826** If pApnd!=0, then try to append new nodes to complete zPath if it is
827** possible to do so and if no existing node corresponds to zPath. If
828** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000829*/
drha7714022015-08-29 00:54:49 +0000830static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000831 JsonParse *pParse, /* The JSON to search */
832 u32 iRoot, /* Begin the search at this node */
833 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000834 int *pApnd, /* Append nodes to complete path if not NULL */
835 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000836){
drhbc8f0922015-08-22 19:39:04 +0000837 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000838 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000839 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000840 if( zPath[0]==0 ) return pRoot;
841 if( zPath[0]=='.' ){
842 if( pRoot->eType!=JSON_OBJECT ) return 0;
843 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000844 if( zPath[0]=='"' ){
845 zKey = zPath + 1;
846 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
847 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000848 if( zPath[i] ){
849 i++;
850 }else{
851 *pzErr = zPath;
852 return 0;
853 }
drh6b43cc82015-08-19 23:02:49 +0000854 }else{
855 zKey = zPath;
856 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
857 nKey = i;
858 }
drha7714022015-08-29 00:54:49 +0000859 if( nKey==0 ){
860 *pzErr = zPath;
861 return 0;
862 }
drh987eb1f2015-08-17 15:17:37 +0000863 j = 1;
drh52216ad2015-08-18 02:28:03 +0000864 for(;;){
865 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000866 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000867 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000868 }
869 j++;
drh505ad2c2015-08-21 17:33:11 +0000870 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000871 }
drh52216ad2015-08-18 02:28:03 +0000872 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
873 iRoot += pRoot->u.iAppend;
874 pRoot = &pParse->aNode[iRoot];
875 j = 1;
876 }
877 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000878 u32 iStart, iLabel;
879 JsonNode *pNode;
880 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
881 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000882 zPath += i;
drha7714022015-08-29 00:54:49 +0000883 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000884 if( pParse->oom ) return 0;
885 if( pNode ){
886 pRoot = &pParse->aNode[iRoot];
887 pRoot->u.iAppend = iStart - iRoot;
888 pRoot->jnFlags |= JNODE_APPEND;
889 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
890 }
891 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000892 }
dan2e8f5512015-09-17 17:21:09 +0000893 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000894 if( pRoot->eType!=JSON_ARRAY ) return 0;
895 i = 0;
drh3d1d2a92015-09-22 01:15:49 +0000896 j = 1;
897 while( safe_isdigit(zPath[j]) ){
898 i = i*10 + zPath[j] - '0';
899 j++;
drh987eb1f2015-08-17 15:17:37 +0000900 }
drh3d1d2a92015-09-22 01:15:49 +0000901 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +0000902 *pzErr = zPath;
903 return 0;
904 }
drh3d1d2a92015-09-22 01:15:49 +0000905 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +0000906 j = 1;
drh52216ad2015-08-18 02:28:03 +0000907 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000908 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
909 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000910 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000911 }
912 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
913 iRoot += pRoot->u.iAppend;
914 pRoot = &pParse->aNode[iRoot];
915 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000916 }
917 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000918 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000919 }
920 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000921 u32 iStart;
922 JsonNode *pNode;
923 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +0000924 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000925 if( pParse->oom ) return 0;
926 if( pNode ){
927 pRoot = &pParse->aNode[iRoot];
928 pRoot->u.iAppend = iStart - iRoot;
929 pRoot->jnFlags |= JNODE_APPEND;
930 }
931 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000932 }
drh3d1d2a92015-09-22 01:15:49 +0000933 }else{
drha7714022015-08-29 00:54:49 +0000934 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +0000935 }
936 return 0;
937}
938
drh52216ad2015-08-18 02:28:03 +0000939/*
drhbc8f0922015-08-22 19:39:04 +0000940** Append content to pParse that will complete zPath. Return a pointer
941** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000942*/
943static JsonNode *jsonLookupAppend(
944 JsonParse *pParse, /* Append content to the JSON parse */
945 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +0000946 int *pApnd, /* Set this flag to 1 */
947 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +0000948){
949 *pApnd = 1;
950 if( zPath[0]==0 ){
951 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
952 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
953 }
954 if( zPath[0]=='.' ){
955 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
956 }else if( strncmp(zPath,"[0]",3)==0 ){
957 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
958 }else{
959 return 0;
960 }
961 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +0000962 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000963}
964
drhbc8f0922015-08-22 19:39:04 +0000965/*
drha7714022015-08-29 00:54:49 +0000966** Return the text of a syntax error message on a JSON path. Space is
967** obtained from sqlite3_malloc().
968*/
969static char *jsonPathSyntaxError(const char *zErr){
970 return sqlite3_mprintf("JSON path error near '%q'", zErr);
971}
972
973/*
974** Do a node lookup using zPath. Return a pointer to the node on success.
975** Return NULL if not found or if there is an error.
976**
977** On an error, write an error message into pCtx and increment the
978** pParse->nErr counter.
979**
980** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
981** nodes are appended.
drha7714022015-08-29 00:54:49 +0000982*/
983static JsonNode *jsonLookup(
984 JsonParse *pParse, /* The JSON to search */
985 const char *zPath, /* The path to search */
986 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +0000987 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +0000988){
989 const char *zErr = 0;
990 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +0000991 char *zMsg;
drha7714022015-08-29 00:54:49 +0000992
993 if( zPath==0 ) return 0;
994 if( zPath[0]!='$' ){
995 zErr = zPath;
996 goto lookup_err;
997 }
998 zPath++;
drha7714022015-08-29 00:54:49 +0000999 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001000 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001001
1002lookup_err:
1003 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001004 assert( zErr!=0 && pCtx!=0 );
1005 zMsg = jsonPathSyntaxError(zErr);
1006 if( zMsg ){
1007 sqlite3_result_error(pCtx, zMsg, -1);
1008 sqlite3_free(zMsg);
1009 }else{
1010 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001011 }
drha7714022015-08-29 00:54:49 +00001012 return 0;
1013}
1014
1015
1016/*
drhbc8f0922015-08-22 19:39:04 +00001017** Report the wrong number of arguments for json_insert(), json_replace()
1018** or json_set().
1019*/
1020static void jsonWrongNumArgs(
1021 sqlite3_context *pCtx,
1022 const char *zFuncName
1023){
1024 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1025 zFuncName);
1026 sqlite3_result_error(pCtx, zMsg, -1);
1027 sqlite3_free(zMsg);
1028}
drh52216ad2015-08-18 02:28:03 +00001029
drha7714022015-08-29 00:54:49 +00001030
drh987eb1f2015-08-17 15:17:37 +00001031/****************************************************************************
1032** SQL functions used for testing and debugging
1033****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001034
drh301eecc2015-08-17 20:14:19 +00001035#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001036/*
drh5634cc02015-08-17 11:28:03 +00001037** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001038** a parse of the JSON provided. Or it returns NULL if JSON is not
1039** well-formed.
1040*/
drh5634cc02015-08-17 11:28:03 +00001041static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001042 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001043 int argc,
1044 sqlite3_value **argv
1045){
drh505ad2c2015-08-21 17:33:11 +00001046 JsonString s; /* Output string - not real JSON */
1047 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001048 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001049
1050 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001051 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001052 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001053 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001054 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001055 const char *zType;
1056 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1057 assert( x.aNode[i].eType==JSON_STRING );
1058 zType = "label";
1059 }else{
1060 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001061 }
drh852944e2015-09-10 03:29:11 +00001062 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1063 i, zType, x.aNode[i].n, x.aUp[i]);
1064 if( x.aNode[i].u.zJContent!=0 ){
1065 jsonAppendRaw(&s, " ", 1);
1066 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1067 }
1068 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001069 }
drh505ad2c2015-08-21 17:33:11 +00001070 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001071 jsonResult(&s);
1072}
1073
drh5634cc02015-08-17 11:28:03 +00001074/*
drhf5ddb9c2015-09-11 00:06:41 +00001075** The json_test1(JSON) function return true (1) if the input is JSON
1076** text generated by another json function. It returns (0) if the input
1077** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001078*/
1079static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001080 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001081 int argc,
1082 sqlite3_value **argv
1083){
mistachkin16a93122015-09-11 18:05:01 +00001084 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001085 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001086}
drh301eecc2015-08-17 20:14:19 +00001087#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001088
drh987eb1f2015-08-17 15:17:37 +00001089/****************************************************************************
1090** SQL function implementations
1091****************************************************************************/
1092
1093/*
1094** Implementation of the json_array(VALUE,...) function. Return a JSON
1095** array that contains all values given in arguments. Or if any argument
1096** is a BLOB, throw an error.
1097*/
1098static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001099 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001100 int argc,
1101 sqlite3_value **argv
1102){
1103 int i;
drh505ad2c2015-08-21 17:33:11 +00001104 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001105
drhbc8f0922015-08-22 19:39:04 +00001106 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001107 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001108 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001109 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001110 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001111 }
drhd0960592015-08-17 21:22:32 +00001112 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001113 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001114 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001115}
1116
1117
1118/*
1119** json_array_length(JSON)
1120** json_array_length(JSON, PATH)
1121**
1122** Return the number of elements in the top-level JSON array.
1123** Return 0 if the input is not a well-formed JSON array.
1124*/
1125static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001126 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001127 int argc,
1128 sqlite3_value **argv
1129){
1130 JsonParse x; /* The parse */
1131 sqlite3_int64 n = 0;
1132 u32 i;
drha8f39a92015-09-21 22:53:16 +00001133 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001134
drhf2df7e72015-08-28 20:07:40 +00001135 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001136 assert( x.nNode );
1137 if( argc==2 ){
1138 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1139 pNode = jsonLookup(&x, zPath, 0, ctx);
1140 }else{
1141 pNode = x.aNode;
1142 }
1143 if( pNode==0 ){
1144 x.nErr = 1;
1145 }else if( pNode->eType==JSON_ARRAY ){
1146 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1147 for(i=1; i<=pNode->n; n++){
1148 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001149 }
drh987eb1f2015-08-17 15:17:37 +00001150 }
drha7714022015-08-29 00:54:49 +00001151 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001152 jsonParseReset(&x);
1153}
1154
1155/*
drh3ad93bb2015-08-29 19:41:45 +00001156** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001157**
drh3ad93bb2015-08-29 19:41:45 +00001158** Return the element described by PATH. Return NULL if there is no
1159** PATH element. If there are multiple PATHs, then return a JSON array
1160** with the result from each path. Throw an error if the JSON or any PATH
1161** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001162*/
1163static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001164 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001165 int argc,
1166 sqlite3_value **argv
1167){
1168 JsonParse x; /* The parse */
1169 JsonNode *pNode;
1170 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001171 JsonString jx;
1172 int i;
1173
1174 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001175 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001176 jsonInit(&jx, ctx);
1177 jsonAppendChar(&jx, '[');
1178 for(i=1; i<argc; i++){
1179 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001180 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001181 if( x.nErr ) break;
1182 if( argc>2 ){
1183 jsonAppendSeparator(&jx);
1184 if( pNode ){
1185 jsonRenderNode(pNode, &jx, 0);
1186 }else{
1187 jsonAppendRaw(&jx, "null", 4);
1188 }
1189 }else if( pNode ){
1190 jsonReturn(pNode, ctx, 0);
1191 }
drh987eb1f2015-08-17 15:17:37 +00001192 }
drh3ad93bb2015-08-29 19:41:45 +00001193 if( argc>2 && i==argc ){
1194 jsonAppendChar(&jx, ']');
1195 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001196 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001197 }
1198 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001199 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001200}
1201
1202/*
1203** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1204** object that contains all name/value given in arguments. Or if any name
1205** is not a string or if any value is a BLOB, throw an error.
1206*/
1207static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001208 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001209 int argc,
1210 sqlite3_value **argv
1211){
1212 int i;
drh505ad2c2015-08-21 17:33:11 +00001213 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001214 const char *z;
1215 u32 n;
1216
1217 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001218 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001219 "of arguments", -1);
1220 return;
1221 }
drhbc8f0922015-08-22 19:39:04 +00001222 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001223 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001224 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001225 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001226 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001227 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001228 return;
1229 }
drhd0960592015-08-17 21:22:32 +00001230 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001231 z = (const char*)sqlite3_value_text(argv[i]);
1232 n = (u32)sqlite3_value_bytes(argv[i]);
1233 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001234 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001235 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001236 }
drhd0960592015-08-17 21:22:32 +00001237 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001238 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001239 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001240}
1241
1242
1243/*
drh301eecc2015-08-17 20:14:19 +00001244** json_remove(JSON, PATH, ...)
1245**
drh3ad93bb2015-08-29 19:41:45 +00001246** Remove the named elements from JSON and return the result. malformed
1247** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001248*/
1249static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001250 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001251 int argc,
1252 sqlite3_value **argv
1253){
1254 JsonParse x; /* The parse */
1255 JsonNode *pNode;
1256 const char *zPath;
1257 u32 i;
1258
1259 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001260 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001261 assert( x.nNode );
1262 for(i=1; i<(u32)argc; i++){
1263 zPath = (const char*)sqlite3_value_text(argv[i]);
1264 if( zPath==0 ) goto remove_done;
1265 pNode = jsonLookup(&x, zPath, 0, ctx);
1266 if( x.nErr ) goto remove_done;
1267 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1268 }
1269 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1270 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001271 }
drha7714022015-08-29 00:54:49 +00001272remove_done:
drh505ad2c2015-08-21 17:33:11 +00001273 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001274}
1275
1276/*
1277** json_replace(JSON, PATH, VALUE, ...)
1278**
1279** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001280** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001281*/
1282static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001283 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001284 int argc,
1285 sqlite3_value **argv
1286){
1287 JsonParse x; /* The parse */
1288 JsonNode *pNode;
1289 const char *zPath;
1290 u32 i;
1291
1292 if( argc<1 ) return;
1293 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001294 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001295 return;
1296 }
drhbc8f0922015-08-22 19:39:04 +00001297 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001298 assert( x.nNode );
1299 for(i=1; i<(u32)argc; i+=2){
1300 zPath = (const char*)sqlite3_value_text(argv[i]);
1301 pNode = jsonLookup(&x, zPath, 0, ctx);
1302 if( x.nErr ) goto replace_err;
1303 if( pNode ){
1304 pNode->jnFlags |= (u8)JNODE_REPLACE;
1305 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001306 }
drha8f39a92015-09-21 22:53:16 +00001307 }
1308 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1309 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1310 }else{
1311 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001312 }
drha7714022015-08-29 00:54:49 +00001313replace_err:
drh505ad2c2015-08-21 17:33:11 +00001314 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001315}
drh505ad2c2015-08-21 17:33:11 +00001316
drh52216ad2015-08-18 02:28:03 +00001317/*
1318** json_set(JSON, PATH, VALUE, ...)
1319**
1320** Set the value at PATH to VALUE. Create the PATH if it does not already
1321** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001322** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001323**
1324** json_insert(JSON, PATH, VALUE, ...)
1325**
1326** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001327** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001328*/
1329static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001330 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001331 int argc,
1332 sqlite3_value **argv
1333){
1334 JsonParse x; /* The parse */
1335 JsonNode *pNode;
1336 const char *zPath;
1337 u32 i;
1338 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001339 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001340
1341 if( argc<1 ) return;
1342 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001343 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001344 return;
1345 }
drhbc8f0922015-08-22 19:39:04 +00001346 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001347 assert( x.nNode );
1348 for(i=1; i<(u32)argc; i+=2){
1349 zPath = (const char*)sqlite3_value_text(argv[i]);
1350 bApnd = 0;
1351 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1352 if( x.oom ){
1353 sqlite3_result_error_nomem(ctx);
1354 goto jsonSetDone;
1355 }else if( x.nErr ){
1356 goto jsonSetDone;
1357 }else if( pNode && (bApnd || bIsSet) ){
1358 pNode->jnFlags |= (u8)JNODE_REPLACE;
1359 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001360 }
drha8f39a92015-09-21 22:53:16 +00001361 }
1362 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1363 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1364 }else{
1365 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001366 }
drhbc8f0922015-08-22 19:39:04 +00001367jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001368 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001369}
drh301eecc2015-08-17 20:14:19 +00001370
1371/*
drh987eb1f2015-08-17 15:17:37 +00001372** json_type(JSON)
1373** json_type(JSON, PATH)
1374**
drh3ad93bb2015-08-29 19:41:45 +00001375** Return the top-level "type" of a JSON string. Throw an error if
1376** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001377*/
1378static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001379 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001380 int argc,
1381 sqlite3_value **argv
1382){
1383 JsonParse x; /* The parse */
1384 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001385 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001386
drhbc8f0922015-08-22 19:39:04 +00001387 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001388 assert( x.nNode );
1389 if( argc==2 ){
1390 zPath = (const char*)sqlite3_value_text(argv[1]);
1391 pNode = jsonLookup(&x, zPath, 0, ctx);
1392 }else{
1393 pNode = x.aNode;
1394 }
1395 if( pNode ){
1396 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001397 }
drh505ad2c2015-08-21 17:33:11 +00001398 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001399}
drh5634cc02015-08-17 11:28:03 +00001400
drhbc8f0922015-08-22 19:39:04 +00001401/*
1402** json_valid(JSON)
1403**
drh3ad93bb2015-08-29 19:41:45 +00001404** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1405** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001406*/
1407static void jsonValidFunc(
1408 sqlite3_context *ctx,
1409 int argc,
1410 sqlite3_value **argv
1411){
1412 JsonParse x; /* The parse */
1413 int rc = 0;
1414
mistachkin16a93122015-09-11 18:05:01 +00001415 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001416 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001417 rc = 1;
1418 }
1419 jsonParseReset(&x);
1420 sqlite3_result_int(ctx, rc);
1421}
1422
drhd2975922015-08-29 17:22:33 +00001423#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001424/****************************************************************************
1425** The json_each virtual table
1426****************************************************************************/
1427typedef struct JsonEachCursor JsonEachCursor;
1428struct JsonEachCursor {
1429 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001430 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001431 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001432 u32 i; /* Index in sParse.aNode[] of current row */
1433 u32 iEnd; /* EOF when i equals or exceeds this value */
1434 u8 eType; /* Type of top-level element */
1435 u8 bRecursive; /* True for json_tree(). False for json_each() */
1436 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001437 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001438 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001439};
1440
1441/* Constructor for the json_each virtual table */
1442static int jsonEachConnect(
1443 sqlite3 *db,
1444 void *pAux,
1445 int argc, const char *const*argv,
1446 sqlite3_vtab **ppVtab,
1447 char **pzErr
1448){
1449 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001450 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001451
1452/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001453#define JEACH_KEY 0
1454#define JEACH_VALUE 1
1455#define JEACH_TYPE 2
1456#define JEACH_ATOM 3
1457#define JEACH_ID 4
1458#define JEACH_PARENT 5
1459#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001460#define JEACH_PATH 7
1461#define JEACH_JSON 8
1462#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001463
drh6fd5c1e2015-08-21 20:37:12 +00001464 UNUSED_PARAM(pzErr);
1465 UNUSED_PARAM(argv);
1466 UNUSED_PARAM(argc);
1467 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001468 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001469 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1470 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001471 if( rc==SQLITE_OK ){
1472 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1473 if( pNew==0 ) return SQLITE_NOMEM;
1474 memset(pNew, 0, sizeof(*pNew));
1475 }
1476 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001477}
1478
1479/* destructor for json_each virtual table */
1480static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1481 sqlite3_free(pVtab);
1482 return SQLITE_OK;
1483}
1484
drh505ad2c2015-08-21 17:33:11 +00001485/* constructor for a JsonEachCursor object for json_each(). */
1486static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001487 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001488
1489 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001490 pCur = sqlite3_malloc( sizeof(*pCur) );
1491 if( pCur==0 ) return SQLITE_NOMEM;
1492 memset(pCur, 0, sizeof(*pCur));
1493 *ppCursor = &pCur->base;
1494 return SQLITE_OK;
1495}
1496
drh505ad2c2015-08-21 17:33:11 +00001497/* constructor for a JsonEachCursor object for json_tree(). */
1498static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1499 int rc = jsonEachOpenEach(p, ppCursor);
1500 if( rc==SQLITE_OK ){
1501 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1502 pCur->bRecursive = 1;
1503 }
1504 return rc;
1505}
1506
drhcb6c6c62015-08-19 22:47:17 +00001507/* Reset a JsonEachCursor back to its original state. Free any memory
1508** held. */
1509static void jsonEachCursorReset(JsonEachCursor *p){
1510 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001511 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001512 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001513 p->iRowid = 0;
1514 p->i = 0;
1515 p->iEnd = 0;
1516 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001517 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001518 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001519}
1520
1521/* Destructor for a jsonEachCursor object */
1522static int jsonEachClose(sqlite3_vtab_cursor *cur){
1523 JsonEachCursor *p = (JsonEachCursor*)cur;
1524 jsonEachCursorReset(p);
1525 sqlite3_free(cur);
1526 return SQLITE_OK;
1527}
1528
1529/* Return TRUE if the jsonEachCursor object has been advanced off the end
1530** of the JSON object */
1531static int jsonEachEof(sqlite3_vtab_cursor *cur){
1532 JsonEachCursor *p = (JsonEachCursor*)cur;
1533 return p->i >= p->iEnd;
1534}
1535
drh505ad2c2015-08-21 17:33:11 +00001536/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001537static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001538 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001539 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001540 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1541 p->i++;
drh4af352d2015-08-21 20:02:48 +00001542 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001543 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001544 u32 iUp = p->sParse.aUp[p->i];
1545 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001546 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001547 if( pUp->eType==JSON_ARRAY ){
1548 if( iUp==p->i-1 ){
1549 pUp->u.iKey = 0;
1550 }else{
1551 pUp->u.iKey++;
1552 }
drh4af352d2015-08-21 20:02:48 +00001553 }
1554 }
drh505ad2c2015-08-21 17:33:11 +00001555 }else{
drh4af352d2015-08-21 20:02:48 +00001556 switch( p->eType ){
1557 case JSON_ARRAY: {
1558 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1559 p->iRowid++;
1560 break;
1561 }
1562 case JSON_OBJECT: {
1563 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1564 p->iRowid++;
1565 break;
1566 }
1567 default: {
1568 p->i = p->iEnd;
1569 break;
1570 }
drh505ad2c2015-08-21 17:33:11 +00001571 }
1572 }
1573 return SQLITE_OK;
1574}
1575
drh4af352d2015-08-21 20:02:48 +00001576/* Append the name of the path for element i to pStr
1577*/
1578static void jsonEachComputePath(
1579 JsonEachCursor *p, /* The cursor */
1580 JsonString *pStr, /* Write the path here */
1581 u32 i /* Path to this element */
1582){
1583 JsonNode *pNode, *pUp;
1584 u32 iUp;
1585 if( i==0 ){
1586 jsonAppendChar(pStr, '$');
1587 return;
drhcb6c6c62015-08-19 22:47:17 +00001588 }
drh4af352d2015-08-21 20:02:48 +00001589 iUp = p->sParse.aUp[i];
1590 jsonEachComputePath(p, pStr, iUp);
1591 pNode = &p->sParse.aNode[i];
1592 pUp = &p->sParse.aNode[iUp];
1593 if( pUp->eType==JSON_ARRAY ){
1594 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1595 }else{
1596 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001597 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001598 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001599 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001600 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1601 }
drhcb6c6c62015-08-19 22:47:17 +00001602}
1603
1604/* Return the value of a column */
1605static int jsonEachColumn(
1606 sqlite3_vtab_cursor *cur, /* The cursor */
1607 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1608 int i /* Which column to return */
1609){
1610 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001611 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001612 switch( i ){
1613 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001614 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001615 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001616 jsonReturn(pThis, ctx, 0);
1617 }else if( p->eType==JSON_ARRAY ){
1618 u32 iKey;
1619 if( p->bRecursive ){
1620 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001621 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001622 }else{
1623 iKey = p->iRowid;
1624 }
drh6fd5c1e2015-08-21 20:37:12 +00001625 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001626 }
1627 break;
1628 }
1629 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001630 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001631 jsonReturn(pThis, ctx, 0);
1632 break;
1633 }
1634 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001635 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001636 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1637 break;
1638 }
1639 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001640 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001641 if( pThis->eType>=JSON_ARRAY ) break;
1642 jsonReturn(pThis, ctx, 0);
1643 break;
1644 }
1645 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001646 sqlite3_result_int64(ctx,
1647 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001648 break;
1649 }
1650 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001651 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001652 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001653 }
1654 break;
1655 }
drh4af352d2015-08-21 20:02:48 +00001656 case JEACH_FULLKEY: {
1657 JsonString x;
1658 jsonInit(&x, ctx);
1659 if( p->bRecursive ){
1660 jsonEachComputePath(p, &x, p->i);
1661 }else{
drh383de692015-09-10 17:20:57 +00001662 if( p->zRoot ){
1663 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001664 }else{
1665 jsonAppendChar(&x, '$');
1666 }
1667 if( p->eType==JSON_ARRAY ){
1668 jsonPrintf(30, &x, "[%d]", p->iRowid);
1669 }else{
1670 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1671 }
1672 }
1673 jsonResult(&x);
1674 break;
1675 }
drhcb6c6c62015-08-19 22:47:17 +00001676 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001677 if( p->bRecursive ){
1678 JsonString x;
1679 jsonInit(&x, ctx);
1680 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1681 jsonResult(&x);
1682 break;
drh4af352d2015-08-21 20:02:48 +00001683 }
drh383de692015-09-10 17:20:57 +00001684 /* For json_each() path and root are the same so fall through
1685 ** into the root case */
1686 }
1687 case JEACH_ROOT: {
1688 const char *zRoot = p->zRoot;
1689 if( zRoot==0 ) zRoot = "$";
1690 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001691 break;
1692 }
drh3d1d2a92015-09-22 01:15:49 +00001693 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00001694 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001695 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1696 break;
1697 }
1698 }
1699 return SQLITE_OK;
1700}
1701
1702/* Return the current rowid value */
1703static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1704 JsonEachCursor *p = (JsonEachCursor*)cur;
1705 *pRowid = p->iRowid;
1706 return SQLITE_OK;
1707}
1708
1709/* The query strategy is to look for an equality constraint on the json
1710** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001711** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001712** and 0 otherwise.
1713*/
1714static int jsonEachBestIndex(
1715 sqlite3_vtab *tab,
1716 sqlite3_index_info *pIdxInfo
1717){
1718 int i;
1719 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001720 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001721 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001722
1723 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001724 pConstraint = pIdxInfo->aConstraint;
1725 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1726 if( pConstraint->usable==0 ) continue;
1727 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1728 switch( pConstraint->iColumn ){
1729 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001730 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001731 default: /* no-op */ break;
1732 }
1733 }
1734 if( jsonIdx<0 ){
1735 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001736 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001737 }else{
drh505ad2c2015-08-21 17:33:11 +00001738 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001739 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1740 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001741 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001742 pIdxInfo->idxNum = 1;
1743 }else{
drh383de692015-09-10 17:20:57 +00001744 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1745 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001746 pIdxInfo->idxNum = 3;
1747 }
1748 }
1749 return SQLITE_OK;
1750}
1751
1752/* Start a search on a new JSON string */
1753static int jsonEachFilter(
1754 sqlite3_vtab_cursor *cur,
1755 int idxNum, const char *idxStr,
1756 int argc, sqlite3_value **argv
1757){
1758 JsonEachCursor *p = (JsonEachCursor*)cur;
1759 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001760 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001761 sqlite3_int64 n;
1762
drh6fd5c1e2015-08-21 20:37:12 +00001763 UNUSED_PARAM(idxStr);
1764 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001765 jsonEachCursorReset(p);
1766 if( idxNum==0 ) return SQLITE_OK;
1767 z = (const char*)sqlite3_value_text(argv[0]);
1768 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001769 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001770 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001771 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001772 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001773 if( jsonParse(&p->sParse, 0, p->zJson) ){
1774 int rc = SQLITE_NOMEM;
1775 if( p->sParse.oom==0 ){
1776 sqlite3_free(cur->pVtab->zErrMsg);
1777 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1778 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1779 }
drhcb6c6c62015-08-19 22:47:17 +00001780 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001781 return rc;
1782 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1783 jsonEachCursorReset(p);
1784 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001785 }else{
1786 JsonNode *pNode;
1787 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001788 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001789 zRoot = (const char*)sqlite3_value_text(argv[1]);
1790 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001791 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001792 p->zRoot = sqlite3_malloc64( n+1 );
1793 if( p->zRoot==0 ) return SQLITE_NOMEM;
1794 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001795 if( zRoot[0]!='$' ){
1796 zErr = zRoot;
1797 }else{
1798 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1799 }
1800 if( zErr ){
drha7714022015-08-29 00:54:49 +00001801 sqlite3_free(cur->pVtab->zErrMsg);
1802 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001803 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001804 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1805 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001806 return SQLITE_OK;
1807 }
1808 }else{
1809 pNode = p->sParse.aNode;
1810 }
drh852944e2015-09-10 03:29:11 +00001811 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001812 p->eType = pNode->eType;
1813 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001814 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001815 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001816 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00001817 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00001818 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1819 p->i--;
1820 }
1821 }else{
1822 p->i++;
1823 }
drhcb6c6c62015-08-19 22:47:17 +00001824 }else{
1825 p->iEnd = p->i+1;
1826 }
1827 }
drha8f39a92015-09-21 22:53:16 +00001828 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001829}
1830
1831/* The methods of the json_each virtual table */
1832static sqlite3_module jsonEachModule = {
1833 0, /* iVersion */
1834 0, /* xCreate */
1835 jsonEachConnect, /* xConnect */
1836 jsonEachBestIndex, /* xBestIndex */
1837 jsonEachDisconnect, /* xDisconnect */
1838 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001839 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001840 jsonEachClose, /* xClose - close a cursor */
1841 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001842 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001843 jsonEachEof, /* xEof - check for end of scan */
1844 jsonEachColumn, /* xColumn - read data */
1845 jsonEachRowid, /* xRowid - read data */
1846 0, /* xUpdate */
1847 0, /* xBegin */
1848 0, /* xSync */
1849 0, /* xCommit */
1850 0, /* xRollback */
1851 0, /* xFindMethod */
1852 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001853 0, /* xSavepoint */
1854 0, /* xRelease */
1855 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001856};
1857
drh505ad2c2015-08-21 17:33:11 +00001858/* The methods of the json_tree virtual table. */
1859static sqlite3_module jsonTreeModule = {
1860 0, /* iVersion */
1861 0, /* xCreate */
1862 jsonEachConnect, /* xConnect */
1863 jsonEachBestIndex, /* xBestIndex */
1864 jsonEachDisconnect, /* xDisconnect */
1865 0, /* xDestroy */
1866 jsonEachOpenTree, /* xOpen - open a cursor */
1867 jsonEachClose, /* xClose - close a cursor */
1868 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001869 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001870 jsonEachEof, /* xEof - check for end of scan */
1871 jsonEachColumn, /* xColumn - read data */
1872 jsonEachRowid, /* xRowid - read data */
1873 0, /* xUpdate */
1874 0, /* xBegin */
1875 0, /* xSync */
1876 0, /* xCommit */
1877 0, /* xRollback */
1878 0, /* xFindMethod */
1879 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001880 0, /* xSavepoint */
1881 0, /* xRelease */
1882 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001883};
drhd2975922015-08-29 17:22:33 +00001884#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001885
1886/****************************************************************************
1887** The following routine is the only publically visible identifier in this
1888** file. Call the following routine in order to register the various SQL
1889** functions and the virtual table implemented by this file.
1890****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001891
drh5fa5c102015-08-12 16:49:40 +00001892#ifdef _WIN32
1893__declspec(dllexport)
1894#endif
1895int sqlite3_json_init(
1896 sqlite3 *db,
1897 char **pzErrMsg,
1898 const sqlite3_api_routines *pApi
1899){
1900 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001901 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001902 static const struct {
1903 const char *zName;
1904 int nArg;
drh52216ad2015-08-18 02:28:03 +00001905 int flag;
drh5fa5c102015-08-12 16:49:40 +00001906 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1907 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001908 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001909 { "json_array", -1, 0, jsonArrayFunc },
1910 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1911 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001912 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001913 { "json_insert", -1, 0, jsonSetFunc },
1914 { "json_object", -1, 0, jsonObjectFunc },
1915 { "json_remove", -1, 0, jsonRemoveFunc },
1916 { "json_replace", -1, 0, jsonReplaceFunc },
1917 { "json_set", -1, 1, jsonSetFunc },
1918 { "json_type", 1, 0, jsonTypeFunc },
1919 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001920 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001921
drh301eecc2015-08-17 20:14:19 +00001922#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001923 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001924 { "json_parse", 1, 0, jsonParseFunc },
1925 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001926#endif
drh5fa5c102015-08-12 16:49:40 +00001927 };
drhd2975922015-08-29 17:22:33 +00001928#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001929 static const struct {
1930 const char *zName;
1931 sqlite3_module *pModule;
1932 } aMod[] = {
1933 { "json_each", &jsonEachModule },
1934 { "json_tree", &jsonTreeModule },
1935 };
drhd2975922015-08-29 17:22:33 +00001936#endif
drh5fa5c102015-08-12 16:49:40 +00001937 SQLITE_EXTENSION_INIT2(pApi);
1938 (void)pzErrMsg; /* Unused parameter */
1939 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1940 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001941 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1942 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001943 aFunc[i].xFunc, 0, 0);
1944 }
drhd2975922015-08-29 17:22:33 +00001945#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001946 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1947 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00001948 }
drhd2975922015-08-29 17:22:33 +00001949#endif
drh5fa5c102015-08-12 16:49:40 +00001950 return rc;
1951}