modernc.org/cc@v1.0.1/v2/testdata/_sqlite/ext/misc/json1.c (about)

     1  /*
     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  ** 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
    20  ** 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.)
    23  */
    24  #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
    25  #if !defined(SQLITEINT_H)
    26  #include "sqlite3ext.h"
    27  #endif
    28  SQLITE_EXTENSION_INIT1
    29  #include <assert.h>
    30  #include <string.h>
    31  #include <stdlib.h>
    32  #include <stdarg.h>
    33  
    34  /* Mark a function parameter as unused, to suppress nuisance compiler
    35  ** warnings. */
    36  #ifndef UNUSED_PARAM
    37  # define UNUSED_PARAM(X)  (void)(X)
    38  #endif
    39  
    40  #ifndef LARGEST_INT64
    41  # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
    42  # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
    43  #endif
    44  
    45  /*
    46  ** Versions of isspace(), isalnum() and isdigit() to which it is safe
    47  ** to pass signed char values.
    48  */
    49  #ifdef sqlite3Isdigit
    50     /* Use the SQLite core versions if this routine is part of the
    51     ** SQLite amalgamation */
    52  #  define safe_isdigit(x)  sqlite3Isdigit(x)
    53  #  define safe_isalnum(x)  sqlite3Isalnum(x)
    54  #  define safe_isxdigit(x) sqlite3Isxdigit(x)
    55  #else
    56     /* Use the standard library for separate compilation */
    57  #include <ctype.h>  /* amalgamator: keep */
    58  #  define safe_isdigit(x)  isdigit((unsigned char)(x))
    59  #  define safe_isalnum(x)  isalnum((unsigned char)(x))
    60  #  define safe_isxdigit(x) isxdigit((unsigned char)(x))
    61  #endif
    62  
    63  /*
    64  ** Growing our own isspace() routine this way is twice as fast as
    65  ** the library isspace() function, resulting in a 7% overall performance
    66  ** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
    67  */
    68  static const char jsonIsSpace[] = {
    69    0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
    70    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    71    1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    72    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    73    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    74    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    75    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    76    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    77    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    78    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    79    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    80    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    81    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    82    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    83    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    84    0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
    85  };
    86  #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
    87  
    88  #ifndef SQLITE_AMALGAMATION
    89    /* Unsigned integer types.  These are already defined in the sqliteInt.h,
    90    ** but the definitions need to be repeated for separate compilation. */
    91    typedef sqlite3_uint64 u64;
    92    typedef unsigned int u32;
    93    typedef unsigned short int u16;
    94    typedef unsigned char u8;
    95  #endif
    96  
    97  /* Objects */
    98  typedef struct JsonString JsonString;
    99  typedef struct JsonNode JsonNode;
   100  typedef struct JsonParse JsonParse;
   101  
   102  /* An instance of this object represents a JSON string
   103  ** under construction.  Really, this is a generic string accumulator
   104  ** that can be and is used to create strings other than JSON.
   105  */
   106  struct JsonString {
   107    sqlite3_context *pCtx;   /* Function context - put error messages here */
   108    char *zBuf;              /* Append JSON content here */
   109    u64 nAlloc;              /* Bytes of storage available in zBuf[] */
   110    u64 nUsed;               /* Bytes of zBuf[] currently used */
   111    u8 bStatic;              /* True if zBuf is static space */
   112    u8 bErr;                 /* True if an error has been encountered */
   113    char zSpace[100];        /* Initial static space */
   114  };
   115  
   116  /* JSON type values
   117  */
   118  #define JSON_NULL     0
   119  #define JSON_TRUE     1
   120  #define JSON_FALSE    2
   121  #define JSON_INT      3
   122  #define JSON_REAL     4
   123  #define JSON_STRING   5
   124  #define JSON_ARRAY    6
   125  #define JSON_OBJECT   7
   126  
   127  /* The "subtype" set for JSON values */
   128  #define JSON_SUBTYPE  74    /* Ascii for "J" */
   129  
   130  /*
   131  ** Names of the various JSON types:
   132  */
   133  static const char * const jsonType[] = {
   134    "null", "true", "false", "integer", "real", "text", "array", "object"
   135  };
   136  
   137  /* Bit values for the JsonNode.jnFlag field
   138  */
   139  #define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
   140  #define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
   141  #define JNODE_REMOVE  0x04         /* Do not output */
   142  #define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
   143  #define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
   144  #define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
   145  #define JNODE_LABEL   0x40         /* Is a label of an object */
   146  
   147  
   148  /* A single node of parsed JSON
   149  */
   150  struct JsonNode {
   151    u8 eType;              /* One of the JSON_ type values */
   152    u8 jnFlags;            /* JNODE flags */
   153    u32 n;                 /* Bytes of content, or number of sub-nodes */
   154    union {
   155      const char *zJContent; /* Content for INT, REAL, and STRING */
   156      u32 iAppend;           /* More terms for ARRAY and OBJECT */
   157      u32 iKey;              /* Key for ARRAY objects in json_tree() */
   158      u32 iReplace;          /* Replacement content for JNODE_REPLACE */
   159      JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
   160    } u;
   161  };
   162  
   163  /* A completely parsed JSON string
   164  */
   165  struct JsonParse {
   166    u32 nNode;         /* Number of slots of aNode[] used */
   167    u32 nAlloc;        /* Number of slots of aNode[] allocated */
   168    JsonNode *aNode;   /* Array of nodes containing the parse */
   169    const char *zJson; /* Original JSON string */
   170    u32 *aUp;          /* Index of parent of each node */
   171    u8 oom;            /* Set to true if out of memory */
   172    u8 nErr;           /* Number of errors seen */
   173    u16 iDepth;        /* Nesting depth */
   174    int nJson;         /* Length of the zJson string in bytes */
   175  };
   176  
   177  /*
   178  ** Maximum nesting depth of JSON for this implementation.
   179  **
   180  ** This limit is needed to avoid a stack overflow in the recursive
   181  ** descent parser.  A depth of 2000 is far deeper than any sane JSON
   182  ** should go.
   183  */
   184  #define JSON_MAX_DEPTH  2000
   185  
   186  /**************************************************************************
   187  ** Utility routines for dealing with JsonString objects
   188  **************************************************************************/
   189  
   190  /* Set the JsonString object to an empty string
   191  */
   192  static void jsonZero(JsonString *p){
   193    p->zBuf = p->zSpace;
   194    p->nAlloc = sizeof(p->zSpace);
   195    p->nUsed = 0;
   196    p->bStatic = 1;
   197  }
   198  
   199  /* Initialize the JsonString object
   200  */
   201  static void jsonInit(JsonString *p, sqlite3_context *pCtx){
   202    p->pCtx = pCtx;
   203    p->bErr = 0;
   204    jsonZero(p);
   205  }
   206  
   207  
   208  /* Free all allocated memory and reset the JsonString object back to its
   209  ** initial state.
   210  */
   211  static void jsonReset(JsonString *p){
   212    if( !p->bStatic ) sqlite3_free(p->zBuf);
   213    jsonZero(p);
   214  }
   215  
   216  
   217  /* Report an out-of-memory (OOM) condition 
   218  */
   219  static void jsonOom(JsonString *p){
   220    p->bErr = 1;
   221    sqlite3_result_error_nomem(p->pCtx);
   222    jsonReset(p);
   223  }
   224  
   225  /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
   226  ** Return zero on success.  Return non-zero on an OOM error
   227  */
   228  static int jsonGrow(JsonString *p, u32 N){
   229    u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
   230    char *zNew;
   231    if( p->bStatic ){
   232      if( p->bErr ) return 1;
   233      zNew = sqlite3_malloc64(nTotal);
   234      if( zNew==0 ){
   235        jsonOom(p);
   236        return SQLITE_NOMEM;
   237      }
   238      memcpy(zNew, p->zBuf, (size_t)p->nUsed);
   239      p->zBuf = zNew;
   240      p->bStatic = 0;
   241    }else{
   242      zNew = sqlite3_realloc64(p->zBuf, nTotal);
   243      if( zNew==0 ){
   244        jsonOom(p);
   245        return SQLITE_NOMEM;
   246      }
   247      p->zBuf = zNew;
   248    }
   249    p->nAlloc = nTotal;
   250    return SQLITE_OK;
   251  }
   252  
   253  /* Append N bytes from zIn onto the end of the JsonString string.
   254  */
   255  static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
   256    if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
   257    memcpy(p->zBuf+p->nUsed, zIn, N);
   258    p->nUsed += N;
   259  }
   260  
   261  /* Append formatted text (not to exceed N bytes) to the JsonString.
   262  */
   263  static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
   264    va_list ap;
   265    if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
   266    va_start(ap, zFormat);
   267    sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
   268    va_end(ap);
   269    p->nUsed += (int)strlen(p->zBuf+p->nUsed);
   270  }
   271  
   272  /* Append a single character
   273  */
   274  static void jsonAppendChar(JsonString *p, char c){
   275    if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
   276    p->zBuf[p->nUsed++] = c;
   277  }
   278  
   279  /* Append a comma separator to the output buffer, if the previous
   280  ** character is not '[' or '{'.
   281  */
   282  static void jsonAppendSeparator(JsonString *p){
   283    char c;
   284    if( p->nUsed==0 ) return;
   285    c = p->zBuf[p->nUsed-1];
   286    if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
   287  }
   288  
   289  /* Append the N-byte string in zIn to the end of the JsonString string
   290  ** under construction.  Enclose the string in "..." and escape
   291  ** any double-quotes or backslash characters contained within the
   292  ** string.
   293  */
   294  static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
   295    u32 i;
   296    if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
   297    p->zBuf[p->nUsed++] = '"';
   298    for(i=0; i<N; i++){
   299      unsigned char c = ((unsigned const char*)zIn)[i];
   300      if( c=='"' || c=='\\' ){
   301        json_simple_escape:
   302        if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
   303        p->zBuf[p->nUsed++] = '\\';
   304      }else if( c<=0x1f ){
   305        static const char aSpecial[] = {
   306           0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
   307           0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
   308        };
   309        assert( sizeof(aSpecial)==32 );
   310        assert( aSpecial['\b']=='b' );
   311        assert( aSpecial['\f']=='f' );
   312        assert( aSpecial['\n']=='n' );
   313        assert( aSpecial['\r']=='r' );
   314        assert( aSpecial['\t']=='t' );
   315        if( aSpecial[c] ){
   316          c = aSpecial[c];
   317          goto json_simple_escape;
   318        }
   319        if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
   320        p->zBuf[p->nUsed++] = '\\';
   321        p->zBuf[p->nUsed++] = 'u';
   322        p->zBuf[p->nUsed++] = '0';
   323        p->zBuf[p->nUsed++] = '0';
   324        p->zBuf[p->nUsed++] = '0' + (c>>4);
   325        c = "0123456789abcdef"[c&0xf];
   326      }
   327      p->zBuf[p->nUsed++] = c;
   328    }
   329    p->zBuf[p->nUsed++] = '"';
   330    assert( p->nUsed<p->nAlloc );
   331  }
   332  
   333  /*
   334  ** Append a function parameter value to the JSON string under 
   335  ** construction.
   336  */
   337  static void jsonAppendValue(
   338    JsonString *p,                 /* Append to this JSON string */
   339    sqlite3_value *pValue          /* Value to append */
   340  ){
   341    switch( sqlite3_value_type(pValue) ){
   342      case SQLITE_NULL: {
   343        jsonAppendRaw(p, "null", 4);
   344        break;
   345      }
   346      case SQLITE_INTEGER:
   347      case SQLITE_FLOAT: {
   348        const char *z = (const char*)sqlite3_value_text(pValue);
   349        u32 n = (u32)sqlite3_value_bytes(pValue);
   350        jsonAppendRaw(p, z, n);
   351        break;
   352      }
   353      case SQLITE_TEXT: {
   354        const char *z = (const char*)sqlite3_value_text(pValue);
   355        u32 n = (u32)sqlite3_value_bytes(pValue);
   356        if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
   357          jsonAppendRaw(p, z, n);
   358        }else{
   359          jsonAppendString(p, z, n);
   360        }
   361        break;
   362      }
   363      default: {
   364        if( p->bErr==0 ){
   365          sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
   366          p->bErr = 2;
   367          jsonReset(p);
   368        }
   369        break;
   370      }
   371    }
   372  }
   373  
   374  
   375  /* Make the JSON in p the result of the SQL function.
   376  */
   377  static void jsonResult(JsonString *p){
   378    if( p->bErr==0 ){
   379      sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, 
   380                            p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
   381                            SQLITE_UTF8);
   382      jsonZero(p);
   383    }
   384    assert( p->bStatic );
   385  }
   386  
   387  /**************************************************************************
   388  ** Utility routines for dealing with JsonNode and JsonParse objects
   389  **************************************************************************/
   390  
   391  /*
   392  ** Return the number of consecutive JsonNode slots need to represent
   393  ** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
   394  ** OBJECT types, the number might be larger.
   395  **
   396  ** Appended elements are not counted.  The value returned is the number
   397  ** by which the JsonNode counter should increment in order to go to the
   398  ** next peer value.
   399  */
   400  static u32 jsonNodeSize(JsonNode *pNode){
   401    return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
   402  }
   403  
   404  /*
   405  ** Reclaim all memory allocated by a JsonParse object.  But do not
   406  ** delete the JsonParse object itself.
   407  */
   408  static void jsonParseReset(JsonParse *pParse){
   409    sqlite3_free(pParse->aNode);
   410    pParse->aNode = 0;
   411    pParse->nNode = 0;
   412    pParse->nAlloc = 0;
   413    sqlite3_free(pParse->aUp);
   414    pParse->aUp = 0;
   415  }
   416  
   417  /*
   418  ** Free a JsonParse object that was obtained from sqlite3_malloc().
   419  */
   420  static void jsonParseFree(JsonParse *pParse){
   421    jsonParseReset(pParse);
   422    sqlite3_free(pParse);
   423  }
   424  
   425  /*
   426  ** Convert the JsonNode pNode into a pure JSON string and
   427  ** append to pOut.  Subsubstructure is also included.  Return
   428  ** the number of JsonNode objects that are encoded.
   429  */
   430  static void jsonRenderNode(
   431    JsonNode *pNode,               /* The node to render */
   432    JsonString *pOut,              /* Write JSON here */
   433    sqlite3_value **aReplace       /* Replacement values */
   434  ){
   435    if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
   436      if( pNode->jnFlags & JNODE_REPLACE ){
   437        jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
   438        return;
   439      }
   440      pNode = pNode->u.pPatch;
   441    }
   442    switch( pNode->eType ){
   443      default: {
   444        assert( pNode->eType==JSON_NULL );
   445        jsonAppendRaw(pOut, "null", 4);
   446        break;
   447      }
   448      case JSON_TRUE: {
   449        jsonAppendRaw(pOut, "true", 4);
   450        break;
   451      }
   452      case JSON_FALSE: {
   453        jsonAppendRaw(pOut, "false", 5);
   454        break;
   455      }
   456      case JSON_STRING: {
   457        if( pNode->jnFlags & JNODE_RAW ){
   458          jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
   459          break;
   460        }
   461        /* Fall through into the next case */
   462      }
   463      case JSON_REAL:
   464      case JSON_INT: {
   465        jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
   466        break;
   467      }
   468      case JSON_ARRAY: {
   469        u32 j = 1;
   470        jsonAppendChar(pOut, '[');
   471        for(;;){
   472          while( j<=pNode->n ){
   473            if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
   474              jsonAppendSeparator(pOut);
   475              jsonRenderNode(&pNode[j], pOut, aReplace);
   476            }
   477            j += jsonNodeSize(&pNode[j]);
   478          }
   479          if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
   480          pNode = &pNode[pNode->u.iAppend];
   481          j = 1;
   482        }
   483        jsonAppendChar(pOut, ']');
   484        break;
   485      }
   486      case JSON_OBJECT: {
   487        u32 j = 1;
   488        jsonAppendChar(pOut, '{');
   489        for(;;){
   490          while( j<=pNode->n ){
   491            if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
   492              jsonAppendSeparator(pOut);
   493              jsonRenderNode(&pNode[j], pOut, aReplace);
   494              jsonAppendChar(pOut, ':');
   495              jsonRenderNode(&pNode[j+1], pOut, aReplace);
   496            }
   497            j += 1 + jsonNodeSize(&pNode[j+1]);
   498          }
   499          if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
   500          pNode = &pNode[pNode->u.iAppend];
   501          j = 1;
   502        }
   503        jsonAppendChar(pOut, '}');
   504        break;
   505      }
   506    }
   507  }
   508  
   509  /*
   510  ** Return a JsonNode and all its descendents as a JSON string.
   511  */
   512  static void jsonReturnJson(
   513    JsonNode *pNode,            /* Node to return */
   514    sqlite3_context *pCtx,      /* Return value for this function */
   515    sqlite3_value **aReplace    /* Array of replacement values */
   516  ){
   517    JsonString s;
   518    jsonInit(&s, pCtx);
   519    jsonRenderNode(pNode, &s, aReplace);
   520    jsonResult(&s);
   521    sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
   522  }
   523  
   524  /*
   525  ** Make the JsonNode the return value of the function.
   526  */
   527  static void jsonReturn(
   528    JsonNode *pNode,            /* Node to return */
   529    sqlite3_context *pCtx,      /* Return value for this function */
   530    sqlite3_value **aReplace    /* Array of replacement values */
   531  ){
   532    switch( pNode->eType ){
   533      default: {
   534        assert( pNode->eType==JSON_NULL );
   535        sqlite3_result_null(pCtx);
   536        break;
   537      }
   538      case JSON_TRUE: {
   539        sqlite3_result_int(pCtx, 1);
   540        break;
   541      }
   542      case JSON_FALSE: {
   543        sqlite3_result_int(pCtx, 0);
   544        break;
   545      }
   546      case JSON_INT: {
   547        sqlite3_int64 i = 0;
   548        const char *z = pNode->u.zJContent;
   549        if( z[0]=='-' ){ z++; }
   550        while( z[0]>='0' && z[0]<='9' ){
   551          unsigned v = *(z++) - '0';
   552          if( i>=LARGEST_INT64/10 ){
   553            if( i>LARGEST_INT64/10 ) goto int_as_real;
   554            if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
   555            if( v==9 ) goto int_as_real;
   556            if( v==8 ){
   557              if( pNode->u.zJContent[0]=='-' ){
   558                sqlite3_result_int64(pCtx, SMALLEST_INT64);
   559                goto int_done;
   560              }else{
   561                goto int_as_real;
   562              }
   563            }
   564          }
   565          i = i*10 + v;
   566        }
   567        if( pNode->u.zJContent[0]=='-' ){ i = -i; }
   568        sqlite3_result_int64(pCtx, i);
   569        int_done:
   570        break;
   571        int_as_real: /* fall through to real */;
   572      }
   573      case JSON_REAL: {
   574        double r;
   575  #ifdef SQLITE_AMALGAMATION
   576        const char *z = pNode->u.zJContent;
   577        sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
   578  #else
   579        r = strtod(pNode->u.zJContent, 0);
   580  #endif
   581        sqlite3_result_double(pCtx, r);
   582        break;
   583      }
   584      case JSON_STRING: {
   585  #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
   586        ** json_insert() and json_replace() and those routines do not
   587        ** call jsonReturn() */
   588        if( pNode->jnFlags & JNODE_RAW ){
   589          sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
   590                              SQLITE_TRANSIENT);
   591        }else 
   592  #endif
   593        assert( (pNode->jnFlags & JNODE_RAW)==0 );
   594        if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
   595          /* JSON formatted without any backslash-escapes */
   596          sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
   597                              SQLITE_TRANSIENT);
   598        }else{
   599          /* Translate JSON formatted string into raw text */
   600          u32 i;
   601          u32 n = pNode->n;
   602          const char *z = pNode->u.zJContent;
   603          char *zOut;
   604          u32 j;
   605          zOut = sqlite3_malloc( n+1 );
   606          if( zOut==0 ){
   607            sqlite3_result_error_nomem(pCtx);
   608            break;
   609          }
   610          for(i=1, j=0; i<n-1; i++){
   611            char c = z[i];
   612            if( c!='\\' ){
   613              zOut[j++] = c;
   614            }else{
   615              c = z[++i];
   616              if( c=='u' ){
   617                u32 v = 0, k;
   618                for(k=0; k<4; i++, k++){
   619                  assert( i<n-2 );
   620                  c = z[i+1];
   621                  assert( safe_isxdigit(c) );
   622                  if( c<='9' ) v = v*16 + c - '0';
   623                  else if( c<='F' ) v = v*16 + c - 'A' + 10;
   624                  else v = v*16 + c - 'a' + 10;
   625                }
   626                if( v==0 ) break;
   627                if( v<=0x7f ){
   628                  zOut[j++] = (char)v;
   629                }else if( v<=0x7ff ){
   630                  zOut[j++] = (char)(0xc0 | (v>>6));
   631                  zOut[j++] = 0x80 | (v&0x3f);
   632                }else{
   633                  zOut[j++] = (char)(0xe0 | (v>>12));
   634                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
   635                  zOut[j++] = 0x80 | (v&0x3f);
   636                }
   637              }else{
   638                if( c=='b' ){
   639                  c = '\b';
   640                }else if( c=='f' ){
   641                  c = '\f';
   642                }else if( c=='n' ){
   643                  c = '\n';
   644                }else if( c=='r' ){
   645                  c = '\r';
   646                }else if( c=='t' ){
   647                  c = '\t';
   648                }
   649                zOut[j++] = c;
   650              }
   651            }
   652          }
   653          zOut[j] = 0;
   654          sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
   655        }
   656        break;
   657      }
   658      case JSON_ARRAY:
   659      case JSON_OBJECT: {
   660        jsonReturnJson(pNode, pCtx, aReplace);
   661        break;
   662      }
   663    }
   664  }
   665  
   666  /* Forward reference */
   667  static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
   668  
   669  /*
   670  ** A macro to hint to the compiler that a function should not be
   671  ** inlined.
   672  */
   673  #if defined(__GNUC__)
   674  #  define JSON_NOINLINE  __attribute__((noinline))
   675  #elif defined(_MSC_VER) && _MSC_VER>=1310
   676  #  define JSON_NOINLINE  __declspec(noinline)
   677  #else
   678  #  define JSON_NOINLINE
   679  #endif
   680  
   681  
   682  static JSON_NOINLINE int jsonParseAddNodeExpand(
   683    JsonParse *pParse,        /* Append the node to this object */
   684    u32 eType,                /* Node type */
   685    u32 n,                    /* Content size or sub-node count */
   686    const char *zContent      /* Content */
   687  ){
   688    u32 nNew;
   689    JsonNode *pNew;
   690    assert( pParse->nNode>=pParse->nAlloc );
   691    if( pParse->oom ) return -1;
   692    nNew = pParse->nAlloc*2 + 10;
   693    pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
   694    if( pNew==0 ){
   695      pParse->oom = 1;
   696      return -1;
   697    }
   698    pParse->nAlloc = nNew;
   699    pParse->aNode = pNew;
   700    assert( pParse->nNode<pParse->nAlloc );
   701    return jsonParseAddNode(pParse, eType, n, zContent);
   702  }
   703  
   704  /*
   705  ** Create a new JsonNode instance based on the arguments and append that
   706  ** instance to the JsonParse.  Return the index in pParse->aNode[] of the
   707  ** new node, or -1 if a memory allocation fails.
   708  */
   709  static int jsonParseAddNode(
   710    JsonParse *pParse,        /* Append the node to this object */
   711    u32 eType,                /* Node type */
   712    u32 n,                    /* Content size or sub-node count */
   713    const char *zContent      /* Content */
   714  ){
   715    JsonNode *p;
   716    if( pParse->nNode>=pParse->nAlloc ){
   717      return jsonParseAddNodeExpand(pParse, eType, n, zContent);
   718    }
   719    p = &pParse->aNode[pParse->nNode];
   720    p->eType = (u8)eType;
   721    p->jnFlags = 0;
   722    p->n = n;
   723    p->u.zJContent = zContent;
   724    return pParse->nNode++;
   725  }
   726  
   727  /*
   728  ** Return true if z[] begins with 4 (or more) hexadecimal digits
   729  */
   730  static int jsonIs4Hex(const char *z){
   731    int i;
   732    for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
   733    return 1;
   734  }
   735  
   736  /*
   737  ** Parse a single JSON value which begins at pParse->zJson[i].  Return the
   738  ** index of the first character past the end of the value parsed.
   739  **
   740  ** Return negative for a syntax error.  Special cases:  return -2 if the
   741  ** first non-whitespace character is '}' and return -3 if the first
   742  ** non-whitespace character is ']'.
   743  */
   744  static int jsonParseValue(JsonParse *pParse, u32 i){
   745    char c;
   746    u32 j;
   747    int iThis;
   748    int x;
   749    JsonNode *pNode;
   750    const char *z = pParse->zJson;
   751    while( safe_isspace(z[i]) ){ i++; }
   752    if( (c = z[i])=='{' ){
   753      /* Parse object */
   754      iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
   755      if( iThis<0 ) return -1;
   756      for(j=i+1;;j++){
   757        while( safe_isspace(z[j]) ){ j++; }
   758        if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
   759        x = jsonParseValue(pParse, j);
   760        if( x<0 ){
   761          pParse->iDepth--;
   762          if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
   763          return -1;
   764        }
   765        if( pParse->oom ) return -1;
   766        pNode = &pParse->aNode[pParse->nNode-1];
   767        if( pNode->eType!=JSON_STRING ) return -1;
   768        pNode->jnFlags |= JNODE_LABEL;
   769        j = x;
   770        while( safe_isspace(z[j]) ){ j++; }
   771        if( z[j]!=':' ) return -1;
   772        j++;
   773        x = jsonParseValue(pParse, j);
   774        pParse->iDepth--;
   775        if( x<0 ) return -1;
   776        j = x;
   777        while( safe_isspace(z[j]) ){ j++; }
   778        c = z[j];
   779        if( c==',' ) continue;
   780        if( c!='}' ) return -1;
   781        break;
   782      }
   783      pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
   784      return j+1;
   785    }else if( c=='[' ){
   786      /* Parse array */
   787      iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
   788      if( iThis<0 ) return -1;
   789      for(j=i+1;;j++){
   790        while( safe_isspace(z[j]) ){ j++; }
   791        if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
   792        x = jsonParseValue(pParse, j);
   793        pParse->iDepth--;
   794        if( x<0 ){
   795          if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
   796          return -1;
   797        }
   798        j = x;
   799        while( safe_isspace(z[j]) ){ j++; }
   800        c = z[j];
   801        if( c==',' ) continue;
   802        if( c!=']' ) return -1;
   803        break;
   804      }
   805      pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
   806      return j+1;
   807    }else if( c=='"' ){
   808      /* Parse string */
   809      u8 jnFlags = 0;
   810      j = i+1;
   811      for(;;){
   812        c = z[j];
   813        if( (c & ~0x1f)==0 ){
   814          /* Control characters are not allowed in strings */
   815          return -1;
   816        }
   817        if( c=='\\' ){
   818          c = z[++j];
   819          if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
   820             || c=='n' || c=='r' || c=='t'
   821             || (c=='u' && jsonIs4Hex(z+j+1)) ){
   822            jnFlags = JNODE_ESCAPE;
   823          }else{
   824            return -1;
   825          }
   826        }else if( c=='"' ){
   827          break;
   828        }
   829        j++;
   830      }
   831      jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
   832      if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
   833      return j+1;
   834    }else if( c=='n'
   835           && strncmp(z+i,"null",4)==0
   836           && !safe_isalnum(z[i+4]) ){
   837      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
   838      return i+4;
   839    }else if( c=='t'
   840           && strncmp(z+i,"true",4)==0
   841           && !safe_isalnum(z[i+4]) ){
   842      jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
   843      return i+4;
   844    }else if( c=='f'
   845           && strncmp(z+i,"false",5)==0
   846           && !safe_isalnum(z[i+5]) ){
   847      jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
   848      return i+5;
   849    }else if( c=='-' || (c>='0' && c<='9') ){
   850      /* Parse number */
   851      u8 seenDP = 0;
   852      u8 seenE = 0;
   853      assert( '-' < '0' );
   854      if( c<='0' ){
   855        j = c=='-' ? i+1 : i;
   856        if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
   857      }
   858      j = i+1;
   859      for(;; j++){
   860        c = z[j];
   861        if( c>='0' && c<='9' ) continue;
   862        if( c=='.' ){
   863          if( z[j-1]=='-' ) return -1;
   864          if( seenDP ) return -1;
   865          seenDP = 1;
   866          continue;
   867        }
   868        if( c=='e' || c=='E' ){
   869          if( z[j-1]<'0' ) return -1;
   870          if( seenE ) return -1;
   871          seenDP = seenE = 1;
   872          c = z[j+1];
   873          if( c=='+' || c=='-' ){
   874            j++;
   875            c = z[j+1];
   876          }
   877          if( c<'0' || c>'9' ) return -1;
   878          continue;
   879        }
   880        break;
   881      }
   882      if( z[j-1]<'0' ) return -1;
   883      jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
   884                          j - i, &z[i]);
   885      return j;
   886    }else if( c=='}' ){
   887      return -2;  /* End of {...} */
   888    }else if( c==']' ){
   889      return -3;  /* End of [...] */
   890    }else if( c==0 ){
   891      return 0;   /* End of file */
   892    }else{
   893      return -1;  /* Syntax error */
   894    }
   895  }
   896  
   897  /*
   898  ** Parse a complete JSON string.  Return 0 on success or non-zero if there
   899  ** are any errors.  If an error occurs, free all memory associated with
   900  ** pParse.
   901  **
   902  ** pParse is uninitialized when this routine is called.
   903  */
   904  static int jsonParse(
   905    JsonParse *pParse,           /* Initialize and fill this JsonParse object */
   906    sqlite3_context *pCtx,       /* Report errors here */
   907    const char *zJson            /* Input JSON text to be parsed */
   908  ){
   909    int i;
   910    memset(pParse, 0, sizeof(*pParse));
   911    if( zJson==0 ) return 1;
   912    pParse->zJson = zJson;
   913    i = jsonParseValue(pParse, 0);
   914    if( pParse->oom ) i = -1;
   915    if( i>0 ){
   916      assert( pParse->iDepth==0 );
   917      while( safe_isspace(zJson[i]) ) i++;
   918      if( zJson[i] ) i = -1;
   919    }
   920    if( i<=0 ){
   921      if( pCtx!=0 ){
   922        if( pParse->oom ){
   923          sqlite3_result_error_nomem(pCtx);
   924        }else{
   925          sqlite3_result_error(pCtx, "malformed JSON", -1);
   926        }
   927      }
   928      jsonParseReset(pParse);
   929      return 1;
   930    }
   931    return 0;
   932  }
   933  
   934  /* Mark node i of pParse as being a child of iParent.  Call recursively
   935  ** to fill in all the descendants of node i.
   936  */
   937  static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
   938    JsonNode *pNode = &pParse->aNode[i];
   939    u32 j;
   940    pParse->aUp[i] = iParent;
   941    switch( pNode->eType ){
   942      case JSON_ARRAY: {
   943        for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
   944          jsonParseFillInParentage(pParse, i+j, i);
   945        }
   946        break;
   947      }
   948      case JSON_OBJECT: {
   949        for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
   950          pParse->aUp[i+j] = i;
   951          jsonParseFillInParentage(pParse, i+j+1, i);
   952        }
   953        break;
   954      }
   955      default: {
   956        break;
   957      }
   958    }
   959  }
   960  
   961  /*
   962  ** Compute the parentage of all nodes in a completed parse.
   963  */
   964  static int jsonParseFindParents(JsonParse *pParse){
   965    u32 *aUp;
   966    assert( pParse->aUp==0 );
   967    aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
   968    if( aUp==0 ){
   969      pParse->oom = 1;
   970      return SQLITE_NOMEM;
   971    }
   972    jsonParseFillInParentage(pParse, 0, 0);
   973    return SQLITE_OK;
   974  }
   975  
   976  /*
   977  ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
   978  */
   979  #define JSON_CACHE_ID  (-429938)
   980  
   981  /*
   982  ** Obtain a complete parse of the JSON found in the first argument
   983  ** of the argv array.  Use the sqlite3_get_auxdata() cache for this
   984  ** parse if it is available.  If the cache is not available or if it
   985  ** is no longer valid, parse the JSON again and return the new parse,
   986  ** and also register the new parse so that it will be available for
   987  ** future sqlite3_get_auxdata() calls.
   988  */
   989  static JsonParse *jsonParseCached(
   990    sqlite3_context *pCtx,
   991    sqlite3_value **argv
   992  ){
   993    const char *zJson = (const char*)sqlite3_value_text(argv[0]);
   994    int nJson = sqlite3_value_bytes(argv[0]);
   995    JsonParse *p;
   996    if( zJson==0 ) return 0;
   997    p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
   998    if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
   999      p->nErr = 0;
  1000      return p; /* The cached entry matches, so return it */
  1001    }
  1002    p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  1003    if( p==0 ){
  1004      sqlite3_result_error_nomem(pCtx);
  1005      return 0;
  1006    }
  1007    memset(p, 0, sizeof(*p));
  1008    p->zJson = (char*)&p[1];
  1009    memcpy((char*)p->zJson, zJson, nJson+1);
  1010    if( jsonParse(p, pCtx, p->zJson) ){
  1011      sqlite3_free(p);
  1012      return 0;
  1013    }
  1014    p->nJson = nJson;
  1015    sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
  1016    return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  1017  }
  1018  
  1019  /*
  1020  ** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
  1021  ** a match.
  1022  */
  1023  static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  1024    if( pNode->jnFlags & JNODE_RAW ){
  1025      if( pNode->n!=nKey ) return 0;
  1026      return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  1027    }else{
  1028      if( pNode->n!=nKey+2 ) return 0;
  1029      return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  1030    }
  1031  }
  1032  
  1033  /* forward declaration */
  1034  static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  1035  
  1036  /*
  1037  ** Search along zPath to find the node specified.  Return a pointer
  1038  ** to that node, or NULL if zPath is malformed or if there is no such
  1039  ** node.
  1040  **
  1041  ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  1042  ** possible to do so and if no existing node corresponds to zPath.  If
  1043  ** new nodes are appended *pApnd is set to 1.
  1044  */
  1045  static JsonNode *jsonLookupStep(
  1046    JsonParse *pParse,      /* The JSON to search */
  1047    u32 iRoot,              /* Begin the search at this node */
  1048    const char *zPath,      /* The path to search */
  1049    int *pApnd,             /* Append nodes to complete path if not NULL */
  1050    const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
  1051  ){
  1052    u32 i, j, nKey;
  1053    const char *zKey;
  1054    JsonNode *pRoot = &pParse->aNode[iRoot];
  1055    if( zPath[0]==0 ) return pRoot;
  1056    if( zPath[0]=='.' ){
  1057      if( pRoot->eType!=JSON_OBJECT ) return 0;
  1058      zPath++;
  1059      if( zPath[0]=='"' ){
  1060        zKey = zPath + 1;
  1061        for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  1062        nKey = i-1;
  1063        if( zPath[i] ){
  1064          i++;
  1065        }else{
  1066          *pzErr = zPath;
  1067          return 0;
  1068        }
  1069      }else{
  1070        zKey = zPath;
  1071        for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  1072        nKey = i;
  1073      }
  1074      if( nKey==0 ){
  1075        *pzErr = zPath;
  1076        return 0;
  1077      }
  1078      j = 1;
  1079      for(;;){
  1080        while( j<=pRoot->n ){
  1081          if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  1082            return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  1083          }
  1084          j++;
  1085          j += jsonNodeSize(&pRoot[j]);
  1086        }
  1087        if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  1088        iRoot += pRoot->u.iAppend;
  1089        pRoot = &pParse->aNode[iRoot];
  1090        j = 1;
  1091      }
  1092      if( pApnd ){
  1093        u32 iStart, iLabel;
  1094        JsonNode *pNode;
  1095        iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  1096        iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  1097        zPath += i;
  1098        pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  1099        if( pParse->oom ) return 0;
  1100        if( pNode ){
  1101          pRoot = &pParse->aNode[iRoot];
  1102          pRoot->u.iAppend = iStart - iRoot;
  1103          pRoot->jnFlags |= JNODE_APPEND;
  1104          pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  1105        }
  1106        return pNode;
  1107      }
  1108    }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  1109      if( pRoot->eType!=JSON_ARRAY ) return 0;
  1110      i = 0;
  1111      j = 1;
  1112      while( safe_isdigit(zPath[j]) ){
  1113        i = i*10 + zPath[j] - '0';
  1114        j++;
  1115      }
  1116      if( zPath[j]!=']' ){
  1117        *pzErr = zPath;
  1118        return 0;
  1119      }
  1120      zPath += j + 1;
  1121      j = 1;
  1122      for(;;){
  1123        while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  1124          if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  1125          j += jsonNodeSize(&pRoot[j]);
  1126        }
  1127        if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  1128        iRoot += pRoot->u.iAppend;
  1129        pRoot = &pParse->aNode[iRoot];
  1130        j = 1;
  1131      }
  1132      if( j<=pRoot->n ){
  1133        return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  1134      }
  1135      if( i==0 && pApnd ){
  1136        u32 iStart;
  1137        JsonNode *pNode;
  1138        iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  1139        pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  1140        if( pParse->oom ) return 0;
  1141        if( pNode ){
  1142          pRoot = &pParse->aNode[iRoot];
  1143          pRoot->u.iAppend = iStart - iRoot;
  1144          pRoot->jnFlags |= JNODE_APPEND;
  1145        }
  1146        return pNode;
  1147      }
  1148    }else{
  1149      *pzErr = zPath;
  1150    }
  1151    return 0;
  1152  }
  1153  
  1154  /*
  1155  ** Append content to pParse that will complete zPath.  Return a pointer
  1156  ** to the inserted node, or return NULL if the append fails.
  1157  */
  1158  static JsonNode *jsonLookupAppend(
  1159    JsonParse *pParse,     /* Append content to the JSON parse */
  1160    const char *zPath,     /* Description of content to append */
  1161    int *pApnd,            /* Set this flag to 1 */
  1162    const char **pzErr     /* Make this point to any syntax error */
  1163  ){
  1164    *pApnd = 1;
  1165    if( zPath[0]==0 ){
  1166      jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  1167      return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  1168    }
  1169    if( zPath[0]=='.' ){
  1170      jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  1171    }else if( strncmp(zPath,"[0]",3)==0 ){
  1172      jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  1173    }else{
  1174      return 0;
  1175    }
  1176    if( pParse->oom ) return 0;
  1177    return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  1178  }
  1179  
  1180  /*
  1181  ** Return the text of a syntax error message on a JSON path.  Space is
  1182  ** obtained from sqlite3_malloc().
  1183  */
  1184  static char *jsonPathSyntaxError(const char *zErr){
  1185    return sqlite3_mprintf("JSON path error near '%q'", zErr);
  1186  }
  1187  
  1188  /*
  1189  ** Do a node lookup using zPath.  Return a pointer to the node on success.
  1190  ** Return NULL if not found or if there is an error.
  1191  **
  1192  ** On an error, write an error message into pCtx and increment the
  1193  ** pParse->nErr counter.
  1194  **
  1195  ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  1196  ** nodes are appended.
  1197  */
  1198  static JsonNode *jsonLookup(
  1199    JsonParse *pParse,      /* The JSON to search */
  1200    const char *zPath,      /* The path to search */
  1201    int *pApnd,             /* Append nodes to complete path if not NULL */
  1202    sqlite3_context *pCtx   /* Report errors here, if not NULL */
  1203  ){
  1204    const char *zErr = 0;
  1205    JsonNode *pNode = 0;
  1206    char *zMsg;
  1207  
  1208    if( zPath==0 ) return 0;
  1209    if( zPath[0]!='$' ){
  1210      zErr = zPath;
  1211      goto lookup_err;
  1212    }
  1213    zPath++;
  1214    pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  1215    if( zErr==0 ) return pNode;
  1216  
  1217  lookup_err:
  1218    pParse->nErr++;
  1219    assert( zErr!=0 && pCtx!=0 );
  1220    zMsg = jsonPathSyntaxError(zErr);
  1221    if( zMsg ){
  1222      sqlite3_result_error(pCtx, zMsg, -1);
  1223      sqlite3_free(zMsg);
  1224    }else{
  1225      sqlite3_result_error_nomem(pCtx);
  1226    }
  1227    return 0;
  1228  }
  1229  
  1230  
  1231  /*
  1232  ** Report the wrong number of arguments for json_insert(), json_replace()
  1233  ** or json_set().
  1234  */
  1235  static void jsonWrongNumArgs(
  1236    sqlite3_context *pCtx,
  1237    const char *zFuncName
  1238  ){
  1239    char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  1240                                 zFuncName);
  1241    sqlite3_result_error(pCtx, zMsg, -1);
  1242    sqlite3_free(zMsg);     
  1243  }
  1244  
  1245  /*
  1246  ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  1247  */
  1248  static void jsonRemoveAllNulls(JsonNode *pNode){
  1249    int i, n;
  1250    assert( pNode->eType==JSON_OBJECT );
  1251    n = pNode->n;
  1252    for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  1253      switch( pNode[i].eType ){
  1254        case JSON_NULL:
  1255          pNode[i].jnFlags |= JNODE_REMOVE;
  1256          break;
  1257        case JSON_OBJECT:
  1258          jsonRemoveAllNulls(&pNode[i]);
  1259          break;
  1260      }
  1261    }
  1262  }
  1263  
  1264  
  1265  /****************************************************************************
  1266  ** SQL functions used for testing and debugging
  1267  ****************************************************************************/
  1268  
  1269  #ifdef SQLITE_DEBUG
  1270  /*
  1271  ** The json_parse(JSON) function returns a string which describes
  1272  ** a parse of the JSON provided.  Or it returns NULL if JSON is not
  1273  ** well-formed.
  1274  */
  1275  static void jsonParseFunc(
  1276    sqlite3_context *ctx,
  1277    int argc,
  1278    sqlite3_value **argv
  1279  ){
  1280    JsonString s;       /* Output string - not real JSON */
  1281    JsonParse x;        /* The parse */
  1282    u32 i;
  1283  
  1284    assert( argc==1 );
  1285    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  1286    jsonParseFindParents(&x);
  1287    jsonInit(&s, ctx);
  1288    for(i=0; i<x.nNode; i++){
  1289      const char *zType;
  1290      if( x.aNode[i].jnFlags & JNODE_LABEL ){
  1291        assert( x.aNode[i].eType==JSON_STRING );
  1292        zType = "label";
  1293      }else{
  1294        zType = jsonType[x.aNode[i].eType];
  1295      }
  1296      jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  1297                 i, zType, x.aNode[i].n, x.aUp[i]);
  1298      if( x.aNode[i].u.zJContent!=0 ){
  1299        jsonAppendRaw(&s, " ", 1);
  1300        jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  1301      }
  1302      jsonAppendRaw(&s, "\n", 1);
  1303    }
  1304    jsonParseReset(&x);
  1305    jsonResult(&s);
  1306  }
  1307  
  1308  /*
  1309  ** The json_test1(JSON) function return true (1) if the input is JSON
  1310  ** text generated by another json function.  It returns (0) if the input
  1311  ** is not known to be JSON.
  1312  */
  1313  static void jsonTest1Func(
  1314    sqlite3_context *ctx,
  1315    int argc,
  1316    sqlite3_value **argv
  1317  ){
  1318    UNUSED_PARAM(argc);
  1319    sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  1320  }
  1321  #endif /* SQLITE_DEBUG */
  1322  
  1323  /****************************************************************************
  1324  ** Scalar SQL function implementations
  1325  ****************************************************************************/
  1326  
  1327  /*
  1328  ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
  1329  ** corresponding to the SQL value input.  Mostly this means putting 
  1330  ** double-quotes around strings and returning the unquoted string "null"
  1331  ** when given a NULL input.
  1332  */
  1333  static void jsonQuoteFunc(
  1334    sqlite3_context *ctx,
  1335    int argc,
  1336    sqlite3_value **argv
  1337  ){
  1338    JsonString jx;
  1339    UNUSED_PARAM(argc);
  1340  
  1341    jsonInit(&jx, ctx);
  1342    jsonAppendValue(&jx, argv[0]);
  1343    jsonResult(&jx);
  1344    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  1345  }
  1346  
  1347  /*
  1348  ** Implementation of the json_array(VALUE,...) function.  Return a JSON
  1349  ** array that contains all values given in arguments.  Or if any argument
  1350  ** is a BLOB, throw an error.
  1351  */
  1352  static void jsonArrayFunc(
  1353    sqlite3_context *ctx,
  1354    int argc,
  1355    sqlite3_value **argv
  1356  ){
  1357    int i;
  1358    JsonString jx;
  1359  
  1360    jsonInit(&jx, ctx);
  1361    jsonAppendChar(&jx, '[');
  1362    for(i=0; i<argc; i++){
  1363      jsonAppendSeparator(&jx);
  1364      jsonAppendValue(&jx, argv[i]);
  1365    }
  1366    jsonAppendChar(&jx, ']');
  1367    jsonResult(&jx);
  1368    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  1369  }
  1370  
  1371  
  1372  /*
  1373  ** json_array_length(JSON)
  1374  ** json_array_length(JSON, PATH)
  1375  **
  1376  ** Return the number of elements in the top-level JSON array.  
  1377  ** Return 0 if the input is not a well-formed JSON array.
  1378  */
  1379  static void jsonArrayLengthFunc(
  1380    sqlite3_context *ctx,
  1381    int argc,
  1382    sqlite3_value **argv
  1383  ){
  1384    JsonParse *p;          /* The parse */
  1385    sqlite3_int64 n = 0;
  1386    u32 i;
  1387    JsonNode *pNode;
  1388  
  1389    p = jsonParseCached(ctx, argv);
  1390    if( p==0 ) return;
  1391    assert( p->nNode );
  1392    if( argc==2 ){
  1393      const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  1394      pNode = jsonLookup(p, zPath, 0, ctx);
  1395    }else{
  1396      pNode = p->aNode;
  1397    }
  1398    if( pNode==0 ){
  1399      return;
  1400    }
  1401    if( pNode->eType==JSON_ARRAY ){
  1402      assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  1403      for(i=1; i<=pNode->n; n++){
  1404        i += jsonNodeSize(&pNode[i]);
  1405      }
  1406    }
  1407    sqlite3_result_int64(ctx, n);
  1408  }
  1409  
  1410  /*
  1411  ** json_extract(JSON, PATH, ...)
  1412  **
  1413  ** Return the element described by PATH.  Return NULL if there is no
  1414  ** PATH element.  If there are multiple PATHs, then return a JSON array
  1415  ** with the result from each path.  Throw an error if the JSON or any PATH
  1416  ** is malformed.
  1417  */
  1418  static void jsonExtractFunc(
  1419    sqlite3_context *ctx,
  1420    int argc,
  1421    sqlite3_value **argv
  1422  ){
  1423    JsonParse *p;          /* The parse */
  1424    JsonNode *pNode;
  1425    const char *zPath;
  1426    JsonString jx;
  1427    int i;
  1428  
  1429    if( argc<2 ) return;
  1430    p = jsonParseCached(ctx, argv);
  1431    if( p==0 ) return;
  1432    jsonInit(&jx, ctx);
  1433    jsonAppendChar(&jx, '[');
  1434    for(i=1; i<argc; i++){
  1435      zPath = (const char*)sqlite3_value_text(argv[i]);
  1436      pNode = jsonLookup(p, zPath, 0, ctx);
  1437      if( p->nErr ) break;
  1438      if( argc>2 ){
  1439        jsonAppendSeparator(&jx);
  1440        if( pNode ){
  1441          jsonRenderNode(pNode, &jx, 0);
  1442        }else{
  1443          jsonAppendRaw(&jx, "null", 4);
  1444        }
  1445      }else if( pNode ){
  1446        jsonReturn(pNode, ctx, 0);
  1447      }
  1448    }
  1449    if( argc>2 && i==argc ){
  1450      jsonAppendChar(&jx, ']');
  1451      jsonResult(&jx);
  1452      sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  1453    }
  1454    jsonReset(&jx);
  1455  }
  1456  
  1457  /* This is the RFC 7396 MergePatch algorithm.
  1458  */
  1459  static JsonNode *jsonMergePatch(
  1460    JsonParse *pParse,   /* The JSON parser that contains the TARGET */
  1461    u32 iTarget,         /* Node of the TARGET in pParse */
  1462    JsonNode *pPatch     /* The PATCH */
  1463  ){
  1464    u32 i, j;
  1465    u32 iRoot;
  1466    JsonNode *pTarget;
  1467    if( pPatch->eType!=JSON_OBJECT ){
  1468      return pPatch;
  1469    }
  1470    assert( iTarget>=0 && iTarget<pParse->nNode );
  1471    pTarget = &pParse->aNode[iTarget];
  1472    assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  1473    if( pTarget->eType!=JSON_OBJECT ){
  1474      jsonRemoveAllNulls(pPatch);
  1475      return pPatch;
  1476    }
  1477    iRoot = iTarget;
  1478    for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  1479      u32 nKey;
  1480      const char *zKey;
  1481      assert( pPatch[i].eType==JSON_STRING );
  1482      assert( pPatch[i].jnFlags & JNODE_LABEL );
  1483      nKey = pPatch[i].n;
  1484      zKey = pPatch[i].u.zJContent;
  1485      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  1486      for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  1487        assert( pTarget[j].eType==JSON_STRING );
  1488        assert( pTarget[j].jnFlags & JNODE_LABEL );
  1489        assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  1490        if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  1491          if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  1492          if( pPatch[i+1].eType==JSON_NULL ){
  1493            pTarget[j+1].jnFlags |= JNODE_REMOVE;
  1494          }else{
  1495            JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  1496            if( pNew==0 ) return 0;
  1497            pTarget = &pParse->aNode[iTarget];
  1498            if( pNew!=&pTarget[j+1] ){
  1499              pTarget[j+1].u.pPatch = pNew;
  1500              pTarget[j+1].jnFlags |= JNODE_PATCH;
  1501            }
  1502          }
  1503          break;
  1504        }
  1505      }
  1506      if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  1507        int iStart, iPatch;
  1508        iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  1509        jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  1510        iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  1511        if( pParse->oom ) return 0;
  1512        jsonRemoveAllNulls(pPatch);
  1513        pTarget = &pParse->aNode[iTarget];
  1514        pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  1515        pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  1516        iRoot = iStart;
  1517        pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  1518        pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  1519      }
  1520    }
  1521    return pTarget;
  1522  }
  1523  
  1524  /*
  1525  ** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
  1526  ** object that is the result of running the RFC 7396 MergePatch() algorithm
  1527  ** on the two arguments.
  1528  */
  1529  static void jsonPatchFunc(
  1530    sqlite3_context *ctx,
  1531    int argc,
  1532    sqlite3_value **argv
  1533  ){
  1534    JsonParse x;     /* The JSON that is being patched */
  1535    JsonParse y;     /* The patch */
  1536    JsonNode *pResult;   /* The result of the merge */
  1537  
  1538    UNUSED_PARAM(argc);
  1539    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  1540    if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  1541      jsonParseReset(&x);
  1542      return;
  1543    }
  1544    pResult = jsonMergePatch(&x, 0, y.aNode);
  1545    assert( pResult!=0 || x.oom );
  1546    if( pResult ){
  1547      jsonReturnJson(pResult, ctx, 0);
  1548    }else{
  1549      sqlite3_result_error_nomem(ctx);
  1550    }
  1551    jsonParseReset(&x);
  1552    jsonParseReset(&y);
  1553  }
  1554  
  1555  
  1556  /*
  1557  ** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
  1558  ** object that contains all name/value given in arguments.  Or if any name
  1559  ** is not a string or if any value is a BLOB, throw an error.
  1560  */
  1561  static void jsonObjectFunc(
  1562    sqlite3_context *ctx,
  1563    int argc,
  1564    sqlite3_value **argv
  1565  ){
  1566    int i;
  1567    JsonString jx;
  1568    const char *z;
  1569    u32 n;
  1570  
  1571    if( argc&1 ){
  1572      sqlite3_result_error(ctx, "json_object() requires an even number "
  1573                                    "of arguments", -1);
  1574      return;
  1575    }
  1576    jsonInit(&jx, ctx);
  1577    jsonAppendChar(&jx, '{');
  1578    for(i=0; i<argc; i+=2){
  1579      if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  1580        sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  1581        jsonReset(&jx);
  1582        return;
  1583      }
  1584      jsonAppendSeparator(&jx);
  1585      z = (const char*)sqlite3_value_text(argv[i]);
  1586      n = (u32)sqlite3_value_bytes(argv[i]);
  1587      jsonAppendString(&jx, z, n);
  1588      jsonAppendChar(&jx, ':');
  1589      jsonAppendValue(&jx, argv[i+1]);
  1590    }
  1591    jsonAppendChar(&jx, '}');
  1592    jsonResult(&jx);
  1593    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  1594  }
  1595  
  1596  
  1597  /*
  1598  ** json_remove(JSON, PATH, ...)
  1599  **
  1600  ** Remove the named elements from JSON and return the result.  malformed
  1601  ** JSON or PATH arguments result in an error.
  1602  */
  1603  static void jsonRemoveFunc(
  1604    sqlite3_context *ctx,
  1605    int argc,
  1606    sqlite3_value **argv
  1607  ){
  1608    JsonParse x;          /* The parse */
  1609    JsonNode *pNode;
  1610    const char *zPath;
  1611    u32 i;
  1612  
  1613    if( argc<1 ) return;
  1614    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  1615    assert( x.nNode );
  1616    for(i=1; i<(u32)argc; i++){
  1617      zPath = (const char*)sqlite3_value_text(argv[i]);
  1618      if( zPath==0 ) goto remove_done;
  1619      pNode = jsonLookup(&x, zPath, 0, ctx);
  1620      if( x.nErr ) goto remove_done;
  1621      if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  1622    }
  1623    if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  1624      jsonReturnJson(x.aNode, ctx, 0);
  1625    }
  1626  remove_done:
  1627    jsonParseReset(&x);
  1628  }
  1629  
  1630  /*
  1631  ** json_replace(JSON, PATH, VALUE, ...)
  1632  **
  1633  ** Replace the value at PATH with VALUE.  If PATH does not already exist,
  1634  ** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
  1635  */
  1636  static void jsonReplaceFunc(
  1637    sqlite3_context *ctx,
  1638    int argc,
  1639    sqlite3_value **argv
  1640  ){
  1641    JsonParse x;          /* The parse */
  1642    JsonNode *pNode;
  1643    const char *zPath;
  1644    u32 i;
  1645  
  1646    if( argc<1 ) return;
  1647    if( (argc&1)==0 ) {
  1648      jsonWrongNumArgs(ctx, "replace");
  1649      return;
  1650    }
  1651    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  1652    assert( x.nNode );
  1653    for(i=1; i<(u32)argc; i+=2){
  1654      zPath = (const char*)sqlite3_value_text(argv[i]);
  1655      pNode = jsonLookup(&x, zPath, 0, ctx);
  1656      if( x.nErr ) goto replace_err;
  1657      if( pNode ){
  1658        pNode->jnFlags |= (u8)JNODE_REPLACE;
  1659        pNode->u.iReplace = i + 1;
  1660      }
  1661    }
  1662    if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  1663      sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  1664    }else{
  1665      jsonReturnJson(x.aNode, ctx, argv);
  1666    }
  1667  replace_err:
  1668    jsonParseReset(&x);
  1669  }
  1670  
  1671  /*
  1672  ** json_set(JSON, PATH, VALUE, ...)
  1673  **
  1674  ** Set the value at PATH to VALUE.  Create the PATH if it does not already
  1675  ** exist.  Overwrite existing values that do exist.
  1676  ** If JSON or PATH is malformed, throw an error.
  1677  **
  1678  ** json_insert(JSON, PATH, VALUE, ...)
  1679  **
  1680  ** Create PATH and initialize it to VALUE.  If PATH already exists, this
  1681  ** routine is a no-op.  If JSON or PATH is malformed, throw an error.
  1682  */
  1683  static void jsonSetFunc(
  1684    sqlite3_context *ctx,
  1685    int argc,
  1686    sqlite3_value **argv
  1687  ){
  1688    JsonParse x;          /* The parse */
  1689    JsonNode *pNode;
  1690    const char *zPath;
  1691    u32 i;
  1692    int bApnd;
  1693    int bIsSet = *(int*)sqlite3_user_data(ctx);
  1694  
  1695    if( argc<1 ) return;
  1696    if( (argc&1)==0 ) {
  1697      jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  1698      return;
  1699    }
  1700    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  1701    assert( x.nNode );
  1702    for(i=1; i<(u32)argc; i+=2){
  1703      zPath = (const char*)sqlite3_value_text(argv[i]);
  1704      bApnd = 0;
  1705      pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  1706      if( x.oom ){
  1707        sqlite3_result_error_nomem(ctx);
  1708        goto jsonSetDone;
  1709      }else if( x.nErr ){
  1710        goto jsonSetDone;
  1711      }else if( pNode && (bApnd || bIsSet) ){
  1712        pNode->jnFlags |= (u8)JNODE_REPLACE;
  1713        pNode->u.iReplace = i + 1;
  1714      }
  1715    }
  1716    if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  1717      sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  1718    }else{
  1719      jsonReturnJson(x.aNode, ctx, argv);
  1720    }
  1721  jsonSetDone:
  1722    jsonParseReset(&x);
  1723  }
  1724  
  1725  /*
  1726  ** json_type(JSON)
  1727  ** json_type(JSON, PATH)
  1728  **
  1729  ** Return the top-level "type" of a JSON string.  Throw an error if
  1730  ** either the JSON or PATH inputs are not well-formed.
  1731  */
  1732  static void jsonTypeFunc(
  1733    sqlite3_context *ctx,
  1734    int argc,
  1735    sqlite3_value **argv
  1736  ){
  1737    JsonParse x;          /* The parse */
  1738    const char *zPath;
  1739    JsonNode *pNode;
  1740  
  1741    if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  1742    assert( x.nNode );
  1743    if( argc==2 ){
  1744      zPath = (const char*)sqlite3_value_text(argv[1]);
  1745      pNode = jsonLookup(&x, zPath, 0, ctx);
  1746    }else{
  1747      pNode = x.aNode;
  1748    }
  1749    if( pNode ){
  1750      sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  1751    }
  1752    jsonParseReset(&x);
  1753  }
  1754  
  1755  /*
  1756  ** json_valid(JSON)
  1757  **
  1758  ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  1759  ** Return 0 otherwise.
  1760  */
  1761  static void jsonValidFunc(
  1762    sqlite3_context *ctx,
  1763    int argc,
  1764    sqlite3_value **argv
  1765  ){
  1766    JsonParse x;          /* The parse */
  1767    int rc = 0;
  1768  
  1769    UNUSED_PARAM(argc);
  1770    if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  1771      rc = 1;
  1772    }
  1773    jsonParseReset(&x);
  1774    sqlite3_result_int(ctx, rc);
  1775  }
  1776  
  1777  
  1778  /****************************************************************************
  1779  ** Aggregate SQL function implementations
  1780  ****************************************************************************/
  1781  /*
  1782  ** json_group_array(VALUE)
  1783  **
  1784  ** Return a JSON array composed of all values in the aggregate.
  1785  */
  1786  static void jsonArrayStep(
  1787    sqlite3_context *ctx,
  1788    int argc,
  1789    sqlite3_value **argv
  1790  ){
  1791    JsonString *pStr;
  1792    UNUSED_PARAM(argc);
  1793    pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  1794    if( pStr ){
  1795      if( pStr->zBuf==0 ){
  1796        jsonInit(pStr, ctx);
  1797        jsonAppendChar(pStr, '[');
  1798      }else{
  1799        jsonAppendChar(pStr, ',');
  1800        pStr->pCtx = ctx;
  1801      }
  1802      jsonAppendValue(pStr, argv[0]);
  1803    }
  1804  }
  1805  static void jsonArrayFinal(sqlite3_context *ctx){
  1806    JsonString *pStr;
  1807    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  1808    if( pStr ){
  1809      pStr->pCtx = ctx;
  1810      jsonAppendChar(pStr, ']');
  1811      if( pStr->bErr ){
  1812        if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  1813        assert( pStr->bStatic );
  1814      }else{
  1815        sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  1816                            pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  1817        pStr->bStatic = 1;
  1818      }
  1819    }else{
  1820      sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  1821    }
  1822    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  1823  }
  1824  
  1825  /*
  1826  ** json_group_obj(NAME,VALUE)
  1827  **
  1828  ** Return a JSON object composed of all names and values in the aggregate.
  1829  */
  1830  static void jsonObjectStep(
  1831    sqlite3_context *ctx,
  1832    int argc,
  1833    sqlite3_value **argv
  1834  ){
  1835    JsonString *pStr;
  1836    const char *z;
  1837    u32 n;
  1838    UNUSED_PARAM(argc);
  1839    pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  1840    if( pStr ){
  1841      if( pStr->zBuf==0 ){
  1842        jsonInit(pStr, ctx);
  1843        jsonAppendChar(pStr, '{');
  1844      }else{
  1845        jsonAppendChar(pStr, ',');
  1846        pStr->pCtx = ctx;
  1847      }
  1848      z = (const char*)sqlite3_value_text(argv[0]);
  1849      n = (u32)sqlite3_value_bytes(argv[0]);
  1850      jsonAppendString(pStr, z, n);
  1851      jsonAppendChar(pStr, ':');
  1852      jsonAppendValue(pStr, argv[1]);
  1853    }
  1854  }
  1855  static void jsonObjectFinal(sqlite3_context *ctx){
  1856    JsonString *pStr;
  1857    pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  1858    if( pStr ){
  1859      jsonAppendChar(pStr, '}');
  1860      if( pStr->bErr ){
  1861        if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  1862        assert( pStr->bStatic );
  1863      }else{
  1864        sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  1865                            pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  1866        pStr->bStatic = 1;
  1867      }
  1868    }else{
  1869      sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  1870    }
  1871    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  1872  }
  1873  
  1874  
  1875  #ifndef SQLITE_OMIT_VIRTUALTABLE
  1876  /****************************************************************************
  1877  ** The json_each virtual table
  1878  ****************************************************************************/
  1879  typedef struct JsonEachCursor JsonEachCursor;
  1880  struct JsonEachCursor {
  1881    sqlite3_vtab_cursor base;  /* Base class - must be first */
  1882    u32 iRowid;                /* The rowid */
  1883    u32 iBegin;                /* The first node of the scan */
  1884    u32 i;                     /* Index in sParse.aNode[] of current row */
  1885    u32 iEnd;                  /* EOF when i equals or exceeds this value */
  1886    u8 eType;                  /* Type of top-level element */
  1887    u8 bRecursive;             /* True for json_tree().  False for json_each() */
  1888    char *zJson;               /* Input JSON */
  1889    char *zRoot;               /* Path by which to filter zJson */
  1890    JsonParse sParse;          /* Parse of the input JSON */
  1891  };
  1892  
  1893  /* Constructor for the json_each virtual table */
  1894  static int jsonEachConnect(
  1895    sqlite3 *db,
  1896    void *pAux,
  1897    int argc, const char *const*argv,
  1898    sqlite3_vtab **ppVtab,
  1899    char **pzErr
  1900  ){
  1901    sqlite3_vtab *pNew;
  1902    int rc;
  1903  
  1904  /* Column numbers */
  1905  #define JEACH_KEY     0
  1906  #define JEACH_VALUE   1
  1907  #define JEACH_TYPE    2
  1908  #define JEACH_ATOM    3
  1909  #define JEACH_ID      4
  1910  #define JEACH_PARENT  5
  1911  #define JEACH_FULLKEY 6
  1912  #define JEACH_PATH    7
  1913  #define JEACH_JSON    8
  1914  #define JEACH_ROOT    9
  1915  
  1916    UNUSED_PARAM(pzErr);
  1917    UNUSED_PARAM(argv);
  1918    UNUSED_PARAM(argc);
  1919    UNUSED_PARAM(pAux);
  1920    rc = sqlite3_declare_vtab(db, 
  1921       "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  1922                      "json HIDDEN,root HIDDEN)");
  1923    if( rc==SQLITE_OK ){
  1924      pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  1925      if( pNew==0 ) return SQLITE_NOMEM;
  1926      memset(pNew, 0, sizeof(*pNew));
  1927    }
  1928    return rc;
  1929  }
  1930  
  1931  /* destructor for json_each virtual table */
  1932  static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  1933    sqlite3_free(pVtab);
  1934    return SQLITE_OK;
  1935  }
  1936  
  1937  /* constructor for a JsonEachCursor object for json_each(). */
  1938  static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  1939    JsonEachCursor *pCur;
  1940  
  1941    UNUSED_PARAM(p);
  1942    pCur = sqlite3_malloc( sizeof(*pCur) );
  1943    if( pCur==0 ) return SQLITE_NOMEM;
  1944    memset(pCur, 0, sizeof(*pCur));
  1945    *ppCursor = &pCur->base;
  1946    return SQLITE_OK;
  1947  }
  1948  
  1949  /* constructor for a JsonEachCursor object for json_tree(). */
  1950  static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  1951    int rc = jsonEachOpenEach(p, ppCursor);
  1952    if( rc==SQLITE_OK ){
  1953      JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  1954      pCur->bRecursive = 1;
  1955    }
  1956    return rc;
  1957  }
  1958  
  1959  /* Reset a JsonEachCursor back to its original state.  Free any memory
  1960  ** held. */
  1961  static void jsonEachCursorReset(JsonEachCursor *p){
  1962    sqlite3_free(p->zJson);
  1963    sqlite3_free(p->zRoot);
  1964    jsonParseReset(&p->sParse);
  1965    p->iRowid = 0;
  1966    p->i = 0;
  1967    p->iEnd = 0;
  1968    p->eType = 0;
  1969    p->zJson = 0;
  1970    p->zRoot = 0;
  1971  }
  1972  
  1973  /* Destructor for a jsonEachCursor object */
  1974  static int jsonEachClose(sqlite3_vtab_cursor *cur){
  1975    JsonEachCursor *p = (JsonEachCursor*)cur;
  1976    jsonEachCursorReset(p);
  1977    sqlite3_free(cur);
  1978    return SQLITE_OK;
  1979  }
  1980  
  1981  /* Return TRUE if the jsonEachCursor object has been advanced off the end
  1982  ** of the JSON object */
  1983  static int jsonEachEof(sqlite3_vtab_cursor *cur){
  1984    JsonEachCursor *p = (JsonEachCursor*)cur;
  1985    return p->i >= p->iEnd;
  1986  }
  1987  
  1988  /* Advance the cursor to the next element for json_tree() */
  1989  static int jsonEachNext(sqlite3_vtab_cursor *cur){
  1990    JsonEachCursor *p = (JsonEachCursor*)cur;
  1991    if( p->bRecursive ){
  1992      if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  1993      p->i++;
  1994      p->iRowid++;
  1995      if( p->i<p->iEnd ){
  1996        u32 iUp = p->sParse.aUp[p->i];
  1997        JsonNode *pUp = &p->sParse.aNode[iUp];
  1998        p->eType = pUp->eType;
  1999        if( pUp->eType==JSON_ARRAY ){
  2000          if( iUp==p->i-1 ){
  2001            pUp->u.iKey = 0;
  2002          }else{
  2003            pUp->u.iKey++;
  2004          }
  2005        }
  2006      }
  2007    }else{
  2008      switch( p->eType ){
  2009        case JSON_ARRAY: {
  2010          p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  2011          p->iRowid++;
  2012          break;
  2013        }
  2014        case JSON_OBJECT: {
  2015          p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  2016          p->iRowid++;
  2017          break;
  2018        }
  2019        default: {
  2020          p->i = p->iEnd;
  2021          break;
  2022        }
  2023      }
  2024    }
  2025    return SQLITE_OK;
  2026  }
  2027  
  2028  /* Append the name of the path for element i to pStr
  2029  */
  2030  static void jsonEachComputePath(
  2031    JsonEachCursor *p,       /* The cursor */
  2032    JsonString *pStr,        /* Write the path here */
  2033    u32 i                    /* Path to this element */
  2034  ){
  2035    JsonNode *pNode, *pUp;
  2036    u32 iUp;
  2037    if( i==0 ){
  2038      jsonAppendChar(pStr, '$');
  2039      return;
  2040    }
  2041    iUp = p->sParse.aUp[i];
  2042    jsonEachComputePath(p, pStr, iUp);
  2043    pNode = &p->sParse.aNode[i];
  2044    pUp = &p->sParse.aNode[iUp];
  2045    if( pUp->eType==JSON_ARRAY ){
  2046      jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  2047    }else{
  2048      assert( pUp->eType==JSON_OBJECT );
  2049      if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  2050      assert( pNode->eType==JSON_STRING );
  2051      assert( pNode->jnFlags & JNODE_LABEL );
  2052      jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  2053    }
  2054  }
  2055  
  2056  /* Return the value of a column */
  2057  static int jsonEachColumn(
  2058    sqlite3_vtab_cursor *cur,   /* The cursor */
  2059    sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
  2060    int i                       /* Which column to return */
  2061  ){
  2062    JsonEachCursor *p = (JsonEachCursor*)cur;
  2063    JsonNode *pThis = &p->sParse.aNode[p->i];
  2064    switch( i ){
  2065      case JEACH_KEY: {
  2066        if( p->i==0 ) break;
  2067        if( p->eType==JSON_OBJECT ){
  2068          jsonReturn(pThis, ctx, 0);
  2069        }else if( p->eType==JSON_ARRAY ){
  2070          u32 iKey;
  2071          if( p->bRecursive ){
  2072            if( p->iRowid==0 ) break;
  2073            iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  2074          }else{
  2075            iKey = p->iRowid;
  2076          }
  2077          sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  2078        }
  2079        break;
  2080      }
  2081      case JEACH_VALUE: {
  2082        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  2083        jsonReturn(pThis, ctx, 0);
  2084        break;
  2085      }
  2086      case JEACH_TYPE: {
  2087        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  2088        sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  2089        break;
  2090      }
  2091      case JEACH_ATOM: {
  2092        if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  2093        if( pThis->eType>=JSON_ARRAY ) break;
  2094        jsonReturn(pThis, ctx, 0);
  2095        break;
  2096      }
  2097      case JEACH_ID: {
  2098        sqlite3_result_int64(ctx, 
  2099           (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  2100        break;
  2101      }
  2102      case JEACH_PARENT: {
  2103        if( p->i>p->iBegin && p->bRecursive ){
  2104          sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  2105        }
  2106        break;
  2107      }
  2108      case JEACH_FULLKEY: {
  2109        JsonString x;
  2110        jsonInit(&x, ctx);
  2111        if( p->bRecursive ){
  2112          jsonEachComputePath(p, &x, p->i);
  2113        }else{
  2114          if( p->zRoot ){
  2115            jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  2116          }else{
  2117            jsonAppendChar(&x, '$');
  2118          }
  2119          if( p->eType==JSON_ARRAY ){
  2120            jsonPrintf(30, &x, "[%d]", p->iRowid);
  2121          }else{
  2122            jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  2123          }
  2124        }
  2125        jsonResult(&x);
  2126        break;
  2127      }
  2128      case JEACH_PATH: {
  2129        if( p->bRecursive ){
  2130          JsonString x;
  2131          jsonInit(&x, ctx);
  2132          jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  2133          jsonResult(&x);
  2134          break;
  2135        }
  2136        /* For json_each() path and root are the same so fall through
  2137        ** into the root case */
  2138      }
  2139      default: {
  2140        const char *zRoot = p->zRoot;
  2141        if( zRoot==0 ) zRoot = "$";
  2142        sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  2143        break;
  2144      }
  2145      case JEACH_JSON: {
  2146        assert( i==JEACH_JSON );
  2147        sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  2148        break;
  2149      }
  2150    }
  2151    return SQLITE_OK;
  2152  }
  2153  
  2154  /* Return the current rowid value */
  2155  static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  2156    JsonEachCursor *p = (JsonEachCursor*)cur;
  2157    *pRowid = p->iRowid;
  2158    return SQLITE_OK;
  2159  }
  2160  
  2161  /* The query strategy is to look for an equality constraint on the json
  2162  ** column.  Without such a constraint, the table cannot operate.  idxNum is
  2163  ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  2164  ** and 0 otherwise.
  2165  */
  2166  static int jsonEachBestIndex(
  2167    sqlite3_vtab *tab,
  2168    sqlite3_index_info *pIdxInfo
  2169  ){
  2170    int i;
  2171    int jsonIdx = -1;
  2172    int rootIdx = -1;
  2173    const struct sqlite3_index_constraint *pConstraint;
  2174  
  2175    UNUSED_PARAM(tab);
  2176    pConstraint = pIdxInfo->aConstraint;
  2177    for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  2178      if( pConstraint->usable==0 ) continue;
  2179      if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  2180      switch( pConstraint->iColumn ){
  2181        case JEACH_JSON:   jsonIdx = i;    break;
  2182        case JEACH_ROOT:   rootIdx = i;    break;
  2183        default:           /* no-op */     break;
  2184      }
  2185    }
  2186    if( jsonIdx<0 ){
  2187      pIdxInfo->idxNum = 0;
  2188      pIdxInfo->estimatedCost = 1e99;
  2189    }else{
  2190      pIdxInfo->estimatedCost = 1.0;
  2191      pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  2192      pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  2193      if( rootIdx<0 ){
  2194        pIdxInfo->idxNum = 1;
  2195      }else{
  2196        pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  2197        pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  2198        pIdxInfo->idxNum = 3;
  2199      }
  2200    }
  2201    return SQLITE_OK;
  2202  }
  2203  
  2204  /* Start a search on a new JSON string */
  2205  static int jsonEachFilter(
  2206    sqlite3_vtab_cursor *cur,
  2207    int idxNum, const char *idxStr,
  2208    int argc, sqlite3_value **argv
  2209  ){
  2210    JsonEachCursor *p = (JsonEachCursor*)cur;
  2211    const char *z;
  2212    const char *zRoot = 0;
  2213    sqlite3_int64 n;
  2214  
  2215    UNUSED_PARAM(idxStr);
  2216    UNUSED_PARAM(argc);
  2217    jsonEachCursorReset(p);
  2218    if( idxNum==0 ) return SQLITE_OK;
  2219    z = (const char*)sqlite3_value_text(argv[0]);
  2220    if( z==0 ) return SQLITE_OK;
  2221    n = sqlite3_value_bytes(argv[0]);
  2222    p->zJson = sqlite3_malloc64( n+1 );
  2223    if( p->zJson==0 ) return SQLITE_NOMEM;
  2224    memcpy(p->zJson, z, (size_t)n+1);
  2225    if( jsonParse(&p->sParse, 0, p->zJson) ){
  2226      int rc = SQLITE_NOMEM;
  2227      if( p->sParse.oom==0 ){
  2228        sqlite3_free(cur->pVtab->zErrMsg);
  2229        cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  2230        if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  2231      }
  2232      jsonEachCursorReset(p);
  2233      return rc;
  2234    }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  2235      jsonEachCursorReset(p);
  2236      return SQLITE_NOMEM;
  2237    }else{
  2238      JsonNode *pNode = 0;
  2239      if( idxNum==3 ){
  2240        const char *zErr = 0;
  2241        zRoot = (const char*)sqlite3_value_text(argv[1]);
  2242        if( zRoot==0 ) return SQLITE_OK;
  2243        n = sqlite3_value_bytes(argv[1]);
  2244        p->zRoot = sqlite3_malloc64( n+1 );
  2245        if( p->zRoot==0 ) return SQLITE_NOMEM;
  2246        memcpy(p->zRoot, zRoot, (size_t)n+1);
  2247        if( zRoot[0]!='$' ){
  2248          zErr = zRoot;
  2249        }else{
  2250          pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  2251        }
  2252        if( zErr ){
  2253          sqlite3_free(cur->pVtab->zErrMsg);
  2254          cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  2255          jsonEachCursorReset(p);
  2256          return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  2257        }else if( pNode==0 ){
  2258          return SQLITE_OK;
  2259        }
  2260      }else{
  2261        pNode = p->sParse.aNode;
  2262      }
  2263      p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  2264      p->eType = pNode->eType;
  2265      if( p->eType>=JSON_ARRAY ){
  2266        pNode->u.iKey = 0;
  2267        p->iEnd = p->i + pNode->n + 1;
  2268        if( p->bRecursive ){
  2269          p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  2270          if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  2271            p->i--;
  2272          }
  2273        }else{
  2274          p->i++;
  2275        }
  2276      }else{
  2277        p->iEnd = p->i+1;
  2278      }
  2279    }
  2280    return SQLITE_OK;
  2281  }
  2282  
  2283  /* The methods of the json_each virtual table */
  2284  static sqlite3_module jsonEachModule = {
  2285    0,                         /* iVersion */
  2286    0,                         /* xCreate */
  2287    jsonEachConnect,           /* xConnect */
  2288    jsonEachBestIndex,         /* xBestIndex */
  2289    jsonEachDisconnect,        /* xDisconnect */
  2290    0,                         /* xDestroy */
  2291    jsonEachOpenEach,          /* xOpen - open a cursor */
  2292    jsonEachClose,             /* xClose - close a cursor */
  2293    jsonEachFilter,            /* xFilter - configure scan constraints */
  2294    jsonEachNext,              /* xNext - advance a cursor */
  2295    jsonEachEof,               /* xEof - check for end of scan */
  2296    jsonEachColumn,            /* xColumn - read data */
  2297    jsonEachRowid,             /* xRowid - read data */
  2298    0,                         /* xUpdate */
  2299    0,                         /* xBegin */
  2300    0,                         /* xSync */
  2301    0,                         /* xCommit */
  2302    0,                         /* xRollback */
  2303    0,                         /* xFindMethod */
  2304    0,                         /* xRename */
  2305    0,                         /* xSavepoint */
  2306    0,                         /* xRelease */
  2307    0                          /* xRollbackTo */
  2308  };
  2309  
  2310  /* The methods of the json_tree virtual table. */
  2311  static sqlite3_module jsonTreeModule = {
  2312    0,                         /* iVersion */
  2313    0,                         /* xCreate */
  2314    jsonEachConnect,           /* xConnect */
  2315    jsonEachBestIndex,         /* xBestIndex */
  2316    jsonEachDisconnect,        /* xDisconnect */
  2317    0,                         /* xDestroy */
  2318    jsonEachOpenTree,          /* xOpen - open a cursor */
  2319    jsonEachClose,             /* xClose - close a cursor */
  2320    jsonEachFilter,            /* xFilter - configure scan constraints */
  2321    jsonEachNext,              /* xNext - advance a cursor */
  2322    jsonEachEof,               /* xEof - check for end of scan */
  2323    jsonEachColumn,            /* xColumn - read data */
  2324    jsonEachRowid,             /* xRowid - read data */
  2325    0,                         /* xUpdate */
  2326    0,                         /* xBegin */
  2327    0,                         /* xSync */
  2328    0,                         /* xCommit */
  2329    0,                         /* xRollback */
  2330    0,                         /* xFindMethod */
  2331    0,                         /* xRename */
  2332    0,                         /* xSavepoint */
  2333    0,                         /* xRelease */
  2334    0                          /* xRollbackTo */
  2335  };
  2336  #endif /* SQLITE_OMIT_VIRTUALTABLE */
  2337  
  2338  /****************************************************************************
  2339  ** The following routines are the only publically visible identifiers in this
  2340  ** file.  Call the following routines in order to register the various SQL
  2341  ** functions and the virtual table implemented by this file.
  2342  ****************************************************************************/
  2343  
  2344  int sqlite3Json1Init(sqlite3 *db){
  2345    int rc = SQLITE_OK;
  2346    unsigned int i;
  2347    static const struct {
  2348       const char *zName;
  2349       int nArg;
  2350       int flag;
  2351       void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  2352    } aFunc[] = {
  2353      { "json",                 1, 0,   jsonRemoveFunc        },
  2354      { "json_array",          -1, 0,   jsonArrayFunc         },
  2355      { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
  2356      { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
  2357      { "json_extract",        -1, 0,   jsonExtractFunc       },
  2358      { "json_insert",         -1, 0,   jsonSetFunc           },
  2359      { "json_object",         -1, 0,   jsonObjectFunc        },
  2360      { "json_patch",           2, 0,   jsonPatchFunc         },
  2361      { "json_quote",           1, 0,   jsonQuoteFunc         },
  2362      { "json_remove",         -1, 0,   jsonRemoveFunc        },
  2363      { "json_replace",        -1, 0,   jsonReplaceFunc       },
  2364      { "json_set",            -1, 1,   jsonSetFunc           },
  2365      { "json_type",            1, 0,   jsonTypeFunc          },
  2366      { "json_type",            2, 0,   jsonTypeFunc          },
  2367      { "json_valid",           1, 0,   jsonValidFunc         },
  2368  
  2369  #if SQLITE_DEBUG
  2370      /* DEBUG and TESTING functions */
  2371      { "json_parse",           1, 0,   jsonParseFunc         },
  2372      { "json_test1",           1, 0,   jsonTest1Func         },
  2373  #endif
  2374    };
  2375    static const struct {
  2376       const char *zName;
  2377       int nArg;
  2378       void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  2379       void (*xFinal)(sqlite3_context*);
  2380    } aAgg[] = {
  2381      { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
  2382      { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
  2383    };
  2384  #ifndef SQLITE_OMIT_VIRTUALTABLE
  2385    static const struct {
  2386       const char *zName;
  2387       sqlite3_module *pModule;
  2388    } aMod[] = {
  2389      { "json_each",            &jsonEachModule               },
  2390      { "json_tree",            &jsonTreeModule               },
  2391    };
  2392  #endif
  2393    for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  2394      rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  2395                                   SQLITE_UTF8 | SQLITE_DETERMINISTIC, 
  2396                                   (void*)&aFunc[i].flag,
  2397                                   aFunc[i].xFunc, 0, 0);
  2398    }
  2399    for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  2400      rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  2401                                   SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  2402                                   0, aAgg[i].xStep, aAgg[i].xFinal);
  2403    }
  2404  #ifndef SQLITE_OMIT_VIRTUALTABLE
  2405    for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  2406      rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  2407    }
  2408  #endif
  2409    return rc;
  2410  }
  2411  
  2412  
  2413  #ifndef SQLITE_CORE
  2414  #ifdef _WIN32
  2415  __declspec(dllexport)
  2416  #endif
  2417  int sqlite3_json_init(
  2418    sqlite3 *db, 
  2419    char **pzErrMsg, 
  2420    const sqlite3_api_routines *pApi
  2421  ){
  2422    SQLITE_EXTENSION_INIT2(pApi);
  2423    (void)pzErrMsg;  /* Unused parameter */
  2424    return sqlite3Json1Init(db);
  2425  }
  2426  #endif
  2427  #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */