blob: c968011eea0b0597ffef9245425676680664c895 [file] [log] [blame]
drh5fa5c102015-08-12 16:49:40 +00001/*
2** 2015-08-12
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This SQLite extension implements JSON functions. The interface is
14** modeled after MySQL JSON functions:
15**
16** https://dev.mysql.com/doc/refman/5.7/en/json.html
17**
drh5634cc02015-08-17 11:28:03 +000018** For the time being, all JSON is stored as pure text. (We might add
19** a JSONB type in the future which stores a binary encoding of JSON in
drhcb6c6c62015-08-19 22:47:17 +000020** a BLOB, but there is no support for JSONB in the current implementation.
21** This implementation parses JSON text at 250 MB/s, so it is hard to see
22** how JSONB might improve on that.)
drh5fa5c102015-08-12 16:49:40 +000023*/
drh50065652015-10-08 19:29:18 +000024#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
drhf2df7e72015-08-28 20:07:40 +000025#if !defined(_SQLITEINT_H_)
drh5fa5c102015-08-12 16:49:40 +000026#include "sqlite3ext.h"
drhf2df7e72015-08-28 20:07:40 +000027#endif
drh5fa5c102015-08-12 16:49:40 +000028SQLITE_EXTENSION_INIT1
29#include <assert.h>
30#include <string.h>
drha0882fa2015-10-09 20:40:44 +000031#include <ctype.h> /* amalgamator: keep */
drh987eb1f2015-08-17 15:17:37 +000032#include <stdlib.h>
drh4af352d2015-08-21 20:02:48 +000033#include <stdarg.h>
drh5fa5c102015-08-12 16:49:40 +000034
drh6fd5c1e2015-08-21 20:37:12 +000035#define UNUSED_PARAM(X) (void)(X)
36
drh8deb4b82015-10-09 18:21:43 +000037#ifndef LARGEST_INT64
38# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
39# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
40#endif
41
dan2e8f5512015-09-17 17:21:09 +000042/*
43** Versions of isspace(), isalnum() and isdigit() to which it is safe
44** to pass signed char values.
45*/
dan2e8f5512015-09-17 17:21:09 +000046#define safe_isdigit(x) isdigit((unsigned char)(x))
47#define safe_isalnum(x) isalnum((unsigned char)(x))
48
drh95677942015-09-24 01:06:37 +000049/*
50** Growing our own isspace() routine this way is twice as fast as
51** the library isspace() function, resulting in a 7% overall performance
52** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
53*/
54static const char jsonIsSpace[] = {
55 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0,
56 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
57 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
58 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
59 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
66 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
67 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
69 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71};
72#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
73
drh9a4718f2015-10-10 14:00:37 +000074#ifndef SQLITE_AMALGAMATION
75 /* Unsigned integer types. These are already defined in the sqliteInt.h,
76 ** but the definitions need to be repeated for separate compilation. */
77 typedef sqlite3_uint64 u64;
78 typedef unsigned int u32;
79 typedef unsigned char u8;
80#endif
drh5fa5c102015-08-12 16:49:40 +000081
drh52216ad2015-08-18 02:28:03 +000082/* Objects */
drh505ad2c2015-08-21 17:33:11 +000083typedef struct JsonString JsonString;
drh52216ad2015-08-18 02:28:03 +000084typedef struct JsonNode JsonNode;
85typedef struct JsonParse JsonParse;
86
drh5634cc02015-08-17 11:28:03 +000087/* An instance of this object represents a JSON string
88** under construction. Really, this is a generic string accumulator
89** that can be and is used to create strings other than JSON.
drh5fa5c102015-08-12 16:49:40 +000090*/
drh505ad2c2015-08-21 17:33:11 +000091struct JsonString {
drh5fa5c102015-08-12 16:49:40 +000092 sqlite3_context *pCtx; /* Function context - put error messages here */
drh5634cc02015-08-17 11:28:03 +000093 char *zBuf; /* Append JSON content here */
drh5fa5c102015-08-12 16:49:40 +000094 u64 nAlloc; /* Bytes of storage available in zBuf[] */
95 u64 nUsed; /* Bytes of zBuf[] currently used */
96 u8 bStatic; /* True if zBuf is static space */
drhd0960592015-08-17 21:22:32 +000097 u8 bErr; /* True if an error has been encountered */
drh5fa5c102015-08-12 16:49:40 +000098 char zSpace[100]; /* Initial static space */
99};
100
drhe9c37f32015-08-15 21:25:36 +0000101/* JSON type values
drhbd0621b2015-08-13 13:54:59 +0000102*/
drhe9c37f32015-08-15 21:25:36 +0000103#define JSON_NULL 0
104#define JSON_TRUE 1
105#define JSON_FALSE 2
106#define JSON_INT 3
107#define JSON_REAL 4
108#define JSON_STRING 5
109#define JSON_ARRAY 6
110#define JSON_OBJECT 7
111
drhf5ddb9c2015-09-11 00:06:41 +0000112/* The "subtype" set for JSON values */
113#define JSON_SUBTYPE 74 /* Ascii for "J" */
114
drh987eb1f2015-08-17 15:17:37 +0000115/*
116** Names of the various JSON types:
117*/
118static const char * const jsonType[] = {
119 "null", "true", "false", "integer", "real", "text", "array", "object"
120};
121
drh301eecc2015-08-17 20:14:19 +0000122/* Bit values for the JsonNode.jnFlag field
123*/
124#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
125#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
126#define JNODE_REMOVE 0x04 /* Do not output */
drhd0960592015-08-17 21:22:32 +0000127#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
drh52216ad2015-08-18 02:28:03 +0000128#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
drhf5ddb9c2015-09-11 00:06:41 +0000129#define JNODE_LABEL 0x20 /* Is a label of an object */
drh301eecc2015-08-17 20:14:19 +0000130
drh987eb1f2015-08-17 15:17:37 +0000131
drhe9c37f32015-08-15 21:25:36 +0000132/* A single node of parsed JSON
133*/
drhe9c37f32015-08-15 21:25:36 +0000134struct JsonNode {
drh5634cc02015-08-17 11:28:03 +0000135 u8 eType; /* One of the JSON_ type values */
drh301eecc2015-08-17 20:14:19 +0000136 u8 jnFlags; /* JNODE flags */
drhd0960592015-08-17 21:22:32 +0000137 u8 iVal; /* Replacement value when JNODE_REPLACE */
drhe9c37f32015-08-15 21:25:36 +0000138 u32 n; /* Bytes of content, or number of sub-nodes */
drh52216ad2015-08-18 02:28:03 +0000139 union {
drh0042a972015-08-18 12:59:58 +0000140 const char *zJContent; /* Content for INT, REAL, and STRING */
141 u32 iAppend; /* More terms for ARRAY and OBJECT */
drh505ad2c2015-08-21 17:33:11 +0000142 u32 iKey; /* Key for ARRAY objects in json_tree() */
drh52216ad2015-08-18 02:28:03 +0000143 } u;
drhe9c37f32015-08-15 21:25:36 +0000144};
145
146/* A completely parsed JSON string
147*/
drhe9c37f32015-08-15 21:25:36 +0000148struct JsonParse {
149 u32 nNode; /* Number of slots of aNode[] used */
150 u32 nAlloc; /* Number of slots of aNode[] allocated */
151 JsonNode *aNode; /* Array of nodes containing the parse */
152 const char *zJson; /* Original JSON string */
drh505ad2c2015-08-21 17:33:11 +0000153 u32 *aUp; /* Index of parent of each node */
drhe9c37f32015-08-15 21:25:36 +0000154 u8 oom; /* Set to true if out of memory */
drha7714022015-08-29 00:54:49 +0000155 u8 nErr; /* Number of errors seen */
drhe9c37f32015-08-15 21:25:36 +0000156};
157
drh505ad2c2015-08-21 17:33:11 +0000158/**************************************************************************
159** Utility routines for dealing with JsonString objects
160**************************************************************************/
drh301eecc2015-08-17 20:14:19 +0000161
drh505ad2c2015-08-21 17:33:11 +0000162/* Set the JsonString object to an empty string
drh5fa5c102015-08-12 16:49:40 +0000163*/
drh505ad2c2015-08-21 17:33:11 +0000164static void jsonZero(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000165 p->zBuf = p->zSpace;
166 p->nAlloc = sizeof(p->zSpace);
167 p->nUsed = 0;
168 p->bStatic = 1;
169}
170
drh505ad2c2015-08-21 17:33:11 +0000171/* Initialize the JsonString object
drh5fa5c102015-08-12 16:49:40 +0000172*/
drh505ad2c2015-08-21 17:33:11 +0000173static void jsonInit(JsonString *p, sqlite3_context *pCtx){
drh5fa5c102015-08-12 16:49:40 +0000174 p->pCtx = pCtx;
drhd0960592015-08-17 21:22:32 +0000175 p->bErr = 0;
drh5fa5c102015-08-12 16:49:40 +0000176 jsonZero(p);
177}
178
179
drh505ad2c2015-08-21 17:33:11 +0000180/* Free all allocated memory and reset the JsonString object back to its
drh5fa5c102015-08-12 16:49:40 +0000181** initial state.
182*/
drh505ad2c2015-08-21 17:33:11 +0000183static void jsonReset(JsonString *p){
drh5fa5c102015-08-12 16:49:40 +0000184 if( !p->bStatic ) sqlite3_free(p->zBuf);
185 jsonZero(p);
186}
187
188
189/* Report an out-of-memory (OOM) condition
190*/
drh505ad2c2015-08-21 17:33:11 +0000191static void jsonOom(JsonString *p){
drh3d1d2a92015-09-22 01:15:49 +0000192 p->bErr = 1;
193 sqlite3_result_error_nomem(p->pCtx);
194 jsonReset(p);
drh5fa5c102015-08-12 16:49:40 +0000195}
196
197/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
198** Return zero on success. Return non-zero on an OOM error
199*/
drh505ad2c2015-08-21 17:33:11 +0000200static int jsonGrow(JsonString *p, u32 N){
drh301eecc2015-08-17 20:14:19 +0000201 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
drh5fa5c102015-08-12 16:49:40 +0000202 char *zNew;
203 if( p->bStatic ){
drhd0960592015-08-17 21:22:32 +0000204 if( p->bErr ) return 1;
drh5fa5c102015-08-12 16:49:40 +0000205 zNew = sqlite3_malloc64(nTotal);
206 if( zNew==0 ){
207 jsonOom(p);
208 return SQLITE_NOMEM;
209 }
drh6fd5c1e2015-08-21 20:37:12 +0000210 memcpy(zNew, p->zBuf, (size_t)p->nUsed);
drh5fa5c102015-08-12 16:49:40 +0000211 p->zBuf = zNew;
212 p->bStatic = 0;
213 }else{
214 zNew = sqlite3_realloc64(p->zBuf, nTotal);
215 if( zNew==0 ){
216 jsonOom(p);
217 return SQLITE_NOMEM;
218 }
219 p->zBuf = zNew;
220 }
221 p->nAlloc = nTotal;
222 return SQLITE_OK;
223}
224
drh505ad2c2015-08-21 17:33:11 +0000225/* Append N bytes from zIn onto the end of the JsonString string.
drh5fa5c102015-08-12 16:49:40 +0000226*/
drh505ad2c2015-08-21 17:33:11 +0000227static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000228 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
229 memcpy(p->zBuf+p->nUsed, zIn, N);
230 p->nUsed += N;
231}
232
drh4af352d2015-08-21 20:02:48 +0000233/* Append formatted text (not to exceed N bytes) to the JsonString.
234*/
235static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
236 va_list ap;
237 if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
238 va_start(ap, zFormat);
239 sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
240 va_end(ap);
241 p->nUsed += (int)strlen(p->zBuf+p->nUsed);
242}
243
drh5634cc02015-08-17 11:28:03 +0000244/* Append a single character
245*/
drh505ad2c2015-08-21 17:33:11 +0000246static void jsonAppendChar(JsonString *p, char c){
drh5634cc02015-08-17 11:28:03 +0000247 if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
248 p->zBuf[p->nUsed++] = c;
249}
250
drh301eecc2015-08-17 20:14:19 +0000251/* Append a comma separator to the output buffer, if the previous
252** character is not '[' or '{'.
253*/
drh505ad2c2015-08-21 17:33:11 +0000254static void jsonAppendSeparator(JsonString *p){
drh301eecc2015-08-17 20:14:19 +0000255 char c;
256 if( p->nUsed==0 ) return;
257 c = p->zBuf[p->nUsed-1];
258 if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
259}
260
drh505ad2c2015-08-21 17:33:11 +0000261/* Append the N-byte string in zIn to the end of the JsonString string
drh5fa5c102015-08-12 16:49:40 +0000262** under construction. Enclose the string in "..." and escape
263** any double-quotes or backslash characters contained within the
264** string.
265*/
drh505ad2c2015-08-21 17:33:11 +0000266static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
drh5fa5c102015-08-12 16:49:40 +0000267 u32 i;
268 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
269 p->zBuf[p->nUsed++] = '"';
270 for(i=0; i<N; i++){
271 char c = zIn[i];
272 if( c=='"' || c=='\\' ){
drh4977ccf2015-09-19 11:57:26 +0000273 if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
drh5fa5c102015-08-12 16:49:40 +0000274 p->zBuf[p->nUsed++] = '\\';
275 }
276 p->zBuf[p->nUsed++] = c;
277 }
278 p->zBuf[p->nUsed++] = '"';
drh4977ccf2015-09-19 11:57:26 +0000279 assert( p->nUsed<p->nAlloc );
drh5fa5c102015-08-12 16:49:40 +0000280}
281
drhd0960592015-08-17 21:22:32 +0000282/*
283** Append a function parameter value to the JSON string under
284** construction.
285*/
286static void jsonAppendValue(
drh505ad2c2015-08-21 17:33:11 +0000287 JsonString *p, /* Append to this JSON string */
drhf5ddb9c2015-09-11 00:06:41 +0000288 sqlite3_value *pValue /* Value to append */
drhd0960592015-08-17 21:22:32 +0000289){
290 switch( sqlite3_value_type(pValue) ){
291 case SQLITE_NULL: {
292 jsonAppendRaw(p, "null", 4);
293 break;
294 }
295 case SQLITE_INTEGER:
296 case SQLITE_FLOAT: {
297 const char *z = (const char*)sqlite3_value_text(pValue);
298 u32 n = (u32)sqlite3_value_bytes(pValue);
299 jsonAppendRaw(p, z, n);
300 break;
301 }
302 case SQLITE_TEXT: {
303 const char *z = (const char*)sqlite3_value_text(pValue);
304 u32 n = (u32)sqlite3_value_bytes(pValue);
drhf5ddb9c2015-09-11 00:06:41 +0000305 if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
drhecb5fed2015-08-28 03:33:50 +0000306 jsonAppendRaw(p, z, n);
307 }else{
308 jsonAppendString(p, z, n);
309 }
drhd0960592015-08-17 21:22:32 +0000310 break;
311 }
312 default: {
313 if( p->bErr==0 ){
314 sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
315 p->bErr = 1;
316 jsonReset(p);
317 }
318 break;
319 }
320 }
321}
322
323
drhbd0621b2015-08-13 13:54:59 +0000324/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000325*/
drh505ad2c2015-08-21 17:33:11 +0000326static void jsonResult(JsonString *p){
drhd0960592015-08-17 21:22:32 +0000327 if( p->bErr==0 ){
drh5fa5c102015-08-12 16:49:40 +0000328 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
329 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
330 SQLITE_UTF8);
331 jsonZero(p);
332 }
333 assert( p->bStatic );
334}
335
drh505ad2c2015-08-21 17:33:11 +0000336/**************************************************************************
337** Utility routines for dealing with JsonNode and JsonParse objects
338**************************************************************************/
339
340/*
341** Return the number of consecutive JsonNode slots need to represent
342** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
343** OBJECT types, the number might be larger.
344**
345** Appended elements are not counted. The value returned is the number
346** by which the JsonNode counter should increment in order to go to the
347** next peer value.
348*/
349static u32 jsonNodeSize(JsonNode *pNode){
350 return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
351}
352
353/*
354** Reclaim all memory allocated by a JsonParse object. But do not
355** delete the JsonParse object itself.
356*/
357static void jsonParseReset(JsonParse *pParse){
358 sqlite3_free(pParse->aNode);
359 pParse->aNode = 0;
360 pParse->nNode = 0;
361 pParse->nAlloc = 0;
362 sqlite3_free(pParse->aUp);
363 pParse->aUp = 0;
364}
365
drh5634cc02015-08-17 11:28:03 +0000366/*
367** Convert the JsonNode pNode into a pure JSON string and
368** append to pOut. Subsubstructure is also included. Return
369** the number of JsonNode objects that are encoded.
drhbd0621b2015-08-13 13:54:59 +0000370*/
drh52216ad2015-08-18 02:28:03 +0000371static void jsonRenderNode(
drhd0960592015-08-17 21:22:32 +0000372 JsonNode *pNode, /* The node to render */
drh505ad2c2015-08-21 17:33:11 +0000373 JsonString *pOut, /* Write JSON here */
drhd0960592015-08-17 21:22:32 +0000374 sqlite3_value **aReplace /* Replacement values */
375){
drh5634cc02015-08-17 11:28:03 +0000376 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000377 default: {
378 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000379 jsonAppendRaw(pOut, "null", 4);
380 break;
381 }
382 case JSON_TRUE: {
383 jsonAppendRaw(pOut, "true", 4);
384 break;
385 }
386 case JSON_FALSE: {
387 jsonAppendRaw(pOut, "false", 5);
388 break;
389 }
390 case JSON_STRING: {
drh301eecc2015-08-17 20:14:19 +0000391 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000392 jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000393 break;
394 }
395 /* Fall through into the next case */
396 }
397 case JSON_REAL:
398 case JSON_INT: {
drh52216ad2015-08-18 02:28:03 +0000399 jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
drh5634cc02015-08-17 11:28:03 +0000400 break;
401 }
402 case JSON_ARRAY: {
drh52216ad2015-08-18 02:28:03 +0000403 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000404 jsonAppendChar(pOut, '[');
drh52216ad2015-08-18 02:28:03 +0000405 for(;;){
406 while( j<=pNode->n ){
407 if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
408 if( pNode[j].jnFlags & JNODE_REPLACE ){
409 jsonAppendSeparator(pOut);
drhf5ddb9c2015-09-11 00:06:41 +0000410 jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
drh52216ad2015-08-18 02:28:03 +0000411 }
412 }else{
drhd0960592015-08-17 21:22:32 +0000413 jsonAppendSeparator(pOut);
drh52216ad2015-08-18 02:28:03 +0000414 jsonRenderNode(&pNode[j], pOut, aReplace);
drhd0960592015-08-17 21:22:32 +0000415 }
drh505ad2c2015-08-21 17:33:11 +0000416 j += jsonNodeSize(&pNode[j]);
drh301eecc2015-08-17 20:14:19 +0000417 }
drh52216ad2015-08-18 02:28:03 +0000418 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
419 pNode = &pNode[pNode->u.iAppend];
420 j = 1;
drh5634cc02015-08-17 11:28:03 +0000421 }
422 jsonAppendChar(pOut, ']');
423 break;
424 }
425 case JSON_OBJECT: {
drh52216ad2015-08-18 02:28:03 +0000426 u32 j = 1;
drh5634cc02015-08-17 11:28:03 +0000427 jsonAppendChar(pOut, '{');
drh52216ad2015-08-18 02:28:03 +0000428 for(;;){
429 while( j<=pNode->n ){
430 if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
431 jsonAppendSeparator(pOut);
432 jsonRenderNode(&pNode[j], pOut, aReplace);
433 jsonAppendChar(pOut, ':');
434 if( pNode[j+1].jnFlags & JNODE_REPLACE ){
drhf5ddb9c2015-09-11 00:06:41 +0000435 jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
drh52216ad2015-08-18 02:28:03 +0000436 }else{
437 jsonRenderNode(&pNode[j+1], pOut, aReplace);
438 }
drhd0960592015-08-17 21:22:32 +0000439 }
drh505ad2c2015-08-21 17:33:11 +0000440 j += 1 + jsonNodeSize(&pNode[j+1]);
drh301eecc2015-08-17 20:14:19 +0000441 }
drh52216ad2015-08-18 02:28:03 +0000442 if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
443 pNode = &pNode[pNode->u.iAppend];
444 j = 1;
drh5634cc02015-08-17 11:28:03 +0000445 }
446 jsonAppendChar(pOut, '}');
447 break;
448 }
drhbd0621b2015-08-13 13:54:59 +0000449 }
drh5634cc02015-08-17 11:28:03 +0000450}
451
452/*
drhf2df7e72015-08-28 20:07:40 +0000453** Return a JsonNode and all its descendents as a JSON string.
454*/
455static void jsonReturnJson(
456 JsonNode *pNode, /* Node to return */
457 sqlite3_context *pCtx, /* Return value for this function */
458 sqlite3_value **aReplace /* Array of replacement values */
459){
460 JsonString s;
461 jsonInit(&s, pCtx);
462 jsonRenderNode(pNode, &s, aReplace);
463 jsonResult(&s);
drhf5ddb9c2015-09-11 00:06:41 +0000464 sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
drhf2df7e72015-08-28 20:07:40 +0000465}
466
467/*
drh5634cc02015-08-17 11:28:03 +0000468** Make the JsonNode the return value of the function.
469*/
drhd0960592015-08-17 21:22:32 +0000470static void jsonReturn(
471 JsonNode *pNode, /* Node to return */
472 sqlite3_context *pCtx, /* Return value for this function */
473 sqlite3_value **aReplace /* Array of replacement values */
474){
drh5634cc02015-08-17 11:28:03 +0000475 switch( pNode->eType ){
drha8f39a92015-09-21 22:53:16 +0000476 default: {
477 assert( pNode->eType==JSON_NULL );
drh5634cc02015-08-17 11:28:03 +0000478 sqlite3_result_null(pCtx);
479 break;
480 }
481 case JSON_TRUE: {
482 sqlite3_result_int(pCtx, 1);
483 break;
484 }
485 case JSON_FALSE: {
486 sqlite3_result_int(pCtx, 0);
487 break;
488 }
drh987eb1f2015-08-17 15:17:37 +0000489 case JSON_INT: {
490 sqlite3_int64 i = 0;
drh52216ad2015-08-18 02:28:03 +0000491 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000492 if( z[0]=='-' ){ z++; }
drh8deb4b82015-10-09 18:21:43 +0000493 while( z[0]>='0' && z[0]<='9' ){
494 unsigned v = *(z++) - '0';
495 if( i>=LARGEST_INT64/10 ){
drha0882fa2015-10-09 20:40:44 +0000496 if( i>LARGEST_INT64/10 ) goto int_as_real;
drh8deb4b82015-10-09 18:21:43 +0000497 if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
498 if( v==9 ) goto int_as_real;
499 if( v==8 ){
500 if( pNode->u.zJContent[0]=='-' ){
501 sqlite3_result_int64(pCtx, SMALLEST_INT64);
502 goto int_done;
503 }else{
504 goto int_as_real;
505 }
506 }
507 }
508 i = i*10 + v;
509 }
drh52216ad2015-08-18 02:28:03 +0000510 if( pNode->u.zJContent[0]=='-' ){ i = -i; }
drh987eb1f2015-08-17 15:17:37 +0000511 sqlite3_result_int64(pCtx, i);
drh8deb4b82015-10-09 18:21:43 +0000512 int_done:
513 break;
514 int_as_real: /* fall through to real */;
515 }
516 case JSON_REAL: {
517 double r = strtod(pNode->u.zJContent, 0);
518 sqlite3_result_double(pCtx, r);
drh987eb1f2015-08-17 15:17:37 +0000519 break;
520 }
drh5634cc02015-08-17 11:28:03 +0000521 case JSON_STRING: {
drha8f39a92015-09-21 22:53:16 +0000522#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
523 ** json_insert() and json_replace() and those routines do not
524 ** call jsonReturn() */
drh301eecc2015-08-17 20:14:19 +0000525 if( pNode->jnFlags & JNODE_RAW ){
drh52216ad2015-08-18 02:28:03 +0000526 sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
527 SQLITE_TRANSIENT);
drha8f39a92015-09-21 22:53:16 +0000528 }else
529#endif
530 assert( (pNode->jnFlags & JNODE_RAW)==0 );
531 if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
drh987eb1f2015-08-17 15:17:37 +0000532 /* JSON formatted without any backslash-escapes */
drh52216ad2015-08-18 02:28:03 +0000533 sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
drh987eb1f2015-08-17 15:17:37 +0000534 SQLITE_TRANSIENT);
drh5634cc02015-08-17 11:28:03 +0000535 }else{
536 /* Translate JSON formatted string into raw text */
drh987eb1f2015-08-17 15:17:37 +0000537 u32 i;
538 u32 n = pNode->n;
drh52216ad2015-08-18 02:28:03 +0000539 const char *z = pNode->u.zJContent;
drh987eb1f2015-08-17 15:17:37 +0000540 char *zOut;
541 u32 j;
542 zOut = sqlite3_malloc( n+1 );
543 if( zOut==0 ){
544 sqlite3_result_error_nomem(pCtx);
545 break;
546 }
547 for(i=1, j=0; i<n-1; i++){
548 char c = z[i];
drh80d87402015-08-24 12:42:41 +0000549 if( c!='\\' ){
drh987eb1f2015-08-17 15:17:37 +0000550 zOut[j++] = c;
551 }else{
552 c = z[++i];
drh80d87402015-08-24 12:42:41 +0000553 if( c=='u' ){
drh987eb1f2015-08-17 15:17:37 +0000554 u32 v = 0, k;
drh80d87402015-08-24 12:42:41 +0000555 for(k=0; k<4 && i<n-2; i++, k++){
drh8784eca2015-08-23 02:42:30 +0000556 c = z[i+1];
drh987eb1f2015-08-17 15:17:37 +0000557 if( c>='0' && c<='9' ) v = v*16 + c - '0';
558 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
559 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
560 else break;
drh987eb1f2015-08-17 15:17:37 +0000561 }
drh80d87402015-08-24 12:42:41 +0000562 if( v==0 ) break;
drh987eb1f2015-08-17 15:17:37 +0000563 if( v<=0x7f ){
mistachkin16a93122015-09-11 18:05:01 +0000564 zOut[j++] = (char)v;
drh987eb1f2015-08-17 15:17:37 +0000565 }else if( v<=0x7ff ){
mistachkin16a93122015-09-11 18:05:01 +0000566 zOut[j++] = (char)(0xc0 | (v>>6));
drh987eb1f2015-08-17 15:17:37 +0000567 zOut[j++] = 0x80 | (v&0x3f);
drh80d87402015-08-24 12:42:41 +0000568 }else{
mistachkin16a93122015-09-11 18:05:01 +0000569 zOut[j++] = (char)(0xe0 | (v>>12));
drh987eb1f2015-08-17 15:17:37 +0000570 zOut[j++] = 0x80 | ((v>>6)&0x3f);
571 zOut[j++] = 0x80 | (v&0x3f);
drh987eb1f2015-08-17 15:17:37 +0000572 }
573 }else{
574 if( c=='b' ){
575 c = '\b';
576 }else if( c=='f' ){
577 c = '\f';
578 }else if( c=='n' ){
579 c = '\n';
580 }else if( c=='r' ){
581 c = '\r';
582 }else if( c=='t' ){
583 c = '\t';
584 }
585 zOut[j++] = c;
586 }
587 }
588 }
589 zOut[j] = 0;
590 sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
drh5634cc02015-08-17 11:28:03 +0000591 }
592 break;
593 }
594 case JSON_ARRAY:
595 case JSON_OBJECT: {
drhf2df7e72015-08-28 20:07:40 +0000596 jsonReturnJson(pNode, pCtx, aReplace);
drh5634cc02015-08-17 11:28:03 +0000597 break;
598 }
599 }
drhbd0621b2015-08-13 13:54:59 +0000600}
601
drh95677942015-09-24 01:06:37 +0000602/* Forward reference */
603static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
604
605/*
606** A macro to hint to the compiler that a function should not be
607** inlined.
608*/
609#if defined(__GNUC__)
610# define JSON_NOINLINE __attribute__((noinline))
611#elif defined(_MSC_VER) && _MSC_VER>=1310
612# define JSON_NOINLINE __declspec(noinline)
613#else
614# define JSON_NOINLINE
615#endif
616
617
618static JSON_NOINLINE int jsonParseAddNodeExpand(
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 u32 nNew;
625 JsonNode *pNew;
626 assert( pParse->nNode>=pParse->nAlloc );
627 if( pParse->oom ) return -1;
628 nNew = pParse->nAlloc*2 + 10;
629 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
630 if( pNew==0 ){
631 pParse->oom = 1;
632 return -1;
633 }
634 pParse->nAlloc = nNew;
635 pParse->aNode = pNew;
636 assert( pParse->nNode<pParse->nAlloc );
637 return jsonParseAddNode(pParse, eType, n, zContent);
638}
639
drh5fa5c102015-08-12 16:49:40 +0000640/*
drhe9c37f32015-08-15 21:25:36 +0000641** Create a new JsonNode instance based on the arguments and append that
642** instance to the JsonParse. Return the index in pParse->aNode[] of the
643** new node, or -1 if a memory allocation fails.
644*/
645static int jsonParseAddNode(
646 JsonParse *pParse, /* Append the node to this object */
647 u32 eType, /* Node type */
648 u32 n, /* Content size or sub-node count */
649 const char *zContent /* Content */
650){
651 JsonNode *p;
652 if( pParse->nNode>=pParse->nAlloc ){
drh95677942015-09-24 01:06:37 +0000653 return jsonParseAddNodeExpand(pParse, eType, n, zContent);
drhe9c37f32015-08-15 21:25:36 +0000654 }
655 p = &pParse->aNode[pParse->nNode];
drh5634cc02015-08-17 11:28:03 +0000656 p->eType = (u8)eType;
drh301eecc2015-08-17 20:14:19 +0000657 p->jnFlags = 0;
drhd0960592015-08-17 21:22:32 +0000658 p->iVal = 0;
drhe9c37f32015-08-15 21:25:36 +0000659 p->n = n;
drh52216ad2015-08-18 02:28:03 +0000660 p->u.zJContent = zContent;
drhe9c37f32015-08-15 21:25:36 +0000661 return pParse->nNode++;
662}
663
664/*
665** Parse a single JSON value which begins at pParse->zJson[i]. Return the
666** index of the first character past the end of the value parsed.
667**
668** Return negative for a syntax error. Special cases: return -2 if the
669** first non-whitespace character is '}' and return -3 if the first
670** non-whitespace character is ']'.
671*/
672static int jsonParseValue(JsonParse *pParse, u32 i){
673 char c;
674 u32 j;
drhbc8f0922015-08-22 19:39:04 +0000675 int iThis;
drhe9c37f32015-08-15 21:25:36 +0000676 int x;
drh852944e2015-09-10 03:29:11 +0000677 JsonNode *pNode;
dan2e8f5512015-09-17 17:21:09 +0000678 while( safe_isspace(pParse->zJson[i]) ){ i++; }
drh8cb15cc2015-09-24 01:40:45 +0000679 if( (c = pParse->zJson[i])=='{' ){
drhe9c37f32015-08-15 21:25:36 +0000680 /* Parse object */
681 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000682 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000683 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000684 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000685 x = jsonParseValue(pParse, j);
686 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000687 if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000688 return -1;
689 }
drhbe9474e2015-08-22 03:05:54 +0000690 if( pParse->oom ) return -1;
drh852944e2015-09-10 03:29:11 +0000691 pNode = &pParse->aNode[pParse->nNode-1];
692 if( pNode->eType!=JSON_STRING ) return -1;
693 pNode->jnFlags |= JNODE_LABEL;
drhe9c37f32015-08-15 21:25:36 +0000694 j = x;
dan2e8f5512015-09-17 17:21:09 +0000695 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000696 if( pParse->zJson[j]!=':' ) return -1;
697 j++;
698 x = jsonParseValue(pParse, j);
699 if( x<0 ) return -1;
700 j = x;
dan2e8f5512015-09-17 17:21:09 +0000701 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000702 c = pParse->zJson[j];
703 if( c==',' ) continue;
704 if( c!='}' ) return -1;
705 break;
706 }
drhbc8f0922015-08-22 19:39:04 +0000707 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000708 return j+1;
709 }else if( c=='[' ){
710 /* Parse array */
711 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
drhbc8f0922015-08-22 19:39:04 +0000712 if( iThis<0 ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000713 for(j=i+1;;j++){
dan2e8f5512015-09-17 17:21:09 +0000714 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000715 x = jsonParseValue(pParse, j);
716 if( x<0 ){
drhf27cd1f2015-09-23 01:10:29 +0000717 if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
drhe9c37f32015-08-15 21:25:36 +0000718 return -1;
719 }
720 j = x;
dan2e8f5512015-09-17 17:21:09 +0000721 while( safe_isspace(pParse->zJson[j]) ){ j++; }
drhe9c37f32015-08-15 21:25:36 +0000722 c = pParse->zJson[j];
723 if( c==',' ) continue;
724 if( c!=']' ) return -1;
725 break;
726 }
drhbc8f0922015-08-22 19:39:04 +0000727 pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
drhe9c37f32015-08-15 21:25:36 +0000728 return j+1;
729 }else if( c=='"' ){
730 /* Parse string */
drh301eecc2015-08-17 20:14:19 +0000731 u8 jnFlags = 0;
drhe9c37f32015-08-15 21:25:36 +0000732 j = i+1;
733 for(;;){
734 c = pParse->zJson[j];
735 if( c==0 ) return -1;
736 if( c=='\\' ){
737 c = pParse->zJson[++j];
738 if( c==0 ) return -1;
drh301eecc2015-08-17 20:14:19 +0000739 jnFlags = JNODE_ESCAPE;
drhe9c37f32015-08-15 21:25:36 +0000740 }else if( c=='"' ){
741 break;
742 }
743 j++;
744 }
745 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
drhbe9474e2015-08-22 03:05:54 +0000746 if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
drhe9c37f32015-08-15 21:25:36 +0000747 return j+1;
748 }else if( c=='n'
749 && strncmp(pParse->zJson+i,"null",4)==0
dan2e8f5512015-09-17 17:21:09 +0000750 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000751 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
752 return i+4;
753 }else if( c=='t'
754 && strncmp(pParse->zJson+i,"true",4)==0
dan2e8f5512015-09-17 17:21:09 +0000755 && !safe_isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000756 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
757 return i+4;
758 }else if( c=='f'
759 && strncmp(pParse->zJson+i,"false",5)==0
dan2e8f5512015-09-17 17:21:09 +0000760 && !safe_isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000761 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
762 return i+5;
763 }else if( c=='-' || (c>='0' && c<='9') ){
764 /* Parse number */
765 u8 seenDP = 0;
766 u8 seenE = 0;
767 j = i+1;
768 for(;; j++){
769 c = pParse->zJson[j];
770 if( c>='0' && c<='9' ) continue;
771 if( c=='.' ){
772 if( pParse->zJson[j-1]=='-' ) return -1;
773 if( seenDP ) return -1;
774 seenDP = 1;
775 continue;
776 }
777 if( c=='e' || c=='E' ){
778 if( pParse->zJson[j-1]<'0' ) return -1;
779 if( seenE ) return -1;
780 seenDP = seenE = 1;
781 c = pParse->zJson[j+1];
drh8784eca2015-08-23 02:42:30 +0000782 if( c=='+' || c=='-' ){
783 j++;
784 c = pParse->zJson[j+1];
785 }
drhd1f00682015-08-29 16:02:37 +0000786 if( c<'0' || c>'9' ) return -1;
drhe9c37f32015-08-15 21:25:36 +0000787 continue;
788 }
789 break;
790 }
791 if( pParse->zJson[j-1]<'0' ) return -1;
792 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
793 j - i, &pParse->zJson[i]);
794 return j;
795 }else if( c=='}' ){
796 return -2; /* End of {...} */
797 }else if( c==']' ){
798 return -3; /* End of [...] */
drh8cb15cc2015-09-24 01:40:45 +0000799 }else if( c==0 ){
800 return 0; /* End of file */
drhe9c37f32015-08-15 21:25:36 +0000801 }else{
802 return -1; /* Syntax error */
803 }
804}
805
806/*
807** Parse a complete JSON string. Return 0 on success or non-zero if there
808** are any errors. If an error occurs, free all memory associated with
809** pParse.
810**
811** pParse is uninitialized when this routine is called.
812*/
drhbc8f0922015-08-22 19:39:04 +0000813static int jsonParse(
814 JsonParse *pParse, /* Initialize and fill this JsonParse object */
815 sqlite3_context *pCtx, /* Report errors here */
816 const char *zJson /* Input JSON text to be parsed */
817){
drhe9c37f32015-08-15 21:25:36 +0000818 int i;
drhe9c37f32015-08-15 21:25:36 +0000819 memset(pParse, 0, sizeof(*pParse));
drhc3722b22015-08-23 20:44:59 +0000820 if( zJson==0 ) return 1;
drhe9c37f32015-08-15 21:25:36 +0000821 pParse->zJson = zJson;
822 i = jsonParseValue(pParse, 0);
drhc3722b22015-08-23 20:44:59 +0000823 if( pParse->oom ) i = -1;
drhe9c37f32015-08-15 21:25:36 +0000824 if( i>0 ){
dan2e8f5512015-09-17 17:21:09 +0000825 while( safe_isspace(zJson[i]) ) i++;
drhe9c37f32015-08-15 21:25:36 +0000826 if( zJson[i] ) i = -1;
827 }
drhd1f00682015-08-29 16:02:37 +0000828 if( i<=0 ){
drhf2df7e72015-08-28 20:07:40 +0000829 if( pCtx!=0 ){
830 if( pParse->oom ){
831 sqlite3_result_error_nomem(pCtx);
832 }else{
833 sqlite3_result_error(pCtx, "malformed JSON", -1);
834 }
835 }
drh505ad2c2015-08-21 17:33:11 +0000836 jsonParseReset(pParse);
drhe9c37f32015-08-15 21:25:36 +0000837 return 1;
838 }
839 return 0;
840}
drh301eecc2015-08-17 20:14:19 +0000841
drh505ad2c2015-08-21 17:33:11 +0000842/* Mark node i of pParse as being a child of iParent. Call recursively
843** to fill in all the descendants of node i.
844*/
845static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
846 JsonNode *pNode = &pParse->aNode[i];
847 u32 j;
848 pParse->aUp[i] = iParent;
849 switch( pNode->eType ){
850 case JSON_ARRAY: {
851 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
852 jsonParseFillInParentage(pParse, i+j, i);
853 }
854 break;
855 }
856 case JSON_OBJECT: {
857 for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
858 pParse->aUp[i+j] = i;
859 jsonParseFillInParentage(pParse, i+j+1, i);
860 }
861 break;
862 }
863 default: {
864 break;
865 }
866 }
867}
868
869/*
870** Compute the parentage of all nodes in a completed parse.
871*/
872static int jsonParseFindParents(JsonParse *pParse){
873 u32 *aUp;
874 assert( pParse->aUp==0 );
875 aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
drhc3722b22015-08-23 20:44:59 +0000876 if( aUp==0 ){
877 pParse->oom = 1;
878 return SQLITE_NOMEM;
879 }
drh505ad2c2015-08-21 17:33:11 +0000880 jsonParseFillInParentage(pParse, 0, 0);
881 return SQLITE_OK;
882}
883
drh8cb0c832015-09-22 00:21:03 +0000884/*
885** Compare the OBJECT label at pNode against zKey,nKey. Return true on
886** a match.
887*/
888static int jsonLabelCompare(JsonNode *pNode, const char *zKey, int nKey){
889 if( pNode->jnFlags & JNODE_RAW ){
890 if( pNode->n!=nKey ) return 0;
891 return strncmp(pNode->u.zJContent, zKey, nKey)==0;
892 }else{
893 if( pNode->n!=nKey+2 ) return 0;
894 return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
895 }
896}
897
drh52216ad2015-08-18 02:28:03 +0000898/* forward declaration */
drha7714022015-08-29 00:54:49 +0000899static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
drh52216ad2015-08-18 02:28:03 +0000900
drh987eb1f2015-08-17 15:17:37 +0000901/*
902** Search along zPath to find the node specified. Return a pointer
903** to that node, or NULL if zPath is malformed or if there is no such
904** node.
drh52216ad2015-08-18 02:28:03 +0000905**
906** If pApnd!=0, then try to append new nodes to complete zPath if it is
907** possible to do so and if no existing node corresponds to zPath. If
908** new nodes are appended *pApnd is set to 1.
drh987eb1f2015-08-17 15:17:37 +0000909*/
drha7714022015-08-29 00:54:49 +0000910static JsonNode *jsonLookupStep(
drh52216ad2015-08-18 02:28:03 +0000911 JsonParse *pParse, /* The JSON to search */
912 u32 iRoot, /* Begin the search at this node */
913 const char *zPath, /* The path to search */
drha7714022015-08-29 00:54:49 +0000914 int *pApnd, /* Append nodes to complete path if not NULL */
915 const char **pzErr /* Make *pzErr point to any syntax error in zPath */
drh52216ad2015-08-18 02:28:03 +0000916){
drhbc8f0922015-08-22 19:39:04 +0000917 u32 i, j, nKey;
drh6b43cc82015-08-19 23:02:49 +0000918 const char *zKey;
drh52216ad2015-08-18 02:28:03 +0000919 JsonNode *pRoot = &pParse->aNode[iRoot];
drh987eb1f2015-08-17 15:17:37 +0000920 if( zPath[0]==0 ) return pRoot;
921 if( zPath[0]=='.' ){
922 if( pRoot->eType!=JSON_OBJECT ) return 0;
923 zPath++;
drh6b43cc82015-08-19 23:02:49 +0000924 if( zPath[0]=='"' ){
925 zKey = zPath + 1;
926 for(i=1; zPath[i] && zPath[i]!='"'; i++){}
927 nKey = i-1;
drha8f39a92015-09-21 22:53:16 +0000928 if( zPath[i] ){
929 i++;
930 }else{
931 *pzErr = zPath;
932 return 0;
933 }
drh6b43cc82015-08-19 23:02:49 +0000934 }else{
935 zKey = zPath;
936 for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
937 nKey = i;
938 }
drha7714022015-08-29 00:54:49 +0000939 if( nKey==0 ){
940 *pzErr = zPath;
941 return 0;
942 }
drh987eb1f2015-08-17 15:17:37 +0000943 j = 1;
drh52216ad2015-08-18 02:28:03 +0000944 for(;;){
945 while( j<=pRoot->n ){
drh8cb0c832015-09-22 00:21:03 +0000946 if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
drha7714022015-08-29 00:54:49 +0000947 return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000948 }
949 j++;
drh505ad2c2015-08-21 17:33:11 +0000950 j += jsonNodeSize(&pRoot[j]);
drh987eb1f2015-08-17 15:17:37 +0000951 }
drh52216ad2015-08-18 02:28:03 +0000952 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
953 iRoot += pRoot->u.iAppend;
954 pRoot = &pParse->aNode[iRoot];
955 j = 1;
956 }
957 if( pApnd ){
drhbc8f0922015-08-22 19:39:04 +0000958 u32 iStart, iLabel;
959 JsonNode *pNode;
960 iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
961 iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
drh52216ad2015-08-18 02:28:03 +0000962 zPath += i;
drha7714022015-08-29 00:54:49 +0000963 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +0000964 if( pParse->oom ) return 0;
965 if( pNode ){
966 pRoot = &pParse->aNode[iRoot];
967 pRoot->u.iAppend = iStart - iRoot;
968 pRoot->jnFlags |= JNODE_APPEND;
969 pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
970 }
971 return pNode;
drh987eb1f2015-08-17 15:17:37 +0000972 }
dan2e8f5512015-09-17 17:21:09 +0000973 }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
drh987eb1f2015-08-17 15:17:37 +0000974 if( pRoot->eType!=JSON_ARRAY ) return 0;
975 i = 0;
drh3d1d2a92015-09-22 01:15:49 +0000976 j = 1;
977 while( safe_isdigit(zPath[j]) ){
978 i = i*10 + zPath[j] - '0';
979 j++;
drh987eb1f2015-08-17 15:17:37 +0000980 }
drh3d1d2a92015-09-22 01:15:49 +0000981 if( zPath[j]!=']' ){
drha7714022015-08-29 00:54:49 +0000982 *pzErr = zPath;
983 return 0;
984 }
drh3d1d2a92015-09-22 01:15:49 +0000985 zPath += j + 1;
drh987eb1f2015-08-17 15:17:37 +0000986 j = 1;
drh52216ad2015-08-18 02:28:03 +0000987 for(;;){
drhbc8f0922015-08-22 19:39:04 +0000988 while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
989 if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
drh505ad2c2015-08-21 17:33:11 +0000990 j += jsonNodeSize(&pRoot[j]);
drh52216ad2015-08-18 02:28:03 +0000991 }
992 if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
993 iRoot += pRoot->u.iAppend;
994 pRoot = &pParse->aNode[iRoot];
995 j = 1;
drh987eb1f2015-08-17 15:17:37 +0000996 }
997 if( j<=pRoot->n ){
drha7714022015-08-29 00:54:49 +0000998 return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +0000999 }
1000 if( i==0 && pApnd ){
drhbc8f0922015-08-22 19:39:04 +00001001 u32 iStart;
1002 JsonNode *pNode;
1003 iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
drha7714022015-08-29 00:54:49 +00001004 pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
drhbc8f0922015-08-22 19:39:04 +00001005 if( pParse->oom ) return 0;
1006 if( pNode ){
1007 pRoot = &pParse->aNode[iRoot];
1008 pRoot->u.iAppend = iStart - iRoot;
1009 pRoot->jnFlags |= JNODE_APPEND;
1010 }
1011 return pNode;
drh987eb1f2015-08-17 15:17:37 +00001012 }
drh3d1d2a92015-09-22 01:15:49 +00001013 }else{
drha7714022015-08-29 00:54:49 +00001014 *pzErr = zPath;
drh987eb1f2015-08-17 15:17:37 +00001015 }
1016 return 0;
1017}
1018
drh52216ad2015-08-18 02:28:03 +00001019/*
drhbc8f0922015-08-22 19:39:04 +00001020** Append content to pParse that will complete zPath. Return a pointer
1021** to the inserted node, or return NULL if the append fails.
drh52216ad2015-08-18 02:28:03 +00001022*/
1023static JsonNode *jsonLookupAppend(
1024 JsonParse *pParse, /* Append content to the JSON parse */
1025 const char *zPath, /* Description of content to append */
drha7714022015-08-29 00:54:49 +00001026 int *pApnd, /* Set this flag to 1 */
1027 const char **pzErr /* Make this point to any syntax error */
drh52216ad2015-08-18 02:28:03 +00001028){
1029 *pApnd = 1;
1030 if( zPath[0]==0 ){
1031 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
1032 return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
1033 }
1034 if( zPath[0]=='.' ){
1035 jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
1036 }else if( strncmp(zPath,"[0]",3)==0 ){
1037 jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
1038 }else{
1039 return 0;
1040 }
1041 if( pParse->oom ) return 0;
drha7714022015-08-29 00:54:49 +00001042 return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
drh52216ad2015-08-18 02:28:03 +00001043}
1044
drhbc8f0922015-08-22 19:39:04 +00001045/*
drha7714022015-08-29 00:54:49 +00001046** Return the text of a syntax error message on a JSON path. Space is
1047** obtained from sqlite3_malloc().
1048*/
1049static char *jsonPathSyntaxError(const char *zErr){
1050 return sqlite3_mprintf("JSON path error near '%q'", zErr);
1051}
1052
1053/*
1054** Do a node lookup using zPath. Return a pointer to the node on success.
1055** Return NULL if not found or if there is an error.
1056**
1057** On an error, write an error message into pCtx and increment the
1058** pParse->nErr counter.
1059**
1060** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
1061** nodes are appended.
drha7714022015-08-29 00:54:49 +00001062*/
1063static JsonNode *jsonLookup(
1064 JsonParse *pParse, /* The JSON to search */
1065 const char *zPath, /* The path to search */
1066 int *pApnd, /* Append nodes to complete path if not NULL */
drhf5ddb9c2015-09-11 00:06:41 +00001067 sqlite3_context *pCtx /* Report errors here, if not NULL */
drha7714022015-08-29 00:54:49 +00001068){
1069 const char *zErr = 0;
1070 JsonNode *pNode = 0;
drha8f39a92015-09-21 22:53:16 +00001071 char *zMsg;
drha7714022015-08-29 00:54:49 +00001072
1073 if( zPath==0 ) return 0;
1074 if( zPath[0]!='$' ){
1075 zErr = zPath;
1076 goto lookup_err;
1077 }
1078 zPath++;
drha7714022015-08-29 00:54:49 +00001079 pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
drha8f39a92015-09-21 22:53:16 +00001080 if( zErr==0 ) return pNode;
drha7714022015-08-29 00:54:49 +00001081
1082lookup_err:
1083 pParse->nErr++;
drha8f39a92015-09-21 22:53:16 +00001084 assert( zErr!=0 && pCtx!=0 );
1085 zMsg = jsonPathSyntaxError(zErr);
1086 if( zMsg ){
1087 sqlite3_result_error(pCtx, zMsg, -1);
1088 sqlite3_free(zMsg);
1089 }else{
1090 sqlite3_result_error_nomem(pCtx);
drha7714022015-08-29 00:54:49 +00001091 }
drha7714022015-08-29 00:54:49 +00001092 return 0;
1093}
1094
1095
1096/*
drhbc8f0922015-08-22 19:39:04 +00001097** Report the wrong number of arguments for json_insert(), json_replace()
1098** or json_set().
1099*/
1100static void jsonWrongNumArgs(
1101 sqlite3_context *pCtx,
1102 const char *zFuncName
1103){
1104 char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
1105 zFuncName);
1106 sqlite3_result_error(pCtx, zMsg, -1);
1107 sqlite3_free(zMsg);
1108}
drh52216ad2015-08-18 02:28:03 +00001109
drha7714022015-08-29 00:54:49 +00001110
drh987eb1f2015-08-17 15:17:37 +00001111/****************************************************************************
1112** SQL functions used for testing and debugging
1113****************************************************************************/
drhe9c37f32015-08-15 21:25:36 +00001114
drh301eecc2015-08-17 20:14:19 +00001115#ifdef SQLITE_DEBUG
drhe9c37f32015-08-15 21:25:36 +00001116/*
drh5634cc02015-08-17 11:28:03 +00001117** The json_parse(JSON) function returns a string which describes
drhe9c37f32015-08-15 21:25:36 +00001118** a parse of the JSON provided. Or it returns NULL if JSON is not
1119** well-formed.
1120*/
drh5634cc02015-08-17 11:28:03 +00001121static void jsonParseFunc(
drhbc8f0922015-08-22 19:39:04 +00001122 sqlite3_context *ctx,
drhe9c37f32015-08-15 21:25:36 +00001123 int argc,
1124 sqlite3_value **argv
1125){
drh505ad2c2015-08-21 17:33:11 +00001126 JsonString s; /* Output string - not real JSON */
1127 JsonParse x; /* The parse */
drhe9c37f32015-08-15 21:25:36 +00001128 u32 i;
drhe9c37f32015-08-15 21:25:36 +00001129
1130 assert( argc==1 );
drhbc8f0922015-08-22 19:39:04 +00001131 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh8784eca2015-08-23 02:42:30 +00001132 jsonParseFindParents(&x);
drhbc8f0922015-08-22 19:39:04 +00001133 jsonInit(&s, ctx);
drhe9c37f32015-08-15 21:25:36 +00001134 for(i=0; i<x.nNode; i++){
drh852944e2015-09-10 03:29:11 +00001135 const char *zType;
1136 if( x.aNode[i].jnFlags & JNODE_LABEL ){
1137 assert( x.aNode[i].eType==JSON_STRING );
1138 zType = "label";
1139 }else{
1140 zType = jsonType[x.aNode[i].eType];
drhe9c37f32015-08-15 21:25:36 +00001141 }
drh852944e2015-09-10 03:29:11 +00001142 jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
1143 i, zType, x.aNode[i].n, x.aUp[i]);
1144 if( x.aNode[i].u.zJContent!=0 ){
1145 jsonAppendRaw(&s, " ", 1);
1146 jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
1147 }
1148 jsonAppendRaw(&s, "\n", 1);
drhe9c37f32015-08-15 21:25:36 +00001149 }
drh505ad2c2015-08-21 17:33:11 +00001150 jsonParseReset(&x);
drhe9c37f32015-08-15 21:25:36 +00001151 jsonResult(&s);
1152}
1153
drh5634cc02015-08-17 11:28:03 +00001154/*
drhf5ddb9c2015-09-11 00:06:41 +00001155** The json_test1(JSON) function return true (1) if the input is JSON
1156** text generated by another json function. It returns (0) if the input
1157** is not known to be JSON.
drh5634cc02015-08-17 11:28:03 +00001158*/
1159static void jsonTest1Func(
drhbc8f0922015-08-22 19:39:04 +00001160 sqlite3_context *ctx,
drh5634cc02015-08-17 11:28:03 +00001161 int argc,
1162 sqlite3_value **argv
1163){
mistachkin16a93122015-09-11 18:05:01 +00001164 UNUSED_PARAM(argc);
drhf5ddb9c2015-09-11 00:06:41 +00001165 sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
drh5634cc02015-08-17 11:28:03 +00001166}
drh301eecc2015-08-17 20:14:19 +00001167#endif /* SQLITE_DEBUG */
drh5634cc02015-08-17 11:28:03 +00001168
drh987eb1f2015-08-17 15:17:37 +00001169/****************************************************************************
1170** SQL function implementations
1171****************************************************************************/
1172
1173/*
1174** Implementation of the json_array(VALUE,...) function. Return a JSON
1175** array that contains all values given in arguments. Or if any argument
1176** is a BLOB, throw an error.
1177*/
1178static void jsonArrayFunc(
drhbc8f0922015-08-22 19:39:04 +00001179 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001180 int argc,
1181 sqlite3_value **argv
1182){
1183 int i;
drh505ad2c2015-08-21 17:33:11 +00001184 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001185
drhbc8f0922015-08-22 19:39:04 +00001186 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001187 jsonAppendChar(&jx, '[');
drh987eb1f2015-08-17 15:17:37 +00001188 for(i=0; i<argc; i++){
drhd0960592015-08-17 21:22:32 +00001189 jsonAppendSeparator(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001190 jsonAppendValue(&jx, argv[i]);
drh987eb1f2015-08-17 15:17:37 +00001191 }
drhd0960592015-08-17 21:22:32 +00001192 jsonAppendChar(&jx, ']');
drh987eb1f2015-08-17 15:17:37 +00001193 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001194 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001195}
1196
1197
1198/*
1199** json_array_length(JSON)
1200** json_array_length(JSON, PATH)
1201**
1202** Return the number of elements in the top-level JSON array.
1203** Return 0 if the input is not a well-formed JSON array.
1204*/
1205static void jsonArrayLengthFunc(
drhbc8f0922015-08-22 19:39:04 +00001206 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001207 int argc,
1208 sqlite3_value **argv
1209){
1210 JsonParse x; /* The parse */
1211 sqlite3_int64 n = 0;
1212 u32 i;
drha8f39a92015-09-21 22:53:16 +00001213 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001214
drhf2df7e72015-08-28 20:07:40 +00001215 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001216 assert( x.nNode );
1217 if( argc==2 ){
1218 const char *zPath = (const char*)sqlite3_value_text(argv[1]);
1219 pNode = jsonLookup(&x, zPath, 0, ctx);
1220 }else{
1221 pNode = x.aNode;
1222 }
1223 if( pNode==0 ){
1224 x.nErr = 1;
1225 }else if( pNode->eType==JSON_ARRAY ){
1226 assert( (pNode->jnFlags & JNODE_APPEND)==0 );
1227 for(i=1; i<=pNode->n; n++){
1228 i += jsonNodeSize(&pNode[i]);
drh987eb1f2015-08-17 15:17:37 +00001229 }
drh987eb1f2015-08-17 15:17:37 +00001230 }
drha7714022015-08-29 00:54:49 +00001231 if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
drhf6ec8d42015-08-28 03:48:04 +00001232 jsonParseReset(&x);
1233}
1234
1235/*
drh3ad93bb2015-08-29 19:41:45 +00001236** json_extract(JSON, PATH, ...)
drh987eb1f2015-08-17 15:17:37 +00001237**
drh3ad93bb2015-08-29 19:41:45 +00001238** Return the element described by PATH. Return NULL if there is no
1239** PATH element. If there are multiple PATHs, then return a JSON array
1240** with the result from each path. Throw an error if the JSON or any PATH
1241** is malformed.
drh987eb1f2015-08-17 15:17:37 +00001242*/
1243static void jsonExtractFunc(
drhbc8f0922015-08-22 19:39:04 +00001244 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001245 int argc,
1246 sqlite3_value **argv
1247){
1248 JsonParse x; /* The parse */
1249 JsonNode *pNode;
1250 const char *zPath;
drh3ad93bb2015-08-29 19:41:45 +00001251 JsonString jx;
1252 int i;
1253
1254 if( argc<2 ) return;
drhbc8f0922015-08-22 19:39:04 +00001255 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drh3ad93bb2015-08-29 19:41:45 +00001256 jsonInit(&jx, ctx);
1257 jsonAppendChar(&jx, '[');
1258 for(i=1; i<argc; i++){
1259 zPath = (const char*)sqlite3_value_text(argv[i]);
drhf5ddb9c2015-09-11 00:06:41 +00001260 pNode = jsonLookup(&x, zPath, 0, ctx);
drh3ad93bb2015-08-29 19:41:45 +00001261 if( x.nErr ) break;
1262 if( argc>2 ){
1263 jsonAppendSeparator(&jx);
1264 if( pNode ){
1265 jsonRenderNode(pNode, &jx, 0);
1266 }else{
1267 jsonAppendRaw(&jx, "null", 4);
1268 }
1269 }else if( pNode ){
1270 jsonReturn(pNode, ctx, 0);
1271 }
drh987eb1f2015-08-17 15:17:37 +00001272 }
drh3ad93bb2015-08-29 19:41:45 +00001273 if( argc>2 && i==argc ){
1274 jsonAppendChar(&jx, ']');
1275 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001276 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh3ad93bb2015-08-29 19:41:45 +00001277 }
1278 jsonReset(&jx);
drh505ad2c2015-08-21 17:33:11 +00001279 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001280}
1281
1282/*
1283** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
1284** object that contains all name/value given in arguments. Or if any name
1285** is not a string or if any value is a BLOB, throw an error.
1286*/
1287static void jsonObjectFunc(
drhbc8f0922015-08-22 19:39:04 +00001288 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001289 int argc,
1290 sqlite3_value **argv
1291){
1292 int i;
drh505ad2c2015-08-21 17:33:11 +00001293 JsonString jx;
drh987eb1f2015-08-17 15:17:37 +00001294 const char *z;
1295 u32 n;
1296
1297 if( argc&1 ){
drhbc8f0922015-08-22 19:39:04 +00001298 sqlite3_result_error(ctx, "json_object() requires an even number "
drh987eb1f2015-08-17 15:17:37 +00001299 "of arguments", -1);
1300 return;
1301 }
drhbc8f0922015-08-22 19:39:04 +00001302 jsonInit(&jx, ctx);
drhd0960592015-08-17 21:22:32 +00001303 jsonAppendChar(&jx, '{');
drh987eb1f2015-08-17 15:17:37 +00001304 for(i=0; i<argc; i+=2){
drh987eb1f2015-08-17 15:17:37 +00001305 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
drhbc8f0922015-08-22 19:39:04 +00001306 sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
drhdc384952015-09-19 18:54:39 +00001307 jsonReset(&jx);
drh987eb1f2015-08-17 15:17:37 +00001308 return;
1309 }
drhd0960592015-08-17 21:22:32 +00001310 jsonAppendSeparator(&jx);
drh987eb1f2015-08-17 15:17:37 +00001311 z = (const char*)sqlite3_value_text(argv[i]);
1312 n = (u32)sqlite3_value_bytes(argv[i]);
1313 jsonAppendString(&jx, z, n);
drhd0960592015-08-17 21:22:32 +00001314 jsonAppendChar(&jx, ':');
drhf5ddb9c2015-09-11 00:06:41 +00001315 jsonAppendValue(&jx, argv[i+1]);
drh987eb1f2015-08-17 15:17:37 +00001316 }
drhd0960592015-08-17 21:22:32 +00001317 jsonAppendChar(&jx, '}');
drh987eb1f2015-08-17 15:17:37 +00001318 jsonResult(&jx);
drhf5ddb9c2015-09-11 00:06:41 +00001319 sqlite3_result_subtype(ctx, JSON_SUBTYPE);
drh987eb1f2015-08-17 15:17:37 +00001320}
1321
1322
1323/*
drh301eecc2015-08-17 20:14:19 +00001324** json_remove(JSON, PATH, ...)
1325**
drh3ad93bb2015-08-29 19:41:45 +00001326** Remove the named elements from JSON and return the result. malformed
1327** JSON or PATH arguments result in an error.
drh301eecc2015-08-17 20:14:19 +00001328*/
1329static void jsonRemoveFunc(
drhbc8f0922015-08-22 19:39:04 +00001330 sqlite3_context *ctx,
drh301eecc2015-08-17 20:14:19 +00001331 int argc,
1332 sqlite3_value **argv
1333){
1334 JsonParse x; /* The parse */
1335 JsonNode *pNode;
1336 const char *zPath;
1337 u32 i;
1338
1339 if( argc<1 ) return;
drhbc8f0922015-08-22 19:39:04 +00001340 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001341 assert( x.nNode );
1342 for(i=1; i<(u32)argc; i++){
1343 zPath = (const char*)sqlite3_value_text(argv[i]);
1344 if( zPath==0 ) goto remove_done;
1345 pNode = jsonLookup(&x, zPath, 0, ctx);
1346 if( x.nErr ) goto remove_done;
1347 if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
1348 }
1349 if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
1350 jsonReturnJson(x.aNode, ctx, 0);
drhd0960592015-08-17 21:22:32 +00001351 }
drha7714022015-08-29 00:54:49 +00001352remove_done:
drh505ad2c2015-08-21 17:33:11 +00001353 jsonParseReset(&x);
drhd0960592015-08-17 21:22:32 +00001354}
1355
1356/*
1357** json_replace(JSON, PATH, VALUE, ...)
1358**
1359** Replace the value at PATH with VALUE. If PATH does not already exist,
drh3ad93bb2015-08-29 19:41:45 +00001360** this routine is a no-op. If JSON or PATH is malformed, throw an error.
drhd0960592015-08-17 21:22:32 +00001361*/
1362static void jsonReplaceFunc(
drhbc8f0922015-08-22 19:39:04 +00001363 sqlite3_context *ctx,
drhd0960592015-08-17 21:22:32 +00001364 int argc,
1365 sqlite3_value **argv
1366){
1367 JsonParse x; /* The parse */
1368 JsonNode *pNode;
1369 const char *zPath;
1370 u32 i;
1371
1372 if( argc<1 ) return;
1373 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001374 jsonWrongNumArgs(ctx, "replace");
drhd0960592015-08-17 21:22:32 +00001375 return;
1376 }
drhbc8f0922015-08-22 19:39:04 +00001377 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001378 assert( x.nNode );
1379 for(i=1; i<(u32)argc; i+=2){
1380 zPath = (const char*)sqlite3_value_text(argv[i]);
1381 pNode = jsonLookup(&x, zPath, 0, ctx);
1382 if( x.nErr ) goto replace_err;
1383 if( pNode ){
1384 pNode->jnFlags |= (u8)JNODE_REPLACE;
1385 pNode->iVal = (u8)(i+1);
drhd0960592015-08-17 21:22:32 +00001386 }
drha8f39a92015-09-21 22:53:16 +00001387 }
1388 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1389 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1390 }else{
1391 jsonReturnJson(x.aNode, ctx, argv);
drh301eecc2015-08-17 20:14:19 +00001392 }
drha7714022015-08-29 00:54:49 +00001393replace_err:
drh505ad2c2015-08-21 17:33:11 +00001394 jsonParseReset(&x);
drh301eecc2015-08-17 20:14:19 +00001395}
drh505ad2c2015-08-21 17:33:11 +00001396
drh52216ad2015-08-18 02:28:03 +00001397/*
1398** json_set(JSON, PATH, VALUE, ...)
1399**
1400** Set the value at PATH to VALUE. Create the PATH if it does not already
1401** exist. Overwrite existing values that do exist.
drh3ad93bb2015-08-29 19:41:45 +00001402** If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001403**
1404** json_insert(JSON, PATH, VALUE, ...)
1405**
1406** Create PATH and initialize it to VALUE. If PATH already exists, this
drh3ad93bb2015-08-29 19:41:45 +00001407** routine is a no-op. If JSON or PATH is malformed, throw an error.
drh52216ad2015-08-18 02:28:03 +00001408*/
1409static void jsonSetFunc(
drhbc8f0922015-08-22 19:39:04 +00001410 sqlite3_context *ctx,
drh52216ad2015-08-18 02:28:03 +00001411 int argc,
1412 sqlite3_value **argv
1413){
1414 JsonParse x; /* The parse */
1415 JsonNode *pNode;
1416 const char *zPath;
1417 u32 i;
1418 int bApnd;
drhbc8f0922015-08-22 19:39:04 +00001419 int bIsSet = *(int*)sqlite3_user_data(ctx);
drh52216ad2015-08-18 02:28:03 +00001420
1421 if( argc<1 ) return;
1422 if( (argc&1)==0 ) {
drhbc8f0922015-08-22 19:39:04 +00001423 jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
drh52216ad2015-08-18 02:28:03 +00001424 return;
1425 }
drhbc8f0922015-08-22 19:39:04 +00001426 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001427 assert( x.nNode );
1428 for(i=1; i<(u32)argc; i+=2){
1429 zPath = (const char*)sqlite3_value_text(argv[i]);
1430 bApnd = 0;
1431 pNode = jsonLookup(&x, zPath, &bApnd, ctx);
1432 if( x.oom ){
1433 sqlite3_result_error_nomem(ctx);
1434 goto jsonSetDone;
1435 }else if( x.nErr ){
1436 goto jsonSetDone;
1437 }else if( pNode && (bApnd || bIsSet) ){
1438 pNode->jnFlags |= (u8)JNODE_REPLACE;
1439 pNode->iVal = (u8)(i+1);
drh52216ad2015-08-18 02:28:03 +00001440 }
drha8f39a92015-09-21 22:53:16 +00001441 }
1442 if( x.aNode[0].jnFlags & JNODE_REPLACE ){
1443 sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
1444 }else{
1445 jsonReturnJson(x.aNode, ctx, argv);
drh52216ad2015-08-18 02:28:03 +00001446 }
drhbc8f0922015-08-22 19:39:04 +00001447jsonSetDone:
drh505ad2c2015-08-21 17:33:11 +00001448 jsonParseReset(&x);
drh52216ad2015-08-18 02:28:03 +00001449}
drh301eecc2015-08-17 20:14:19 +00001450
1451/*
drh987eb1f2015-08-17 15:17:37 +00001452** json_type(JSON)
1453** json_type(JSON, PATH)
1454**
drh3ad93bb2015-08-29 19:41:45 +00001455** Return the top-level "type" of a JSON string. Throw an error if
1456** either the JSON or PATH inputs are not well-formed.
drh987eb1f2015-08-17 15:17:37 +00001457*/
1458static void jsonTypeFunc(
drhbc8f0922015-08-22 19:39:04 +00001459 sqlite3_context *ctx,
drh987eb1f2015-08-17 15:17:37 +00001460 int argc,
1461 sqlite3_value **argv
1462){
1463 JsonParse x; /* The parse */
1464 const char *zPath;
drha8f39a92015-09-21 22:53:16 +00001465 JsonNode *pNode;
drh987eb1f2015-08-17 15:17:37 +00001466
drhbc8f0922015-08-22 19:39:04 +00001467 if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
drha8f39a92015-09-21 22:53:16 +00001468 assert( x.nNode );
1469 if( argc==2 ){
1470 zPath = (const char*)sqlite3_value_text(argv[1]);
1471 pNode = jsonLookup(&x, zPath, 0, ctx);
1472 }else{
1473 pNode = x.aNode;
1474 }
1475 if( pNode ){
1476 sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
drh987eb1f2015-08-17 15:17:37 +00001477 }
drh505ad2c2015-08-21 17:33:11 +00001478 jsonParseReset(&x);
drh987eb1f2015-08-17 15:17:37 +00001479}
drh5634cc02015-08-17 11:28:03 +00001480
drhbc8f0922015-08-22 19:39:04 +00001481/*
1482** json_valid(JSON)
1483**
drh3ad93bb2015-08-29 19:41:45 +00001484** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
1485** Return 0 otherwise.
drhbc8f0922015-08-22 19:39:04 +00001486*/
1487static void jsonValidFunc(
1488 sqlite3_context *ctx,
1489 int argc,
1490 sqlite3_value **argv
1491){
1492 JsonParse x; /* The parse */
1493 int rc = 0;
1494
mistachkin16a93122015-09-11 18:05:01 +00001495 UNUSED_PARAM(argc);
drha8f39a92015-09-21 22:53:16 +00001496 if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
drhbc8f0922015-08-22 19:39:04 +00001497 rc = 1;
1498 }
1499 jsonParseReset(&x);
1500 sqlite3_result_int(ctx, rc);
1501}
1502
drhd2975922015-08-29 17:22:33 +00001503#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcb6c6c62015-08-19 22:47:17 +00001504/****************************************************************************
1505** The json_each virtual table
1506****************************************************************************/
1507typedef struct JsonEachCursor JsonEachCursor;
1508struct JsonEachCursor {
1509 sqlite3_vtab_cursor base; /* Base class - must be first */
drh505ad2c2015-08-21 17:33:11 +00001510 u32 iRowid; /* The rowid */
drh852944e2015-09-10 03:29:11 +00001511 u32 iBegin; /* The first node of the scan */
drh505ad2c2015-08-21 17:33:11 +00001512 u32 i; /* Index in sParse.aNode[] of current row */
1513 u32 iEnd; /* EOF when i equals or exceeds this value */
1514 u8 eType; /* Type of top-level element */
1515 u8 bRecursive; /* True for json_tree(). False for json_each() */
1516 char *zJson; /* Input JSON */
drh383de692015-09-10 17:20:57 +00001517 char *zRoot; /* Path by which to filter zJson */
drh505ad2c2015-08-21 17:33:11 +00001518 JsonParse sParse; /* Parse of the input JSON */
drhcb6c6c62015-08-19 22:47:17 +00001519};
1520
1521/* Constructor for the json_each virtual table */
1522static int jsonEachConnect(
1523 sqlite3 *db,
1524 void *pAux,
1525 int argc, const char *const*argv,
1526 sqlite3_vtab **ppVtab,
1527 char **pzErr
1528){
1529 sqlite3_vtab *pNew;
drh505ad2c2015-08-21 17:33:11 +00001530 int rc;
drhcb6c6c62015-08-19 22:47:17 +00001531
1532/* Column numbers */
drh4af352d2015-08-21 20:02:48 +00001533#define JEACH_KEY 0
1534#define JEACH_VALUE 1
1535#define JEACH_TYPE 2
1536#define JEACH_ATOM 3
1537#define JEACH_ID 4
1538#define JEACH_PARENT 5
1539#define JEACH_FULLKEY 6
drh383de692015-09-10 17:20:57 +00001540#define JEACH_PATH 7
1541#define JEACH_JSON 8
1542#define JEACH_ROOT 9
drhcb6c6c62015-08-19 22:47:17 +00001543
drh6fd5c1e2015-08-21 20:37:12 +00001544 UNUSED_PARAM(pzErr);
1545 UNUSED_PARAM(argv);
1546 UNUSED_PARAM(argc);
1547 UNUSED_PARAM(pAux);
drh505ad2c2015-08-21 17:33:11 +00001548 rc = sqlite3_declare_vtab(db,
drh383de692015-09-10 17:20:57 +00001549 "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
1550 "json HIDDEN,root HIDDEN)");
drh505ad2c2015-08-21 17:33:11 +00001551 if( rc==SQLITE_OK ){
1552 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
1553 if( pNew==0 ) return SQLITE_NOMEM;
1554 memset(pNew, 0, sizeof(*pNew));
1555 }
1556 return rc;
drhcb6c6c62015-08-19 22:47:17 +00001557}
1558
1559/* destructor for json_each virtual table */
1560static int jsonEachDisconnect(sqlite3_vtab *pVtab){
1561 sqlite3_free(pVtab);
1562 return SQLITE_OK;
1563}
1564
drh505ad2c2015-08-21 17:33:11 +00001565/* constructor for a JsonEachCursor object for json_each(). */
1566static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
drhcb6c6c62015-08-19 22:47:17 +00001567 JsonEachCursor *pCur;
drh6fd5c1e2015-08-21 20:37:12 +00001568
1569 UNUSED_PARAM(p);
drhcb6c6c62015-08-19 22:47:17 +00001570 pCur = sqlite3_malloc( sizeof(*pCur) );
1571 if( pCur==0 ) return SQLITE_NOMEM;
1572 memset(pCur, 0, sizeof(*pCur));
1573 *ppCursor = &pCur->base;
1574 return SQLITE_OK;
1575}
1576
drh505ad2c2015-08-21 17:33:11 +00001577/* constructor for a JsonEachCursor object for json_tree(). */
1578static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1579 int rc = jsonEachOpenEach(p, ppCursor);
1580 if( rc==SQLITE_OK ){
1581 JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
1582 pCur->bRecursive = 1;
1583 }
1584 return rc;
1585}
1586
drhcb6c6c62015-08-19 22:47:17 +00001587/* Reset a JsonEachCursor back to its original state. Free any memory
1588** held. */
1589static void jsonEachCursorReset(JsonEachCursor *p){
1590 sqlite3_free(p->zJson);
drh383de692015-09-10 17:20:57 +00001591 sqlite3_free(p->zRoot);
drh505ad2c2015-08-21 17:33:11 +00001592 jsonParseReset(&p->sParse);
drhcb6c6c62015-08-19 22:47:17 +00001593 p->iRowid = 0;
1594 p->i = 0;
1595 p->iEnd = 0;
1596 p->eType = 0;
drhcb6c6c62015-08-19 22:47:17 +00001597 p->zJson = 0;
drh383de692015-09-10 17:20:57 +00001598 p->zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001599}
1600
1601/* Destructor for a jsonEachCursor object */
1602static int jsonEachClose(sqlite3_vtab_cursor *cur){
1603 JsonEachCursor *p = (JsonEachCursor*)cur;
1604 jsonEachCursorReset(p);
1605 sqlite3_free(cur);
1606 return SQLITE_OK;
1607}
1608
1609/* Return TRUE if the jsonEachCursor object has been advanced off the end
1610** of the JSON object */
1611static int jsonEachEof(sqlite3_vtab_cursor *cur){
1612 JsonEachCursor *p = (JsonEachCursor*)cur;
1613 return p->i >= p->iEnd;
1614}
1615
drh505ad2c2015-08-21 17:33:11 +00001616/* Advance the cursor to the next element for json_tree() */
drh4af352d2015-08-21 20:02:48 +00001617static int jsonEachNext(sqlite3_vtab_cursor *cur){
drh505ad2c2015-08-21 17:33:11 +00001618 JsonEachCursor *p = (JsonEachCursor*)cur;
drh4af352d2015-08-21 20:02:48 +00001619 if( p->bRecursive ){
drh852944e2015-09-10 03:29:11 +00001620 if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
1621 p->i++;
drh4af352d2015-08-21 20:02:48 +00001622 p->iRowid++;
drh852944e2015-09-10 03:29:11 +00001623 if( p->i<p->iEnd ){
drh8784eca2015-08-23 02:42:30 +00001624 u32 iUp = p->sParse.aUp[p->i];
1625 JsonNode *pUp = &p->sParse.aNode[iUp];
drh4af352d2015-08-21 20:02:48 +00001626 p->eType = pUp->eType;
drh8784eca2015-08-23 02:42:30 +00001627 if( pUp->eType==JSON_ARRAY ){
1628 if( iUp==p->i-1 ){
1629 pUp->u.iKey = 0;
1630 }else{
1631 pUp->u.iKey++;
1632 }
drh4af352d2015-08-21 20:02:48 +00001633 }
1634 }
drh505ad2c2015-08-21 17:33:11 +00001635 }else{
drh4af352d2015-08-21 20:02:48 +00001636 switch( p->eType ){
1637 case JSON_ARRAY: {
1638 p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
1639 p->iRowid++;
1640 break;
1641 }
1642 case JSON_OBJECT: {
1643 p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
1644 p->iRowid++;
1645 break;
1646 }
1647 default: {
1648 p->i = p->iEnd;
1649 break;
1650 }
drh505ad2c2015-08-21 17:33:11 +00001651 }
1652 }
1653 return SQLITE_OK;
1654}
1655
drh4af352d2015-08-21 20:02:48 +00001656/* Append the name of the path for element i to pStr
1657*/
1658static void jsonEachComputePath(
1659 JsonEachCursor *p, /* The cursor */
1660 JsonString *pStr, /* Write the path here */
1661 u32 i /* Path to this element */
1662){
1663 JsonNode *pNode, *pUp;
1664 u32 iUp;
1665 if( i==0 ){
1666 jsonAppendChar(pStr, '$');
1667 return;
drhcb6c6c62015-08-19 22:47:17 +00001668 }
drh4af352d2015-08-21 20:02:48 +00001669 iUp = p->sParse.aUp[i];
1670 jsonEachComputePath(p, pStr, iUp);
1671 pNode = &p->sParse.aNode[i];
1672 pUp = &p->sParse.aNode[iUp];
1673 if( pUp->eType==JSON_ARRAY ){
1674 jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
1675 }else{
1676 assert( pUp->eType==JSON_OBJECT );
drh852944e2015-09-10 03:29:11 +00001677 if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
drh4af352d2015-08-21 20:02:48 +00001678 assert( pNode->eType==JSON_STRING );
drh852944e2015-09-10 03:29:11 +00001679 assert( pNode->jnFlags & JNODE_LABEL );
drh4af352d2015-08-21 20:02:48 +00001680 jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
1681 }
drhcb6c6c62015-08-19 22:47:17 +00001682}
1683
1684/* Return the value of a column */
1685static int jsonEachColumn(
1686 sqlite3_vtab_cursor *cur, /* The cursor */
1687 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1688 int i /* Which column to return */
1689){
1690 JsonEachCursor *p = (JsonEachCursor*)cur;
drh505ad2c2015-08-21 17:33:11 +00001691 JsonNode *pThis = &p->sParse.aNode[p->i];
drhcb6c6c62015-08-19 22:47:17 +00001692 switch( i ){
1693 case JEACH_KEY: {
drh8784eca2015-08-23 02:42:30 +00001694 if( p->i==0 ) break;
drhcb6c6c62015-08-19 22:47:17 +00001695 if( p->eType==JSON_OBJECT ){
drh505ad2c2015-08-21 17:33:11 +00001696 jsonReturn(pThis, ctx, 0);
1697 }else if( p->eType==JSON_ARRAY ){
1698 u32 iKey;
1699 if( p->bRecursive ){
1700 if( p->iRowid==0 ) break;
drh8784eca2015-08-23 02:42:30 +00001701 iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
drh505ad2c2015-08-21 17:33:11 +00001702 }else{
1703 iKey = p->iRowid;
1704 }
drh6fd5c1e2015-08-21 20:37:12 +00001705 sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
drhcb6c6c62015-08-19 22:47:17 +00001706 }
1707 break;
1708 }
1709 case JEACH_VALUE: {
drh852944e2015-09-10 03:29:11 +00001710 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001711 jsonReturn(pThis, ctx, 0);
1712 break;
1713 }
1714 case JEACH_TYPE: {
drh852944e2015-09-10 03:29:11 +00001715 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001716 sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
1717 break;
1718 }
1719 case JEACH_ATOM: {
drh852944e2015-09-10 03:29:11 +00001720 if( pThis->jnFlags & JNODE_LABEL ) pThis++;
drh505ad2c2015-08-21 17:33:11 +00001721 if( pThis->eType>=JSON_ARRAY ) break;
1722 jsonReturn(pThis, ctx, 0);
1723 break;
1724 }
1725 case JEACH_ID: {
drh852944e2015-09-10 03:29:11 +00001726 sqlite3_result_int64(ctx,
1727 (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
drh505ad2c2015-08-21 17:33:11 +00001728 break;
1729 }
1730 case JEACH_PARENT: {
drh852944e2015-09-10 03:29:11 +00001731 if( p->i>p->iBegin && p->bRecursive ){
drh6fd5c1e2015-08-21 20:37:12 +00001732 sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
drhcb6c6c62015-08-19 22:47:17 +00001733 }
1734 break;
1735 }
drh4af352d2015-08-21 20:02:48 +00001736 case JEACH_FULLKEY: {
1737 JsonString x;
1738 jsonInit(&x, ctx);
1739 if( p->bRecursive ){
1740 jsonEachComputePath(p, &x, p->i);
1741 }else{
drh383de692015-09-10 17:20:57 +00001742 if( p->zRoot ){
1743 jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
drh4af352d2015-08-21 20:02:48 +00001744 }else{
1745 jsonAppendChar(&x, '$');
1746 }
1747 if( p->eType==JSON_ARRAY ){
1748 jsonPrintf(30, &x, "[%d]", p->iRowid);
1749 }else{
1750 jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
1751 }
1752 }
1753 jsonResult(&x);
1754 break;
1755 }
drhcb6c6c62015-08-19 22:47:17 +00001756 case JEACH_PATH: {
drh383de692015-09-10 17:20:57 +00001757 if( p->bRecursive ){
1758 JsonString x;
1759 jsonInit(&x, ctx);
1760 jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
1761 jsonResult(&x);
1762 break;
drh4af352d2015-08-21 20:02:48 +00001763 }
drh383de692015-09-10 17:20:57 +00001764 /* For json_each() path and root are the same so fall through
1765 ** into the root case */
1766 }
1767 case JEACH_ROOT: {
1768 const char *zRoot = p->zRoot;
1769 if( zRoot==0 ) zRoot = "$";
1770 sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
drhcb6c6c62015-08-19 22:47:17 +00001771 break;
1772 }
drh3d1d2a92015-09-22 01:15:49 +00001773 case JEACH_JSON: {
drh505ad2c2015-08-21 17:33:11 +00001774 assert( i==JEACH_JSON );
drhcb6c6c62015-08-19 22:47:17 +00001775 sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
1776 break;
1777 }
1778 }
1779 return SQLITE_OK;
1780}
1781
1782/* Return the current rowid value */
1783static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1784 JsonEachCursor *p = (JsonEachCursor*)cur;
1785 *pRowid = p->iRowid;
1786 return SQLITE_OK;
1787}
1788
1789/* The query strategy is to look for an equality constraint on the json
1790** column. Without such a constraint, the table cannot operate. idxNum is
drh383de692015-09-10 17:20:57 +00001791** 1 if the constraint is found, 3 if the constraint and zRoot are found,
drhcb6c6c62015-08-19 22:47:17 +00001792** and 0 otherwise.
1793*/
1794static int jsonEachBestIndex(
1795 sqlite3_vtab *tab,
1796 sqlite3_index_info *pIdxInfo
1797){
1798 int i;
1799 int jsonIdx = -1;
drh383de692015-09-10 17:20:57 +00001800 int rootIdx = -1;
drhcb6c6c62015-08-19 22:47:17 +00001801 const struct sqlite3_index_constraint *pConstraint;
drh6fd5c1e2015-08-21 20:37:12 +00001802
1803 UNUSED_PARAM(tab);
drhcb6c6c62015-08-19 22:47:17 +00001804 pConstraint = pIdxInfo->aConstraint;
1805 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
1806 if( pConstraint->usable==0 ) continue;
1807 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
1808 switch( pConstraint->iColumn ){
1809 case JEACH_JSON: jsonIdx = i; break;
drh383de692015-09-10 17:20:57 +00001810 case JEACH_ROOT: rootIdx = i; break;
drhcb6c6c62015-08-19 22:47:17 +00001811 default: /* no-op */ break;
1812 }
1813 }
1814 if( jsonIdx<0 ){
1815 pIdxInfo->idxNum = 0;
drh505ad2c2015-08-21 17:33:11 +00001816 pIdxInfo->estimatedCost = 1e99;
drhcb6c6c62015-08-19 22:47:17 +00001817 }else{
drh505ad2c2015-08-21 17:33:11 +00001818 pIdxInfo->estimatedCost = 1.0;
drhcb6c6c62015-08-19 22:47:17 +00001819 pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
1820 pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
drh383de692015-09-10 17:20:57 +00001821 if( rootIdx<0 ){
drhcb6c6c62015-08-19 22:47:17 +00001822 pIdxInfo->idxNum = 1;
1823 }else{
drh383de692015-09-10 17:20:57 +00001824 pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
1825 pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
drhcb6c6c62015-08-19 22:47:17 +00001826 pIdxInfo->idxNum = 3;
1827 }
1828 }
1829 return SQLITE_OK;
1830}
1831
1832/* Start a search on a new JSON string */
1833static int jsonEachFilter(
1834 sqlite3_vtab_cursor *cur,
1835 int idxNum, const char *idxStr,
1836 int argc, sqlite3_value **argv
1837){
1838 JsonEachCursor *p = (JsonEachCursor*)cur;
1839 const char *z;
mistachkin16a93122015-09-11 18:05:01 +00001840 const char *zRoot = 0;
drhcb6c6c62015-08-19 22:47:17 +00001841 sqlite3_int64 n;
1842
drh6fd5c1e2015-08-21 20:37:12 +00001843 UNUSED_PARAM(idxStr);
1844 UNUSED_PARAM(argc);
drhcb6c6c62015-08-19 22:47:17 +00001845 jsonEachCursorReset(p);
1846 if( idxNum==0 ) return SQLITE_OK;
1847 z = (const char*)sqlite3_value_text(argv[0]);
1848 if( z==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001849 n = sqlite3_value_bytes(argv[0]);
drh6fd5c1e2015-08-21 20:37:12 +00001850 p->zJson = sqlite3_malloc64( n+1 );
drhcb6c6c62015-08-19 22:47:17 +00001851 if( p->zJson==0 ) return SQLITE_NOMEM;
drh6fd5c1e2015-08-21 20:37:12 +00001852 memcpy(p->zJson, z, (size_t)n+1);
drha7714022015-08-29 00:54:49 +00001853 if( jsonParse(&p->sParse, 0, p->zJson) ){
1854 int rc = SQLITE_NOMEM;
1855 if( p->sParse.oom==0 ){
1856 sqlite3_free(cur->pVtab->zErrMsg);
1857 cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
1858 if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
1859 }
drhcb6c6c62015-08-19 22:47:17 +00001860 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001861 return rc;
1862 }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
1863 jsonEachCursorReset(p);
1864 return SQLITE_NOMEM;
drhcb6c6c62015-08-19 22:47:17 +00001865 }else{
drh95677942015-09-24 01:06:37 +00001866 JsonNode *pNode = 0;
drhcb6c6c62015-08-19 22:47:17 +00001867 if( idxNum==3 ){
drha7714022015-08-29 00:54:49 +00001868 const char *zErr = 0;
drha8f39a92015-09-21 22:53:16 +00001869 zRoot = (const char*)sqlite3_value_text(argv[1]);
1870 if( zRoot==0 ) return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001871 n = sqlite3_value_bytes(argv[1]);
drh383de692015-09-10 17:20:57 +00001872 p->zRoot = sqlite3_malloc64( n+1 );
1873 if( p->zRoot==0 ) return SQLITE_NOMEM;
1874 memcpy(p->zRoot, zRoot, (size_t)n+1);
drha8f39a92015-09-21 22:53:16 +00001875 if( zRoot[0]!='$' ){
1876 zErr = zRoot;
1877 }else{
1878 pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
1879 }
1880 if( zErr ){
drha7714022015-08-29 00:54:49 +00001881 sqlite3_free(cur->pVtab->zErrMsg);
1882 cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
drhcb6c6c62015-08-19 22:47:17 +00001883 jsonEachCursorReset(p);
drha7714022015-08-29 00:54:49 +00001884 return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
1885 }else if( pNode==0 ){
drhcb6c6c62015-08-19 22:47:17 +00001886 return SQLITE_OK;
1887 }
1888 }else{
1889 pNode = p->sParse.aNode;
1890 }
drh852944e2015-09-10 03:29:11 +00001891 p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
drhcb6c6c62015-08-19 22:47:17 +00001892 p->eType = pNode->eType;
1893 if( p->eType>=JSON_ARRAY ){
drh8784eca2015-08-23 02:42:30 +00001894 pNode->u.iKey = 0;
drhc3722b22015-08-23 20:44:59 +00001895 p->iEnd = p->i + pNode->n + 1;
drh852944e2015-09-10 03:29:11 +00001896 if( p->bRecursive ){
drh3d1d2a92015-09-22 01:15:49 +00001897 p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
drh852944e2015-09-10 03:29:11 +00001898 if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
1899 p->i--;
1900 }
1901 }else{
1902 p->i++;
1903 }
drhcb6c6c62015-08-19 22:47:17 +00001904 }else{
1905 p->iEnd = p->i+1;
1906 }
1907 }
drha8f39a92015-09-21 22:53:16 +00001908 return SQLITE_OK;
drhcb6c6c62015-08-19 22:47:17 +00001909}
1910
1911/* The methods of the json_each virtual table */
1912static sqlite3_module jsonEachModule = {
1913 0, /* iVersion */
1914 0, /* xCreate */
1915 jsonEachConnect, /* xConnect */
1916 jsonEachBestIndex, /* xBestIndex */
1917 jsonEachDisconnect, /* xDisconnect */
1918 0, /* xDestroy */
drh505ad2c2015-08-21 17:33:11 +00001919 jsonEachOpenEach, /* xOpen - open a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001920 jsonEachClose, /* xClose - close a cursor */
1921 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001922 jsonEachNext, /* xNext - advance a cursor */
drhcb6c6c62015-08-19 22:47:17 +00001923 jsonEachEof, /* xEof - check for end of scan */
1924 jsonEachColumn, /* xColumn - read data */
1925 jsonEachRowid, /* xRowid - read data */
1926 0, /* xUpdate */
1927 0, /* xBegin */
1928 0, /* xSync */
1929 0, /* xCommit */
1930 0, /* xRollback */
1931 0, /* xFindMethod */
1932 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001933 0, /* xSavepoint */
1934 0, /* xRelease */
1935 0 /* xRollbackTo */
drhcb6c6c62015-08-19 22:47:17 +00001936};
1937
drh505ad2c2015-08-21 17:33:11 +00001938/* The methods of the json_tree virtual table. */
1939static sqlite3_module jsonTreeModule = {
1940 0, /* iVersion */
1941 0, /* xCreate */
1942 jsonEachConnect, /* xConnect */
1943 jsonEachBestIndex, /* xBestIndex */
1944 jsonEachDisconnect, /* xDisconnect */
1945 0, /* xDestroy */
1946 jsonEachOpenTree, /* xOpen - open a cursor */
1947 jsonEachClose, /* xClose - close a cursor */
1948 jsonEachFilter, /* xFilter - configure scan constraints */
drh4af352d2015-08-21 20:02:48 +00001949 jsonEachNext, /* xNext - advance a cursor */
drh505ad2c2015-08-21 17:33:11 +00001950 jsonEachEof, /* xEof - check for end of scan */
1951 jsonEachColumn, /* xColumn - read data */
1952 jsonEachRowid, /* xRowid - read data */
1953 0, /* xUpdate */
1954 0, /* xBegin */
1955 0, /* xSync */
1956 0, /* xCommit */
1957 0, /* xRollback */
1958 0, /* xFindMethod */
1959 0, /* xRename */
drh6fd5c1e2015-08-21 20:37:12 +00001960 0, /* xSavepoint */
1961 0, /* xRelease */
1962 0 /* xRollbackTo */
drh505ad2c2015-08-21 17:33:11 +00001963};
drhd2975922015-08-29 17:22:33 +00001964#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh505ad2c2015-08-21 17:33:11 +00001965
1966/****************************************************************************
drh2f20e132015-09-26 17:44:59 +00001967** The following routines are the only publically visible identifiers in this
1968** file. Call the following routines in order to register the various SQL
drh505ad2c2015-08-21 17:33:11 +00001969** functions and the virtual table implemented by this file.
1970****************************************************************************/
drhcb6c6c62015-08-19 22:47:17 +00001971
drh2f20e132015-09-26 17:44:59 +00001972int sqlite3Json1Init(sqlite3 *db){
drh5fa5c102015-08-12 16:49:40 +00001973 int rc = SQLITE_OK;
drh6fd5c1e2015-08-21 20:37:12 +00001974 unsigned int i;
drh5fa5c102015-08-12 16:49:40 +00001975 static const struct {
1976 const char *zName;
1977 int nArg;
drh52216ad2015-08-18 02:28:03 +00001978 int flag;
drh5fa5c102015-08-12 16:49:40 +00001979 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
1980 } aFunc[] = {
drhf5ddb9c2015-09-11 00:06:41 +00001981 { "json", 1, 0, jsonRemoveFunc },
drh52216ad2015-08-18 02:28:03 +00001982 { "json_array", -1, 0, jsonArrayFunc },
1983 { "json_array_length", 1, 0, jsonArrayLengthFunc },
1984 { "json_array_length", 2, 0, jsonArrayLengthFunc },
drh3ad93bb2015-08-29 19:41:45 +00001985 { "json_extract", -1, 0, jsonExtractFunc },
drh52216ad2015-08-18 02:28:03 +00001986 { "json_insert", -1, 0, jsonSetFunc },
1987 { "json_object", -1, 0, jsonObjectFunc },
1988 { "json_remove", -1, 0, jsonRemoveFunc },
1989 { "json_replace", -1, 0, jsonReplaceFunc },
1990 { "json_set", -1, 1, jsonSetFunc },
1991 { "json_type", 1, 0, jsonTypeFunc },
1992 { "json_type", 2, 0, jsonTypeFunc },
drhbc8f0922015-08-22 19:39:04 +00001993 { "json_valid", 1, 0, jsonValidFunc },
drh987eb1f2015-08-17 15:17:37 +00001994
drh301eecc2015-08-17 20:14:19 +00001995#if SQLITE_DEBUG
drh987eb1f2015-08-17 15:17:37 +00001996 /* DEBUG and TESTING functions */
drh52216ad2015-08-18 02:28:03 +00001997 { "json_parse", 1, 0, jsonParseFunc },
1998 { "json_test1", 1, 0, jsonTest1Func },
drh301eecc2015-08-17 20:14:19 +00001999#endif
drh5fa5c102015-08-12 16:49:40 +00002000 };
drhd2975922015-08-29 17:22:33 +00002001#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002002 static const struct {
2003 const char *zName;
2004 sqlite3_module *pModule;
2005 } aMod[] = {
2006 { "json_each", &jsonEachModule },
2007 { "json_tree", &jsonTreeModule },
2008 };
drhd2975922015-08-29 17:22:33 +00002009#endif
drh5fa5c102015-08-12 16:49:40 +00002010 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
2011 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
drh52216ad2015-08-18 02:28:03 +00002012 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
2013 (void*)&aFunc[i].flag,
drh5fa5c102015-08-12 16:49:40 +00002014 aFunc[i].xFunc, 0, 0);
2015 }
drhd2975922015-08-29 17:22:33 +00002016#ifndef SQLITE_OMIT_VIRTUALTABLE
drh505ad2c2015-08-21 17:33:11 +00002017 for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
2018 rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
drhcb6c6c62015-08-19 22:47:17 +00002019 }
drhd2975922015-08-29 17:22:33 +00002020#endif
drh5fa5c102015-08-12 16:49:40 +00002021 return rc;
2022}
drh2f20e132015-09-26 17:44:59 +00002023
2024
2025#ifdef _WIN32
2026__declspec(dllexport)
2027#endif
2028int sqlite3_json_init(
2029 sqlite3 *db,
2030 char **pzErrMsg,
2031 const sqlite3_api_routines *pApi
2032){
2033 SQLITE_EXTENSION_INIT2(pApi);
2034 (void)pzErrMsg; /* Unused parameter */
2035 return sqlite3Json1Init(db);
2036}
drh50065652015-10-08 19:29:18 +00002037#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */