blob: c3e21dd5086976272b54252250675b35aa822337 [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=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000242 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000243 p->zBuf[p->nUsed++] = '\\';
244 }
245 p->zBuf[p->nUsed++] = c;
246 }
247 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000248 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000249}
250
drhd0960592015-08-17 21:22:32 +0000251/*
252** Append a function parameter value to the JSON string under
253** construction.
254*/
255static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000256 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000257 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000258){
259 switch( sqlite3_value_type(pValue) ){
260 case SQLITE_NULL: {
261 jsonAppendRaw(p, "null", 4);
262 break;
263 }
264 case SQLITE_INTEGER:
265 case SQLITE_FLOAT: {
266 const char *z = (const char*)sqlite3_value_text(pValue);
267 u32 n = (u32)sqlite3_value_bytes(pValue);
268 jsonAppendRaw(p, z, n);
269 break;
270 }
271 case SQLITE_TEXT: {
272 const char *z = (const char*)sqlite3_value_text(pValue);
273 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000274 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000275 jsonAppendRaw(p, z, n);
276 }else{
277 jsonAppendString(p, z, n);
278 }
drhd0960592015-08-17 21:22:32 +0000279 break;
280 }
281 default: {
282 if( p->bErr==0 ){
283 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
284 p->bErr = 1;
285 jsonReset(p);
286 }
287 break;
288 }
289 }
290}
291
292
drhbd0621b2015-08-13 13:54:59 +0000293/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000294*/
drh505ad2c2015-08-21 17:33:11 +0000295static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000296 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000297 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
298 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
299 SQLITE_UTF8);
300 jsonZero(p);
301 }
302 assert( p->bStatic );
303}
304
drh505ad2c2015-08-21 17:33:11 +0000305/**************************************************************************
306** Utility routines for dealing with JsonNode and JsonParse objects
307**************************************************************************/
308
309/*
310** Return the number of consecutive JsonNode slots need to represent
311** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
312** OBJECT types, the number might be larger.
313**
314** Appended elements are not counted. The value returned is the number
315** by which the JsonNode counter should increment in order to go to the
316** next peer value.
317*/
318static u32 jsonNodeSize(JsonNode *pNode){
319 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
320}
321
322/*
323** Reclaim all memory allocated by a JsonParse object. But do not
324** delete the JsonParse object itself.
325*/
326static void jsonParseReset(JsonParse *pParse){
327 sqlite3_free(pParse->aNode);
328 pParse->aNode = 0;
329 pParse->nNode = 0;
330 pParse->nAlloc = 0;
331 sqlite3_free(pParse->aUp);
332 pParse->aUp = 0;
333}
334
drh5634cc02015-08-17 11:28:03 +0000335/*
336** Convert the JsonNode pNode into a pure JSON string and
337** append to pOut. Subsubstructure is also included. Return
338** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000339*/
drh52216ad2015-08-18 02:28:03 +0000340static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000341 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000342 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000343 sqlite3_value **aReplace /* Replacement values */
344){
drh5634cc02015-08-17 11:28:03 +0000345 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000346 default: {
347 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000348 jsonAppendRaw(pOut, "null", 4);
349 break;
350 }
351 case JSON_TRUE: {
352 jsonAppendRaw(pOut, "true", 4);
353 break;
354 }
355 case JSON_FALSE: {
356 jsonAppendRaw(pOut, "false", 5);
357 break;
358 }
359 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000360 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000361 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000362 break;
363 }
364 /* Fall through into the next case */
365 }
366 case JSON_REAL:
367 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000368 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000369 break;
370 }
371 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000372 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000373 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000374 for(;;){
375 while( j<=pNode->n ){
376 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
377 if( pNode[j].jnFlags & JNODE_REPLACE ){
378 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000379 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000380 }
381 }else{
drhd0960592015-08-17 21:22:32 +0000382 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000383 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000384 }
drh505ad2c2015-08-21 17:33:11 +0000385 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000386 }
drh52216ad2015-08-18 02:28:03 +0000387 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
388 pNode = &pNode[pNode->u.iAppend];
389 j = 1;
drh5634cc02015-08-17 11:28:03 +0000390 }
391 jsonAppendChar(pOut, ']');
392 break;
393 }
394 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000395 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000396 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000397 for(;;){
398 while( j<=pNode->n ){
399 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
400 jsonAppendSeparator(pOut);
401 jsonRenderNode(&pNode[j], pOut, aReplace);
402 jsonAppendChar(pOut, ':');
403 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000404 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000405 }else{
406 jsonRenderNode(&pNode[j+1], pOut, aReplace);
407 }
drhd0960592015-08-17 21:22:32 +0000408 }
drh505ad2c2015-08-21 17:33:11 +0000409 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000410 }
drh52216ad2015-08-18 02:28:03 +0000411 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
412 pNode = &pNode[pNode->u.iAppend];
413 j = 1;
drh5634cc02015-08-17 11:28:03 +0000414 }
415 jsonAppendChar(pOut, '}');
416 break;
417 }
drhbd0621b2015-08-13 13:54:59 +0000418 }
drh5634cc02015-08-17 11:28:03 +0000419}
420
421/*
drhf2df7e72015-08-28 20:07:40 +0000422** Return a JsonNode and all its descendents as a JSON string.
423*/
424static void jsonReturnJson(
425 JsonNode *pNode, /* Node to return */
426 sqlite3_context *pCtx, /* Return value for this function */
427 sqlite3_value **aReplace /* Array of replacement values */
428){
429 JsonString s;
430 jsonInit(&s, pCtx);
431 jsonRenderNode(pNode, &s, aReplace);
432 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000433 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000434}
435
436/*
drh5634cc02015-08-17 11:28:03 +0000437** Make the JsonNode the return value of the function.
438*/
drhd0960592015-08-17 21:22:32 +0000439static void jsonReturn(
440 JsonNode *pNode, /* Node to return */
441 sqlite3_context *pCtx, /* Return value for this function */
442 sqlite3_value **aReplace /* Array of replacement values */
443){
drh5634cc02015-08-17 11:28:03 +0000444 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000445 default: {
446 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000447 sqlite3_result_null(pCtx);
448 break;
449 }
450 case JSON_TRUE: {
451 sqlite3_result_int(pCtx, 1);
452 break;
453 }
454 case JSON_FALSE: {
455 sqlite3_result_int(pCtx, 0);
456 break;
457 }
drh987eb1f2015-08-17 15:17:37 +0000458 case JSON_REAL: {
drh52216ad2015-08-18 02:28:03 +0000459 double r = strtod(pNode->u.zJContent, 0);
drh987eb1f2015-08-17 15:17:37 +0000460 sqlite3_result_double(pCtx, r);
drh5634cc02015-08-17 11:28:03 +0000461 break;
462 }
drh987eb1f2015-08-17 15:17:37 +0000463 case JSON_INT: {
464 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000465 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000466 if( z[0]=='-' ){ z++; }
467 while( z[0]>='0' && z[0]<='9' ){ i = i*10 + *(z++) - '0'; }
drh52216ad2015-08-18 02:28:03 +0000468 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000469 sqlite3_result_int64(pCtx, i);
470 break;
471 }
drh5634cc02015-08-17 11:28:03 +0000472 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000473#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
474 ** json_insert() and json_replace() and those routines do not
475 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000476 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000477 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
478 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000479 }else
480#endif
481 assert( (pNode->jnFlags & JNODE_RAW)==0 );
482 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000483 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000484 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000485 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000486 }else{
487 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000488 u32 i;
489 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000490 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000491 char *zOut;
492 u32 j;
493 zOut = sqlite3_malloc( n+1 );
494 if( zOut==0 ){
495 sqlite3_result_error_nomem(pCtx);
496 break;
497 }
498 for(i=1, j=0; i<n-1; i++){
499 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000500 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000501 zOut[j++] = c;
502 }else{
503 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000504 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000505 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000506 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000507 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000508 if( c>='0' && c<='9' ) v = v*16 + c - '0';
509 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
510 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
511 else break;
drh987eb1f2015-08-17 15:17:37 +0000512 }
drh80d87402015-08-24 12:42:41 +0000513 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000514 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000515 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000516 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000517 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000518 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000519 }else{
mistachkin16a93122015-09-11 18:05:01 +0000520 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000521 zOut[j++] = 0x80 | ((v>>6)&0x3f);
522 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000523 }
524 }else{
525 if( c=='b' ){
526 c = '\b';
527 }else if( c=='f' ){
528 c = '\f';
529 }else if( c=='n' ){
530 c = '\n';
531 }else if( c=='r' ){
532 c = '\r';
533 }else if( c=='t' ){
534 c = '\t';
535 }
536 zOut[j++] = c;
537 }
538 }
539 }
540 zOut[j] = 0;
541 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000542 }
543 break;
544 }
545 case JSON_ARRAY:
546 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000547 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000548 break;
549 }
550 }
drhbd0621b2015-08-13 13:54:59 +0000551}
552
drh5fa5c102015-08-12 16:49:40 +0000553/*
drhe9c37f32015-08-15 21:25:36 +0000554** Create a new JsonNode instance based on the arguments and append that
555** instance to the JsonParse. Return the index in pParse->aNode[] of the
556** new node, or -1 if a memory allocation fails.
557*/
558static int jsonParseAddNode(
559 JsonParse *pParse, /* Append the node to this object */
560 u32 eType, /* Node type */
561 u32 n, /* Content size or sub-node count */
562 const char *zContent /* Content */
563){
564 JsonNode *p;
565 if( pParse->nNode>=pParse->nAlloc ){
566 u32 nNew;
567 JsonNode *pNew;
568 if( pParse->oom ) return -1;
569 nNew = pParse->nAlloc*2 + 10;
570 if( nNew<=pParse->nNode ){
571 pParse->oom = 1;
572 return -1;
573 }
574 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
575 if( pNew==0 ){
576 pParse->oom = 1;
577 return -1;
578 }
579 pParse->nAlloc = nNew;
580 pParse->aNode = pNew;
581 }
582 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000583 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000584 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000585 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000586 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000587 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000588 return pParse->nNode++;
589}
590
591/*
592** Parse a single JSON value which begins at pParse->zJson[i]. Return the
593** index of the first character past the end of the value parsed.
594**
595** Return negative for a syntax error. Special cases: return -2 if the
596** first non-whitespace character is '}' and return -3 if the first
597** non-whitespace character is ']'.
598*/
599static int jsonParseValue(JsonParse *pParse, u32 i){
600 char c;
601 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000602 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000603 int x;
drh852944e2015-09-10 03:29:11 +0000604 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000605 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drhe9c37f32015-08-15 21:25:36 +0000606 if( (c = pParse->zJson[i])==0 ) return 0;
607 if( c=='{' ){
608 /* Parse object */
609 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000610 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000611 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000612 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000613 x = jsonParseValue(pParse, j);
614 if( x<0 ){
drha8f39a92015-09-21 22:53:16 +0000615 if( x==(-2) ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000616 return -1;
617 }
drhbe9474e2015-08-22 03:05:54 +0000618 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000619 pNode = &pParse->aNode[pParse->nNode-1];
620 if( pNode->eType!=JSON_STRING ) return -1;
621 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000622 j = x;
dan2e8f5512015-09-17 17:21:09 +0000623 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000624 if( pParse->zJson[j]!=':' ) return -1;
625 j++;
626 x = jsonParseValue(pParse, j);
627 if( x<0 ) return -1;
628 j = x;
dan2e8f5512015-09-17 17:21:09 +0000629 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000630 c = pParse->zJson[j];
631 if( c==',' ) continue;
632 if( c!='}' ) return -1;
633 break;
634 }
drhbc8f0922015-08-22 19:39:04 +0000635 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000636 return j+1;
637 }else if( c=='[' ){
638 /* Parse array */
639 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000640 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000641 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000642 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000643 x = jsonParseValue(pParse, j);
644 if( x<0 ){
drha8f39a92015-09-21 22:53:16 +0000645 if( x==(-3) ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000646 return -1;
647 }
648 j = x;
dan2e8f5512015-09-17 17:21:09 +0000649 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000650 c = pParse->zJson[j];
651 if( c==',' ) continue;
652 if( c!=']' ) return -1;
653 break;
654 }
drhbc8f0922015-08-22 19:39:04 +0000655 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000656 return j+1;
657 }else if( c=='"' ){
658 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000659 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000660 j = i+1;
661 for(;;){
662 c = pParse->zJson[j];
663 if( c==0 ) return -1;
664 if( c=='\\' ){
665 c = pParse->zJson[++j];
666 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000667 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000668 }else if( c=='"' ){
669 break;
670 }
671 j++;
672 }
673 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000674 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000675 return j+1;
676 }else if( c=='n'
677 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000678 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000679 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
680 return i+4;
681 }else if( c=='t'
682 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000683 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000684 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
685 return i+4;
686 }else if( c=='f'
687 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000688 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000689 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
690 return i+5;
691 }else if( c=='-' || (c>='0' && c<='9') ){
692 /* Parse number */
693 u8 seenDP = 0;
694 u8 seenE = 0;
695 j = i+1;
696 for(;; j++){
697 c = pParse->zJson[j];
698 if( c>='0' && c<='9' ) continue;
699 if( c=='.' ){
700 if( pParse->zJson[j-1]=='-' ) return -1;
701 if( seenDP ) return -1;
702 seenDP = 1;
703 continue;
704 }
705 if( c=='e' || c=='E' ){
706 if( pParse->zJson[j-1]<'0' ) return -1;
707 if( seenE ) return -1;
708 seenDP = seenE = 1;
709 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000710 if( c=='+' || c=='-' ){
711 j++;
712 c = pParse->zJson[j+1];
713 }
drhd1f00682015-08-29 16:02:37 +0000714 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000715 continue;
716 }
717 break;
718 }
719 if( pParse->zJson[j-1]<'0' ) return -1;
720 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
721 j - i, &pParse->zJson[i]);
722 return j;
723 }else if( c=='}' ){
724 return -2; /* End of {...} */
725 }else if( c==']' ){
726 return -3; /* End of [...] */
727 }else{
728 return -1; /* Syntax error */
729 }
730}
731
732/*
733** Parse a complete JSON string. Return 0 on success or non-zero if there
734** are any errors. If an error occurs, free all memory associated with
735** pParse.
736**
737** pParse is uninitialized when this routine is called.
738*/
drhbc8f0922015-08-22 19:39:04 +0000739static int jsonParse(
740 JsonParse *pParse, /* Initialize and fill this JsonParse object */
741 sqlite3_context *pCtx, /* Report errors here */
742 const char *zJson /* Input JSON text to be parsed */
743){
drhe9c37f32015-08-15 21:25:36 +0000744 int i;
drhe9c37f32015-08-15 21:25:36 +0000745 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000746 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000747 pParse->zJson = zJson;
748 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000749 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000750 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000751 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000752 if( zJson[i] ) i = -1;
753 }
drhd1f00682015-08-29 16:02:37 +0000754 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000755 if( pCtx!=0 ){
756 if( pParse->oom ){
757 sqlite3_result_error_nomem(pCtx);
758 }else{
759 sqlite3_result_error(pCtx, "malformed JSON", -1);
760 }
761 }
drh505ad2c2015-08-21 17:33:11 +0000762 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000763 return 1;
764 }
765 return 0;
766}
drh301eecc2015-08-17 20:14:19 +0000767
drh505ad2c2015-08-21 17:33:11 +0000768/* Mark node i of pParse as being a child of iParent. Call recursively
769** to fill in all the descendants of node i.
770*/
771static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
772 JsonNode *pNode = &pParse->aNode[i];
773 u32 j;
774 pParse->aUp[i] = iParent;
775 switch( pNode->eType ){
776 case JSON_ARRAY: {
777 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
778 jsonParseFillInParentage(pParse, i+j, i);
779 }
780 break;
781 }
782 case JSON_OBJECT: {
783 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
784 pParse->aUp[i+j] = i;
785 jsonParseFillInParentage(pParse, i+j+1, i);
786 }
787 break;
788 }
789 default: {
790 break;
791 }
792 }
793}
794
795/*
796** Compute the parentage of all nodes in a completed parse.
797*/
798static int jsonParseFindParents(JsonParse *pParse){
799 u32 *aUp;
800 assert( pParse->aUp==0 );
801 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000802 if( aUp==0 ){
803 pParse->oom = 1;
804 return SQLITE_NOMEM;
805 }
drh505ad2c2015-08-21 17:33:11 +0000806 jsonParseFillInParentage(pParse, 0, 0);
807 return SQLITE_OK;
808}
809
drh8cb0c832015-09-22 00:21:03 +0000810/*
811** Compare the OBJECT label at pNode against zKey,nKey. Return true on
812** a match.
813*/
814static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
815 if( pNode->jnFlags & JNODE_RAW ){
816 if( pNode->n!=nKey ) return 0;
817 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
818 }else{
819 if( pNode->n!=nKey+2 ) return 0;
820 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
821 }
822}
823
drh52216ad2015-08-18 02:28:03 +0000824/* forward declaration */
drha7714022015-08-29 00:54:49 +0000825static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000826
drh987eb1f2015-08-17 15:17:37 +0000827/*
828** Search along zPath to find the node specified. Return a pointer
829** to that node, or NULL if zPath is malformed or if there is no such
830** node.
drh52216ad2015-08-18 02:28:03 +0000831**
832** If pApnd!=0, then try to append new nodes to complete zPath if it is
833** possible to do so and if no existing node corresponds to zPath. If
834** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000835*/
drha7714022015-08-29 00:54:49 +0000836static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000837 JsonParse *pParse, /* The JSON to search */
838 u32 iRoot, /* Begin the search at this node */
839 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000840 int *pApnd, /* Append nodes to complete path if not NULL */
841 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000842){
drhbc8f0922015-08-22 19:39:04 +0000843 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000844 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000845 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000846 if( zPath[0]==0 ) return pRoot;
847 if( zPath[0]=='.' ){
848 if( pRoot->eType!=JSON_OBJECT ) return 0;
849 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000850 if( zPath[0]=='"' ){
851 zKey = zPath + 1;
852 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
853 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000854 if( zPath[i] ){
855 i++;
856 }else{
857 *pzErr = zPath;
858 return 0;
859 }
drh6b43cc82015-08-19 23:02:49 +0000860 }else{
861 zKey = zPath;
862 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
863 nKey = i;
864 }
drha7714022015-08-29 00:54:49 +0000865 if( nKey==0 ){
866 *pzErr = zPath;
867 return 0;
868 }
drh987eb1f2015-08-17 15:17:37 +0000869 j = 1;
drh52216ad2015-08-18 02:28:03 +0000870 for(;;){
871 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000872 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000873 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000874 }
875 j++;
drh505ad2c2015-08-21 17:33:11 +0000876 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000877 }
drh52216ad2015-08-18 02:28:03 +0000878 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
879 iRoot += pRoot->u.iAppend;
880 pRoot = &pParse->aNode[iRoot];
881 j = 1;
882 }
883 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000884 u32 iStart, iLabel;
885 JsonNode *pNode;
886 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
887 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000888 zPath += i;
drha7714022015-08-29 00:54:49 +0000889 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000890 if( pParse->oom ) return 0;
891 if( pNode ){
892 pRoot = &pParse->aNode[iRoot];
893 pRoot->u.iAppend = iStart - iRoot;
894 pRoot->jnFlags |= JNODE_APPEND;
895 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
896 }
897 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000898 }
dan2e8f5512015-09-17 17:21:09 +0000899 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000900 if( pRoot->eType!=JSON_ARRAY ) return 0;
901 i = 0;
902 zPath++;
dan2e8f5512015-09-17 17:21:09 +0000903 while( safe_isdigit(zPath[0]) ){
drh8784eca2015-08-23 02:42:30 +0000904 i = i*10 + zPath[0] - '0';
drh987eb1f2015-08-17 15:17:37 +0000905 zPath++;
906 }
drha7714022015-08-29 00:54:49 +0000907 if( zPath[0]!=']' ){
908 *pzErr = zPath;
909 return 0;
910 }
drh987eb1f2015-08-17 15:17:37 +0000911 zPath++;
912 j = 1;
drh52216ad2015-08-18 02:28:03 +0000913 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000914 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
915 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000916 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000917 }
918 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
919 iRoot += pRoot->u.iAppend;
920 pRoot = &pParse->aNode[iRoot];
921 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000922 }
923 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000924 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000925 }
926 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000927 u32 iStart;
928 JsonNode *pNode;
929 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +0000930 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000931 if( pParse->oom ) return 0;
932 if( pNode ){
933 pRoot = &pParse->aNode[iRoot];
934 pRoot->u.iAppend = iStart - iRoot;
935 pRoot->jnFlags |= JNODE_APPEND;
936 }
937 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000938 }
drha7714022015-08-29 00:54:49 +0000939 }else if( zPath[0]!=0 ){
940 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +0000941 }
942 return 0;
943}
944
drh52216ad2015-08-18 02:28:03 +0000945/*
drhbc8f0922015-08-22 19:39:04 +0000946** Append content to pParse that will complete zPath. Return a pointer
947** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000948*/
949static JsonNode *jsonLookupAppend(
950 JsonParse *pParse, /* Append content to the JSON parse */
951 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +0000952 int *pApnd, /* Set this flag to 1 */
953 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +0000954){
955 *pApnd = 1;
956 if( zPath[0]==0 ){
957 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
958 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
959 }
960 if( zPath[0]=='.' ){
961 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
962 }else if( strncmp(zPath,"[0]",3)==0 ){
963 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
964 }else{
965 return 0;
966 }
967 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +0000968 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000969}
970
drhbc8f0922015-08-22 19:39:04 +0000971/*
drha7714022015-08-29 00:54:49 +0000972** Return the text of a syntax error message on a JSON path. Space is
973** obtained from sqlite3_malloc().
974*/
975static char *jsonPathSyntaxError(const char *zErr){
976 return sqlite3_mprintf("JSON path error near '%q'", zErr);
977}
978
979/*
980** Do a node lookup using zPath. Return a pointer to the node on success.
981** Return NULL if not found or if there is an error.
982**
983** On an error, write an error message into pCtx and increment the
984** pParse->nErr counter.
985**
986** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
987** nodes are appended.
drha7714022015-08-29 00:54:49 +0000988*/
989static JsonNode *jsonLookup(
990 JsonParse *pParse, /* The JSON to search */
991 const char *zPath, /* The path to search */
992 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +0000993 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +0000994){
995 const char *zErr = 0;
996 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +0000997 char *zMsg;
drha7714022015-08-29 00:54:49 +0000998
999 if( zPath==0 ) return 0;
1000 if( zPath[0]!='$' ){
1001 zErr = zPath;
1002 goto lookup_err;
1003 }
1004 zPath++;
drha7714022015-08-29 00:54:49 +00001005 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001006 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001007
1008lookup_err:
1009 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001010 assert( zErr!=0 && pCtx!=0 );
1011 zMsg = jsonPathSyntaxError(zErr);
1012 if( zMsg ){
1013 sqlite3_result_error(pCtx, zMsg, -1);
1014 sqlite3_free(zMsg);
1015 }else{
1016 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001017 }
drha7714022015-08-29 00:54:49 +00001018 return 0;
1019}
1020
1021
1022/*
drhbc8f0922015-08-22 19:39:04 +00001023** Report the wrong number of arguments for json_insert(), json_replace()
1024** or json_set().
1025*/
1026static void jsonWrongNumArgs(
1027 sqlite3_context *pCtx,
1028 const char *zFuncName
1029){
1030 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1031 zFuncName);
1032 sqlite3_result_error(pCtx, zMsg, -1);
1033 sqlite3_free(zMsg);
1034}
drh52216ad2015-08-18 02:28:03 +00001035
drha7714022015-08-29 00:54:49 +00001036
drh987eb1f2015-08-17 15:17:37 +00001037/****************************************************************************
1038** SQL functions used for testing and debugging
1039****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001040
drh301eecc2015-08-17 20:14:19 +00001041#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001042/*
drh5634cc02015-08-17 11:28:03 +00001043** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001044** a parse of the JSON provided. Or it returns NULL if JSON is not
1045** well-formed.
1046*/
drh5634cc02015-08-17 11:28:03 +00001047static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001048 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001049 int argc,
1050 sqlite3_value **argv
1051){
drh505ad2c2015-08-21 17:33:11 +00001052 JsonString s; /* Output string - not real JSON */
1053 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001054 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001055
1056 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001057 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001058 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001059 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001060 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001061 const char *zType;
1062 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1063 assert( x.aNode[i].eType==JSON_STRING );
1064 zType = "label";
1065 }else{
1066 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001067 }
drh852944e2015-09-10 03:29:11 +00001068 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1069 i, zType, x.aNode[i].n, x.aUp[i]);
1070 if( x.aNode[i].u.zJContent!=0 ){
1071 jsonAppendRaw(&s, " ", 1);
1072 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1073 }
1074 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001075 }
drh505ad2c2015-08-21 17:33:11 +00001076 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001077 jsonResult(&s);
1078}
1079
drh5634cc02015-08-17 11:28:03 +00001080/*
drhf5ddb9c2015-09-11 00:06:41 +00001081** The json_test1(JSON) function return true (1) if the input is JSON
1082** text generated by another json function. It returns (0) if the input
1083** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001084*/
1085static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001086 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001087 int argc,
1088 sqlite3_value **argv
1089){
mistachkin16a93122015-09-11 18:05:01 +00001090 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001091 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001092}
drh301eecc2015-08-17 20:14:19 +00001093#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001094
drh987eb1f2015-08-17 15:17:37 +00001095/****************************************************************************
1096** SQL function implementations
1097****************************************************************************/
1098
1099/*
1100** Implementation of the json_array(VALUE,...) function. Return a JSON
1101** array that contains all values given in arguments. Or if any argument
1102** is a BLOB, throw an error.
1103*/
1104static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001105 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001106 int argc,
1107 sqlite3_value **argv
1108){
1109 int i;
drh505ad2c2015-08-21 17:33:11 +00001110 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001111
drhbc8f0922015-08-22 19:39:04 +00001112 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001113 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001114 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001115 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001116 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001117 }
drhd0960592015-08-17 21:22:32 +00001118 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001119 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001120 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001121}
1122
1123
1124/*
1125** json_array_length(JSON)
1126** json_array_length(JSON, PATH)
1127**
1128** Return the number of elements in the top-level JSON array.
1129** Return 0 if the input is not a well-formed JSON array.
1130*/
1131static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001132 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001133 int argc,
1134 sqlite3_value **argv
1135){
1136 JsonParse x; /* The parse */
1137 sqlite3_int64 n = 0;
1138 u32 i;
drha8f39a92015-09-21 22:53:16 +00001139 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001140
drhf2df7e72015-08-28 20:07:40 +00001141 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001142 assert( x.nNode );
1143 if( argc==2 ){
1144 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1145 pNode = jsonLookup(&x, zPath, 0, ctx);
1146 }else{
1147 pNode = x.aNode;
1148 }
1149 if( pNode==0 ){
1150 x.nErr = 1;
1151 }else if( pNode->eType==JSON_ARRAY ){
1152 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1153 for(i=1; i<=pNode->n; n++){
1154 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001155 }
drh987eb1f2015-08-17 15:17:37 +00001156 }
drha7714022015-08-29 00:54:49 +00001157 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001158 jsonParseReset(&x);
1159}
1160
1161/*
drh3ad93bb2015-08-29 19:41:45 +00001162** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001163**
drh3ad93bb2015-08-29 19:41:45 +00001164** Return the element described by PATH. Return NULL if there is no
1165** PATH element. If there are multiple PATHs, then return a JSON array
1166** with the result from each path. Throw an error if the JSON or any PATH
1167** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001168*/
1169static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001170 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001171 int argc,
1172 sqlite3_value **argv
1173){
1174 JsonParse x; /* The parse */
1175 JsonNode *pNode;
1176 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001177 JsonString jx;
1178 int i;
1179
1180 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001181 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001182 jsonInit(&jx, ctx);
1183 jsonAppendChar(&jx, '[');
1184 for(i=1; i<argc; i++){
1185 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001186 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001187 if( x.nErr ) break;
1188 if( argc>2 ){
1189 jsonAppendSeparator(&jx);
1190 if( pNode ){
1191 jsonRenderNode(pNode, &jx, 0);
1192 }else{
1193 jsonAppendRaw(&jx, "null", 4);
1194 }
1195 }else if( pNode ){
1196 jsonReturn(pNode, ctx, 0);
1197 }
drh987eb1f2015-08-17 15:17:37 +00001198 }
drh3ad93bb2015-08-29 19:41:45 +00001199 if( argc>2 && i==argc ){
1200 jsonAppendChar(&jx, ']');
1201 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001202 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001203 }
1204 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001205 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001206}
1207
1208/*
1209** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1210** object that contains all name/value given in arguments. Or if any name
1211** is not a string or if any value is a BLOB, throw an error.
1212*/
1213static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001214 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001215 int argc,
1216 sqlite3_value **argv
1217){
1218 int i;
drh505ad2c2015-08-21 17:33:11 +00001219 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001220 const char *z;
1221 u32 n;
1222
1223 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001224 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001225 "of arguments", -1);
1226 return;
1227 }
drhbc8f0922015-08-22 19:39:04 +00001228 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001229 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001230 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001231 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001232 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001233 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001234 return;
1235 }
drhd0960592015-08-17 21:22:32 +00001236 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001237 z = (const char*)sqlite3_value_text(argv[i]);
1238 n = (u32)sqlite3_value_bytes(argv[i]);
1239 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001240 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001241 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001242 }
drhd0960592015-08-17 21:22:32 +00001243 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001244 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001245 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001246}
1247
1248
1249/*
drh301eecc2015-08-17 20:14:19 +00001250** json_remove(JSON, PATH, ...)
1251**
drh3ad93bb2015-08-29 19:41:45 +00001252** Remove the named elements from JSON and return the result. malformed
1253** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001254*/
1255static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001256 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001257 int argc,
1258 sqlite3_value **argv
1259){
1260 JsonParse x; /* The parse */
1261 JsonNode *pNode;
1262 const char *zPath;
1263 u32 i;
1264
1265 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001266 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001267 assert( x.nNode );
1268 for(i=1; i<(u32)argc; i++){
1269 zPath = (const char*)sqlite3_value_text(argv[i]);
1270 if( zPath==0 ) goto remove_done;
1271 pNode = jsonLookup(&x, zPath, 0, ctx);
1272 if( x.nErr ) goto remove_done;
1273 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1274 }
1275 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1276 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001277 }
drha7714022015-08-29 00:54:49 +00001278remove_done:
drh505ad2c2015-08-21 17:33:11 +00001279 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001280}
1281
1282/*
1283** json_replace(JSON, PATH, VALUE, ...)
1284**
1285** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001286** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001287*/
1288static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001289 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001290 int argc,
1291 sqlite3_value **argv
1292){
1293 JsonParse x; /* The parse */
1294 JsonNode *pNode;
1295 const char *zPath;
1296 u32 i;
1297
1298 if( argc<1 ) return;
1299 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001300 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001301 return;
1302 }
drhbc8f0922015-08-22 19:39:04 +00001303 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001304 assert( x.nNode );
1305 for(i=1; i<(u32)argc; i+=2){
1306 zPath = (const char*)sqlite3_value_text(argv[i]);
1307 pNode = jsonLookup(&x, zPath, 0, ctx);
1308 if( x.nErr ) goto replace_err;
1309 if( pNode ){
1310 pNode->jnFlags |= (u8)JNODE_REPLACE;
1311 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001312 }
drha8f39a92015-09-21 22:53:16 +00001313 }
1314 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1315 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1316 }else{
1317 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001318 }
drha7714022015-08-29 00:54:49 +00001319replace_err:
drh505ad2c2015-08-21 17:33:11 +00001320 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001321}
drh505ad2c2015-08-21 17:33:11 +00001322
drh52216ad2015-08-18 02:28:03 +00001323/*
1324** json_set(JSON, PATH, VALUE, ...)
1325**
1326** Set the value at PATH to VALUE. Create the PATH if it does not already
1327** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001328** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001329**
1330** json_insert(JSON, PATH, VALUE, ...)
1331**
1332** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001333** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001334*/
1335static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001336 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001337 int argc,
1338 sqlite3_value **argv
1339){
1340 JsonParse x; /* The parse */
1341 JsonNode *pNode;
1342 const char *zPath;
1343 u32 i;
1344 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001345 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001346
1347 if( argc<1 ) return;
1348 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001349 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001350 return;
1351 }
drhbc8f0922015-08-22 19:39:04 +00001352 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001353 assert( x.nNode );
1354 for(i=1; i<(u32)argc; i+=2){
1355 zPath = (const char*)sqlite3_value_text(argv[i]);
1356 bApnd = 0;
1357 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1358 if( x.oom ){
1359 sqlite3_result_error_nomem(ctx);
1360 goto jsonSetDone;
1361 }else if( x.nErr ){
1362 goto jsonSetDone;
1363 }else if( pNode && (bApnd || bIsSet) ){
1364 pNode->jnFlags |= (u8)JNODE_REPLACE;
1365 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001366 }
drha8f39a92015-09-21 22:53:16 +00001367 }
1368 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1369 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1370 }else{
1371 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001372 }
drhbc8f0922015-08-22 19:39:04 +00001373jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001374 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001375}
drh301eecc2015-08-17 20:14:19 +00001376
1377/*
drh987eb1f2015-08-17 15:17:37 +00001378** json_type(JSON)
1379** json_type(JSON, PATH)
1380**
drh3ad93bb2015-08-29 19:41:45 +00001381** Return the top-level "type" of a JSON string. Throw an error if
1382** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001383*/
1384static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001385 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001386 int argc,
1387 sqlite3_value **argv
1388){
1389 JsonParse x; /* The parse */
1390 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001391 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001392
drhbc8f0922015-08-22 19:39:04 +00001393 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001394 assert( x.nNode );
1395 if( argc==2 ){
1396 zPath = (const char*)sqlite3_value_text(argv[1]);
1397 pNode = jsonLookup(&x, zPath, 0, ctx);
1398 }else{
1399 pNode = x.aNode;
1400 }
1401 if( pNode ){
1402 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001403 }
drh505ad2c2015-08-21 17:33:11 +00001404 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001405}
drh5634cc02015-08-17 11:28:03 +00001406
drhbc8f0922015-08-22 19:39:04 +00001407/*
1408** json_valid(JSON)
1409**
drh3ad93bb2015-08-29 19:41:45 +00001410** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1411** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001412*/
1413static void jsonValidFunc(
1414 sqlite3_context *ctx,
1415 int argc,
1416 sqlite3_value **argv
1417){
1418 JsonParse x; /* The parse */
1419 int rc = 0;
1420
mistachkin16a93122015-09-11 18:05:01 +00001421 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001422 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001423 rc = 1;
1424 }
1425 jsonParseReset(&x);
1426 sqlite3_result_int(ctx, rc);
1427}
1428
drhd2975922015-08-29 17:22:33 +00001429#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001430/****************************************************************************
1431** The json_each virtual table
1432****************************************************************************/
1433typedef struct JsonEachCursor JsonEachCursor;
1434struct JsonEachCursor {
1435 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001436 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001437 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001438 u32 i; /* Index in sParse.aNode[] of current row */
1439 u32 iEnd; /* EOF when i equals or exceeds this value */
1440 u8 eType; /* Type of top-level element */
1441 u8 bRecursive; /* True for json_tree(). False for json_each() */
1442 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001443 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001444 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001445};
1446
1447/* Constructor for the json_each virtual table */
1448static int jsonEachConnect(
1449 sqlite3 *db,
1450 void *pAux,
1451 int argc, const char *const*argv,
1452 sqlite3_vtab **ppVtab,
1453 char **pzErr
1454){
1455 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001456 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001457
1458/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001459#define JEACH_KEY 0
1460#define JEACH_VALUE 1
1461#define JEACH_TYPE 2
1462#define JEACH_ATOM 3
1463#define JEACH_ID 4
1464#define JEACH_PARENT 5
1465#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001466#define JEACH_PATH 7
1467#define JEACH_JSON 8
1468#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001469
drh6fd5c1e2015-08-21 20:37:12 +00001470 UNUSED_PARAM(pzErr);
1471 UNUSED_PARAM(argv);
1472 UNUSED_PARAM(argc);
1473 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001474 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001475 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1476 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001477 if( rc==SQLITE_OK ){
1478 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1479 if( pNew==0 ) return SQLITE_NOMEM;
1480 memset(pNew, 0, sizeof(*pNew));
1481 }
1482 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001483}
1484
1485/* destructor for json_each virtual table */
1486static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1487 sqlite3_free(pVtab);
1488 return SQLITE_OK;
1489}
1490
drh505ad2c2015-08-21 17:33:11 +00001491/* constructor for a JsonEachCursor object for json_each(). */
1492static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001493 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001494
1495 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001496 pCur = sqlite3_malloc( sizeof(*pCur) );
1497 if( pCur==0 ) return SQLITE_NOMEM;
1498 memset(pCur, 0, sizeof(*pCur));
1499 *ppCursor = &pCur->base;
1500 return SQLITE_OK;
1501}
1502
drh505ad2c2015-08-21 17:33:11 +00001503/* constructor for a JsonEachCursor object for json_tree(). */
1504static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1505 int rc = jsonEachOpenEach(p, ppCursor);
1506 if( rc==SQLITE_OK ){
1507 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1508 pCur->bRecursive = 1;
1509 }
1510 return rc;
1511}
1512
drhcb6c6c62015-08-19 22:47:17 +00001513/* Reset a JsonEachCursor back to its original state. Free any memory
1514** held. */
1515static void jsonEachCursorReset(JsonEachCursor *p){
1516 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001517 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001518 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001519 p->iRowid = 0;
1520 p->i = 0;
1521 p->iEnd = 0;
1522 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001523 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001524 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001525}
1526
1527/* Destructor for a jsonEachCursor object */
1528static int jsonEachClose(sqlite3_vtab_cursor *cur){
1529 JsonEachCursor *p = (JsonEachCursor*)cur;
1530 jsonEachCursorReset(p);
1531 sqlite3_free(cur);
1532 return SQLITE_OK;
1533}
1534
1535/* Return TRUE if the jsonEachCursor object has been advanced off the end
1536** of the JSON object */
1537static int jsonEachEof(sqlite3_vtab_cursor *cur){
1538 JsonEachCursor *p = (JsonEachCursor*)cur;
1539 return p->i >= p->iEnd;
1540}
1541
drh505ad2c2015-08-21 17:33:11 +00001542/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001543static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001544 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001545 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001546 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1547 p->i++;
drh4af352d2015-08-21 20:02:48 +00001548 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001549 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001550 u32 iUp = p->sParse.aUp[p->i];
1551 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001552 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001553 if( pUp->eType==JSON_ARRAY ){
1554 if( iUp==p->i-1 ){
1555 pUp->u.iKey = 0;
1556 }else{
1557 pUp->u.iKey++;
1558 }
drh4af352d2015-08-21 20:02:48 +00001559 }
1560 }
drh505ad2c2015-08-21 17:33:11 +00001561 }else{
drh4af352d2015-08-21 20:02:48 +00001562 switch( p->eType ){
1563 case JSON_ARRAY: {
1564 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1565 p->iRowid++;
1566 break;
1567 }
1568 case JSON_OBJECT: {
1569 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1570 p->iRowid++;
1571 break;
1572 }
1573 default: {
1574 p->i = p->iEnd;
1575 break;
1576 }
drh505ad2c2015-08-21 17:33:11 +00001577 }
1578 }
1579 return SQLITE_OK;
1580}
1581
drh4af352d2015-08-21 20:02:48 +00001582/* Append the name of the path for element i to pStr
1583*/
1584static void jsonEachComputePath(
1585 JsonEachCursor *p, /* The cursor */
1586 JsonString *pStr, /* Write the path here */
1587 u32 i /* Path to this element */
1588){
1589 JsonNode *pNode, *pUp;
1590 u32 iUp;
1591 if( i==0 ){
1592 jsonAppendChar(pStr, '$');
1593 return;
drhcb6c6c62015-08-19 22:47:17 +00001594 }
drh4af352d2015-08-21 20:02:48 +00001595 iUp = p->sParse.aUp[i];
1596 jsonEachComputePath(p, pStr, iUp);
1597 pNode = &p->sParse.aNode[i];
1598 pUp = &p->sParse.aNode[iUp];
1599 if( pUp->eType==JSON_ARRAY ){
1600 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1601 }else{
1602 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001603 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001604 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001605 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001606 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1607 }
drhcb6c6c62015-08-19 22:47:17 +00001608}
1609
1610/* Return the value of a column */
1611static int jsonEachColumn(
1612 sqlite3_vtab_cursor *cur, /* The cursor */
1613 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1614 int i /* Which column to return */
1615){
1616 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001617 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001618 switch( i ){
1619 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001620 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001621 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001622 jsonReturn(pThis, ctx, 0);
1623 }else if( p->eType==JSON_ARRAY ){
1624 u32 iKey;
1625 if( p->bRecursive ){
1626 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001627 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001628 }else{
1629 iKey = p->iRowid;
1630 }
drh6fd5c1e2015-08-21 20:37:12 +00001631 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001632 }
1633 break;
1634 }
1635 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001636 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001637 jsonReturn(pThis, ctx, 0);
1638 break;
1639 }
1640 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001641 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001642 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1643 break;
1644 }
1645 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001646 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001647 if( pThis->eType>=JSON_ARRAY ) break;
1648 jsonReturn(pThis, ctx, 0);
1649 break;
1650 }
1651 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001652 sqlite3_result_int64(ctx,
1653 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001654 break;
1655 }
1656 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001657 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001658 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001659 }
1660 break;
1661 }
drh4af352d2015-08-21 20:02:48 +00001662 case JEACH_FULLKEY: {
1663 JsonString x;
1664 jsonInit(&x, ctx);
1665 if( p->bRecursive ){
1666 jsonEachComputePath(p, &x, p->i);
1667 }else{
drh383de692015-09-10 17:20:57 +00001668 if( p->zRoot ){
1669 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001670 }else{
1671 jsonAppendChar(&x, '$');
1672 }
1673 if( p->eType==JSON_ARRAY ){
1674 jsonPrintf(30, &x, "[%d]", p->iRowid);
1675 }else{
1676 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1677 }
1678 }
1679 jsonResult(&x);
1680 break;
1681 }
drhcb6c6c62015-08-19 22:47:17 +00001682 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001683 if( p->bRecursive ){
1684 JsonString x;
1685 jsonInit(&x, ctx);
1686 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1687 jsonResult(&x);
1688 break;
drh4af352d2015-08-21 20:02:48 +00001689 }
drh383de692015-09-10 17:20:57 +00001690 /* For json_each() path and root are the same so fall through
1691 ** into the root case */
1692 }
1693 case JEACH_ROOT: {
1694 const char *zRoot = p->zRoot;
1695 if( zRoot==0 ) zRoot = "$";
1696 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001697 break;
1698 }
1699 default: {
drh505ad2c2015-08-21 17:33:11 +00001700 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001701 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1702 break;
1703 }
1704 }
1705 return SQLITE_OK;
1706}
1707
1708/* Return the current rowid value */
1709static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1710 JsonEachCursor *p = (JsonEachCursor*)cur;
1711 *pRowid = p->iRowid;
1712 return SQLITE_OK;
1713}
1714
1715/* The query strategy is to look for an equality constraint on the json
1716** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001717** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001718** and 0 otherwise.
1719*/
1720static int jsonEachBestIndex(
1721 sqlite3_vtab *tab,
1722 sqlite3_index_info *pIdxInfo
1723){
1724 int i;
1725 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001726 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001727 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001728
1729 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001730 pConstraint = pIdxInfo->aConstraint;
1731 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1732 if( pConstraint->usable==0 ) continue;
1733 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1734 switch( pConstraint->iColumn ){
1735 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001736 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001737 default: /* no-op */ break;
1738 }
1739 }
1740 if( jsonIdx<0 ){
1741 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001742 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001743 }else{
drh505ad2c2015-08-21 17:33:11 +00001744 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001745 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1746 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001747 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001748 pIdxInfo->idxNum = 1;
1749 }else{
drh383de692015-09-10 17:20:57 +00001750 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1751 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001752 pIdxInfo->idxNum = 3;
1753 }
1754 }
1755 return SQLITE_OK;
1756}
1757
1758/* Start a search on a new JSON string */
1759static int jsonEachFilter(
1760 sqlite3_vtab_cursor *cur,
1761 int idxNum, const char *idxStr,
1762 int argc, sqlite3_value **argv
1763){
1764 JsonEachCursor *p = (JsonEachCursor*)cur;
1765 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001766 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001767 sqlite3_int64 n;
1768
drh6fd5c1e2015-08-21 20:37:12 +00001769 UNUSED_PARAM(idxStr);
1770 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001771 jsonEachCursorReset(p);
1772 if( idxNum==0 ) return SQLITE_OK;
1773 z = (const char*)sqlite3_value_text(argv[0]);
1774 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001775 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001776 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001777 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001778 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001779 if( jsonParse(&p->sParse, 0, p->zJson) ){
1780 int rc = SQLITE_NOMEM;
1781 if( p->sParse.oom==0 ){
1782 sqlite3_free(cur->pVtab->zErrMsg);
1783 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1784 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1785 }
drhcb6c6c62015-08-19 22:47:17 +00001786 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001787 return rc;
1788 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1789 jsonEachCursorReset(p);
1790 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001791 }else{
1792 JsonNode *pNode;
1793 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001794 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001795 zRoot = (const char*)sqlite3_value_text(argv[1]);
1796 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001797 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001798 p->zRoot = sqlite3_malloc64( n+1 );
1799 if( p->zRoot==0 ) return SQLITE_NOMEM;
1800 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001801 if( zRoot[0]!='$' ){
1802 zErr = zRoot;
1803 }else{
1804 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1805 }
1806 if( zErr ){
drha7714022015-08-29 00:54:49 +00001807 sqlite3_free(cur->pVtab->zErrMsg);
1808 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001809 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001810 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1811 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001812 return SQLITE_OK;
1813 }
1814 }else{
1815 pNode = p->sParse.aNode;
1816 }
drh852944e2015-09-10 03:29:11 +00001817 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001818 p->eType = pNode->eType;
1819 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001820 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001821 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001822 if( p->bRecursive ){
1823 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1824 p->i--;
1825 }
1826 }else{
1827 p->i++;
1828 }
drhcb6c6c62015-08-19 22:47:17 +00001829 }else{
1830 p->iEnd = p->i+1;
1831 }
1832 }
drha8f39a92015-09-21 22:53:16 +00001833 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001834}
1835
1836/* The methods of the json_each virtual table */
1837static sqlite3_module jsonEachModule = {
1838 0, /* iVersion */
1839 0, /* xCreate */
1840 jsonEachConnect, /* xConnect */
1841 jsonEachBestIndex, /* xBestIndex */
1842 jsonEachDisconnect, /* xDisconnect */
1843 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001844 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001845 jsonEachClose, /* xClose - close a cursor */
1846 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001847 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001848 jsonEachEof, /* xEof - check for end of scan */
1849 jsonEachColumn, /* xColumn - read data */
1850 jsonEachRowid, /* xRowid - read data */
1851 0, /* xUpdate */
1852 0, /* xBegin */
1853 0, /* xSync */
1854 0, /* xCommit */
1855 0, /* xRollback */
1856 0, /* xFindMethod */
1857 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001858 0, /* xSavepoint */
1859 0, /* xRelease */
1860 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001861};
1862
drh505ad2c2015-08-21 17:33:11 +00001863/* The methods of the json_tree virtual table. */
1864static sqlite3_module jsonTreeModule = {
1865 0, /* iVersion */
1866 0, /* xCreate */
1867 jsonEachConnect, /* xConnect */
1868 jsonEachBestIndex, /* xBestIndex */
1869 jsonEachDisconnect, /* xDisconnect */
1870 0, /* xDestroy */
1871 jsonEachOpenTree, /* xOpen - open a cursor */
1872 jsonEachClose, /* xClose - close a cursor */
1873 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001874 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001875 jsonEachEof, /* xEof - check for end of scan */
1876 jsonEachColumn, /* xColumn - read data */
1877 jsonEachRowid, /* xRowid - read data */
1878 0, /* xUpdate */
1879 0, /* xBegin */
1880 0, /* xSync */
1881 0, /* xCommit */
1882 0, /* xRollback */
1883 0, /* xFindMethod */
1884 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001885 0, /* xSavepoint */
1886 0, /* xRelease */
1887 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001888};
drhd2975922015-08-29 17:22:33 +00001889#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001890
1891/****************************************************************************
1892** The following routine is the only publically visible identifier in this
1893** file. Call the following routine in order to register the various SQL
1894** functions and the virtual table implemented by this file.
1895****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001896
drh5fa5c102015-08-12 16:49:40 +00001897#ifdef _WIN32
1898__declspec(dllexport)
1899#endif
1900int sqlite3_json_init(
1901 sqlite3 *db,
1902 char **pzErrMsg,
1903 const sqlite3_api_routines *pApi
1904){
1905 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001906 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001907 static const struct {
1908 const char *zName;
1909 int nArg;
drh52216ad2015-08-18 02:28:03 +00001910 int flag;
drh5fa5c102015-08-12 16:49:40 +00001911 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1912 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001913 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001914 { "json_array", -1, 0, jsonArrayFunc },
1915 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1916 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001917 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001918 { "json_insert", -1, 0, jsonSetFunc },
1919 { "json_object", -1, 0, jsonObjectFunc },
1920 { "json_remove", -1, 0, jsonRemoveFunc },
1921 { "json_replace", -1, 0, jsonReplaceFunc },
1922 { "json_set", -1, 1, jsonSetFunc },
1923 { "json_type", 1, 0, jsonTypeFunc },
1924 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001925 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001926
drh301eecc2015-08-17 20:14:19 +00001927#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001928 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001929 { "json_parse", 1, 0, jsonParseFunc },
1930 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001931#endif
drh5fa5c102015-08-12 16:49:40 +00001932 };
drhd2975922015-08-29 17:22:33 +00001933#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001934 static const struct {
1935 const char *zName;
1936 sqlite3_module *pModule;
1937 } aMod[] = {
1938 { "json_each", &jsonEachModule },
1939 { "json_tree", &jsonTreeModule },
1940 };
drhd2975922015-08-29 17:22:33 +00001941#endif
drh5fa5c102015-08-12 16:49:40 +00001942 SQLITE_EXTENSION_INIT2(pApi);
1943 (void)pzErrMsg; /* Unused parameter */
1944 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1945 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001946 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1947 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001948 aFunc[i].xFunc, 0, 0);
1949 }
drhd2975922015-08-29 17:22:33 +00001950#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001951 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1952 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00001953 }
drhd2975922015-08-29 17:22:33 +00001954#endif
drh5fa5c102015-08-12 16:49:40 +00001955 return rc;
1956}