blob: 2962df25e40198d93edf57f17373555fb79274a9 [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
drh8deb4b82015-10-09 18:21:43 +000037#ifndef LARGEST_INT64
38# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
39# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
40#endif
41
dan2e8f5512015-09-17 17:21:09 +000042/*
43** Versions of isspace(), isalnum() and isdigit() to which it is safe
44** to pass signed char values.
45*/
dan2e8f5512015-09-17 17:21:09 +000046#define safe_isdigit(x) isdigit((unsigned char)(x))
47#define safe_isalnum(x) isalnum((unsigned char)(x))
48
drh95677942015-09-24 01:06:37 +000049/*
50** Growing our own isspace() routine this way is twice as fast as
51** the library isspace() function, resulting in a 7% overall performance
52** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
53*/
54static const char jsonIsSpace[] = {
55 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0,
56 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
57 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
59 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
66 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
67 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
69 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71};
72#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
73
drh5fa5c102015-08-12 16:49:40 +000074/* Unsigned integer types */
75typedef sqlite3_uint64 u64;
76typedef unsigned int u32;
77typedef unsigned char u8;
78
drh52216ad2015-08-18 02:28:03 +000079/* Objects */
drh505ad2c2015-08-21 17:33:11 +000080typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000081typedef struct JsonNode JsonNode;
82typedef struct JsonParse JsonParse;
83
drh5634cc02015-08-17 11:28:03 +000084/* An instance of this object represents a JSON string
85** under construction. Really, this is a generic string accumulator
86** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000087*/
drh505ad2c2015-08-21 17:33:11 +000088struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000089 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000090 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000091 u64 nAlloc; /* Bytes of storage available in zBuf[] */
92 u64 nUsed; /* Bytes of zBuf[] currently used */
93 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000094 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000095 char zSpace[100]; /* Initial static space */
96};
97
drhe9c37f32015-08-15 21:25:36 +000098/* JSON type values
drhbd0621b2015-08-13 13:54:59 +000099*/
drhe9c37f32015-08-15 21:25:36 +0000100#define JSON_NULL 0
101#define JSON_TRUE 1
102#define JSON_FALSE 2
103#define JSON_INT 3
104#define JSON_REAL 4
105#define JSON_STRING 5
106#define JSON_ARRAY 6
107#define JSON_OBJECT 7
108
drhf5ddb9c2015-09-11 00:06:41 +0000109/* The "subtype" set for JSON values */
110#define JSON_SUBTYPE 74 /* Ascii for "J" */
111
drh987eb1f2015-08-17 15:17:37 +0000112/*
113** Names of the various JSON types:
114*/
115static const char * const jsonType[] = {
116 "null", "true", "false", "integer", "real", "text", "array", "object"
117};
118
drh301eecc2015-08-17 20:14:19 +0000119/* Bit values for the JsonNode.jnFlag field
120*/
121#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
122#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
123#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +0000124#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +0000125#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drhf5ddb9c2015-09-11 00:06:41 +0000126#define JNODE_LABEL 0x20 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000127
drh987eb1f2015-08-17 15:17:37 +0000128
drhe9c37f32015-08-15 21:25:36 +0000129/* A single node of parsed JSON
130*/
drhe9c37f32015-08-15 21:25:36 +0000131struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000132 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000133 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +0000134 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +0000135 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000136 union {
drh0042a972015-08-18 12:59:58 +0000137 const char *zJContent; /* Content for INT, REAL, and STRING */
138 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000139 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +0000140 } u;
drhe9c37f32015-08-15 21:25:36 +0000141};
142
143/* A completely parsed JSON string
144*/
drhe9c37f32015-08-15 21:25:36 +0000145struct JsonParse {
146 u32 nNode; /* Number of slots of aNode[] used */
147 u32 nAlloc; /* Number of slots of aNode[] allocated */
148 JsonNode *aNode; /* Array of nodes containing the parse */
149 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000150 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000151 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000152 u8 nErr; /* Number of errors seen */
drhe9c37f32015-08-15 21:25:36 +0000153};
154
drh505ad2c2015-08-21 17:33:11 +0000155/**************************************************************************
156** Utility routines for dealing with JsonString objects
157**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000158
drh505ad2c2015-08-21 17:33:11 +0000159/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000160*/
drh505ad2c2015-08-21 17:33:11 +0000161static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000162 p->zBuf = p->zSpace;
163 p->nAlloc = sizeof(p->zSpace);
164 p->nUsed = 0;
165 p->bStatic = 1;
166}
167
drh505ad2c2015-08-21 17:33:11 +0000168/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000169*/
drh505ad2c2015-08-21 17:33:11 +0000170static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000171 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000172 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000173 jsonZero(p);
174}
175
176
drh505ad2c2015-08-21 17:33:11 +0000177/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000178** initial state.
179*/
drh505ad2c2015-08-21 17:33:11 +0000180static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000181 if( !p->bStatic ) sqlite3_free(p->zBuf);
182 jsonZero(p);
183}
184
185
186/* Report an out-of-memory (OOM) condition
187*/
drh505ad2c2015-08-21 17:33:11 +0000188static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000189 p->bErr = 1;
190 sqlite3_result_error_nomem(p->pCtx);
191 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000192}
193
194/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
195** Return zero on success. Return non-zero on an OOM error
196*/
drh505ad2c2015-08-21 17:33:11 +0000197static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000198 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000199 char *zNew;
200 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000201 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000202 zNew = sqlite3_malloc64(nTotal);
203 if( zNew==0 ){
204 jsonOom(p);
205 return SQLITE_NOMEM;
206 }
drh6fd5c1e2015-08-21 20:37:12 +0000207 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000208 p->zBuf = zNew;
209 p->bStatic = 0;
210 }else{
211 zNew = sqlite3_realloc64(p->zBuf, nTotal);
212 if( zNew==0 ){
213 jsonOom(p);
214 return SQLITE_NOMEM;
215 }
216 p->zBuf = zNew;
217 }
218 p->nAlloc = nTotal;
219 return SQLITE_OK;
220}
221
drh505ad2c2015-08-21 17:33:11 +0000222/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000223*/
drh505ad2c2015-08-21 17:33:11 +0000224static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000225 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
226 memcpy(p->zBuf+p->nUsed, zIn, N);
227 p->nUsed += N;
228}
229
drh4af352d2015-08-21 20:02:48 +0000230/* Append formatted text (not to exceed N bytes) to the JsonString.
231*/
232static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
233 va_list ap;
234 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
235 va_start(ap, zFormat);
236 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
237 va_end(ap);
238 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
239}
240
drh5634cc02015-08-17 11:28:03 +0000241/* Append a single character
242*/
drh505ad2c2015-08-21 17:33:11 +0000243static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000244 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
245 p->zBuf[p->nUsed++] = c;
246}
247
drh301eecc2015-08-17 20:14:19 +0000248/* Append a comma separator to the output buffer, if the previous
249** character is not '[' or '{'.
250*/
drh505ad2c2015-08-21 17:33:11 +0000251static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000252 char c;
253 if( p->nUsed==0 ) return;
254 c = p->zBuf[p->nUsed-1];
255 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
256}
257
drh505ad2c2015-08-21 17:33:11 +0000258/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000259** under construction. Enclose the string in "..." and escape
260** any double-quotes or backslash characters contained within the
261** string.
262*/
drh505ad2c2015-08-21 17:33:11 +0000263static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000264 u32 i;
265 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
266 p->zBuf[p->nUsed++] = '"';
267 for(i=0; i<N; i++){
268 char c = zIn[i];
269 if( c=='"' || c=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000270 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000271 p->zBuf[p->nUsed++] = '\\';
272 }
273 p->zBuf[p->nUsed++] = c;
274 }
275 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000276 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000277}
278
drhd0960592015-08-17 21:22:32 +0000279/*
280** Append a function parameter value to the JSON string under
281** construction.
282*/
283static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000284 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000285 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000286){
287 switch( sqlite3_value_type(pValue) ){
288 case SQLITE_NULL: {
289 jsonAppendRaw(p, "null", 4);
290 break;
291 }
292 case SQLITE_INTEGER:
293 case SQLITE_FLOAT: {
294 const char *z = (const char*)sqlite3_value_text(pValue);
295 u32 n = (u32)sqlite3_value_bytes(pValue);
296 jsonAppendRaw(p, z, n);
297 break;
298 }
299 case SQLITE_TEXT: {
300 const char *z = (const char*)sqlite3_value_text(pValue);
301 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000302 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000303 jsonAppendRaw(p, z, n);
304 }else{
305 jsonAppendString(p, z, n);
306 }
drhd0960592015-08-17 21:22:32 +0000307 break;
308 }
309 default: {
310 if( p->bErr==0 ){
311 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
312 p->bErr = 1;
313 jsonReset(p);
314 }
315 break;
316 }
317 }
318}
319
320
drhbd0621b2015-08-13 13:54:59 +0000321/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000322*/
drh505ad2c2015-08-21 17:33:11 +0000323static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000324 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000325 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
326 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
327 SQLITE_UTF8);
328 jsonZero(p);
329 }
330 assert( p->bStatic );
331}
332
drh505ad2c2015-08-21 17:33:11 +0000333/**************************************************************************
334** Utility routines for dealing with JsonNode and JsonParse objects
335**************************************************************************/
336
337/*
338** Return the number of consecutive JsonNode slots need to represent
339** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
340** OBJECT types, the number might be larger.
341**
342** Appended elements are not counted. The value returned is the number
343** by which the JsonNode counter should increment in order to go to the
344** next peer value.
345*/
346static u32 jsonNodeSize(JsonNode *pNode){
347 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
348}
349
350/*
351** Reclaim all memory allocated by a JsonParse object. But do not
352** delete the JsonParse object itself.
353*/
354static void jsonParseReset(JsonParse *pParse){
355 sqlite3_free(pParse->aNode);
356 pParse->aNode = 0;
357 pParse->nNode = 0;
358 pParse->nAlloc = 0;
359 sqlite3_free(pParse->aUp);
360 pParse->aUp = 0;
361}
362
drh5634cc02015-08-17 11:28:03 +0000363/*
364** Convert the JsonNode pNode into a pure JSON string and
365** append to pOut. Subsubstructure is also included. Return
366** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000367*/
drh52216ad2015-08-18 02:28:03 +0000368static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000369 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000370 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000371 sqlite3_value **aReplace /* Replacement values */
372){
drh5634cc02015-08-17 11:28:03 +0000373 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000374 default: {
375 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000376 jsonAppendRaw(pOut, "null", 4);
377 break;
378 }
379 case JSON_TRUE: {
380 jsonAppendRaw(pOut, "true", 4);
381 break;
382 }
383 case JSON_FALSE: {
384 jsonAppendRaw(pOut, "false", 5);
385 break;
386 }
387 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000388 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000389 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000390 break;
391 }
392 /* Fall through into the next case */
393 }
394 case JSON_REAL:
395 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000396 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000397 break;
398 }
399 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000400 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000401 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000402 for(;;){
403 while( j<=pNode->n ){
404 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
405 if( pNode[j].jnFlags & JNODE_REPLACE ){
406 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000407 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000408 }
409 }else{
drhd0960592015-08-17 21:22:32 +0000410 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000411 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000412 }
drh505ad2c2015-08-21 17:33:11 +0000413 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000414 }
drh52216ad2015-08-18 02:28:03 +0000415 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
416 pNode = &pNode[pNode->u.iAppend];
417 j = 1;
drh5634cc02015-08-17 11:28:03 +0000418 }
419 jsonAppendChar(pOut, ']');
420 break;
421 }
422 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000423 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000424 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000425 for(;;){
426 while( j<=pNode->n ){
427 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
428 jsonAppendSeparator(pOut);
429 jsonRenderNode(&pNode[j], pOut, aReplace);
430 jsonAppendChar(pOut, ':');
431 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000432 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000433 }else{
434 jsonRenderNode(&pNode[j+1], pOut, aReplace);
435 }
drhd0960592015-08-17 21:22:32 +0000436 }
drh505ad2c2015-08-21 17:33:11 +0000437 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000438 }
drh52216ad2015-08-18 02:28:03 +0000439 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
440 pNode = &pNode[pNode->u.iAppend];
441 j = 1;
drh5634cc02015-08-17 11:28:03 +0000442 }
443 jsonAppendChar(pOut, '}');
444 break;
445 }
drhbd0621b2015-08-13 13:54:59 +0000446 }
drh5634cc02015-08-17 11:28:03 +0000447}
448
449/*
drhf2df7e72015-08-28 20:07:40 +0000450** Return a JsonNode and all its descendents as a JSON string.
451*/
452static void jsonReturnJson(
453 JsonNode *pNode, /* Node to return */
454 sqlite3_context *pCtx, /* Return value for this function */
455 sqlite3_value **aReplace /* Array of replacement values */
456){
457 JsonString s;
458 jsonInit(&s, pCtx);
459 jsonRenderNode(pNode, &s, aReplace);
460 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000461 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000462}
463
464/*
drh5634cc02015-08-17 11:28:03 +0000465** Make the JsonNode the return value of the function.
466*/
drhd0960592015-08-17 21:22:32 +0000467static void jsonReturn(
468 JsonNode *pNode, /* Node to return */
469 sqlite3_context *pCtx, /* Return value for this function */
470 sqlite3_value **aReplace /* Array of replacement values */
471){
drh5634cc02015-08-17 11:28:03 +0000472 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000473 default: {
474 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000475 sqlite3_result_null(pCtx);
476 break;
477 }
478 case JSON_TRUE: {
479 sqlite3_result_int(pCtx, 1);
480 break;
481 }
482 case JSON_FALSE: {
483 sqlite3_result_int(pCtx, 0);
484 break;
485 }
drh987eb1f2015-08-17 15:17:37 +0000486 case JSON_INT: {
487 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000488 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000489 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000490 while( z[0]>='0' && z[0]<='9' ){
491 unsigned v = *(z++) - '0';
492 if( i>=LARGEST_INT64/10 ){
493 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
494 if( v==9 ) goto int_as_real;
495 if( v==8 ){
496 if( pNode->u.zJContent[0]=='-' ){
497 sqlite3_result_int64(pCtx, SMALLEST_INT64);
498 goto int_done;
499 }else{
500 goto int_as_real;
501 }
502 }
503 }
504 i = i*10 + v;
505 }
drh52216ad2015-08-18 02:28:03 +0000506 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000507 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000508 int_done:
509 break;
510 int_as_real: /* fall through to real */;
511 }
512 case JSON_REAL: {
513 double r = strtod(pNode->u.zJContent, 0);
514 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000515 break;
516 }
drh5634cc02015-08-17 11:28:03 +0000517 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000518#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
519 ** json_insert() and json_replace() and those routines do not
520 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000521 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000522 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
523 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000524 }else
525#endif
526 assert( (pNode->jnFlags & JNODE_RAW)==0 );
527 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000528 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000529 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000530 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000531 }else{
532 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000533 u32 i;
534 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000535 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000536 char *zOut;
537 u32 j;
538 zOut = sqlite3_malloc( n+1 );
539 if( zOut==0 ){
540 sqlite3_result_error_nomem(pCtx);
541 break;
542 }
543 for(i=1, j=0; i<n-1; i++){
544 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000545 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000546 zOut[j++] = c;
547 }else{
548 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000549 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000550 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000551 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000552 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000553 if( c>='0' && c<='9' ) v = v*16 + c - '0';
554 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
555 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
556 else break;
drh987eb1f2015-08-17 15:17:37 +0000557 }
drh80d87402015-08-24 12:42:41 +0000558 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000559 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000560 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000561 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000562 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000563 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000564 }else{
mistachkin16a93122015-09-11 18:05:01 +0000565 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000566 zOut[j++] = 0x80 | ((v>>6)&0x3f);
567 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000568 }
569 }else{
570 if( c=='b' ){
571 c = '\b';
572 }else if( c=='f' ){
573 c = '\f';
574 }else if( c=='n' ){
575 c = '\n';
576 }else if( c=='r' ){
577 c = '\r';
578 }else if( c=='t' ){
579 c = '\t';
580 }
581 zOut[j++] = c;
582 }
583 }
584 }
585 zOut[j] = 0;
586 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000587 }
588 break;
589 }
590 case JSON_ARRAY:
591 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000592 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000593 break;
594 }
595 }
drhbd0621b2015-08-13 13:54:59 +0000596}
597
drh95677942015-09-24 01:06:37 +0000598/* Forward reference */
599static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
600
601/*
602** A macro to hint to the compiler that a function should not be
603** inlined.
604*/
605#if defined(__GNUC__)
606# define JSON_NOINLINE __attribute__((noinline))
607#elif defined(_MSC_VER) && _MSC_VER>=1310
608# define JSON_NOINLINE __declspec(noinline)
609#else
610# define JSON_NOINLINE
611#endif
612
613
614static JSON_NOINLINE int jsonParseAddNodeExpand(
615 JsonParse *pParse, /* Append the node to this object */
616 u32 eType, /* Node type */
617 u32 n, /* Content size or sub-node count */
618 const char *zContent /* Content */
619){
620 u32 nNew;
621 JsonNode *pNew;
622 assert( pParse->nNode>=pParse->nAlloc );
623 if( pParse->oom ) return -1;
624 nNew = pParse->nAlloc*2 + 10;
625 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
626 if( pNew==0 ){
627 pParse->oom = 1;
628 return -1;
629 }
630 pParse->nAlloc = nNew;
631 pParse->aNode = pNew;
632 assert( pParse->nNode<pParse->nAlloc );
633 return jsonParseAddNode(pParse, eType, n, zContent);
634}
635
drh5fa5c102015-08-12 16:49:40 +0000636/*
drhe9c37f32015-08-15 21:25:36 +0000637** Create a new JsonNode instance based on the arguments and append that
638** instance to the JsonParse. Return the index in pParse->aNode[] of the
639** new node, or -1 if a memory allocation fails.
640*/
641static int jsonParseAddNode(
642 JsonParse *pParse, /* Append the node to this object */
643 u32 eType, /* Node type */
644 u32 n, /* Content size or sub-node count */
645 const char *zContent /* Content */
646){
647 JsonNode *p;
648 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000649 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000650 }
651 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000652 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000653 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000654 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000655 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000656 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000657 return pParse->nNode++;
658}
659
660/*
661** Parse a single JSON value which begins at pParse->zJson[i]. Return the
662** index of the first character past the end of the value parsed.
663**
664** Return negative for a syntax error. Special cases: return -2 if the
665** first non-whitespace character is '}' and return -3 if the first
666** non-whitespace character is ']'.
667*/
668static int jsonParseValue(JsonParse *pParse, u32 i){
669 char c;
670 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000671 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000672 int x;
drh852944e2015-09-10 03:29:11 +0000673 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000674 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drh8cb15cc2015-09-24 01:40:45 +0000675 if( (c = pParse->zJson[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000676 /* Parse object */
677 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000678 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000679 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000680 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000681 x = jsonParseValue(pParse, j);
682 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000683 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000684 return -1;
685 }
drhbe9474e2015-08-22 03:05:54 +0000686 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000687 pNode = &pParse->aNode[pParse->nNode-1];
688 if( pNode->eType!=JSON_STRING ) return -1;
689 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000690 j = x;
dan2e8f5512015-09-17 17:21:09 +0000691 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000692 if( pParse->zJson[j]!=':' ) return -1;
693 j++;
694 x = jsonParseValue(pParse, j);
695 if( x<0 ) return -1;
696 j = x;
dan2e8f5512015-09-17 17:21:09 +0000697 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000698 c = pParse->zJson[j];
699 if( c==',' ) continue;
700 if( c!='}' ) return -1;
701 break;
702 }
drhbc8f0922015-08-22 19:39:04 +0000703 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000704 return j+1;
705 }else if( c=='[' ){
706 /* Parse array */
707 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000708 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000709 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000710 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000711 x = jsonParseValue(pParse, j);
712 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000713 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000714 return -1;
715 }
716 j = x;
dan2e8f5512015-09-17 17:21:09 +0000717 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000718 c = pParse->zJson[j];
719 if( c==',' ) continue;
720 if( c!=']' ) return -1;
721 break;
722 }
drhbc8f0922015-08-22 19:39:04 +0000723 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000724 return j+1;
725 }else if( c=='"' ){
726 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000727 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000728 j = i+1;
729 for(;;){
730 c = pParse->zJson[j];
731 if( c==0 ) return -1;
732 if( c=='\\' ){
733 c = pParse->zJson[++j];
734 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000735 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000736 }else if( c=='"' ){
737 break;
738 }
739 j++;
740 }
741 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000742 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000743 return j+1;
744 }else if( c=='n'
745 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000746 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000747 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
748 return i+4;
749 }else if( c=='t'
750 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000751 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000752 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
753 return i+4;
754 }else if( c=='f'
755 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000756 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000757 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
758 return i+5;
759 }else if( c=='-' || (c>='0' && c<='9') ){
760 /* Parse number */
761 u8 seenDP = 0;
762 u8 seenE = 0;
763 j = i+1;
764 for(;; j++){
765 c = pParse->zJson[j];
766 if( c>='0' && c<='9' ) continue;
767 if( c=='.' ){
768 if( pParse->zJson[j-1]=='-' ) return -1;
769 if( seenDP ) return -1;
770 seenDP = 1;
771 continue;
772 }
773 if( c=='e' || c=='E' ){
774 if( pParse->zJson[j-1]<'0' ) return -1;
775 if( seenE ) return -1;
776 seenDP = seenE = 1;
777 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000778 if( c=='+' || c=='-' ){
779 j++;
780 c = pParse->zJson[j+1];
781 }
drhd1f00682015-08-29 16:02:37 +0000782 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000783 continue;
784 }
785 break;
786 }
787 if( pParse->zJson[j-1]<'0' ) return -1;
788 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
789 j - i, &pParse->zJson[i]);
790 return j;
791 }else if( c=='}' ){
792 return -2; /* End of {...} */
793 }else if( c==']' ){
794 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000795 }else if( c==0 ){
796 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000797 }else{
798 return -1; /* Syntax error */
799 }
800}
801
802/*
803** Parse a complete JSON string. Return 0 on success or non-zero if there
804** are any errors. If an error occurs, free all memory associated with
805** pParse.
806**
807** pParse is uninitialized when this routine is called.
808*/
drhbc8f0922015-08-22 19:39:04 +0000809static int jsonParse(
810 JsonParse *pParse, /* Initialize and fill this JsonParse object */
811 sqlite3_context *pCtx, /* Report errors here */
812 const char *zJson /* Input JSON text to be parsed */
813){
drhe9c37f32015-08-15 21:25:36 +0000814 int i;
drhe9c37f32015-08-15 21:25:36 +0000815 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000816 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000817 pParse->zJson = zJson;
818 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000819 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000820 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000821 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000822 if( zJson[i] ) i = -1;
823 }
drhd1f00682015-08-29 16:02:37 +0000824 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000825 if( pCtx!=0 ){
826 if( pParse->oom ){
827 sqlite3_result_error_nomem(pCtx);
828 }else{
829 sqlite3_result_error(pCtx, "malformed JSON", -1);
830 }
831 }
drh505ad2c2015-08-21 17:33:11 +0000832 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000833 return 1;
834 }
835 return 0;
836}
drh301eecc2015-08-17 20:14:19 +0000837
drh505ad2c2015-08-21 17:33:11 +0000838/* Mark node i of pParse as being a child of iParent. Call recursively
839** to fill in all the descendants of node i.
840*/
841static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
842 JsonNode *pNode = &pParse->aNode[i];
843 u32 j;
844 pParse->aUp[i] = iParent;
845 switch( pNode->eType ){
846 case JSON_ARRAY: {
847 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
848 jsonParseFillInParentage(pParse, i+j, i);
849 }
850 break;
851 }
852 case JSON_OBJECT: {
853 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
854 pParse->aUp[i+j] = i;
855 jsonParseFillInParentage(pParse, i+j+1, i);
856 }
857 break;
858 }
859 default: {
860 break;
861 }
862 }
863}
864
865/*
866** Compute the parentage of all nodes in a completed parse.
867*/
868static int jsonParseFindParents(JsonParse *pParse){
869 u32 *aUp;
870 assert( pParse->aUp==0 );
871 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000872 if( aUp==0 ){
873 pParse->oom = 1;
874 return SQLITE_NOMEM;
875 }
drh505ad2c2015-08-21 17:33:11 +0000876 jsonParseFillInParentage(pParse, 0, 0);
877 return SQLITE_OK;
878}
879
drh8cb0c832015-09-22 00:21:03 +0000880/*
881** Compare the OBJECT label at pNode against zKey,nKey. Return true on
882** a match.
883*/
884static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
885 if( pNode->jnFlags & JNODE_RAW ){
886 if( pNode->n!=nKey ) return 0;
887 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
888 }else{
889 if( pNode->n!=nKey+2 ) return 0;
890 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
891 }
892}
893
drh52216ad2015-08-18 02:28:03 +0000894/* forward declaration */
drha7714022015-08-29 00:54:49 +0000895static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000896
drh987eb1f2015-08-17 15:17:37 +0000897/*
898** Search along zPath to find the node specified. Return a pointer
899** to that node, or NULL if zPath is malformed or if there is no such
900** node.
drh52216ad2015-08-18 02:28:03 +0000901**
902** If pApnd!=0, then try to append new nodes to complete zPath if it is
903** possible to do so and if no existing node corresponds to zPath. If
904** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000905*/
drha7714022015-08-29 00:54:49 +0000906static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000907 JsonParse *pParse, /* The JSON to search */
908 u32 iRoot, /* Begin the search at this node */
909 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000910 int *pApnd, /* Append nodes to complete path if not NULL */
911 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000912){
drhbc8f0922015-08-22 19:39:04 +0000913 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000914 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000915 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000916 if( zPath[0]==0 ) return pRoot;
917 if( zPath[0]=='.' ){
918 if( pRoot->eType!=JSON_OBJECT ) return 0;
919 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000920 if( zPath[0]=='"' ){
921 zKey = zPath + 1;
922 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
923 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000924 if( zPath[i] ){
925 i++;
926 }else{
927 *pzErr = zPath;
928 return 0;
929 }
drh6b43cc82015-08-19 23:02:49 +0000930 }else{
931 zKey = zPath;
932 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
933 nKey = i;
934 }
drha7714022015-08-29 00:54:49 +0000935 if( nKey==0 ){
936 *pzErr = zPath;
937 return 0;
938 }
drh987eb1f2015-08-17 15:17:37 +0000939 j = 1;
drh52216ad2015-08-18 02:28:03 +0000940 for(;;){
941 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000942 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000943 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000944 }
945 j++;
drh505ad2c2015-08-21 17:33:11 +0000946 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000947 }
drh52216ad2015-08-18 02:28:03 +0000948 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
949 iRoot += pRoot->u.iAppend;
950 pRoot = &pParse->aNode[iRoot];
951 j = 1;
952 }
953 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000954 u32 iStart, iLabel;
955 JsonNode *pNode;
956 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
957 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000958 zPath += i;
drha7714022015-08-29 00:54:49 +0000959 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000960 if( pParse->oom ) return 0;
961 if( pNode ){
962 pRoot = &pParse->aNode[iRoot];
963 pRoot->u.iAppend = iStart - iRoot;
964 pRoot->jnFlags |= JNODE_APPEND;
965 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
966 }
967 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000968 }
dan2e8f5512015-09-17 17:21:09 +0000969 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000970 if( pRoot->eType!=JSON_ARRAY ) return 0;
971 i = 0;
drh3d1d2a92015-09-22 01:15:49 +0000972 j = 1;
973 while( safe_isdigit(zPath[j]) ){
974 i = i*10 + zPath[j] - '0';
975 j++;
drh987eb1f2015-08-17 15:17:37 +0000976 }
drh3d1d2a92015-09-22 01:15:49 +0000977 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +0000978 *pzErr = zPath;
979 return 0;
980 }
drh3d1d2a92015-09-22 01:15:49 +0000981 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +0000982 j = 1;
drh52216ad2015-08-18 02:28:03 +0000983 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000984 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
985 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000986 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000987 }
988 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
989 iRoot += pRoot->u.iAppend;
990 pRoot = &pParse->aNode[iRoot];
991 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000992 }
993 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000994 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000995 }
996 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000997 u32 iStart;
998 JsonNode *pNode;
999 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001000 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001001 if( pParse->oom ) return 0;
1002 if( pNode ){
1003 pRoot = &pParse->aNode[iRoot];
1004 pRoot->u.iAppend = iStart - iRoot;
1005 pRoot->jnFlags |= JNODE_APPEND;
1006 }
1007 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001008 }
drh3d1d2a92015-09-22 01:15:49 +00001009 }else{
drha7714022015-08-29 00:54:49 +00001010 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001011 }
1012 return 0;
1013}
1014
drh52216ad2015-08-18 02:28:03 +00001015/*
drhbc8f0922015-08-22 19:39:04 +00001016** Append content to pParse that will complete zPath. Return a pointer
1017** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001018*/
1019static JsonNode *jsonLookupAppend(
1020 JsonParse *pParse, /* Append content to the JSON parse */
1021 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001022 int *pApnd, /* Set this flag to 1 */
1023 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001024){
1025 *pApnd = 1;
1026 if( zPath[0]==0 ){
1027 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1028 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1029 }
1030 if( zPath[0]=='.' ){
1031 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1032 }else if( strncmp(zPath,"[0]",3)==0 ){
1033 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1034 }else{
1035 return 0;
1036 }
1037 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001038 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001039}
1040
drhbc8f0922015-08-22 19:39:04 +00001041/*
drha7714022015-08-29 00:54:49 +00001042** Return the text of a syntax error message on a JSON path. Space is
1043** obtained from sqlite3_malloc().
1044*/
1045static char *jsonPathSyntaxError(const char *zErr){
1046 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1047}
1048
1049/*
1050** Do a node lookup using zPath. Return a pointer to the node on success.
1051** Return NULL if not found or if there is an error.
1052**
1053** On an error, write an error message into pCtx and increment the
1054** pParse->nErr counter.
1055**
1056** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1057** nodes are appended.
drha7714022015-08-29 00:54:49 +00001058*/
1059static JsonNode *jsonLookup(
1060 JsonParse *pParse, /* The JSON to search */
1061 const char *zPath, /* The path to search */
1062 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001063 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001064){
1065 const char *zErr = 0;
1066 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001067 char *zMsg;
drha7714022015-08-29 00:54:49 +00001068
1069 if( zPath==0 ) return 0;
1070 if( zPath[0]!='$' ){
1071 zErr = zPath;
1072 goto lookup_err;
1073 }
1074 zPath++;
drha7714022015-08-29 00:54:49 +00001075 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001076 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001077
1078lookup_err:
1079 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001080 assert( zErr!=0 && pCtx!=0 );
1081 zMsg = jsonPathSyntaxError(zErr);
1082 if( zMsg ){
1083 sqlite3_result_error(pCtx, zMsg, -1);
1084 sqlite3_free(zMsg);
1085 }else{
1086 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001087 }
drha7714022015-08-29 00:54:49 +00001088 return 0;
1089}
1090
1091
1092/*
drhbc8f0922015-08-22 19:39:04 +00001093** Report the wrong number of arguments for json_insert(), json_replace()
1094** or json_set().
1095*/
1096static void jsonWrongNumArgs(
1097 sqlite3_context *pCtx,
1098 const char *zFuncName
1099){
1100 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1101 zFuncName);
1102 sqlite3_result_error(pCtx, zMsg, -1);
1103 sqlite3_free(zMsg);
1104}
drh52216ad2015-08-18 02:28:03 +00001105
drha7714022015-08-29 00:54:49 +00001106
drh987eb1f2015-08-17 15:17:37 +00001107/****************************************************************************
1108** SQL functions used for testing and debugging
1109****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001110
drh301eecc2015-08-17 20:14:19 +00001111#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001112/*
drh5634cc02015-08-17 11:28:03 +00001113** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001114** a parse of the JSON provided. Or it returns NULL if JSON is not
1115** well-formed.
1116*/
drh5634cc02015-08-17 11:28:03 +00001117static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001118 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001119 int argc,
1120 sqlite3_value **argv
1121){
drh505ad2c2015-08-21 17:33:11 +00001122 JsonString s; /* Output string - not real JSON */
1123 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001124 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001125
1126 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001127 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001128 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001129 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001130 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001131 const char *zType;
1132 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1133 assert( x.aNode[i].eType==JSON_STRING );
1134 zType = "label";
1135 }else{
1136 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001137 }
drh852944e2015-09-10 03:29:11 +00001138 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1139 i, zType, x.aNode[i].n, x.aUp[i]);
1140 if( x.aNode[i].u.zJContent!=0 ){
1141 jsonAppendRaw(&s, " ", 1);
1142 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1143 }
1144 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001145 }
drh505ad2c2015-08-21 17:33:11 +00001146 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001147 jsonResult(&s);
1148}
1149
drh5634cc02015-08-17 11:28:03 +00001150/*
drhf5ddb9c2015-09-11 00:06:41 +00001151** The json_test1(JSON) function return true (1) if the input is JSON
1152** text generated by another json function. It returns (0) if the input
1153** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001154*/
1155static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001156 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001157 int argc,
1158 sqlite3_value **argv
1159){
mistachkin16a93122015-09-11 18:05:01 +00001160 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001161 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001162}
drh301eecc2015-08-17 20:14:19 +00001163#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001164
drh987eb1f2015-08-17 15:17:37 +00001165/****************************************************************************
1166** SQL function implementations
1167****************************************************************************/
1168
1169/*
1170** Implementation of the json_array(VALUE,...) function. Return a JSON
1171** array that contains all values given in arguments. Or if any argument
1172** is a BLOB, throw an error.
1173*/
1174static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001175 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001176 int argc,
1177 sqlite3_value **argv
1178){
1179 int i;
drh505ad2c2015-08-21 17:33:11 +00001180 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001181
drhbc8f0922015-08-22 19:39:04 +00001182 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001183 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001184 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001185 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001186 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001187 }
drhd0960592015-08-17 21:22:32 +00001188 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001189 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001190 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001191}
1192
1193
1194/*
1195** json_array_length(JSON)
1196** json_array_length(JSON, PATH)
1197**
1198** Return the number of elements in the top-level JSON array.
1199** Return 0 if the input is not a well-formed JSON array.
1200*/
1201static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001202 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001203 int argc,
1204 sqlite3_value **argv
1205){
1206 JsonParse x; /* The parse */
1207 sqlite3_int64 n = 0;
1208 u32 i;
drha8f39a92015-09-21 22:53:16 +00001209 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001210
drhf2df7e72015-08-28 20:07:40 +00001211 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001212 assert( x.nNode );
1213 if( argc==2 ){
1214 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1215 pNode = jsonLookup(&x, zPath, 0, ctx);
1216 }else{
1217 pNode = x.aNode;
1218 }
1219 if( pNode==0 ){
1220 x.nErr = 1;
1221 }else if( pNode->eType==JSON_ARRAY ){
1222 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1223 for(i=1; i<=pNode->n; n++){
1224 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001225 }
drh987eb1f2015-08-17 15:17:37 +00001226 }
drha7714022015-08-29 00:54:49 +00001227 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001228 jsonParseReset(&x);
1229}
1230
1231/*
drh3ad93bb2015-08-29 19:41:45 +00001232** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001233**
drh3ad93bb2015-08-29 19:41:45 +00001234** Return the element described by PATH. Return NULL if there is no
1235** PATH element. If there are multiple PATHs, then return a JSON array
1236** with the result from each path. Throw an error if the JSON or any PATH
1237** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001238*/
1239static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001240 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001241 int argc,
1242 sqlite3_value **argv
1243){
1244 JsonParse x; /* The parse */
1245 JsonNode *pNode;
1246 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001247 JsonString jx;
1248 int i;
1249
1250 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001251 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001252 jsonInit(&jx, ctx);
1253 jsonAppendChar(&jx, '[');
1254 for(i=1; i<argc; i++){
1255 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001256 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001257 if( x.nErr ) break;
1258 if( argc>2 ){
1259 jsonAppendSeparator(&jx);
1260 if( pNode ){
1261 jsonRenderNode(pNode, &jx, 0);
1262 }else{
1263 jsonAppendRaw(&jx, "null", 4);
1264 }
1265 }else if( pNode ){
1266 jsonReturn(pNode, ctx, 0);
1267 }
drh987eb1f2015-08-17 15:17:37 +00001268 }
drh3ad93bb2015-08-29 19:41:45 +00001269 if( argc>2 && i==argc ){
1270 jsonAppendChar(&jx, ']');
1271 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001272 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001273 }
1274 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001275 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001276}
1277
1278/*
1279** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1280** object that contains all name/value given in arguments. Or if any name
1281** is not a string or if any value is a BLOB, throw an error.
1282*/
1283static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001284 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001285 int argc,
1286 sqlite3_value **argv
1287){
1288 int i;
drh505ad2c2015-08-21 17:33:11 +00001289 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001290 const char *z;
1291 u32 n;
1292
1293 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001294 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001295 "of arguments", -1);
1296 return;
1297 }
drhbc8f0922015-08-22 19:39:04 +00001298 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001299 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001300 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001301 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001302 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001303 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001304 return;
1305 }
drhd0960592015-08-17 21:22:32 +00001306 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001307 z = (const char*)sqlite3_value_text(argv[i]);
1308 n = (u32)sqlite3_value_bytes(argv[i]);
1309 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001310 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001311 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001312 }
drhd0960592015-08-17 21:22:32 +00001313 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001314 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001315 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001316}
1317
1318
1319/*
drh301eecc2015-08-17 20:14:19 +00001320** json_remove(JSON, PATH, ...)
1321**
drh3ad93bb2015-08-29 19:41:45 +00001322** Remove the named elements from JSON and return the result. malformed
1323** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001324*/
1325static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001326 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001327 int argc,
1328 sqlite3_value **argv
1329){
1330 JsonParse x; /* The parse */
1331 JsonNode *pNode;
1332 const char *zPath;
1333 u32 i;
1334
1335 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001336 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001337 assert( x.nNode );
1338 for(i=1; i<(u32)argc; i++){
1339 zPath = (const char*)sqlite3_value_text(argv[i]);
1340 if( zPath==0 ) goto remove_done;
1341 pNode = jsonLookup(&x, zPath, 0, ctx);
1342 if( x.nErr ) goto remove_done;
1343 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1344 }
1345 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1346 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001347 }
drha7714022015-08-29 00:54:49 +00001348remove_done:
drh505ad2c2015-08-21 17:33:11 +00001349 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001350}
1351
1352/*
1353** json_replace(JSON, PATH, VALUE, ...)
1354**
1355** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001356** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001357*/
1358static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001359 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001360 int argc,
1361 sqlite3_value **argv
1362){
1363 JsonParse x; /* The parse */
1364 JsonNode *pNode;
1365 const char *zPath;
1366 u32 i;
1367
1368 if( argc<1 ) return;
1369 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001370 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001371 return;
1372 }
drhbc8f0922015-08-22 19:39:04 +00001373 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001374 assert( x.nNode );
1375 for(i=1; i<(u32)argc; i+=2){
1376 zPath = (const char*)sqlite3_value_text(argv[i]);
1377 pNode = jsonLookup(&x, zPath, 0, ctx);
1378 if( x.nErr ) goto replace_err;
1379 if( pNode ){
1380 pNode->jnFlags |= (u8)JNODE_REPLACE;
1381 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001382 }
drha8f39a92015-09-21 22:53:16 +00001383 }
1384 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1385 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1386 }else{
1387 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001388 }
drha7714022015-08-29 00:54:49 +00001389replace_err:
drh505ad2c2015-08-21 17:33:11 +00001390 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001391}
drh505ad2c2015-08-21 17:33:11 +00001392
drh52216ad2015-08-18 02:28:03 +00001393/*
1394** json_set(JSON, PATH, VALUE, ...)
1395**
1396** Set the value at PATH to VALUE. Create the PATH if it does not already
1397** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001398** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001399**
1400** json_insert(JSON, PATH, VALUE, ...)
1401**
1402** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001403** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001404*/
1405static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001406 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001407 int argc,
1408 sqlite3_value **argv
1409){
1410 JsonParse x; /* The parse */
1411 JsonNode *pNode;
1412 const char *zPath;
1413 u32 i;
1414 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001415 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001416
1417 if( argc<1 ) return;
1418 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001419 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001420 return;
1421 }
drhbc8f0922015-08-22 19:39:04 +00001422 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001423 assert( x.nNode );
1424 for(i=1; i<(u32)argc; i+=2){
1425 zPath = (const char*)sqlite3_value_text(argv[i]);
1426 bApnd = 0;
1427 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1428 if( x.oom ){
1429 sqlite3_result_error_nomem(ctx);
1430 goto jsonSetDone;
1431 }else if( x.nErr ){
1432 goto jsonSetDone;
1433 }else if( pNode && (bApnd || bIsSet) ){
1434 pNode->jnFlags |= (u8)JNODE_REPLACE;
1435 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001436 }
drha8f39a92015-09-21 22:53:16 +00001437 }
1438 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1439 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1440 }else{
1441 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001442 }
drhbc8f0922015-08-22 19:39:04 +00001443jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001444 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001445}
drh301eecc2015-08-17 20:14:19 +00001446
1447/*
drh987eb1f2015-08-17 15:17:37 +00001448** json_type(JSON)
1449** json_type(JSON, PATH)
1450**
drh3ad93bb2015-08-29 19:41:45 +00001451** Return the top-level "type" of a JSON string. Throw an error if
1452** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001453*/
1454static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001455 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001456 int argc,
1457 sqlite3_value **argv
1458){
1459 JsonParse x; /* The parse */
1460 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001461 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001462
drhbc8f0922015-08-22 19:39:04 +00001463 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001464 assert( x.nNode );
1465 if( argc==2 ){
1466 zPath = (const char*)sqlite3_value_text(argv[1]);
1467 pNode = jsonLookup(&x, zPath, 0, ctx);
1468 }else{
1469 pNode = x.aNode;
1470 }
1471 if( pNode ){
1472 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001473 }
drh505ad2c2015-08-21 17:33:11 +00001474 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001475}
drh5634cc02015-08-17 11:28:03 +00001476
drhbc8f0922015-08-22 19:39:04 +00001477/*
1478** json_valid(JSON)
1479**
drh3ad93bb2015-08-29 19:41:45 +00001480** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1481** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001482*/
1483static void jsonValidFunc(
1484 sqlite3_context *ctx,
1485 int argc,
1486 sqlite3_value **argv
1487){
1488 JsonParse x; /* The parse */
1489 int rc = 0;
1490
mistachkin16a93122015-09-11 18:05:01 +00001491 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001492 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001493 rc = 1;
1494 }
1495 jsonParseReset(&x);
1496 sqlite3_result_int(ctx, rc);
1497}
1498
drhd2975922015-08-29 17:22:33 +00001499#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001500/****************************************************************************
1501** The json_each virtual table
1502****************************************************************************/
1503typedef struct JsonEachCursor JsonEachCursor;
1504struct JsonEachCursor {
1505 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001506 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001507 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001508 u32 i; /* Index in sParse.aNode[] of current row */
1509 u32 iEnd; /* EOF when i equals or exceeds this value */
1510 u8 eType; /* Type of top-level element */
1511 u8 bRecursive; /* True for json_tree(). False for json_each() */
1512 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001513 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001514 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001515};
1516
1517/* Constructor for the json_each virtual table */
1518static int jsonEachConnect(
1519 sqlite3 *db,
1520 void *pAux,
1521 int argc, const char *const*argv,
1522 sqlite3_vtab **ppVtab,
1523 char **pzErr
1524){
1525 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001526 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001527
1528/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001529#define JEACH_KEY 0
1530#define JEACH_VALUE 1
1531#define JEACH_TYPE 2
1532#define JEACH_ATOM 3
1533#define JEACH_ID 4
1534#define JEACH_PARENT 5
1535#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001536#define JEACH_PATH 7
1537#define JEACH_JSON 8
1538#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001539
drh6fd5c1e2015-08-21 20:37:12 +00001540 UNUSED_PARAM(pzErr);
1541 UNUSED_PARAM(argv);
1542 UNUSED_PARAM(argc);
1543 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001544 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001545 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1546 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001547 if( rc==SQLITE_OK ){
1548 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1549 if( pNew==0 ) return SQLITE_NOMEM;
1550 memset(pNew, 0, sizeof(*pNew));
1551 }
1552 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001553}
1554
1555/* destructor for json_each virtual table */
1556static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1557 sqlite3_free(pVtab);
1558 return SQLITE_OK;
1559}
1560
drh505ad2c2015-08-21 17:33:11 +00001561/* constructor for a JsonEachCursor object for json_each(). */
1562static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001563 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001564
1565 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001566 pCur = sqlite3_malloc( sizeof(*pCur) );
1567 if( pCur==0 ) return SQLITE_NOMEM;
1568 memset(pCur, 0, sizeof(*pCur));
1569 *ppCursor = &pCur->base;
1570 return SQLITE_OK;
1571}
1572
drh505ad2c2015-08-21 17:33:11 +00001573/* constructor for a JsonEachCursor object for json_tree(). */
1574static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1575 int rc = jsonEachOpenEach(p, ppCursor);
1576 if( rc==SQLITE_OK ){
1577 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1578 pCur->bRecursive = 1;
1579 }
1580 return rc;
1581}
1582
drhcb6c6c62015-08-19 22:47:17 +00001583/* Reset a JsonEachCursor back to its original state. Free any memory
1584** held. */
1585static void jsonEachCursorReset(JsonEachCursor *p){
1586 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001587 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001588 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001589 p->iRowid = 0;
1590 p->i = 0;
1591 p->iEnd = 0;
1592 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001593 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001594 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001595}
1596
1597/* Destructor for a jsonEachCursor object */
1598static int jsonEachClose(sqlite3_vtab_cursor *cur){
1599 JsonEachCursor *p = (JsonEachCursor*)cur;
1600 jsonEachCursorReset(p);
1601 sqlite3_free(cur);
1602 return SQLITE_OK;
1603}
1604
1605/* Return TRUE if the jsonEachCursor object has been advanced off the end
1606** of the JSON object */
1607static int jsonEachEof(sqlite3_vtab_cursor *cur){
1608 JsonEachCursor *p = (JsonEachCursor*)cur;
1609 return p->i >= p->iEnd;
1610}
1611
drh505ad2c2015-08-21 17:33:11 +00001612/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001613static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001614 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001615 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001616 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1617 p->i++;
drh4af352d2015-08-21 20:02:48 +00001618 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001619 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001620 u32 iUp = p->sParse.aUp[p->i];
1621 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001622 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001623 if( pUp->eType==JSON_ARRAY ){
1624 if( iUp==p->i-1 ){
1625 pUp->u.iKey = 0;
1626 }else{
1627 pUp->u.iKey++;
1628 }
drh4af352d2015-08-21 20:02:48 +00001629 }
1630 }
drh505ad2c2015-08-21 17:33:11 +00001631 }else{
drh4af352d2015-08-21 20:02:48 +00001632 switch( p->eType ){
1633 case JSON_ARRAY: {
1634 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1635 p->iRowid++;
1636 break;
1637 }
1638 case JSON_OBJECT: {
1639 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1640 p->iRowid++;
1641 break;
1642 }
1643 default: {
1644 p->i = p->iEnd;
1645 break;
1646 }
drh505ad2c2015-08-21 17:33:11 +00001647 }
1648 }
1649 return SQLITE_OK;
1650}
1651
drh4af352d2015-08-21 20:02:48 +00001652/* Append the name of the path for element i to pStr
1653*/
1654static void jsonEachComputePath(
1655 JsonEachCursor *p, /* The cursor */
1656 JsonString *pStr, /* Write the path here */
1657 u32 i /* Path to this element */
1658){
1659 JsonNode *pNode, *pUp;
1660 u32 iUp;
1661 if( i==0 ){
1662 jsonAppendChar(pStr, '$');
1663 return;
drhcb6c6c62015-08-19 22:47:17 +00001664 }
drh4af352d2015-08-21 20:02:48 +00001665 iUp = p->sParse.aUp[i];
1666 jsonEachComputePath(p, pStr, iUp);
1667 pNode = &p->sParse.aNode[i];
1668 pUp = &p->sParse.aNode[iUp];
1669 if( pUp->eType==JSON_ARRAY ){
1670 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1671 }else{
1672 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001673 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001674 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001675 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001676 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1677 }
drhcb6c6c62015-08-19 22:47:17 +00001678}
1679
1680/* Return the value of a column */
1681static int jsonEachColumn(
1682 sqlite3_vtab_cursor *cur, /* The cursor */
1683 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1684 int i /* Which column to return */
1685){
1686 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001687 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001688 switch( i ){
1689 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001690 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001691 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001692 jsonReturn(pThis, ctx, 0);
1693 }else if( p->eType==JSON_ARRAY ){
1694 u32 iKey;
1695 if( p->bRecursive ){
1696 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001697 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001698 }else{
1699 iKey = p->iRowid;
1700 }
drh6fd5c1e2015-08-21 20:37:12 +00001701 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001702 }
1703 break;
1704 }
1705 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001706 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001707 jsonReturn(pThis, ctx, 0);
1708 break;
1709 }
1710 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001711 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001712 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1713 break;
1714 }
1715 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001716 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001717 if( pThis->eType>=JSON_ARRAY ) break;
1718 jsonReturn(pThis, ctx, 0);
1719 break;
1720 }
1721 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001722 sqlite3_result_int64(ctx,
1723 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001724 break;
1725 }
1726 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001727 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001728 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001729 }
1730 break;
1731 }
drh4af352d2015-08-21 20:02:48 +00001732 case JEACH_FULLKEY: {
1733 JsonString x;
1734 jsonInit(&x, ctx);
1735 if( p->bRecursive ){
1736 jsonEachComputePath(p, &x, p->i);
1737 }else{
drh383de692015-09-10 17:20:57 +00001738 if( p->zRoot ){
1739 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001740 }else{
1741 jsonAppendChar(&x, '$');
1742 }
1743 if( p->eType==JSON_ARRAY ){
1744 jsonPrintf(30, &x, "[%d]", p->iRowid);
1745 }else{
1746 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1747 }
1748 }
1749 jsonResult(&x);
1750 break;
1751 }
drhcb6c6c62015-08-19 22:47:17 +00001752 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001753 if( p->bRecursive ){
1754 JsonString x;
1755 jsonInit(&x, ctx);
1756 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1757 jsonResult(&x);
1758 break;
drh4af352d2015-08-21 20:02:48 +00001759 }
drh383de692015-09-10 17:20:57 +00001760 /* For json_each() path and root are the same so fall through
1761 ** into the root case */
1762 }
1763 case JEACH_ROOT: {
1764 const char *zRoot = p->zRoot;
1765 if( zRoot==0 ) zRoot = "$";
1766 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001767 break;
1768 }
drh3d1d2a92015-09-22 01:15:49 +00001769 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00001770 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001771 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1772 break;
1773 }
1774 }
1775 return SQLITE_OK;
1776}
1777
1778/* Return the current rowid value */
1779static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1780 JsonEachCursor *p = (JsonEachCursor*)cur;
1781 *pRowid = p->iRowid;
1782 return SQLITE_OK;
1783}
1784
1785/* The query strategy is to look for an equality constraint on the json
1786** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001787** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001788** and 0 otherwise.
1789*/
1790static int jsonEachBestIndex(
1791 sqlite3_vtab *tab,
1792 sqlite3_index_info *pIdxInfo
1793){
1794 int i;
1795 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001796 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001797 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001798
1799 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001800 pConstraint = pIdxInfo->aConstraint;
1801 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1802 if( pConstraint->usable==0 ) continue;
1803 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1804 switch( pConstraint->iColumn ){
1805 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001806 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001807 default: /* no-op */ break;
1808 }
1809 }
1810 if( jsonIdx<0 ){
1811 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001812 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001813 }else{
drh505ad2c2015-08-21 17:33:11 +00001814 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001815 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1816 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001817 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001818 pIdxInfo->idxNum = 1;
1819 }else{
drh383de692015-09-10 17:20:57 +00001820 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1821 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001822 pIdxInfo->idxNum = 3;
1823 }
1824 }
1825 return SQLITE_OK;
1826}
1827
1828/* Start a search on a new JSON string */
1829static int jsonEachFilter(
1830 sqlite3_vtab_cursor *cur,
1831 int idxNum, const char *idxStr,
1832 int argc, sqlite3_value **argv
1833){
1834 JsonEachCursor *p = (JsonEachCursor*)cur;
1835 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001836 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001837 sqlite3_int64 n;
1838
drh6fd5c1e2015-08-21 20:37:12 +00001839 UNUSED_PARAM(idxStr);
1840 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001841 jsonEachCursorReset(p);
1842 if( idxNum==0 ) return SQLITE_OK;
1843 z = (const char*)sqlite3_value_text(argv[0]);
1844 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001845 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001846 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001847 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001848 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001849 if( jsonParse(&p->sParse, 0, p->zJson) ){
1850 int rc = SQLITE_NOMEM;
1851 if( p->sParse.oom==0 ){
1852 sqlite3_free(cur->pVtab->zErrMsg);
1853 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1854 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1855 }
drhcb6c6c62015-08-19 22:47:17 +00001856 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001857 return rc;
1858 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1859 jsonEachCursorReset(p);
1860 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001861 }else{
drh95677942015-09-24 01:06:37 +00001862 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00001863 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001864 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001865 zRoot = (const char*)sqlite3_value_text(argv[1]);
1866 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001867 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001868 p->zRoot = sqlite3_malloc64( n+1 );
1869 if( p->zRoot==0 ) return SQLITE_NOMEM;
1870 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001871 if( zRoot[0]!='$' ){
1872 zErr = zRoot;
1873 }else{
1874 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1875 }
1876 if( zErr ){
drha7714022015-08-29 00:54:49 +00001877 sqlite3_free(cur->pVtab->zErrMsg);
1878 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001879 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001880 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1881 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001882 return SQLITE_OK;
1883 }
1884 }else{
1885 pNode = p->sParse.aNode;
1886 }
drh852944e2015-09-10 03:29:11 +00001887 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001888 p->eType = pNode->eType;
1889 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001890 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001891 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001892 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00001893 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00001894 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1895 p->i--;
1896 }
1897 }else{
1898 p->i++;
1899 }
drhcb6c6c62015-08-19 22:47:17 +00001900 }else{
1901 p->iEnd = p->i+1;
1902 }
1903 }
drha8f39a92015-09-21 22:53:16 +00001904 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001905}
1906
1907/* The methods of the json_each virtual table */
1908static sqlite3_module jsonEachModule = {
1909 0, /* iVersion */
1910 0, /* xCreate */
1911 jsonEachConnect, /* xConnect */
1912 jsonEachBestIndex, /* xBestIndex */
1913 jsonEachDisconnect, /* xDisconnect */
1914 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001915 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001916 jsonEachClose, /* xClose - close a cursor */
1917 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001918 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001919 jsonEachEof, /* xEof - check for end of scan */
1920 jsonEachColumn, /* xColumn - read data */
1921 jsonEachRowid, /* xRowid - read data */
1922 0, /* xUpdate */
1923 0, /* xBegin */
1924 0, /* xSync */
1925 0, /* xCommit */
1926 0, /* xRollback */
1927 0, /* xFindMethod */
1928 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001929 0, /* xSavepoint */
1930 0, /* xRelease */
1931 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001932};
1933
drh505ad2c2015-08-21 17:33:11 +00001934/* The methods of the json_tree virtual table. */
1935static sqlite3_module jsonTreeModule = {
1936 0, /* iVersion */
1937 0, /* xCreate */
1938 jsonEachConnect, /* xConnect */
1939 jsonEachBestIndex, /* xBestIndex */
1940 jsonEachDisconnect, /* xDisconnect */
1941 0, /* xDestroy */
1942 jsonEachOpenTree, /* xOpen - open a cursor */
1943 jsonEachClose, /* xClose - close a cursor */
1944 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001945 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001946 jsonEachEof, /* xEof - check for end of scan */
1947 jsonEachColumn, /* xColumn - read data */
1948 jsonEachRowid, /* xRowid - read data */
1949 0, /* xUpdate */
1950 0, /* xBegin */
1951 0, /* xSync */
1952 0, /* xCommit */
1953 0, /* xRollback */
1954 0, /* xFindMethod */
1955 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001956 0, /* xSavepoint */
1957 0, /* xRelease */
1958 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001959};
drhd2975922015-08-29 17:22:33 +00001960#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001961
1962/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00001963** The following routines are the only publically visible identifiers in this
1964** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00001965** functions and the virtual table implemented by this file.
1966****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001967
drh2f20e132015-09-26 17:44:59 +00001968int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00001969 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001970 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001971 static const struct {
1972 const char *zName;
1973 int nArg;
drh52216ad2015-08-18 02:28:03 +00001974 int flag;
drh5fa5c102015-08-12 16:49:40 +00001975 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1976 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001977 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001978 { "json_array", -1, 0, jsonArrayFunc },
1979 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1980 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001981 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001982 { "json_insert", -1, 0, jsonSetFunc },
1983 { "json_object", -1, 0, jsonObjectFunc },
1984 { "json_remove", -1, 0, jsonRemoveFunc },
1985 { "json_replace", -1, 0, jsonReplaceFunc },
1986 { "json_set", -1, 1, jsonSetFunc },
1987 { "json_type", 1, 0, jsonTypeFunc },
1988 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001989 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001990
drh301eecc2015-08-17 20:14:19 +00001991#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001992 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001993 { "json_parse", 1, 0, jsonParseFunc },
1994 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001995#endif
drh5fa5c102015-08-12 16:49:40 +00001996 };
drhd2975922015-08-29 17:22:33 +00001997#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00001998 static const struct {
1999 const char *zName;
2000 sqlite3_module *pModule;
2001 } aMod[] = {
2002 { "json_each", &jsonEachModule },
2003 { "json_tree", &jsonTreeModule },
2004 };
drhd2975922015-08-29 17:22:33 +00002005#endif
drh5fa5c102015-08-12 16:49:40 +00002006 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2007 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002008 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2009 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002010 aFunc[i].xFunc, 0, 0);
2011 }
drhd2975922015-08-29 17:22:33 +00002012#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002013 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2014 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002015 }
drhd2975922015-08-29 17:22:33 +00002016#endif
drh5fa5c102015-08-12 16:49:40 +00002017 return rc;
2018}
drh2f20e132015-09-26 17:44:59 +00002019
2020
2021#ifdef _WIN32
2022__declspec(dllexport)
2023#endif
2024int sqlite3_json_init(
2025 sqlite3 *db,
2026 char **pzErrMsg,
2027 const sqlite3_api_routines *pApi
2028){
2029 SQLITE_EXTENSION_INIT2(pApi);
2030 (void)pzErrMsg; /* Unused parameter */
2031 return sqlite3Json1Init(db);
2032}
drh50065652015-10-08 19:29:18 +00002033#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */