blob: f81cbf75a7146f9f292801f4b129d2da8d2f3d3b [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**
18** JSON is pure text. JSONB is a binary encoding that is smaller and easier
19** to parse but which holds the equivalent information. Conversions between
20** JSON and JSONB are lossless.
21**
22** Most of the functions here will accept either JSON or JSONB input. The
23** input is understood to be JSONB if it a BLOB and JSON if the input is
24** of any other type. Functions that begin with the "json_" prefix return
25** JSON and functions that begin with "jsonb_" return JSONB.
drhbd0621b2015-08-13 13:54:59 +000026**
27** JSONB format:
28**
29** A JSONB blob is a sequence of terms. Each term begins with a single
30** variable length integer X which determines the type and size of the term.
31**
32** type = X%8
33** size = X>>3
34**
35** Term types are 0 through 7 for null, true, false, integer, real, string,
36** array, and object. The meaning of size depends on the type.
37**
38** For null, true, and false terms, the size is always 0.
39**
40** For integer terms, the size is the number of bytes that contains the
41** integer value. The value is stored as big-endian twos-complement.
42**
43** For real terms, the size is always 8 and the value is a big-ending
44** double-precision floating-point number.
45**
46** For string terms, the size is the number of bytes in the string. The
47** string itself immediately follows the X integer. There are no escapes
48** and the string is not zero-terminated. The string is always stored as
49** UTF8.
50**
51** For array terms, the size is the number of bytes in content. The
52** content consists of zero or more additional terms that are the elements
53** of the array.
54**
55** For object terms, the size is the number of bytes of content. The
56** content is zero or more pairs of terms. The first element of each
57** pair is a string term which is the label and the second element is
58** the value.
59**
60** Variable Length Integers:
61**
62** The variable length integer encoding is the 64-bit unsigned integer encoding
63** originally developed for SQLite4. The encoding for each integer is between
64** 1 and 9 bytes. Call those bytes A0 through A8. The encoding is as follows:
65**
66** If A0 is between 0 and 240 inclusive, then the value is A0.
67**
68** If A0 is between 241 and 248 inclusive, then the value is
69** 240+256*(A0-241)+A1.
70**
71** If A0 is 249 then the value is 2288+256*A1+A2.
72**
73** If A0 is 250 or more then the value is a (A0-247)-byte big-endian
74** integer taken from starting at A1.
drh5fa5c102015-08-12 16:49:40 +000075*/
76#include "sqlite3ext.h"
77SQLITE_EXTENSION_INIT1
78#include <assert.h>
79#include <string.h>
drhe9c37f32015-08-15 21:25:36 +000080#include <ctype.h>
drh5fa5c102015-08-12 16:49:40 +000081
82/* Unsigned integer types */
83typedef sqlite3_uint64 u64;
84typedef unsigned int u32;
85typedef unsigned char u8;
86
drhbd0621b2015-08-13 13:54:59 +000087/* An instance of this object represents a JSON string or
88** JSONB blob under construction.
drh5fa5c102015-08-12 16:49:40 +000089*/
90typedef struct Json Json;
91struct Json {
92 sqlite3_context *pCtx; /* Function context - put error messages here */
drhbd0621b2015-08-13 13:54:59 +000093 char *zBuf; /* Append JSON or JSONB 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 */
drhe9c37f32015-08-15 21:25:36 +000097 u8 oom; /* True if an OOM 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
112/* A single node of parsed JSON
113*/
114typedef struct JsonNode JsonNode;
115struct JsonNode {
116 u32 eType; /* One of the JSON_ type values */
117 u32 n; /* Bytes of content, or number of sub-nodes */
118 const char *zContent; /* Content for JSON_INT, JSON_REAL, or JSON_STRING */
119};
120
121/* A completely parsed JSON string
122*/
123typedef struct JsonParse JsonParse;
124struct JsonParse {
125 u32 nNode; /* Number of slots of aNode[] used */
126 u32 nAlloc; /* Number of slots of aNode[] allocated */
127 JsonNode *aNode; /* Array of nodes containing the parse */
128 const char *zJson; /* Original JSON string */
129 u8 oom; /* Set to true if out of memory */
130};
131
drhbd0621b2015-08-13 13:54:59 +0000132
133#if 0
134/*
135** Decode the varint in the first n bytes z[]. Write the integer value
136** into *pResult and return the number of bytes in the varint.
137**
138** If the decode fails because there are not enough bytes in z[] then
139** return 0;
140*/
141static int jsonGetVarint64(
142 const unsigned char *z,
143 int n,
144 u64 *pResult
145){
146 unsigned int x;
147 if( n<1 ) return 0;
148 if( z[0]<=240 ){
149 *pResult = z[0];
150 return 1;
151 }
152 if( z[0]<=248 ){
153 if( n<2 ) return 0;
154 *pResult = (z[0]-241)*256 + z[1] + 240;
155 return 2;
156 }
157 if( n<z[0]-246 ) return 0;
158 if( z[0]==249 ){
159 *pResult = 2288 + 256*z[1] + z[2];
160 return 3;
161 }
162 if( z[0]==250 ){
163 *pResult = (z[1]<<16) + (z[2]<<8) + z[3];
164 return 4;
165 }
166 x = (z[1]<<24) + (z[2]<<16) + (z[3]<<8) + z[4];
167 if( z[0]==251 ){
168 *pResult = x;
169 return 5;
170 }
171 if( z[0]==252 ){
172 *pResult = (((u64)x)<<8) + z[5];
173 return 6;
174 }
175 if( z[0]==253 ){
176 *pResult = (((u64)x)<<16) + (z[5]<<8) + z[6];
177 return 7;
178 }
179 if( z[0]==254 ){
180 *pResult = (((u64)x)<<24) + (z[5]<<16) + (z[6]<<8) + z[7];
181 return 8;
182 }
183 *pResult = (((u64)x)<<32) +
184 (0xffffffff & ((z[5]<<24) + (z[6]<<16) + (z[7]<<8) + z[8]));
185 return 9;
186}
187#endif
188
drh5fa5c102015-08-12 16:49:40 +0000189/* Set the Json object to an empty string
190*/
191static void jsonZero(Json *p){
192 p->zBuf = p->zSpace;
193 p->nAlloc = sizeof(p->zSpace);
194 p->nUsed = 0;
195 p->bStatic = 1;
196}
197
198/* Initialize the Json object
199*/
200static void jsonInit(Json *p, sqlite3_context *pCtx){
201 p->pCtx = pCtx;
drhe9c37f32015-08-15 21:25:36 +0000202 p->oom = 0;
drh5fa5c102015-08-12 16:49:40 +0000203 jsonZero(p);
204}
205
206
207/* Free all allocated memory and reset the Json object back to its
208** initial state.
209*/
210static void jsonReset(Json *p){
211 if( !p->bStatic ) sqlite3_free(p->zBuf);
212 jsonZero(p);
213}
214
215
216/* Report an out-of-memory (OOM) condition
217*/
218static void jsonOom(Json *p){
drhe9c37f32015-08-15 21:25:36 +0000219 p->oom = 1;
drh5fa5c102015-08-12 16:49:40 +0000220 sqlite3_result_error_nomem(p->pCtx);
221 jsonReset(p);
222}
223
224/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
225** Return zero on success. Return non-zero on an OOM error
226*/
227static int jsonGrow(Json *p, u32 N){
228 u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+100;
229 char *zNew;
230 if( p->bStatic ){
drhe9c37f32015-08-15 21:25:36 +0000231 if( p->oom ) return SQLITE_NOMEM;
drh5fa5c102015-08-12 16:49:40 +0000232 zNew = sqlite3_malloc64(nTotal);
233 if( zNew==0 ){
234 jsonOom(p);
235 return SQLITE_NOMEM;
236 }
237 memcpy(zNew, p->zBuf, p->nUsed);
238 p->zBuf = zNew;
239 p->bStatic = 0;
240 }else{
241 zNew = sqlite3_realloc64(p->zBuf, nTotal);
242 if( zNew==0 ){
243 jsonOom(p);
244 return SQLITE_NOMEM;
245 }
246 p->zBuf = zNew;
247 }
248 p->nAlloc = nTotal;
249 return SQLITE_OK;
250}
251
252/* Append N bytes from zIn onto the end of the Json string.
253*/
254static void jsonAppendRaw(Json *p, const char *zIn, u32 N){
255 if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
256 memcpy(p->zBuf+p->nUsed, zIn, N);
257 p->nUsed += N;
258}
259
drhe9c37f32015-08-15 21:25:36 +0000260/* Append the zero-terminated string zIn
261*/
262static void jsonAppend(Json *p, const char *zIn){
263 jsonAppendRaw(p, zIn, (u32)strlen(zIn));
264}
265
drh5fa5c102015-08-12 16:49:40 +0000266/* Append the N-byte string in zIn to the end of the Json string
267** under construction. Enclose the string in "..." and escape
268** any double-quotes or backslash characters contained within the
269** string.
270*/
271static void jsonAppendString(Json *p, const char *zIn, u32 N){
272 u32 i;
273 if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
274 p->zBuf[p->nUsed++] = '"';
275 for(i=0; i<N; i++){
276 char c = zIn[i];
277 if( c=='"' || c=='\\' ){
278 if( (p->nUsed+N+1-i > p->nAlloc) && jsonGrow(p,N+1-i)!=0 ) return;
279 p->zBuf[p->nUsed++] = '\\';
280 }
281 p->zBuf[p->nUsed++] = c;
282 }
283 p->zBuf[p->nUsed++] = '"';
284}
285
drhbd0621b2015-08-13 13:54:59 +0000286/*
287** Write a 32-bit unsigned integer as 4 big-endian bytes.
288*/
289static void jsonPutInt32(unsigned char *z, unsigned int y){
290 z[0] = (unsigned char)(y>>24);
291 z[1] = (unsigned char)(y>>16);
292 z[2] = (unsigned char)(y>>8);
293 z[3] = (unsigned char)(y);
294}
295
296
297/* Write integer X as a variable-length integer into the buffer z[].
298** z[] is guaranteed to be at least 9 bytes in length. Return the
299** number of bytes written.
300*/
301int jsonPutVarint64(char *zIn, u64 x){
302 unsigned char *z = (unsigned char*)zIn;
303 unsigned int w, y;
304 if( x<=240 ){
305 z[0] = (unsigned char)x;
306 return 1;
307 }
308 if( x<=2287 ){
309 y = (unsigned int)(x - 240);
310 z[0] = (unsigned char)(y/256 + 241);
311 z[1] = (unsigned char)(y%256);
312 return 2;
313 }
314 if( x<=67823 ){
315 y = (unsigned int)(x - 2288);
316 z[0] = 249;
317 z[1] = (unsigned char)(y/256);
318 z[2] = (unsigned char)(y%256);
319 return 3;
320 }
321 y = (unsigned int)x;
322 w = (unsigned int)(x>>32);
323 if( w==0 ){
324 if( y<=16777215 ){
325 z[0] = 250;
326 z[1] = (unsigned char)(y>>16);
327 z[2] = (unsigned char)(y>>8);
328 z[3] = (unsigned char)(y);
329 return 4;
330 }
331 z[0] = 251;
332 jsonPutInt32(z+1, y);
333 return 5;
334 }
335 if( w<=255 ){
336 z[0] = 252;
337 z[1] = (unsigned char)w;
338 jsonPutInt32(z+2, y);
339 return 6;
340 }
341 if( w<=65535 ){
342 z[0] = 253;
343 z[1] = (unsigned char)(w>>8);
344 z[2] = (unsigned char)w;
345 jsonPutInt32(z+3, y);
346 return 7;
347 }
348 if( w<=16777215 ){
349 z[0] = 254;
350 z[1] = (unsigned char)(w>>16);
351 z[2] = (unsigned char)(w>>8);
352 z[3] = (unsigned char)w;
353 jsonPutInt32(z+4, y);
354 return 8;
355 }
356 z[0] = 255;
357 jsonPutInt32(z+1, w);
358 jsonPutInt32(z+5, y);
359 return 9;
360}
361
362
363/* Append integer X as a variable-length integer on the JSONB currently
364** under construction in p.
365*/
366static void jsonAppendVarint(Json *p, u64 X){
367 if( (p->nUsed+9 > p->nAlloc) && jsonGrow(p,9)!=0 ) return;
368 p->nUsed += jsonPutVarint64(p->zBuf+p->nUsed, X);
369}
370
371/* Make the JSON in p the result of the SQL function.
drh5fa5c102015-08-12 16:49:40 +0000372*/
373static void jsonResult(Json *p){
drhe9c37f32015-08-15 21:25:36 +0000374 if( p->oom==0 ){
drh5fa5c102015-08-12 16:49:40 +0000375 sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
376 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
377 SQLITE_UTF8);
378 jsonZero(p);
379 }
380 assert( p->bStatic );
381}
382
drhbd0621b2015-08-13 13:54:59 +0000383/* Make the JSONB in p the result of the SQL function.
384*/
385static void jsonbResult(Json *p){
drhe9c37f32015-08-15 21:25:36 +0000386 if( p->oom==0 ){
drhbd0621b2015-08-13 13:54:59 +0000387 sqlite3_result_blob(p->pCtx, p->zBuf, p->nUsed,
388 p->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
389 jsonZero(p);
390 }
391 assert( p->bStatic );
392}
393
drh5fa5c102015-08-12 16:49:40 +0000394/*
395** Implementation of the json_array(VALUE,...) function. Return a JSON
396** array that contains all values given in arguments. Or if any argument
397** is a BLOB, throw an error.
398*/
399static void jsonArrayFunc(
400 sqlite3_context *context,
401 int argc,
402 sqlite3_value **argv
403){
404 int i;
405 Json jx;
406 char cSep = '[';
407
408 jsonInit(&jx, context);
409 for(i=0; i<argc; i++){
410 jsonAppendRaw(&jx, &cSep, 1);
411 cSep = ',';
412 switch( sqlite3_value_type(argv[i]) ){
413 case SQLITE_NULL: {
414 jsonAppendRaw(&jx, "null", 4);
415 break;
416 }
417 case SQLITE_INTEGER:
418 case SQLITE_FLOAT: {
419 const char *z = (const char*)sqlite3_value_text(argv[i]);
420 u32 n = (u32)sqlite3_value_bytes(argv[i]);
421 jsonAppendRaw(&jx, z, n);
422 break;
423 }
424 case SQLITE_TEXT: {
425 const char *z = (const char*)sqlite3_value_text(argv[i]);
426 u32 n = (u32)sqlite3_value_bytes(argv[i]);
427 jsonAppendString(&jx, z, n);
428 break;
429 }
430 default: {
431 jsonZero(&jx);
432 sqlite3_result_error(context, "JSON cannot hold BLOB values", -1);
433 return;
434 }
435 }
436 }
437 jsonAppendRaw(&jx, "]", 1);
drh2032d602015-08-12 17:23:34 +0000438 jsonResult(&jx);
439}
440
441/*
drhbd0621b2015-08-13 13:54:59 +0000442** Implementation of the jsonb_array(VALUE,...) function. Return a JSON
443** array that contains all values given in arguments. Or if any argument
444** is a BLOB, throw an error.
445*/
446static void jsonbArrayFunc(
447 sqlite3_context *context,
448 int argc,
449 sqlite3_value **argv
450){
451 int i;
452 Json jx;
453
454 jsonInit(&jx, context);
455 jx.nUsed = 5;
456 for(i=0; i<argc; i++){
457 switch( sqlite3_value_type(argv[i]) ){
458 case SQLITE_NULL: {
drhe9c37f32015-08-15 21:25:36 +0000459 jsonAppendVarint(&jx, JSON_NULL);
drhbd0621b2015-08-13 13:54:59 +0000460 break;
461 }
462 case SQLITE_INTEGER:
463 case SQLITE_FLOAT: {
464 const char *z = (const char*)sqlite3_value_text(argv[i]);
465 u32 n = (u32)sqlite3_value_bytes(argv[i]);
466 jsonAppendRaw(&jx, z, n);
467 break;
468 }
469 case SQLITE_TEXT: {
470 const char *z = (const char*)sqlite3_value_text(argv[i]);
471 u32 n = (u32)sqlite3_value_bytes(argv[i]);
drhe9c37f32015-08-15 21:25:36 +0000472 jsonAppendVarint(&jx, JSON_STRING + 4*(u64)n);
drhbd0621b2015-08-13 13:54:59 +0000473 jsonAppendString(&jx, z, n);
474 break;
475 }
476 default: {
477 jsonZero(&jx);
478 sqlite3_result_error(context, "JSON cannot hold BLOB values", -1);
479 return;
480 }
481 }
482 }
drhe9c37f32015-08-15 21:25:36 +0000483 if( jx.oom==0 ){
drhbd0621b2015-08-13 13:54:59 +0000484 jx.zBuf[0] = 251;
485 jsonPutInt32((unsigned char*)(jx.zBuf+1), jx.nUsed-5);
486 jsonbResult(&jx);
487 }
488}
489
490/*
drh2032d602015-08-12 17:23:34 +0000491** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
492** object that contains all name/value given in arguments. Or if any name
493** is not a string or if any value is a BLOB, throw an error.
494*/
495static void jsonObjectFunc(
496 sqlite3_context *context,
497 int argc,
498 sqlite3_value **argv
499){
500 int i;
501 Json jx;
502 char cSep = '{';
503 const char *z;
504 u32 n;
505
506 if( argc&1 ){
507 sqlite3_result_error(context, "json_object() requires an even number "
508 "of arguments", -1);
509 return;
510 }
511 jsonInit(&jx, context);
512 for(i=0; i<argc; i+=2){
513 jsonAppendRaw(&jx, &cSep, 1);
514 cSep = ',';
515 if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
516 sqlite3_result_error(context, "json_object() labels must be TEXT", -1);
517 jsonZero(&jx);
518 return;
519 }
520 z = (const char*)sqlite3_value_text(argv[i]);
521 n = (u32)sqlite3_value_bytes(argv[i]);
522 jsonAppendString(&jx, z, n);
523 jsonAppendRaw(&jx, ":", 1);
524 switch( sqlite3_value_type(argv[i+1]) ){
525 case SQLITE_NULL: {
526 jsonAppendRaw(&jx, "null", 4);
527 break;
528 }
529 case SQLITE_INTEGER:
530 case SQLITE_FLOAT: {
531 z = (const char*)sqlite3_value_text(argv[i+1]);
532 n = (u32)sqlite3_value_bytes(argv[i+1]);
533 jsonAppendRaw(&jx, z, n);
534 break;
535 }
536 case SQLITE_TEXT: {
537 z = (const char*)sqlite3_value_text(argv[i+1]);
538 n = (u32)sqlite3_value_bytes(argv[i+1]);
539 jsonAppendString(&jx, z, n);
540 break;
541 }
542 default: {
543 jsonZero(&jx);
544 sqlite3_result_error(context, "JSON cannot hold BLOB values", -1);
545 return;
546 }
547 }
548 }
549 jsonAppendRaw(&jx, "}", 1);
550 jsonResult(&jx);
drh5fa5c102015-08-12 16:49:40 +0000551}
552
drhe9c37f32015-08-15 21:25:36 +0000553/*
554** Create a new JsonNode instance based on the arguments and append that
555** instance to the JsonParse. Return the index in pParse->aNode[] of the
556** new node, or -1 if a memory allocation fails.
557*/
558static int jsonParseAddNode(
559 JsonParse *pParse, /* Append the node to this object */
560 u32 eType, /* Node type */
561 u32 n, /* Content size or sub-node count */
562 const char *zContent /* Content */
563){
564 JsonNode *p;
565 if( pParse->nNode>=pParse->nAlloc ){
566 u32 nNew;
567 JsonNode *pNew;
568 if( pParse->oom ) return -1;
569 nNew = pParse->nAlloc*2 + 10;
570 if( nNew<=pParse->nNode ){
571 pParse->oom = 1;
572 return -1;
573 }
574 pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
575 if( pNew==0 ){
576 pParse->oom = 1;
577 return -1;
578 }
579 pParse->nAlloc = nNew;
580 pParse->aNode = pNew;
581 }
582 p = &pParse->aNode[pParse->nNode];
583 p->eType = eType;
584 p->n = n;
585 p->zContent = zContent;
586 return pParse->nNode++;
587}
588
589/*
590** Parse a single JSON value which begins at pParse->zJson[i]. Return the
591** index of the first character past the end of the value parsed.
592**
593** Return negative for a syntax error. Special cases: return -2 if the
594** first non-whitespace character is '}' and return -3 if the first
595** non-whitespace character is ']'.
596*/
597static int jsonParseValue(JsonParse *pParse, u32 i){
598 char c;
599 u32 j;
600 u32 iThis;
601 int x;
602 while( isspace(pParse->zJson[i]) ){ i++; }
603 if( (c = pParse->zJson[i])==0 ) return 0;
604 if( c=='{' ){
605 /* Parse object */
606 iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
607 if( iThis<0 ) return -1;
608 for(j=i+1;;j++){
609 while( isspace(pParse->zJson[j]) ){ j++; }
610 x = jsonParseValue(pParse, j);
611 if( x<0 ){
612 if( x==(-2) && pParse->nNode==iThis+1 ) return j+1;
613 return -1;
614 }
615 if( pParse->aNode[pParse->nNode-1].eType!=JSON_STRING ) return -1;
616 j = x;
617 while( isspace(pParse->zJson[j]) ){ j++; }
618 if( pParse->zJson[j]!=':' ) return -1;
619 j++;
620 x = jsonParseValue(pParse, j);
621 if( x<0 ) return -1;
622 j = x;
623 while( isspace(pParse->zJson[j]) ){ j++; }
624 c = pParse->zJson[j];
625 if( c==',' ) continue;
626 if( c!='}' ) return -1;
627 break;
628 }
629 pParse->aNode[iThis].n = pParse->nNode - iThis - 1;
630 return j+1;
631 }else if( c=='[' ){
632 /* Parse array */
633 iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
634 if( iThis<0 ) return -1;
635 for(j=i+1;;j++){
636 while( isspace(pParse->zJson[j]) ){ j++; }
637 x = jsonParseValue(pParse, j);
638 if( x<0 ){
639 if( x==(-3) && pParse->nNode==iThis+1 ) return j+1;
640 return -1;
641 }
642 j = x;
643 while( isspace(pParse->zJson[j]) ){ j++; }
644 c = pParse->zJson[j];
645 if( c==',' ) continue;
646 if( c!=']' ) return -1;
647 break;
648 }
649 pParse->aNode[iThis].n = pParse->nNode - iThis - 1;
650 return j+1;
651 }else if( c=='"' ){
652 /* Parse string */
653 j = i+1;
654 for(;;){
655 c = pParse->zJson[j];
656 if( c==0 ) return -1;
657 if( c=='\\' ){
658 c = pParse->zJson[++j];
659 if( c==0 ) return -1;
660 }else if( c=='"' ){
661 break;
662 }
663 j++;
664 }
665 jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
666 return j+1;
667 }else if( c=='n'
668 && strncmp(pParse->zJson+i,"null",4)==0
drhb2cd10e2015-08-15 21:29:14 +0000669 && !isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000670 jsonParseAddNode(pParse, JSON_NULL, 0, 0);
671 return i+4;
672 }else if( c=='t'
673 && strncmp(pParse->zJson+i,"true",4)==0
drhb2cd10e2015-08-15 21:29:14 +0000674 && !isalnum(pParse->zJson[i+4]) ){
drhe9c37f32015-08-15 21:25:36 +0000675 jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
676 return i+4;
677 }else if( c=='f'
678 && strncmp(pParse->zJson+i,"false",5)==0
drhb2cd10e2015-08-15 21:29:14 +0000679 && !isalnum(pParse->zJson[i+5]) ){
drhe9c37f32015-08-15 21:25:36 +0000680 jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
681 return i+5;
682 }else if( c=='-' || (c>='0' && c<='9') ){
683 /* Parse number */
684 u8 seenDP = 0;
685 u8 seenE = 0;
686 j = i+1;
687 for(;; j++){
688 c = pParse->zJson[j];
689 if( c>='0' && c<='9' ) continue;
690 if( c=='.' ){
691 if( pParse->zJson[j-1]=='-' ) return -1;
692 if( seenDP ) return -1;
693 seenDP = 1;
694 continue;
695 }
696 if( c=='e' || c=='E' ){
697 if( pParse->zJson[j-1]<'0' ) return -1;
698 if( seenE ) return -1;
699 seenDP = seenE = 1;
700 c = pParse->zJson[j+1];
701 if( c=='+' || c=='-' ) j++;
702 continue;
703 }
704 break;
705 }
706 if( pParse->zJson[j-1]<'0' ) return -1;
707 jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
708 j - i, &pParse->zJson[i]);
709 return j;
710 }else if( c=='}' ){
711 return -2; /* End of {...} */
712 }else if( c==']' ){
713 return -3; /* End of [...] */
714 }else{
715 return -1; /* Syntax error */
716 }
717}
718
719/*
720** Parse a complete JSON string. Return 0 on success or non-zero if there
721** are any errors. If an error occurs, free all memory associated with
722** pParse.
723**
724** pParse is uninitialized when this routine is called.
725*/
726static int jsonParse(JsonParse *pParse, const char *zJson){
727 int i;
728 if( zJson==0 ) return 1;
729 memset(pParse, 0, sizeof(*pParse));
730 pParse->zJson = zJson;
731 i = jsonParseValue(pParse, 0);
732 if( i>0 ){
733 while( isspace(zJson[i]) ) i++;
734 if( zJson[i] ) i = -1;
735 }
736 if( i<0 ){
737 sqlite3_free(pParse->aNode);
738 pParse->aNode = 0;
739 pParse->nNode = 0;
740 pParse->nAlloc = 0;
741 return 1;
742 }
743 return 0;
744}
745
746/*
747** The json_debug(JSON) function returns a string which describes
748** a parse of the JSON provided. Or it returns NULL if JSON is not
749** well-formed.
750*/
751static void jsonDebugFunc(
752 sqlite3_context *context,
753 int argc,
754 sqlite3_value **argv
755){
756 Json s; /* Output string - not real JSON */
757 JsonParse x; /* The parse */
758 u32 i;
759 char zBuf[50];
760 static const char *azType[] = {
761 "NULL", "TRUE", "FALSE", "INT", "REAL", "STRING", "ARRAY", "OBJECT"
762 };
763
764 assert( argc==1 );
765 if( jsonParse(&x, (const char*)sqlite3_value_text(argv[0])) ) return;
766 jsonInit(&s, context);
767 for(i=0; i<x.nNode; i++){
768 sqlite3_snprintf(sizeof(zBuf), zBuf, "node %u:\n", i);
769 jsonAppend(&s, zBuf);
770 sqlite3_snprintf(sizeof(zBuf), zBuf, " type: %s\n",
771 azType[x.aNode[i].eType]);
772 jsonAppend(&s, zBuf);
773 if( x.aNode[i].eType>=JSON_INT ){
774 sqlite3_snprintf(sizeof(zBuf), zBuf, " n: %u\n", x.aNode[i].n);
775 jsonAppend(&s, zBuf);
776 }
777 if( x.aNode[i].zContent!=0 ){
778 sqlite3_snprintf(sizeof(zBuf), zBuf, " ofst: %u\n",
779 (u32)(x.aNode[i].zContent - x.zJson));
780 jsonAppend(&s, zBuf);
781 jsonAppendRaw(&s, " text: ", 8);
782 jsonAppendRaw(&s, x.aNode[i].zContent, x.aNode[i].n);
783 jsonAppendRaw(&s, "\n", 1);
784 }
785 }
786 sqlite3_free(x.aNode);
787 jsonResult(&s);
788}
789
drh5fa5c102015-08-12 16:49:40 +0000790#ifdef _WIN32
791__declspec(dllexport)
792#endif
793int sqlite3_json_init(
794 sqlite3 *db,
795 char **pzErrMsg,
796 const sqlite3_api_routines *pApi
797){
798 int rc = SQLITE_OK;
799 int i;
800 static const struct {
801 const char *zName;
802 int nArg;
803 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
804 } aFunc[] = {
drh2032d602015-08-12 17:23:34 +0000805 { "json_array", -1, jsonArrayFunc },
drhbd0621b2015-08-13 13:54:59 +0000806 { "jsonb_array", -1, jsonbArrayFunc },
drh2032d602015-08-12 17:23:34 +0000807 { "json_object", -1, jsonObjectFunc },
drhe9c37f32015-08-15 21:25:36 +0000808 { "json_debug", 1, jsonDebugFunc },
drh5fa5c102015-08-12 16:49:40 +0000809 };
810 SQLITE_EXTENSION_INIT2(pApi);
811 (void)pzErrMsg; /* Unused parameter */
812 for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
813 rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
814 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
815 aFunc[i].xFunc, 0, 0);
816 }
817 return rc;
818}