blob: f6fb2eafec4f5ad100e1d551749355481e610a75 [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>
drhe9c37f32015-08-15 21:25:36 +000031#include <ctype.h>
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
dan2e8f5512015-09-17 17:21:09 +000037/*
38** Versions of isspace(), isalnum() and isdigit() to which it is safe
39** to pass signed char values.
40*/
dan2e8f5512015-09-17 17:21:09 +000041#define safe_isdigit(x) isdigit((unsigned char)(x))
42#define safe_isalnum(x) isalnum((unsigned char)(x))
43
drh95677942015-09-24 01:06:37 +000044/*
45** Growing our own isspace() routine this way is twice as fast as
46** the library isspace() function, resulting in a 7% overall performance
47** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
48*/
49static const char jsonIsSpace[] = {
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0,
51 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
54 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
55 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
56 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
57 0, 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};
67#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
68
drh5fa5c102015-08-12 16:49:40 +000069/* Unsigned integer types */
70typedef sqlite3_uint64 u64;
71typedef unsigned int u32;
72typedef unsigned char u8;
73
drh52216ad2015-08-18 02:28:03 +000074/* Objects */
drh505ad2c2015-08-21 17:33:11 +000075typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000076typedef struct JsonNode JsonNode;
77typedef struct JsonParse JsonParse;
78
drh5634cc02015-08-17 11:28:03 +000079/* An instance of this object represents a JSON string
80** under construction. Really, this is a generic string accumulator
81** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000082*/
drh505ad2c2015-08-21 17:33:11 +000083struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000084 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000085 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000086 u64 nAlloc; /* Bytes of storage available in zBuf[] */
87 u64 nUsed; /* Bytes of zBuf[] currently used */
88 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000089 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000090 char zSpace[100]; /* Initial static space */
91};
92
drhe9c37f32015-08-15 21:25:36 +000093/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000094*/
drhe9c37f32015-08-15 21:25:36 +000095#define JSON_NULL 0
96#define JSON_TRUE 1
97#define JSON_FALSE 2
98#define JSON_INT 3
99#define JSON_REAL 4
100#define JSON_STRING 5
101#define JSON_ARRAY 6
102#define JSON_OBJECT 7
103
drhf5ddb9c2015-09-11 00:06:41 +0000104/* The "subtype" set for JSON values */
105#define JSON_SUBTYPE 74 /* Ascii for "J" */
106
drh987eb1f2015-08-17 15:17:37 +0000107/*
108** Names of the various JSON types:
109*/
110static const char * const jsonType[] = {
111 "null", "true", "false", "integer", "real", "text", "array", "object"
112};
113
drh301eecc2015-08-17 20:14:19 +0000114/* Bit values for the JsonNode.jnFlag field
115*/
116#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
117#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
118#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +0000119#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +0000120#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drhf5ddb9c2015-09-11 00:06:41 +0000121#define JNODE_LABEL 0x20 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000122
drh987eb1f2015-08-17 15:17:37 +0000123
drhe9c37f32015-08-15 21:25:36 +0000124/* A single node of parsed JSON
125*/
drhe9c37f32015-08-15 21:25:36 +0000126struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000127 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000128 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +0000129 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +0000130 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000131 union {
drh0042a972015-08-18 12:59:58 +0000132 const char *zJContent; /* Content for INT, REAL, and STRING */
133 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000134 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +0000135 } u;
drhe9c37f32015-08-15 21:25:36 +0000136};
137
138/* A completely parsed JSON string
139*/
drhe9c37f32015-08-15 21:25:36 +0000140struct JsonParse {
141 u32 nNode; /* Number of slots of aNode[] used */
142 u32 nAlloc; /* Number of slots of aNode[] allocated */
143 JsonNode *aNode; /* Array of nodes containing the parse */
144 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000145 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000146 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000147 u8 nErr; /* Number of errors seen */
drhe9c37f32015-08-15 21:25:36 +0000148};
149
drh505ad2c2015-08-21 17:33:11 +0000150/**************************************************************************
151** Utility routines for dealing with JsonString objects
152**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000153
drh505ad2c2015-08-21 17:33:11 +0000154/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000155*/
drh505ad2c2015-08-21 17:33:11 +0000156static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000157 p->zBuf = p->zSpace;
158 p->nAlloc = sizeof(p->zSpace);
159 p->nUsed = 0;
160 p->bStatic = 1;
161}
162
drh505ad2c2015-08-21 17:33:11 +0000163/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000164*/
drh505ad2c2015-08-21 17:33:11 +0000165static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000166 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000167 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000168 jsonZero(p);
169}
170
171
drh505ad2c2015-08-21 17:33:11 +0000172/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000173** initial state.
174*/
drh505ad2c2015-08-21 17:33:11 +0000175static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000176 if( !p->bStatic ) sqlite3_free(p->zBuf);
177 jsonZero(p);
178}
179
180
181/* Report an out-of-memory (OOM) condition
182*/
drh505ad2c2015-08-21 17:33:11 +0000183static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000184 p->bErr = 1;
185 sqlite3_result_error_nomem(p->pCtx);
186 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000187}
188
189/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
190** Return zero on success. Return non-zero on an OOM error
191*/
drh505ad2c2015-08-21 17:33:11 +0000192static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000193 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000194 char *zNew;
195 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000196 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000197 zNew = sqlite3_malloc64(nTotal);
198 if( zNew==0 ){
199 jsonOom(p);
200 return SQLITE_NOMEM;
201 }
drh6fd5c1e2015-08-21 20:37:12 +0000202 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000203 p->zBuf = zNew;
204 p->bStatic = 0;
205 }else{
206 zNew = sqlite3_realloc64(p->zBuf, nTotal);
207 if( zNew==0 ){
208 jsonOom(p);
209 return SQLITE_NOMEM;
210 }
211 p->zBuf = zNew;
212 }
213 p->nAlloc = nTotal;
214 return SQLITE_OK;
215}
216
drh505ad2c2015-08-21 17:33:11 +0000217/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000218*/
drh505ad2c2015-08-21 17:33:11 +0000219static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000220 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
221 memcpy(p->zBuf+p->nUsed, zIn, N);
222 p->nUsed += N;
223}
224
drh4af352d2015-08-21 20:02:48 +0000225/* Append formatted text (not to exceed N bytes) to the JsonString.
226*/
227static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
228 va_list ap;
229 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
230 va_start(ap, zFormat);
231 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
232 va_end(ap);
233 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
234}
235
drh5634cc02015-08-17 11:28:03 +0000236/* Append a single character
237*/
drh505ad2c2015-08-21 17:33:11 +0000238static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000239 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
240 p->zBuf[p->nUsed++] = c;
241}
242
drh301eecc2015-08-17 20:14:19 +0000243/* Append a comma separator to the output buffer, if the previous
244** character is not '[' or '{'.
245*/
drh505ad2c2015-08-21 17:33:11 +0000246static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000247 char c;
248 if( p->nUsed==0 ) return;
249 c = p->zBuf[p->nUsed-1];
250 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
251}
252
drh505ad2c2015-08-21 17:33:11 +0000253/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000254** under construction. Enclose the string in "..." and escape
255** any double-quotes or backslash characters contained within the
256** string.
257*/
drh505ad2c2015-08-21 17:33:11 +0000258static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000259 u32 i;
260 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
261 p->zBuf[p->nUsed++] = '"';
262 for(i=0; i<N; i++){
263 char c = zIn[i];
264 if( c=='"' || c=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000265 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000266 p->zBuf[p->nUsed++] = '\\';
267 }
268 p->zBuf[p->nUsed++] = c;
269 }
270 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000271 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000272}
273
drhd0960592015-08-17 21:22:32 +0000274/*
275** Append a function parameter value to the JSON string under
276** construction.
277*/
278static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000279 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000280 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000281){
282 switch( sqlite3_value_type(pValue) ){
283 case SQLITE_NULL: {
284 jsonAppendRaw(p, "null", 4);
285 break;
286 }
287 case SQLITE_INTEGER:
288 case SQLITE_FLOAT: {
289 const char *z = (const char*)sqlite3_value_text(pValue);
290 u32 n = (u32)sqlite3_value_bytes(pValue);
291 jsonAppendRaw(p, z, n);
292 break;
293 }
294 case SQLITE_TEXT: {
295 const char *z = (const char*)sqlite3_value_text(pValue);
296 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000297 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000298 jsonAppendRaw(p, z, n);
299 }else{
300 jsonAppendString(p, z, n);
301 }
drhd0960592015-08-17 21:22:32 +0000302 break;
303 }
304 default: {
305 if( p->bErr==0 ){
306 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
307 p->bErr = 1;
308 jsonReset(p);
309 }
310 break;
311 }
312 }
313}
314
315
drhbd0621b2015-08-13 13:54:59 +0000316/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000317*/
drh505ad2c2015-08-21 17:33:11 +0000318static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000319 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000320 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
321 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
322 SQLITE_UTF8);
323 jsonZero(p);
324 }
325 assert( p->bStatic );
326}
327
drh505ad2c2015-08-21 17:33:11 +0000328/**************************************************************************
329** Utility routines for dealing with JsonNode and JsonParse objects
330**************************************************************************/
331
332/*
333** Return the number of consecutive JsonNode slots need to represent
334** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
335** OBJECT types, the number might be larger.
336**
337** Appended elements are not counted. The value returned is the number
338** by which the JsonNode counter should increment in order to go to the
339** next peer value.
340*/
341static u32 jsonNodeSize(JsonNode *pNode){
342 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
343}
344
345/*
346** Reclaim all memory allocated by a JsonParse object. But do not
347** delete the JsonParse object itself.
348*/
349static void jsonParseReset(JsonParse *pParse){
350 sqlite3_free(pParse->aNode);
351 pParse->aNode = 0;
352 pParse->nNode = 0;
353 pParse->nAlloc = 0;
354 sqlite3_free(pParse->aUp);
355 pParse->aUp = 0;
356}
357
drh5634cc02015-08-17 11:28:03 +0000358/*
359** Convert the JsonNode pNode into a pure JSON string and
360** append to pOut. Subsubstructure is also included. Return
361** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000362*/
drh52216ad2015-08-18 02:28:03 +0000363static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000364 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000365 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000366 sqlite3_value **aReplace /* Replacement values */
367){
drh5634cc02015-08-17 11:28:03 +0000368 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000369 default: {
370 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000371 jsonAppendRaw(pOut, "null", 4);
372 break;
373 }
374 case JSON_TRUE: {
375 jsonAppendRaw(pOut, "true", 4);
376 break;
377 }
378 case JSON_FALSE: {
379 jsonAppendRaw(pOut, "false", 5);
380 break;
381 }
382 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000383 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000384 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000385 break;
386 }
387 /* Fall through into the next case */
388 }
389 case JSON_REAL:
390 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000391 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000392 break;
393 }
394 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000395 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000396 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000397 for(;;){
398 while( j<=pNode->n ){
399 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
400 if( pNode[j].jnFlags & JNODE_REPLACE ){
401 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000402 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000403 }
404 }else{
drhd0960592015-08-17 21:22:32 +0000405 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000406 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000407 }
drh505ad2c2015-08-21 17:33:11 +0000408 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000409 }
drh52216ad2015-08-18 02:28:03 +0000410 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
411 pNode = &pNode[pNode->u.iAppend];
412 j = 1;
drh5634cc02015-08-17 11:28:03 +0000413 }
414 jsonAppendChar(pOut, ']');
415 break;
416 }
417 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000418 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000419 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000420 for(;;){
421 while( j<=pNode->n ){
422 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
423 jsonAppendSeparator(pOut);
424 jsonRenderNode(&pNode[j], pOut, aReplace);
425 jsonAppendChar(pOut, ':');
426 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000427 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000428 }else{
429 jsonRenderNode(&pNode[j+1], pOut, aReplace);
430 }
drhd0960592015-08-17 21:22:32 +0000431 }
drh505ad2c2015-08-21 17:33:11 +0000432 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000433 }
drh52216ad2015-08-18 02:28:03 +0000434 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
435 pNode = &pNode[pNode->u.iAppend];
436 j = 1;
drh5634cc02015-08-17 11:28:03 +0000437 }
438 jsonAppendChar(pOut, '}');
439 break;
440 }
drhbd0621b2015-08-13 13:54:59 +0000441 }
drh5634cc02015-08-17 11:28:03 +0000442}
443
444/*
drhf2df7e72015-08-28 20:07:40 +0000445** Return a JsonNode and all its descendents as a JSON string.
446*/
447static void jsonReturnJson(
448 JsonNode *pNode, /* Node to return */
449 sqlite3_context *pCtx, /* Return value for this function */
450 sqlite3_value **aReplace /* Array of replacement values */
451){
452 JsonString s;
453 jsonInit(&s, pCtx);
454 jsonRenderNode(pNode, &s, aReplace);
455 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000456 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000457}
458
459/*
drh5634cc02015-08-17 11:28:03 +0000460** Make the JsonNode the return value of the function.
461*/
drhd0960592015-08-17 21:22:32 +0000462static void jsonReturn(
463 JsonNode *pNode, /* Node to return */
464 sqlite3_context *pCtx, /* Return value for this function */
465 sqlite3_value **aReplace /* Array of replacement values */
466){
drh5634cc02015-08-17 11:28:03 +0000467 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000468 default: {
469 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000470 sqlite3_result_null(pCtx);
471 break;
472 }
473 case JSON_TRUE: {
474 sqlite3_result_int(pCtx, 1);
475 break;
476 }
477 case JSON_FALSE: {
478 sqlite3_result_int(pCtx, 0);
479 break;
480 }
drh987eb1f2015-08-17 15:17:37 +0000481 case JSON_REAL: {
drh52216ad2015-08-18 02:28:03 +0000482 double r = strtod(pNode->u.zJContent, 0);
drh987eb1f2015-08-17 15:17:37 +0000483 sqlite3_result_double(pCtx, r);
drh5634cc02015-08-17 11:28:03 +0000484 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++; }
490 while( z[0]>='0' && z[0]<='9' ){ i = i*10 + *(z++) - '0'; }
drh52216ad2015-08-18 02:28:03 +0000491 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000492 sqlite3_result_int64(pCtx, i);
493 break;
494 }
drh5634cc02015-08-17 11:28:03 +0000495 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000496#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
497 ** json_insert() and json_replace() and those routines do not
498 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000499 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000500 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
501 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000502 }else
503#endif
504 assert( (pNode->jnFlags & JNODE_RAW)==0 );
505 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000506 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000507 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000508 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000509 }else{
510 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000511 u32 i;
512 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000513 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000514 char *zOut;
515 u32 j;
516 zOut = sqlite3_malloc( n+1 );
517 if( zOut==0 ){
518 sqlite3_result_error_nomem(pCtx);
519 break;
520 }
521 for(i=1, j=0; i<n-1; i++){
522 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000523 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000524 zOut[j++] = c;
525 }else{
526 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000527 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000528 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000529 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000530 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000531 if( c>='0' && c<='9' ) v = v*16 + c - '0';
532 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
533 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
534 else break;
drh987eb1f2015-08-17 15:17:37 +0000535 }
drh80d87402015-08-24 12:42:41 +0000536 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000537 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000538 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000539 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000540 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000541 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000542 }else{
mistachkin16a93122015-09-11 18:05:01 +0000543 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000544 zOut[j++] = 0x80 | ((v>>6)&0x3f);
545 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000546 }
547 }else{
548 if( c=='b' ){
549 c = '\b';
550 }else if( c=='f' ){
551 c = '\f';
552 }else if( c=='n' ){
553 c = '\n';
554 }else if( c=='r' ){
555 c = '\r';
556 }else if( c=='t' ){
557 c = '\t';
558 }
559 zOut[j++] = c;
560 }
561 }
562 }
563 zOut[j] = 0;
564 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000565 }
566 break;
567 }
568 case JSON_ARRAY:
569 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000570 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000571 break;
572 }
573 }
drhbd0621b2015-08-13 13:54:59 +0000574}
575
drh95677942015-09-24 01:06:37 +0000576/* Forward reference */
577static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
578
579/*
580** A macro to hint to the compiler that a function should not be
581** inlined.
582*/
583#if defined(__GNUC__)
584# define JSON_NOINLINE __attribute__((noinline))
585#elif defined(_MSC_VER) && _MSC_VER>=1310
586# define JSON_NOINLINE __declspec(noinline)
587#else
588# define JSON_NOINLINE
589#endif
590
591
592static JSON_NOINLINE int jsonParseAddNodeExpand(
593 JsonParse *pParse, /* Append the node to this object */
594 u32 eType, /* Node type */
595 u32 n, /* Content size or sub-node count */
596 const char *zContent /* Content */
597){
598 u32 nNew;
599 JsonNode *pNew;
600 assert( pParse->nNode>=pParse->nAlloc );
601 if( pParse->oom ) return -1;
602 nNew = pParse->nAlloc*2 + 10;
603 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
604 if( pNew==0 ){
605 pParse->oom = 1;
606 return -1;
607 }
608 pParse->nAlloc = nNew;
609 pParse->aNode = pNew;
610 assert( pParse->nNode<pParse->nAlloc );
611 return jsonParseAddNode(pParse, eType, n, zContent);
612}
613
drh5fa5c102015-08-12 16:49:40 +0000614/*
drhe9c37f32015-08-15 21:25:36 +0000615** Create a new JsonNode instance based on the arguments and append that
616** instance to the JsonParse. Return the index in pParse->aNode[] of the
617** new node, or -1 if a memory allocation fails.
618*/
619static int jsonParseAddNode(
620 JsonParse *pParse, /* Append the node to this object */
621 u32 eType, /* Node type */
622 u32 n, /* Content size or sub-node count */
623 const char *zContent /* Content */
624){
625 JsonNode *p;
626 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000627 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000628 }
629 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000630 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000631 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000632 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000633 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000634 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000635 return pParse->nNode++;
636}
637
638/*
639** Parse a single JSON value which begins at pParse->zJson[i]. Return the
640** index of the first character past the end of the value parsed.
641**
642** Return negative for a syntax error. Special cases: return -2 if the
643** first non-whitespace character is '}' and return -3 if the first
644** non-whitespace character is ']'.
645*/
646static int jsonParseValue(JsonParse *pParse, u32 i){
647 char c;
648 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000649 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000650 int x;
drh852944e2015-09-10 03:29:11 +0000651 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000652 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drh8cb15cc2015-09-24 01:40:45 +0000653 if( (c = pParse->zJson[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000654 /* Parse object */
655 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000656 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000657 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000658 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000659 x = jsonParseValue(pParse, j);
660 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000661 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000662 return -1;
663 }
drhbe9474e2015-08-22 03:05:54 +0000664 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000665 pNode = &pParse->aNode[pParse->nNode-1];
666 if( pNode->eType!=JSON_STRING ) return -1;
667 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000668 j = x;
dan2e8f5512015-09-17 17:21:09 +0000669 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000670 if( pParse->zJson[j]!=':' ) return -1;
671 j++;
672 x = jsonParseValue(pParse, j);
673 if( x<0 ) return -1;
674 j = x;
dan2e8f5512015-09-17 17:21:09 +0000675 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000676 c = pParse->zJson[j];
677 if( c==',' ) continue;
678 if( c!='}' ) return -1;
679 break;
680 }
drhbc8f0922015-08-22 19:39:04 +0000681 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000682 return j+1;
683 }else if( c=='[' ){
684 /* Parse array */
685 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000686 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000687 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000688 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000689 x = jsonParseValue(pParse, j);
690 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000691 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000692 return -1;
693 }
694 j = x;
dan2e8f5512015-09-17 17:21:09 +0000695 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000696 c = pParse->zJson[j];
697 if( c==',' ) continue;
698 if( c!=']' ) return -1;
699 break;
700 }
drhbc8f0922015-08-22 19:39:04 +0000701 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000702 return j+1;
703 }else if( c=='"' ){
704 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000705 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000706 j = i+1;
707 for(;;){
708 c = pParse->zJson[j];
709 if( c==0 ) return -1;
710 if( c=='\\' ){
711 c = pParse->zJson[++j];
712 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000713 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000714 }else if( c=='"' ){
715 break;
716 }
717 j++;
718 }
719 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000720 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000721 return j+1;
722 }else if( c=='n'
723 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000724 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000725 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
726 return i+4;
727 }else if( c=='t'
728 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000729 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000730 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
731 return i+4;
732 }else if( c=='f'
733 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000734 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000735 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
736 return i+5;
737 }else if( c=='-' || (c>='0' && c<='9') ){
738 /* Parse number */
739 u8 seenDP = 0;
740 u8 seenE = 0;
741 j = i+1;
742 for(;; j++){
743 c = pParse->zJson[j];
744 if( c>='0' && c<='9' ) continue;
745 if( c=='.' ){
746 if( pParse->zJson[j-1]=='-' ) return -1;
747 if( seenDP ) return -1;
748 seenDP = 1;
749 continue;
750 }
751 if( c=='e' || c=='E' ){
752 if( pParse->zJson[j-1]<'0' ) return -1;
753 if( seenE ) return -1;
754 seenDP = seenE = 1;
755 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000756 if( c=='+' || c=='-' ){
757 j++;
758 c = pParse->zJson[j+1];
759 }
drhd1f00682015-08-29 16:02:37 +0000760 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000761 continue;
762 }
763 break;
764 }
765 if( pParse->zJson[j-1]<'0' ) return -1;
766 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
767 j - i, &pParse->zJson[i]);
768 return j;
769 }else if( c=='}' ){
770 return -2; /* End of {...} */
771 }else if( c==']' ){
772 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000773 }else if( c==0 ){
774 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000775 }else{
776 return -1; /* Syntax error */
777 }
778}
779
780/*
781** Parse a complete JSON string. Return 0 on success or non-zero if there
782** are any errors. If an error occurs, free all memory associated with
783** pParse.
784**
785** pParse is uninitialized when this routine is called.
786*/
drhbc8f0922015-08-22 19:39:04 +0000787static int jsonParse(
788 JsonParse *pParse, /* Initialize and fill this JsonParse object */
789 sqlite3_context *pCtx, /* Report errors here */
790 const char *zJson /* Input JSON text to be parsed */
791){
drhe9c37f32015-08-15 21:25:36 +0000792 int i;
drhe9c37f32015-08-15 21:25:36 +0000793 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000794 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000795 pParse->zJson = zJson;
796 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000797 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000798 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000799 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000800 if( zJson[i] ) i = -1;
801 }
drhd1f00682015-08-29 16:02:37 +0000802 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000803 if( pCtx!=0 ){
804 if( pParse->oom ){
805 sqlite3_result_error_nomem(pCtx);
806 }else{
807 sqlite3_result_error(pCtx, "malformed JSON", -1);
808 }
809 }
drh505ad2c2015-08-21 17:33:11 +0000810 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000811 return 1;
812 }
813 return 0;
814}
drh301eecc2015-08-17 20:14:19 +0000815
drh505ad2c2015-08-21 17:33:11 +0000816/* Mark node i of pParse as being a child of iParent. Call recursively
817** to fill in all the descendants of node i.
818*/
819static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
820 JsonNode *pNode = &pParse->aNode[i];
821 u32 j;
822 pParse->aUp[i] = iParent;
823 switch( pNode->eType ){
824 case JSON_ARRAY: {
825 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
826 jsonParseFillInParentage(pParse, i+j, i);
827 }
828 break;
829 }
830 case JSON_OBJECT: {
831 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
832 pParse->aUp[i+j] = i;
833 jsonParseFillInParentage(pParse, i+j+1, i);
834 }
835 break;
836 }
837 default: {
838 break;
839 }
840 }
841}
842
843/*
844** Compute the parentage of all nodes in a completed parse.
845*/
846static int jsonParseFindParents(JsonParse *pParse){
847 u32 *aUp;
848 assert( pParse->aUp==0 );
849 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000850 if( aUp==0 ){
851 pParse->oom = 1;
852 return SQLITE_NOMEM;
853 }
drh505ad2c2015-08-21 17:33:11 +0000854 jsonParseFillInParentage(pParse, 0, 0);
855 return SQLITE_OK;
856}
857
drh8cb0c832015-09-22 00:21:03 +0000858/*
859** Compare the OBJECT label at pNode against zKey,nKey. Return true on
860** a match.
861*/
862static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
863 if( pNode->jnFlags & JNODE_RAW ){
864 if( pNode->n!=nKey ) return 0;
865 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
866 }else{
867 if( pNode->n!=nKey+2 ) return 0;
868 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
869 }
870}
871
drh52216ad2015-08-18 02:28:03 +0000872/* forward declaration */
drha7714022015-08-29 00:54:49 +0000873static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000874
drh987eb1f2015-08-17 15:17:37 +0000875/*
876** Search along zPath to find the node specified. Return a pointer
877** to that node, or NULL if zPath is malformed or if there is no such
878** node.
drh52216ad2015-08-18 02:28:03 +0000879**
880** If pApnd!=0, then try to append new nodes to complete zPath if it is
881** possible to do so and if no existing node corresponds to zPath. If
882** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000883*/
drha7714022015-08-29 00:54:49 +0000884static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000885 JsonParse *pParse, /* The JSON to search */
886 u32 iRoot, /* Begin the search at this node */
887 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000888 int *pApnd, /* Append nodes to complete path if not NULL */
889 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000890){
drhbc8f0922015-08-22 19:39:04 +0000891 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000892 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000893 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000894 if( zPath[0]==0 ) return pRoot;
895 if( zPath[0]=='.' ){
896 if( pRoot->eType!=JSON_OBJECT ) return 0;
897 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000898 if( zPath[0]=='"' ){
899 zKey = zPath + 1;
900 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
901 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000902 if( zPath[i] ){
903 i++;
904 }else{
905 *pzErr = zPath;
906 return 0;
907 }
drh6b43cc82015-08-19 23:02:49 +0000908 }else{
909 zKey = zPath;
910 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
911 nKey = i;
912 }
drha7714022015-08-29 00:54:49 +0000913 if( nKey==0 ){
914 *pzErr = zPath;
915 return 0;
916 }
drh987eb1f2015-08-17 15:17:37 +0000917 j = 1;
drh52216ad2015-08-18 02:28:03 +0000918 for(;;){
919 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000920 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000921 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000922 }
923 j++;
drh505ad2c2015-08-21 17:33:11 +0000924 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000925 }
drh52216ad2015-08-18 02:28:03 +0000926 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
927 iRoot += pRoot->u.iAppend;
928 pRoot = &pParse->aNode[iRoot];
929 j = 1;
930 }
931 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000932 u32 iStart, iLabel;
933 JsonNode *pNode;
934 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
935 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000936 zPath += i;
drha7714022015-08-29 00:54:49 +0000937 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000938 if( pParse->oom ) return 0;
939 if( pNode ){
940 pRoot = &pParse->aNode[iRoot];
941 pRoot->u.iAppend = iStart - iRoot;
942 pRoot->jnFlags |= JNODE_APPEND;
943 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
944 }
945 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000946 }
dan2e8f5512015-09-17 17:21:09 +0000947 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000948 if( pRoot->eType!=JSON_ARRAY ) return 0;
949 i = 0;
drh3d1d2a92015-09-22 01:15:49 +0000950 j = 1;
951 while( safe_isdigit(zPath[j]) ){
952 i = i*10 + zPath[j] - '0';
953 j++;
drh987eb1f2015-08-17 15:17:37 +0000954 }
drh3d1d2a92015-09-22 01:15:49 +0000955 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +0000956 *pzErr = zPath;
957 return 0;
958 }
drh3d1d2a92015-09-22 01:15:49 +0000959 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +0000960 j = 1;
drh52216ad2015-08-18 02:28:03 +0000961 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000962 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
963 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000964 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000965 }
966 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
967 iRoot += pRoot->u.iAppend;
968 pRoot = &pParse->aNode[iRoot];
969 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000970 }
971 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000972 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000973 }
974 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000975 u32 iStart;
976 JsonNode *pNode;
977 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +0000978 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000979 if( pParse->oom ) return 0;
980 if( pNode ){
981 pRoot = &pParse->aNode[iRoot];
982 pRoot->u.iAppend = iStart - iRoot;
983 pRoot->jnFlags |= JNODE_APPEND;
984 }
985 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000986 }
drh3d1d2a92015-09-22 01:15:49 +0000987 }else{
drha7714022015-08-29 00:54:49 +0000988 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +0000989 }
990 return 0;
991}
992
drh52216ad2015-08-18 02:28:03 +0000993/*
drhbc8f0922015-08-22 19:39:04 +0000994** Append content to pParse that will complete zPath. Return a pointer
995** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000996*/
997static JsonNode *jsonLookupAppend(
998 JsonParse *pParse, /* Append content to the JSON parse */
999 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001000 int *pApnd, /* Set this flag to 1 */
1001 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001002){
1003 *pApnd = 1;
1004 if( zPath[0]==0 ){
1005 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1006 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1007 }
1008 if( zPath[0]=='.' ){
1009 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1010 }else if( strncmp(zPath,"[0]",3)==0 ){
1011 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1012 }else{
1013 return 0;
1014 }
1015 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001016 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001017}
1018
drhbc8f0922015-08-22 19:39:04 +00001019/*
drha7714022015-08-29 00:54:49 +00001020** Return the text of a syntax error message on a JSON path. Space is
1021** obtained from sqlite3_malloc().
1022*/
1023static char *jsonPathSyntaxError(const char *zErr){
1024 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1025}
1026
1027/*
1028** Do a node lookup using zPath. Return a pointer to the node on success.
1029** Return NULL if not found or if there is an error.
1030**
1031** On an error, write an error message into pCtx and increment the
1032** pParse->nErr counter.
1033**
1034** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1035** nodes are appended.
drha7714022015-08-29 00:54:49 +00001036*/
1037static JsonNode *jsonLookup(
1038 JsonParse *pParse, /* The JSON to search */
1039 const char *zPath, /* The path to search */
1040 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001041 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001042){
1043 const char *zErr = 0;
1044 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001045 char *zMsg;
drha7714022015-08-29 00:54:49 +00001046
1047 if( zPath==0 ) return 0;
1048 if( zPath[0]!='$' ){
1049 zErr = zPath;
1050 goto lookup_err;
1051 }
1052 zPath++;
drha7714022015-08-29 00:54:49 +00001053 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001054 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001055
1056lookup_err:
1057 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001058 assert( zErr!=0 && pCtx!=0 );
1059 zMsg = jsonPathSyntaxError(zErr);
1060 if( zMsg ){
1061 sqlite3_result_error(pCtx, zMsg, -1);
1062 sqlite3_free(zMsg);
1063 }else{
1064 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001065 }
drha7714022015-08-29 00:54:49 +00001066 return 0;
1067}
1068
1069
1070/*
drhbc8f0922015-08-22 19:39:04 +00001071** Report the wrong number of arguments for json_insert(), json_replace()
1072** or json_set().
1073*/
1074static void jsonWrongNumArgs(
1075 sqlite3_context *pCtx,
1076 const char *zFuncName
1077){
1078 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1079 zFuncName);
1080 sqlite3_result_error(pCtx, zMsg, -1);
1081 sqlite3_free(zMsg);
1082}
drh52216ad2015-08-18 02:28:03 +00001083
drha7714022015-08-29 00:54:49 +00001084
drh987eb1f2015-08-17 15:17:37 +00001085/****************************************************************************
1086** SQL functions used for testing and debugging
1087****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001088
drh301eecc2015-08-17 20:14:19 +00001089#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001090/*
drh5634cc02015-08-17 11:28:03 +00001091** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001092** a parse of the JSON provided. Or it returns NULL if JSON is not
1093** well-formed.
1094*/
drh5634cc02015-08-17 11:28:03 +00001095static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001096 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001097 int argc,
1098 sqlite3_value **argv
1099){
drh505ad2c2015-08-21 17:33:11 +00001100 JsonString s; /* Output string - not real JSON */
1101 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001102 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001103
1104 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001105 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001106 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001107 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001108 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001109 const char *zType;
1110 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1111 assert( x.aNode[i].eType==JSON_STRING );
1112 zType = "label";
1113 }else{
1114 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001115 }
drh852944e2015-09-10 03:29:11 +00001116 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1117 i, zType, x.aNode[i].n, x.aUp[i]);
1118 if( x.aNode[i].u.zJContent!=0 ){
1119 jsonAppendRaw(&s, " ", 1);
1120 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1121 }
1122 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001123 }
drh505ad2c2015-08-21 17:33:11 +00001124 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001125 jsonResult(&s);
1126}
1127
drh5634cc02015-08-17 11:28:03 +00001128/*
drhf5ddb9c2015-09-11 00:06:41 +00001129** The json_test1(JSON) function return true (1) if the input is JSON
1130** text generated by another json function. It returns (0) if the input
1131** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001132*/
1133static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001134 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001135 int argc,
1136 sqlite3_value **argv
1137){
mistachkin16a93122015-09-11 18:05:01 +00001138 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001139 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001140}
drh301eecc2015-08-17 20:14:19 +00001141#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001142
drh987eb1f2015-08-17 15:17:37 +00001143/****************************************************************************
1144** SQL function implementations
1145****************************************************************************/
1146
1147/*
1148** Implementation of the json_array(VALUE,...) function. Return a JSON
1149** array that contains all values given in arguments. Or if any argument
1150** is a BLOB, throw an error.
1151*/
1152static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001153 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001154 int argc,
1155 sqlite3_value **argv
1156){
1157 int i;
drh505ad2c2015-08-21 17:33:11 +00001158 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001159
drhbc8f0922015-08-22 19:39:04 +00001160 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001161 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001162 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001163 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001164 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001165 }
drhd0960592015-08-17 21:22:32 +00001166 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001167 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001168 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001169}
1170
1171
1172/*
1173** json_array_length(JSON)
1174** json_array_length(JSON, PATH)
1175**
1176** Return the number of elements in the top-level JSON array.
1177** Return 0 if the input is not a well-formed JSON array.
1178*/
1179static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001180 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001181 int argc,
1182 sqlite3_value **argv
1183){
1184 JsonParse x; /* The parse */
1185 sqlite3_int64 n = 0;
1186 u32 i;
drha8f39a92015-09-21 22:53:16 +00001187 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001188
drhf2df7e72015-08-28 20:07:40 +00001189 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001190 assert( x.nNode );
1191 if( argc==2 ){
1192 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1193 pNode = jsonLookup(&x, zPath, 0, ctx);
1194 }else{
1195 pNode = x.aNode;
1196 }
1197 if( pNode==0 ){
1198 x.nErr = 1;
1199 }else if( pNode->eType==JSON_ARRAY ){
1200 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1201 for(i=1; i<=pNode->n; n++){
1202 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001203 }
drh987eb1f2015-08-17 15:17:37 +00001204 }
drha7714022015-08-29 00:54:49 +00001205 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001206 jsonParseReset(&x);
1207}
1208
1209/*
drh3ad93bb2015-08-29 19:41:45 +00001210** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001211**
drh3ad93bb2015-08-29 19:41:45 +00001212** Return the element described by PATH. Return NULL if there is no
1213** PATH element. If there are multiple PATHs, then return a JSON array
1214** with the result from each path. Throw an error if the JSON or any PATH
1215** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001216*/
1217static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001218 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001219 int argc,
1220 sqlite3_value **argv
1221){
1222 JsonParse x; /* The parse */
1223 JsonNode *pNode;
1224 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001225 JsonString jx;
1226 int i;
1227
1228 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001229 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001230 jsonInit(&jx, ctx);
1231 jsonAppendChar(&jx, '[');
1232 for(i=1; i<argc; i++){
1233 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001234 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001235 if( x.nErr ) break;
1236 if( argc>2 ){
1237 jsonAppendSeparator(&jx);
1238 if( pNode ){
1239 jsonRenderNode(pNode, &jx, 0);
1240 }else{
1241 jsonAppendRaw(&jx, "null", 4);
1242 }
1243 }else if( pNode ){
1244 jsonReturn(pNode, ctx, 0);
1245 }
drh987eb1f2015-08-17 15:17:37 +00001246 }
drh3ad93bb2015-08-29 19:41:45 +00001247 if( argc>2 && i==argc ){
1248 jsonAppendChar(&jx, ']');
1249 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001250 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001251 }
1252 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001253 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001254}
1255
1256/*
1257** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1258** object that contains all name/value given in arguments. Or if any name
1259** is not a string or if any value is a BLOB, throw an error.
1260*/
1261static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001262 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001263 int argc,
1264 sqlite3_value **argv
1265){
1266 int i;
drh505ad2c2015-08-21 17:33:11 +00001267 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001268 const char *z;
1269 u32 n;
1270
1271 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001272 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001273 "of arguments", -1);
1274 return;
1275 }
drhbc8f0922015-08-22 19:39:04 +00001276 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001277 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001278 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001279 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001280 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001281 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001282 return;
1283 }
drhd0960592015-08-17 21:22:32 +00001284 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001285 z = (const char*)sqlite3_value_text(argv[i]);
1286 n = (u32)sqlite3_value_bytes(argv[i]);
1287 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001288 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001289 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001290 }
drhd0960592015-08-17 21:22:32 +00001291 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001292 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001293 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001294}
1295
1296
1297/*
drh301eecc2015-08-17 20:14:19 +00001298** json_remove(JSON, PATH, ...)
1299**
drh3ad93bb2015-08-29 19:41:45 +00001300** Remove the named elements from JSON and return the result. malformed
1301** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001302*/
1303static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001304 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001305 int argc,
1306 sqlite3_value **argv
1307){
1308 JsonParse x; /* The parse */
1309 JsonNode *pNode;
1310 const char *zPath;
1311 u32 i;
1312
1313 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001314 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001315 assert( x.nNode );
1316 for(i=1; i<(u32)argc; i++){
1317 zPath = (const char*)sqlite3_value_text(argv[i]);
1318 if( zPath==0 ) goto remove_done;
1319 pNode = jsonLookup(&x, zPath, 0, ctx);
1320 if( x.nErr ) goto remove_done;
1321 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1322 }
1323 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1324 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001325 }
drha7714022015-08-29 00:54:49 +00001326remove_done:
drh505ad2c2015-08-21 17:33:11 +00001327 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001328}
1329
1330/*
1331** json_replace(JSON, PATH, VALUE, ...)
1332**
1333** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001334** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001335*/
1336static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001337 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001338 int argc,
1339 sqlite3_value **argv
1340){
1341 JsonParse x; /* The parse */
1342 JsonNode *pNode;
1343 const char *zPath;
1344 u32 i;
1345
1346 if( argc<1 ) return;
1347 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001348 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001349 return;
1350 }
drhbc8f0922015-08-22 19:39:04 +00001351 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001352 assert( x.nNode );
1353 for(i=1; i<(u32)argc; i+=2){
1354 zPath = (const char*)sqlite3_value_text(argv[i]);
1355 pNode = jsonLookup(&x, zPath, 0, ctx);
1356 if( x.nErr ) goto replace_err;
1357 if( pNode ){
1358 pNode->jnFlags |= (u8)JNODE_REPLACE;
1359 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001360 }
drha8f39a92015-09-21 22:53:16 +00001361 }
1362 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1363 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1364 }else{
1365 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001366 }
drha7714022015-08-29 00:54:49 +00001367replace_err:
drh505ad2c2015-08-21 17:33:11 +00001368 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001369}
drh505ad2c2015-08-21 17:33:11 +00001370
drh52216ad2015-08-18 02:28:03 +00001371/*
1372** json_set(JSON, PATH, VALUE, ...)
1373**
1374** Set the value at PATH to VALUE. Create the PATH if it does not already
1375** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001376** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001377**
1378** json_insert(JSON, PATH, VALUE, ...)
1379**
1380** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001381** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001382*/
1383static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001384 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001385 int argc,
1386 sqlite3_value **argv
1387){
1388 JsonParse x; /* The parse */
1389 JsonNode *pNode;
1390 const char *zPath;
1391 u32 i;
1392 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001393 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001394
1395 if( argc<1 ) return;
1396 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001397 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001398 return;
1399 }
drhbc8f0922015-08-22 19:39:04 +00001400 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001401 assert( x.nNode );
1402 for(i=1; i<(u32)argc; i+=2){
1403 zPath = (const char*)sqlite3_value_text(argv[i]);
1404 bApnd = 0;
1405 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1406 if( x.oom ){
1407 sqlite3_result_error_nomem(ctx);
1408 goto jsonSetDone;
1409 }else if( x.nErr ){
1410 goto jsonSetDone;
1411 }else if( pNode && (bApnd || bIsSet) ){
1412 pNode->jnFlags |= (u8)JNODE_REPLACE;
1413 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001414 }
drha8f39a92015-09-21 22:53:16 +00001415 }
1416 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1417 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1418 }else{
1419 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001420 }
drhbc8f0922015-08-22 19:39:04 +00001421jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001422 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001423}
drh301eecc2015-08-17 20:14:19 +00001424
1425/*
drh987eb1f2015-08-17 15:17:37 +00001426** json_type(JSON)
1427** json_type(JSON, PATH)
1428**
drh3ad93bb2015-08-29 19:41:45 +00001429** Return the top-level "type" of a JSON string. Throw an error if
1430** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001431*/
1432static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001433 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001434 int argc,
1435 sqlite3_value **argv
1436){
1437 JsonParse x; /* The parse */
1438 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001439 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001440
drhbc8f0922015-08-22 19:39:04 +00001441 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001442 assert( x.nNode );
1443 if( argc==2 ){
1444 zPath = (const char*)sqlite3_value_text(argv[1]);
1445 pNode = jsonLookup(&x, zPath, 0, ctx);
1446 }else{
1447 pNode = x.aNode;
1448 }
1449 if( pNode ){
1450 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001451 }
drh505ad2c2015-08-21 17:33:11 +00001452 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001453}
drh5634cc02015-08-17 11:28:03 +00001454
drhbc8f0922015-08-22 19:39:04 +00001455/*
1456** json_valid(JSON)
1457**
drh3ad93bb2015-08-29 19:41:45 +00001458** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1459** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001460*/
1461static void jsonValidFunc(
1462 sqlite3_context *ctx,
1463 int argc,
1464 sqlite3_value **argv
1465){
1466 JsonParse x; /* The parse */
1467 int rc = 0;
1468
mistachkin16a93122015-09-11 18:05:01 +00001469 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001470 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001471 rc = 1;
1472 }
1473 jsonParseReset(&x);
1474 sqlite3_result_int(ctx, rc);
1475}
1476
drhd2975922015-08-29 17:22:33 +00001477#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001478/****************************************************************************
1479** The json_each virtual table
1480****************************************************************************/
1481typedef struct JsonEachCursor JsonEachCursor;
1482struct JsonEachCursor {
1483 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001484 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001485 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001486 u32 i; /* Index in sParse.aNode[] of current row */
1487 u32 iEnd; /* EOF when i equals or exceeds this value */
1488 u8 eType; /* Type of top-level element */
1489 u8 bRecursive; /* True for json_tree(). False for json_each() */
1490 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001491 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001492 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001493};
1494
1495/* Constructor for the json_each virtual table */
1496static int jsonEachConnect(
1497 sqlite3 *db,
1498 void *pAux,
1499 int argc, const char *const*argv,
1500 sqlite3_vtab **ppVtab,
1501 char **pzErr
1502){
1503 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001504 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001505
1506/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001507#define JEACH_KEY 0
1508#define JEACH_VALUE 1
1509#define JEACH_TYPE 2
1510#define JEACH_ATOM 3
1511#define JEACH_ID 4
1512#define JEACH_PARENT 5
1513#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001514#define JEACH_PATH 7
1515#define JEACH_JSON 8
1516#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001517
drh6fd5c1e2015-08-21 20:37:12 +00001518 UNUSED_PARAM(pzErr);
1519 UNUSED_PARAM(argv);
1520 UNUSED_PARAM(argc);
1521 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001522 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001523 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1524 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001525 if( rc==SQLITE_OK ){
1526 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1527 if( pNew==0 ) return SQLITE_NOMEM;
1528 memset(pNew, 0, sizeof(*pNew));
1529 }
1530 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001531}
1532
1533/* destructor for json_each virtual table */
1534static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1535 sqlite3_free(pVtab);
1536 return SQLITE_OK;
1537}
1538
drh505ad2c2015-08-21 17:33:11 +00001539/* constructor for a JsonEachCursor object for json_each(). */
1540static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001541 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001542
1543 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001544 pCur = sqlite3_malloc( sizeof(*pCur) );
1545 if( pCur==0 ) return SQLITE_NOMEM;
1546 memset(pCur, 0, sizeof(*pCur));
1547 *ppCursor = &pCur->base;
1548 return SQLITE_OK;
1549}
1550
drh505ad2c2015-08-21 17:33:11 +00001551/* constructor for a JsonEachCursor object for json_tree(). */
1552static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1553 int rc = jsonEachOpenEach(p, ppCursor);
1554 if( rc==SQLITE_OK ){
1555 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1556 pCur->bRecursive = 1;
1557 }
1558 return rc;
1559}
1560
drhcb6c6c62015-08-19 22:47:17 +00001561/* Reset a JsonEachCursor back to its original state. Free any memory
1562** held. */
1563static void jsonEachCursorReset(JsonEachCursor *p){
1564 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001565 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001566 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001567 p->iRowid = 0;
1568 p->i = 0;
1569 p->iEnd = 0;
1570 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001571 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001572 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001573}
1574
1575/* Destructor for a jsonEachCursor object */
1576static int jsonEachClose(sqlite3_vtab_cursor *cur){
1577 JsonEachCursor *p = (JsonEachCursor*)cur;
1578 jsonEachCursorReset(p);
1579 sqlite3_free(cur);
1580 return SQLITE_OK;
1581}
1582
1583/* Return TRUE if the jsonEachCursor object has been advanced off the end
1584** of the JSON object */
1585static int jsonEachEof(sqlite3_vtab_cursor *cur){
1586 JsonEachCursor *p = (JsonEachCursor*)cur;
1587 return p->i >= p->iEnd;
1588}
1589
drh505ad2c2015-08-21 17:33:11 +00001590/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001591static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001592 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001593 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001594 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1595 p->i++;
drh4af352d2015-08-21 20:02:48 +00001596 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001597 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001598 u32 iUp = p->sParse.aUp[p->i];
1599 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001600 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001601 if( pUp->eType==JSON_ARRAY ){
1602 if( iUp==p->i-1 ){
1603 pUp->u.iKey = 0;
1604 }else{
1605 pUp->u.iKey++;
1606 }
drh4af352d2015-08-21 20:02:48 +00001607 }
1608 }
drh505ad2c2015-08-21 17:33:11 +00001609 }else{
drh4af352d2015-08-21 20:02:48 +00001610 switch( p->eType ){
1611 case JSON_ARRAY: {
1612 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1613 p->iRowid++;
1614 break;
1615 }
1616 case JSON_OBJECT: {
1617 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1618 p->iRowid++;
1619 break;
1620 }
1621 default: {
1622 p->i = p->iEnd;
1623 break;
1624 }
drh505ad2c2015-08-21 17:33:11 +00001625 }
1626 }
1627 return SQLITE_OK;
1628}
1629
drh4af352d2015-08-21 20:02:48 +00001630/* Append the name of the path for element i to pStr
1631*/
1632static void jsonEachComputePath(
1633 JsonEachCursor *p, /* The cursor */
1634 JsonString *pStr, /* Write the path here */
1635 u32 i /* Path to this element */
1636){
1637 JsonNode *pNode, *pUp;
1638 u32 iUp;
1639 if( i==0 ){
1640 jsonAppendChar(pStr, '$');
1641 return;
drhcb6c6c62015-08-19 22:47:17 +00001642 }
drh4af352d2015-08-21 20:02:48 +00001643 iUp = p->sParse.aUp[i];
1644 jsonEachComputePath(p, pStr, iUp);
1645 pNode = &p->sParse.aNode[i];
1646 pUp = &p->sParse.aNode[iUp];
1647 if( pUp->eType==JSON_ARRAY ){
1648 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1649 }else{
1650 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001651 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001652 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001653 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001654 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1655 }
drhcb6c6c62015-08-19 22:47:17 +00001656}
1657
1658/* Return the value of a column */
1659static int jsonEachColumn(
1660 sqlite3_vtab_cursor *cur, /* The cursor */
1661 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1662 int i /* Which column to return */
1663){
1664 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001665 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001666 switch( i ){
1667 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001668 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001669 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001670 jsonReturn(pThis, ctx, 0);
1671 }else if( p->eType==JSON_ARRAY ){
1672 u32 iKey;
1673 if( p->bRecursive ){
1674 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001675 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001676 }else{
1677 iKey = p->iRowid;
1678 }
drh6fd5c1e2015-08-21 20:37:12 +00001679 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001680 }
1681 break;
1682 }
1683 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001684 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001685 jsonReturn(pThis, ctx, 0);
1686 break;
1687 }
1688 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001689 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001690 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1691 break;
1692 }
1693 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001694 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001695 if( pThis->eType>=JSON_ARRAY ) break;
1696 jsonReturn(pThis, ctx, 0);
1697 break;
1698 }
1699 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001700 sqlite3_result_int64(ctx,
1701 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001702 break;
1703 }
1704 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001705 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001706 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001707 }
1708 break;
1709 }
drh4af352d2015-08-21 20:02:48 +00001710 case JEACH_FULLKEY: {
1711 JsonString x;
1712 jsonInit(&x, ctx);
1713 if( p->bRecursive ){
1714 jsonEachComputePath(p, &x, p->i);
1715 }else{
drh383de692015-09-10 17:20:57 +00001716 if( p->zRoot ){
1717 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001718 }else{
1719 jsonAppendChar(&x, '$');
1720 }
1721 if( p->eType==JSON_ARRAY ){
1722 jsonPrintf(30, &x, "[%d]", p->iRowid);
1723 }else{
1724 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1725 }
1726 }
1727 jsonResult(&x);
1728 break;
1729 }
drhcb6c6c62015-08-19 22:47:17 +00001730 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001731 if( p->bRecursive ){
1732 JsonString x;
1733 jsonInit(&x, ctx);
1734 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1735 jsonResult(&x);
1736 break;
drh4af352d2015-08-21 20:02:48 +00001737 }
drh383de692015-09-10 17:20:57 +00001738 /* For json_each() path and root are the same so fall through
1739 ** into the root case */
1740 }
1741 case JEACH_ROOT: {
1742 const char *zRoot = p->zRoot;
1743 if( zRoot==0 ) zRoot = "$";
1744 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001745 break;
1746 }
drh3d1d2a92015-09-22 01:15:49 +00001747 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00001748 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001749 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1750 break;
1751 }
1752 }
1753 return SQLITE_OK;
1754}
1755
1756/* Return the current rowid value */
1757static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1758 JsonEachCursor *p = (JsonEachCursor*)cur;
1759 *pRowid = p->iRowid;
1760 return SQLITE_OK;
1761}
1762
1763/* The query strategy is to look for an equality constraint on the json
1764** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001765** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001766** and 0 otherwise.
1767*/
1768static int jsonEachBestIndex(
1769 sqlite3_vtab *tab,
1770 sqlite3_index_info *pIdxInfo
1771){
1772 int i;
1773 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001774 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001775 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001776
1777 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001778 pConstraint = pIdxInfo->aConstraint;
1779 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1780 if( pConstraint->usable==0 ) continue;
1781 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1782 switch( pConstraint->iColumn ){
1783 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001784 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001785 default: /* no-op */ break;
1786 }
1787 }
1788 if( jsonIdx<0 ){
1789 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001790 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001791 }else{
drh505ad2c2015-08-21 17:33:11 +00001792 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001793 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1794 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001795 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001796 pIdxInfo->idxNum = 1;
1797 }else{
drh383de692015-09-10 17:20:57 +00001798 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1799 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001800 pIdxInfo->idxNum = 3;
1801 }
1802 }
1803 return SQLITE_OK;
1804}
1805
1806/* Start a search on a new JSON string */
1807static int jsonEachFilter(
1808 sqlite3_vtab_cursor *cur,
1809 int idxNum, const char *idxStr,
1810 int argc, sqlite3_value **argv
1811){
1812 JsonEachCursor *p = (JsonEachCursor*)cur;
1813 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001814 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001815 sqlite3_int64 n;
1816
drh6fd5c1e2015-08-21 20:37:12 +00001817 UNUSED_PARAM(idxStr);
1818 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001819 jsonEachCursorReset(p);
1820 if( idxNum==0 ) return SQLITE_OK;
1821 z = (const char*)sqlite3_value_text(argv[0]);
1822 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001823 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001824 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001825 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001826 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001827 if( jsonParse(&p->sParse, 0, p->zJson) ){
1828 int rc = SQLITE_NOMEM;
1829 if( p->sParse.oom==0 ){
1830 sqlite3_free(cur->pVtab->zErrMsg);
1831 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1832 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1833 }
drhcb6c6c62015-08-19 22:47:17 +00001834 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001835 return rc;
1836 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1837 jsonEachCursorReset(p);
1838 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001839 }else{
drh95677942015-09-24 01:06:37 +00001840 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00001841 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001842 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001843 zRoot = (const char*)sqlite3_value_text(argv[1]);
1844 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001845 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001846 p->zRoot = sqlite3_malloc64( n+1 );
1847 if( p->zRoot==0 ) return SQLITE_NOMEM;
1848 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001849 if( zRoot[0]!='$' ){
1850 zErr = zRoot;
1851 }else{
1852 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1853 }
1854 if( zErr ){
drha7714022015-08-29 00:54:49 +00001855 sqlite3_free(cur->pVtab->zErrMsg);
1856 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001857 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001858 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1859 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001860 return SQLITE_OK;
1861 }
1862 }else{
1863 pNode = p->sParse.aNode;
1864 }
drh852944e2015-09-10 03:29:11 +00001865 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001866 p->eType = pNode->eType;
1867 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001868 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001869 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001870 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00001871 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00001872 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1873 p->i--;
1874 }
1875 }else{
1876 p->i++;
1877 }
drhcb6c6c62015-08-19 22:47:17 +00001878 }else{
1879 p->iEnd = p->i+1;
1880 }
1881 }
drha8f39a92015-09-21 22:53:16 +00001882 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001883}
1884
1885/* The methods of the json_each virtual table */
1886static sqlite3_module jsonEachModule = {
1887 0, /* iVersion */
1888 0, /* xCreate */
1889 jsonEachConnect, /* xConnect */
1890 jsonEachBestIndex, /* xBestIndex */
1891 jsonEachDisconnect, /* xDisconnect */
1892 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001893 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001894 jsonEachClose, /* xClose - close a cursor */
1895 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001896 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001897 jsonEachEof, /* xEof - check for end of scan */
1898 jsonEachColumn, /* xColumn - read data */
1899 jsonEachRowid, /* xRowid - read data */
1900 0, /* xUpdate */
1901 0, /* xBegin */
1902 0, /* xSync */
1903 0, /* xCommit */
1904 0, /* xRollback */
1905 0, /* xFindMethod */
1906 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001907 0, /* xSavepoint */
1908 0, /* xRelease */
1909 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001910};
1911
drh505ad2c2015-08-21 17:33:11 +00001912/* The methods of the json_tree virtual table. */
1913static sqlite3_module jsonTreeModule = {
1914 0, /* iVersion */
1915 0, /* xCreate */
1916 jsonEachConnect, /* xConnect */
1917 jsonEachBestIndex, /* xBestIndex */
1918 jsonEachDisconnect, /* xDisconnect */
1919 0, /* xDestroy */
1920 jsonEachOpenTree, /* xOpen - open a cursor */
1921 jsonEachClose, /* xClose - close a cursor */
1922 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001923 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001924 jsonEachEof, /* xEof - check for end of scan */
1925 jsonEachColumn, /* xColumn - read data */
1926 jsonEachRowid, /* xRowid - read data */
1927 0, /* xUpdate */
1928 0, /* xBegin */
1929 0, /* xSync */
1930 0, /* xCommit */
1931 0, /* xRollback */
1932 0, /* xFindMethod */
1933 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001934 0, /* xSavepoint */
1935 0, /* xRelease */
1936 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001937};
drhd2975922015-08-29 17:22:33 +00001938#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001939
1940/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00001941** The following routines are the only publically visible identifiers in this
1942** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00001943** functions and the virtual table implemented by this file.
1944****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001945
drh2f20e132015-09-26 17:44:59 +00001946int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00001947 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001948 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001949 static const struct {
1950 const char *zName;
1951 int nArg;
drh52216ad2015-08-18 02:28:03 +00001952 int flag;
drh5fa5c102015-08-12 16:49:40 +00001953 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1954 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001955 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001956 { "json_array", -1, 0, jsonArrayFunc },
1957 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1958 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001959 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001960 { "json_insert", -1, 0, jsonSetFunc },
1961 { "json_object", -1, 0, jsonObjectFunc },
1962 { "json_remove", -1, 0, jsonRemoveFunc },
1963 { "json_replace", -1, 0, jsonReplaceFunc },
1964 { "json_set", -1, 1, jsonSetFunc },
1965 { "json_type", 1, 0, jsonTypeFunc },
1966 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001967 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001968
drh301eecc2015-08-17 20:14:19 +00001969#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001970 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001971 { "json_parse", 1, 0, jsonParseFunc },
1972 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001973#endif
drh5fa5c102015-08-12 16:49:40 +00001974 };
drhd2975922015-08-29 17:22:33 +00001975#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001976 static const struct {
1977 const char *zName;
1978 sqlite3_module *pModule;
1979 } aMod[] = {
1980 { "json_each", &jsonEachModule },
1981 { "json_tree", &jsonTreeModule },
1982 };
drhd2975922015-08-29 17:22:33 +00001983#endif
drh5fa5c102015-08-12 16:49:40 +00001984 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1985 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001986 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1987 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001988 aFunc[i].xFunc, 0, 0);
1989 }
drhd2975922015-08-29 17:22:33 +00001990#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001991 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1992 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00001993 }
drhd2975922015-08-29 17:22:33 +00001994#endif
drh5fa5c102015-08-12 16:49:40 +00001995 return rc;
1996}
drh2f20e132015-09-26 17:44:59 +00001997
1998
1999#ifdef _WIN32
2000__declspec(dllexport)
2001#endif
2002int sqlite3_json_init(
2003 sqlite3 *db,
2004 char **pzErrMsg,
2005 const sqlite3_api_routines *pApi
2006){
2007 SQLITE_EXTENSION_INIT2(pApi);
2008 (void)pzErrMsg; /* Unused parameter */
2009 return sqlite3Json1Init(db);
2010}
drh50065652015-10-08 19:29:18 +00002011#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */