blob: fa36419cfc73428fccb18fb399f886d9f08e9c1e [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*/
drh50065652015-10-08 19:29:18 +000024#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
drhf2df7e72015-08-28 20:07:40 +000025#if !defined(_SQLITEINT_H_)
drh5fa5c102015-08-12 16:49:40 +000026#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000027#endif
drh5fa5c102015-08-12 16:49:40 +000028SQLITE_EXTENSION_INIT1
29#include <assert.h>
30#include <string.h>
drha0882fa2015-10-09 20:40:44 +000031#include <ctype.h> /* amalgamator: keep */
drh987eb1f2015-08-17 15:17:37 +000032#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000033#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000034
drh6fd5c1e2015-08-21 20:37:12 +000035#define UNUSED_PARAM(X) (void)(X)
36
drh8deb4b82015-10-09 18:21:43 +000037#ifndef LARGEST_INT64
38# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
39# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
40#endif
41
dan2e8f5512015-09-17 17:21:09 +000042/*
43** Versions of isspace(), isalnum() and isdigit() to which it is safe
44** to pass signed char values.
45*/
dan2e8f5512015-09-17 17:21:09 +000046#define safe_isdigit(x) isdigit((unsigned char)(x))
47#define safe_isalnum(x) isalnum((unsigned char)(x))
48
drh95677942015-09-24 01:06:37 +000049/*
50** Growing our own isspace() routine this way is twice as fast as
51** the library isspace() function, resulting in a 7% overall performance
52** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
53*/
54static const char jsonIsSpace[] = {
55 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0,
56 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
57 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
59 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
66 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
67 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
69 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71};
72#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
73
drh5fa5c102015-08-12 16:49:40 +000074/* Unsigned integer types */
75typedef sqlite3_uint64 u64;
76typedef unsigned int u32;
77typedef unsigned char u8;
78
drh52216ad2015-08-18 02:28:03 +000079/* Objects */
drh505ad2c2015-08-21 17:33:11 +000080typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000081typedef struct JsonNode JsonNode;
82typedef struct JsonParse JsonParse;
83
drh5634cc02015-08-17 11:28:03 +000084/* An instance of this object represents a JSON string
85** under construction. Really, this is a generic string accumulator
86** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000087*/
drh505ad2c2015-08-21 17:33:11 +000088struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000089 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000090 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000091 u64 nAlloc; /* Bytes of storage available in zBuf[] */
92 u64 nUsed; /* Bytes of zBuf[] currently used */
93 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000094 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000095 char zSpace[100]; /* Initial static space */
96};
97
drhe9c37f32015-08-15 21:25:36 +000098/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000099*/
drhe9c37f32015-08-15 21:25:36 +0000100#define JSON_NULL 0
101#define JSON_TRUE 1
102#define JSON_FALSE 2
103#define JSON_INT 3
104#define JSON_REAL 4
105#define JSON_STRING 5
106#define JSON_ARRAY 6
107#define JSON_OBJECT 7
108
drhf5ddb9c2015-09-11 00:06:41 +0000109/* The "subtype" set for JSON values */
110#define JSON_SUBTYPE 74 /* Ascii for "J" */
111
drh987eb1f2015-08-17 15:17:37 +0000112/*
113** Names of the various JSON types:
114*/
115static const char * const jsonType[] = {
116 "null", "true", "false", "integer", "real", "text", "array", "object"
117};
118
drh301eecc2015-08-17 20:14:19 +0000119/* Bit values for the JsonNode.jnFlag field
120*/
121#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
122#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
123#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +0000124#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +0000125#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drhf5ddb9c2015-09-11 00:06:41 +0000126#define JNODE_LABEL 0x20 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000127
drh987eb1f2015-08-17 15:17:37 +0000128
drhe9c37f32015-08-15 21:25:36 +0000129/* A single node of parsed JSON
130*/
drhe9c37f32015-08-15 21:25:36 +0000131struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000132 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000133 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +0000134 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +0000135 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000136 union {
drh0042a972015-08-18 12:59:58 +0000137 const char *zJContent; /* Content for INT, REAL, and STRING */
138 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000139 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +0000140 } u;
drhe9c37f32015-08-15 21:25:36 +0000141};
142
143/* A completely parsed JSON string
144*/
drhe9c37f32015-08-15 21:25:36 +0000145struct JsonParse {
146 u32 nNode; /* Number of slots of aNode[] used */
147 u32 nAlloc; /* Number of slots of aNode[] allocated */
148 JsonNode *aNode; /* Array of nodes containing the parse */
149 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000150 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000151 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000152 u8 nErr; /* Number of errors seen */
drhe9c37f32015-08-15 21:25:36 +0000153};
154
drh505ad2c2015-08-21 17:33:11 +0000155/**************************************************************************
156** Utility routines for dealing with JsonString objects
157**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000158
drh505ad2c2015-08-21 17:33:11 +0000159/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000160*/
drh505ad2c2015-08-21 17:33:11 +0000161static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000162 p->zBuf = p->zSpace;
163 p->nAlloc = sizeof(p->zSpace);
164 p->nUsed = 0;
165 p->bStatic = 1;
166}
167
drh505ad2c2015-08-21 17:33:11 +0000168/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000169*/
drh505ad2c2015-08-21 17:33:11 +0000170static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000171 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000172 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000173 jsonZero(p);
174}
175
176
drh505ad2c2015-08-21 17:33:11 +0000177/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000178** initial state.
179*/
drh505ad2c2015-08-21 17:33:11 +0000180static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000181 if( !p->bStatic ) sqlite3_free(p->zBuf);
182 jsonZero(p);
183}
184
185
186/* Report an out-of-memory (OOM) condition
187*/
drh505ad2c2015-08-21 17:33:11 +0000188static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000189 p->bErr = 1;
190 sqlite3_result_error_nomem(p->pCtx);
191 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000192}
193
194/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
195** Return zero on success. Return non-zero on an OOM error
196*/
drh505ad2c2015-08-21 17:33:11 +0000197static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000198 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000199 char *zNew;
200 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000201 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000202 zNew = sqlite3_malloc64(nTotal);
203 if( zNew==0 ){
204 jsonOom(p);
205 return SQLITE_NOMEM;
206 }
drh6fd5c1e2015-08-21 20:37:12 +0000207 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000208 p->zBuf = zNew;
209 p->bStatic = 0;
210 }else{
211 zNew = sqlite3_realloc64(p->zBuf, nTotal);
212 if( zNew==0 ){
213 jsonOom(p);
214 return SQLITE_NOMEM;
215 }
216 p->zBuf = zNew;
217 }
218 p->nAlloc = nTotal;
219 return SQLITE_OK;
220}
221
drh505ad2c2015-08-21 17:33:11 +0000222/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000223*/
drh505ad2c2015-08-21 17:33:11 +0000224static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000225 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
226 memcpy(p->zBuf+p->nUsed, zIn, N);
227 p->nUsed += N;
228}
229
drh4af352d2015-08-21 20:02:48 +0000230/* Append formatted text (not to exceed N bytes) to the JsonString.
231*/
232static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
233 va_list ap;
234 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
235 va_start(ap, zFormat);
236 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
237 va_end(ap);
238 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
239}
240
drh5634cc02015-08-17 11:28:03 +0000241/* Append a single character
242*/
drh505ad2c2015-08-21 17:33:11 +0000243static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000244 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
245 p->zBuf[p->nUsed++] = c;
246}
247
drh301eecc2015-08-17 20:14:19 +0000248/* Append a comma separator to the output buffer, if the previous
249** character is not '[' or '{'.
250*/
drh505ad2c2015-08-21 17:33:11 +0000251static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000252 char c;
253 if( p->nUsed==0 ) return;
254 c = p->zBuf[p->nUsed-1];
255 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
256}
257
drh505ad2c2015-08-21 17:33:11 +0000258/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000259** under construction. Enclose the string in "..." and escape
260** any double-quotes or backslash characters contained within the
261** string.
262*/
drh505ad2c2015-08-21 17:33:11 +0000263static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000264 u32 i;
265 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
266 p->zBuf[p->nUsed++] = '"';
267 for(i=0; i<N; i++){
268 char c = zIn[i];
269 if( c=='"' || c=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000270 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000271 p->zBuf[p->nUsed++] = '\\';
272 }
273 p->zBuf[p->nUsed++] = c;
274 }
275 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000276 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000277}
278
drhd0960592015-08-17 21:22:32 +0000279/*
280** Append a function parameter value to the JSON string under
281** construction.
282*/
283static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000284 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000285 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000286){
287 switch( sqlite3_value_type(pValue) ){
288 case SQLITE_NULL: {
289 jsonAppendRaw(p, "null", 4);
290 break;
291 }
292 case SQLITE_INTEGER:
293 case SQLITE_FLOAT: {
294 const char *z = (const char*)sqlite3_value_text(pValue);
295 u32 n = (u32)sqlite3_value_bytes(pValue);
296 jsonAppendRaw(p, z, n);
297 break;
298 }
299 case SQLITE_TEXT: {
300 const char *z = (const char*)sqlite3_value_text(pValue);
301 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000302 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000303 jsonAppendRaw(p, z, n);
304 }else{
305 jsonAppendString(p, z, n);
306 }
drhd0960592015-08-17 21:22:32 +0000307 break;
308 }
309 default: {
310 if( p->bErr==0 ){
311 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
312 p->bErr = 1;
313 jsonReset(p);
314 }
315 break;
316 }
317 }
318}
319
320
drhbd0621b2015-08-13 13:54:59 +0000321/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000322*/
drh505ad2c2015-08-21 17:33:11 +0000323static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000324 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000325 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
326 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
327 SQLITE_UTF8);
328 jsonZero(p);
329 }
330 assert( p->bStatic );
331}
332
drh505ad2c2015-08-21 17:33:11 +0000333/**************************************************************************
334** Utility routines for dealing with JsonNode and JsonParse objects
335**************************************************************************/
336
337/*
338** Return the number of consecutive JsonNode slots need to represent
339** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
340** OBJECT types, the number might be larger.
341**
342** Appended elements are not counted. The value returned is the number
343** by which the JsonNode counter should increment in order to go to the
344** next peer value.
345*/
346static u32 jsonNodeSize(JsonNode *pNode){
347 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
348}
349
350/*
351** Reclaim all memory allocated by a JsonParse object. But do not
352** delete the JsonParse object itself.
353*/
354static void jsonParseReset(JsonParse *pParse){
355 sqlite3_free(pParse->aNode);
356 pParse->aNode = 0;
357 pParse->nNode = 0;
358 pParse->nAlloc = 0;
359 sqlite3_free(pParse->aUp);
360 pParse->aUp = 0;
361}
362
drh5634cc02015-08-17 11:28:03 +0000363/*
364** Convert the JsonNode pNode into a pure JSON string and
365** append to pOut. Subsubstructure is also included. Return
366** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000367*/
drh52216ad2015-08-18 02:28:03 +0000368static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000369 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000370 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000371 sqlite3_value **aReplace /* Replacement values */
372){
drh5634cc02015-08-17 11:28:03 +0000373 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000374 default: {
375 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000376 jsonAppendRaw(pOut, "null", 4);
377 break;
378 }
379 case JSON_TRUE: {
380 jsonAppendRaw(pOut, "true", 4);
381 break;
382 }
383 case JSON_FALSE: {
384 jsonAppendRaw(pOut, "false", 5);
385 break;
386 }
387 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000388 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000389 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000390 break;
391 }
392 /* Fall through into the next case */
393 }
394 case JSON_REAL:
395 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000396 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000397 break;
398 }
399 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000400 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000401 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000402 for(;;){
403 while( j<=pNode->n ){
404 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
405 if( pNode[j].jnFlags & JNODE_REPLACE ){
406 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000407 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000408 }
409 }else{
drhd0960592015-08-17 21:22:32 +0000410 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000411 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000412 }
drh505ad2c2015-08-21 17:33:11 +0000413 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000414 }
drh52216ad2015-08-18 02:28:03 +0000415 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
416 pNode = &pNode[pNode->u.iAppend];
417 j = 1;
drh5634cc02015-08-17 11:28:03 +0000418 }
419 jsonAppendChar(pOut, ']');
420 break;
421 }
422 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000423 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000424 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000425 for(;;){
426 while( j<=pNode->n ){
427 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
428 jsonAppendSeparator(pOut);
429 jsonRenderNode(&pNode[j], pOut, aReplace);
430 jsonAppendChar(pOut, ':');
431 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000432 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000433 }else{
434 jsonRenderNode(&pNode[j+1], pOut, aReplace);
435 }
drhd0960592015-08-17 21:22:32 +0000436 }
drh505ad2c2015-08-21 17:33:11 +0000437 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000438 }
drh52216ad2015-08-18 02:28:03 +0000439 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
440 pNode = &pNode[pNode->u.iAppend];
441 j = 1;
drh5634cc02015-08-17 11:28:03 +0000442 }
443 jsonAppendChar(pOut, '}');
444 break;
445 }
drhbd0621b2015-08-13 13:54:59 +0000446 }
drh5634cc02015-08-17 11:28:03 +0000447}
448
449/*
drhf2df7e72015-08-28 20:07:40 +0000450** Return a JsonNode and all its descendents as a JSON string.
451*/
452static void jsonReturnJson(
453 JsonNode *pNode, /* Node to return */
454 sqlite3_context *pCtx, /* Return value for this function */
455 sqlite3_value **aReplace /* Array of replacement values */
456){
457 JsonString s;
458 jsonInit(&s, pCtx);
459 jsonRenderNode(pNode, &s, aReplace);
460 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000461 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000462}
463
464/*
drh5634cc02015-08-17 11:28:03 +0000465** Make the JsonNode the return value of the function.
466*/
drhd0960592015-08-17 21:22:32 +0000467static void jsonReturn(
468 JsonNode *pNode, /* Node to return */
469 sqlite3_context *pCtx, /* Return value for this function */
470 sqlite3_value **aReplace /* Array of replacement values */
471){
drh5634cc02015-08-17 11:28:03 +0000472 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000473 default: {
474 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000475 sqlite3_result_null(pCtx);
476 break;
477 }
478 case JSON_TRUE: {
479 sqlite3_result_int(pCtx, 1);
480 break;
481 }
482 case JSON_FALSE: {
483 sqlite3_result_int(pCtx, 0);
484 break;
485 }
drh987eb1f2015-08-17 15:17:37 +0000486 case JSON_INT: {
487 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000488 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000489 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000490 while( z[0]>='0' && z[0]<='9' ){
491 unsigned v = *(z++) - '0';
492 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000493 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000494 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
495 if( v==9 ) goto int_as_real;
496 if( v==8 ){
497 if( pNode->u.zJContent[0]=='-' ){
498 sqlite3_result_int64(pCtx, SMALLEST_INT64);
499 goto int_done;
500 }else{
501 goto int_as_real;
502 }
503 }
504 }
505 i = i*10 + v;
506 }
drh52216ad2015-08-18 02:28:03 +0000507 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000508 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000509 int_done:
510 break;
511 int_as_real: /* fall through to real */;
512 }
513 case JSON_REAL: {
514 double r = strtod(pNode->u.zJContent, 0);
515 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000516 break;
517 }
drh5634cc02015-08-17 11:28:03 +0000518 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000519#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
520 ** json_insert() and json_replace() and those routines do not
521 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000522 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000523 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
524 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000525 }else
526#endif
527 assert( (pNode->jnFlags & JNODE_RAW)==0 );
528 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000529 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000530 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000531 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000532 }else{
533 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000534 u32 i;
535 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000536 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000537 char *zOut;
538 u32 j;
539 zOut = sqlite3_malloc( n+1 );
540 if( zOut==0 ){
541 sqlite3_result_error_nomem(pCtx);
542 break;
543 }
544 for(i=1, j=0; i<n-1; i++){
545 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000546 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000547 zOut[j++] = c;
548 }else{
549 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000550 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000551 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000552 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000553 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000554 if( c>='0' && c<='9' ) v = v*16 + c - '0';
555 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
556 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
557 else break;
drh987eb1f2015-08-17 15:17:37 +0000558 }
drh80d87402015-08-24 12:42:41 +0000559 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000560 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000561 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000562 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000563 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000564 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000565 }else{
mistachkin16a93122015-09-11 18:05:01 +0000566 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000567 zOut[j++] = 0x80 | ((v>>6)&0x3f);
568 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000569 }
570 }else{
571 if( c=='b' ){
572 c = '\b';
573 }else if( c=='f' ){
574 c = '\f';
575 }else if( c=='n' ){
576 c = '\n';
577 }else if( c=='r' ){
578 c = '\r';
579 }else if( c=='t' ){
580 c = '\t';
581 }
582 zOut[j++] = c;
583 }
584 }
585 }
586 zOut[j] = 0;
587 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000588 }
589 break;
590 }
591 case JSON_ARRAY:
592 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000593 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000594 break;
595 }
596 }
drhbd0621b2015-08-13 13:54:59 +0000597}
598
drh95677942015-09-24 01:06:37 +0000599/* Forward reference */
600static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
601
602/*
603** A macro to hint to the compiler that a function should not be
604** inlined.
605*/
606#if defined(__GNUC__)
607# define JSON_NOINLINE __attribute__((noinline))
608#elif defined(_MSC_VER) && _MSC_VER>=1310
609# define JSON_NOINLINE __declspec(noinline)
610#else
611# define JSON_NOINLINE
612#endif
613
614
615static JSON_NOINLINE int jsonParseAddNodeExpand(
616 JsonParse *pParse, /* Append the node to this object */
617 u32 eType, /* Node type */
618 u32 n, /* Content size or sub-node count */
619 const char *zContent /* Content */
620){
621 u32 nNew;
622 JsonNode *pNew;
623 assert( pParse->nNode>=pParse->nAlloc );
624 if( pParse->oom ) return -1;
625 nNew = pParse->nAlloc*2 + 10;
626 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
627 if( pNew==0 ){
628 pParse->oom = 1;
629 return -1;
630 }
631 pParse->nAlloc = nNew;
632 pParse->aNode = pNew;
633 assert( pParse->nNode<pParse->nAlloc );
634 return jsonParseAddNode(pParse, eType, n, zContent);
635}
636
drh5fa5c102015-08-12 16:49:40 +0000637/*
drhe9c37f32015-08-15 21:25:36 +0000638** Create a new JsonNode instance based on the arguments and append that
639** instance to the JsonParse. Return the index in pParse->aNode[] of the
640** new node, or -1 if a memory allocation fails.
641*/
642static int jsonParseAddNode(
643 JsonParse *pParse, /* Append the node to this object */
644 u32 eType, /* Node type */
645 u32 n, /* Content size or sub-node count */
646 const char *zContent /* Content */
647){
648 JsonNode *p;
649 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000650 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000651 }
652 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000653 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000654 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000655 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000656 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000657 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000658 return pParse->nNode++;
659}
660
661/*
662** Parse a single JSON value which begins at pParse->zJson[i]. Return the
663** index of the first character past the end of the value parsed.
664**
665** Return negative for a syntax error. Special cases: return -2 if the
666** first non-whitespace character is '}' and return -3 if the first
667** non-whitespace character is ']'.
668*/
669static int jsonParseValue(JsonParse *pParse, u32 i){
670 char c;
671 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000672 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000673 int x;
drh852944e2015-09-10 03:29:11 +0000674 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000675 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drh8cb15cc2015-09-24 01:40:45 +0000676 if( (c = pParse->zJson[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000677 /* Parse object */
678 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000679 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000680 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000681 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000682 x = jsonParseValue(pParse, j);
683 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000684 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000685 return -1;
686 }
drhbe9474e2015-08-22 03:05:54 +0000687 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000688 pNode = &pParse->aNode[pParse->nNode-1];
689 if( pNode->eType!=JSON_STRING ) return -1;
690 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000691 j = x;
dan2e8f5512015-09-17 17:21:09 +0000692 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000693 if( pParse->zJson[j]!=':' ) return -1;
694 j++;
695 x = jsonParseValue(pParse, j);
696 if( x<0 ) return -1;
697 j = x;
dan2e8f5512015-09-17 17:21:09 +0000698 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000699 c = pParse->zJson[j];
700 if( c==',' ) continue;
701 if( c!='}' ) return -1;
702 break;
703 }
drhbc8f0922015-08-22 19:39:04 +0000704 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000705 return j+1;
706 }else if( c=='[' ){
707 /* Parse array */
708 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000709 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000710 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000711 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000712 x = jsonParseValue(pParse, j);
713 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000714 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000715 return -1;
716 }
717 j = x;
dan2e8f5512015-09-17 17:21:09 +0000718 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000719 c = pParse->zJson[j];
720 if( c==',' ) continue;
721 if( c!=']' ) return -1;
722 break;
723 }
drhbc8f0922015-08-22 19:39:04 +0000724 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000725 return j+1;
726 }else if( c=='"' ){
727 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000728 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000729 j = i+1;
730 for(;;){
731 c = pParse->zJson[j];
732 if( c==0 ) return -1;
733 if( c=='\\' ){
734 c = pParse->zJson[++j];
735 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000736 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000737 }else if( c=='"' ){
738 break;
739 }
740 j++;
741 }
742 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000743 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000744 return j+1;
745 }else if( c=='n'
746 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000747 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000748 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
749 return i+4;
750 }else if( c=='t'
751 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000752 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000753 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
754 return i+4;
755 }else if( c=='f'
756 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000757 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000758 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
759 return i+5;
760 }else if( c=='-' || (c>='0' && c<='9') ){
761 /* Parse number */
762 u8 seenDP = 0;
763 u8 seenE = 0;
764 j = i+1;
765 for(;; j++){
766 c = pParse->zJson[j];
767 if( c>='0' && c<='9' ) continue;
768 if( c=='.' ){
769 if( pParse->zJson[j-1]=='-' ) return -1;
770 if( seenDP ) return -1;
771 seenDP = 1;
772 continue;
773 }
774 if( c=='e' || c=='E' ){
775 if( pParse->zJson[j-1]<'0' ) return -1;
776 if( seenE ) return -1;
777 seenDP = seenE = 1;
778 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000779 if( c=='+' || c=='-' ){
780 j++;
781 c = pParse->zJson[j+1];
782 }
drhd1f00682015-08-29 16:02:37 +0000783 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000784 continue;
785 }
786 break;
787 }
788 if( pParse->zJson[j-1]<'0' ) return -1;
789 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
790 j - i, &pParse->zJson[i]);
791 return j;
792 }else if( c=='}' ){
793 return -2; /* End of {...} */
794 }else if( c==']' ){
795 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000796 }else if( c==0 ){
797 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000798 }else{
799 return -1; /* Syntax error */
800 }
801}
802
803/*
804** Parse a complete JSON string. Return 0 on success or non-zero if there
805** are any errors. If an error occurs, free all memory associated with
806** pParse.
807**
808** pParse is uninitialized when this routine is called.
809*/
drhbc8f0922015-08-22 19:39:04 +0000810static int jsonParse(
811 JsonParse *pParse, /* Initialize and fill this JsonParse object */
812 sqlite3_context *pCtx, /* Report errors here */
813 const char *zJson /* Input JSON text to be parsed */
814){
drhe9c37f32015-08-15 21:25:36 +0000815 int i;
drhe9c37f32015-08-15 21:25:36 +0000816 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000817 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000818 pParse->zJson = zJson;
819 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000820 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000821 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000822 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000823 if( zJson[i] ) i = -1;
824 }
drhd1f00682015-08-29 16:02:37 +0000825 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000826 if( pCtx!=0 ){
827 if( pParse->oom ){
828 sqlite3_result_error_nomem(pCtx);
829 }else{
830 sqlite3_result_error(pCtx, "malformed JSON", -1);
831 }
832 }
drh505ad2c2015-08-21 17:33:11 +0000833 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000834 return 1;
835 }
836 return 0;
837}
drh301eecc2015-08-17 20:14:19 +0000838
drh505ad2c2015-08-21 17:33:11 +0000839/* Mark node i of pParse as being a child of iParent. Call recursively
840** to fill in all the descendants of node i.
841*/
842static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
843 JsonNode *pNode = &pParse->aNode[i];
844 u32 j;
845 pParse->aUp[i] = iParent;
846 switch( pNode->eType ){
847 case JSON_ARRAY: {
848 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
849 jsonParseFillInParentage(pParse, i+j, i);
850 }
851 break;
852 }
853 case JSON_OBJECT: {
854 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
855 pParse->aUp[i+j] = i;
856 jsonParseFillInParentage(pParse, i+j+1, i);
857 }
858 break;
859 }
860 default: {
861 break;
862 }
863 }
864}
865
866/*
867** Compute the parentage of all nodes in a completed parse.
868*/
869static int jsonParseFindParents(JsonParse *pParse){
870 u32 *aUp;
871 assert( pParse->aUp==0 );
872 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000873 if( aUp==0 ){
874 pParse->oom = 1;
875 return SQLITE_NOMEM;
876 }
drh505ad2c2015-08-21 17:33:11 +0000877 jsonParseFillInParentage(pParse, 0, 0);
878 return SQLITE_OK;
879}
880
drh8cb0c832015-09-22 00:21:03 +0000881/*
882** Compare the OBJECT label at pNode against zKey,nKey. Return true on
883** a match.
884*/
885static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
886 if( pNode->jnFlags & JNODE_RAW ){
887 if( pNode->n!=nKey ) return 0;
888 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
889 }else{
890 if( pNode->n!=nKey+2 ) return 0;
891 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
892 }
893}
894
drh52216ad2015-08-18 02:28:03 +0000895/* forward declaration */
drha7714022015-08-29 00:54:49 +0000896static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000897
drh987eb1f2015-08-17 15:17:37 +0000898/*
899** Search along zPath to find the node specified. Return a pointer
900** to that node, or NULL if zPath is malformed or if there is no such
901** node.
drh52216ad2015-08-18 02:28:03 +0000902**
903** If pApnd!=0, then try to append new nodes to complete zPath if it is
904** possible to do so and if no existing node corresponds to zPath. If
905** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000906*/
drha7714022015-08-29 00:54:49 +0000907static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000908 JsonParse *pParse, /* The JSON to search */
909 u32 iRoot, /* Begin the search at this node */
910 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000911 int *pApnd, /* Append nodes to complete path if not NULL */
912 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000913){
drhbc8f0922015-08-22 19:39:04 +0000914 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000915 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000916 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000917 if( zPath[0]==0 ) return pRoot;
918 if( zPath[0]=='.' ){
919 if( pRoot->eType!=JSON_OBJECT ) return 0;
920 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000921 if( zPath[0]=='"' ){
922 zKey = zPath + 1;
923 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
924 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000925 if( zPath[i] ){
926 i++;
927 }else{
928 *pzErr = zPath;
929 return 0;
930 }
drh6b43cc82015-08-19 23:02:49 +0000931 }else{
932 zKey = zPath;
933 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
934 nKey = i;
935 }
drha7714022015-08-29 00:54:49 +0000936 if( nKey==0 ){
937 *pzErr = zPath;
938 return 0;
939 }
drh987eb1f2015-08-17 15:17:37 +0000940 j = 1;
drh52216ad2015-08-18 02:28:03 +0000941 for(;;){
942 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000943 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000944 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000945 }
946 j++;
drh505ad2c2015-08-21 17:33:11 +0000947 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000948 }
drh52216ad2015-08-18 02:28:03 +0000949 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
950 iRoot += pRoot->u.iAppend;
951 pRoot = &pParse->aNode[iRoot];
952 j = 1;
953 }
954 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000955 u32 iStart, iLabel;
956 JsonNode *pNode;
957 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
958 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000959 zPath += i;
drha7714022015-08-29 00:54:49 +0000960 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000961 if( pParse->oom ) return 0;
962 if( pNode ){
963 pRoot = &pParse->aNode[iRoot];
964 pRoot->u.iAppend = iStart - iRoot;
965 pRoot->jnFlags |= JNODE_APPEND;
966 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
967 }
968 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000969 }
dan2e8f5512015-09-17 17:21:09 +0000970 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000971 if( pRoot->eType!=JSON_ARRAY ) return 0;
972 i = 0;
drh3d1d2a92015-09-22 01:15:49 +0000973 j = 1;
974 while( safe_isdigit(zPath[j]) ){
975 i = i*10 + zPath[j] - '0';
976 j++;
drh987eb1f2015-08-17 15:17:37 +0000977 }
drh3d1d2a92015-09-22 01:15:49 +0000978 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +0000979 *pzErr = zPath;
980 return 0;
981 }
drh3d1d2a92015-09-22 01:15:49 +0000982 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +0000983 j = 1;
drh52216ad2015-08-18 02:28:03 +0000984 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000985 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
986 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000987 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000988 }
989 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
990 iRoot += pRoot->u.iAppend;
991 pRoot = &pParse->aNode[iRoot];
992 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000993 }
994 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000995 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000996 }
997 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000998 u32 iStart;
999 JsonNode *pNode;
1000 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001001 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001002 if( pParse->oom ) return 0;
1003 if( pNode ){
1004 pRoot = &pParse->aNode[iRoot];
1005 pRoot->u.iAppend = iStart - iRoot;
1006 pRoot->jnFlags |= JNODE_APPEND;
1007 }
1008 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001009 }
drh3d1d2a92015-09-22 01:15:49 +00001010 }else{
drha7714022015-08-29 00:54:49 +00001011 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001012 }
1013 return 0;
1014}
1015
drh52216ad2015-08-18 02:28:03 +00001016/*
drhbc8f0922015-08-22 19:39:04 +00001017** Append content to pParse that will complete zPath. Return a pointer
1018** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001019*/
1020static JsonNode *jsonLookupAppend(
1021 JsonParse *pParse, /* Append content to the JSON parse */
1022 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001023 int *pApnd, /* Set this flag to 1 */
1024 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001025){
1026 *pApnd = 1;
1027 if( zPath[0]==0 ){
1028 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1029 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1030 }
1031 if( zPath[0]=='.' ){
1032 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1033 }else if( strncmp(zPath,"[0]",3)==0 ){
1034 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1035 }else{
1036 return 0;
1037 }
1038 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001039 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001040}
1041
drhbc8f0922015-08-22 19:39:04 +00001042/*
drha7714022015-08-29 00:54:49 +00001043** Return the text of a syntax error message on a JSON path. Space is
1044** obtained from sqlite3_malloc().
1045*/
1046static char *jsonPathSyntaxError(const char *zErr){
1047 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1048}
1049
1050/*
1051** Do a node lookup using zPath. Return a pointer to the node on success.
1052** Return NULL if not found or if there is an error.
1053**
1054** On an error, write an error message into pCtx and increment the
1055** pParse->nErr counter.
1056**
1057** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1058** nodes are appended.
drha7714022015-08-29 00:54:49 +00001059*/
1060static JsonNode *jsonLookup(
1061 JsonParse *pParse, /* The JSON to search */
1062 const char *zPath, /* The path to search */
1063 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001064 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001065){
1066 const char *zErr = 0;
1067 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001068 char *zMsg;
drha7714022015-08-29 00:54:49 +00001069
1070 if( zPath==0 ) return 0;
1071 if( zPath[0]!='$' ){
1072 zErr = zPath;
1073 goto lookup_err;
1074 }
1075 zPath++;
drha7714022015-08-29 00:54:49 +00001076 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001077 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001078
1079lookup_err:
1080 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001081 assert( zErr!=0 && pCtx!=0 );
1082 zMsg = jsonPathSyntaxError(zErr);
1083 if( zMsg ){
1084 sqlite3_result_error(pCtx, zMsg, -1);
1085 sqlite3_free(zMsg);
1086 }else{
1087 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001088 }
drha7714022015-08-29 00:54:49 +00001089 return 0;
1090}
1091
1092
1093/*
drhbc8f0922015-08-22 19:39:04 +00001094** Report the wrong number of arguments for json_insert(), json_replace()
1095** or json_set().
1096*/
1097static void jsonWrongNumArgs(
1098 sqlite3_context *pCtx,
1099 const char *zFuncName
1100){
1101 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1102 zFuncName);
1103 sqlite3_result_error(pCtx, zMsg, -1);
1104 sqlite3_free(zMsg);
1105}
drh52216ad2015-08-18 02:28:03 +00001106
drha7714022015-08-29 00:54:49 +00001107
drh987eb1f2015-08-17 15:17:37 +00001108/****************************************************************************
1109** SQL functions used for testing and debugging
1110****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001111
drh301eecc2015-08-17 20:14:19 +00001112#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001113/*
drh5634cc02015-08-17 11:28:03 +00001114** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001115** a parse of the JSON provided. Or it returns NULL if JSON is not
1116** well-formed.
1117*/
drh5634cc02015-08-17 11:28:03 +00001118static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001119 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001120 int argc,
1121 sqlite3_value **argv
1122){
drh505ad2c2015-08-21 17:33:11 +00001123 JsonString s; /* Output string - not real JSON */
1124 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001125 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001126
1127 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001128 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001129 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001130 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001131 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001132 const char *zType;
1133 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1134 assert( x.aNode[i].eType==JSON_STRING );
1135 zType = "label";
1136 }else{
1137 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001138 }
drh852944e2015-09-10 03:29:11 +00001139 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1140 i, zType, x.aNode[i].n, x.aUp[i]);
1141 if( x.aNode[i].u.zJContent!=0 ){
1142 jsonAppendRaw(&s, " ", 1);
1143 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1144 }
1145 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001146 }
drh505ad2c2015-08-21 17:33:11 +00001147 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001148 jsonResult(&s);
1149}
1150
drh5634cc02015-08-17 11:28:03 +00001151/*
drhf5ddb9c2015-09-11 00:06:41 +00001152** The json_test1(JSON) function return true (1) if the input is JSON
1153** text generated by another json function. It returns (0) if the input
1154** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001155*/
1156static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001157 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001158 int argc,
1159 sqlite3_value **argv
1160){
mistachkin16a93122015-09-11 18:05:01 +00001161 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001162 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001163}
drh301eecc2015-08-17 20:14:19 +00001164#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001165
drh987eb1f2015-08-17 15:17:37 +00001166/****************************************************************************
1167** SQL function implementations
1168****************************************************************************/
1169
1170/*
1171** Implementation of the json_array(VALUE,...) function. Return a JSON
1172** array that contains all values given in arguments. Or if any argument
1173** is a BLOB, throw an error.
1174*/
1175static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001176 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001177 int argc,
1178 sqlite3_value **argv
1179){
1180 int i;
drh505ad2c2015-08-21 17:33:11 +00001181 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001182
drhbc8f0922015-08-22 19:39:04 +00001183 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001184 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001185 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001186 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001187 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001188 }
drhd0960592015-08-17 21:22:32 +00001189 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001190 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001191 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001192}
1193
1194
1195/*
1196** json_array_length(JSON)
1197** json_array_length(JSON, PATH)
1198**
1199** Return the number of elements in the top-level JSON array.
1200** Return 0 if the input is not a well-formed JSON array.
1201*/
1202static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001203 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001204 int argc,
1205 sqlite3_value **argv
1206){
1207 JsonParse x; /* The parse */
1208 sqlite3_int64 n = 0;
1209 u32 i;
drha8f39a92015-09-21 22:53:16 +00001210 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001211
drhf2df7e72015-08-28 20:07:40 +00001212 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001213 assert( x.nNode );
1214 if( argc==2 ){
1215 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1216 pNode = jsonLookup(&x, zPath, 0, ctx);
1217 }else{
1218 pNode = x.aNode;
1219 }
1220 if( pNode==0 ){
1221 x.nErr = 1;
1222 }else if( pNode->eType==JSON_ARRAY ){
1223 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1224 for(i=1; i<=pNode->n; n++){
1225 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001226 }
drh987eb1f2015-08-17 15:17:37 +00001227 }
drha7714022015-08-29 00:54:49 +00001228 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001229 jsonParseReset(&x);
1230}
1231
1232/*
drh3ad93bb2015-08-29 19:41:45 +00001233** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001234**
drh3ad93bb2015-08-29 19:41:45 +00001235** Return the element described by PATH. Return NULL if there is no
1236** PATH element. If there are multiple PATHs, then return a JSON array
1237** with the result from each path. Throw an error if the JSON or any PATH
1238** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001239*/
1240static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001241 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001242 int argc,
1243 sqlite3_value **argv
1244){
1245 JsonParse x; /* The parse */
1246 JsonNode *pNode;
1247 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001248 JsonString jx;
1249 int i;
1250
1251 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001252 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001253 jsonInit(&jx, ctx);
1254 jsonAppendChar(&jx, '[');
1255 for(i=1; i<argc; i++){
1256 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001257 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001258 if( x.nErr ) break;
1259 if( argc>2 ){
1260 jsonAppendSeparator(&jx);
1261 if( pNode ){
1262 jsonRenderNode(pNode, &jx, 0);
1263 }else{
1264 jsonAppendRaw(&jx, "null", 4);
1265 }
1266 }else if( pNode ){
1267 jsonReturn(pNode, ctx, 0);
1268 }
drh987eb1f2015-08-17 15:17:37 +00001269 }
drh3ad93bb2015-08-29 19:41:45 +00001270 if( argc>2 && i==argc ){
1271 jsonAppendChar(&jx, ']');
1272 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001273 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001274 }
1275 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001276 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001277}
1278
1279/*
1280** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1281** object that contains all name/value given in arguments. Or if any name
1282** is not a string or if any value is a BLOB, throw an error.
1283*/
1284static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001285 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001286 int argc,
1287 sqlite3_value **argv
1288){
1289 int i;
drh505ad2c2015-08-21 17:33:11 +00001290 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001291 const char *z;
1292 u32 n;
1293
1294 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001295 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001296 "of arguments", -1);
1297 return;
1298 }
drhbc8f0922015-08-22 19:39:04 +00001299 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001300 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001301 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001302 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001303 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001304 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001305 return;
1306 }
drhd0960592015-08-17 21:22:32 +00001307 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001308 z = (const char*)sqlite3_value_text(argv[i]);
1309 n = (u32)sqlite3_value_bytes(argv[i]);
1310 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001311 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001312 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001313 }
drhd0960592015-08-17 21:22:32 +00001314 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001315 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001316 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001317}
1318
1319
1320/*
drh301eecc2015-08-17 20:14:19 +00001321** json_remove(JSON, PATH, ...)
1322**
drh3ad93bb2015-08-29 19:41:45 +00001323** Remove the named elements from JSON and return the result. malformed
1324** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001325*/
1326static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001327 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001328 int argc,
1329 sqlite3_value **argv
1330){
1331 JsonParse x; /* The parse */
1332 JsonNode *pNode;
1333 const char *zPath;
1334 u32 i;
1335
1336 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001337 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001338 assert( x.nNode );
1339 for(i=1; i<(u32)argc; i++){
1340 zPath = (const char*)sqlite3_value_text(argv[i]);
1341 if( zPath==0 ) goto remove_done;
1342 pNode = jsonLookup(&x, zPath, 0, ctx);
1343 if( x.nErr ) goto remove_done;
1344 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1345 }
1346 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1347 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001348 }
drha7714022015-08-29 00:54:49 +00001349remove_done:
drh505ad2c2015-08-21 17:33:11 +00001350 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001351}
1352
1353/*
1354** json_replace(JSON, PATH, VALUE, ...)
1355**
1356** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001357** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001358*/
1359static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001360 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001361 int argc,
1362 sqlite3_value **argv
1363){
1364 JsonParse x; /* The parse */
1365 JsonNode *pNode;
1366 const char *zPath;
1367 u32 i;
1368
1369 if( argc<1 ) return;
1370 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001371 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001372 return;
1373 }
drhbc8f0922015-08-22 19:39:04 +00001374 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001375 assert( x.nNode );
1376 for(i=1; i<(u32)argc; i+=2){
1377 zPath = (const char*)sqlite3_value_text(argv[i]);
1378 pNode = jsonLookup(&x, zPath, 0, ctx);
1379 if( x.nErr ) goto replace_err;
1380 if( pNode ){
1381 pNode->jnFlags |= (u8)JNODE_REPLACE;
1382 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001383 }
drha8f39a92015-09-21 22:53:16 +00001384 }
1385 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1386 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1387 }else{
1388 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001389 }
drha7714022015-08-29 00:54:49 +00001390replace_err:
drh505ad2c2015-08-21 17:33:11 +00001391 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001392}
drh505ad2c2015-08-21 17:33:11 +00001393
drh52216ad2015-08-18 02:28:03 +00001394/*
1395** json_set(JSON, PATH, VALUE, ...)
1396**
1397** Set the value at PATH to VALUE. Create the PATH if it does not already
1398** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001399** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001400**
1401** json_insert(JSON, PATH, VALUE, ...)
1402**
1403** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001404** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001405*/
1406static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001407 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001408 int argc,
1409 sqlite3_value **argv
1410){
1411 JsonParse x; /* The parse */
1412 JsonNode *pNode;
1413 const char *zPath;
1414 u32 i;
1415 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001416 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001417
1418 if( argc<1 ) return;
1419 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001420 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001421 return;
1422 }
drhbc8f0922015-08-22 19:39:04 +00001423 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001424 assert( x.nNode );
1425 for(i=1; i<(u32)argc; i+=2){
1426 zPath = (const char*)sqlite3_value_text(argv[i]);
1427 bApnd = 0;
1428 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1429 if( x.oom ){
1430 sqlite3_result_error_nomem(ctx);
1431 goto jsonSetDone;
1432 }else if( x.nErr ){
1433 goto jsonSetDone;
1434 }else if( pNode && (bApnd || bIsSet) ){
1435 pNode->jnFlags |= (u8)JNODE_REPLACE;
1436 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001437 }
drha8f39a92015-09-21 22:53:16 +00001438 }
1439 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1440 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1441 }else{
1442 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001443 }
drhbc8f0922015-08-22 19:39:04 +00001444jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001445 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001446}
drh301eecc2015-08-17 20:14:19 +00001447
1448/*
drh987eb1f2015-08-17 15:17:37 +00001449** json_type(JSON)
1450** json_type(JSON, PATH)
1451**
drh3ad93bb2015-08-29 19:41:45 +00001452** Return the top-level "type" of a JSON string. Throw an error if
1453** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001454*/
1455static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001456 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001457 int argc,
1458 sqlite3_value **argv
1459){
1460 JsonParse x; /* The parse */
1461 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001462 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001463
drhbc8f0922015-08-22 19:39:04 +00001464 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001465 assert( x.nNode );
1466 if( argc==2 ){
1467 zPath = (const char*)sqlite3_value_text(argv[1]);
1468 pNode = jsonLookup(&x, zPath, 0, ctx);
1469 }else{
1470 pNode = x.aNode;
1471 }
1472 if( pNode ){
1473 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001474 }
drh505ad2c2015-08-21 17:33:11 +00001475 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001476}
drh5634cc02015-08-17 11:28:03 +00001477
drhbc8f0922015-08-22 19:39:04 +00001478/*
1479** json_valid(JSON)
1480**
drh3ad93bb2015-08-29 19:41:45 +00001481** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1482** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001483*/
1484static void jsonValidFunc(
1485 sqlite3_context *ctx,
1486 int argc,
1487 sqlite3_value **argv
1488){
1489 JsonParse x; /* The parse */
1490 int rc = 0;
1491
mistachkin16a93122015-09-11 18:05:01 +00001492 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001493 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001494 rc = 1;
1495 }
1496 jsonParseReset(&x);
1497 sqlite3_result_int(ctx, rc);
1498}
1499
drhd2975922015-08-29 17:22:33 +00001500#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001501/****************************************************************************
1502** The json_each virtual table
1503****************************************************************************/
1504typedef struct JsonEachCursor JsonEachCursor;
1505struct JsonEachCursor {
1506 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001507 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001508 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001509 u32 i; /* Index in sParse.aNode[] of current row */
1510 u32 iEnd; /* EOF when i equals or exceeds this value */
1511 u8 eType; /* Type of top-level element */
1512 u8 bRecursive; /* True for json_tree(). False for json_each() */
1513 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001514 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001515 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001516};
1517
1518/* Constructor for the json_each virtual table */
1519static int jsonEachConnect(
1520 sqlite3 *db,
1521 void *pAux,
1522 int argc, const char *const*argv,
1523 sqlite3_vtab **ppVtab,
1524 char **pzErr
1525){
1526 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001527 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001528
1529/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001530#define JEACH_KEY 0
1531#define JEACH_VALUE 1
1532#define JEACH_TYPE 2
1533#define JEACH_ATOM 3
1534#define JEACH_ID 4
1535#define JEACH_PARENT 5
1536#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001537#define JEACH_PATH 7
1538#define JEACH_JSON 8
1539#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001540
drh6fd5c1e2015-08-21 20:37:12 +00001541 UNUSED_PARAM(pzErr);
1542 UNUSED_PARAM(argv);
1543 UNUSED_PARAM(argc);
1544 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001545 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001546 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1547 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001548 if( rc==SQLITE_OK ){
1549 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1550 if( pNew==0 ) return SQLITE_NOMEM;
1551 memset(pNew, 0, sizeof(*pNew));
1552 }
1553 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001554}
1555
1556/* destructor for json_each virtual table */
1557static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1558 sqlite3_free(pVtab);
1559 return SQLITE_OK;
1560}
1561
drh505ad2c2015-08-21 17:33:11 +00001562/* constructor for a JsonEachCursor object for json_each(). */
1563static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001564 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001565
1566 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001567 pCur = sqlite3_malloc( sizeof(*pCur) );
1568 if( pCur==0 ) return SQLITE_NOMEM;
1569 memset(pCur, 0, sizeof(*pCur));
1570 *ppCursor = &pCur->base;
1571 return SQLITE_OK;
1572}
1573
drh505ad2c2015-08-21 17:33:11 +00001574/* constructor for a JsonEachCursor object for json_tree(). */
1575static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1576 int rc = jsonEachOpenEach(p, ppCursor);
1577 if( rc==SQLITE_OK ){
1578 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1579 pCur->bRecursive = 1;
1580 }
1581 return rc;
1582}
1583
drhcb6c6c62015-08-19 22:47:17 +00001584/* Reset a JsonEachCursor back to its original state. Free any memory
1585** held. */
1586static void jsonEachCursorReset(JsonEachCursor *p){
1587 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001588 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001589 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001590 p->iRowid = 0;
1591 p->i = 0;
1592 p->iEnd = 0;
1593 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001594 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001595 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001596}
1597
1598/* Destructor for a jsonEachCursor object */
1599static int jsonEachClose(sqlite3_vtab_cursor *cur){
1600 JsonEachCursor *p = (JsonEachCursor*)cur;
1601 jsonEachCursorReset(p);
1602 sqlite3_free(cur);
1603 return SQLITE_OK;
1604}
1605
1606/* Return TRUE if the jsonEachCursor object has been advanced off the end
1607** of the JSON object */
1608static int jsonEachEof(sqlite3_vtab_cursor *cur){
1609 JsonEachCursor *p = (JsonEachCursor*)cur;
1610 return p->i >= p->iEnd;
1611}
1612
drh505ad2c2015-08-21 17:33:11 +00001613/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001614static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001615 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001616 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001617 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1618 p->i++;
drh4af352d2015-08-21 20:02:48 +00001619 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001620 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001621 u32 iUp = p->sParse.aUp[p->i];
1622 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001623 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001624 if( pUp->eType==JSON_ARRAY ){
1625 if( iUp==p->i-1 ){
1626 pUp->u.iKey = 0;
1627 }else{
1628 pUp->u.iKey++;
1629 }
drh4af352d2015-08-21 20:02:48 +00001630 }
1631 }
drh505ad2c2015-08-21 17:33:11 +00001632 }else{
drh4af352d2015-08-21 20:02:48 +00001633 switch( p->eType ){
1634 case JSON_ARRAY: {
1635 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1636 p->iRowid++;
1637 break;
1638 }
1639 case JSON_OBJECT: {
1640 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1641 p->iRowid++;
1642 break;
1643 }
1644 default: {
1645 p->i = p->iEnd;
1646 break;
1647 }
drh505ad2c2015-08-21 17:33:11 +00001648 }
1649 }
1650 return SQLITE_OK;
1651}
1652
drh4af352d2015-08-21 20:02:48 +00001653/* Append the name of the path for element i to pStr
1654*/
1655static void jsonEachComputePath(
1656 JsonEachCursor *p, /* The cursor */
1657 JsonString *pStr, /* Write the path here */
1658 u32 i /* Path to this element */
1659){
1660 JsonNode *pNode, *pUp;
1661 u32 iUp;
1662 if( i==0 ){
1663 jsonAppendChar(pStr, '$');
1664 return;
drhcb6c6c62015-08-19 22:47:17 +00001665 }
drh4af352d2015-08-21 20:02:48 +00001666 iUp = p->sParse.aUp[i];
1667 jsonEachComputePath(p, pStr, iUp);
1668 pNode = &p->sParse.aNode[i];
1669 pUp = &p->sParse.aNode[iUp];
1670 if( pUp->eType==JSON_ARRAY ){
1671 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1672 }else{
1673 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001674 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001675 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001676 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001677 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1678 }
drhcb6c6c62015-08-19 22:47:17 +00001679}
1680
1681/* Return the value of a column */
1682static int jsonEachColumn(
1683 sqlite3_vtab_cursor *cur, /* The cursor */
1684 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1685 int i /* Which column to return */
1686){
1687 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001688 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001689 switch( i ){
1690 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001691 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001692 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001693 jsonReturn(pThis, ctx, 0);
1694 }else if( p->eType==JSON_ARRAY ){
1695 u32 iKey;
1696 if( p->bRecursive ){
1697 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001698 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001699 }else{
1700 iKey = p->iRowid;
1701 }
drh6fd5c1e2015-08-21 20:37:12 +00001702 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001703 }
1704 break;
1705 }
1706 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001707 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001708 jsonReturn(pThis, ctx, 0);
1709 break;
1710 }
1711 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001712 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001713 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1714 break;
1715 }
1716 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001717 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001718 if( pThis->eType>=JSON_ARRAY ) break;
1719 jsonReturn(pThis, ctx, 0);
1720 break;
1721 }
1722 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001723 sqlite3_result_int64(ctx,
1724 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001725 break;
1726 }
1727 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001728 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001729 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001730 }
1731 break;
1732 }
drh4af352d2015-08-21 20:02:48 +00001733 case JEACH_FULLKEY: {
1734 JsonString x;
1735 jsonInit(&x, ctx);
1736 if( p->bRecursive ){
1737 jsonEachComputePath(p, &x, p->i);
1738 }else{
drh383de692015-09-10 17:20:57 +00001739 if( p->zRoot ){
1740 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001741 }else{
1742 jsonAppendChar(&x, '$');
1743 }
1744 if( p->eType==JSON_ARRAY ){
1745 jsonPrintf(30, &x, "[%d]", p->iRowid);
1746 }else{
1747 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1748 }
1749 }
1750 jsonResult(&x);
1751 break;
1752 }
drhcb6c6c62015-08-19 22:47:17 +00001753 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001754 if( p->bRecursive ){
1755 JsonString x;
1756 jsonInit(&x, ctx);
1757 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1758 jsonResult(&x);
1759 break;
drh4af352d2015-08-21 20:02:48 +00001760 }
drh383de692015-09-10 17:20:57 +00001761 /* For json_each() path and root are the same so fall through
1762 ** into the root case */
1763 }
1764 case JEACH_ROOT: {
1765 const char *zRoot = p->zRoot;
1766 if( zRoot==0 ) zRoot = "$";
1767 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001768 break;
1769 }
drh3d1d2a92015-09-22 01:15:49 +00001770 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00001771 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001772 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1773 break;
1774 }
1775 }
1776 return SQLITE_OK;
1777}
1778
1779/* Return the current rowid value */
1780static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1781 JsonEachCursor *p = (JsonEachCursor*)cur;
1782 *pRowid = p->iRowid;
1783 return SQLITE_OK;
1784}
1785
1786/* The query strategy is to look for an equality constraint on the json
1787** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001788** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001789** and 0 otherwise.
1790*/
1791static int jsonEachBestIndex(
1792 sqlite3_vtab *tab,
1793 sqlite3_index_info *pIdxInfo
1794){
1795 int i;
1796 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001797 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001798 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001799
1800 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001801 pConstraint = pIdxInfo->aConstraint;
1802 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1803 if( pConstraint->usable==0 ) continue;
1804 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1805 switch( pConstraint->iColumn ){
1806 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001807 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001808 default: /* no-op */ break;
1809 }
1810 }
1811 if( jsonIdx<0 ){
1812 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001813 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001814 }else{
drh505ad2c2015-08-21 17:33:11 +00001815 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001816 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1817 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001818 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001819 pIdxInfo->idxNum = 1;
1820 }else{
drh383de692015-09-10 17:20:57 +00001821 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1822 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001823 pIdxInfo->idxNum = 3;
1824 }
1825 }
1826 return SQLITE_OK;
1827}
1828
1829/* Start a search on a new JSON string */
1830static int jsonEachFilter(
1831 sqlite3_vtab_cursor *cur,
1832 int idxNum, const char *idxStr,
1833 int argc, sqlite3_value **argv
1834){
1835 JsonEachCursor *p = (JsonEachCursor*)cur;
1836 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001837 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001838 sqlite3_int64 n;
1839
drh6fd5c1e2015-08-21 20:37:12 +00001840 UNUSED_PARAM(idxStr);
1841 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001842 jsonEachCursorReset(p);
1843 if( idxNum==0 ) return SQLITE_OK;
1844 z = (const char*)sqlite3_value_text(argv[0]);
1845 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001846 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001847 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001848 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001849 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001850 if( jsonParse(&p->sParse, 0, p->zJson) ){
1851 int rc = SQLITE_NOMEM;
1852 if( p->sParse.oom==0 ){
1853 sqlite3_free(cur->pVtab->zErrMsg);
1854 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1855 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1856 }
drhcb6c6c62015-08-19 22:47:17 +00001857 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001858 return rc;
1859 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1860 jsonEachCursorReset(p);
1861 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001862 }else{
drh95677942015-09-24 01:06:37 +00001863 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00001864 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001865 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001866 zRoot = (const char*)sqlite3_value_text(argv[1]);
1867 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001868 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001869 p->zRoot = sqlite3_malloc64( n+1 );
1870 if( p->zRoot==0 ) return SQLITE_NOMEM;
1871 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001872 if( zRoot[0]!='$' ){
1873 zErr = zRoot;
1874 }else{
1875 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1876 }
1877 if( zErr ){
drha7714022015-08-29 00:54:49 +00001878 sqlite3_free(cur->pVtab->zErrMsg);
1879 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001880 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001881 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1882 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001883 return SQLITE_OK;
1884 }
1885 }else{
1886 pNode = p->sParse.aNode;
1887 }
drh852944e2015-09-10 03:29:11 +00001888 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001889 p->eType = pNode->eType;
1890 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001891 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001892 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001893 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00001894 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00001895 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1896 p->i--;
1897 }
1898 }else{
1899 p->i++;
1900 }
drhcb6c6c62015-08-19 22:47:17 +00001901 }else{
1902 p->iEnd = p->i+1;
1903 }
1904 }
drha8f39a92015-09-21 22:53:16 +00001905 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001906}
1907
1908/* The methods of the json_each virtual table */
1909static sqlite3_module jsonEachModule = {
1910 0, /* iVersion */
1911 0, /* xCreate */
1912 jsonEachConnect, /* xConnect */
1913 jsonEachBestIndex, /* xBestIndex */
1914 jsonEachDisconnect, /* xDisconnect */
1915 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001916 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001917 jsonEachClose, /* xClose - close a cursor */
1918 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001919 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001920 jsonEachEof, /* xEof - check for end of scan */
1921 jsonEachColumn, /* xColumn - read data */
1922 jsonEachRowid, /* xRowid - read data */
1923 0, /* xUpdate */
1924 0, /* xBegin */
1925 0, /* xSync */
1926 0, /* xCommit */
1927 0, /* xRollback */
1928 0, /* xFindMethod */
1929 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001930 0, /* xSavepoint */
1931 0, /* xRelease */
1932 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001933};
1934
drh505ad2c2015-08-21 17:33:11 +00001935/* The methods of the json_tree virtual table. */
1936static sqlite3_module jsonTreeModule = {
1937 0, /* iVersion */
1938 0, /* xCreate */
1939 jsonEachConnect, /* xConnect */
1940 jsonEachBestIndex, /* xBestIndex */
1941 jsonEachDisconnect, /* xDisconnect */
1942 0, /* xDestroy */
1943 jsonEachOpenTree, /* xOpen - open a cursor */
1944 jsonEachClose, /* xClose - close a cursor */
1945 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001946 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001947 jsonEachEof, /* xEof - check for end of scan */
1948 jsonEachColumn, /* xColumn - read data */
1949 jsonEachRowid, /* xRowid - read data */
1950 0, /* xUpdate */
1951 0, /* xBegin */
1952 0, /* xSync */
1953 0, /* xCommit */
1954 0, /* xRollback */
1955 0, /* xFindMethod */
1956 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001957 0, /* xSavepoint */
1958 0, /* xRelease */
1959 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001960};
drhd2975922015-08-29 17:22:33 +00001961#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001962
1963/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00001964** The following routines are the only publically visible identifiers in this
1965** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00001966** functions and the virtual table implemented by this file.
1967****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001968
drh2f20e132015-09-26 17:44:59 +00001969int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00001970 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001971 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001972 static const struct {
1973 const char *zName;
1974 int nArg;
drh52216ad2015-08-18 02:28:03 +00001975 int flag;
drh5fa5c102015-08-12 16:49:40 +00001976 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1977 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001978 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001979 { "json_array", -1, 0, jsonArrayFunc },
1980 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1981 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001982 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001983 { "json_insert", -1, 0, jsonSetFunc },
1984 { "json_object", -1, 0, jsonObjectFunc },
1985 { "json_remove", -1, 0, jsonRemoveFunc },
1986 { "json_replace", -1, 0, jsonReplaceFunc },
1987 { "json_set", -1, 1, jsonSetFunc },
1988 { "json_type", 1, 0, jsonTypeFunc },
1989 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001990 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001991
drh301eecc2015-08-17 20:14:19 +00001992#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001993 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001994 { "json_parse", 1, 0, jsonParseFunc },
1995 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001996#endif
drh5fa5c102015-08-12 16:49:40 +00001997 };
drhd2975922015-08-29 17:22:33 +00001998#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001999 static const struct {
2000 const char *zName;
2001 sqlite3_module *pModule;
2002 } aMod[] = {
2003 { "json_each", &jsonEachModule },
2004 { "json_tree", &jsonTreeModule },
2005 };
drhd2975922015-08-29 17:22:33 +00002006#endif
drh5fa5c102015-08-12 16:49:40 +00002007 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2008 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002009 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2010 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002011 aFunc[i].xFunc, 0, 0);
2012 }
drhd2975922015-08-29 17:22:33 +00002013#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002014 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2015 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002016 }
drhd2975922015-08-29 17:22:33 +00002017#endif
drh5fa5c102015-08-12 16:49:40 +00002018 return rc;
2019}
drh2f20e132015-09-26 17:44:59 +00002020
2021
2022#ifdef _WIN32
2023__declspec(dllexport)
2024#endif
2025int sqlite3_json_init(
2026 sqlite3 *db,
2027 char **pzErrMsg,
2028 const sqlite3_api_routines *pApi
2029){
2030 SQLITE_EXTENSION_INIT2(pApi);
2031 (void)pzErrMsg; /* Unused parameter */
2032 return sqlite3Json1Init(db);
2033}
drh50065652015-10-08 19:29:18 +00002034#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */