blob: cf766120cdb958e5bea1a1a3180c32ffd11a5eac [file] [log] [blame]
drh5fa5c102015-08-12 16:49:40 +00001/*
2** 2015-08-12
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This SQLite extension implements JSON functions. The interface is
14** modeled after MySQL JSON functions:
15**
16** https://dev.mysql.com/doc/refman/5.7/en/json.html
17**
drh5634cc02015-08-17 11:28:03 +000018** For the time being, all JSON is stored as pure text. (We might add
19** a JSONB type in the future which stores a binary encoding of JSON in
drhcb6c6c62015-08-19 22:47:17 +000020** a BLOB, but there is no support for JSONB in the current implementation.
21** This implementation parses JSON text at 250 MB/s, so it is hard to see
22** how JSONB might improve on that.)
drh5fa5c102015-08-12 16:49:40 +000023*/
drhf2df7e72015-08-28 20:07:40 +000024#if !defined(_SQLITEINT_H_)
drh5fa5c102015-08-12 16:49:40 +000025#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000026#endif
drh5fa5c102015-08-12 16:49:40 +000027SQLITE_EXTENSION_INIT1
28#include <assert.h>
29#include <string.h>
drhe9c37f32015-08-15 21:25:36 +000030#include <ctype.h>
drh987eb1f2015-08-17 15:17:37 +000031#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000032#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000033
drh6fd5c1e2015-08-21 20:37:12 +000034#define UNUSED_PARAM(X) (void)(X)
35
dan2e8f5512015-09-17 17:21:09 +000036/*
37** Versions of isspace(), isalnum() and isdigit() to which it is safe
38** to pass signed char values.
39*/
dan2e8f5512015-09-17 17:21:09 +000040#define safe_isdigit(x) isdigit((unsigned char)(x))
41#define safe_isalnum(x) isalnum((unsigned char)(x))
42
drh95677942015-09-24 01:06:37 +000043/*
44** Growing our own isspace() routine this way is twice as fast as
45** the library isspace() function, resulting in a 7% overall performance
46** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
47*/
48static const char jsonIsSpace[] = {
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0,
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
51 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52 0, 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};
66#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
67
drh5fa5c102015-08-12 16:49:40 +000068/* Unsigned integer types */
69typedef sqlite3_uint64 u64;
70typedef unsigned int u32;
71typedef unsigned char u8;
72
drh52216ad2015-08-18 02:28:03 +000073/* Objects */
drh505ad2c2015-08-21 17:33:11 +000074typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000075typedef struct JsonNode JsonNode;
76typedef struct JsonParse JsonParse;
77
drh5634cc02015-08-17 11:28:03 +000078/* An instance of this object represents a JSON string
79** under construction. Really, this is a generic string accumulator
80** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000081*/
drh505ad2c2015-08-21 17:33:11 +000082struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000083 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000084 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000085 u64 nAlloc; /* Bytes of storage available in zBuf[] */
86 u64 nUsed; /* Bytes of zBuf[] currently used */
87 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000088 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000089 char zSpace[100]; /* Initial static space */
90};
91
drhe9c37f32015-08-15 21:25:36 +000092/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000093*/
drhe9c37f32015-08-15 21:25:36 +000094#define JSON_NULL 0
95#define JSON_TRUE 1
96#define JSON_FALSE 2
97#define JSON_INT 3
98#define JSON_REAL 4
99#define JSON_STRING 5
100#define JSON_ARRAY 6
101#define JSON_OBJECT 7
102
drhf5ddb9c2015-09-11 00:06:41 +0000103/* The "subtype" set for JSON values */
104#define JSON_SUBTYPE 74 /* Ascii for "J" */
105
drh987eb1f2015-08-17 15:17:37 +0000106/*
107** Names of the various JSON types:
108*/
109static const char * const jsonType[] = {
110 "null", "true", "false", "integer", "real", "text", "array", "object"
111};
112
drh301eecc2015-08-17 20:14:19 +0000113/* Bit values for the JsonNode.jnFlag field
114*/
115#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
116#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
117#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +0000118#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +0000119#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drhf5ddb9c2015-09-11 00:06:41 +0000120#define JNODE_LABEL 0x20 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000121
drh987eb1f2015-08-17 15:17:37 +0000122
drhe9c37f32015-08-15 21:25:36 +0000123/* A single node of parsed JSON
124*/
drhe9c37f32015-08-15 21:25:36 +0000125struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000126 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000127 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +0000128 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +0000129 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000130 union {
drh0042a972015-08-18 12:59:58 +0000131 const char *zJContent; /* Content for INT, REAL, and STRING */
132 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000133 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +0000134 } u;
drhe9c37f32015-08-15 21:25:36 +0000135};
136
137/* A completely parsed JSON string
138*/
drhe9c37f32015-08-15 21:25:36 +0000139struct JsonParse {
140 u32 nNode; /* Number of slots of aNode[] used */
141 u32 nAlloc; /* Number of slots of aNode[] allocated */
142 JsonNode *aNode; /* Array of nodes containing the parse */
143 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000144 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000145 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000146 u8 nErr; /* Number of errors seen */
drhe9c37f32015-08-15 21:25:36 +0000147};
148
drh505ad2c2015-08-21 17:33:11 +0000149/**************************************************************************
150** Utility routines for dealing with JsonString objects
151**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000152
drh505ad2c2015-08-21 17:33:11 +0000153/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000154*/
drh505ad2c2015-08-21 17:33:11 +0000155static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000156 p->zBuf = p->zSpace;
157 p->nAlloc = sizeof(p->zSpace);
158 p->nUsed = 0;
159 p->bStatic = 1;
160}
161
drh505ad2c2015-08-21 17:33:11 +0000162/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000163*/
drh505ad2c2015-08-21 17:33:11 +0000164static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000165 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000166 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000167 jsonZero(p);
168}
169
170
drh505ad2c2015-08-21 17:33:11 +0000171/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000172** initial state.
173*/
drh505ad2c2015-08-21 17:33:11 +0000174static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000175 if( !p->bStatic ) sqlite3_free(p->zBuf);
176 jsonZero(p);
177}
178
179
180/* Report an out-of-memory (OOM) condition
181*/
drh505ad2c2015-08-21 17:33:11 +0000182static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000183 p->bErr = 1;
184 sqlite3_result_error_nomem(p->pCtx);
185 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000186}
187
188/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
189** Return zero on success. Return non-zero on an OOM error
190*/
drh505ad2c2015-08-21 17:33:11 +0000191static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000192 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000193 char *zNew;
194 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000195 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000196 zNew = sqlite3_malloc64(nTotal);
197 if( zNew==0 ){
198 jsonOom(p);
199 return SQLITE_NOMEM;
200 }
drh6fd5c1e2015-08-21 20:37:12 +0000201 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000202 p->zBuf = zNew;
203 p->bStatic = 0;
204 }else{
205 zNew = sqlite3_realloc64(p->zBuf, nTotal);
206 if( zNew==0 ){
207 jsonOom(p);
208 return SQLITE_NOMEM;
209 }
210 p->zBuf = zNew;
211 }
212 p->nAlloc = nTotal;
213 return SQLITE_OK;
214}
215
drh505ad2c2015-08-21 17:33:11 +0000216/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000217*/
drh505ad2c2015-08-21 17:33:11 +0000218static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000219 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
220 memcpy(p->zBuf+p->nUsed, zIn, N);
221 p->nUsed += N;
222}
223
drh4af352d2015-08-21 20:02:48 +0000224/* Append formatted text (not to exceed N bytes) to the JsonString.
225*/
226static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
227 va_list ap;
228 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
229 va_start(ap, zFormat);
230 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
231 va_end(ap);
232 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
233}
234
drh5634cc02015-08-17 11:28:03 +0000235/* Append a single character
236*/
drh505ad2c2015-08-21 17:33:11 +0000237static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000238 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
239 p->zBuf[p->nUsed++] = c;
240}
241
drh301eecc2015-08-17 20:14:19 +0000242/* Append a comma separator to the output buffer, if the previous
243** character is not '[' or '{'.
244*/
drh505ad2c2015-08-21 17:33:11 +0000245static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000246 char c;
247 if( p->nUsed==0 ) return;
248 c = p->zBuf[p->nUsed-1];
249 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
250}
251
drh505ad2c2015-08-21 17:33:11 +0000252/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000253** under construction. Enclose the string in "..." and escape
254** any double-quotes or backslash characters contained within the
255** string.
256*/
drh505ad2c2015-08-21 17:33:11 +0000257static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000258 u32 i;
259 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
260 p->zBuf[p->nUsed++] = '"';
261 for(i=0; i<N; i++){
262 char c = zIn[i];
263 if( c=='"' || c=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000264 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000265 p->zBuf[p->nUsed++] = '\\';
266 }
267 p->zBuf[p->nUsed++] = c;
268 }
269 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000270 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000271}
272
drhd0960592015-08-17 21:22:32 +0000273/*
274** Append a function parameter value to the JSON string under
275** construction.
276*/
277static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000278 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000279 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000280){
281 switch( sqlite3_value_type(pValue) ){
282 case SQLITE_NULL: {
283 jsonAppendRaw(p, "null", 4);
284 break;
285 }
286 case SQLITE_INTEGER:
287 case SQLITE_FLOAT: {
288 const char *z = (const char*)sqlite3_value_text(pValue);
289 u32 n = (u32)sqlite3_value_bytes(pValue);
290 jsonAppendRaw(p, z, n);
291 break;
292 }
293 case SQLITE_TEXT: {
294 const char *z = (const char*)sqlite3_value_text(pValue);
295 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000296 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000297 jsonAppendRaw(p, z, n);
298 }else{
299 jsonAppendString(p, z, n);
300 }
drhd0960592015-08-17 21:22:32 +0000301 break;
302 }
303 default: {
304 if( p->bErr==0 ){
305 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
306 p->bErr = 1;
307 jsonReset(p);
308 }
309 break;
310 }
311 }
312}
313
314
drhbd0621b2015-08-13 13:54:59 +0000315/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000316*/
drh505ad2c2015-08-21 17:33:11 +0000317static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000318 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000319 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
320 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
321 SQLITE_UTF8);
322 jsonZero(p);
323 }
324 assert( p->bStatic );
325}
326
drh505ad2c2015-08-21 17:33:11 +0000327/**************************************************************************
328** Utility routines for dealing with JsonNode and JsonParse objects
329**************************************************************************/
330
331/*
332** Return the number of consecutive JsonNode slots need to represent
333** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
334** OBJECT types, the number might be larger.
335**
336** Appended elements are not counted. The value returned is the number
337** by which the JsonNode counter should increment in order to go to the
338** next peer value.
339*/
340static u32 jsonNodeSize(JsonNode *pNode){
341 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
342}
343
344/*
345** Reclaim all memory allocated by a JsonParse object. But do not
346** delete the JsonParse object itself.
347*/
348static void jsonParseReset(JsonParse *pParse){
349 sqlite3_free(pParse->aNode);
350 pParse->aNode = 0;
351 pParse->nNode = 0;
352 pParse->nAlloc = 0;
353 sqlite3_free(pParse->aUp);
354 pParse->aUp = 0;
355}
356
drh5634cc02015-08-17 11:28:03 +0000357/*
358** Convert the JsonNode pNode into a pure JSON string and
359** append to pOut. Subsubstructure is also included. Return
360** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000361*/
drh52216ad2015-08-18 02:28:03 +0000362static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000363 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000364 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000365 sqlite3_value **aReplace /* Replacement values */
366){
drh5634cc02015-08-17 11:28:03 +0000367 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000368 default: {
369 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000370 jsonAppendRaw(pOut, "null", 4);
371 break;
372 }
373 case JSON_TRUE: {
374 jsonAppendRaw(pOut, "true", 4);
375 break;
376 }
377 case JSON_FALSE: {
378 jsonAppendRaw(pOut, "false", 5);
379 break;
380 }
381 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000382 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000383 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000384 break;
385 }
386 /* Fall through into the next case */
387 }
388 case JSON_REAL:
389 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000390 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000391 break;
392 }
393 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000394 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000395 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000396 for(;;){
397 while( j<=pNode->n ){
398 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
399 if( pNode[j].jnFlags & JNODE_REPLACE ){
400 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000401 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000402 }
403 }else{
drhd0960592015-08-17 21:22:32 +0000404 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000405 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000406 }
drh505ad2c2015-08-21 17:33:11 +0000407 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000408 }
drh52216ad2015-08-18 02:28:03 +0000409 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
410 pNode = &pNode[pNode->u.iAppend];
411 j = 1;
drh5634cc02015-08-17 11:28:03 +0000412 }
413 jsonAppendChar(pOut, ']');
414 break;
415 }
416 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000417 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000418 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000419 for(;;){
420 while( j<=pNode->n ){
421 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
422 jsonAppendSeparator(pOut);
423 jsonRenderNode(&pNode[j], pOut, aReplace);
424 jsonAppendChar(pOut, ':');
425 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000426 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000427 }else{
428 jsonRenderNode(&pNode[j+1], pOut, aReplace);
429 }
drhd0960592015-08-17 21:22:32 +0000430 }
drh505ad2c2015-08-21 17:33:11 +0000431 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000432 }
drh52216ad2015-08-18 02:28:03 +0000433 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
434 pNode = &pNode[pNode->u.iAppend];
435 j = 1;
drh5634cc02015-08-17 11:28:03 +0000436 }
437 jsonAppendChar(pOut, '}');
438 break;
439 }
drhbd0621b2015-08-13 13:54:59 +0000440 }
drh5634cc02015-08-17 11:28:03 +0000441}
442
443/*
drhf2df7e72015-08-28 20:07:40 +0000444** Return a JsonNode and all its descendents as a JSON string.
445*/
446static void jsonReturnJson(
447 JsonNode *pNode, /* Node to return */
448 sqlite3_context *pCtx, /* Return value for this function */
449 sqlite3_value **aReplace /* Array of replacement values */
450){
451 JsonString s;
452 jsonInit(&s, pCtx);
453 jsonRenderNode(pNode, &s, aReplace);
454 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000455 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000456}
457
458/*
drh5634cc02015-08-17 11:28:03 +0000459** Make the JsonNode the return value of the function.
460*/
drhd0960592015-08-17 21:22:32 +0000461static void jsonReturn(
462 JsonNode *pNode, /* Node to return */
463 sqlite3_context *pCtx, /* Return value for this function */
464 sqlite3_value **aReplace /* Array of replacement values */
465){
drh5634cc02015-08-17 11:28:03 +0000466 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000467 default: {
468 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000469 sqlite3_result_null(pCtx);
470 break;
471 }
472 case JSON_TRUE: {
473 sqlite3_result_int(pCtx, 1);
474 break;
475 }
476 case JSON_FALSE: {
477 sqlite3_result_int(pCtx, 0);
478 break;
479 }
drh987eb1f2015-08-17 15:17:37 +0000480 case JSON_REAL: {
drh52216ad2015-08-18 02:28:03 +0000481 double r = strtod(pNode->u.zJContent, 0);
drh987eb1f2015-08-17 15:17:37 +0000482 sqlite3_result_double(pCtx, r);
drh5634cc02015-08-17 11:28:03 +0000483 break;
484 }
drh987eb1f2015-08-17 15:17:37 +0000485 case JSON_INT: {
486 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000487 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000488 if( z[0]=='-' ){ z++; }
489 while( z[0]>='0' && z[0]<='9' ){ i = i*10 + *(z++) - '0'; }
drh52216ad2015-08-18 02:28:03 +0000490 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000491 sqlite3_result_int64(pCtx, i);
492 break;
493 }
drh5634cc02015-08-17 11:28:03 +0000494 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000495#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
496 ** json_insert() and json_replace() and those routines do not
497 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000498 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000499 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
500 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000501 }else
502#endif
503 assert( (pNode->jnFlags & JNODE_RAW)==0 );
504 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000505 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000506 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000507 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000508 }else{
509 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000510 u32 i;
511 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000512 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000513 char *zOut;
514 u32 j;
515 zOut = sqlite3_malloc( n+1 );
516 if( zOut==0 ){
517 sqlite3_result_error_nomem(pCtx);
518 break;
519 }
520 for(i=1, j=0; i<n-1; i++){
521 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000522 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000523 zOut[j++] = c;
524 }else{
525 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000526 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000527 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000528 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000529 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000530 if( c>='0' && c<='9' ) v = v*16 + c - '0';
531 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
532 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
533 else break;
drh987eb1f2015-08-17 15:17:37 +0000534 }
drh80d87402015-08-24 12:42:41 +0000535 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000536 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000537 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000538 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000539 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000540 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000541 }else{
mistachkin16a93122015-09-11 18:05:01 +0000542 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000543 zOut[j++] = 0x80 | ((v>>6)&0x3f);
544 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000545 }
546 }else{
547 if( c=='b' ){
548 c = '\b';
549 }else if( c=='f' ){
550 c = '\f';
551 }else if( c=='n' ){
552 c = '\n';
553 }else if( c=='r' ){
554 c = '\r';
555 }else if( c=='t' ){
556 c = '\t';
557 }
558 zOut[j++] = c;
559 }
560 }
561 }
562 zOut[j] = 0;
563 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000564 }
565 break;
566 }
567 case JSON_ARRAY:
568 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000569 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000570 break;
571 }
572 }
drhbd0621b2015-08-13 13:54:59 +0000573}
574
drh95677942015-09-24 01:06:37 +0000575/* Forward reference */
576static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
577
578/*
579** A macro to hint to the compiler that a function should not be
580** inlined.
581*/
582#if defined(__GNUC__)
583# define JSON_NOINLINE __attribute__((noinline))
584#elif defined(_MSC_VER) && _MSC_VER>=1310
585# define JSON_NOINLINE __declspec(noinline)
586#else
587# define JSON_NOINLINE
588#endif
589
590
591static JSON_NOINLINE int jsonParseAddNodeExpand(
592 JsonParse *pParse, /* Append the node to this object */
593 u32 eType, /* Node type */
594 u32 n, /* Content size or sub-node count */
595 const char *zContent /* Content */
596){
597 u32 nNew;
598 JsonNode *pNew;
599 assert( pParse->nNode>=pParse->nAlloc );
600 if( pParse->oom ) return -1;
601 nNew = pParse->nAlloc*2 + 10;
602 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
603 if( pNew==0 ){
604 pParse->oom = 1;
605 return -1;
606 }
607 pParse->nAlloc = nNew;
608 pParse->aNode = pNew;
609 assert( pParse->nNode<pParse->nAlloc );
610 return jsonParseAddNode(pParse, eType, n, zContent);
611}
612
drh5fa5c102015-08-12 16:49:40 +0000613/*
drhe9c37f32015-08-15 21:25:36 +0000614** Create a new JsonNode instance based on the arguments and append that
615** instance to the JsonParse. Return the index in pParse->aNode[] of the
616** new node, or -1 if a memory allocation fails.
617*/
618static int jsonParseAddNode(
619 JsonParse *pParse, /* Append the node to this object */
620 u32 eType, /* Node type */
621 u32 n, /* Content size or sub-node count */
622 const char *zContent /* Content */
623){
624 JsonNode *p;
625 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000626 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000627 }
628 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000629 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000630 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000631 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000632 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000633 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000634 return pParse->nNode++;
635}
636
637/*
638** Parse a single JSON value which begins at pParse->zJson[i]. Return the
639** index of the first character past the end of the value parsed.
640**
641** Return negative for a syntax error. Special cases: return -2 if the
642** first non-whitespace character is '}' and return -3 if the first
643** non-whitespace character is ']'.
644*/
645static int jsonParseValue(JsonParse *pParse, u32 i){
646 char c;
647 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000648 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000649 int x;
drh852944e2015-09-10 03:29:11 +0000650 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000651 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drhe9c37f32015-08-15 21:25:36 +0000652 if( (c = pParse->zJson[i])==0 ) return 0;
653 if( c=='{' ){
654 /* 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 [...] */
773 }else{
774 return -1; /* Syntax error */
775 }
776}
777
778/*
779** Parse a complete JSON string. Return 0 on success or non-zero if there
780** are any errors. If an error occurs, free all memory associated with
781** pParse.
782**
783** pParse is uninitialized when this routine is called.
784*/
drhbc8f0922015-08-22 19:39:04 +0000785static int jsonParse(
786 JsonParse *pParse, /* Initialize and fill this JsonParse object */
787 sqlite3_context *pCtx, /* Report errors here */
788 const char *zJson /* Input JSON text to be parsed */
789){
drhe9c37f32015-08-15 21:25:36 +0000790 int i;
drhe9c37f32015-08-15 21:25:36 +0000791 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000792 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000793 pParse->zJson = zJson;
794 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000795 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000796 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000797 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000798 if( zJson[i] ) i = -1;
799 }
drhd1f00682015-08-29 16:02:37 +0000800 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000801 if( pCtx!=0 ){
802 if( pParse->oom ){
803 sqlite3_result_error_nomem(pCtx);
804 }else{
805 sqlite3_result_error(pCtx, "malformed JSON", -1);
806 }
807 }
drh505ad2c2015-08-21 17:33:11 +0000808 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000809 return 1;
810 }
811 return 0;
812}
drh301eecc2015-08-17 20:14:19 +0000813
drh505ad2c2015-08-21 17:33:11 +0000814/* Mark node i of pParse as being a child of iParent. Call recursively
815** to fill in all the descendants of node i.
816*/
817static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
818 JsonNode *pNode = &pParse->aNode[i];
819 u32 j;
820 pParse->aUp[i] = iParent;
821 switch( pNode->eType ){
822 case JSON_ARRAY: {
823 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
824 jsonParseFillInParentage(pParse, i+j, i);
825 }
826 break;
827 }
828 case JSON_OBJECT: {
829 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
830 pParse->aUp[i+j] = i;
831 jsonParseFillInParentage(pParse, i+j+1, i);
832 }
833 break;
834 }
835 default: {
836 break;
837 }
838 }
839}
840
841/*
842** Compute the parentage of all nodes in a completed parse.
843*/
844static int jsonParseFindParents(JsonParse *pParse){
845 u32 *aUp;
846 assert( pParse->aUp==0 );
847 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000848 if( aUp==0 ){
849 pParse->oom = 1;
850 return SQLITE_NOMEM;
851 }
drh505ad2c2015-08-21 17:33:11 +0000852 jsonParseFillInParentage(pParse, 0, 0);
853 return SQLITE_OK;
854}
855
drh8cb0c832015-09-22 00:21:03 +0000856/*
857** Compare the OBJECT label at pNode against zKey,nKey. Return true on
858** a match.
859*/
860static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
861 if( pNode->jnFlags & JNODE_RAW ){
862 if( pNode->n!=nKey ) return 0;
863 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
864 }else{
865 if( pNode->n!=nKey+2 ) return 0;
866 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
867 }
868}
869
drh52216ad2015-08-18 02:28:03 +0000870/* forward declaration */
drha7714022015-08-29 00:54:49 +0000871static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000872
drh987eb1f2015-08-17 15:17:37 +0000873/*
874** Search along zPath to find the node specified. Return a pointer
875** to that node, or NULL if zPath is malformed or if there is no such
876** node.
drh52216ad2015-08-18 02:28:03 +0000877**
878** If pApnd!=0, then try to append new nodes to complete zPath if it is
879** possible to do so and if no existing node corresponds to zPath. If
880** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000881*/
drha7714022015-08-29 00:54:49 +0000882static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000883 JsonParse *pParse, /* The JSON to search */
884 u32 iRoot, /* Begin the search at this node */
885 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000886 int *pApnd, /* Append nodes to complete path if not NULL */
887 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000888){
drhbc8f0922015-08-22 19:39:04 +0000889 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000890 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000891 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000892 if( zPath[0]==0 ) return pRoot;
893 if( zPath[0]=='.' ){
894 if( pRoot->eType!=JSON_OBJECT ) return 0;
895 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000896 if( zPath[0]=='"' ){
897 zKey = zPath + 1;
898 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
899 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000900 if( zPath[i] ){
901 i++;
902 }else{
903 *pzErr = zPath;
904 return 0;
905 }
drh6b43cc82015-08-19 23:02:49 +0000906 }else{
907 zKey = zPath;
908 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
909 nKey = i;
910 }
drha7714022015-08-29 00:54:49 +0000911 if( nKey==0 ){
912 *pzErr = zPath;
913 return 0;
914 }
drh987eb1f2015-08-17 15:17:37 +0000915 j = 1;
drh52216ad2015-08-18 02:28:03 +0000916 for(;;){
917 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000918 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000919 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000920 }
921 j++;
drh505ad2c2015-08-21 17:33:11 +0000922 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000923 }
drh52216ad2015-08-18 02:28:03 +0000924 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
925 iRoot += pRoot->u.iAppend;
926 pRoot = &pParse->aNode[iRoot];
927 j = 1;
928 }
929 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000930 u32 iStart, iLabel;
931 JsonNode *pNode;
932 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
933 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000934 zPath += i;
drha7714022015-08-29 00:54:49 +0000935 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000936 if( pParse->oom ) return 0;
937 if( pNode ){
938 pRoot = &pParse->aNode[iRoot];
939 pRoot->u.iAppend = iStart - iRoot;
940 pRoot->jnFlags |= JNODE_APPEND;
941 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
942 }
943 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000944 }
dan2e8f5512015-09-17 17:21:09 +0000945 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000946 if( pRoot->eType!=JSON_ARRAY ) return 0;
947 i = 0;
drh3d1d2a92015-09-22 01:15:49 +0000948 j = 1;
949 while( safe_isdigit(zPath[j]) ){
950 i = i*10 + zPath[j] - '0';
951 j++;
drh987eb1f2015-08-17 15:17:37 +0000952 }
drh3d1d2a92015-09-22 01:15:49 +0000953 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +0000954 *pzErr = zPath;
955 return 0;
956 }
drh3d1d2a92015-09-22 01:15:49 +0000957 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +0000958 j = 1;
drh52216ad2015-08-18 02:28:03 +0000959 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000960 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
961 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000962 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000963 }
964 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
965 iRoot += pRoot->u.iAppend;
966 pRoot = &pParse->aNode[iRoot];
967 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000968 }
969 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000970 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000971 }
972 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000973 u32 iStart;
974 JsonNode *pNode;
975 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +0000976 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000977 if( pParse->oom ) return 0;
978 if( pNode ){
979 pRoot = &pParse->aNode[iRoot];
980 pRoot->u.iAppend = iStart - iRoot;
981 pRoot->jnFlags |= JNODE_APPEND;
982 }
983 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000984 }
drh3d1d2a92015-09-22 01:15:49 +0000985 }else{
drha7714022015-08-29 00:54:49 +0000986 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +0000987 }
988 return 0;
989}
990
drh52216ad2015-08-18 02:28:03 +0000991/*
drhbc8f0922015-08-22 19:39:04 +0000992** Append content to pParse that will complete zPath. Return a pointer
993** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +0000994*/
995static JsonNode *jsonLookupAppend(
996 JsonParse *pParse, /* Append content to the JSON parse */
997 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +0000998 int *pApnd, /* Set this flag to 1 */
999 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001000){
1001 *pApnd = 1;
1002 if( zPath[0]==0 ){
1003 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1004 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1005 }
1006 if( zPath[0]=='.' ){
1007 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1008 }else if( strncmp(zPath,"[0]",3)==0 ){
1009 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1010 }else{
1011 return 0;
1012 }
1013 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001014 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001015}
1016
drhbc8f0922015-08-22 19:39:04 +00001017/*
drha7714022015-08-29 00:54:49 +00001018** Return the text of a syntax error message on a JSON path. Space is
1019** obtained from sqlite3_malloc().
1020*/
1021static char *jsonPathSyntaxError(const char *zErr){
1022 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1023}
1024
1025/*
1026** Do a node lookup using zPath. Return a pointer to the node on success.
1027** Return NULL if not found or if there is an error.
1028**
1029** On an error, write an error message into pCtx and increment the
1030** pParse->nErr counter.
1031**
1032** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1033** nodes are appended.
drha7714022015-08-29 00:54:49 +00001034*/
1035static JsonNode *jsonLookup(
1036 JsonParse *pParse, /* The JSON to search */
1037 const char *zPath, /* The path to search */
1038 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001039 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001040){
1041 const char *zErr = 0;
1042 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001043 char *zMsg;
drha7714022015-08-29 00:54:49 +00001044
1045 if( zPath==0 ) return 0;
1046 if( zPath[0]!='$' ){
1047 zErr = zPath;
1048 goto lookup_err;
1049 }
1050 zPath++;
drha7714022015-08-29 00:54:49 +00001051 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001052 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001053
1054lookup_err:
1055 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001056 assert( zErr!=0 && pCtx!=0 );
1057 zMsg = jsonPathSyntaxError(zErr);
1058 if( zMsg ){
1059 sqlite3_result_error(pCtx, zMsg, -1);
1060 sqlite3_free(zMsg);
1061 }else{
1062 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001063 }
drha7714022015-08-29 00:54:49 +00001064 return 0;
1065}
1066
1067
1068/*
drhbc8f0922015-08-22 19:39:04 +00001069** Report the wrong number of arguments for json_insert(), json_replace()
1070** or json_set().
1071*/
1072static void jsonWrongNumArgs(
1073 sqlite3_context *pCtx,
1074 const char *zFuncName
1075){
1076 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1077 zFuncName);
1078 sqlite3_result_error(pCtx, zMsg, -1);
1079 sqlite3_free(zMsg);
1080}
drh52216ad2015-08-18 02:28:03 +00001081
drha7714022015-08-29 00:54:49 +00001082
drh987eb1f2015-08-17 15:17:37 +00001083/****************************************************************************
1084** SQL functions used for testing and debugging
1085****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001086
drh301eecc2015-08-17 20:14:19 +00001087#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001088/*
drh5634cc02015-08-17 11:28:03 +00001089** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001090** a parse of the JSON provided. Or it returns NULL if JSON is not
1091** well-formed.
1092*/
drh5634cc02015-08-17 11:28:03 +00001093static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001094 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001095 int argc,
1096 sqlite3_value **argv
1097){
drh505ad2c2015-08-21 17:33:11 +00001098 JsonString s; /* Output string - not real JSON */
1099 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001100 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001101
1102 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001103 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001104 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001105 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001106 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001107 const char *zType;
1108 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1109 assert( x.aNode[i].eType==JSON_STRING );
1110 zType = "label";
1111 }else{
1112 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001113 }
drh852944e2015-09-10 03:29:11 +00001114 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1115 i, zType, x.aNode[i].n, x.aUp[i]);
1116 if( x.aNode[i].u.zJContent!=0 ){
1117 jsonAppendRaw(&s, " ", 1);
1118 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1119 }
1120 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001121 }
drh505ad2c2015-08-21 17:33:11 +00001122 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001123 jsonResult(&s);
1124}
1125
drh5634cc02015-08-17 11:28:03 +00001126/*
drhf5ddb9c2015-09-11 00:06:41 +00001127** The json_test1(JSON) function return true (1) if the input is JSON
1128** text generated by another json function. It returns (0) if the input
1129** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001130*/
1131static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001132 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001133 int argc,
1134 sqlite3_value **argv
1135){
mistachkin16a93122015-09-11 18:05:01 +00001136 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001137 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001138}
drh301eecc2015-08-17 20:14:19 +00001139#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001140
drh987eb1f2015-08-17 15:17:37 +00001141/****************************************************************************
1142** SQL function implementations
1143****************************************************************************/
1144
1145/*
1146** Implementation of the json_array(VALUE,...) function. Return a JSON
1147** array that contains all values given in arguments. Or if any argument
1148** is a BLOB, throw an error.
1149*/
1150static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001151 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001152 int argc,
1153 sqlite3_value **argv
1154){
1155 int i;
drh505ad2c2015-08-21 17:33:11 +00001156 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001157
drhbc8f0922015-08-22 19:39:04 +00001158 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001159 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001160 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001161 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001162 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001163 }
drhd0960592015-08-17 21:22:32 +00001164 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001165 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001166 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001167}
1168
1169
1170/*
1171** json_array_length(JSON)
1172** json_array_length(JSON, PATH)
1173**
1174** Return the number of elements in the top-level JSON array.
1175** Return 0 if the input is not a well-formed JSON array.
1176*/
1177static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001178 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001179 int argc,
1180 sqlite3_value **argv
1181){
1182 JsonParse x; /* The parse */
1183 sqlite3_int64 n = 0;
1184 u32 i;
drha8f39a92015-09-21 22:53:16 +00001185 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001186
drhf2df7e72015-08-28 20:07:40 +00001187 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001188 assert( x.nNode );
1189 if( argc==2 ){
1190 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1191 pNode = jsonLookup(&x, zPath, 0, ctx);
1192 }else{
1193 pNode = x.aNode;
1194 }
1195 if( pNode==0 ){
1196 x.nErr = 1;
1197 }else if( pNode->eType==JSON_ARRAY ){
1198 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1199 for(i=1; i<=pNode->n; n++){
1200 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001201 }
drh987eb1f2015-08-17 15:17:37 +00001202 }
drha7714022015-08-29 00:54:49 +00001203 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001204 jsonParseReset(&x);
1205}
1206
1207/*
drh3ad93bb2015-08-29 19:41:45 +00001208** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001209**
drh3ad93bb2015-08-29 19:41:45 +00001210** Return the element described by PATH. Return NULL if there is no
1211** PATH element. If there are multiple PATHs, then return a JSON array
1212** with the result from each path. Throw an error if the JSON or any PATH
1213** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001214*/
1215static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001216 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001217 int argc,
1218 sqlite3_value **argv
1219){
1220 JsonParse x; /* The parse */
1221 JsonNode *pNode;
1222 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001223 JsonString jx;
1224 int i;
1225
1226 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001227 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001228 jsonInit(&jx, ctx);
1229 jsonAppendChar(&jx, '[');
1230 for(i=1; i<argc; i++){
1231 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001232 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001233 if( x.nErr ) break;
1234 if( argc>2 ){
1235 jsonAppendSeparator(&jx);
1236 if( pNode ){
1237 jsonRenderNode(pNode, &jx, 0);
1238 }else{
1239 jsonAppendRaw(&jx, "null", 4);
1240 }
1241 }else if( pNode ){
1242 jsonReturn(pNode, ctx, 0);
1243 }
drh987eb1f2015-08-17 15:17:37 +00001244 }
drh3ad93bb2015-08-29 19:41:45 +00001245 if( argc>2 && i==argc ){
1246 jsonAppendChar(&jx, ']');
1247 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001248 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001249 }
1250 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001251 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001252}
1253
1254/*
1255** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1256** object that contains all name/value given in arguments. Or if any name
1257** is not a string or if any value is a BLOB, throw an error.
1258*/
1259static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001260 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001261 int argc,
1262 sqlite3_value **argv
1263){
1264 int i;
drh505ad2c2015-08-21 17:33:11 +00001265 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001266 const char *z;
1267 u32 n;
1268
1269 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001270 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001271 "of arguments", -1);
1272 return;
1273 }
drhbc8f0922015-08-22 19:39:04 +00001274 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001275 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001276 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001277 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001278 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001279 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001280 return;
1281 }
drhd0960592015-08-17 21:22:32 +00001282 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001283 z = (const char*)sqlite3_value_text(argv[i]);
1284 n = (u32)sqlite3_value_bytes(argv[i]);
1285 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001286 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001287 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001288 }
drhd0960592015-08-17 21:22:32 +00001289 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001290 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001291 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001292}
1293
1294
1295/*
drh301eecc2015-08-17 20:14:19 +00001296** json_remove(JSON, PATH, ...)
1297**
drh3ad93bb2015-08-29 19:41:45 +00001298** Remove the named elements from JSON and return the result. malformed
1299** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001300*/
1301static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001302 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001303 int argc,
1304 sqlite3_value **argv
1305){
1306 JsonParse x; /* The parse */
1307 JsonNode *pNode;
1308 const char *zPath;
1309 u32 i;
1310
1311 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001312 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001313 assert( x.nNode );
1314 for(i=1; i<(u32)argc; i++){
1315 zPath = (const char*)sqlite3_value_text(argv[i]);
1316 if( zPath==0 ) goto remove_done;
1317 pNode = jsonLookup(&x, zPath, 0, ctx);
1318 if( x.nErr ) goto remove_done;
1319 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1320 }
1321 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1322 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001323 }
drha7714022015-08-29 00:54:49 +00001324remove_done:
drh505ad2c2015-08-21 17:33:11 +00001325 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001326}
1327
1328/*
1329** json_replace(JSON, PATH, VALUE, ...)
1330**
1331** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001332** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001333*/
1334static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001335 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001336 int argc,
1337 sqlite3_value **argv
1338){
1339 JsonParse x; /* The parse */
1340 JsonNode *pNode;
1341 const char *zPath;
1342 u32 i;
1343
1344 if( argc<1 ) return;
1345 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001346 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001347 return;
1348 }
drhbc8f0922015-08-22 19:39:04 +00001349 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001350 assert( x.nNode );
1351 for(i=1; i<(u32)argc; i+=2){
1352 zPath = (const char*)sqlite3_value_text(argv[i]);
1353 pNode = jsonLookup(&x, zPath, 0, ctx);
1354 if( x.nErr ) goto replace_err;
1355 if( pNode ){
1356 pNode->jnFlags |= (u8)JNODE_REPLACE;
1357 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001358 }
drha8f39a92015-09-21 22:53:16 +00001359 }
1360 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1361 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1362 }else{
1363 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001364 }
drha7714022015-08-29 00:54:49 +00001365replace_err:
drh505ad2c2015-08-21 17:33:11 +00001366 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001367}
drh505ad2c2015-08-21 17:33:11 +00001368
drh52216ad2015-08-18 02:28:03 +00001369/*
1370** json_set(JSON, PATH, VALUE, ...)
1371**
1372** Set the value at PATH to VALUE. Create the PATH if it does not already
1373** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001374** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001375**
1376** json_insert(JSON, PATH, VALUE, ...)
1377**
1378** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001379** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001380*/
1381static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001382 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001383 int argc,
1384 sqlite3_value **argv
1385){
1386 JsonParse x; /* The parse */
1387 JsonNode *pNode;
1388 const char *zPath;
1389 u32 i;
1390 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001391 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001392
1393 if( argc<1 ) return;
1394 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001395 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001396 return;
1397 }
drhbc8f0922015-08-22 19:39:04 +00001398 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001399 assert( x.nNode );
1400 for(i=1; i<(u32)argc; i+=2){
1401 zPath = (const char*)sqlite3_value_text(argv[i]);
1402 bApnd = 0;
1403 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1404 if( x.oom ){
1405 sqlite3_result_error_nomem(ctx);
1406 goto jsonSetDone;
1407 }else if( x.nErr ){
1408 goto jsonSetDone;
1409 }else if( pNode && (bApnd || bIsSet) ){
1410 pNode->jnFlags |= (u8)JNODE_REPLACE;
1411 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001412 }
drha8f39a92015-09-21 22:53:16 +00001413 }
1414 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1415 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1416 }else{
1417 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001418 }
drhbc8f0922015-08-22 19:39:04 +00001419jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001420 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001421}
drh301eecc2015-08-17 20:14:19 +00001422
1423/*
drh987eb1f2015-08-17 15:17:37 +00001424** json_type(JSON)
1425** json_type(JSON, PATH)
1426**
drh3ad93bb2015-08-29 19:41:45 +00001427** Return the top-level "type" of a JSON string. Throw an error if
1428** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001429*/
1430static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001431 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001432 int argc,
1433 sqlite3_value **argv
1434){
1435 JsonParse x; /* The parse */
1436 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001437 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001438
drhbc8f0922015-08-22 19:39:04 +00001439 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001440 assert( x.nNode );
1441 if( argc==2 ){
1442 zPath = (const char*)sqlite3_value_text(argv[1]);
1443 pNode = jsonLookup(&x, zPath, 0, ctx);
1444 }else{
1445 pNode = x.aNode;
1446 }
1447 if( pNode ){
1448 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001449 }
drh505ad2c2015-08-21 17:33:11 +00001450 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001451}
drh5634cc02015-08-17 11:28:03 +00001452
drhbc8f0922015-08-22 19:39:04 +00001453/*
1454** json_valid(JSON)
1455**
drh3ad93bb2015-08-29 19:41:45 +00001456** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1457** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001458*/
1459static void jsonValidFunc(
1460 sqlite3_context *ctx,
1461 int argc,
1462 sqlite3_value **argv
1463){
1464 JsonParse x; /* The parse */
1465 int rc = 0;
1466
mistachkin16a93122015-09-11 18:05:01 +00001467 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001468 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001469 rc = 1;
1470 }
1471 jsonParseReset(&x);
1472 sqlite3_result_int(ctx, rc);
1473}
1474
drhd2975922015-08-29 17:22:33 +00001475#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001476/****************************************************************************
1477** The json_each virtual table
1478****************************************************************************/
1479typedef struct JsonEachCursor JsonEachCursor;
1480struct JsonEachCursor {
1481 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001482 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001483 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001484 u32 i; /* Index in sParse.aNode[] of current row */
1485 u32 iEnd; /* EOF when i equals or exceeds this value */
1486 u8 eType; /* Type of top-level element */
1487 u8 bRecursive; /* True for json_tree(). False for json_each() */
1488 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001489 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001490 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001491};
1492
1493/* Constructor for the json_each virtual table */
1494static int jsonEachConnect(
1495 sqlite3 *db,
1496 void *pAux,
1497 int argc, const char *const*argv,
1498 sqlite3_vtab **ppVtab,
1499 char **pzErr
1500){
1501 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001502 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001503
1504/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001505#define JEACH_KEY 0
1506#define JEACH_VALUE 1
1507#define JEACH_TYPE 2
1508#define JEACH_ATOM 3
1509#define JEACH_ID 4
1510#define JEACH_PARENT 5
1511#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001512#define JEACH_PATH 7
1513#define JEACH_JSON 8
1514#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001515
drh6fd5c1e2015-08-21 20:37:12 +00001516 UNUSED_PARAM(pzErr);
1517 UNUSED_PARAM(argv);
1518 UNUSED_PARAM(argc);
1519 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001520 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001521 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1522 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001523 if( rc==SQLITE_OK ){
1524 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1525 if( pNew==0 ) return SQLITE_NOMEM;
1526 memset(pNew, 0, sizeof(*pNew));
1527 }
1528 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001529}
1530
1531/* destructor for json_each virtual table */
1532static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1533 sqlite3_free(pVtab);
1534 return SQLITE_OK;
1535}
1536
drh505ad2c2015-08-21 17:33:11 +00001537/* constructor for a JsonEachCursor object for json_each(). */
1538static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001539 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001540
1541 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001542 pCur = sqlite3_malloc( sizeof(*pCur) );
1543 if( pCur==0 ) return SQLITE_NOMEM;
1544 memset(pCur, 0, sizeof(*pCur));
1545 *ppCursor = &pCur->base;
1546 return SQLITE_OK;
1547}
1548
drh505ad2c2015-08-21 17:33:11 +00001549/* constructor for a JsonEachCursor object for json_tree(). */
1550static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1551 int rc = jsonEachOpenEach(p, ppCursor);
1552 if( rc==SQLITE_OK ){
1553 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1554 pCur->bRecursive = 1;
1555 }
1556 return rc;
1557}
1558
drhcb6c6c62015-08-19 22:47:17 +00001559/* Reset a JsonEachCursor back to its original state. Free any memory
1560** held. */
1561static void jsonEachCursorReset(JsonEachCursor *p){
1562 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001563 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001564 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001565 p->iRowid = 0;
1566 p->i = 0;
1567 p->iEnd = 0;
1568 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001569 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001570 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001571}
1572
1573/* Destructor for a jsonEachCursor object */
1574static int jsonEachClose(sqlite3_vtab_cursor *cur){
1575 JsonEachCursor *p = (JsonEachCursor*)cur;
1576 jsonEachCursorReset(p);
1577 sqlite3_free(cur);
1578 return SQLITE_OK;
1579}
1580
1581/* Return TRUE if the jsonEachCursor object has been advanced off the end
1582** of the JSON object */
1583static int jsonEachEof(sqlite3_vtab_cursor *cur){
1584 JsonEachCursor *p = (JsonEachCursor*)cur;
1585 return p->i >= p->iEnd;
1586}
1587
drh505ad2c2015-08-21 17:33:11 +00001588/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001589static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001590 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001591 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001592 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1593 p->i++;
drh4af352d2015-08-21 20:02:48 +00001594 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001595 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001596 u32 iUp = p->sParse.aUp[p->i];
1597 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001598 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001599 if( pUp->eType==JSON_ARRAY ){
1600 if( iUp==p->i-1 ){
1601 pUp->u.iKey = 0;
1602 }else{
1603 pUp->u.iKey++;
1604 }
drh4af352d2015-08-21 20:02:48 +00001605 }
1606 }
drh505ad2c2015-08-21 17:33:11 +00001607 }else{
drh4af352d2015-08-21 20:02:48 +00001608 switch( p->eType ){
1609 case JSON_ARRAY: {
1610 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1611 p->iRowid++;
1612 break;
1613 }
1614 case JSON_OBJECT: {
1615 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1616 p->iRowid++;
1617 break;
1618 }
1619 default: {
1620 p->i = p->iEnd;
1621 break;
1622 }
drh505ad2c2015-08-21 17:33:11 +00001623 }
1624 }
1625 return SQLITE_OK;
1626}
1627
drh4af352d2015-08-21 20:02:48 +00001628/* Append the name of the path for element i to pStr
1629*/
1630static void jsonEachComputePath(
1631 JsonEachCursor *p, /* The cursor */
1632 JsonString *pStr, /* Write the path here */
1633 u32 i /* Path to this element */
1634){
1635 JsonNode *pNode, *pUp;
1636 u32 iUp;
1637 if( i==0 ){
1638 jsonAppendChar(pStr, '$');
1639 return;
drhcb6c6c62015-08-19 22:47:17 +00001640 }
drh4af352d2015-08-21 20:02:48 +00001641 iUp = p->sParse.aUp[i];
1642 jsonEachComputePath(p, pStr, iUp);
1643 pNode = &p->sParse.aNode[i];
1644 pUp = &p->sParse.aNode[iUp];
1645 if( pUp->eType==JSON_ARRAY ){
1646 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1647 }else{
1648 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001649 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001650 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001651 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001652 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1653 }
drhcb6c6c62015-08-19 22:47:17 +00001654}
1655
1656/* Return the value of a column */
1657static int jsonEachColumn(
1658 sqlite3_vtab_cursor *cur, /* The cursor */
1659 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1660 int i /* Which column to return */
1661){
1662 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001663 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001664 switch( i ){
1665 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001666 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001667 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001668 jsonReturn(pThis, ctx, 0);
1669 }else if( p->eType==JSON_ARRAY ){
1670 u32 iKey;
1671 if( p->bRecursive ){
1672 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001673 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001674 }else{
1675 iKey = p->iRowid;
1676 }
drh6fd5c1e2015-08-21 20:37:12 +00001677 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001678 }
1679 break;
1680 }
1681 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001682 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001683 jsonReturn(pThis, ctx, 0);
1684 break;
1685 }
1686 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001687 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001688 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1689 break;
1690 }
1691 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001692 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001693 if( pThis->eType>=JSON_ARRAY ) break;
1694 jsonReturn(pThis, ctx, 0);
1695 break;
1696 }
1697 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001698 sqlite3_result_int64(ctx,
1699 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001700 break;
1701 }
1702 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001703 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001704 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001705 }
1706 break;
1707 }
drh4af352d2015-08-21 20:02:48 +00001708 case JEACH_FULLKEY: {
1709 JsonString x;
1710 jsonInit(&x, ctx);
1711 if( p->bRecursive ){
1712 jsonEachComputePath(p, &x, p->i);
1713 }else{
drh383de692015-09-10 17:20:57 +00001714 if( p->zRoot ){
1715 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001716 }else{
1717 jsonAppendChar(&x, '$');
1718 }
1719 if( p->eType==JSON_ARRAY ){
1720 jsonPrintf(30, &x, "[%d]", p->iRowid);
1721 }else{
1722 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1723 }
1724 }
1725 jsonResult(&x);
1726 break;
1727 }
drhcb6c6c62015-08-19 22:47:17 +00001728 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001729 if( p->bRecursive ){
1730 JsonString x;
1731 jsonInit(&x, ctx);
1732 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1733 jsonResult(&x);
1734 break;
drh4af352d2015-08-21 20:02:48 +00001735 }
drh383de692015-09-10 17:20:57 +00001736 /* For json_each() path and root are the same so fall through
1737 ** into the root case */
1738 }
1739 case JEACH_ROOT: {
1740 const char *zRoot = p->zRoot;
1741 if( zRoot==0 ) zRoot = "$";
1742 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001743 break;
1744 }
drh3d1d2a92015-09-22 01:15:49 +00001745 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00001746 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001747 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1748 break;
1749 }
1750 }
1751 return SQLITE_OK;
1752}
1753
1754/* Return the current rowid value */
1755static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1756 JsonEachCursor *p = (JsonEachCursor*)cur;
1757 *pRowid = p->iRowid;
1758 return SQLITE_OK;
1759}
1760
1761/* The query strategy is to look for an equality constraint on the json
1762** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001763** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001764** and 0 otherwise.
1765*/
1766static int jsonEachBestIndex(
1767 sqlite3_vtab *tab,
1768 sqlite3_index_info *pIdxInfo
1769){
1770 int i;
1771 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001772 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001773 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001774
1775 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001776 pConstraint = pIdxInfo->aConstraint;
1777 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1778 if( pConstraint->usable==0 ) continue;
1779 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1780 switch( pConstraint->iColumn ){
1781 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001782 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001783 default: /* no-op */ break;
1784 }
1785 }
1786 if( jsonIdx<0 ){
1787 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001788 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001789 }else{
drh505ad2c2015-08-21 17:33:11 +00001790 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001791 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1792 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001793 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001794 pIdxInfo->idxNum = 1;
1795 }else{
drh383de692015-09-10 17:20:57 +00001796 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1797 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001798 pIdxInfo->idxNum = 3;
1799 }
1800 }
1801 return SQLITE_OK;
1802}
1803
1804/* Start a search on a new JSON string */
1805static int jsonEachFilter(
1806 sqlite3_vtab_cursor *cur,
1807 int idxNum, const char *idxStr,
1808 int argc, sqlite3_value **argv
1809){
1810 JsonEachCursor *p = (JsonEachCursor*)cur;
1811 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001812 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001813 sqlite3_int64 n;
1814
drh6fd5c1e2015-08-21 20:37:12 +00001815 UNUSED_PARAM(idxStr);
1816 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001817 jsonEachCursorReset(p);
1818 if( idxNum==0 ) return SQLITE_OK;
1819 z = (const char*)sqlite3_value_text(argv[0]);
1820 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001821 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001822 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001823 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001824 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001825 if( jsonParse(&p->sParse, 0, p->zJson) ){
1826 int rc = SQLITE_NOMEM;
1827 if( p->sParse.oom==0 ){
1828 sqlite3_free(cur->pVtab->zErrMsg);
1829 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1830 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1831 }
drhcb6c6c62015-08-19 22:47:17 +00001832 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001833 return rc;
1834 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1835 jsonEachCursorReset(p);
1836 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001837 }else{
drh95677942015-09-24 01:06:37 +00001838 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00001839 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001840 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001841 zRoot = (const char*)sqlite3_value_text(argv[1]);
1842 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001843 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001844 p->zRoot = sqlite3_malloc64( n+1 );
1845 if( p->zRoot==0 ) return SQLITE_NOMEM;
1846 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001847 if( zRoot[0]!='$' ){
1848 zErr = zRoot;
1849 }else{
1850 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1851 }
1852 if( zErr ){
drha7714022015-08-29 00:54:49 +00001853 sqlite3_free(cur->pVtab->zErrMsg);
1854 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001855 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001856 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1857 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001858 return SQLITE_OK;
1859 }
1860 }else{
1861 pNode = p->sParse.aNode;
1862 }
drh852944e2015-09-10 03:29:11 +00001863 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001864 p->eType = pNode->eType;
1865 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001866 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001867 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001868 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00001869 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00001870 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1871 p->i--;
1872 }
1873 }else{
1874 p->i++;
1875 }
drhcb6c6c62015-08-19 22:47:17 +00001876 }else{
1877 p->iEnd = p->i+1;
1878 }
1879 }
drha8f39a92015-09-21 22:53:16 +00001880 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001881}
1882
1883/* The methods of the json_each virtual table */
1884static sqlite3_module jsonEachModule = {
1885 0, /* iVersion */
1886 0, /* xCreate */
1887 jsonEachConnect, /* xConnect */
1888 jsonEachBestIndex, /* xBestIndex */
1889 jsonEachDisconnect, /* xDisconnect */
1890 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001891 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001892 jsonEachClose, /* xClose - close a cursor */
1893 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001894 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001895 jsonEachEof, /* xEof - check for end of scan */
1896 jsonEachColumn, /* xColumn - read data */
1897 jsonEachRowid, /* xRowid - read data */
1898 0, /* xUpdate */
1899 0, /* xBegin */
1900 0, /* xSync */
1901 0, /* xCommit */
1902 0, /* xRollback */
1903 0, /* xFindMethod */
1904 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001905 0, /* xSavepoint */
1906 0, /* xRelease */
1907 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001908};
1909
drh505ad2c2015-08-21 17:33:11 +00001910/* The methods of the json_tree virtual table. */
1911static sqlite3_module jsonTreeModule = {
1912 0, /* iVersion */
1913 0, /* xCreate */
1914 jsonEachConnect, /* xConnect */
1915 jsonEachBestIndex, /* xBestIndex */
1916 jsonEachDisconnect, /* xDisconnect */
1917 0, /* xDestroy */
1918 jsonEachOpenTree, /* xOpen - open a cursor */
1919 jsonEachClose, /* xClose - close a cursor */
1920 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001921 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001922 jsonEachEof, /* xEof - check for end of scan */
1923 jsonEachColumn, /* xColumn - read data */
1924 jsonEachRowid, /* xRowid - read data */
1925 0, /* xUpdate */
1926 0, /* xBegin */
1927 0, /* xSync */
1928 0, /* xCommit */
1929 0, /* xRollback */
1930 0, /* xFindMethod */
1931 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001932 0, /* xSavepoint */
1933 0, /* xRelease */
1934 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001935};
drhd2975922015-08-29 17:22:33 +00001936#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001937
1938/****************************************************************************
1939** The following routine is the only publically visible identifier in this
1940** file. Call the following routine in order to register the various SQL
1941** functions and the virtual table implemented by this file.
1942****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001943
drh5fa5c102015-08-12 16:49:40 +00001944#ifdef _WIN32
1945__declspec(dllexport)
1946#endif
1947int sqlite3_json_init(
1948 sqlite3 *db,
1949 char **pzErrMsg,
1950 const sqlite3_api_routines *pApi
1951){
1952 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001953 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001954 static const struct {
1955 const char *zName;
1956 int nArg;
drh52216ad2015-08-18 02:28:03 +00001957 int flag;
drh5fa5c102015-08-12 16:49:40 +00001958 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1959 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001960 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001961 { "json_array", -1, 0, jsonArrayFunc },
1962 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1963 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001964 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001965 { "json_insert", -1, 0, jsonSetFunc },
1966 { "json_object", -1, 0, jsonObjectFunc },
1967 { "json_remove", -1, 0, jsonRemoveFunc },
1968 { "json_replace", -1, 0, jsonReplaceFunc },
1969 { "json_set", -1, 1, jsonSetFunc },
1970 { "json_type", 1, 0, jsonTypeFunc },
1971 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001972 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001973
drh301eecc2015-08-17 20:14:19 +00001974#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001975 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001976 { "json_parse", 1, 0, jsonParseFunc },
1977 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001978#endif
drh5fa5c102015-08-12 16:49:40 +00001979 };
drhd2975922015-08-29 17:22:33 +00001980#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001981 static const struct {
1982 const char *zName;
1983 sqlite3_module *pModule;
1984 } aMod[] = {
1985 { "json_each", &jsonEachModule },
1986 { "json_tree", &jsonTreeModule },
1987 };
drhd2975922015-08-29 17:22:33 +00001988#endif
drh5fa5c102015-08-12 16:49:40 +00001989 SQLITE_EXTENSION_INIT2(pApi);
1990 (void)pzErrMsg; /* Unused parameter */
1991 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
1992 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00001993 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
1994 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00001995 aFunc[i].xFunc, 0, 0);
1996 }
drhd2975922015-08-29 17:22:33 +00001997#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001998 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
1999 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002000 }
drhd2975922015-08-29 17:22:33 +00002001#endif
drh5fa5c102015-08-12 16:49:40 +00002002 return rc;
2003}