blob: a68ef7469c15ab8284fe707e3122abbbf905dc88 [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*/
24#include "sqlite3ext.h"
25SQLITE_EXTENSION_INIT1
26#include <assert.h>
27#include <string.h>
drhe9c37f32015-08-15 21:25:36 +000028#include <ctype.h>
drh987eb1f2015-08-17 15:17:37 +000029#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000030#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000031
drh6fd5c1e2015-08-21 20:37:12 +000032#define UNUSED_PARAM(X) (void)(X)
33
drh5fa5c102015-08-12 16:49:40 +000034/* Unsigned integer types */
35typedef sqlite3_uint64 u64;
36typedef unsigned int u32;
37typedef unsigned char u8;
38
drh52216ad2015-08-18 02:28:03 +000039/* Objects */
drh505ad2c2015-08-21 17:33:11 +000040typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000041typedef struct JsonNode JsonNode;
42typedef struct JsonParse JsonParse;
43
drh5634cc02015-08-17 11:28:03 +000044/* An instance of this object represents a JSON string
45** under construction. Really, this is a generic string accumulator
46** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000047*/
drh505ad2c2015-08-21 17:33:11 +000048struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000049 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000050 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000051 u64 nAlloc; /* Bytes of storage available in zBuf[] */
52 u64 nUsed; /* Bytes of zBuf[] currently used */
53 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000054 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000055 char zSpace[100]; /* Initial static space */
56};
57
drhe9c37f32015-08-15 21:25:36 +000058/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000059*/
drhe9c37f32015-08-15 21:25:36 +000060#define JSON_NULL 0
61#define JSON_TRUE 1
62#define JSON_FALSE 2
63#define JSON_INT 3
64#define JSON_REAL 4
65#define JSON_STRING 5
66#define JSON_ARRAY 6
67#define JSON_OBJECT 7
68
drh987eb1f2015-08-17 15:17:37 +000069/*
70** Names of the various JSON types:
71*/
72static const char * const jsonType[] = {
73 "null", "true", "false", "integer", "real", "text", "array", "object"
74};
75
drh301eecc2015-08-17 20:14:19 +000076/* Bit values for the JsonNode.jnFlag field
77*/
78#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
79#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
80#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +000081#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +000082#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drh301eecc2015-08-17 20:14:19 +000083
drh987eb1f2015-08-17 15:17:37 +000084
drhe9c37f32015-08-15 21:25:36 +000085/* A single node of parsed JSON
86*/
drhe9c37f32015-08-15 21:25:36 +000087struct JsonNode {
drh5634cc02015-08-17 11:28:03 +000088 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +000089 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +000090 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +000091 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +000092 union {
drh0042a972015-08-18 12:59:58 +000093 const char *zJContent; /* Content for INT, REAL, and STRING */
94 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +000095 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +000096 } u;
drhe9c37f32015-08-15 21:25:36 +000097};
98
99/* A completely parsed JSON string
100*/
drhe9c37f32015-08-15 21:25:36 +0000101struct JsonParse {
102 u32 nNode; /* Number of slots of aNode[] used */
103 u32 nAlloc; /* Number of slots of aNode[] allocated */
104 JsonNode *aNode; /* Array of nodes containing the parse */
105 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000106 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000107 u8 oom; /* Set to true if out of memory */
108};
109
drh505ad2c2015-08-21 17:33:11 +0000110/**************************************************************************
111** Utility routines for dealing with JsonString objects
112**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000113
drh505ad2c2015-08-21 17:33:11 +0000114/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000115*/
drh505ad2c2015-08-21 17:33:11 +0000116static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000117 p->zBuf = p->zSpace;
118 p->nAlloc = sizeof(p->zSpace);
119 p->nUsed = 0;
120 p->bStatic = 1;
121}
122
drh505ad2c2015-08-21 17:33:11 +0000123/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000124*/
drh505ad2c2015-08-21 17:33:11 +0000125static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000126 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000127 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000128 jsonZero(p);
129}
130
131
drh505ad2c2015-08-21 17:33:11 +0000132/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000133** initial state.
134*/
drh505ad2c2015-08-21 17:33:11 +0000135static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000136 if( !p->bStatic ) sqlite3_free(p->zBuf);
137 jsonZero(p);
138}
139
140
141/* Report an out-of-memory (OOM) condition
142*/
drh505ad2c2015-08-21 17:33:11 +0000143static void jsonOom(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000144 if( !p->bErr ){
145 p->bErr = 1;
146 sqlite3_result_error_nomem(p->pCtx);
147 jsonReset(p);
148 }
drh5fa5c102015-08-12 16:49:40 +0000149}
150
151/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
152** Return zero on success. Return non-zero on an OOM error
153*/
drh505ad2c2015-08-21 17:33:11 +0000154static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000155 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000156 char *zNew;
157 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000158 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000159 zNew = sqlite3_malloc64(nTotal);
160 if( zNew==0 ){
161 jsonOom(p);
162 return SQLITE_NOMEM;
163 }
drh6fd5c1e2015-08-21 20:37:12 +0000164 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000165 p->zBuf = zNew;
166 p->bStatic = 0;
167 }else{
168 zNew = sqlite3_realloc64(p->zBuf, nTotal);
169 if( zNew==0 ){
170 jsonOom(p);
171 return SQLITE_NOMEM;
172 }
173 p->zBuf = zNew;
174 }
175 p->nAlloc = nTotal;
176 return SQLITE_OK;
177}
178
drh505ad2c2015-08-21 17:33:11 +0000179/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000180*/
drh505ad2c2015-08-21 17:33:11 +0000181static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000182 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
183 memcpy(p->zBuf+p->nUsed, zIn, N);
184 p->nUsed += N;
185}
186
drh4af352d2015-08-21 20:02:48 +0000187/* Append formatted text (not to exceed N bytes) to the JsonString.
188*/
189static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
190 va_list ap;
191 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
192 va_start(ap, zFormat);
193 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
194 va_end(ap);
195 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
196}
197
drhd0960592015-08-17 21:22:32 +0000198#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +0000199/* Append the zero-terminated string zIn
200*/
drh505ad2c2015-08-21 17:33:11 +0000201static void jsonAppend(JsonString *p, const char *zIn){
drhe9c37f32015-08-15 21:25:36 +0000202 jsonAppendRaw(p, zIn, (u32)strlen(zIn));
203}
drhd0960592015-08-17 21:22:32 +0000204#endif
drhe9c37f32015-08-15 21:25:36 +0000205
drh5634cc02015-08-17 11:28:03 +0000206/* Append a single character
207*/
drh505ad2c2015-08-21 17:33:11 +0000208static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000209 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
210 p->zBuf[p->nUsed++] = c;
211}
212
drh301eecc2015-08-17 20:14:19 +0000213/* Append a comma separator to the output buffer, if the previous
214** character is not '[' or '{'.
215*/
drh505ad2c2015-08-21 17:33:11 +0000216static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000217 char c;
218 if( p->nUsed==0 ) return;
219 c = p->zBuf[p->nUsed-1];
220 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
221}
222
drh505ad2c2015-08-21 17:33:11 +0000223/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000224** under construction. Enclose the string in "..." and escape
225** any double-quotes or backslash characters contained within the
226** string.
227*/
drh505ad2c2015-08-21 17:33:11 +0000228static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000229 u32 i;
230 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
231 p->zBuf[p->nUsed++] = '"';
232 for(i=0; i<N; i++){
233 char c = zIn[i];
234 if( c=='"' || c=='\\' ){
235 if( (p->nUsed+N+1-i > p->nAlloc) && jsonGrow(p,N+1-i)!=0 ) return;
236 p->zBuf[p->nUsed++] = '\\';
237 }
238 p->zBuf[p->nUsed++] = c;
239 }
240 p->zBuf[p->nUsed++] = '"';
241}
242
drhd0960592015-08-17 21:22:32 +0000243/*
244** Append a function parameter value to the JSON string under
245** construction.
246*/
247static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000248 JsonString *p, /* Append to this JSON string */
drhd0960592015-08-17 21:22:32 +0000249 sqlite3_value *pValue /* Value to append */
250){
251 switch( sqlite3_value_type(pValue) ){
252 case SQLITE_NULL: {
253 jsonAppendRaw(p, "null", 4);
254 break;
255 }
256 case SQLITE_INTEGER:
257 case SQLITE_FLOAT: {
258 const char *z = (const char*)sqlite3_value_text(pValue);
259 u32 n = (u32)sqlite3_value_bytes(pValue);
260 jsonAppendRaw(p, z, n);
261 break;
262 }
263 case SQLITE_TEXT: {
264 const char *z = (const char*)sqlite3_value_text(pValue);
265 u32 n = (u32)sqlite3_value_bytes(pValue);
266 jsonAppendString(p, z, n);
267 break;
268 }
269 default: {
270 if( p->bErr==0 ){
271 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
272 p->bErr = 1;
273 jsonReset(p);
274 }
275 break;
276 }
277 }
278}
279
280
drhbd0621b2015-08-13 13:54:59 +0000281/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000282*/
drh505ad2c2015-08-21 17:33:11 +0000283static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000284 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000285 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
286 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
287 SQLITE_UTF8);
288 jsonZero(p);
289 }
290 assert( p->bStatic );
291}
292
drh505ad2c2015-08-21 17:33:11 +0000293/**************************************************************************
294** Utility routines for dealing with JsonNode and JsonParse objects
295**************************************************************************/
296
297/*
298** Return the number of consecutive JsonNode slots need to represent
299** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
300** OBJECT types, the number might be larger.
301**
302** Appended elements are not counted. The value returned is the number
303** by which the JsonNode counter should increment in order to go to the
304** next peer value.
305*/
306static u32 jsonNodeSize(JsonNode *pNode){
307 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
308}
309
310/*
311** Reclaim all memory allocated by a JsonParse object. But do not
312** delete the JsonParse object itself.
313*/
314static void jsonParseReset(JsonParse *pParse){
315 sqlite3_free(pParse->aNode);
316 pParse->aNode = 0;
317 pParse->nNode = 0;
318 pParse->nAlloc = 0;
319 sqlite3_free(pParse->aUp);
320 pParse->aUp = 0;
321}
322
drh5634cc02015-08-17 11:28:03 +0000323/*
324** Convert the JsonNode pNode into a pure JSON string and
325** append to pOut. Subsubstructure is also included. Return
326** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000327*/
drh52216ad2015-08-18 02:28:03 +0000328static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000329 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000330 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000331 sqlite3_value **aReplace /* Replacement values */
332){
drh5634cc02015-08-17 11:28:03 +0000333 switch( pNode->eType ){
334 case JSON_NULL: {
335 jsonAppendRaw(pOut, "null", 4);
336 break;
337 }
338 case JSON_TRUE: {
339 jsonAppendRaw(pOut, "true", 4);
340 break;
341 }
342 case JSON_FALSE: {
343 jsonAppendRaw(pOut, "false", 5);
344 break;
345 }
346 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000347 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000348 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000349 break;
350 }
351 /* Fall through into the next case */
352 }
353 case JSON_REAL:
354 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000355 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000356 break;
357 }
358 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000359 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000360 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000361 for(;;){
362 while( j<=pNode->n ){
363 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
364 if( pNode[j].jnFlags & JNODE_REPLACE ){
365 jsonAppendSeparator(pOut);
366 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
367 }
368 }else{
drhd0960592015-08-17 21:22:32 +0000369 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000370 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000371 }
drh505ad2c2015-08-21 17:33:11 +0000372 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000373 }
drh52216ad2015-08-18 02:28:03 +0000374 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
375 pNode = &pNode[pNode->u.iAppend];
376 j = 1;
drh5634cc02015-08-17 11:28:03 +0000377 }
378 jsonAppendChar(pOut, ']');
379 break;
380 }
381 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000382 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000383 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000384 for(;;){
385 while( j<=pNode->n ){
386 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
387 jsonAppendSeparator(pOut);
388 jsonRenderNode(&pNode[j], pOut, aReplace);
389 jsonAppendChar(pOut, ':');
390 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
391 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
392 }else{
393 jsonRenderNode(&pNode[j+1], pOut, aReplace);
394 }
drhd0960592015-08-17 21:22:32 +0000395 }
drh505ad2c2015-08-21 17:33:11 +0000396 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000397 }
drh52216ad2015-08-18 02:28:03 +0000398 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
399 pNode = &pNode[pNode->u.iAppend];
400 j = 1;
drh5634cc02015-08-17 11:28:03 +0000401 }
402 jsonAppendChar(pOut, '}');
403 break;
404 }
drhbd0621b2015-08-13 13:54:59 +0000405 }
drh5634cc02015-08-17 11:28:03 +0000406}
407
408/*
409** Make the JsonNode the return value of the function.
410*/
drhd0960592015-08-17 21:22:32 +0000411static void jsonReturn(
412 JsonNode *pNode, /* Node to return */
413 sqlite3_context *pCtx, /* Return value for this function */
414 sqlite3_value **aReplace /* Array of replacement values */
415){
drh5634cc02015-08-17 11:28:03 +0000416 switch( pNode->eType ){
417 case JSON_NULL: {
418 sqlite3_result_null(pCtx);
419 break;
420 }
421 case JSON_TRUE: {
422 sqlite3_result_int(pCtx, 1);
423 break;
424 }
425 case JSON_FALSE: {
426 sqlite3_result_int(pCtx, 0);
427 break;
428 }
drh987eb1f2015-08-17 15:17:37 +0000429 case JSON_REAL: {
drh52216ad2015-08-18 02:28:03 +0000430 double r = strtod(pNode->u.zJContent, 0);
drh987eb1f2015-08-17 15:17:37 +0000431 sqlite3_result_double(pCtx, r);
drh5634cc02015-08-17 11:28:03 +0000432 break;
433 }
drh987eb1f2015-08-17 15:17:37 +0000434 case JSON_INT: {
435 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000436 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000437 if( z[0]=='-' ){ z++; }
438 while( z[0]>='0' && z[0]<='9' ){ i = i*10 + *(z++) - '0'; }
drh52216ad2015-08-18 02:28:03 +0000439 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000440 sqlite3_result_int64(pCtx, i);
441 break;
442 }
drh5634cc02015-08-17 11:28:03 +0000443 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000444 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000445 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
446 SQLITE_TRANSIENT);
drh301eecc2015-08-17 20:14:19 +0000447 }else if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000448 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000449 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000450 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000451 }else{
452 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000453 u32 i;
454 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000455 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000456 char *zOut;
457 u32 j;
458 zOut = sqlite3_malloc( n+1 );
459 if( zOut==0 ){
460 sqlite3_result_error_nomem(pCtx);
461 break;
462 }
463 for(i=1, j=0; i<n-1; i++){
464 char c = z[i];
465 if( c!='\\' && z[i+1] ){
466 zOut[j++] = c;
467 }else{
468 c = z[++i];
469 if( c=='u' && z[1] ){
470 u32 v = 0, k;
471 z++;
472 for(k=0; k<4 && z[k]; k++){
473 c = z[0];
474 if( c>='0' && c<='9' ) v = v*16 + c - '0';
475 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
476 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
477 else break;
478 z++;
479 }
480 if( v<=0x7f ){
481 zOut[j++] = v;
482 }else if( v<=0x7ff ){
483 zOut[j++] = 0xc0 | (v>>6);
484 zOut[j++] = 0x80 | (v&0x3f);
485 }else if( v<=0xffff ){
486 zOut[j++] = 0xe0 | (v>>12);
487 zOut[j++] = 0x80 | ((v>>6)&0x3f);
488 zOut[j++] = 0x80 | (v&0x3f);
489 }else if( v<=0x10ffff ){
490 zOut[j++] = 0xf0 | (v>>18);
491 zOut[j++] = 0x80 | ((v>>12)&0x3f);
492 zOut[j++] = 0x80 | ((v>>6)&0x3f);
493 zOut[j++] = 0x80 | (v&0x3f);
494 }
495 }else{
496 if( c=='b' ){
497 c = '\b';
498 }else if( c=='f' ){
499 c = '\f';
500 }else if( c=='n' ){
501 c = '\n';
502 }else if( c=='r' ){
503 c = '\r';
504 }else if( c=='t' ){
505 c = '\t';
506 }
507 zOut[j++] = c;
508 }
509 }
510 }
511 zOut[j] = 0;
512 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000513 }
514 break;
515 }
516 case JSON_ARRAY:
517 case JSON_OBJECT: {
drh505ad2c2015-08-21 17:33:11 +0000518 JsonString s;
drh5634cc02015-08-17 11:28:03 +0000519 jsonInit(&s, pCtx);
drhd0960592015-08-17 21:22:32 +0000520 jsonRenderNode(pNode, &s, aReplace);
drh5634cc02015-08-17 11:28:03 +0000521 jsonResult(&s);
522 break;
523 }
524 }
drhbd0621b2015-08-13 13:54:59 +0000525}
526
drh5fa5c102015-08-12 16:49:40 +0000527/*
drhe9c37f32015-08-15 21:25:36 +0000528** Create a new JsonNode instance based on the arguments and append that
529** instance to the JsonParse. Return the index in pParse->aNode[] of the
530** new node, or -1 if a memory allocation fails.
531*/
532static int jsonParseAddNode(
533 JsonParse *pParse, /* Append the node to this object */
534 u32 eType, /* Node type */
535 u32 n, /* Content size or sub-node count */
536 const char *zContent /* Content */
537){
538 JsonNode *p;
539 if( pParse->nNode>=pParse->nAlloc ){
540 u32 nNew;
541 JsonNode *pNew;
542 if( pParse->oom ) return -1;
543 nNew = pParse->nAlloc*2 + 10;
544 if( nNew<=pParse->nNode ){
545 pParse->oom = 1;
546 return -1;
547 }
548 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
549 if( pNew==0 ){
550 pParse->oom = 1;
551 return -1;
552 }
553 pParse->nAlloc = nNew;
554 pParse->aNode = pNew;
555 }
556 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000557 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000558 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000559 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000560 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000561 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000562 return pParse->nNode++;
563}
564
565/*
566** Parse a single JSON value which begins at pParse->zJson[i]. Return the
567** index of the first character past the end of the value parsed.
568**
569** Return negative for a syntax error. Special cases: return -2 if the
570** first non-whitespace character is '}' and return -3 if the first
571** non-whitespace character is ']'.
572*/
573static int jsonParseValue(JsonParse *pParse, u32 i){
574 char c;
575 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000576 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000577 int x;
578 while( isspace(pParse->zJson[i]) ){ i++; }
579 if( (c = pParse->zJson[i])==0 ) return 0;
580 if( c=='{' ){
581 /* Parse object */
582 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000583 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000584 for(j=i+1;;j++){
585 while( isspace(pParse->zJson[j]) ){ j++; }
586 x = jsonParseValue(pParse, j);
587 if( x<0 ){
drhbc8f0922015-08-22 19:39:04 +0000588 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000589 return -1;
590 }
drhbe9474e2015-08-22 03:05:54 +0000591 if( pParse->oom ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000592 if( pParse->aNode[pParse->nNode-1].eType!=JSON_STRING ) return -1;
593 j = x;
594 while( isspace(pParse->zJson[j]) ){ j++; }
595 if( pParse->zJson[j]!=':' ) return -1;
596 j++;
597 x = jsonParseValue(pParse, j);
598 if( x<0 ) return -1;
599 j = x;
600 while( isspace(pParse->zJson[j]) ){ j++; }
601 c = pParse->zJson[j];
602 if( c==',' ) continue;
603 if( c!='}' ) return -1;
604 break;
605 }
drhbc8f0922015-08-22 19:39:04 +0000606 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000607 return j+1;
608 }else if( c=='[' ){
609 /* Parse array */
610 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000611 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000612 for(j=i+1;;j++){
613 while( isspace(pParse->zJson[j]) ){ j++; }
614 x = jsonParseValue(pParse, j);
615 if( x<0 ){
drhbc8f0922015-08-22 19:39:04 +0000616 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000617 return -1;
618 }
619 j = x;
620 while( isspace(pParse->zJson[j]) ){ j++; }
621 c = pParse->zJson[j];
622 if( c==',' ) continue;
623 if( c!=']' ) return -1;
624 break;
625 }
drhbc8f0922015-08-22 19:39:04 +0000626 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000627 return j+1;
628 }else if( c=='"' ){
629 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000630 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000631 j = i+1;
632 for(;;){
633 c = pParse->zJson[j];
634 if( c==0 ) return -1;
635 if( c=='\\' ){
636 c = pParse->zJson[++j];
637 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000638 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000639 }else if( c=='"' ){
640 break;
641 }
642 j++;
643 }
644 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000645 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000646 return j+1;
647 }else if( c=='n'
648 && strncmp(pParse->zJson+i,"null",4)==0
drhb2cd10e2015-08-15 21:29:14 +0000649 && !isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000650 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
651 return i+4;
652 }else if( c=='t'
653 && strncmp(pParse->zJson+i,"true",4)==0
drhb2cd10e2015-08-15 21:29:14 +0000654 && !isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000655 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
656 return i+4;
657 }else if( c=='f'
658 && strncmp(pParse->zJson+i,"false",5)==0
drhb2cd10e2015-08-15 21:29:14 +0000659 && !isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000660 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
661 return i+5;
662 }else if( c=='-' || (c>='0' && c<='9') ){
663 /* Parse number */
664 u8 seenDP = 0;
665 u8 seenE = 0;
666 j = i+1;
667 for(;; j++){
668 c = pParse->zJson[j];
669 if( c>='0' && c<='9' ) continue;
670 if( c=='.' ){
671 if( pParse->zJson[j-1]=='-' ) return -1;
672 if( seenDP ) return -1;
673 seenDP = 1;
674 continue;
675 }
676 if( c=='e' || c=='E' ){
677 if( pParse->zJson[j-1]<'0' ) return -1;
678 if( seenE ) return -1;
679 seenDP = seenE = 1;
680 c = pParse->zJson[j+1];
681 if( c=='+' || c=='-' ) j++;
682 continue;
683 }
684 break;
685 }
686 if( pParse->zJson[j-1]<'0' ) return -1;
687 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
688 j - i, &pParse->zJson[i]);
689 return j;
690 }else if( c=='}' ){
691 return -2; /* End of {...} */
692 }else if( c==']' ){
693 return -3; /* End of [...] */
694 }else{
695 return -1; /* Syntax error */
696 }
697}
698
699/*
700** Parse a complete JSON string. Return 0 on success or non-zero if there
701** are any errors. If an error occurs, free all memory associated with
702** pParse.
703**
704** pParse is uninitialized when this routine is called.
705*/
drhbc8f0922015-08-22 19:39:04 +0000706static int jsonParse(
707 JsonParse *pParse, /* Initialize and fill this JsonParse object */
708 sqlite3_context *pCtx, /* Report errors here */
709 const char *zJson /* Input JSON text to be parsed */
710){
drhe9c37f32015-08-15 21:25:36 +0000711 int i;
712 if( zJson==0 ) return 1;
713 memset(pParse, 0, sizeof(*pParse));
714 pParse->zJson = zJson;
715 i = jsonParseValue(pParse, 0);
716 if( i>0 ){
717 while( isspace(zJson[i]) ) i++;
718 if( zJson[i] ) i = -1;
719 }
720 if( i<0 ){
drhbc8f0922015-08-22 19:39:04 +0000721 if( pParse->oom && pCtx!=0 ) sqlite3_result_error_nomem(pCtx);
drh505ad2c2015-08-21 17:33:11 +0000722 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000723 return 1;
724 }
725 return 0;
726}
drh301eecc2015-08-17 20:14:19 +0000727
drh505ad2c2015-08-21 17:33:11 +0000728/* Mark node i of pParse as being a child of iParent. Call recursively
729** to fill in all the descendants of node i.
730*/
731static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
732 JsonNode *pNode = &pParse->aNode[i];
733 u32 j;
734 pParse->aUp[i] = iParent;
735 switch( pNode->eType ){
736 case JSON_ARRAY: {
737 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
738 jsonParseFillInParentage(pParse, i+j, i);
739 }
740 break;
741 }
742 case JSON_OBJECT: {
743 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
744 pParse->aUp[i+j] = i;
745 jsonParseFillInParentage(pParse, i+j+1, i);
746 }
747 break;
748 }
749 default: {
750 break;
751 }
752 }
753}
754
755/*
756** Compute the parentage of all nodes in a completed parse.
757*/
758static int jsonParseFindParents(JsonParse *pParse){
759 u32 *aUp;
760 assert( pParse->aUp==0 );
761 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
762 if( aUp==0 ) return SQLITE_NOMEM;
763 jsonParseFillInParentage(pParse, 0, 0);
764 return SQLITE_OK;
765}
766
drh52216ad2015-08-18 02:28:03 +0000767/* forward declaration */
768static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*);
769
drh987eb1f2015-08-17 15:17:37 +0000770/*
771** Search along zPath to find the node specified. Return a pointer
772** to that node, or NULL if zPath is malformed or if there is no such
773** node.
drh52216ad2015-08-18 02:28:03 +0000774**
775** If pApnd!=0, then try to append new nodes to complete zPath if it is
776** possible to do so and if no existing node corresponds to zPath. If
777** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000778*/
drh52216ad2015-08-18 02:28:03 +0000779static JsonNode *jsonLookup(
780 JsonParse *pParse, /* The JSON to search */
781 u32 iRoot, /* Begin the search at this node */
782 const char *zPath, /* The path to search */
783 int *pApnd /* Append nodes to complete path if not NULL */
784){
drhbc8f0922015-08-22 19:39:04 +0000785 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000786 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000787 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000788 if( zPath[0]==0 ) return pRoot;
789 if( zPath[0]=='.' ){
790 if( pRoot->eType!=JSON_OBJECT ) return 0;
791 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000792 if( zPath[0]=='"' ){
793 zKey = zPath + 1;
794 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
795 nKey = i-1;
796 if( zPath[i] ) i++;
797 }else{
798 zKey = zPath;
799 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
800 nKey = i;
801 }
802 if( nKey==0 ) return 0;
drh987eb1f2015-08-17 15:17:37 +0000803 j = 1;
drh52216ad2015-08-18 02:28:03 +0000804 for(;;){
805 while( j<=pRoot->n ){
drh6b43cc82015-08-19 23:02:49 +0000806 if( pRoot[j].n==nKey+2
807 && strncmp(&pRoot[j].u.zJContent[1],zKey,nKey)==0
drh52216ad2015-08-18 02:28:03 +0000808 ){
809 return jsonLookup(pParse, iRoot+j+1, &zPath[i], pApnd);
810 }
811 j++;
drh505ad2c2015-08-21 17:33:11 +0000812 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000813 }
drh52216ad2015-08-18 02:28:03 +0000814 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
815 iRoot += pRoot->u.iAppend;
816 pRoot = &pParse->aNode[iRoot];
817 j = 1;
818 }
819 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000820 u32 iStart, iLabel;
821 JsonNode *pNode;
822 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
823 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000824 zPath += i;
drhbc8f0922015-08-22 19:39:04 +0000825 pNode = jsonLookupAppend(pParse, zPath, pApnd);
826 if( pParse->oom ) return 0;
827 if( pNode ){
828 pRoot = &pParse->aNode[iRoot];
829 pRoot->u.iAppend = iStart - iRoot;
830 pRoot->jnFlags |= JNODE_APPEND;
831 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
832 }
833 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000834 }
835 }else if( zPath[0]=='[' && isdigit(zPath[1]) ){
836 if( pRoot->eType!=JSON_ARRAY ) return 0;
837 i = 0;
838 zPath++;
839 while( isdigit(zPath[0]) ){
840 i = i + zPath[0] - '0';
841 zPath++;
842 }
843 if( zPath[0]!=']' ) return 0;
844 zPath++;
845 j = 1;
drh52216ad2015-08-18 02:28:03 +0000846 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000847 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
848 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000849 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000850 }
851 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
852 iRoot += pRoot->u.iAppend;
853 pRoot = &pParse->aNode[iRoot];
854 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000855 }
856 if( j<=pRoot->n ){
drh52216ad2015-08-18 02:28:03 +0000857 return jsonLookup(pParse, iRoot+j, zPath, pApnd);
858 }
859 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000860 u32 iStart;
861 JsonNode *pNode;
862 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
863 pNode = jsonLookupAppend(pParse, zPath, pApnd);
864 if( pParse->oom ) return 0;
865 if( pNode ){
866 pRoot = &pParse->aNode[iRoot];
867 pRoot->u.iAppend = iStart - iRoot;
868 pRoot->jnFlags |= JNODE_APPEND;
869 }
870 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000871 }
872 }
873 return 0;
874}
875
drh52216ad2015-08-18 02:28:03 +0000876/*
drhbc8f0922015-08-22 19:39:04 +0000877** Append content to pParse that will complete zPath. Return a pointer
878** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000879*/
880static JsonNode *jsonLookupAppend(
881 JsonParse *pParse, /* Append content to the JSON parse */
882 const char *zPath, /* Description of content to append */
883 int *pApnd /* Set this flag to 1 */
884){
885 *pApnd = 1;
886 if( zPath[0]==0 ){
887 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
888 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
889 }
890 if( zPath[0]=='.' ){
891 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
892 }else if( strncmp(zPath,"[0]",3)==0 ){
893 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
894 }else{
895 return 0;
896 }
897 if( pParse->oom ) return 0;
898 return jsonLookup(pParse, pParse->nNode-1, zPath, pApnd);
899}
900
drhbc8f0922015-08-22 19:39:04 +0000901/*
902** Report the wrong number of arguments for json_insert(), json_replace()
903** or json_set().
904*/
905static void jsonWrongNumArgs(
906 sqlite3_context *pCtx,
907 const char *zFuncName
908){
909 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
910 zFuncName);
911 sqlite3_result_error(pCtx, zMsg, -1);
912 sqlite3_free(zMsg);
913}
drh52216ad2015-08-18 02:28:03 +0000914
drh987eb1f2015-08-17 15:17:37 +0000915/****************************************************************************
916** SQL functions used for testing and debugging
917****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +0000918
drh301eecc2015-08-17 20:14:19 +0000919#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +0000920/*
drh5634cc02015-08-17 11:28:03 +0000921** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +0000922** a parse of the JSON provided. Or it returns NULL if JSON is not
923** well-formed.
924*/
drh5634cc02015-08-17 11:28:03 +0000925static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +0000926 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +0000927 int argc,
928 sqlite3_value **argv
929){
drh505ad2c2015-08-21 17:33:11 +0000930 JsonString s; /* Output string - not real JSON */
931 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +0000932 u32 i;
drh301eecc2015-08-17 20:14:19 +0000933 char zBuf[100];
drhe9c37f32015-08-15 21:25:36 +0000934
935 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +0000936 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
937 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +0000938 for(i=0; i<x.nNode; i++){
drh301eecc2015-08-17 20:14:19 +0000939 sqlite3_snprintf(sizeof(zBuf), zBuf, "node %3u: %7s n=%d\n",
940 i, jsonType[x.aNode[i].eType], x.aNode[i].n);
drhe9c37f32015-08-15 21:25:36 +0000941 jsonAppend(&s, zBuf);
drh52216ad2015-08-18 02:28:03 +0000942 if( x.aNode[i].u.zJContent!=0 ){
drh301eecc2015-08-17 20:14:19 +0000943 jsonAppendRaw(&s, " text: ", 10);
drh52216ad2015-08-18 02:28:03 +0000944 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
drhe9c37f32015-08-15 21:25:36 +0000945 jsonAppendRaw(&s, "\n", 1);
946 }
947 }
drh505ad2c2015-08-21 17:33:11 +0000948 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +0000949 jsonResult(&s);
950}
951
drh5634cc02015-08-17 11:28:03 +0000952/*
953** The json_test1(JSON) function parses and rebuilds the JSON string.
954*/
955static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +0000956 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +0000957 int argc,
958 sqlite3_value **argv
959){
960 JsonParse x; /* The parse */
drhbc8f0922015-08-22 19:39:04 +0000961 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
962 jsonReturn(x.aNode, ctx, 0);
drh505ad2c2015-08-21 17:33:11 +0000963 jsonParseReset(&x);
drh5634cc02015-08-17 11:28:03 +0000964}
965
966/*
967** The json_nodecount(JSON) function returns the number of nodes in the
968** input JSON string.
969*/
970static void jsonNodeCountFunc(
drhbc8f0922015-08-22 19:39:04 +0000971 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +0000972 int argc,
973 sqlite3_value **argv
974){
975 JsonParse x; /* The parse */
drhbc8f0922015-08-22 19:39:04 +0000976 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
977 sqlite3_result_int64(ctx, (sqlite3_int64)x.nNode);
drh505ad2c2015-08-21 17:33:11 +0000978 jsonParseReset(&x);
drh5634cc02015-08-17 11:28:03 +0000979}
drh301eecc2015-08-17 20:14:19 +0000980#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +0000981
drh987eb1f2015-08-17 15:17:37 +0000982/****************************************************************************
983** SQL function implementations
984****************************************************************************/
985
986/*
987** Implementation of the json_array(VALUE,...) function. Return a JSON
988** array that contains all values given in arguments. Or if any argument
989** is a BLOB, throw an error.
990*/
991static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +0000992 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +0000993 int argc,
994 sqlite3_value **argv
995){
996 int i;
drh505ad2c2015-08-21 17:33:11 +0000997 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +0000998
drhbc8f0922015-08-22 19:39:04 +0000999 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001000 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001001 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001002 jsonAppendSeparator(&jx);
1003 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001004 }
drhd0960592015-08-17 21:22:32 +00001005 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001006 jsonResult(&jx);
1007}
1008
1009
1010/*
1011** json_array_length(JSON)
1012** json_array_length(JSON, PATH)
1013**
1014** Return the number of elements in the top-level JSON array.
1015** Return 0 if the input is not a well-formed JSON array.
1016*/
1017static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001018 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001019 int argc,
1020 sqlite3_value **argv
1021){
1022 JsonParse x; /* The parse */
1023 sqlite3_int64 n = 0;
1024 u32 i;
1025 const char *zPath;
1026
1027 if( argc==2 ){
1028 zPath = (const char*)sqlite3_value_text(argv[1]);
1029 if( zPath==0 ) return;
1030 if( zPath[0]!='$' ) return;
1031 zPath++;
1032 }else{
1033 zPath = 0;
1034 }
drhbc8f0922015-08-22 19:39:04 +00001035 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0]))==0 ){
drh987eb1f2015-08-17 15:17:37 +00001036 if( x.nNode ){
1037 JsonNode *pNode = x.aNode;
drh52216ad2015-08-18 02:28:03 +00001038 if( zPath ) pNode = jsonLookup(&x, 0, zPath, 0);
drh987eb1f2015-08-17 15:17:37 +00001039 if( pNode->eType==JSON_ARRAY ){
drh52216ad2015-08-18 02:28:03 +00001040 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
drh301eecc2015-08-17 20:14:19 +00001041 for(i=1; i<=pNode->n; n++){
drh505ad2c2015-08-21 17:33:11 +00001042 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001043 }
1044 }
1045 }
drh505ad2c2015-08-21 17:33:11 +00001046 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001047 }
drhbc8f0922015-08-22 19:39:04 +00001048 if( !x.oom ) sqlite3_result_int64(ctx, n);
drh987eb1f2015-08-17 15:17:37 +00001049}
1050
1051/*
1052** json_extract(JSON, PATH)
1053**
1054** Return the element described by PATH. Return NULL if JSON is not
1055** valid JSON or if there is no PATH element or if PATH is malformed.
1056*/
1057static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001058 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001059 int argc,
1060 sqlite3_value **argv
1061){
1062 JsonParse x; /* The parse */
1063 JsonNode *pNode;
1064 const char *zPath;
1065 assert( argc==2 );
1066 zPath = (const char*)sqlite3_value_text(argv[1]);
1067 if( zPath==0 ) return;
1068 if( zPath[0]!='$' ) return;
1069 zPath++;
drhbc8f0922015-08-22 19:39:04 +00001070 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh52216ad2015-08-18 02:28:03 +00001071 pNode = jsonLookup(&x, 0, zPath, 0);
drh987eb1f2015-08-17 15:17:37 +00001072 if( pNode ){
drhbc8f0922015-08-22 19:39:04 +00001073 jsonReturn(pNode, ctx, 0);
drh987eb1f2015-08-17 15:17:37 +00001074 }
drh505ad2c2015-08-21 17:33:11 +00001075 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001076}
1077
1078/*
1079** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1080** object that contains all name/value given in arguments. Or if any name
1081** is not a string or if any value is a BLOB, throw an error.
1082*/
1083static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001084 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001085 int argc,
1086 sqlite3_value **argv
1087){
1088 int i;
drh505ad2c2015-08-21 17:33:11 +00001089 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001090 const char *z;
1091 u32 n;
1092
1093 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001094 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001095 "of arguments", -1);
1096 return;
1097 }
drhbc8f0922015-08-22 19:39:04 +00001098 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001099 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001100 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001101 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001102 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drh987eb1f2015-08-17 15:17:37 +00001103 jsonZero(&jx);
1104 return;
1105 }
drhd0960592015-08-17 21:22:32 +00001106 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001107 z = (const char*)sqlite3_value_text(argv[i]);
1108 n = (u32)sqlite3_value_bytes(argv[i]);
1109 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001110 jsonAppendChar(&jx, ':');
1111 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001112 }
drhd0960592015-08-17 21:22:32 +00001113 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001114 jsonResult(&jx);
1115}
1116
1117
1118/*
drh301eecc2015-08-17 20:14:19 +00001119** json_remove(JSON, PATH, ...)
1120**
1121** Remove the named elements from JSON and return the result. Ill-formed
1122** PATH arguments are silently ignored. If JSON is ill-formed, then NULL
1123** is returned.
1124*/
1125static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001126 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001127 int argc,
1128 sqlite3_value **argv
1129){
1130 JsonParse x; /* The parse */
1131 JsonNode *pNode;
1132 const char *zPath;
1133 u32 i;
1134
1135 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001136 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh301eecc2015-08-17 20:14:19 +00001137 if( x.nNode ){
drh6fd5c1e2015-08-21 20:37:12 +00001138 for(i=1; i<(u32)argc; i++){
drh301eecc2015-08-17 20:14:19 +00001139 zPath = (const char*)sqlite3_value_text(argv[i]);
1140 if( zPath==0 ) continue;
1141 if( zPath[0]!='$' ) continue;
drh52216ad2015-08-18 02:28:03 +00001142 pNode = jsonLookup(&x, 0, &zPath[1], 0);
drh301eecc2015-08-17 20:14:19 +00001143 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1144 }
1145 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
drhbc8f0922015-08-22 19:39:04 +00001146 jsonReturn(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001147 }
1148 }
drh505ad2c2015-08-21 17:33:11 +00001149 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001150}
1151
1152/*
1153** json_replace(JSON, PATH, VALUE, ...)
1154**
1155** Replace the value at PATH with VALUE. If PATH does not already exist,
1156** this routine is a no-op. If JSON is ill-formed, return NULL.
1157*/
1158static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001159 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001160 int argc,
1161 sqlite3_value **argv
1162){
1163 JsonParse x; /* The parse */
1164 JsonNode *pNode;
1165 const char *zPath;
1166 u32 i;
1167
1168 if( argc<1 ) return;
1169 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001170 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001171 return;
1172 }
drhbc8f0922015-08-22 19:39:04 +00001173 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drhd0960592015-08-17 21:22:32 +00001174 if( x.nNode ){
drh6fd5c1e2015-08-21 20:37:12 +00001175 for(i=1; i<(u32)argc; i+=2){
drhd0960592015-08-17 21:22:32 +00001176 zPath = (const char*)sqlite3_value_text(argv[i]);
1177 if( zPath==0 ) continue;
1178 if( zPath[0]!='$' ) continue;
drh52216ad2015-08-18 02:28:03 +00001179 pNode = jsonLookup(&x, 0, &zPath[1], 0);
drhd0960592015-08-17 21:22:32 +00001180 if( pNode ){
1181 pNode->jnFlags |= JNODE_REPLACE;
1182 pNode->iVal = i+1;
1183 }
1184 }
1185 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drhbc8f0922015-08-22 19:39:04 +00001186 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
drhd0960592015-08-17 21:22:32 +00001187 }else{
drhbc8f0922015-08-22 19:39:04 +00001188 jsonReturn(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001189 }
1190 }
drh505ad2c2015-08-21 17:33:11 +00001191 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001192}
drh505ad2c2015-08-21 17:33:11 +00001193
drh52216ad2015-08-18 02:28:03 +00001194/*
1195** json_set(JSON, PATH, VALUE, ...)
1196**
1197** Set the value at PATH to VALUE. Create the PATH if it does not already
1198** exist. Overwrite existing values that do exist.
1199** If JSON is ill-formed, return NULL.
1200**
1201** json_insert(JSON, PATH, VALUE, ...)
1202**
1203** Create PATH and initialize it to VALUE. If PATH already exists, this
1204** routine is a no-op. If JSON is ill-formed, return NULL.
1205*/
1206static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001207 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001208 int argc,
1209 sqlite3_value **argv
1210){
1211 JsonParse x; /* The parse */
1212 JsonNode *pNode;
1213 const char *zPath;
1214 u32 i;
1215 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001216 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001217
1218 if( argc<1 ) return;
1219 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001220 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001221 return;
1222 }
drhbc8f0922015-08-22 19:39:04 +00001223 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh52216ad2015-08-18 02:28:03 +00001224 if( x.nNode ){
drh6fd5c1e2015-08-21 20:37:12 +00001225 for(i=1; i<(u32)argc; i+=2){
drh52216ad2015-08-18 02:28:03 +00001226 zPath = (const char*)sqlite3_value_text(argv[i]);
1227 if( zPath==0 ) continue;
1228 if( zPath[0]!='$' ) continue;
1229 bApnd = 0;
1230 pNode = jsonLookup(&x, 0, &zPath[1], &bApnd);
drhbc8f0922015-08-22 19:39:04 +00001231 if( x.oom ){
1232 sqlite3_result_error_nomem(ctx);
1233 goto jsonSetDone;
1234 }else if( pNode && (bApnd || bIsSet) ){
drh52216ad2015-08-18 02:28:03 +00001235 pNode->jnFlags |= JNODE_REPLACE;
1236 pNode->iVal = i+1;
1237 }
1238 }
1239 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
drhbc8f0922015-08-22 19:39:04 +00001240 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
drh52216ad2015-08-18 02:28:03 +00001241 }else{
drhbc8f0922015-08-22 19:39:04 +00001242 jsonReturn(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001243 }
1244 }
drhbc8f0922015-08-22 19:39:04 +00001245jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001246 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001247}
drh301eecc2015-08-17 20:14:19 +00001248
1249/*
drh987eb1f2015-08-17 15:17:37 +00001250** json_type(JSON)
1251** json_type(JSON, PATH)
1252**
1253** Return the top-level "type" of a JSON string. Return NULL if the
1254** input is not a well-formed JSON string.
1255*/
1256static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001257 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001258 int argc,
1259 sqlite3_value **argv
1260){
1261 JsonParse x; /* The parse */
1262 const char *zPath;
1263
1264 if( argc==2 ){
1265 zPath = (const char*)sqlite3_value_text(argv[1]);
1266 if( zPath==0 ) return;
1267 if( zPath[0]!='$' ) return;
1268 zPath++;
1269 }else{
1270 zPath = 0;
1271 }
drhbc8f0922015-08-22 19:39:04 +00001272 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh987eb1f2015-08-17 15:17:37 +00001273 if( x.nNode ){
1274 JsonNode *pNode = x.aNode;
drh52216ad2015-08-18 02:28:03 +00001275 if( zPath ) pNode = jsonLookup(&x, 0, zPath, 0);
drhbc8f0922015-08-22 19:39:04 +00001276 if( pNode ){
1277 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
1278 }
drh987eb1f2015-08-17 15:17:37 +00001279 }
drh505ad2c2015-08-21 17:33:11 +00001280 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001281}
drh5634cc02015-08-17 11:28:03 +00001282
drhbc8f0922015-08-22 19:39:04 +00001283/*
1284** json_valid(JSON)
1285**
1286** Return 1 if JSON is a valid JSON string. Return 0 otherwise.
1287*/
1288static void jsonValidFunc(
1289 sqlite3_context *ctx,
1290 int argc,
1291 sqlite3_value **argv
1292){
1293 JsonParse x; /* The parse */
1294 int rc = 0;
1295
1296 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0]))==0
1297 && x.nNode>0
1298 ){
1299 rc = 1;
1300 }
1301 jsonParseReset(&x);
1302 sqlite3_result_int(ctx, rc);
1303}
1304
drhcb6c6c62015-08-19 22:47:17 +00001305/****************************************************************************
1306** The json_each virtual table
1307****************************************************************************/
1308typedef struct JsonEachCursor JsonEachCursor;
1309struct JsonEachCursor {
1310 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001311 u32 iRowid; /* The rowid */
1312 u32 i; /* Index in sParse.aNode[] of current row */
1313 u32 iEnd; /* EOF when i equals or exceeds this value */
1314 u8 eType; /* Type of top-level element */
1315 u8 bRecursive; /* True for json_tree(). False for json_each() */
1316 char *zJson; /* Input JSON */
1317 char *zPath; /* Path by which to filter zJson */
1318 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001319};
1320
1321/* Constructor for the json_each virtual table */
1322static int jsonEachConnect(
1323 sqlite3 *db,
1324 void *pAux,
1325 int argc, const char *const*argv,
1326 sqlite3_vtab **ppVtab,
1327 char **pzErr
1328){
1329 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001330 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001331
1332/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001333#define JEACH_KEY 0
1334#define JEACH_VALUE 1
1335#define JEACH_TYPE 2
1336#define JEACH_ATOM 3
1337#define JEACH_ID 4
1338#define JEACH_PARENT 5
1339#define JEACH_FULLKEY 6
1340#define JEACH_JSON 7
1341#define JEACH_PATH 8
drhcb6c6c62015-08-19 22:47:17 +00001342
drh6fd5c1e2015-08-21 20:37:12 +00001343 UNUSED_PARAM(pzErr);
1344 UNUSED_PARAM(argv);
1345 UNUSED_PARAM(argc);
1346 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001347 rc = sqlite3_declare_vtab(db,
drh4af352d2015-08-21 20:02:48 +00001348 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,"
1349 "json HIDDEN,path HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001350 if( rc==SQLITE_OK ){
1351 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1352 if( pNew==0 ) return SQLITE_NOMEM;
1353 memset(pNew, 0, sizeof(*pNew));
1354 }
1355 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001356}
1357
1358/* destructor for json_each virtual table */
1359static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1360 sqlite3_free(pVtab);
1361 return SQLITE_OK;
1362}
1363
drh505ad2c2015-08-21 17:33:11 +00001364/* constructor for a JsonEachCursor object for json_each(). */
1365static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001366 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001367
1368 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001369 pCur = sqlite3_malloc( sizeof(*pCur) );
1370 if( pCur==0 ) return SQLITE_NOMEM;
1371 memset(pCur, 0, sizeof(*pCur));
1372 *ppCursor = &pCur->base;
1373 return SQLITE_OK;
1374}
1375
drh505ad2c2015-08-21 17:33:11 +00001376/* constructor for a JsonEachCursor object for json_tree(). */
1377static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1378 int rc = jsonEachOpenEach(p, ppCursor);
1379 if( rc==SQLITE_OK ){
1380 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1381 pCur->bRecursive = 1;
1382 }
1383 return rc;
1384}
1385
drhcb6c6c62015-08-19 22:47:17 +00001386/* Reset a JsonEachCursor back to its original state. Free any memory
1387** held. */
1388static void jsonEachCursorReset(JsonEachCursor *p){
1389 sqlite3_free(p->zJson);
1390 sqlite3_free(p->zPath);
drh505ad2c2015-08-21 17:33:11 +00001391 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001392 p->iRowid = 0;
1393 p->i = 0;
1394 p->iEnd = 0;
1395 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001396 p->zJson = 0;
1397 p->zPath = 0;
1398}
1399
1400/* Destructor for a jsonEachCursor object */
1401static int jsonEachClose(sqlite3_vtab_cursor *cur){
1402 JsonEachCursor *p = (JsonEachCursor*)cur;
1403 jsonEachCursorReset(p);
1404 sqlite3_free(cur);
1405 return SQLITE_OK;
1406}
1407
1408/* Return TRUE if the jsonEachCursor object has been advanced off the end
1409** of the JSON object */
1410static int jsonEachEof(sqlite3_vtab_cursor *cur){
1411 JsonEachCursor *p = (JsonEachCursor*)cur;
1412 return p->i >= p->iEnd;
1413}
1414
drh505ad2c2015-08-21 17:33:11 +00001415/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001416static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001417 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001418 if( p->bRecursive ){
1419 if( p->i==0 ){
1420 p->i = 1;
1421 }else if( p->sParse.aNode[p->sParse.aUp[p->i]].eType==JSON_OBJECT ){
1422 p->i += 2;
1423 }else{
1424 p->i++;
1425 }
1426 p->iRowid++;
1427 if( p->i<p->sParse.nNode ){
1428 JsonNode *pUp = &p->sParse.aNode[p->sParse.aUp[p->i]];
1429 p->eType = pUp->eType;
1430 if( pUp->eType==JSON_ARRAY ) pUp->u.iKey++;
1431 if( p->sParse.aNode[p->i].eType==JSON_ARRAY ){
1432 p->sParse.aNode[p->i].u.iKey = 0;
1433 }
1434 }
drh505ad2c2015-08-21 17:33:11 +00001435 }else{
drh4af352d2015-08-21 20:02:48 +00001436 switch( p->eType ){
1437 case JSON_ARRAY: {
1438 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1439 p->iRowid++;
1440 break;
1441 }
1442 case JSON_OBJECT: {
1443 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1444 p->iRowid++;
1445 break;
1446 }
1447 default: {
1448 p->i = p->iEnd;
1449 break;
1450 }
drh505ad2c2015-08-21 17:33:11 +00001451 }
1452 }
1453 return SQLITE_OK;
1454}
1455
drh4af352d2015-08-21 20:02:48 +00001456/* Append the name of the path for element i to pStr
1457*/
1458static void jsonEachComputePath(
1459 JsonEachCursor *p, /* The cursor */
1460 JsonString *pStr, /* Write the path here */
1461 u32 i /* Path to this element */
1462){
1463 JsonNode *pNode, *pUp;
1464 u32 iUp;
1465 if( i==0 ){
1466 jsonAppendChar(pStr, '$');
1467 return;
drhcb6c6c62015-08-19 22:47:17 +00001468 }
drh4af352d2015-08-21 20:02:48 +00001469 iUp = p->sParse.aUp[i];
1470 jsonEachComputePath(p, pStr, iUp);
1471 pNode = &p->sParse.aNode[i];
1472 pUp = &p->sParse.aNode[iUp];
1473 if( pUp->eType==JSON_ARRAY ){
1474 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1475 }else{
1476 assert( pUp->eType==JSON_OBJECT );
1477 if( pNode->eType>=JSON_ARRAY ) pNode--;
1478 assert( pNode->eType==JSON_STRING );
1479 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1480 }
drhcb6c6c62015-08-19 22:47:17 +00001481}
1482
1483/* Return the value of a column */
1484static int jsonEachColumn(
1485 sqlite3_vtab_cursor *cur, /* The cursor */
1486 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1487 int i /* Which column to return */
1488){
1489 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001490 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001491 switch( i ){
1492 case JEACH_KEY: {
1493 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001494 jsonReturn(pThis, ctx, 0);
1495 }else if( p->eType==JSON_ARRAY ){
1496 u32 iKey;
1497 if( p->bRecursive ){
1498 if( p->iRowid==0 ) break;
1499 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey - 1;
1500 }else{
1501 iKey = p->iRowid;
1502 }
drh6fd5c1e2015-08-21 20:37:12 +00001503 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001504 }
1505 break;
1506 }
1507 case JEACH_VALUE: {
drh505ad2c2015-08-21 17:33:11 +00001508 if( p->eType==JSON_OBJECT ) pThis++;
1509 jsonReturn(pThis, ctx, 0);
1510 break;
1511 }
1512 case JEACH_TYPE: {
1513 if( p->eType==JSON_OBJECT ) pThis++;
1514 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1515 break;
1516 }
1517 case JEACH_ATOM: {
1518 if( p->eType==JSON_OBJECT ) pThis++;
1519 if( pThis->eType>=JSON_ARRAY ) break;
1520 jsonReturn(pThis, ctx, 0);
1521 break;
1522 }
1523 case JEACH_ID: {
drh6fd5c1e2015-08-21 20:37:12 +00001524 sqlite3_result_int64(ctx, (sqlite3_int64)p->i + (p->eType==JSON_OBJECT));
drh505ad2c2015-08-21 17:33:11 +00001525 break;
1526 }
1527 case JEACH_PARENT: {
1528 if( p->i>0 && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001529 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001530 }
1531 break;
1532 }
drh4af352d2015-08-21 20:02:48 +00001533 case JEACH_FULLKEY: {
1534 JsonString x;
1535 jsonInit(&x, ctx);
1536 if( p->bRecursive ){
1537 jsonEachComputePath(p, &x, p->i);
1538 }else{
1539 if( p->zPath ){
1540 jsonAppendRaw(&x, p->zPath, (int)strlen(p->zPath));
1541 }else{
1542 jsonAppendChar(&x, '$');
1543 }
1544 if( p->eType==JSON_ARRAY ){
1545 jsonPrintf(30, &x, "[%d]", p->iRowid);
1546 }else{
1547 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1548 }
1549 }
1550 jsonResult(&x);
1551 break;
1552 }
drhcb6c6c62015-08-19 22:47:17 +00001553 case JEACH_PATH: {
1554 const char *zPath = p->zPath;
drh4af352d2015-08-21 20:02:48 +00001555 if( zPath==0 ){
1556 if( p->bRecursive ){
1557 JsonString x;
1558 jsonInit(&x, ctx);
1559 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1560 jsonResult(&x);
1561 break;
1562 }
1563 zPath = "$";
1564 }
drhcb6c6c62015-08-19 22:47:17 +00001565 sqlite3_result_text(ctx, zPath, -1, SQLITE_STATIC);
1566 break;
1567 }
1568 default: {
drh505ad2c2015-08-21 17:33:11 +00001569 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001570 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1571 break;
1572 }
1573 }
1574 return SQLITE_OK;
1575}
1576
1577/* Return the current rowid value */
1578static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1579 JsonEachCursor *p = (JsonEachCursor*)cur;
1580 *pRowid = p->iRowid;
1581 return SQLITE_OK;
1582}
1583
1584/* The query strategy is to look for an equality constraint on the json
1585** column. Without such a constraint, the table cannot operate. idxNum is
1586** 1 if the constraint is found, 3 if the constraint and zPath are found,
1587** and 0 otherwise.
1588*/
1589static int jsonEachBestIndex(
1590 sqlite3_vtab *tab,
1591 sqlite3_index_info *pIdxInfo
1592){
1593 int i;
1594 int jsonIdx = -1;
1595 int pathIdx = -1;
1596 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001597
1598 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001599 pConstraint = pIdxInfo->aConstraint;
1600 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1601 if( pConstraint->usable==0 ) continue;
1602 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1603 switch( pConstraint->iColumn ){
1604 case JEACH_JSON: jsonIdx = i; break;
1605 case JEACH_PATH: pathIdx = i; break;
1606 default: /* no-op */ break;
1607 }
1608 }
1609 if( jsonIdx<0 ){
1610 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001611 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001612 }else{
drh505ad2c2015-08-21 17:33:11 +00001613 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001614 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1615 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
1616 if( pathIdx<0 ){
1617 pIdxInfo->idxNum = 1;
1618 }else{
1619 pIdxInfo->aConstraintUsage[pathIdx].argvIndex = 2;
1620 pIdxInfo->aConstraintUsage[pathIdx].omit = 1;
1621 pIdxInfo->idxNum = 3;
1622 }
1623 }
1624 return SQLITE_OK;
1625}
1626
1627/* Start a search on a new JSON string */
1628static int jsonEachFilter(
1629 sqlite3_vtab_cursor *cur,
1630 int idxNum, const char *idxStr,
1631 int argc, sqlite3_value **argv
1632){
1633 JsonEachCursor *p = (JsonEachCursor*)cur;
1634 const char *z;
1635 const char *zPath;
1636 sqlite3_int64 n;
1637
drh6fd5c1e2015-08-21 20:37:12 +00001638 UNUSED_PARAM(idxStr);
1639 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001640 jsonEachCursorReset(p);
1641 if( idxNum==0 ) return SQLITE_OK;
1642 z = (const char*)sqlite3_value_text(argv[0]);
1643 if( z==0 ) return SQLITE_OK;
1644 if( idxNum&2 ){
1645 zPath = (const char*)sqlite3_value_text(argv[1]);
1646 if( zPath==0 || zPath[0]!='$' ) return SQLITE_OK;
1647 }
1648 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001649 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001650 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001651 memcpy(p->zJson, z, (size_t)n+1);
drhbc8f0922015-08-22 19:39:04 +00001652 if( jsonParse(&p->sParse, 0, p->zJson)
drh505ad2c2015-08-21 17:33:11 +00001653 || (p->bRecursive && jsonParseFindParents(&p->sParse))
1654 ){
drhcb6c6c62015-08-19 22:47:17 +00001655 jsonEachCursorReset(p);
1656 }else{
1657 JsonNode *pNode;
1658 if( idxNum==3 ){
drh4af352d2015-08-21 20:02:48 +00001659 p->bRecursive = 0;
drhcb6c6c62015-08-19 22:47:17 +00001660 n = sqlite3_value_bytes(argv[1]);
drh6fd5c1e2015-08-21 20:37:12 +00001661 p->zPath = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001662 if( p->zPath==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001663 memcpy(p->zPath, zPath, (size_t)n+1);
drhcb6c6c62015-08-19 22:47:17 +00001664 pNode = jsonLookup(&p->sParse, 0, p->zPath+1, 0);
1665 if( pNode==0 ){
1666 jsonEachCursorReset(p);
1667 return SQLITE_OK;
1668 }
1669 }else{
1670 pNode = p->sParse.aNode;
1671 }
1672 p->i = (int)(pNode - p->sParse.aNode);
1673 p->eType = pNode->eType;
1674 if( p->eType>=JSON_ARRAY ){
1675 p->i++;
1676 p->iEnd = p->i + pNode->n;
1677 }else{
1678 p->iEnd = p->i+1;
1679 }
1680 }
drhbc8f0922015-08-22 19:39:04 +00001681 return p->sParse.oom ? SQLITE_NOMEM : SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001682}
1683
1684/* The methods of the json_each virtual table */
1685static sqlite3_module jsonEachModule = {
1686 0, /* iVersion */
1687 0, /* xCreate */
1688 jsonEachConnect, /* xConnect */
1689 jsonEachBestIndex, /* xBestIndex */
1690 jsonEachDisconnect, /* xDisconnect */
1691 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001692 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001693 jsonEachClose, /* xClose - close a cursor */
1694 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001695 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001696 jsonEachEof, /* xEof - check for end of scan */
1697 jsonEachColumn, /* xColumn - read data */
1698 jsonEachRowid, /* xRowid - read data */
1699 0, /* xUpdate */
1700 0, /* xBegin */
1701 0, /* xSync */
1702 0, /* xCommit */
1703 0, /* xRollback */
1704 0, /* xFindMethod */
1705 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001706 0, /* xSavepoint */
1707 0, /* xRelease */
1708 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001709};
1710
drh505ad2c2015-08-21 17:33:11 +00001711/* The methods of the json_tree virtual table. */
1712static sqlite3_module jsonTreeModule = {
1713 0, /* iVersion */
1714 0, /* xCreate */
1715 jsonEachConnect, /* xConnect */
1716 jsonEachBestIndex, /* xBestIndex */
1717 jsonEachDisconnect, /* xDisconnect */
1718 0, /* xDestroy */
1719 jsonEachOpenTree, /* xOpen - open a cursor */
1720 jsonEachClose, /* xClose - close a cursor */
1721 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001722 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001723 jsonEachEof, /* xEof - check for end of scan */
1724 jsonEachColumn, /* xColumn - read data */
1725 jsonEachRowid, /* xRowid - read data */
1726 0, /* xUpdate */
1727 0, /* xBegin */
1728 0, /* xSync */
1729 0, /* xCommit */
1730 0, /* xRollback */
1731 0, /* xFindMethod */
1732 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001733 0, /* xSavepoint */
1734 0, /* xRelease */
1735 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001736};
1737
1738/****************************************************************************
1739** The following routine is the only publically visible identifier in this
1740** file. Call the following routine in order to register the various SQL
1741** functions and the virtual table implemented by this file.
1742****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001743
drh5fa5c102015-08-12 16:49:40 +00001744#ifdef _WIN32
1745__declspec(dllexport)
1746#endif
1747int sqlite3_json_init(
1748 sqlite3 *db,
1749 char **pzErrMsg,
1750 const sqlite3_api_routines *pApi
1751){
1752 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001753 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001754 static const struct {
1755 const char *zName;
1756 int nArg;
drh52216ad2015-08-18 02:28:03 +00001757 int flag;
drh5fa5c102015-08-12 16:49:40 +00001758 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1759 } aFunc[] = {
drh52216ad2015-08-18 02:28:03 +00001760 { "json_array", -1, 0, jsonArrayFunc },
1761 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1762 { "json_array_length", 2, 0, jsonArrayLengthFunc },
1763 { "json_extract", 2, 0, jsonExtractFunc },
1764 { "json_insert", -1, 0, jsonSetFunc },
1765 { "json_object", -1, 0, jsonObjectFunc },
1766 { "json_remove", -1, 0, jsonRemoveFunc },
1767 { "json_replace", -1, 0, jsonReplaceFunc },
1768 { "json_set", -1, 1, jsonSetFunc },
1769 { "json_type", 1, 0, jsonTypeFunc },
1770 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001771 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001772
drh301eecc2015-08-17 20:14:19 +00001773#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001774 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001775 { "json_parse", 1, 0, jsonParseFunc },
1776 { "json_test1", 1, 0, jsonTest1Func },
1777 { "json_nodecount", 1, 0, jsonNodeCountFunc },
drh301eecc2015-08-17 20:14:19 +00001778#endif
drh5fa5c102015-08-12 16:49:40 +00001779 };
drh505ad2c2015-08-21 17:33:11 +00001780 static const struct {
1781 const char *zName;
1782 sqlite3_module *pModule;
1783 } aMod[] = {
1784 { "json_each", &jsonEachModule },
1785 { "json_tree", &jsonTreeModule },
1786 };
drh5fa5c102015-08-12 16:49:40 +00001787 SQLITE_EXTENSION_INIT2(pApi);
1788 (void)pzErrMsg; /* Unused parameter */
1789 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1790 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001791 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1792 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001793 aFunc[i].xFunc, 0, 0);
1794 }
drh505ad2c2015-08-21 17:33:11 +00001795 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1796 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00001797 }
drh5fa5c102015-08-12 16:49:40 +00001798 return rc;
1799}