blob: b878c0a3e469641fdd418659a1311927f8707411 [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){
drhd0960592015-08-17 21:22:32 +0000159 if( !p->bErr ){
160 p->bErr = 1;
161 sqlite3_result_error_nomem(p->pCtx);
162 jsonReset(p);
163 }
drh5fa5c102015-08-12 16:49:40 +0000164}
165
166/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
167** Return zero on success. Return non-zero on an OOM error
168*/
drh505ad2c2015-08-21 17:33:11 +0000169static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000170 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000171 char *zNew;
172 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000173 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000174 zNew = sqlite3_malloc64(nTotal);
175 if( zNew==0 ){
176 jsonOom(p);
177 return SQLITE_NOMEM;
178 }
drh6fd5c1e2015-08-21 20:37:12 +0000179 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000180 p->zBuf = zNew;
181 p->bStatic = 0;
182 }else{
183 zNew = sqlite3_realloc64(p->zBuf, nTotal);
184 if( zNew==0 ){
185 jsonOom(p);
186 return SQLITE_NOMEM;
187 }
188 p->zBuf = zNew;
189 }
190 p->nAlloc = nTotal;
191 return SQLITE_OK;
192}
193
drh505ad2c2015-08-21 17:33:11 +0000194/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000195*/
drh505ad2c2015-08-21 17:33:11 +0000196static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000197 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
198 memcpy(p->zBuf+p->nUsed, zIn, N);
199 p->nUsed += N;
200}
201
drh4af352d2015-08-21 20:02:48 +0000202/* Append formatted text (not to exceed N bytes) to the JsonString.
203*/
204static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
205 va_list ap;
206 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
207 va_start(ap, zFormat);
208 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
209 va_end(ap);
210 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
211}
212
drh5634cc02015-08-17 11:28:03 +0000213/* Append a single character
214*/
drh505ad2c2015-08-21 17:33:11 +0000215static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000216 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
217 p->zBuf[p->nUsed++] = c;
218}
219
drh301eecc2015-08-17 20:14:19 +0000220/* Append a comma separator to the output buffer, if the previous
221** character is not '[' or '{'.
222*/
drh505ad2c2015-08-21 17:33:11 +0000223static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000224 char c;
225 if( p->nUsed==0 ) return;
226 c = p->zBuf[p->nUsed-1];
227 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
228}
229
drh505ad2c2015-08-21 17:33:11 +0000230/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000231** under construction. Enclose the string in "..." and escape
232** any double-quotes or backslash characters contained within the
233** string.
234*/
drh505ad2c2015-08-21 17:33:11 +0000235static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000236 u32 i;
237 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
238 p->zBuf[p->nUsed++] = '"';
239 for(i=0; i<N; i++){
240 char c = zIn[i];
241 if( c=='"' || c=='\\' ){
242 if( (p->nUsed+N+1-i > p->nAlloc) && jsonGrow(p,N+1-i)!=0 ) return;
243 p->zBuf[p->nUsed++] = '\\';
244 }
245 p->zBuf[p->nUsed++] = c;
246 }
247 p->zBuf[p->nUsed++] = '"';
248}
249
drhd0960592015-08-17 21:22:32 +0000250/*
251** Append a function parameter value to the JSON string under
252** construction.
253*/
254static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000255 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000256 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000257){
258 switch( sqlite3_value_type(pValue) ){
259 case SQLITE_NULL: {
260 jsonAppendRaw(p, "null", 4);
261 break;
262 }
263 case SQLITE_INTEGER:
264 case SQLITE_FLOAT: {
265 const char *z = (const char*)sqlite3_value_text(pValue);
266 u32 n = (u32)sqlite3_value_bytes(pValue);
267 jsonAppendRaw(p, z, n);
268 break;
269 }
270 case SQLITE_TEXT: {
271 const char *z = (const char*)sqlite3_value_text(pValue);
272 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000273 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000274 jsonAppendRaw(p, z, n);
275 }else{
276 jsonAppendString(p, z, n);
277 }
drhd0960592015-08-17 21:22:32 +0000278 break;
279 }
280 default: {
281 if( p->bErr==0 ){
282 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
283 p->bErr = 1;
284 jsonReset(p);
285 }
286 break;
287 }
288 }
289}
290
291
drhbd0621b2015-08-13 13:54:59 +0000292/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000293*/
drh505ad2c2015-08-21 17:33:11 +0000294static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000295 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000296 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
297 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
298 SQLITE_UTF8);
299 jsonZero(p);
300 }
301 assert( p->bStatic );
302}
303
drh505ad2c2015-08-21 17:33:11 +0000304/**************************************************************************
305** Utility routines for dealing with JsonNode and JsonParse objects
306**************************************************************************/
307
308/*
309** Return the number of consecutive JsonNode slots need to represent
310** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
311** OBJECT types, the number might be larger.
312**
313** Appended elements are not counted. The value returned is the number
314** by which the JsonNode counter should increment in order to go to the
315** next peer value.
316*/
317static u32 jsonNodeSize(JsonNode *pNode){
318 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
319}
320
321/*
322** Reclaim all memory allocated by a JsonParse object. But do not
323** delete the JsonParse object itself.
324*/
325static void jsonParseReset(JsonParse *pParse){
326 sqlite3_free(pParse->aNode);
327 pParse->aNode = 0;
328 pParse->nNode = 0;
329 pParse->nAlloc = 0;
330 sqlite3_free(pParse->aUp);
331 pParse->aUp = 0;
332}
333
drh5634cc02015-08-17 11:28:03 +0000334/*
335** Convert the JsonNode pNode into a pure JSON string and
336** append to pOut. Subsubstructure is also included. Return
337** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000338*/
drh52216ad2015-08-18 02:28:03 +0000339static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000340 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000341 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000342 sqlite3_value **aReplace /* Replacement values */
343){
drh5634cc02015-08-17 11:28:03 +0000344 switch( pNode->eType ){
345 case JSON_NULL: {
346 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 ){
443 case JSON_NULL: {
444 sqlite3_result_null(pCtx);
445 break;
446 }
447 case JSON_TRUE: {
448 sqlite3_result_int(pCtx, 1);
449 break;
450 }
451 case JSON_FALSE: {
452 sqlite3_result_int(pCtx, 0);
453 break;
454 }
drh987eb1f2015-08-17 15:17:37 +0000455 case JSON_REAL: {
drh52216ad2015-08-18 02:28:03 +0000456 double r = strtod(pNode->u.zJContent, 0);
drh987eb1f2015-08-17 15:17:37 +0000457 sqlite3_result_double(pCtx, r);
drh5634cc02015-08-17 11:28:03 +0000458 break;
459 }
drh987eb1f2015-08-17 15:17:37 +0000460 case JSON_INT: {
461 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000462 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000463 if( z[0]=='-' ){ z++; }
464 while( z[0]>='0' && z[0]<='9' ){ i = i*10 + *(z++) - '0'; }
drh52216ad2015-08-18 02:28:03 +0000465 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000466 sqlite3_result_int64(pCtx, i);
467 break;
468 }
drh5634cc02015-08-17 11:28:03 +0000469 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000470 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000471 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
472 SQLITE_TRANSIENT);
drh301eecc2015-08-17 20:14:19 +0000473 }else if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000474 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000475 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000476 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000477 }else{
478 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000479 u32 i;
480 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000481 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000482 char *zOut;
483 u32 j;
484 zOut = sqlite3_malloc( n+1 );
485 if( zOut==0 ){
486 sqlite3_result_error_nomem(pCtx);
487 break;
488 }
489 for(i=1, j=0; i<n-1; i++){
490 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000491 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000492 zOut[j++] = c;
493 }else{
494 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000495 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000496 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000497 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000498 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000499 if( c>='0' && c<='9' ) v = v*16 + c - '0';
500 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
501 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
502 else break;
drh987eb1f2015-08-17 15:17:37 +0000503 }
drh80d87402015-08-24 12:42:41 +0000504 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000505 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000506 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000507 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000508 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000509 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000510 }else{
mistachkin16a93122015-09-11 18:05:01 +0000511 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000512 zOut[j++] = 0x80 | ((v>>6)&0x3f);
513 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000514 }
515 }else{
516 if( c=='b' ){
517 c = '\b';
518 }else if( c=='f' ){
519 c = '\f';
520 }else if( c=='n' ){
521 c = '\n';
522 }else if( c=='r' ){
523 c = '\r';
524 }else if( c=='t' ){
525 c = '\t';
526 }
527 zOut[j++] = c;
528 }
529 }
530 }
531 zOut[j] = 0;
532 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000533 }
534 break;
535 }
536 case JSON_ARRAY:
537 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000538 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000539 break;
540 }
541 }
drhbd0621b2015-08-13 13:54:59 +0000542}
543
drh5fa5c102015-08-12 16:49:40 +0000544/*
drhe9c37f32015-08-15 21:25:36 +0000545** Create a new JsonNode instance based on the arguments and append that
546** instance to the JsonParse. Return the index in pParse->aNode[] of the
547** new node, or -1 if a memory allocation fails.
548*/
549static int jsonParseAddNode(
550 JsonParse *pParse, /* Append the node to this object */
551 u32 eType, /* Node type */
552 u32 n, /* Content size or sub-node count */
553 const char *zContent /* Content */
554){
555 JsonNode *p;
556 if( pParse->nNode>=pParse->nAlloc ){
557 u32 nNew;
558 JsonNode *pNew;
559 if( pParse->oom ) return -1;
560 nNew = pParse->nAlloc*2 + 10;
561 if( nNew<=pParse->nNode ){
562 pParse->oom = 1;
563 return -1;
564 }
565 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
566 if( pNew==0 ){
567 pParse->oom = 1;
568 return -1;
569 }
570 pParse->nAlloc = nNew;
571 pParse->aNode = pNew;
572 }
573 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000574 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000575 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000576 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000577 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000578 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000579 return pParse->nNode++;
580}
581
582/*
583** Parse a single JSON value which begins at pParse->zJson[i]. Return the
584** index of the first character past the end of the value parsed.
585**
586** Return negative for a syntax error. Special cases: return -2 if the
587** first non-whitespace character is '}' and return -3 if the first
588** non-whitespace character is ']'.
589*/
590static int jsonParseValue(JsonParse *pParse, u32 i){
591 char c;
592 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000593 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000594 int x;
drh852944e2015-09-10 03:29:11 +0000595 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000596 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drhe9c37f32015-08-15 21:25:36 +0000597 if( (c = pParse->zJson[i])==0 ) return 0;
598 if( c=='{' ){
599 /* Parse object */
600 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000601 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000602 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000603 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000604 x = jsonParseValue(pParse, j);
605 if( x<0 ){
drhbc8f0922015-08-22 19:39:04 +0000606 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000607 return -1;
608 }
drhbe9474e2015-08-22 03:05:54 +0000609 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000610 pNode = &pParse->aNode[pParse->nNode-1];
611 if( pNode->eType!=JSON_STRING ) return -1;
612 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000613 j = x;
dan2e8f5512015-09-17 17:21:09 +0000614 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000615 if( pParse->zJson[j]!=':' ) return -1;
616 j++;
617 x = jsonParseValue(pParse, j);
618 if( x<0 ) return -1;
619 j = x;
dan2e8f5512015-09-17 17:21:09 +0000620 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000621 c = pParse->zJson[j];
622 if( c==',' ) continue;
623 if( c!='}' ) return -1;
624 break;
625 }
drhbc8f0922015-08-22 19:39:04 +0000626 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000627 return j+1;
628 }else if( c=='[' ){
629 /* Parse array */
630 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000631 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000632 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000633 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000634 x = jsonParseValue(pParse, j);
635 if( x<0 ){
drhbc8f0922015-08-22 19:39:04 +0000636 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000637 return -1;
638 }
639 j = x;
dan2e8f5512015-09-17 17:21:09 +0000640 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000641 c = pParse->zJson[j];
642 if( c==',' ) continue;
643 if( c!=']' ) return -1;
644 break;
645 }
drhbc8f0922015-08-22 19:39:04 +0000646 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000647 return j+1;
648 }else if( c=='"' ){
649 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000650 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000651 j = i+1;
652 for(;;){
653 c = pParse->zJson[j];
654 if( c==0 ) return -1;
655 if( c=='\\' ){
656 c = pParse->zJson[++j];
657 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000658 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000659 }else if( c=='"' ){
660 break;
661 }
662 j++;
663 }
664 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000665 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000666 return j+1;
667 }else if( c=='n'
668 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000669 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000670 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
671 return i+4;
672 }else if( c=='t'
673 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000674 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000675 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
676 return i+4;
677 }else if( c=='f'
678 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000679 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000680 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
681 return i+5;
682 }else if( c=='-' || (c>='0' && c<='9') ){
683 /* Parse number */
684 u8 seenDP = 0;
685 u8 seenE = 0;
686 j = i+1;
687 for(;; j++){
688 c = pParse->zJson[j];
689 if( c>='0' && c<='9' ) continue;
690 if( c=='.' ){
691 if( pParse->zJson[j-1]=='-' ) return -1;
692 if( seenDP ) return -1;
693 seenDP = 1;
694 continue;
695 }
696 if( c=='e' || c=='E' ){
697 if( pParse->zJson[j-1]<'0' ) return -1;
698 if( seenE ) return -1;
699 seenDP = seenE = 1;
700 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000701 if( c=='+' || c=='-' ){
702 j++;
703 c = pParse->zJson[j+1];
704 }
drhd1f00682015-08-29 16:02:37 +0000705 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000706 continue;
707 }
708 break;
709 }
710 if( pParse->zJson[j-1]<'0' ) return -1;
711 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
712 j - i, &pParse->zJson[i]);
713 return j;
714 }else if( c=='}' ){
715 return -2; /* End of {...} */
716 }else if( c==']' ){
717 return -3; /* End of [...] */
718 }else{
719 return -1; /* Syntax error */
720 }
721}
722
723/*
724** Parse a complete JSON string. Return 0 on success or non-zero if there
725** are any errors. If an error occurs, free all memory associated with
726** pParse.
727**
728** pParse is uninitialized when this routine is called.
729*/
drhbc8f0922015-08-22 19:39:04 +0000730static int jsonParse(
731 JsonParse *pParse, /* Initialize and fill this JsonParse object */
732 sqlite3_context *pCtx, /* Report errors here */
733 const char *zJson /* Input JSON text to be parsed */
734){
drhe9c37f32015-08-15 21:25:36 +0000735 int i;
drhe9c37f32015-08-15 21:25:36 +0000736 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000737 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000738 pParse->zJson = zJson;
739 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000740 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000741 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000742 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000743 if( zJson[i] ) i = -1;
744 }
drhd1f00682015-08-29 16:02:37 +0000745 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000746 if( pCtx!=0 ){
747 if( pParse->oom ){
748 sqlite3_result_error_nomem(pCtx);
749 }else{
750 sqlite3_result_error(pCtx, "malformed JSON", -1);
751 }
752 }
drh505ad2c2015-08-21 17:33:11 +0000753 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000754 return 1;
755 }
756 return 0;
757}
drh301eecc2015-08-17 20:14:19 +0000758
drh505ad2c2015-08-21 17:33:11 +0000759/* Mark node i of pParse as being a child of iParent. Call recursively
760** to fill in all the descendants of node i.
761*/
762static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
763 JsonNode *pNode = &pParse->aNode[i];
764 u32 j;
765 pParse->aUp[i] = iParent;
766 switch( pNode->eType ){
767 case JSON_ARRAY: {
768 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
769 jsonParseFillInParentage(pParse, i+j, i);
770 }
771 break;
772 }
773 case JSON_OBJECT: {
774 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
775 pParse->aUp[i+j] = i;
776 jsonParseFillInParentage(pParse, i+j+1, i);
777 }
778 break;
779 }
780 default: {
781 break;
782 }
783 }
784}
785
786/*
787** Compute the parentage of all nodes in a completed parse.
788*/
789static int jsonParseFindParents(JsonParse *pParse){
790 u32 *aUp;
791 assert( pParse->aUp==0 );
792 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000793 if( aUp==0 ){
794 pParse->oom = 1;
795 return SQLITE_NOMEM;
796 }
drh505ad2c2015-08-21 17:33:11 +0000797 jsonParseFillInParentage(pParse, 0, 0);
798 return SQLITE_OK;
799}
800
drh52216ad2015-08-18 02:28:03 +0000801/* forward declaration */
drha7714022015-08-29 00:54:49 +0000802static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000803
drh987eb1f2015-08-17 15:17:37 +0000804/*
805** Search along zPath to find the node specified. Return a pointer
806** to that node, or NULL if zPath is malformed or if there is no such
807** node.
drh52216ad2015-08-18 02:28:03 +0000808**
809** If pApnd!=0, then try to append new nodes to complete zPath if it is
810** possible to do so and if no existing node corresponds to zPath. If
811** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000812*/
drha7714022015-08-29 00:54:49 +0000813static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000814 JsonParse *pParse, /* The JSON to search */
815 u32 iRoot, /* Begin the search at this node */
816 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000817 int *pApnd, /* Append nodes to complete path if not NULL */
818 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000819){
drhbc8f0922015-08-22 19:39:04 +0000820 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000821 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000822 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000823 if( zPath[0]==0 ) return pRoot;
824 if( zPath[0]=='.' ){
825 if( pRoot->eType!=JSON_OBJECT ) return 0;
826 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000827 if( zPath[0]=='"' ){
828 zKey = zPath + 1;
829 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
830 nKey = i-1;
831 if( zPath[i] ) i++;
832 }else{
833 zKey = zPath;
834 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
835 nKey = i;
836 }
drha7714022015-08-29 00:54:49 +0000837 if( nKey==0 ){
838 *pzErr = zPath;
839 return 0;
840 }
drh987eb1f2015-08-17 15:17:37 +0000841 j = 1;
drh52216ad2015-08-18 02:28:03 +0000842 for(;;){
843 while( j<=pRoot->n ){
drh6b43cc82015-08-19 23:02:49 +0000844 if( pRoot[j].n==nKey+2
845 && strncmp(&pRoot[j].u.zJContent[1],zKey,nKey)==0
drh52216ad2015-08-18 02:28:03 +0000846 ){
drha7714022015-08-29 00:54:49 +0000847 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000848 }
849 j++;
drh505ad2c2015-08-21 17:33:11 +0000850 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000851 }
drh52216ad2015-08-18 02:28:03 +0000852 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
853 iRoot += pRoot->u.iAppend;
854 pRoot = &pParse->aNode[iRoot];
855 j = 1;
856 }
857 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000858 u32 iStart, iLabel;
859 JsonNode *pNode;
860 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
861 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000862 zPath += i;
drha7714022015-08-29 00:54:49 +0000863 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000864 if( pParse->oom ) return 0;
865 if( pNode ){
866 pRoot = &pParse->aNode[iRoot];
867 pRoot->u.iAppend = iStart - iRoot;
868 pRoot->jnFlags |= JNODE_APPEND;
869 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
870 }
871 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000872 }
dan2e8f5512015-09-17 17:21:09 +0000873 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000874 if( pRoot->eType!=JSON_ARRAY ) return 0;
875 i = 0;
876 zPath++;
dan2e8f5512015-09-17 17:21:09 +0000877 while( safe_isdigit(zPath[0]) ){
drh8784eca2015-08-23 02:42:30 +0000878 i = i*10 + zPath[0] - '0';
drh987eb1f2015-08-17 15:17:37 +0000879 zPath++;
880 }
drha7714022015-08-29 00:54:49 +0000881 if( zPath[0]!=']' ){
882 *pzErr = zPath;
883 return 0;
884 }
drh987eb1f2015-08-17 15:17:37 +0000885 zPath++;
886 j = 1;
drh52216ad2015-08-18 02:28:03 +0000887 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000888 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
889 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000890 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000891 }
892 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
893 iRoot += pRoot->u.iAppend;
894 pRoot = &pParse->aNode[iRoot];
895 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000896 }
897 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000898 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000899 }
900 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000901 u32 iStart;
902 JsonNode *pNode;
903 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +0000904 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000905 if( pParse->oom ) return 0;
906 if( pNode ){
907 pRoot = &pParse->aNode[iRoot];
908 pRoot->u.iAppend = iStart - iRoot;
909 pRoot->jnFlags |= JNODE_APPEND;
910 }
911 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000912 }
drha7714022015-08-29 00:54:49 +0000913 }else if( zPath[0]!=0 ){
914 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +0000915 }
916 return 0;
917}
918
drh52216ad2015-08-18 02:28:03 +0000919/*
drhbc8f0922015-08-22 19:39:04 +0000920** Append content to pParse that will complete zPath. Return a pointer
921** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000922*/
923static JsonNode *jsonLookupAppend(
924 JsonParse *pParse, /* Append content to the JSON parse */
925 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +0000926 int *pApnd, /* Set this flag to 1 */
927 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +0000928){
929 *pApnd = 1;
930 if( zPath[0]==0 ){
931 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
932 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
933 }
934 if( zPath[0]=='.' ){
935 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
936 }else if( strncmp(zPath,"[0]",3)==0 ){
937 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
938 }else{
939 return 0;
940 }
941 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +0000942 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000943}
944
drhbc8f0922015-08-22 19:39:04 +0000945/*
drha7714022015-08-29 00:54:49 +0000946** Return the text of a syntax error message on a JSON path. Space is
947** obtained from sqlite3_malloc().
948*/
949static char *jsonPathSyntaxError(const char *zErr){
950 return sqlite3_mprintf("JSON path error near '%q'", zErr);
951}
952
953/*
954** Do a node lookup using zPath. Return a pointer to the node on success.
955** Return NULL if not found or if there is an error.
956**
957** On an error, write an error message into pCtx and increment the
958** pParse->nErr counter.
959**
960** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
961** nodes are appended.
drha7714022015-08-29 00:54:49 +0000962*/
963static JsonNode *jsonLookup(
964 JsonParse *pParse, /* The JSON to search */
965 const char *zPath, /* The path to search */
966 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +0000967 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +0000968){
969 const char *zErr = 0;
970 JsonNode *pNode = 0;
drha7714022015-08-29 00:54:49 +0000971
972 if( zPath==0 ) return 0;
973 if( zPath[0]!='$' ){
974 zErr = zPath;
975 goto lookup_err;
976 }
977 zPath++;
drha7714022015-08-29 00:54:49 +0000978 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
979 return pNode;
980
981lookup_err:
982 pParse->nErr++;
983 if( zErr!=0 && pCtx!=0 ){
984 char *z = jsonPathSyntaxError(zErr);
985 if( z ){
986 sqlite3_result_error(pCtx, z, -1);
987 sqlite3_free(z);
988 }else{
989 sqlite3_result_error_nomem(pCtx);
990 }
991 }
drha7714022015-08-29 00:54:49 +0000992 return 0;
993}
994
995
996/*
drhbc8f0922015-08-22 19:39:04 +0000997** Report the wrong number of arguments for json_insert(), json_replace()
998** or json_set().
999*/
1000static void jsonWrongNumArgs(
1001 sqlite3_context *pCtx,
1002 const char *zFuncName
1003){
1004 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1005 zFuncName);
1006 sqlite3_result_error(pCtx, zMsg, -1);
1007 sqlite3_free(zMsg);
1008}
drh52216ad2015-08-18 02:28:03 +00001009
drha7714022015-08-29 00:54:49 +00001010
drh987eb1f2015-08-17 15:17:37 +00001011/****************************************************************************
1012** SQL functions used for testing and debugging
1013****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001014
drh301eecc2015-08-17 20:14:19 +00001015#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001016/*
drh5634cc02015-08-17 11:28:03 +00001017** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001018** a parse of the JSON provided. Or it returns NULL if JSON is not
1019** well-formed.
1020*/
drh5634cc02015-08-17 11:28:03 +00001021static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001022 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001023 int argc,
1024 sqlite3_value **argv
1025){
drh505ad2c2015-08-21 17:33:11 +00001026 JsonString s; /* Output string - not real JSON */
1027 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001028 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001029
1030 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001031 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001032 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001033 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001034 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001035 const char *zType;
1036 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1037 assert( x.aNode[i].eType==JSON_STRING );
1038 zType = "label";
1039 }else{
1040 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001041 }
drh852944e2015-09-10 03:29:11 +00001042 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1043 i, zType, x.aNode[i].n, x.aUp[i]);
1044 if( x.aNode[i].u.zJContent!=0 ){
1045 jsonAppendRaw(&s, " ", 1);
1046 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1047 }
1048 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001049 }
drh505ad2c2015-08-21 17:33:11 +00001050 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001051 jsonResult(&s);
1052}
1053
drh5634cc02015-08-17 11:28:03 +00001054/*
drhf5ddb9c2015-09-11 00:06:41 +00001055** The json_test1(JSON) function return true (1) if the input is JSON
1056** text generated by another json function. It returns (0) if the input
1057** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001058*/
1059static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001060 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001061 int argc,
1062 sqlite3_value **argv
1063){
mistachkin16a93122015-09-11 18:05:01 +00001064 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001065 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001066}
drh301eecc2015-08-17 20:14:19 +00001067#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001068
drh987eb1f2015-08-17 15:17:37 +00001069/****************************************************************************
1070** SQL function implementations
1071****************************************************************************/
1072
1073/*
1074** Implementation of the json_array(VALUE,...) function. Return a JSON
1075** array that contains all values given in arguments. Or if any argument
1076** is a BLOB, throw an error.
1077*/
1078static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001079 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001080 int argc,
1081 sqlite3_value **argv
1082){
1083 int i;
drh505ad2c2015-08-21 17:33:11 +00001084 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001085
drhbc8f0922015-08-22 19:39:04 +00001086 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001087 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001088 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001089 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001090 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001091 }
drhd0960592015-08-17 21:22:32 +00001092 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001093 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001094 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001095}
1096
1097
1098/*
1099** json_array_length(JSON)
1100** json_array_length(JSON, PATH)
1101**
1102** Return the number of elements in the top-level JSON array.
1103** Return 0 if the input is not a well-formed JSON array.
1104*/
1105static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001106 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001107 int argc,
1108 sqlite3_value **argv
1109){
1110 JsonParse x; /* The parse */
1111 sqlite3_int64 n = 0;
1112 u32 i;
drh987eb1f2015-08-17 15:17:37 +00001113
drhf2df7e72015-08-28 20:07:40 +00001114 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
1115 if( x.nNode ){
drha7714022015-08-29 00:54:49 +00001116 JsonNode *pNode;
1117 if( argc==2 ){
1118 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
drhf5ddb9c2015-09-11 00:06:41 +00001119 pNode = jsonLookup(&x, zPath, 0, ctx);
drha7714022015-08-29 00:54:49 +00001120 }else{
1121 pNode = x.aNode;
1122 }
1123 if( pNode==0 ){
1124 x.nErr = 1;
1125 }else if( pNode->eType==JSON_ARRAY ){
drhf2df7e72015-08-28 20:07:40 +00001126 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1127 for(i=1; i<=pNode->n; n++){
1128 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001129 }
1130 }
drh987eb1f2015-08-17 15:17:37 +00001131 }
drha7714022015-08-29 00:54:49 +00001132 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001133 jsonParseReset(&x);
1134}
1135
1136/*
drh3ad93bb2015-08-29 19:41:45 +00001137** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001138**
drh3ad93bb2015-08-29 19:41:45 +00001139** Return the element described by PATH. Return NULL if there is no
1140** PATH element. If there are multiple PATHs, then return a JSON array
1141** with the result from each path. Throw an error if the JSON or any PATH
1142** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001143*/
1144static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001145 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001146 int argc,
1147 sqlite3_value **argv
1148){
1149 JsonParse x; /* The parse */
1150 JsonNode *pNode;
1151 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001152 JsonString jx;
1153 int i;
1154
1155 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001156 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001157 jsonInit(&jx, ctx);
1158 jsonAppendChar(&jx, '[');
1159 for(i=1; i<argc; i++){
1160 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001161 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001162 if( x.nErr ) break;
1163 if( argc>2 ){
1164 jsonAppendSeparator(&jx);
1165 if( pNode ){
1166 jsonRenderNode(pNode, &jx, 0);
1167 }else{
1168 jsonAppendRaw(&jx, "null", 4);
1169 }
1170 }else if( pNode ){
1171 jsonReturn(pNode, ctx, 0);
1172 }
drh987eb1f2015-08-17 15:17:37 +00001173 }
drh3ad93bb2015-08-29 19:41:45 +00001174 if( argc>2 && i==argc ){
1175 jsonAppendChar(&jx, ']');
1176 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001177 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001178 }
1179 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001180 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001181}
1182
1183/*
1184** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1185** object that contains all name/value given in arguments. Or if any name
1186** is not a string or if any value is a BLOB, throw an error.
1187*/
1188static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001189 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001190 int argc,
1191 sqlite3_value **argv
1192){
1193 int i;
drh505ad2c2015-08-21 17:33:11 +00001194 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001195 const char *z;
1196 u32 n;
1197
1198 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001199 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001200 "of arguments", -1);
1201 return;
1202 }
drhbc8f0922015-08-22 19:39:04 +00001203 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001204 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001205 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001206 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001207 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drh987eb1f2015-08-17 15:17:37 +00001208 jsonZero(&jx);
1209 return;
1210 }
drhd0960592015-08-17 21:22:32 +00001211 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001212 z = (const char*)sqlite3_value_text(argv[i]);
1213 n = (u32)sqlite3_value_bytes(argv[i]);
1214 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001215 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001216 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001217 }
drhd0960592015-08-17 21:22:32 +00001218 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001219 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001220 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001221}
1222
1223
1224/*
drh301eecc2015-08-17 20:14:19 +00001225** json_remove(JSON, PATH, ...)
1226**
drh3ad93bb2015-08-29 19:41:45 +00001227** Remove the named elements from JSON and return the result. malformed
1228** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001229*/
1230static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001231 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001232 int argc,
1233 sqlite3_value **argv
1234){
1235 JsonParse x; /* The parse */
1236 JsonNode *pNode;
1237 const char *zPath;
1238 u32 i;
1239
1240 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001241 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh301eecc2015-08-17 20:14:19 +00001242 if( x.nNode ){
drh6fd5c1e2015-08-21 20:37:12 +00001243 for(i=1; i<(u32)argc; i++){
drh301eecc2015-08-17 20:14:19 +00001244 zPath = (const char*)sqlite3_value_text(argv[i]);
drha7714022015-08-29 00:54:49 +00001245 if( zPath==0 ) goto remove_done;
drhf5ddb9c2015-09-11 00:06:41 +00001246 pNode = jsonLookup(&x, zPath, 0, ctx);
drha7714022015-08-29 00:54:49 +00001247 if( x.nErr ) goto remove_done;
drh301eecc2015-08-17 20:14:19 +00001248 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1249 }
1250 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
drhf2df7e72015-08-28 20:07:40 +00001251 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001252 }
1253 }
drha7714022015-08-29 00:54:49 +00001254remove_done:
drh505ad2c2015-08-21 17:33:11 +00001255 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001256}
1257
1258/*
1259** json_replace(JSON, PATH, VALUE, ...)
1260**
1261** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001262** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001263*/
1264static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001265 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001266 int argc,
1267 sqlite3_value **argv
1268){
1269 JsonParse x; /* The parse */
1270 JsonNode *pNode;
1271 const char *zPath;
1272 u32 i;
1273
1274 if( argc<1 ) return;
1275 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001276 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001277 return;
1278 }
drhbc8f0922015-08-22 19:39:04 +00001279 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drhd0960592015-08-17 21:22:32 +00001280 if( x.nNode ){
drh6fd5c1e2015-08-21 20:37:12 +00001281 for(i=1; i<(u32)argc; i+=2){
drhd0960592015-08-17 21:22:32 +00001282 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001283 pNode = jsonLookup(&x, zPath, 0, ctx);
drha7714022015-08-29 00:54:49 +00001284 if( x.nErr ) goto replace_err;
drhd0960592015-08-17 21:22:32 +00001285 if( pNode ){
mistachkin16a93122015-09-11 18:05:01 +00001286 pNode->jnFlags |= (u8)JNODE_REPLACE;
1287 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001288 }
1289 }
1290 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drhbc8f0922015-08-22 19:39:04 +00001291 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
drhd0960592015-08-17 21:22:32 +00001292 }else{
drhf2df7e72015-08-28 20:07:40 +00001293 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001294 }
1295 }
drha7714022015-08-29 00:54:49 +00001296replace_err:
drh505ad2c2015-08-21 17:33:11 +00001297 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001298}
drh505ad2c2015-08-21 17:33:11 +00001299
drh52216ad2015-08-18 02:28:03 +00001300/*
1301** json_set(JSON, PATH, VALUE, ...)
1302**
1303** Set the value at PATH to VALUE. Create the PATH if it does not already
1304** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001305** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001306**
1307** json_insert(JSON, PATH, VALUE, ...)
1308**
1309** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001310** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001311*/
1312static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001313 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001314 int argc,
1315 sqlite3_value **argv
1316){
1317 JsonParse x; /* The parse */
1318 JsonNode *pNode;
1319 const char *zPath;
1320 u32 i;
1321 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001322 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001323
1324 if( argc<1 ) return;
1325 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001326 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001327 return;
1328 }
drhbc8f0922015-08-22 19:39:04 +00001329 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh52216ad2015-08-18 02:28:03 +00001330 if( x.nNode ){
drh6fd5c1e2015-08-21 20:37:12 +00001331 for(i=1; i<(u32)argc; i+=2){
drh52216ad2015-08-18 02:28:03 +00001332 zPath = (const char*)sqlite3_value_text(argv[i]);
drh52216ad2015-08-18 02:28:03 +00001333 bApnd = 0;
drhf5ddb9c2015-09-11 00:06:41 +00001334 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
drhbc8f0922015-08-22 19:39:04 +00001335 if( x.oom ){
1336 sqlite3_result_error_nomem(ctx);
1337 goto jsonSetDone;
drha7714022015-08-29 00:54:49 +00001338 }else if( x.nErr ){
1339 goto jsonSetDone;
drhbc8f0922015-08-22 19:39:04 +00001340 }else if( pNode && (bApnd || bIsSet) ){
mistachkin16a93122015-09-11 18:05:01 +00001341 pNode->jnFlags |= (u8)JNODE_REPLACE;
1342 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001343 }
1344 }
1345 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drhbc8f0922015-08-22 19:39:04 +00001346 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
drh52216ad2015-08-18 02:28:03 +00001347 }else{
drhf2df7e72015-08-28 20:07:40 +00001348 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001349 }
1350 }
drhbc8f0922015-08-22 19:39:04 +00001351jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001352 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001353}
drh301eecc2015-08-17 20:14:19 +00001354
1355/*
drh987eb1f2015-08-17 15:17:37 +00001356** json_type(JSON)
1357** json_type(JSON, PATH)
1358**
drh3ad93bb2015-08-29 19:41:45 +00001359** Return the top-level "type" of a JSON string. Throw an error if
1360** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001361*/
1362static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001363 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001364 int argc,
1365 sqlite3_value **argv
1366){
1367 JsonParse x; /* The parse */
1368 const char *zPath;
1369
drhbc8f0922015-08-22 19:39:04 +00001370 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh987eb1f2015-08-17 15:17:37 +00001371 if( x.nNode ){
drha7714022015-08-29 00:54:49 +00001372 JsonNode *pNode;
1373 if( argc==2 ){
1374 zPath = (const char*)sqlite3_value_text(argv[1]);
drhf5ddb9c2015-09-11 00:06:41 +00001375 pNode = jsonLookup(&x, zPath, 0, ctx);
drha7714022015-08-29 00:54:49 +00001376 }else{
1377 pNode = x.aNode;
1378 }
drhbc8f0922015-08-22 19:39:04 +00001379 if( pNode ){
1380 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
1381 }
drh987eb1f2015-08-17 15:17:37 +00001382 }
drh505ad2c2015-08-21 17:33:11 +00001383 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001384}
drh5634cc02015-08-17 11:28:03 +00001385
drhbc8f0922015-08-22 19:39:04 +00001386/*
1387** json_valid(JSON)
1388**
drh3ad93bb2015-08-29 19:41:45 +00001389** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1390** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001391*/
1392static void jsonValidFunc(
1393 sqlite3_context *ctx,
1394 int argc,
1395 sqlite3_value **argv
1396){
1397 JsonParse x; /* The parse */
1398 int rc = 0;
1399
mistachkin16a93122015-09-11 18:05:01 +00001400 UNUSED_PARAM(argc);
drhf2df7e72015-08-28 20:07:40 +00001401 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0
drhbc8f0922015-08-22 19:39:04 +00001402 && x.nNode>0
1403 ){
1404 rc = 1;
1405 }
1406 jsonParseReset(&x);
1407 sqlite3_result_int(ctx, rc);
1408}
1409
drhd2975922015-08-29 17:22:33 +00001410#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001411/****************************************************************************
1412** The json_each virtual table
1413****************************************************************************/
1414typedef struct JsonEachCursor JsonEachCursor;
1415struct JsonEachCursor {
1416 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001417 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001418 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001419 u32 i; /* Index in sParse.aNode[] of current row */
1420 u32 iEnd; /* EOF when i equals or exceeds this value */
1421 u8 eType; /* Type of top-level element */
1422 u8 bRecursive; /* True for json_tree(). False for json_each() */
1423 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001424 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001425 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001426};
1427
1428/* Constructor for the json_each virtual table */
1429static int jsonEachConnect(
1430 sqlite3 *db,
1431 void *pAux,
1432 int argc, const char *const*argv,
1433 sqlite3_vtab **ppVtab,
1434 char **pzErr
1435){
1436 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001437 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001438
1439/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001440#define JEACH_KEY 0
1441#define JEACH_VALUE 1
1442#define JEACH_TYPE 2
1443#define JEACH_ATOM 3
1444#define JEACH_ID 4
1445#define JEACH_PARENT 5
1446#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001447#define JEACH_PATH 7
1448#define JEACH_JSON 8
1449#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001450
drh6fd5c1e2015-08-21 20:37:12 +00001451 UNUSED_PARAM(pzErr);
1452 UNUSED_PARAM(argv);
1453 UNUSED_PARAM(argc);
1454 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001455 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001456 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1457 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001458 if( rc==SQLITE_OK ){
1459 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1460 if( pNew==0 ) return SQLITE_NOMEM;
1461 memset(pNew, 0, sizeof(*pNew));
1462 }
1463 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001464}
1465
1466/* destructor for json_each virtual table */
1467static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1468 sqlite3_free(pVtab);
1469 return SQLITE_OK;
1470}
1471
drh505ad2c2015-08-21 17:33:11 +00001472/* constructor for a JsonEachCursor object for json_each(). */
1473static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001474 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001475
1476 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001477 pCur = sqlite3_malloc( sizeof(*pCur) );
1478 if( pCur==0 ) return SQLITE_NOMEM;
1479 memset(pCur, 0, sizeof(*pCur));
1480 *ppCursor = &pCur->base;
1481 return SQLITE_OK;
1482}
1483
drh505ad2c2015-08-21 17:33:11 +00001484/* constructor for a JsonEachCursor object for json_tree(). */
1485static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1486 int rc = jsonEachOpenEach(p, ppCursor);
1487 if( rc==SQLITE_OK ){
1488 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1489 pCur->bRecursive = 1;
1490 }
1491 return rc;
1492}
1493
drhcb6c6c62015-08-19 22:47:17 +00001494/* Reset a JsonEachCursor back to its original state. Free any memory
1495** held. */
1496static void jsonEachCursorReset(JsonEachCursor *p){
1497 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001498 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001499 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001500 p->iRowid = 0;
1501 p->i = 0;
1502 p->iEnd = 0;
1503 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001504 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001505 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001506}
1507
1508/* Destructor for a jsonEachCursor object */
1509static int jsonEachClose(sqlite3_vtab_cursor *cur){
1510 JsonEachCursor *p = (JsonEachCursor*)cur;
1511 jsonEachCursorReset(p);
1512 sqlite3_free(cur);
1513 return SQLITE_OK;
1514}
1515
1516/* Return TRUE if the jsonEachCursor object has been advanced off the end
1517** of the JSON object */
1518static int jsonEachEof(sqlite3_vtab_cursor *cur){
1519 JsonEachCursor *p = (JsonEachCursor*)cur;
1520 return p->i >= p->iEnd;
1521}
1522
drh505ad2c2015-08-21 17:33:11 +00001523/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001524static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001525 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001526 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001527 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1528 p->i++;
drh4af352d2015-08-21 20:02:48 +00001529 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001530 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001531 u32 iUp = p->sParse.aUp[p->i];
1532 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001533 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001534 if( pUp->eType==JSON_ARRAY ){
1535 if( iUp==p->i-1 ){
1536 pUp->u.iKey = 0;
1537 }else{
1538 pUp->u.iKey++;
1539 }
drh4af352d2015-08-21 20:02:48 +00001540 }
1541 }
drh505ad2c2015-08-21 17:33:11 +00001542 }else{
drh4af352d2015-08-21 20:02:48 +00001543 switch( p->eType ){
1544 case JSON_ARRAY: {
1545 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1546 p->iRowid++;
1547 break;
1548 }
1549 case JSON_OBJECT: {
1550 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1551 p->iRowid++;
1552 break;
1553 }
1554 default: {
1555 p->i = p->iEnd;
1556 break;
1557 }
drh505ad2c2015-08-21 17:33:11 +00001558 }
1559 }
1560 return SQLITE_OK;
1561}
1562
drh4af352d2015-08-21 20:02:48 +00001563/* Append the name of the path for element i to pStr
1564*/
1565static void jsonEachComputePath(
1566 JsonEachCursor *p, /* The cursor */
1567 JsonString *pStr, /* Write the path here */
1568 u32 i /* Path to this element */
1569){
1570 JsonNode *pNode, *pUp;
1571 u32 iUp;
1572 if( i==0 ){
1573 jsonAppendChar(pStr, '$');
1574 return;
drhcb6c6c62015-08-19 22:47:17 +00001575 }
drh4af352d2015-08-21 20:02:48 +00001576 iUp = p->sParse.aUp[i];
1577 jsonEachComputePath(p, pStr, iUp);
1578 pNode = &p->sParse.aNode[i];
1579 pUp = &p->sParse.aNode[iUp];
1580 if( pUp->eType==JSON_ARRAY ){
1581 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1582 }else{
1583 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001584 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001585 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001586 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001587 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1588 }
drhcb6c6c62015-08-19 22:47:17 +00001589}
1590
1591/* Return the value of a column */
1592static int jsonEachColumn(
1593 sqlite3_vtab_cursor *cur, /* The cursor */
1594 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1595 int i /* Which column to return */
1596){
1597 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001598 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001599 switch( i ){
1600 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001601 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001602 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001603 jsonReturn(pThis, ctx, 0);
1604 }else if( p->eType==JSON_ARRAY ){
1605 u32 iKey;
1606 if( p->bRecursive ){
1607 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001608 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001609 }else{
1610 iKey = p->iRowid;
1611 }
drh6fd5c1e2015-08-21 20:37:12 +00001612 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001613 }
1614 break;
1615 }
1616 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001617 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001618 jsonReturn(pThis, ctx, 0);
1619 break;
1620 }
1621 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001622 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001623 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1624 break;
1625 }
1626 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001627 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001628 if( pThis->eType>=JSON_ARRAY ) break;
1629 jsonReturn(pThis, ctx, 0);
1630 break;
1631 }
1632 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001633 sqlite3_result_int64(ctx,
1634 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001635 break;
1636 }
1637 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001638 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001639 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001640 }
1641 break;
1642 }
drh4af352d2015-08-21 20:02:48 +00001643 case JEACH_FULLKEY: {
1644 JsonString x;
1645 jsonInit(&x, ctx);
1646 if( p->bRecursive ){
1647 jsonEachComputePath(p, &x, p->i);
1648 }else{
drh383de692015-09-10 17:20:57 +00001649 if( p->zRoot ){
1650 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001651 }else{
1652 jsonAppendChar(&x, '$');
1653 }
1654 if( p->eType==JSON_ARRAY ){
1655 jsonPrintf(30, &x, "[%d]", p->iRowid);
1656 }else{
1657 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1658 }
1659 }
1660 jsonResult(&x);
1661 break;
1662 }
drhcb6c6c62015-08-19 22:47:17 +00001663 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001664 if( p->bRecursive ){
1665 JsonString x;
1666 jsonInit(&x, ctx);
1667 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1668 jsonResult(&x);
1669 break;
drh4af352d2015-08-21 20:02:48 +00001670 }
drh383de692015-09-10 17:20:57 +00001671 /* For json_each() path and root are the same so fall through
1672 ** into the root case */
1673 }
1674 case JEACH_ROOT: {
1675 const char *zRoot = p->zRoot;
1676 if( zRoot==0 ) zRoot = "$";
1677 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001678 break;
1679 }
1680 default: {
drh505ad2c2015-08-21 17:33:11 +00001681 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001682 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1683 break;
1684 }
1685 }
1686 return SQLITE_OK;
1687}
1688
1689/* Return the current rowid value */
1690static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1691 JsonEachCursor *p = (JsonEachCursor*)cur;
1692 *pRowid = p->iRowid;
1693 return SQLITE_OK;
1694}
1695
1696/* The query strategy is to look for an equality constraint on the json
1697** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001698** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001699** and 0 otherwise.
1700*/
1701static int jsonEachBestIndex(
1702 sqlite3_vtab *tab,
1703 sqlite3_index_info *pIdxInfo
1704){
1705 int i;
1706 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001707 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001708 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001709
1710 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001711 pConstraint = pIdxInfo->aConstraint;
1712 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1713 if( pConstraint->usable==0 ) continue;
1714 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1715 switch( pConstraint->iColumn ){
1716 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001717 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001718 default: /* no-op */ break;
1719 }
1720 }
1721 if( jsonIdx<0 ){
1722 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001723 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001724 }else{
drh505ad2c2015-08-21 17:33:11 +00001725 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001726 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1727 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001728 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001729 pIdxInfo->idxNum = 1;
1730 }else{
drh383de692015-09-10 17:20:57 +00001731 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1732 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001733 pIdxInfo->idxNum = 3;
1734 }
1735 }
1736 return SQLITE_OK;
1737}
1738
1739/* Start a search on a new JSON string */
1740static int jsonEachFilter(
1741 sqlite3_vtab_cursor *cur,
1742 int idxNum, const char *idxStr,
1743 int argc, sqlite3_value **argv
1744){
1745 JsonEachCursor *p = (JsonEachCursor*)cur;
1746 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001747 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001748 sqlite3_int64 n;
1749
drh6fd5c1e2015-08-21 20:37:12 +00001750 UNUSED_PARAM(idxStr);
1751 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001752 jsonEachCursorReset(p);
1753 if( idxNum==0 ) return SQLITE_OK;
1754 z = (const char*)sqlite3_value_text(argv[0]);
1755 if( z==0 ) return SQLITE_OK;
1756 if( idxNum&2 ){
drh383de692015-09-10 17:20:57 +00001757 zRoot = (const char*)sqlite3_value_text(argv[1]);
1758 if( zRoot==0 ) return SQLITE_OK;
1759 if( zRoot[0]!='$' ){
drha7714022015-08-29 00:54:49 +00001760 sqlite3_free(cur->pVtab->zErrMsg);
drh383de692015-09-10 17:20:57 +00001761 cur->pVtab->zErrMsg = jsonPathSyntaxError(zRoot);
drha7714022015-08-29 00:54:49 +00001762 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1763 }
drhcb6c6c62015-08-19 22:47:17 +00001764 }
1765 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001766 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001767 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001768 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001769 if( jsonParse(&p->sParse, 0, p->zJson) ){
1770 int rc = SQLITE_NOMEM;
1771 if( p->sParse.oom==0 ){
1772 sqlite3_free(cur->pVtab->zErrMsg);
1773 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1774 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1775 }
drhcb6c6c62015-08-19 22:47:17 +00001776 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001777 return rc;
1778 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1779 jsonEachCursorReset(p);
1780 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001781 }else{
1782 JsonNode *pNode;
1783 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001784 const char *zErr = 0;
drhcb6c6c62015-08-19 22:47:17 +00001785 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001786 p->zRoot = sqlite3_malloc64( n+1 );
1787 if( p->zRoot==0 ) return SQLITE_NOMEM;
1788 memcpy(p->zRoot, zRoot, (size_t)n+1);
1789 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
drha7714022015-08-29 00:54:49 +00001790 if( p->sParse.nErr ){
1791 sqlite3_free(cur->pVtab->zErrMsg);
1792 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001793 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001794 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1795 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001796 return SQLITE_OK;
1797 }
1798 }else{
1799 pNode = p->sParse.aNode;
1800 }
drh852944e2015-09-10 03:29:11 +00001801 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001802 p->eType = pNode->eType;
1803 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001804 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001805 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001806 if( p->bRecursive ){
1807 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1808 p->i--;
1809 }
1810 }else{
1811 p->i++;
1812 }
drhcb6c6c62015-08-19 22:47:17 +00001813 }else{
1814 p->iEnd = p->i+1;
1815 }
1816 }
drhbc8f0922015-08-22 19:39:04 +00001817 return p->sParse.oom ? SQLITE_NOMEM : SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001818}
1819
1820/* The methods of the json_each virtual table */
1821static sqlite3_module jsonEachModule = {
1822 0, /* iVersion */
1823 0, /* xCreate */
1824 jsonEachConnect, /* xConnect */
1825 jsonEachBestIndex, /* xBestIndex */
1826 jsonEachDisconnect, /* xDisconnect */
1827 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001828 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001829 jsonEachClose, /* xClose - close a cursor */
1830 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001831 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001832 jsonEachEof, /* xEof - check for end of scan */
1833 jsonEachColumn, /* xColumn - read data */
1834 jsonEachRowid, /* xRowid - read data */
1835 0, /* xUpdate */
1836 0, /* xBegin */
1837 0, /* xSync */
1838 0, /* xCommit */
1839 0, /* xRollback */
1840 0, /* xFindMethod */
1841 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001842 0, /* xSavepoint */
1843 0, /* xRelease */
1844 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001845};
1846
drh505ad2c2015-08-21 17:33:11 +00001847/* The methods of the json_tree virtual table. */
1848static sqlite3_module jsonTreeModule = {
1849 0, /* iVersion */
1850 0, /* xCreate */
1851 jsonEachConnect, /* xConnect */
1852 jsonEachBestIndex, /* xBestIndex */
1853 jsonEachDisconnect, /* xDisconnect */
1854 0, /* xDestroy */
1855 jsonEachOpenTree, /* xOpen - open a cursor */
1856 jsonEachClose, /* xClose - close a cursor */
1857 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001858 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001859 jsonEachEof, /* xEof - check for end of scan */
1860 jsonEachColumn, /* xColumn - read data */
1861 jsonEachRowid, /* xRowid - read data */
1862 0, /* xUpdate */
1863 0, /* xBegin */
1864 0, /* xSync */
1865 0, /* xCommit */
1866 0, /* xRollback */
1867 0, /* xFindMethod */
1868 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001869 0, /* xSavepoint */
1870 0, /* xRelease */
1871 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001872};
drhd2975922015-08-29 17:22:33 +00001873#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001874
1875/****************************************************************************
1876** The following routine is the only publically visible identifier in this
1877** file. Call the following routine in order to register the various SQL
1878** functions and the virtual table implemented by this file.
1879****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001880
drh5fa5c102015-08-12 16:49:40 +00001881#ifdef _WIN32
1882__declspec(dllexport)
1883#endif
1884int sqlite3_json_init(
1885 sqlite3 *db,
1886 char **pzErrMsg,
1887 const sqlite3_api_routines *pApi
1888){
1889 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001890 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001891 static const struct {
1892 const char *zName;
1893 int nArg;
drh52216ad2015-08-18 02:28:03 +00001894 int flag;
drh5fa5c102015-08-12 16:49:40 +00001895 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1896 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001897 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001898 { "json_array", -1, 0, jsonArrayFunc },
1899 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1900 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001901 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001902 { "json_insert", -1, 0, jsonSetFunc },
1903 { "json_object", -1, 0, jsonObjectFunc },
1904 { "json_remove", -1, 0, jsonRemoveFunc },
1905 { "json_replace", -1, 0, jsonReplaceFunc },
1906 { "json_set", -1, 1, jsonSetFunc },
1907 { "json_type", 1, 0, jsonTypeFunc },
1908 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001909 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001910
drh301eecc2015-08-17 20:14:19 +00001911#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001912 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001913 { "json_parse", 1, 0, jsonParseFunc },
1914 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001915#endif
drh5fa5c102015-08-12 16:49:40 +00001916 };
drhd2975922015-08-29 17:22:33 +00001917#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001918 static const struct {
1919 const char *zName;
1920 sqlite3_module *pModule;
1921 } aMod[] = {
1922 { "json_each", &jsonEachModule },
1923 { "json_tree", &jsonTreeModule },
1924 };
drhd2975922015-08-29 17:22:33 +00001925#endif
drh5fa5c102015-08-12 16:49:40 +00001926 SQLITE_EXTENSION_INIT2(pApi);
1927 (void)pzErrMsg; /* Unused parameter */
1928 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1929 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001930 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1931 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001932 aFunc[i].xFunc, 0, 0);
1933 }
drhd2975922015-08-29 17:22:33 +00001934#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001935 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1936 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00001937 }
drhd2975922015-08-29 17:22:33 +00001938#endif
drh5fa5c102015-08-12 16:49:40 +00001939 return rc;
1940}