blob: 4e21b151a71b5404ec7d8995c5441a316f786b51 [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
drh52216ad2015-08-18 02:28:03 +0000810/* forward declaration */
drha7714022015-08-29 00:54:49 +0000811static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000812
drh987eb1f2015-08-17 15:17:37 +0000813/*
814** Search along zPath to find the node specified. Return a pointer
815** to that node, or NULL if zPath is malformed or if there is no such
816** node.
drh52216ad2015-08-18 02:28:03 +0000817**
818** If pApnd!=0, then try to append new nodes to complete zPath if it is
819** possible to do so and if no existing node corresponds to zPath. If
820** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000821*/
drha7714022015-08-29 00:54:49 +0000822static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000823 JsonParse *pParse, /* The JSON to search */
824 u32 iRoot, /* Begin the search at this node */
825 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000826 int *pApnd, /* Append nodes to complete path if not NULL */
827 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000828){
drhbc8f0922015-08-22 19:39:04 +0000829 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000830 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000831 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000832 if( zPath[0]==0 ) return pRoot;
833 if( zPath[0]=='.' ){
834 if( pRoot->eType!=JSON_OBJECT ) return 0;
835 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000836 if( zPath[0]=='"' ){
837 zKey = zPath + 1;
838 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
839 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000840 if( zPath[i] ){
841 i++;
842 }else{
843 *pzErr = zPath;
844 return 0;
845 }
drh6b43cc82015-08-19 23:02:49 +0000846 }else{
847 zKey = zPath;
848 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
849 nKey = i;
850 }
drha7714022015-08-29 00:54:49 +0000851 if( nKey==0 ){
852 *pzErr = zPath;
853 return 0;
854 }
drh987eb1f2015-08-17 15:17:37 +0000855 j = 1;
drh52216ad2015-08-18 02:28:03 +0000856 for(;;){
857 while( j<=pRoot->n ){
drh6b43cc82015-08-19 23:02:49 +0000858 if( pRoot[j].n==nKey+2
859 && strncmp(&pRoot[j].u.zJContent[1],zKey,nKey)==0
drh52216ad2015-08-18 02:28:03 +0000860 ){
drha7714022015-08-29 00:54:49 +0000861 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000862 }
863 j++;
drh505ad2c2015-08-21 17:33:11 +0000864 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000865 }
drh52216ad2015-08-18 02:28:03 +0000866 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
867 iRoot += pRoot->u.iAppend;
868 pRoot = &pParse->aNode[iRoot];
869 j = 1;
870 }
871 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000872 u32 iStart, iLabel;
873 JsonNode *pNode;
874 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
875 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000876 zPath += i;
drha7714022015-08-29 00:54:49 +0000877 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000878 if( pParse->oom ) return 0;
879 if( pNode ){
880 pRoot = &pParse->aNode[iRoot];
881 pRoot->u.iAppend = iStart - iRoot;
882 pRoot->jnFlags |= JNODE_APPEND;
883 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
884 }
885 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000886 }
dan2e8f5512015-09-17 17:21:09 +0000887 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000888 if( pRoot->eType!=JSON_ARRAY ) return 0;
889 i = 0;
890 zPath++;
dan2e8f5512015-09-17 17:21:09 +0000891 while( safe_isdigit(zPath[0]) ){
drh8784eca2015-08-23 02:42:30 +0000892 i = i*10 + zPath[0] - '0';
drh987eb1f2015-08-17 15:17:37 +0000893 zPath++;
894 }
drha7714022015-08-29 00:54:49 +0000895 if( zPath[0]!=']' ){
896 *pzErr = zPath;
897 return 0;
898 }
drh987eb1f2015-08-17 15:17:37 +0000899 zPath++;
900 j = 1;
drh52216ad2015-08-18 02:28:03 +0000901 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000902 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
903 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000904 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000905 }
906 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
907 iRoot += pRoot->u.iAppend;
908 pRoot = &pParse->aNode[iRoot];
909 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000910 }
911 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000912 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000913 }
914 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000915 u32 iStart;
916 JsonNode *pNode;
917 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +0000918 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000919 if( pParse->oom ) return 0;
920 if( pNode ){
921 pRoot = &pParse->aNode[iRoot];
922 pRoot->u.iAppend = iStart - iRoot;
923 pRoot->jnFlags |= JNODE_APPEND;
924 }
925 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000926 }
drha7714022015-08-29 00:54:49 +0000927 }else if( zPath[0]!=0 ){
928 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +0000929 }
930 return 0;
931}
932
drh52216ad2015-08-18 02:28:03 +0000933/*
drhbc8f0922015-08-22 19:39:04 +0000934** Append content to pParse that will complete zPath. Return a pointer
935** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000936*/
937static JsonNode *jsonLookupAppend(
938 JsonParse *pParse, /* Append content to the JSON parse */
939 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +0000940 int *pApnd, /* Set this flag to 1 */
941 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +0000942){
943 *pApnd = 1;
944 if( zPath[0]==0 ){
945 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
946 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
947 }
948 if( zPath[0]=='.' ){
949 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
950 }else if( strncmp(zPath,"[0]",3)==0 ){
951 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
952 }else{
953 return 0;
954 }
955 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +0000956 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000957}
958
drhbc8f0922015-08-22 19:39:04 +0000959/*
drha7714022015-08-29 00:54:49 +0000960** Return the text of a syntax error message on a JSON path. Space is
961** obtained from sqlite3_malloc().
962*/
963static char *jsonPathSyntaxError(const char *zErr){
964 return sqlite3_mprintf("JSON path error near '%q'", zErr);
965}
966
967/*
968** Do a node lookup using zPath. Return a pointer to the node on success.
969** Return NULL if not found or if there is an error.
970**
971** On an error, write an error message into pCtx and increment the
972** pParse->nErr counter.
973**
974** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
975** nodes are appended.
drha7714022015-08-29 00:54:49 +0000976*/
977static JsonNode *jsonLookup(
978 JsonParse *pParse, /* The JSON to search */
979 const char *zPath, /* The path to search */
980 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +0000981 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +0000982){
983 const char *zErr = 0;
984 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +0000985 char *zMsg;
drha7714022015-08-29 00:54:49 +0000986
987 if( zPath==0 ) return 0;
988 if( zPath[0]!='$' ){
989 zErr = zPath;
990 goto lookup_err;
991 }
992 zPath++;
drha7714022015-08-29 00:54:49 +0000993 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +0000994 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +0000995
996lookup_err:
997 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +0000998 assert( zErr!=0 && pCtx!=0 );
999 zMsg = jsonPathSyntaxError(zErr);
1000 if( zMsg ){
1001 sqlite3_result_error(pCtx, zMsg, -1);
1002 sqlite3_free(zMsg);
1003 }else{
1004 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001005 }
drha7714022015-08-29 00:54:49 +00001006 return 0;
1007}
1008
1009
1010/*
drhbc8f0922015-08-22 19:39:04 +00001011** Report the wrong number of arguments for json_insert(), json_replace()
1012** or json_set().
1013*/
1014static void jsonWrongNumArgs(
1015 sqlite3_context *pCtx,
1016 const char *zFuncName
1017){
1018 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1019 zFuncName);
1020 sqlite3_result_error(pCtx, zMsg, -1);
1021 sqlite3_free(zMsg);
1022}
drh52216ad2015-08-18 02:28:03 +00001023
drha7714022015-08-29 00:54:49 +00001024
drh987eb1f2015-08-17 15:17:37 +00001025/****************************************************************************
1026** SQL functions used for testing and debugging
1027****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001028
drh301eecc2015-08-17 20:14:19 +00001029#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001030/*
drh5634cc02015-08-17 11:28:03 +00001031** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001032** a parse of the JSON provided. Or it returns NULL if JSON is not
1033** well-formed.
1034*/
drh5634cc02015-08-17 11:28:03 +00001035static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001036 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001037 int argc,
1038 sqlite3_value **argv
1039){
drh505ad2c2015-08-21 17:33:11 +00001040 JsonString s; /* Output string - not real JSON */
1041 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001042 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001043
1044 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001045 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001046 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001047 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001048 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001049 const char *zType;
1050 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1051 assert( x.aNode[i].eType==JSON_STRING );
1052 zType = "label";
1053 }else{
1054 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001055 }
drh852944e2015-09-10 03:29:11 +00001056 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1057 i, zType, x.aNode[i].n, x.aUp[i]);
1058 if( x.aNode[i].u.zJContent!=0 ){
1059 jsonAppendRaw(&s, " ", 1);
1060 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1061 }
1062 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001063 }
drh505ad2c2015-08-21 17:33:11 +00001064 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001065 jsonResult(&s);
1066}
1067
drh5634cc02015-08-17 11:28:03 +00001068/*
drhf5ddb9c2015-09-11 00:06:41 +00001069** The json_test1(JSON) function return true (1) if the input is JSON
1070** text generated by another json function. It returns (0) if the input
1071** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001072*/
1073static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001074 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001075 int argc,
1076 sqlite3_value **argv
1077){
mistachkin16a93122015-09-11 18:05:01 +00001078 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001079 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001080}
drh301eecc2015-08-17 20:14:19 +00001081#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001082
drh987eb1f2015-08-17 15:17:37 +00001083/****************************************************************************
1084** SQL function implementations
1085****************************************************************************/
1086
1087/*
1088** Implementation of the json_array(VALUE,...) function. Return a JSON
1089** array that contains all values given in arguments. Or if any argument
1090** is a BLOB, throw an error.
1091*/
1092static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001093 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001094 int argc,
1095 sqlite3_value **argv
1096){
1097 int i;
drh505ad2c2015-08-21 17:33:11 +00001098 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001099
drhbc8f0922015-08-22 19:39:04 +00001100 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001101 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001102 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001103 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001104 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001105 }
drhd0960592015-08-17 21:22:32 +00001106 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001107 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001108 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001109}
1110
1111
1112/*
1113** json_array_length(JSON)
1114** json_array_length(JSON, PATH)
1115**
1116** Return the number of elements in the top-level JSON array.
1117** Return 0 if the input is not a well-formed JSON array.
1118*/
1119static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001120 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001121 int argc,
1122 sqlite3_value **argv
1123){
1124 JsonParse x; /* The parse */
1125 sqlite3_int64 n = 0;
1126 u32 i;
drha8f39a92015-09-21 22:53:16 +00001127 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001128
drhf2df7e72015-08-28 20:07:40 +00001129 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001130 assert( x.nNode );
1131 if( argc==2 ){
1132 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1133 pNode = jsonLookup(&x, zPath, 0, ctx);
1134 }else{
1135 pNode = x.aNode;
1136 }
1137 if( pNode==0 ){
1138 x.nErr = 1;
1139 }else if( pNode->eType==JSON_ARRAY ){
1140 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1141 for(i=1; i<=pNode->n; n++){
1142 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001143 }
drh987eb1f2015-08-17 15:17:37 +00001144 }
drha7714022015-08-29 00:54:49 +00001145 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001146 jsonParseReset(&x);
1147}
1148
1149/*
drh3ad93bb2015-08-29 19:41:45 +00001150** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001151**
drh3ad93bb2015-08-29 19:41:45 +00001152** Return the element described by PATH. Return NULL if there is no
1153** PATH element. If there are multiple PATHs, then return a JSON array
1154** with the result from each path. Throw an error if the JSON or any PATH
1155** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001156*/
1157static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001158 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001159 int argc,
1160 sqlite3_value **argv
1161){
1162 JsonParse x; /* The parse */
1163 JsonNode *pNode;
1164 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001165 JsonString jx;
1166 int i;
1167
1168 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001169 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001170 jsonInit(&jx, ctx);
1171 jsonAppendChar(&jx, '[');
1172 for(i=1; i<argc; i++){
1173 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001174 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001175 if( x.nErr ) break;
1176 if( argc>2 ){
1177 jsonAppendSeparator(&jx);
1178 if( pNode ){
1179 jsonRenderNode(pNode, &jx, 0);
1180 }else{
1181 jsonAppendRaw(&jx, "null", 4);
1182 }
1183 }else if( pNode ){
1184 jsonReturn(pNode, ctx, 0);
1185 }
drh987eb1f2015-08-17 15:17:37 +00001186 }
drh3ad93bb2015-08-29 19:41:45 +00001187 if( argc>2 && i==argc ){
1188 jsonAppendChar(&jx, ']');
1189 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001190 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001191 }
1192 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001193 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001194}
1195
1196/*
1197** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1198** object that contains all name/value given in arguments. Or if any name
1199** is not a string or if any value is a BLOB, throw an error.
1200*/
1201static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001202 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001203 int argc,
1204 sqlite3_value **argv
1205){
1206 int i;
drh505ad2c2015-08-21 17:33:11 +00001207 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001208 const char *z;
1209 u32 n;
1210
1211 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001212 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001213 "of arguments", -1);
1214 return;
1215 }
drhbc8f0922015-08-22 19:39:04 +00001216 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001217 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001218 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001219 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001220 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001221 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001222 return;
1223 }
drhd0960592015-08-17 21:22:32 +00001224 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001225 z = (const char*)sqlite3_value_text(argv[i]);
1226 n = (u32)sqlite3_value_bytes(argv[i]);
1227 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001228 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001229 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001230 }
drhd0960592015-08-17 21:22:32 +00001231 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001232 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001233 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001234}
1235
1236
1237/*
drh301eecc2015-08-17 20:14:19 +00001238** json_remove(JSON, PATH, ...)
1239**
drh3ad93bb2015-08-29 19:41:45 +00001240** Remove the named elements from JSON and return the result. malformed
1241** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001242*/
1243static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001244 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001245 int argc,
1246 sqlite3_value **argv
1247){
1248 JsonParse x; /* The parse */
1249 JsonNode *pNode;
1250 const char *zPath;
1251 u32 i;
1252
1253 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001254 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001255 assert( x.nNode );
1256 for(i=1; i<(u32)argc; i++){
1257 zPath = (const char*)sqlite3_value_text(argv[i]);
1258 if( zPath==0 ) goto remove_done;
1259 pNode = jsonLookup(&x, zPath, 0, ctx);
1260 if( x.nErr ) goto remove_done;
1261 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1262 }
1263 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1264 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001265 }
drha7714022015-08-29 00:54:49 +00001266remove_done:
drh505ad2c2015-08-21 17:33:11 +00001267 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001268}
1269
1270/*
1271** json_replace(JSON, PATH, VALUE, ...)
1272**
1273** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001274** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001275*/
1276static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001277 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001278 int argc,
1279 sqlite3_value **argv
1280){
1281 JsonParse x; /* The parse */
1282 JsonNode *pNode;
1283 const char *zPath;
1284 u32 i;
1285
1286 if( argc<1 ) return;
1287 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001288 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001289 return;
1290 }
drhbc8f0922015-08-22 19:39:04 +00001291 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001292 assert( x.nNode );
1293 for(i=1; i<(u32)argc; i+=2){
1294 zPath = (const char*)sqlite3_value_text(argv[i]);
1295 pNode = jsonLookup(&x, zPath, 0, ctx);
1296 if( x.nErr ) goto replace_err;
1297 if( pNode ){
1298 pNode->jnFlags |= (u8)JNODE_REPLACE;
1299 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001300 }
drha8f39a92015-09-21 22:53:16 +00001301 }
1302 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1303 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1304 }else{
1305 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001306 }
drha7714022015-08-29 00:54:49 +00001307replace_err:
drh505ad2c2015-08-21 17:33:11 +00001308 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001309}
drh505ad2c2015-08-21 17:33:11 +00001310
drh52216ad2015-08-18 02:28:03 +00001311/*
1312** json_set(JSON, PATH, VALUE, ...)
1313**
1314** Set the value at PATH to VALUE. Create the PATH if it does not already
1315** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001316** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001317**
1318** json_insert(JSON, PATH, VALUE, ...)
1319**
1320** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001321** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001322*/
1323static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001324 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001325 int argc,
1326 sqlite3_value **argv
1327){
1328 JsonParse x; /* The parse */
1329 JsonNode *pNode;
1330 const char *zPath;
1331 u32 i;
1332 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001333 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001334
1335 if( argc<1 ) return;
1336 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001337 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001338 return;
1339 }
drhbc8f0922015-08-22 19:39:04 +00001340 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001341 assert( x.nNode );
1342 for(i=1; i<(u32)argc; i+=2){
1343 zPath = (const char*)sqlite3_value_text(argv[i]);
1344 bApnd = 0;
1345 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1346 if( x.oom ){
1347 sqlite3_result_error_nomem(ctx);
1348 goto jsonSetDone;
1349 }else if( x.nErr ){
1350 goto jsonSetDone;
1351 }else if( pNode && (bApnd || bIsSet) ){
1352 pNode->jnFlags |= (u8)JNODE_REPLACE;
1353 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001354 }
drha8f39a92015-09-21 22:53:16 +00001355 }
1356 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1357 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1358 }else{
1359 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001360 }
drhbc8f0922015-08-22 19:39:04 +00001361jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001362 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001363}
drh301eecc2015-08-17 20:14:19 +00001364
1365/*
drh987eb1f2015-08-17 15:17:37 +00001366** json_type(JSON)
1367** json_type(JSON, PATH)
1368**
drh3ad93bb2015-08-29 19:41:45 +00001369** Return the top-level "type" of a JSON string. Throw an error if
1370** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001371*/
1372static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001373 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001374 int argc,
1375 sqlite3_value **argv
1376){
1377 JsonParse x; /* The parse */
1378 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001379 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001380
drhbc8f0922015-08-22 19:39:04 +00001381 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001382 assert( x.nNode );
1383 if( argc==2 ){
1384 zPath = (const char*)sqlite3_value_text(argv[1]);
1385 pNode = jsonLookup(&x, zPath, 0, ctx);
1386 }else{
1387 pNode = x.aNode;
1388 }
1389 if( pNode ){
1390 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001391 }
drh505ad2c2015-08-21 17:33:11 +00001392 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001393}
drh5634cc02015-08-17 11:28:03 +00001394
drhbc8f0922015-08-22 19:39:04 +00001395/*
1396** json_valid(JSON)
1397**
drh3ad93bb2015-08-29 19:41:45 +00001398** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1399** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001400*/
1401static void jsonValidFunc(
1402 sqlite3_context *ctx,
1403 int argc,
1404 sqlite3_value **argv
1405){
1406 JsonParse x; /* The parse */
1407 int rc = 0;
1408
mistachkin16a93122015-09-11 18:05:01 +00001409 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001410 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001411 rc = 1;
1412 }
1413 jsonParseReset(&x);
1414 sqlite3_result_int(ctx, rc);
1415}
1416
drhd2975922015-08-29 17:22:33 +00001417#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001418/****************************************************************************
1419** The json_each virtual table
1420****************************************************************************/
1421typedef struct JsonEachCursor JsonEachCursor;
1422struct JsonEachCursor {
1423 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001424 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001425 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001426 u32 i; /* Index in sParse.aNode[] of current row */
1427 u32 iEnd; /* EOF when i equals or exceeds this value */
1428 u8 eType; /* Type of top-level element */
1429 u8 bRecursive; /* True for json_tree(). False for json_each() */
1430 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001431 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001432 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001433};
1434
1435/* Constructor for the json_each virtual table */
1436static int jsonEachConnect(
1437 sqlite3 *db,
1438 void *pAux,
1439 int argc, const char *const*argv,
1440 sqlite3_vtab **ppVtab,
1441 char **pzErr
1442){
1443 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001444 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001445
1446/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001447#define JEACH_KEY 0
1448#define JEACH_VALUE 1
1449#define JEACH_TYPE 2
1450#define JEACH_ATOM 3
1451#define JEACH_ID 4
1452#define JEACH_PARENT 5
1453#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001454#define JEACH_PATH 7
1455#define JEACH_JSON 8
1456#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001457
drh6fd5c1e2015-08-21 20:37:12 +00001458 UNUSED_PARAM(pzErr);
1459 UNUSED_PARAM(argv);
1460 UNUSED_PARAM(argc);
1461 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001462 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001463 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1464 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001465 if( rc==SQLITE_OK ){
1466 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1467 if( pNew==0 ) return SQLITE_NOMEM;
1468 memset(pNew, 0, sizeof(*pNew));
1469 }
1470 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001471}
1472
1473/* destructor for json_each virtual table */
1474static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1475 sqlite3_free(pVtab);
1476 return SQLITE_OK;
1477}
1478
drh505ad2c2015-08-21 17:33:11 +00001479/* constructor for a JsonEachCursor object for json_each(). */
1480static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001481 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001482
1483 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001484 pCur = sqlite3_malloc( sizeof(*pCur) );
1485 if( pCur==0 ) return SQLITE_NOMEM;
1486 memset(pCur, 0, sizeof(*pCur));
1487 *ppCursor = &pCur->base;
1488 return SQLITE_OK;
1489}
1490
drh505ad2c2015-08-21 17:33:11 +00001491/* constructor for a JsonEachCursor object for json_tree(). */
1492static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1493 int rc = jsonEachOpenEach(p, ppCursor);
1494 if( rc==SQLITE_OK ){
1495 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1496 pCur->bRecursive = 1;
1497 }
1498 return rc;
1499}
1500
drhcb6c6c62015-08-19 22:47:17 +00001501/* Reset a JsonEachCursor back to its original state. Free any memory
1502** held. */
1503static void jsonEachCursorReset(JsonEachCursor *p){
1504 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001505 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001506 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001507 p->iRowid = 0;
1508 p->i = 0;
1509 p->iEnd = 0;
1510 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001511 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001512 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001513}
1514
1515/* Destructor for a jsonEachCursor object */
1516static int jsonEachClose(sqlite3_vtab_cursor *cur){
1517 JsonEachCursor *p = (JsonEachCursor*)cur;
1518 jsonEachCursorReset(p);
1519 sqlite3_free(cur);
1520 return SQLITE_OK;
1521}
1522
1523/* Return TRUE if the jsonEachCursor object has been advanced off the end
1524** of the JSON object */
1525static int jsonEachEof(sqlite3_vtab_cursor *cur){
1526 JsonEachCursor *p = (JsonEachCursor*)cur;
1527 return p->i >= p->iEnd;
1528}
1529
drh505ad2c2015-08-21 17:33:11 +00001530/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001531static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001532 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001533 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001534 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1535 p->i++;
drh4af352d2015-08-21 20:02:48 +00001536 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001537 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001538 u32 iUp = p->sParse.aUp[p->i];
1539 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001540 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001541 if( pUp->eType==JSON_ARRAY ){
1542 if( iUp==p->i-1 ){
1543 pUp->u.iKey = 0;
1544 }else{
1545 pUp->u.iKey++;
1546 }
drh4af352d2015-08-21 20:02:48 +00001547 }
1548 }
drh505ad2c2015-08-21 17:33:11 +00001549 }else{
drh4af352d2015-08-21 20:02:48 +00001550 switch( p->eType ){
1551 case JSON_ARRAY: {
1552 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1553 p->iRowid++;
1554 break;
1555 }
1556 case JSON_OBJECT: {
1557 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1558 p->iRowid++;
1559 break;
1560 }
1561 default: {
1562 p->i = p->iEnd;
1563 break;
1564 }
drh505ad2c2015-08-21 17:33:11 +00001565 }
1566 }
1567 return SQLITE_OK;
1568}
1569
drh4af352d2015-08-21 20:02:48 +00001570/* Append the name of the path for element i to pStr
1571*/
1572static void jsonEachComputePath(
1573 JsonEachCursor *p, /* The cursor */
1574 JsonString *pStr, /* Write the path here */
1575 u32 i /* Path to this element */
1576){
1577 JsonNode *pNode, *pUp;
1578 u32 iUp;
1579 if( i==0 ){
1580 jsonAppendChar(pStr, '$');
1581 return;
drhcb6c6c62015-08-19 22:47:17 +00001582 }
drh4af352d2015-08-21 20:02:48 +00001583 iUp = p->sParse.aUp[i];
1584 jsonEachComputePath(p, pStr, iUp);
1585 pNode = &p->sParse.aNode[i];
1586 pUp = &p->sParse.aNode[iUp];
1587 if( pUp->eType==JSON_ARRAY ){
1588 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1589 }else{
1590 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001591 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001592 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001593 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001594 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1595 }
drhcb6c6c62015-08-19 22:47:17 +00001596}
1597
1598/* Return the value of a column */
1599static int jsonEachColumn(
1600 sqlite3_vtab_cursor *cur, /* The cursor */
1601 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1602 int i /* Which column to return */
1603){
1604 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001605 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001606 switch( i ){
1607 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001608 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001609 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001610 jsonReturn(pThis, ctx, 0);
1611 }else if( p->eType==JSON_ARRAY ){
1612 u32 iKey;
1613 if( p->bRecursive ){
1614 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001615 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001616 }else{
1617 iKey = p->iRowid;
1618 }
drh6fd5c1e2015-08-21 20:37:12 +00001619 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001620 }
1621 break;
1622 }
1623 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001624 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001625 jsonReturn(pThis, ctx, 0);
1626 break;
1627 }
1628 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001629 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001630 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1631 break;
1632 }
1633 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001634 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001635 if( pThis->eType>=JSON_ARRAY ) break;
1636 jsonReturn(pThis, ctx, 0);
1637 break;
1638 }
1639 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001640 sqlite3_result_int64(ctx,
1641 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001642 break;
1643 }
1644 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001645 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001646 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001647 }
1648 break;
1649 }
drh4af352d2015-08-21 20:02:48 +00001650 case JEACH_FULLKEY: {
1651 JsonString x;
1652 jsonInit(&x, ctx);
1653 if( p->bRecursive ){
1654 jsonEachComputePath(p, &x, p->i);
1655 }else{
drh383de692015-09-10 17:20:57 +00001656 if( p->zRoot ){
1657 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001658 }else{
1659 jsonAppendChar(&x, '$');
1660 }
1661 if( p->eType==JSON_ARRAY ){
1662 jsonPrintf(30, &x, "[%d]", p->iRowid);
1663 }else{
1664 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1665 }
1666 }
1667 jsonResult(&x);
1668 break;
1669 }
drhcb6c6c62015-08-19 22:47:17 +00001670 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001671 if( p->bRecursive ){
1672 JsonString x;
1673 jsonInit(&x, ctx);
1674 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1675 jsonResult(&x);
1676 break;
drh4af352d2015-08-21 20:02:48 +00001677 }
drh383de692015-09-10 17:20:57 +00001678 /* For json_each() path and root are the same so fall through
1679 ** into the root case */
1680 }
1681 case JEACH_ROOT: {
1682 const char *zRoot = p->zRoot;
1683 if( zRoot==0 ) zRoot = "$";
1684 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001685 break;
1686 }
1687 default: {
drh505ad2c2015-08-21 17:33:11 +00001688 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001689 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1690 break;
1691 }
1692 }
1693 return SQLITE_OK;
1694}
1695
1696/* Return the current rowid value */
1697static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1698 JsonEachCursor *p = (JsonEachCursor*)cur;
1699 *pRowid = p->iRowid;
1700 return SQLITE_OK;
1701}
1702
1703/* The query strategy is to look for an equality constraint on the json
1704** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001705** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001706** and 0 otherwise.
1707*/
1708static int jsonEachBestIndex(
1709 sqlite3_vtab *tab,
1710 sqlite3_index_info *pIdxInfo
1711){
1712 int i;
1713 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001714 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001715 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001716
1717 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001718 pConstraint = pIdxInfo->aConstraint;
1719 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1720 if( pConstraint->usable==0 ) continue;
1721 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1722 switch( pConstraint->iColumn ){
1723 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001724 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001725 default: /* no-op */ break;
1726 }
1727 }
1728 if( jsonIdx<0 ){
1729 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001730 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001731 }else{
drh505ad2c2015-08-21 17:33:11 +00001732 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001733 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1734 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001735 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001736 pIdxInfo->idxNum = 1;
1737 }else{
drh383de692015-09-10 17:20:57 +00001738 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1739 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001740 pIdxInfo->idxNum = 3;
1741 }
1742 }
1743 return SQLITE_OK;
1744}
1745
1746/* Start a search on a new JSON string */
1747static int jsonEachFilter(
1748 sqlite3_vtab_cursor *cur,
1749 int idxNum, const char *idxStr,
1750 int argc, sqlite3_value **argv
1751){
1752 JsonEachCursor *p = (JsonEachCursor*)cur;
1753 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001754 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001755 sqlite3_int64 n;
1756
drh6fd5c1e2015-08-21 20:37:12 +00001757 UNUSED_PARAM(idxStr);
1758 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001759 jsonEachCursorReset(p);
1760 if( idxNum==0 ) return SQLITE_OK;
1761 z = (const char*)sqlite3_value_text(argv[0]);
1762 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001763 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001764 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001765 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001766 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001767 if( jsonParse(&p->sParse, 0, p->zJson) ){
1768 int rc = SQLITE_NOMEM;
1769 if( p->sParse.oom==0 ){
1770 sqlite3_free(cur->pVtab->zErrMsg);
1771 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1772 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1773 }
drhcb6c6c62015-08-19 22:47:17 +00001774 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001775 return rc;
1776 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1777 jsonEachCursorReset(p);
1778 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001779 }else{
1780 JsonNode *pNode;
1781 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001782 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001783 zRoot = (const char*)sqlite3_value_text(argv[1]);
1784 if( zRoot==0 ) return SQLITE_OK;
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);
drha8f39a92015-09-21 22:53:16 +00001789 if( zRoot[0]!='$' ){
1790 zErr = zRoot;
1791 }else{
1792 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1793 }
1794 if( zErr ){
drha7714022015-08-29 00:54:49 +00001795 sqlite3_free(cur->pVtab->zErrMsg);
1796 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001797 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001798 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1799 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001800 return SQLITE_OK;
1801 }
1802 }else{
1803 pNode = p->sParse.aNode;
1804 }
drh852944e2015-09-10 03:29:11 +00001805 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001806 p->eType = pNode->eType;
1807 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001808 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001809 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001810 if( p->bRecursive ){
1811 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1812 p->i--;
1813 }
1814 }else{
1815 p->i++;
1816 }
drhcb6c6c62015-08-19 22:47:17 +00001817 }else{
1818 p->iEnd = p->i+1;
1819 }
1820 }
drha8f39a92015-09-21 22:53:16 +00001821 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001822}
1823
1824/* The methods of the json_each virtual table */
1825static sqlite3_module jsonEachModule = {
1826 0, /* iVersion */
1827 0, /* xCreate */
1828 jsonEachConnect, /* xConnect */
1829 jsonEachBestIndex, /* xBestIndex */
1830 jsonEachDisconnect, /* xDisconnect */
1831 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001832 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001833 jsonEachClose, /* xClose - close a cursor */
1834 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001835 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001836 jsonEachEof, /* xEof - check for end of scan */
1837 jsonEachColumn, /* xColumn - read data */
1838 jsonEachRowid, /* xRowid - read data */
1839 0, /* xUpdate */
1840 0, /* xBegin */
1841 0, /* xSync */
1842 0, /* xCommit */
1843 0, /* xRollback */
1844 0, /* xFindMethod */
1845 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001846 0, /* xSavepoint */
1847 0, /* xRelease */
1848 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001849};
1850
drh505ad2c2015-08-21 17:33:11 +00001851/* The methods of the json_tree virtual table. */
1852static sqlite3_module jsonTreeModule = {
1853 0, /* iVersion */
1854 0, /* xCreate */
1855 jsonEachConnect, /* xConnect */
1856 jsonEachBestIndex, /* xBestIndex */
1857 jsonEachDisconnect, /* xDisconnect */
1858 0, /* xDestroy */
1859 jsonEachOpenTree, /* xOpen - open a cursor */
1860 jsonEachClose, /* xClose - close a cursor */
1861 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001862 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001863 jsonEachEof, /* xEof - check for end of scan */
1864 jsonEachColumn, /* xColumn - read data */
1865 jsonEachRowid, /* xRowid - read data */
1866 0, /* xUpdate */
1867 0, /* xBegin */
1868 0, /* xSync */
1869 0, /* xCommit */
1870 0, /* xRollback */
1871 0, /* xFindMethod */
1872 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001873 0, /* xSavepoint */
1874 0, /* xRelease */
1875 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001876};
drhd2975922015-08-29 17:22:33 +00001877#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001878
1879/****************************************************************************
1880** The following routine is the only publically visible identifier in this
1881** file. Call the following routine in order to register the various SQL
1882** functions and the virtual table implemented by this file.
1883****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001884
drh5fa5c102015-08-12 16:49:40 +00001885#ifdef _WIN32
1886__declspec(dllexport)
1887#endif
1888int sqlite3_json_init(
1889 sqlite3 *db,
1890 char **pzErrMsg,
1891 const sqlite3_api_routines *pApi
1892){
1893 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001894 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001895 static const struct {
1896 const char *zName;
1897 int nArg;
drh52216ad2015-08-18 02:28:03 +00001898 int flag;
drh5fa5c102015-08-12 16:49:40 +00001899 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1900 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001901 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001902 { "json_array", -1, 0, jsonArrayFunc },
1903 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1904 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001905 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001906 { "json_insert", -1, 0, jsonSetFunc },
1907 { "json_object", -1, 0, jsonObjectFunc },
1908 { "json_remove", -1, 0, jsonRemoveFunc },
1909 { "json_replace", -1, 0, jsonReplaceFunc },
1910 { "json_set", -1, 1, jsonSetFunc },
1911 { "json_type", 1, 0, jsonTypeFunc },
1912 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001913 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001914
drh301eecc2015-08-17 20:14:19 +00001915#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001916 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001917 { "json_parse", 1, 0, jsonParseFunc },
1918 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001919#endif
drh5fa5c102015-08-12 16:49:40 +00001920 };
drhd2975922015-08-29 17:22:33 +00001921#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001922 static const struct {
1923 const char *zName;
1924 sqlite3_module *pModule;
1925 } aMod[] = {
1926 { "json_each", &jsonEachModule },
1927 { "json_tree", &jsonTreeModule },
1928 };
drhd2975922015-08-29 17:22:33 +00001929#endif
drh5fa5c102015-08-12 16:49:40 +00001930 SQLITE_EXTENSION_INIT2(pApi);
1931 (void)pzErrMsg; /* Unused parameter */
1932 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1933 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001934 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1935 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001936 aFunc[i].xFunc, 0, 0);
1937 }
drhd2975922015-08-29 17:22:33 +00001938#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001939 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1940 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00001941 }
drhd2975922015-08-29 17:22:33 +00001942#endif
drh5fa5c102015-08-12 16:49:40 +00001943 return rc;
1944}