sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
| 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 | ** SQLite JSON functions. |
| 14 | ** |
| 15 | ** This file began as an extension in ext/misc/json1.c in 2015. That |
| 16 | ** extension proved so useful that it has now been moved into the core. |
| 17 | ** |
| 18 | ** The original design stored all JSON as pure text, canonical RFC-8259. |
| 19 | ** Support for JSON-5 extensions was added with version 3.42.0 (2023-05-16). |
| 20 | ** All generated JSON text still conforms strictly to RFC-8259, but text |
| 21 | ** with JSON-5 extensions is accepted as input. |
| 22 | ** |
| 23 | ** Beginning with version 3.45.0 (circa 2024-01-01), these routines also |
| 24 | ** accept BLOB values that have JSON encoded using a binary representation |
| 25 | ** called "JSONB". The name JSONB comes from PostgreSQL, however the on-disk |
| 26 | ** format for SQLite-JSONB is completely different and incompatible with |
| 27 | ** PostgreSQL-JSONB. |
| 28 | ** |
| 29 | ** Decoding and interpreting JSONB is still O(N) where N is the size of |
| 30 | ** the input, the same as text JSON. However, the constant of proportionality |
| 31 | ** for JSONB is much smaller due to faster parsing. The size of each |
| 32 | ** element in JSONB is encoded in its header, so there is no need to search |
| 33 | ** for delimiters using persnickety syntax rules. JSONB seems to be about |
| 34 | ** 3x faster than text JSON as a result. JSONB is also tends to be slightly |
| 35 | ** smaller than text JSON, by 5% or 10%, but there are corner cases where |
| 36 | ** JSONB can be slightly larger. So you are not far mistaken to say that |
| 37 | ** a JSONB blob is the same size as the equivalent RFC-8259 text. |
| 38 | ** |
| 39 | ** |
| 40 | ** THE JSONB ENCODING: |
| 41 | ** |
| 42 | ** Every JSON element is encoded in JSONB as a header and a payload. |
| 43 | ** The header is between 1 and 9 bytes in size. The payload is zero |
| 44 | ** or more bytes. |
| 45 | ** |
| 46 | ** The lower 4 bits of the first byte of the header determines the |
| 47 | ** element type: |
| 48 | ** |
| 49 | ** 0: NULL |
| 50 | ** 1: TRUE |
| 51 | ** 2: FALSE |
| 52 | ** 3: INT -- RFC-8259 integer literal |
| 53 | ** 4: INT5 -- JSON5 integer literal |
| 54 | ** 5: FLOAT -- RFC-8259 floating point literal |
| 55 | ** 6: FLOAT5 -- JSON5 floating point literal |
| 56 | ** 7: TEXT -- Text literal acceptable to both SQL and JSON |
| 57 | ** 8: TEXTJ -- Text containing RFC-8259 escapes |
| 58 | ** 9: TEXT5 -- Text containing JSON5 and/or RFC-8259 escapes |
| 59 | ** 10: TEXTRAW -- Text containing unescaped syntax characters |
| 60 | ** 11: ARRAY |
| 61 | ** 12: OBJECT |
| 62 | ** |
| 63 | ** The other three possible values (13-15) are reserved for future |
| 64 | ** enhancements. |
| 65 | ** |
| 66 | ** The upper 4 bits of the first byte determine the size of the header |
| 67 | ** and sometimes also the size of the payload. If X is the first byte |
| 68 | ** of the element and if X>>4 is between 0 and 11, then the payload |
| 69 | ** will be that many bytes in size and the header is exactly one byte |
| 70 | ** in size. Other four values for X>>4 (12-15) indicate that the header |
| 71 | ** is more than one byte in size and that the payload size is determined |
| 72 | ** by the remainder of the header, interpreted as a unsigned big-endian |
| 73 | ** integer. |
| 74 | ** |
| 75 | ** Value of X>>4 Size integer Total header size |
| 76 | ** ------------- -------------------- ----------------- |
| 77 | ** 12 1 byte (0-255) 2 |
| 78 | ** 13 2 byte (0-65535) 3 |
| 79 | ** 14 4 byte (0-4294967295) 5 |
| 80 | ** 15 8 byte (0-1.8e19) 9 |
| 81 | ** |
| 82 | ** The payload size need not be expressed in its minimal form. For example, |
| 83 | ** if the payload size is 10, the size can be expressed in any of 5 different |
| 84 | ** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by one 0x0a byte, |
| 85 | ** (3) (X>>4)==13 followed by 0x00 and 0x0a, (4) (X>>4)==14 followed by |
| 86 | ** 0x00 0x00 0x00 0x0a, or (5) (X>>4)==15 followed by 7 bytes of 0x00 and |
| 87 | ** a single byte of 0x0a. The shorter forms are preferred, of course, but |
| 88 | ** sometimes when generating JSONB, the payload size is not known in advance |
| 89 | ** and it is convenient to reserve sufficient header space to cover the |
| 90 | ** largest possible payload size and then come back later and patch up |
| 91 | ** the size when it becomes known, resulting in a non-minimal encoding. |
| 92 | ** |
| 93 | ** The value (X>>4)==15 is not actually used in the current implementation |
| 94 | ** (as SQLite is currently unable to handle BLOBs larger than about 2GB) |
| 95 | ** but is included in the design to allow for future enhancements. |
| 96 | ** |
| 97 | ** The payload follows the header. NULL, TRUE, and FALSE have no payload and |
| 98 | ** their payload size must always be zero. The payload for INT, INT5, |
| 99 | ** FLOAT, FLOAT5, TEXT, TEXTJ, TEXT5, and TEXTROW is text. Note that the |
| 100 | ** "..." or '...' delimiters are omitted from the various text encodings. |
| 101 | ** The payload for ARRAY and OBJECT is a list of additional elements that |
| 102 | ** are the content for the array or object. The payload for an OBJECT |
| 103 | ** must be an even number of elements. The first element of each pair is |
| 104 | ** the label and must be of type TEXT, TEXTJ, TEXT5, or TEXTRAW. |
| 105 | ** |
| 106 | ** A valid JSONB blob consists of a single element, as described above. |
| 107 | ** Usually this will be an ARRAY or OBJECT element which has many more |
| 108 | ** elements as its content. But the overall blob is just a single element. |
| 109 | ** |
| 110 | ** Input validation for JSONB blobs simply checks that the element type |
| 111 | ** code is between 0 and 12 and that the total size of the element |
| 112 | ** (header plus payload) is the same as the size of the BLOB. If those |
| 113 | ** checks are true, the BLOB is assumed to be JSONB and processing continues. |
| 114 | ** Errors are only raised if some other miscoding is discovered during |
| 115 | ** processing. |
| 116 | ** |
| 117 | ** Additional information can be found in the doc/jsonb.md file of the |
| 118 | ** canonical SQLite source tree. |
| 119 | */ |
| 120 | #ifndef SQLITE_OMIT_JSON |
| 121 | #include "sqliteInt.h" |
| 122 | |
| 123 | /* JSONB element types |
| 124 | */ |
| 125 | #define JSONB_NULL 0 /* "null" */ |
| 126 | #define JSONB_TRUE 1 /* "true" */ |
| 127 | #define JSONB_FALSE 2 /* "false" */ |
| 128 | #define JSONB_INT 3 /* integer acceptable to JSON and SQL */ |
| 129 | #define JSONB_INT5 4 /* integer in 0x000 notation */ |
| 130 | #define JSONB_FLOAT 5 /* float acceptable to JSON and SQL */ |
| 131 | #define JSONB_FLOAT5 6 /* float with JSON5 extensions */ |
| 132 | #define JSONB_TEXT 7 /* Text compatible with both JSON and SQL */ |
| 133 | #define JSONB_TEXTJ 8 /* Text with JSON escapes */ |
| 134 | #define JSONB_TEXT5 9 /* Text with JSON-5 escape */ |
| 135 | #define JSONB_TEXTRAW 10 /* SQL text that needs escaping for JSON */ |
| 136 | #define JSONB_ARRAY 11 /* An array */ |
| 137 | #define JSONB_OBJECT 12 /* An object */ |
| 138 | |
| 139 | /* Human-readable names for the JSONB values. The index for each |
| 140 | ** string must correspond to the JSONB_* integer above. |
| 141 | */ |
| 142 | static const char * const jsonbType[] = { |
| 143 | "null", "true", "false", "integer", "integer", |
| 144 | "real", "real", "text", "text", "text", |
| 145 | "text", "array", "object", "", "", "", "" |
| 146 | }; |
| 147 | |
| 148 | /* |
| 149 | ** Growing our own isspace() routine this way is twice as fast as |
| 150 | ** the library isspace() function, resulting in a 7% overall performance |
| 151 | ** increase for the text-JSON parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os). |
| 152 | */ |
| 153 | static const char jsonIsSpace[] = { |
| 154 | #ifdef SQLITE_ASCII |
| 155 | /*0 1 2 3 4 5 6 7 8 9 a b c d e f */ |
| 156 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, /* 0 */ |
| 157 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ |
| 158 | 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */ |
| 159 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3 */ |
| 160 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4 */ |
| 161 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5 */ |
| 162 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6 */ |
| 163 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7 */ |
| 164 | |
| 165 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */ |
| 166 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */ |
| 167 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */ |
| 168 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* b */ |
| 169 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* c */ |
| 170 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* d */ |
| 171 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* e */ |
| 172 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f */ |
| 173 | #endif |
| 174 | #ifdef SQLITE_EBCDIC |
| 175 | /*0 1 2 3 4 5 6 7 8 9 a b c d e f */ |
| 176 | 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, /* 0 */ |
| 177 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ |
| 178 | 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */ |
| 179 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3 */ |
| 180 | 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4 */ |
| 181 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5 */ |
| 182 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6 */ |
| 183 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7 */ |
| 184 | |
| 185 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */ |
| 186 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */ |
| 187 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */ |
| 188 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* b */ |
| 189 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* c */ |
| 190 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* d */ |
| 191 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* e */ |
| 192 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f */ |
| 193 | #endif |
| 194 | |
| 195 | }; |
| 196 | #define jsonIsspace(x) (jsonIsSpace[(unsigned char)x]) |
| 197 | |
| 198 | /* |
| 199 | ** The set of all space characters recognized by jsonIsspace(). |
| 200 | ** Useful as the second argument to strspn(). |
| 201 | */ |
| 202 | #ifdef SQLITE_ASCII |
| 203 | static const char jsonSpaces[] = "\011\012\015\040"; |
| 204 | #endif |
| 205 | #ifdef SQLITE_EBCDIC |
| 206 | static const char jsonSpaces[] = "\005\045\015\100"; |
| 207 | #endif |
| 208 | |
| 209 | |
| 210 | /* |
| 211 | ** Characters that are special to JSON. Control characters, |
| 212 | ** '"' and '\\' and '\''. Actually, '\'' is not special to |
| 213 | ** canonical JSON, but it is special in JSON-5, so we include |
| 214 | ** it in the set of special characters. |
| 215 | */ |
| 216 | static const char jsonIsOk[256] = { |
| 217 | #ifdef SQLITE_ASCII |
| 218 | /*0 1 2 3 4 5 6 7 8 9 a b c d e f */ |
| 219 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */ |
| 220 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ |
| 221 | 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, /* 2 */ |
| 222 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 3 */ |
| 223 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4 */ |
| 224 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, /* 5 */ |
| 225 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6 */ |
| 226 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 7 */ |
| 227 | |
| 228 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8 */ |
| 229 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9 */ |
| 230 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* a */ |
| 231 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* b */ |
| 232 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* c */ |
| 233 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* d */ |
| 234 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* e */ |
| 235 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 /* f */ |
| 236 | #endif |
| 237 | #ifdef SQLITE_EBCDIC |
| 238 | /*0 1 2 3 4 5 6 7 8 9 a b c d e f */ |
| 239 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */ |
| 240 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ |
| 241 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */ |
| 242 | 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, /* 3 */ |
| 243 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4 */ |
| 244 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 5 */ |
| 245 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6 */ |
| 246 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, /* 7 */ |
| 247 | |
| 248 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8 */ |
| 249 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9 */ |
| 250 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* a */ |
| 251 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* b */ |
| 252 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* c */ |
| 253 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* d */ |
| 254 | 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* e */ |
| 255 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 /* f */ |
| 256 | #endif |
| 257 | }; |
| 258 | |
| 259 | /* Objects */ |
| 260 | typedef struct JsonCache JsonCache; |
| 261 | typedef struct JsonString JsonString; |
| 262 | typedef struct JsonParse JsonParse; |
| 263 | |
| 264 | /* |
| 265 | ** Magic number used for the JSON parse cache in sqlite3_get_auxdata() |
| 266 | */ |
| 267 | #define JSON_CACHE_ID (-429938) /* Cache entry */ |
| 268 | #define JSON_CACHE_SIZE 4 /* Max number of cache entries */ |
| 269 | |
| 270 | /* |
| 271 | ** jsonUnescapeOneChar() returns this invalid code point if it encounters |
| 272 | ** a syntax error. |
| 273 | */ |
| 274 | #define JSON_INVALID_CHAR 0x99999 |
| 275 | |
| 276 | /* A cache mapping JSON text into JSONB blobs. |
| 277 | ** |
| 278 | ** Each cache entry is a JsonParse object with the following restrictions: |
| 279 | ** |
| 280 | ** * The bReadOnly flag must be set |
| 281 | ** |
| 282 | ** * The aBlob[] array must be owned by the JsonParse object. In other |
| 283 | ** words, nBlobAlloc must be non-zero. |
| 284 | ** |
| 285 | ** * eEdit and delta must be zero. |
| 286 | ** |
| 287 | ** * zJson must be an RCStr. In other words bJsonIsRCStr must be true. |
| 288 | */ |
| 289 | struct JsonCache { |
| 290 | sqlite3 *db; /* Database connection */ |
| 291 | int nUsed; /* Number of active entries in the cache */ |
| 292 | JsonParse *a[JSON_CACHE_SIZE]; /* One line for each cache entry */ |
| 293 | }; |
| 294 | |
| 295 | /* An instance of this object represents a JSON string |
| 296 | ** under construction. Really, this is a generic string accumulator |
| 297 | ** that can be and is used to create strings other than JSON. |
| 298 | ** |
| 299 | ** If the generated string is longer than will fit into the zSpace[] buffer, |
| 300 | ** then it will be an RCStr string. This aids with caching of large |
| 301 | ** JSON strings. |
| 302 | */ |
| 303 | struct JsonString { |
| 304 | sqlite3_context *pCtx; /* Function context - put error messages here */ |
| 305 | char *zBuf; /* Append JSON content here */ |
| 306 | u64 nAlloc; /* Bytes of storage available in zBuf[] */ |
| 307 | u64 nUsed; /* Bytes of zBuf[] currently used */ |
| 308 | u8 bStatic; /* True if zBuf is static space */ |
| 309 | u8 eErr; /* True if an error has been encountered */ |
| 310 | char zSpace[100]; /* Initial static space */ |
| 311 | }; |
| 312 | |
| 313 | /* Allowed values for JsonString.eErr */ |
| 314 | #define JSTRING_OOM 0x01 /* Out of memory */ |
| 315 | #define JSTRING_MALFORMED 0x02 /* Malformed JSONB */ |
| 316 | #define JSTRING_TOODEEP 0x04 /* JSON nested too deep */ |
| 317 | #define JSTRING_ERR 0x08 /* Error already sent to sqlite3_result */ |
| 318 | |
| 319 | /* The "subtype" set for text JSON values passed through using |
| 320 | ** sqlite3_result_subtype() and sqlite3_value_subtype(). |
| 321 | */ |
| 322 | #define JSON_SUBTYPE 74 /* Ascii for "J" */ |
| 323 | |
| 324 | /* |
| 325 | ** Bit values for the flags passed into various SQL function implementations |
| 326 | ** via the sqlite3_user_data() value. |
| 327 | */ |
| 328 | #define JSON_JSON 0x01 /* Result is always JSON */ |
| 329 | #define JSON_SQL 0x02 /* Result is always SQL */ |
| 330 | #define JSON_ABPATH 0x03 /* Allow abbreviated JSON path specs */ |
| 331 | #define JSON_ISSET 0x04 /* json_set(), not json_insert() */ |
| 332 | #define JSON_AINS 0x08 /* json_array_insert(), not json_insert() */ |
| 333 | #define JSON_BLOB 0x10 /* Use the BLOB output format */ |
| 334 | |
| 335 | #define JSON_INSERT_TYPE(X) (((X)&0xC)>>2) |
| 336 | |
| 337 | |
| 338 | /* A parsed JSON value. Lifecycle: |
| 339 | ** |
| 340 | ** 1. JSON comes in and is parsed into a JSONB value in aBlob. The |
| 341 | ** original text is stored in zJson. This step is skipped if the |
| 342 | ** input is JSONB instead of text JSON. |
| 343 | ** |
| 344 | ** 2. The aBlob[] array is searched using the JSON path notation, if needed. |
| 345 | ** |
| 346 | ** 3. Zero or more changes are made to aBlob[] (via json_remove() or |
| 347 | ** json_replace() or json_patch() or similar). |
| 348 | ** |
| 349 | ** 4. New JSON text is generated from the aBlob[] for output. This step |
| 350 | ** is skipped if the function is one of the jsonb_* functions that |
| 351 | ** returns JSONB instead of text JSON. |
| 352 | */ |
| 353 | struct JsonParse { |
| 354 | u8 *aBlob; /* JSONB representation of JSON value */ |
| 355 | u32 nBlob; /* Bytes of aBlob[] actually used */ |
| 356 | u32 nBlobAlloc; /* Bytes allocated to aBlob[]. 0 if aBlob is external */ |
| 357 | char *zJson; /* Json text used for parsing */ |
| 358 | sqlite3 *db; /* The database connection to which this object belongs */ |
| 359 | int nJson; /* Length of the zJson string in bytes */ |
| 360 | u32 nJPRef; /* Number of references to this object */ |
| 361 | u32 iErr; /* Error location in zJson[] */ |
| 362 | u16 iDepth; /* Nesting depth */ |
| 363 | u8 nErr; /* Number of errors seen */ |
| 364 | u8 oom; /* Set to true if out of memory */ |
| 365 | u8 bJsonIsRCStr; /* True if zJson is an RCStr */ |
| 366 | u8 hasNonstd; /* True if input uses non-standard features like JSON5 */ |
| 367 | u8 bReadOnly; /* Do not modify. */ |
| 368 | /* Search and edit information. See jsonLookupStep() */ |
| 369 | u8 eEdit; /* Edit operation to apply */ |
| 370 | int delta; /* Size change due to the edit */ |
| 371 | u32 nIns; /* Number of bytes to insert */ |
| 372 | u32 iLabel; /* Location of label if search landed on an object value */ |
| 373 | u8 *aIns; /* Content to be inserted */ |
| 374 | }; |
| 375 | |
| 376 | /* Allowed values for JsonParse.eEdit */ |
| 377 | #define JEDIT_DEL 1 /* Delete if exists */ |
| 378 | #define JEDIT_REPL 2 /* Overwrite if exists */ |
| 379 | #define JEDIT_INS 3 /* Insert if not exists */ |
| 380 | #define JEDIT_SET 4 /* Insert or overwrite */ |
| 381 | #define JEDIT_AINS 5 /* array_insert() */ |
| 382 | |
| 383 | /* |
| 384 | ** The approximate maximum nesting depth of JSON for this implementation. |
| 385 | ** |
| 386 | ** Applications should say well clear of this maximum. Depending on |
| 387 | ** implementation quirks, the limit might not reached one or two before |
| 388 | ** or one or two after the published limit. |
| 389 | ** |
| 390 | ** This limit is needed to avoid a stack overflow in the recursive |
| 391 | ** descent parser. A depth of 1000 is far deeper than any sane JSON |
| 392 | ** should go. Historical note: This limit was 2000 prior to version 3.42.0 |
| 393 | */ |
| 394 | #ifndef SQLITE_JSON_MAX_DEPTH |
| 395 | # define JSON_MAX_DEPTH 1000 |
| 396 | #else |
| 397 | # define JSON_MAX_DEPTH SQLITE_JSON_MAX_DEPTH |
| 398 | #endif |
| 399 | |
| 400 | /* |
| 401 | ** Allowed values for the flgs argument to jsonParseFuncArg(); |
| 402 | */ |
| 403 | #define JSON_EDITABLE 0x01 /* Generate a writable JsonParse object */ |
| 404 | #define JSON_KEEPERROR 0x02 /* Return non-NULL even if there is an error */ |
| 405 | #define JSON_NOCACHE 0x04 /* Do not use the JSON cache */ |
| 406 | |
| 407 | /************************************************************************** |
| 408 | ** Forward references |
| 409 | **************************************************************************/ |
| 410 | static void jsonReturnStringAsBlob(JsonString*); |
| 411 | static int jsonArgIsJsonb(sqlite3_value *pJson, JsonParse *p); |
| 412 | static u32 jsonTranslateBlobToText(JsonParse*,u32,JsonString*); |
| 413 | static void jsonReturnParse(sqlite3_context*,JsonParse*); |
| 414 | static JsonParse *jsonParseFuncArg(sqlite3_context*,sqlite3_value*,u32); |
| 415 | static void jsonParseFree(JsonParse*); |
| 416 | static u32 jsonbPayloadSize(const JsonParse*, u32, u32*); |
| 417 | static u32 jsonUnescapeOneChar(const char*, u32, u32*); |
| 418 | |
| 419 | /************************************************************************** |
| 420 | ** Utility routines for dealing with JsonCache objects |
| 421 | **************************************************************************/ |
| 422 | |
| 423 | /* |
| 424 | ** Free a JsonCache object. |
| 425 | */ |
| 426 | static void jsonCacheDelete(JsonCache *p){ |
| 427 | int i; |
| 428 | for(i=0; i<p->nUsed; i++){ |
| 429 | jsonParseFree(p->a[i]); |
| 430 | } |
| 431 | sqlite3DbFree(p->db, p); |
| 432 | } |
| 433 | static void jsonCacheDeleteGeneric(void *p){ |
| 434 | jsonCacheDelete((JsonCache*)p); |
| 435 | } |
| 436 | |
| 437 | /* |
| 438 | ** Insert a new entry into the cache. If the cache is full, expel |
| 439 | ** the least recently used entry. Return SQLITE_OK on success or a |
| 440 | ** result code otherwise. |
| 441 | ** |
| 442 | ** Cache entries are stored in age order, oldest first. |
| 443 | */ |
| 444 | static int jsonCacheInsert( |
| 445 | sqlite3_context *ctx, /* The SQL statement context holding the cache */ |
| 446 | JsonParse *pParse /* The parse object to be added to the cache */ |
| 447 | ){ |
| 448 | JsonCache *p; |
| 449 | |
| 450 | assert( pParse->zJson!=0 ); |
| 451 | assert( pParse->bJsonIsRCStr ); |
| 452 | assert( pParse->delta==0 ); |
| 453 | p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID); |
| 454 | if( p==0 ){ |
| 455 | sqlite3 *db = sqlite3_context_db_handle(ctx); |
| 456 | p = sqlite3DbMallocZero(db, sizeof(*p)); |
| 457 | if( p==0 ) return SQLITE_NOMEM; |
| 458 | p->db = db; |
| 459 | sqlite3_set_auxdata(ctx, JSON_CACHE_ID, p, jsonCacheDeleteGeneric); |
| 460 | p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID); |
| 461 | if( p==0 ) return SQLITE_NOMEM; |
| 462 | } |
| 463 | if( p->nUsed >= JSON_CACHE_SIZE ){ |
| 464 | jsonParseFree(p->a[0]); |
| 465 | memmove(p->a, &p->a[1], (JSON_CACHE_SIZE-1)*sizeof(p->a[0])); |
| 466 | p->nUsed = JSON_CACHE_SIZE-1; |
| 467 | } |
| 468 | assert( pParse->nBlobAlloc>0 ); |
| 469 | pParse->eEdit = 0; |
| 470 | pParse->nJPRef++; |
| 471 | pParse->bReadOnly = 1; |
| 472 | p->a[p->nUsed] = pParse; |
| 473 | p->nUsed++; |
| 474 | return SQLITE_OK; |
| 475 | } |
| 476 | |
| 477 | /* |
| 478 | ** Search for a cached translation the json text supplied by pArg. Return |
| 479 | ** the JsonParse object if found. Return NULL if not found. |
| 480 | ** |
| 481 | ** When a match if found, the matching entry is moved to become the |
| 482 | ** most-recently used entry if it isn't so already. |
| 483 | ** |
| 484 | ** The JsonParse object returned still belongs to the Cache and might |
| 485 | ** be deleted at any moment. If the caller wants the JsonParse to |
| 486 | ** linger, it needs to increment the nPJRef reference counter. |
| 487 | */ |
| 488 | static JsonParse *jsonCacheSearch( |
| 489 | sqlite3_context *ctx, /* The SQL statement context holding the cache */ |
| 490 | sqlite3_value *pArg /* Function argument containing SQL text */ |
| 491 | ){ |
| 492 | JsonCache *p; |
| 493 | int i; |
| 494 | const char *zJson; |
| 495 | int nJson; |
| 496 | |
| 497 | if( sqlite3_value_type(pArg)!=SQLITE_TEXT ){ |
| 498 | return 0; |
| 499 | } |
| 500 | zJson = (const char*)sqlite3_value_text(pArg); |
| 501 | if( zJson==0 ) return 0; |
| 502 | nJson = sqlite3_value_bytes(pArg); |
| 503 | |
| 504 | p = sqlite3_get_auxdata(ctx, JSON_CACHE_ID); |
| 505 | if( p==0 ){ |
| 506 | return 0; |
| 507 | } |
| 508 | for(i=0; i<p->nUsed; i++){ |
| 509 | if( p->a[i]->zJson==zJson ) break; |
| 510 | } |
| 511 | if( i>=p->nUsed ){ |
| 512 | for(i=0; i<p->nUsed; i++){ |
| 513 | if( p->a[i]->nJson!=nJson ) continue; |
| 514 | if( memcmp(p->a[i]->zJson, zJson, nJson)==0 ) break; |
| 515 | } |
| 516 | } |
| 517 | if( i<p->nUsed ){ |
| 518 | if( i<p->nUsed-1 ){ |
| 519 | /* Make the matching entry the most recently used entry */ |
| 520 | JsonParse *tmp = p->a[i]; |
| 521 | memmove(&p->a[i], &p->a[i+1], (p->nUsed-i-1)*sizeof(tmp)); |
| 522 | p->a[p->nUsed-1] = tmp; |
| 523 | i = p->nUsed - 1; |
| 524 | } |
| 525 | assert( p->a[i]->delta==0 ); |
| 526 | return p->a[i]; |
| 527 | }else{ |
| 528 | return 0; |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | /************************************************************************** |
| 533 | ** Utility routines for dealing with JsonString objects |
| 534 | **************************************************************************/ |
| 535 | |
| 536 | /* Turn uninitialized bulk memory into a valid JsonString object |
| 537 | ** holding a zero-length string. |
| 538 | */ |
| 539 | static void jsonStringZero(JsonString *p){ |
| 540 | p->zBuf = p->zSpace; |
| 541 | p->nAlloc = sizeof(p->zSpace); |
| 542 | p->nUsed = 0; |
| 543 | p->bStatic = 1; |
| 544 | } |
| 545 | |
| 546 | /* Initialize the JsonString object |
| 547 | */ |
| 548 | static void jsonStringInit(JsonString *p, sqlite3_context *pCtx){ |
| 549 | p->pCtx = pCtx; |
| 550 | p->eErr = 0; |
| 551 | jsonStringZero(p); |
| 552 | } |
| 553 | |
| 554 | /* Free all allocated memory and reset the JsonString object back to its |
| 555 | ** initial state. |
| 556 | */ |
| 557 | static void jsonStringReset(JsonString *p){ |
| 558 | if( !p->bStatic ) sqlite3RCStrUnref(p->zBuf); |
| 559 | jsonStringZero(p); |
| 560 | } |
| 561 | |
| 562 | /* Report an out-of-memory (OOM) condition |
| 563 | */ |
| 564 | static void jsonStringOom(JsonString *p){ |
| 565 | p->eErr |= JSTRING_OOM; |
| 566 | if( p->pCtx ) sqlite3_result_error_nomem(p->pCtx); |
| 567 | jsonStringReset(p); |
| 568 | } |
| 569 | |
| 570 | /* Report JSON nested too deep |
| 571 | */ |
| 572 | static void jsonStringTooDeep(JsonString *p){ |
| 573 | p->eErr |= JSTRING_TOODEEP; |
| 574 | assert( p->pCtx!=0 ); |
| 575 | sqlite3_result_error(p->pCtx, "JSON nested too deep", -1); |
| 576 | jsonStringReset(p); |
| 577 | } |
| 578 | |
| 579 | /* Enlarge pJson->zBuf so that it can hold at least N more bytes. |
| 580 | ** Return zero on success. Return non-zero on an OOM error |
| 581 | */ |
| 582 | static int jsonStringGrow(JsonString *p, u32 N){ |
| 583 | u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10; |
| 584 | char *zNew; |
| 585 | if( p->bStatic ){ |
| 586 | if( p->eErr ) return 1; |
| 587 | zNew = sqlite3RCStrNew(nTotal); |
| 588 | if( zNew==0 ){ |
| 589 | jsonStringOom(p); |
| 590 | return SQLITE_NOMEM; |
| 591 | } |
| 592 | memcpy(zNew, p->zBuf, (size_t)p->nUsed); |
| 593 | p->zBuf = zNew; |
| 594 | p->bStatic = 0; |
| 595 | }else{ |
| 596 | p->zBuf = sqlite3RCStrResize(p->zBuf, nTotal); |
| 597 | if( p->zBuf==0 ){ |
| 598 | p->eErr |= JSTRING_OOM; |
| 599 | jsonStringZero(p); |
| 600 | return SQLITE_NOMEM; |
| 601 | } |
| 602 | } |
| 603 | p->nAlloc = nTotal; |
| 604 | return SQLITE_OK; |
| 605 | } |
| 606 | |
| 607 | /* Append N bytes from zIn onto the end of the JsonString string. |
| 608 | */ |
| 609 | static SQLITE_NOINLINE void jsonStringExpandAndAppend( |
| 610 | JsonString *p, |
| 611 | const char *zIn, |
| 612 | u32 N |
| 613 | ){ |
| 614 | assert( N>0 ); |
| 615 | if( jsonStringGrow(p,N) ) return; |
| 616 | memcpy(p->zBuf+p->nUsed, zIn, N); |
| 617 | p->nUsed += N; |
| 618 | } |
| 619 | static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){ |
| 620 | if( N==0 ) return; |
| 621 | if( N+p->nUsed >= p->nAlloc ){ |
| 622 | jsonStringExpandAndAppend(p,zIn,N); |
| 623 | }else{ |
| 624 | memcpy(p->zBuf+p->nUsed, zIn, N); |
| 625 | p->nUsed += N; |
| 626 | } |
| 627 | } |
| 628 | static void jsonAppendRawNZ(JsonString *p, const char *zIn, u32 N){ |
| 629 | assert( N>0 ); |
| 630 | if( N+p->nUsed >= p->nAlloc ){ |
| 631 | jsonStringExpandAndAppend(p,zIn,N); |
| 632 | }else{ |
| 633 | memcpy(p->zBuf+p->nUsed, zIn, N); |
| 634 | p->nUsed += N; |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | /* Append formatted text (not to exceed N bytes) to the JsonString. |
| 639 | */ |
| 640 | static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){ |
| 641 | va_list ap; |
| 642 | if( (p->nUsed + N >= p->nAlloc) && jsonStringGrow(p, N) ) return; |
| 643 | va_start(ap, zFormat); |
| 644 | sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap); |
| 645 | va_end(ap); |
| 646 | p->nUsed += (int)strlen(p->zBuf+p->nUsed); |
| 647 | } |
| 648 | |
| 649 | /* Append a single character |
| 650 | */ |
| 651 | static SQLITE_NOINLINE void jsonAppendCharExpand(JsonString *p, char c){ |
| 652 | if( jsonStringGrow(p,1) ) return; |
| 653 | p->zBuf[p->nUsed++] = c; |
| 654 | } |
| 655 | static void jsonAppendChar(JsonString *p, char c){ |
| 656 | if( p->nUsed>=p->nAlloc ){ |
| 657 | jsonAppendCharExpand(p,c); |
| 658 | }else{ |
| 659 | p->zBuf[p->nUsed++] = c; |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | /* Remove a single character from the end of the string |
| 664 | */ |
| 665 | static void jsonStringTrimOneChar(JsonString *p){ |
| 666 | if( p->eErr==0 ){ |
| 667 | assert( p->nUsed>0 ); |
| 668 | p->nUsed--; |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | |
| 673 | /* Make sure there is a zero terminator on p->zBuf[] |
| 674 | ** |
| 675 | ** Return true on success. Return false if an OOM prevents this |
| 676 | ** from happening. |
| 677 | */ |
| 678 | static int jsonStringTerminate(JsonString *p){ |
| 679 | jsonAppendChar(p, 0); |
| 680 | jsonStringTrimOneChar(p); |
| 681 | return p->eErr==0; |
| 682 | } |
| 683 | |
| 684 | /* Append a comma separator to the output buffer, if the previous |
| 685 | ** character is not '[' or '{'. |
| 686 | */ |
| 687 | static void jsonAppendSeparator(JsonString *p){ |
| 688 | char c; |
| 689 | if( p->nUsed==0 ) return; |
| 690 | c = p->zBuf[p->nUsed-1]; |
| 691 | if( c=='[' || c=='{' ) return; |
| 692 | jsonAppendChar(p, ','); |
| 693 | } |
| 694 | |
| 695 | /* c is a control character. Append the canonical JSON representation |
| 696 | ** of that control character to p. |
| 697 | ** |
| 698 | ** This routine assumes that the output buffer has already been enlarged |
| 699 | ** sufficiently to hold the worst-case encoding plus a nul terminator. |
| 700 | */ |
| 701 | static void jsonAppendControlChar(JsonString *p, u8 c){ |
| 702 | static const char aSpecial[] = { |
| 703 | 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, |
| 704 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 |
| 705 | }; |
| 706 | assert( sizeof(aSpecial)==32 ); |
| 707 | assert( aSpecial['\b']=='b' ); |
| 708 | assert( aSpecial['\f']=='f' ); |
| 709 | assert( aSpecial['\n']=='n' ); |
| 710 | assert( aSpecial['\r']=='r' ); |
| 711 | assert( aSpecial['\t']=='t' ); |
| 712 | assert( c>=0 && c<sizeof(aSpecial) ); |
| 713 | assert( p->nUsed+7 <= p->nAlloc ); |
| 714 | if( aSpecial[c] ){ |
| 715 | p->zBuf[p->nUsed] = '\\'; |
| 716 | p->zBuf[p->nUsed+1] = aSpecial[c]; |
| 717 | p->nUsed += 2; |
| 718 | }else{ |
| 719 | p->zBuf[p->nUsed] = '\\'; |
| 720 | p->zBuf[p->nUsed+1] = 'u'; |
| 721 | p->zBuf[p->nUsed+2] = '0'; |
| 722 | p->zBuf[p->nUsed+3] = '0'; |
| 723 | p->zBuf[p->nUsed+4] = "0123456789abcdef"[c>>4]; |
| 724 | p->zBuf[p->nUsed+5] = "0123456789abcdef"[c&0xf]; |
| 725 | p->nUsed += 6; |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | /* Append the N-byte string in zIn to the end of the JsonString string |
| 730 | ** under construction. Enclose the string in double-quotes ("...") and |
| 731 | ** escape any double-quotes or backslash characters contained within the |
| 732 | ** string. |
| 733 | ** |
| 734 | ** This routine is a high-runner. There is a measurable performance |
| 735 | ** increase associated with unwinding the jsonIsOk[] loop. |
| 736 | */ |
| 737 | static void jsonAppendString(JsonString *p, const char *zIn, u32 N){ |
| 738 | u32 k; |
| 739 | u8 c; |
| 740 | const u8 *z = (const u8*)zIn; |
| 741 | if( z==0 ) return; |
| 742 | if( (N+p->nUsed+2 >= p->nAlloc) && jsonStringGrow(p,N+2)!=0 ) return; |
| 743 | p->zBuf[p->nUsed++] = '"'; |
| 744 | while( 1 /*exit-by-break*/ ){ |
| 745 | k = 0; |
| 746 | /* The following while() is the 4-way unwound equivalent of |
| 747 | ** |
| 748 | ** while( k<N && jsonIsOk[z[k]] ){ k++; } |
| 749 | */ |
| 750 | while( 1 /* Exit by break */ ){ |
| 751 | if( k+3>=N ){ |
| 752 | while( k<N && jsonIsOk[z[k]] ){ k++; } |
| 753 | break; |
| 754 | } |
| 755 | if( !jsonIsOk[z[k]] ){ |
| 756 | break; |
| 757 | } |
| 758 | if( !jsonIsOk[z[k+1]] ){ |
| 759 | k += 1; |
| 760 | break; |
| 761 | } |
| 762 | if( !jsonIsOk[z[k+2]] ){ |
| 763 | k += 2; |
| 764 | break; |
| 765 | } |
| 766 | if( !jsonIsOk[z[k+3]] ){ |
| 767 | k += 3; |
| 768 | break; |
| 769 | }else{ |
| 770 | k += 4; |
| 771 | } |
| 772 | } |
| 773 | if( k>=N ){ |
| 774 | if( k>0 ){ |
| 775 | memcpy(&p->zBuf[p->nUsed], z, k); |
| 776 | p->nUsed += k; |
| 777 | } |
| 778 | break; |
| 779 | } |
| 780 | if( k>0 ){ |
| 781 | memcpy(&p->zBuf[p->nUsed], z, k); |
| 782 | p->nUsed += k; |
| 783 | z += k; |
| 784 | N -= k; |
| 785 | } |
| 786 | c = z[0]; |
| 787 | if( c=='"' || c=='\\' ){ |
| 788 | if( (p->nUsed+N+3 > p->nAlloc) && jsonStringGrow(p,N+3)!=0 ) return; |
| 789 | p->zBuf[p->nUsed++] = '\\'; |
| 790 | p->zBuf[p->nUsed++] = c; |
| 791 | }else if( c=='\'' ){ |
| 792 | p->zBuf[p->nUsed++] = c; |
| 793 | }else{ |
| 794 | if( (p->nUsed+N+7 > p->nAlloc) && jsonStringGrow(p,N+7)!=0 ) return; |
| 795 | jsonAppendControlChar(p, c); |
| 796 | } |
| 797 | z++; |
| 798 | N--; |
| 799 | } |
| 800 | p->zBuf[p->nUsed++] = '"'; |
| 801 | assert( p->nUsed<p->nAlloc ); |
| 802 | } |
| 803 | |
| 804 | /* |
| 805 | ** Append an sqlite3_value (such as a function parameter) to the JSON |
| 806 | ** string under construction in p. |
| 807 | */ |
| 808 | static void jsonAppendSqlValue( |
| 809 | JsonString *p, /* Append to this JSON string */ |
| 810 | sqlite3_value *pValue /* Value to append */ |
| 811 | ){ |
| 812 | switch( sqlite3_value_type(pValue) ){ |
| 813 | case SQLITE_NULL: { |
| 814 | jsonAppendRawNZ(p, "null", 4); |
| 815 | break; |
| 816 | } |
| 817 | case SQLITE_FLOAT: { |
| 818 | jsonPrintf(100, p, "%!0.17g", sqlite3_value_double(pValue)); |
| 819 | break; |
| 820 | } |
| 821 | case SQLITE_INTEGER: { |
| 822 | const char *z = (const char*)sqlite3_value_text(pValue); |
| 823 | u32 n = (u32)sqlite3_value_bytes(pValue); |
| 824 | jsonAppendRaw(p, z, n); |
| 825 | break; |
| 826 | } |
| 827 | case SQLITE_TEXT: { |
| 828 | const char *z = (const char*)sqlite3_value_text(pValue); |
| 829 | u32 n = (u32)sqlite3_value_bytes(pValue); |
| 830 | if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){ |
| 831 | jsonAppendRaw(p, z, n); |
| 832 | }else{ |
| 833 | jsonAppendString(p, z, n); |
| 834 | } |
| 835 | break; |
| 836 | } |
| 837 | default: { |
| 838 | JsonParse px; |
| 839 | memset(&px, 0, sizeof(px)); |
| 840 | if( jsonArgIsJsonb(pValue, &px) ){ |
| 841 | jsonTranslateBlobToText(&px, 0, p); |
| 842 | }else if( p->eErr==0 ){ |
| 843 | sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1); |
| 844 | p->eErr = JSTRING_ERR; |
| 845 | jsonStringReset(p); |
| 846 | } |
| 847 | break; |
| 848 | } |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | /* Make the text in p (which is probably a generated JSON text string) |
| 853 | ** the result of the SQL function. |
| 854 | ** |
| 855 | ** The JsonString is reset. |
| 856 | ** |
| 857 | ** If pParse and ctx are both non-NULL, then the SQL string in p is |
| 858 | ** loaded into the zJson field of the pParse object as a RCStr and the |
| 859 | ** pParse is added to the cache. |
| 860 | */ |
| 861 | static void jsonReturnString( |
| 862 | JsonString *p, /* String to return */ |
| 863 | JsonParse *pParse, /* JSONB source or NULL */ |
| 864 | sqlite3_context *ctx /* Where to cache */ |
| 865 | ){ |
| 866 | assert( (pParse!=0)==(ctx!=0) ); |
| 867 | assert( ctx==0 || ctx==p->pCtx ); |
| 868 | jsonStringTerminate(p); |
| 869 | if( p->eErr==0 ){ |
| 870 | int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(p->pCtx)); |
| 871 | if( flags & JSON_BLOB ){ |
| 872 | jsonReturnStringAsBlob(p); |
| 873 | }else if( p->bStatic ){ |
| 874 | sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, |
| 875 | SQLITE_TRANSIENT, SQLITE_UTF8); |
| 876 | }else{ |
| 877 | if( pParse && pParse->bJsonIsRCStr==0 && pParse->nBlobAlloc>0 ){ |
| 878 | int rc; |
| 879 | pParse->zJson = sqlite3RCStrRef(p->zBuf); |
| 880 | pParse->nJson = p->nUsed; |
| 881 | pParse->bJsonIsRCStr = 1; |
| 882 | rc = jsonCacheInsert(ctx, pParse); |
| 883 | if( rc==SQLITE_NOMEM ){ |
| 884 | sqlite3_result_error_nomem(ctx); |
| 885 | jsonStringReset(p); |
| 886 | return; |
| 887 | } |
| 888 | } |
| 889 | sqlite3_result_text64(p->pCtx, sqlite3RCStrRef(p->zBuf), p->nUsed, |
| 890 | sqlite3RCStrUnref, |
| 891 | SQLITE_UTF8); |
| 892 | } |
| 893 | }else if( p->eErr & JSTRING_OOM ){ |
| 894 | sqlite3_result_error_nomem(p->pCtx); |
| 895 | }else if( p->eErr & JSTRING_TOODEEP ){ |
| 896 | /* error already in p->pCtx */ |
| 897 | }else if( p->eErr & JSTRING_MALFORMED ){ |
| 898 | sqlite3_result_error(p->pCtx, "malformed JSON", -1); |
| 899 | } |
| 900 | jsonStringReset(p); |
| 901 | } |
| 902 | |
| 903 | /************************************************************************** |
| 904 | ** Utility routines for dealing with JsonParse objects |
| 905 | **************************************************************************/ |
| 906 | |
| 907 | /* |
| 908 | ** Reclaim all memory allocated by a JsonParse object. But do not |
| 909 | ** delete the JsonParse object itself. |
| 910 | */ |
| 911 | static void jsonParseReset(JsonParse *pParse){ |
| 912 | assert( pParse->nJPRef<=1 ); |
| 913 | if( pParse->bJsonIsRCStr ){ |
| 914 | sqlite3RCStrUnref(pParse->zJson); |
| 915 | pParse->zJson = 0; |
| 916 | pParse->nJson = 0; |
| 917 | pParse->bJsonIsRCStr = 0; |
| 918 | } |
| 919 | if( pParse->nBlobAlloc ){ |
| 920 | sqlite3DbFree(pParse->db, pParse->aBlob); |
| 921 | pParse->aBlob = 0; |
| 922 | pParse->nBlob = 0; |
| 923 | pParse->nBlobAlloc = 0; |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | /* |
| 928 | ** Decrement the reference count on the JsonParse object. When the |
| 929 | ** count reaches zero, free the object. |
| 930 | */ |
| 931 | static void jsonParseFree(JsonParse *pParse){ |
| 932 | if( pParse ){ |
| 933 | if( pParse->nJPRef>1 ){ |
| 934 | pParse->nJPRef--; |
| 935 | }else{ |
| 936 | jsonParseReset(pParse); |
| 937 | sqlite3DbFree(pParse->db, pParse); |
| 938 | } |
| 939 | } |
| 940 | } |
| 941 | |
| 942 | /************************************************************************** |
| 943 | ** Utility routines for the JSON text parser |
| 944 | **************************************************************************/ |
| 945 | |
| 946 | /* |
| 947 | ** Translate a single byte of Hex into an integer. |
| 948 | ** This routine only gives a correct answer if h really is a valid hexadecimal |
| 949 | ** character: 0..9a..fA..F. But unlike sqlite3HexToInt(), it does not |
| 950 | ** assert() if the digit is not hex. |
| 951 | */ |
| 952 | static u8 jsonHexToInt(int h){ |
| 953 | #ifdef SQLITE_ASCII |
| 954 | h += 9*(1&(h>>6)); |
| 955 | #endif |
| 956 | #ifdef SQLITE_EBCDIC |
| 957 | h += 9*(1&~(h>>4)); |
| 958 | #endif |
| 959 | return (u8)(h & 0xf); |
| 960 | } |
| 961 | |
| 962 | /* |
| 963 | ** Convert a 4-byte hex string into an integer |
| 964 | */ |
| 965 | static u32 jsonHexToInt4(const char *z){ |
| 966 | u32 v; |
| 967 | v = (jsonHexToInt(z[0])<<12) |
| 968 | + (jsonHexToInt(z[1])<<8) |
| 969 | + (jsonHexToInt(z[2])<<4) |
| 970 | + jsonHexToInt(z[3]); |
| 971 | return v; |
| 972 | } |
| 973 | |
| 974 | /* |
| 975 | ** Return true if z[] begins with 2 (or more) hexadecimal digits |
| 976 | */ |
| 977 | static int jsonIs2Hex(const char *z){ |
| 978 | return sqlite3Isxdigit(z[0]) && sqlite3Isxdigit(z[1]); |
| 979 | } |
| 980 | |
| 981 | /* |
| 982 | ** Return true if z[] begins with 4 (or more) hexadecimal digits |
| 983 | */ |
| 984 | static int jsonIs4Hex(const char *z){ |
| 985 | return jsonIs2Hex(z) && jsonIs2Hex(&z[2]); |
| 986 | } |
| 987 | |
| 988 | /* |
| 989 | ** Return the number of bytes of JSON5 whitespace at the beginning of |
| 990 | ** the input string z[]. |
| 991 | ** |
| 992 | ** JSON5 whitespace consists of any of the following characters: |
| 993 | ** |
| 994 | ** Unicode UTF-8 Name |
| 995 | ** U+0009 09 horizontal tab |
| 996 | ** U+000a 0a line feed |
| 997 | ** U+000b 0b vertical tab |
| 998 | ** U+000c 0c form feed |
| 999 | ** U+000d 0d carriage return |
| 1000 | ** U+0020 20 space |
| 1001 | ** U+00a0 c2 a0 non-breaking space |
| 1002 | ** U+1680 e1 9a 80 ogham space mark |
| 1003 | ** U+2000 e2 80 80 en quad |
| 1004 | ** U+2001 e2 80 81 em quad |
| 1005 | ** U+2002 e2 80 82 en space |
| 1006 | ** U+2003 e2 80 83 em space |
| 1007 | ** U+2004 e2 80 84 three-per-em space |
| 1008 | ** U+2005 e2 80 85 four-per-em space |
| 1009 | ** U+2006 e2 80 86 six-per-em space |
| 1010 | ** U+2007 e2 80 87 figure space |
| 1011 | ** U+2008 e2 80 88 punctuation space |
| 1012 | ** U+2009 e2 80 89 thin space |
| 1013 | ** U+200a e2 80 8a hair space |
| 1014 | ** U+2028 e2 80 a8 line separator |
| 1015 | ** U+2029 e2 80 a9 paragraph separator |
| 1016 | ** U+202f e2 80 af narrow no-break space (NNBSP) |
| 1017 | ** U+205f e2 81 9f medium mathematical space (MMSP) |
| 1018 | ** U+3000 e3 80 80 ideographical space |
| 1019 | ** U+FEFF ef bb bf byte order mark |
| 1020 | ** |
| 1021 | ** In addition, comments between '/', '*' and '*', '/' and |
| 1022 | ** from '/', '/' to end-of-line are also considered to be whitespace. |
| 1023 | */ |
| 1024 | static int json5Whitespace(const char *zIn){ |
| 1025 | int n = 0; |
| 1026 | const u8 *z = (u8*)zIn; |
| 1027 | while( 1 /*exit by "goto whitespace_done"*/ ){ |
| 1028 | switch( z[n] ){ |
| 1029 | case 0x09: |
| 1030 | case 0x0a: |
| 1031 | case 0x0b: |
| 1032 | case 0x0c: |
| 1033 | case 0x0d: |
| 1034 | case 0x20: { |
| 1035 | n++; |
| 1036 | break; |
| 1037 | } |
| 1038 | case '/': { |
| 1039 | if( z[n+1]=='*' && z[n+2]!=0 ){ |
| 1040 | int j; |
| 1041 | for(j=n+3; z[j]!='/' || z[j-1]!='*'; j++){ |
| 1042 | if( z[j]==0 ) goto whitespace_done; |
| 1043 | } |
| 1044 | n = j+1; |
| 1045 | break; |
| 1046 | }else if( z[n+1]=='/' ){ |
| 1047 | int j; |
| 1048 | char c; |
| 1049 | for(j=n+2; (c = z[j])!=0; j++){ |
| 1050 | if( c=='\n' || c=='\r' ) break; |
| 1051 | if( 0xe2==(u8)c && 0x80==(u8)z[j+1] |
| 1052 | && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2]) |
| 1053 | ){ |
| 1054 | j += 2; |
| 1055 | break; |
| 1056 | } |
| 1057 | } |
| 1058 | n = j; |
| 1059 | if( z[n] ) n++; |
| 1060 | break; |
| 1061 | } |
| 1062 | goto whitespace_done; |
| 1063 | } |
| 1064 | case 0xc2: { |
| 1065 | if( z[n+1]==0xa0 ){ |
| 1066 | n += 2; |
| 1067 | break; |
| 1068 | } |
| 1069 | goto whitespace_done; |
| 1070 | } |
| 1071 | case 0xe1: { |
| 1072 | if( z[n+1]==0x9a && z[n+2]==0x80 ){ |
| 1073 | n += 3; |
| 1074 | break; |
| 1075 | } |
| 1076 | goto whitespace_done; |
| 1077 | } |
| 1078 | case 0xe2: { |
| 1079 | if( z[n+1]==0x80 ){ |
| 1080 | u8 c = z[n+2]; |
| 1081 | if( c<0x80 ) goto whitespace_done; |
| 1082 | if( c<=0x8a || c==0xa8 || c==0xa9 || c==0xaf ){ |
| 1083 | n += 3; |
| 1084 | break; |
| 1085 | } |
| 1086 | }else if( z[n+1]==0x81 && z[n+2]==0x9f ){ |
| 1087 | n += 3; |
| 1088 | break; |
| 1089 | } |
| 1090 | goto whitespace_done; |
| 1091 | } |
| 1092 | case 0xe3: { |
| 1093 | if( z[n+1]==0x80 && z[n+2]==0x80 ){ |
| 1094 | n += 3; |
| 1095 | break; |
| 1096 | } |
| 1097 | goto whitespace_done; |
| 1098 | } |
| 1099 | case 0xef: { |
| 1100 | if( z[n+1]==0xbb && z[n+2]==0xbf ){ |
| 1101 | n += 3; |
| 1102 | break; |
| 1103 | } |
| 1104 | goto whitespace_done; |
| 1105 | } |
| 1106 | default: { |
| 1107 | goto whitespace_done; |
| 1108 | } |
| 1109 | } |
| 1110 | } |
| 1111 | whitespace_done: |
| 1112 | return n; |
| 1113 | } |
| 1114 | |
| 1115 | /* |
| 1116 | ** Extra floating-point literals to allow in JSON. |
| 1117 | */ |
| 1118 | static const struct NanInfName { |
| 1119 | char c1; |
| 1120 | char c2; |
| 1121 | char n; |
| 1122 | char eType; |
| 1123 | char nRepl; |
| 1124 | char *zMatch; |
| 1125 | char *zRepl; |
| 1126 | } aNanInfName[] = { |
| 1127 | { 'i', 'I', 3, JSONB_FLOAT, 7, "inf", "9.0e999" }, |
| 1128 | { 'i', 'I', 8, JSONB_FLOAT, 7, "infinity", "9.0e999" }, |
| 1129 | { 'n', 'N', 3, JSONB_NULL, 4, "NaN", "null" }, |
| 1130 | { 'q', 'Q', 4, JSONB_NULL, 4, "QNaN", "null" }, |
| 1131 | { 's', 'S', 4, JSONB_NULL, 4, "SNaN", "null" }, |
| 1132 | }; |
| 1133 | |
| 1134 | |
| 1135 | /* |
| 1136 | ** Report the wrong number of arguments for json_insert(), json_replace() |
| 1137 | ** or json_set(). |
| 1138 | */ |
| 1139 | static void jsonWrongNumArgs( |
| 1140 | sqlite3_context *pCtx, |
| 1141 | const char *zFuncName |
| 1142 | ){ |
| 1143 | char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments", |
| 1144 | zFuncName); |
| 1145 | sqlite3_result_error(pCtx, zMsg, -1); |
| 1146 | sqlite3_free(zMsg); |
| 1147 | } |
| 1148 | |
| 1149 | /**************************************************************************** |
| 1150 | ** Utility routines for dealing with the binary BLOB representation of JSON |
| 1151 | ****************************************************************************/ |
| 1152 | |
| 1153 | /* |
| 1154 | ** Expand pParse->aBlob so that it holds at least N bytes. |
| 1155 | ** |
| 1156 | ** Return the number of errors. |
| 1157 | */ |
| 1158 | static int jsonBlobExpand(JsonParse *pParse, u64 N){ |
| 1159 | u8 *aNew; |
| 1160 | u64 t; |
| 1161 | assert( N>pParse->nBlobAlloc ); |
| 1162 | if( pParse->nBlobAlloc==0 ){ |
| 1163 | t = 100; |
| 1164 | }else{ |
| 1165 | t = pParse->nBlobAlloc*2; |
| 1166 | } |
| 1167 | if( t<N ) t = N+100; |
| 1168 | aNew = sqlite3DbRealloc(pParse->db, pParse->aBlob, t); |
| 1169 | if( aNew==0 ){ pParse->oom = 1; return 1; } |
| 1170 | assert( t<0x7fffffff ); |
| 1171 | pParse->aBlob = aNew; |
| 1172 | pParse->nBlobAlloc = (u32)t; |
| 1173 | return 0; |
| 1174 | } |
| 1175 | |
| 1176 | /* |
| 1177 | ** If pParse->aBlob is not previously editable (because it is taken |
| 1178 | ** from sqlite3_value_blob(), as indicated by the fact that |
| 1179 | ** pParse->nBlobAlloc==0 and pParse->nBlob>0) then make it editable |
| 1180 | ** by making a copy into space obtained from malloc. |
| 1181 | ** |
| 1182 | ** Return true on success. Return false on OOM. |
| 1183 | */ |
| 1184 | static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){ |
| 1185 | u8 *aOld; |
| 1186 | u64 nSize; |
| 1187 | assert( !pParse->bReadOnly ); |
| 1188 | if( pParse->oom ) return 0; |
| 1189 | if( pParse->nBlobAlloc>0 ) return 1; |
| 1190 | aOld = pParse->aBlob; |
| 1191 | nSize = pParse->nBlob + nExtra; |
| 1192 | pParse->aBlob = 0; |
| 1193 | if( jsonBlobExpand(pParse, nSize) ){ |
| 1194 | return 0; |
| 1195 | } |
| 1196 | assert( pParse->nBlobAlloc >= pParse->nBlob + nExtra ); |
| 1197 | memcpy(pParse->aBlob, aOld, pParse->nBlob); |
| 1198 | return 1; |
| 1199 | } |
| 1200 | |
| 1201 | /* Expand pParse->aBlob and append one bytes. |
| 1202 | */ |
| 1203 | static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte( |
| 1204 | JsonParse *pParse, |
| 1205 | u8 c |
| 1206 | ){ |
| 1207 | jsonBlobExpand(pParse, (u64)pParse->nBlob+1); |
| 1208 | if( pParse->oom==0 ){ |
| 1209 | assert( pParse->nBlob+1<=pParse->nBlobAlloc ); |
| 1210 | pParse->aBlob[pParse->nBlob++] = c; |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | /* Append a single character. |
| 1215 | */ |
| 1216 | static void jsonBlobAppendOneByte(JsonParse *pParse, u8 c){ |
| 1217 | if( pParse->nBlob >= pParse->nBlobAlloc ){ |
| 1218 | jsonBlobExpandAndAppendOneByte(pParse, c); |
| 1219 | }else{ |
| 1220 | pParse->aBlob[pParse->nBlob++] = c; |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | /* Slow version of jsonBlobAppendNode() that first resizes the |
| 1225 | ** pParse->aBlob structure. |
| 1226 | */ |
| 1227 | static void jsonBlobAppendNode(JsonParse*,u8,u64,const void*); |
| 1228 | static SQLITE_NOINLINE void jsonBlobExpandAndAppendNode( |
| 1229 | JsonParse *pParse, |
| 1230 | u8 eType, |
| 1231 | u64 szPayload, |
| 1232 | const void *aPayload |
| 1233 | ){ |
| 1234 | if( jsonBlobExpand(pParse, (u64)pParse->nBlob+(u64)szPayload+9) ) return; |
| 1235 | jsonBlobAppendNode(pParse, eType, szPayload, aPayload); |
| 1236 | } |
| 1237 | |
| 1238 | |
| 1239 | /* Append a node type byte together with the payload size and |
| 1240 | ** possibly also the payload. |
| 1241 | ** |
| 1242 | ** If aPayload is not NULL, then it is a pointer to the payload which |
| 1243 | ** is also appended. If aPayload is NULL, the pParse->aBlob[] array |
| 1244 | ** is resized (if necessary) so that it is big enough to hold the |
| 1245 | ** payload, but the payload is not appended and pParse->nBlob is left |
| 1246 | ** pointing to where the first byte of payload will eventually be. |
| 1247 | */ |
| 1248 | static void jsonBlobAppendNode( |
| 1249 | JsonParse *pParse, /* The JsonParse object under construction */ |
| 1250 | u8 eType, /* Node type. One of JSONB_* */ |
| 1251 | u64 szPayload, /* Number of bytes of payload */ |
| 1252 | const void *aPayload /* The payload. Might be NULL */ |
| 1253 | ){ |
| 1254 | u8 *a; |
| 1255 | if( pParse->nBlob+szPayload+9 > pParse->nBlobAlloc ){ |
| 1256 | jsonBlobExpandAndAppendNode(pParse,eType,szPayload,aPayload); |
| 1257 | return; |
| 1258 | } |
| 1259 | assert( pParse->aBlob!=0 ); |
| 1260 | a = &pParse->aBlob[pParse->nBlob]; |
| 1261 | if( szPayload<=11 ){ |
| 1262 | a[0] = eType | (szPayload<<4); |
| 1263 | pParse->nBlob += 1; |
| 1264 | }else if( szPayload<=0xff ){ |
| 1265 | a[0] = eType | 0xc0; |
| 1266 | a[1] = szPayload & 0xff; |
| 1267 | pParse->nBlob += 2; |
| 1268 | }else if( szPayload<=0xffff ){ |
| 1269 | a[0] = eType | 0xd0; |
| 1270 | a[1] = (szPayload >> 8) & 0xff; |
| 1271 | a[2] = szPayload & 0xff; |
| 1272 | pParse->nBlob += 3; |
| 1273 | }else{ |
| 1274 | a[0] = eType | 0xe0; |
| 1275 | a[1] = (szPayload >> 24) & 0xff; |
| 1276 | a[2] = (szPayload >> 16) & 0xff; |
| 1277 | a[3] = (szPayload >> 8) & 0xff; |
| 1278 | a[4] = szPayload & 0xff; |
| 1279 | pParse->nBlob += 5; |
| 1280 | } |
| 1281 | if( aPayload ){ |
| 1282 | pParse->nBlob += szPayload; |
| 1283 | memcpy(&pParse->aBlob[pParse->nBlob-szPayload], aPayload, szPayload); |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | /* Change the payload size for the node at index i to be szPayload. |
| 1288 | */ |
| 1289 | static int jsonBlobChangePayloadSize( |
| 1290 | JsonParse *pParse, |
| 1291 | u32 i, |
| 1292 | u32 szPayload |
| 1293 | ){ |
| 1294 | u8 *a; |
| 1295 | u8 szType; |
| 1296 | u8 nExtra; |
| 1297 | u8 nNeeded; |
| 1298 | int delta; |
| 1299 | if( pParse->oom ) return 0; |
| 1300 | a = &pParse->aBlob[i]; |
| 1301 | szType = a[0]>>4; |
| 1302 | if( szType<=11 ){ |
| 1303 | nExtra = 0; |
| 1304 | }else if( szType==12 ){ |
| 1305 | nExtra = 1; |
| 1306 | }else if( szType==13 ){ |
| 1307 | nExtra = 2; |
| 1308 | }else if( szType==14 ){ |
| 1309 | nExtra = 4; |
| 1310 | }else{ |
| 1311 | nExtra = 8; |
| 1312 | } |
| 1313 | if( szPayload<=11 ){ |
| 1314 | nNeeded = 0; |
| 1315 | }else if( szPayload<=0xff ){ |
| 1316 | nNeeded = 1; |
| 1317 | }else if( szPayload<=0xffff ){ |
| 1318 | nNeeded = 2; |
| 1319 | }else{ |
| 1320 | nNeeded = 4; |
| 1321 | } |
| 1322 | delta = nNeeded - nExtra; |
| 1323 | if( delta ){ |
| 1324 | u64 newSize = (u64)pParse->nBlob + delta; |
| 1325 | if( delta>0 ){ |
| 1326 | if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){ |
| 1327 | return 0; /* OOM error. Error state recorded in pParse->oom. */ |
| 1328 | } |
| 1329 | a = &pParse->aBlob[i]; |
| 1330 | memmove(&a[1+delta], &a[1], pParse->nBlob - (i+1)); |
| 1331 | }else{ |
| 1332 | memmove(&a[1], &a[1-delta], pParse->nBlob - (i+1-delta)); |
| 1333 | } |
| 1334 | pParse->nBlob = newSize; |
| 1335 | } |
| 1336 | if( nNeeded==0 ){ |
| 1337 | a[0] = (a[0] & 0x0f) | (szPayload<<4); |
| 1338 | }else if( nNeeded==1 ){ |
| 1339 | a[0] = (a[0] & 0x0f) | 0xc0; |
| 1340 | a[1] = szPayload & 0xff; |
| 1341 | }else if( nNeeded==2 ){ |
| 1342 | a[0] = (a[0] & 0x0f) | 0xd0; |
| 1343 | a[1] = (szPayload >> 8) & 0xff; |
| 1344 | a[2] = szPayload & 0xff; |
| 1345 | }else{ |
| 1346 | a[0] = (a[0] & 0x0f) | 0xe0; |
| 1347 | a[1] = (szPayload >> 24) & 0xff; |
| 1348 | a[2] = (szPayload >> 16) & 0xff; |
| 1349 | a[3] = (szPayload >> 8) & 0xff; |
| 1350 | a[4] = szPayload & 0xff; |
| 1351 | } |
| 1352 | return delta; |
| 1353 | } |
| 1354 | |
| 1355 | /* |
| 1356 | ** If z[0] is 'u' and is followed by exactly 4 hexadecimal character, |
| 1357 | ** then set *pOp to JSONB_TEXTJ and return true. If not, do not make |
| 1358 | ** any changes to *pOp and return false. |
| 1359 | */ |
| 1360 | static int jsonIs4HexB(const char *z, int *pOp){ |
| 1361 | if( z[0]!='u' ) return 0; |
| 1362 | if( !jsonIs4Hex(&z[1]) ) return 0; |
| 1363 | *pOp = JSONB_TEXTJ; |
| 1364 | return 1; |
| 1365 | } |
| 1366 | |
| 1367 | /* |
| 1368 | ** Check a single element of the JSONB in pParse for validity. |
| 1369 | ** |
| 1370 | ** The element to be checked starts at offset i and must end at on the |
| 1371 | ** last byte before iEnd. |
| 1372 | ** |
| 1373 | ** Return 0 if everything is correct. Return the 1-based byte offset of the |
| 1374 | ** error if a problem is detected. (In other words, if the error is at offset |
| 1375 | ** 0, return 1). |
| 1376 | */ |
| 1377 | static u32 jsonbValidityCheck( |
| 1378 | const JsonParse *pParse, /* Input JSONB. Only aBlob and nBlob are used */ |
| 1379 | u32 i, /* Start of element as pParse->aBlob[i] */ |
| 1380 | u32 iEnd, /* One more than the last byte of the element */ |
| 1381 | u32 iDepth /* Current nesting depth */ |
| 1382 | ){ |
| 1383 | u32 n, sz, j, k; |
| 1384 | const u8 *z; |
| 1385 | u8 x; |
| 1386 | if( iDepth>JSON_MAX_DEPTH ) return i+1; |
| 1387 | sz = 0; |
| 1388 | n = jsonbPayloadSize(pParse, i, &sz); |
| 1389 | if( NEVER(n==0) ) return i+1; /* Checked by caller */ |
| 1390 | if( NEVER(i+n+sz!=iEnd) ) return i+1; /* Checked by caller */ |
| 1391 | z = pParse->aBlob; |
| 1392 | x = z[i] & 0x0f; |
| 1393 | switch( x ){ |
| 1394 | case JSONB_NULL: |
| 1395 | case JSONB_TRUE: |
| 1396 | case JSONB_FALSE: { |
| 1397 | return n+sz==1 ? 0 : i+1; |
| 1398 | } |
| 1399 | case JSONB_INT: { |
| 1400 | if( sz<1 ) return i+1; |
| 1401 | j = i+n; |
| 1402 | if( z[j]=='-' ){ |
| 1403 | j++; |
| 1404 | if( sz<2 ) return i+1; |
| 1405 | } |
| 1406 | k = i+n+sz; |
| 1407 | while( j<k ){ |
| 1408 | if( sqlite3Isdigit(z[j]) ){ |
| 1409 | j++; |
| 1410 | }else{ |
| 1411 | return j+1; |
| 1412 | } |
| 1413 | } |
| 1414 | return 0; |
| 1415 | } |
| 1416 | case JSONB_INT5: { |
| 1417 | if( sz<3 ) return i+1; |
| 1418 | j = i+n; |
| 1419 | if( z[j]=='-' ){ |
| 1420 | if( sz<4 ) return i+1; |
| 1421 | j++; |
| 1422 | } |
| 1423 | if( z[j]!='0' ) return i+1; |
| 1424 | if( z[j+1]!='x' && z[j+1]!='X' ) return j+2; |
| 1425 | j += 2; |
| 1426 | k = i+n+sz; |
| 1427 | while( j<k ){ |
| 1428 | if( sqlite3Isxdigit(z[j]) ){ |
| 1429 | j++; |
| 1430 | }else{ |
| 1431 | return j+1; |
| 1432 | } |
| 1433 | } |
| 1434 | return 0; |
| 1435 | } |
| 1436 | case JSONB_FLOAT: |
| 1437 | case JSONB_FLOAT5: { |
| 1438 | u8 seen = 0; /* 0: initial. 1: '.' seen 2: 'e' seen */ |
| 1439 | if( sz<2 ) return i+1; |
| 1440 | j = i+n; |
| 1441 | k = j+sz; |
| 1442 | if( z[j]=='-' ){ |
| 1443 | j++; |
| 1444 | if( sz<3 ) return i+1; |
| 1445 | } |
| 1446 | if( z[j]=='.' ){ |
| 1447 | if( x==JSONB_FLOAT ) return j+1; |
| 1448 | if( !sqlite3Isdigit(z[j+1]) ) return j+1; |
| 1449 | j += 2; |
| 1450 | seen = 1; |
| 1451 | }else if( z[j]=='0' && x==JSONB_FLOAT ){ |
| 1452 | if( j+3>k ) return j+1; |
| 1453 | if( z[j+1]!='.' && z[j+1]!='e' && z[j+1]!='E' ) return j+1; |
| 1454 | j++; |
| 1455 | } |
| 1456 | for(; j<k; j++){ |
| 1457 | if( sqlite3Isdigit(z[j]) ) continue; |
| 1458 | if( z[j]=='.' ){ |
| 1459 | if( seen>0 ) return j+1; |
| 1460 | if( x==JSONB_FLOAT && (j==k-1 || !sqlite3Isdigit(z[j+1])) ){ |
| 1461 | return j+1; |
| 1462 | } |
| 1463 | seen = 1; |
| 1464 | continue; |
| 1465 | } |
| 1466 | if( z[j]=='e' || z[j]=='E' ){ |
| 1467 | if( seen==2 ) return j+1; |
| 1468 | if( j==k-1 ) return j+1; |
| 1469 | if( z[j+1]=='+' || z[j+1]=='-' ){ |
| 1470 | j++; |
| 1471 | if( j==k-1 ) return j+1; |
| 1472 | } |
| 1473 | seen = 2; |
| 1474 | continue; |
| 1475 | } |
| 1476 | return j+1; |
| 1477 | } |
| 1478 | if( seen==0 ) return i+1; |
| 1479 | return 0; |
| 1480 | } |
| 1481 | case JSONB_TEXT: { |
| 1482 | j = i+n; |
| 1483 | k = j+sz; |
| 1484 | while( j<k ){ |
| 1485 | if( !jsonIsOk[z[j]] && z[j]!='\'' ) return j+1; |
| 1486 | j++; |
| 1487 | } |
| 1488 | return 0; |
| 1489 | } |
| 1490 | case JSONB_TEXTJ: |
| 1491 | case JSONB_TEXT5: { |
| 1492 | j = i+n; |
| 1493 | k = j+sz; |
| 1494 | while( j<k ){ |
| 1495 | if( !jsonIsOk[z[j]] && z[j]!='\'' ){ |
| 1496 | if( z[j]=='"' ){ |
| 1497 | if( x==JSONB_TEXTJ ) return j+1; |
| 1498 | }else if( z[j]<=0x1f ){ |
| 1499 | /* Control characters in JSON5 string literals are ok */ |
| 1500 | if( x==JSONB_TEXTJ ) return j+1; |
| 1501 | }else if( NEVER(z[j]!='\\') || j+1>=k ){ |
| 1502 | return j+1; |
| 1503 | }else if( strchr("\"\\/bfnrt",z[j+1])!=0 ){ |
| 1504 | j++; |
| 1505 | }else if( z[j+1]=='u' ){ |
| 1506 | if( j+5>=k ) return j+1; |
| 1507 | if( !jsonIs4Hex((const char*)&z[j+2]) ) return j+1; |
| 1508 | j++; |
| 1509 | }else if( x!=JSONB_TEXT5 ){ |
| 1510 | return j+1; |
| 1511 | }else{ |
| 1512 | u32 c = 0; |
| 1513 | u32 szC = jsonUnescapeOneChar((const char*)&z[j], k-j, &c); |
| 1514 | if( c==JSON_INVALID_CHAR ) return j+1; |
| 1515 | j += szC - 1; |
| 1516 | } |
| 1517 | } |
| 1518 | j++; |
| 1519 | } |
| 1520 | return 0; |
| 1521 | } |
| 1522 | case JSONB_TEXTRAW: { |
| 1523 | return 0; |
| 1524 | } |
| 1525 | case JSONB_ARRAY: { |
| 1526 | u32 sub; |
| 1527 | j = i+n; |
| 1528 | k = j+sz; |
| 1529 | while( j<k ){ |
| 1530 | sz = 0; |
| 1531 | n = jsonbPayloadSize(pParse, j, &sz); |
| 1532 | if( n==0 ) return j+1; |
| 1533 | if( j+n+sz>k ) return j+1; |
| 1534 | sub = jsonbValidityCheck(pParse, j, j+n+sz, iDepth+1); |
| 1535 | if( sub ) return sub; |
| 1536 | j += n + sz; |
| 1537 | } |
| 1538 | assert( j==k ); |
| 1539 | return 0; |
| 1540 | } |
| 1541 | case JSONB_OBJECT: { |
| 1542 | u32 cnt = 0; |
| 1543 | u32 sub; |
| 1544 | j = i+n; |
| 1545 | k = j+sz; |
| 1546 | while( j<k ){ |
| 1547 | sz = 0; |
| 1548 | n = jsonbPayloadSize(pParse, j, &sz); |
| 1549 | if( n==0 ) return j+1; |
| 1550 | if( j+n+sz>k ) return j+1; |
| 1551 | if( (cnt & 1)==0 ){ |
| 1552 | x = z[j] & 0x0f; |
| 1553 | if( x<JSONB_TEXT || x>JSONB_TEXTRAW ) return j+1; |
| 1554 | } |
| 1555 | sub = jsonbValidityCheck(pParse, j, j+n+sz, iDepth+1); |
| 1556 | if( sub ) return sub; |
| 1557 | cnt++; |
| 1558 | j += n + sz; |
| 1559 | } |
| 1560 | assert( j==k ); |
| 1561 | if( (cnt & 1)!=0 ) return j+1; |
| 1562 | return 0; |
| 1563 | } |
| 1564 | default: { |
| 1565 | return i+1; |
| 1566 | } |
| 1567 | } |
| 1568 | } |
| 1569 | |
| 1570 | /* |
| 1571 | ** Translate a single element of JSON text at pParse->zJson[i] into |
| 1572 | ** its equivalent binary JSONB representation. Append the translation into |
| 1573 | ** pParse->aBlob[] beginning at pParse->nBlob. The size of |
| 1574 | ** pParse->aBlob[] is increased as necessary. |
| 1575 | ** |
| 1576 | ** Return the index of the first character past the end of the element parsed, |
| 1577 | ** or one of the following special result codes: |
| 1578 | ** |
| 1579 | ** 0 End of input |
| 1580 | ** -1 Syntax error or OOM |
| 1581 | ** -2 '}' seen \ |
| 1582 | ** -3 ']' seen \___ For these returns, pParse->iErr is set to |
| 1583 | ** -4 ',' seen / the index in zJson[] of the seen character |
| 1584 | ** -5 ':' seen / |
| 1585 | */ |
| 1586 | static int jsonTranslateTextToBlob(JsonParse *pParse, u32 i){ |
| 1587 | char c; |
| 1588 | u32 j; |
| 1589 | u32 iThis, iStart; |
| 1590 | int x; |
| 1591 | u8 t; |
| 1592 | const char *z = pParse->zJson; |
| 1593 | json_parse_restart: |
| 1594 | switch( (u8)z[i] ){ |
| 1595 | case '{': { |
| 1596 | /* Parse object */ |
| 1597 | iThis = pParse->nBlob; |
| 1598 | jsonBlobAppendNode(pParse, JSONB_OBJECT, pParse->nJson-i, 0); |
| 1599 | if( ++pParse->iDepth > JSON_MAX_DEPTH ){ |
| 1600 | pParse->iErr = i; |
| 1601 | return -1; |
| 1602 | } |
| 1603 | iStart = pParse->nBlob; |
| 1604 | for(j=i+1;;j++){ |
| 1605 | u32 iBlob = pParse->nBlob; |
| 1606 | x = jsonTranslateTextToBlob(pParse, j); |
| 1607 | if( x<=0 ){ |
| 1608 | int op; |
| 1609 | if( x==(-2) ){ |
| 1610 | j = pParse->iErr; |
| 1611 | if( pParse->nBlob!=(u32)iStart ) pParse->hasNonstd = 1; |
| 1612 | break; |
| 1613 | } |
| 1614 | j += json5Whitespace(&z[j]); |
| 1615 | op = JSONB_TEXT; |
| 1616 | if( sqlite3JsonId1(z[j]) |
| 1617 | || (z[j]=='\\' && jsonIs4HexB(&z[j+1], &op)) |
| 1618 | ){ |
| 1619 | int k = j+1; |
| 1620 | while( (sqlite3JsonId2(z[k]) && json5Whitespace(&z[k])==0) |
| 1621 | || (z[k]=='\\' && jsonIs4HexB(&z[k+1], &op)) |
| 1622 | ){ |
| 1623 | k++; |
| 1624 | } |
| 1625 | assert( iBlob==pParse->nBlob ); |
| 1626 | jsonBlobAppendNode(pParse, op, k-j, &z[j]); |
| 1627 | pParse->hasNonstd = 1; |
| 1628 | x = k; |
| 1629 | }else{ |
| 1630 | if( x!=-1 ) pParse->iErr = j; |
| 1631 | return -1; |
| 1632 | } |
| 1633 | } |
| 1634 | if( pParse->oom ) return -1; |
| 1635 | t = pParse->aBlob[iBlob] & 0x0f; |
| 1636 | if( t<JSONB_TEXT || t>JSONB_TEXTRAW ){ |
| 1637 | pParse->iErr = j; |
| 1638 | return -1; |
| 1639 | } |
| 1640 | j = x; |
| 1641 | if( z[j]==':' ){ |
| 1642 | j++; |
| 1643 | }else{ |
| 1644 | if( jsonIsspace(z[j]) ){ |
| 1645 | /* strspn() is not helpful here */ |
| 1646 | do{ j++; }while( jsonIsspace(z[j]) ); |
| 1647 | if( z[j]==':' ){ |
| 1648 | j++; |
| 1649 | goto parse_object_value; |
| 1650 | } |
| 1651 | } |
| 1652 | x = jsonTranslateTextToBlob(pParse, j); |
| 1653 | if( x!=(-5) ){ |
| 1654 | if( x!=(-1) ) pParse->iErr = j; |
| 1655 | return -1; |
| 1656 | } |
| 1657 | j = pParse->iErr+1; |
| 1658 | } |
| 1659 | parse_object_value: |
| 1660 | x = jsonTranslateTextToBlob(pParse, j); |
| 1661 | if( x<=0 ){ |
| 1662 | if( x!=(-1) ) pParse->iErr = j; |
| 1663 | return -1; |
| 1664 | } |
| 1665 | j = x; |
| 1666 | if( z[j]==',' ){ |
| 1667 | continue; |
| 1668 | }else if( z[j]=='}' ){ |
| 1669 | break; |
| 1670 | }else{ |
| 1671 | if( jsonIsspace(z[j]) ){ |
| 1672 | j += 1 + (u32)strspn(&z[j+1], jsonSpaces); |
| 1673 | if( z[j]==',' ){ |
| 1674 | continue; |
| 1675 | }else if( z[j]=='}' ){ |
| 1676 | break; |
| 1677 | } |
| 1678 | } |
| 1679 | x = jsonTranslateTextToBlob(pParse, j); |
| 1680 | if( x==(-4) ){ |
| 1681 | j = pParse->iErr; |
| 1682 | continue; |
| 1683 | } |
| 1684 | if( x==(-2) ){ |
| 1685 | j = pParse->iErr; |
| 1686 | break; |
| 1687 | } |
| 1688 | } |
| 1689 | pParse->iErr = j; |
| 1690 | return -1; |
| 1691 | } |
| 1692 | jsonBlobChangePayloadSize(pParse, iThis, pParse->nBlob - iStart); |
| 1693 | pParse->iDepth--; |
| 1694 | return j+1; |
| 1695 | } |
| 1696 | case '[': { |
| 1697 | /* Parse array */ |
| 1698 | iThis = pParse->nBlob; |
| 1699 | assert( i<=(u32)pParse->nJson ); |
| 1700 | jsonBlobAppendNode(pParse, JSONB_ARRAY, pParse->nJson - i, 0); |
| 1701 | iStart = pParse->nBlob; |
| 1702 | if( pParse->oom ) return -1; |
| 1703 | if( ++pParse->iDepth > JSON_MAX_DEPTH ){ |
| 1704 | pParse->iErr = i; |
| 1705 | return -1; |
| 1706 | } |
| 1707 | for(j=i+1;;j++){ |
| 1708 | x = jsonTranslateTextToBlob(pParse, j); |
| 1709 | if( x<=0 ){ |
| 1710 | if( x==(-3) ){ |
| 1711 | j = pParse->iErr; |
| 1712 | if( pParse->nBlob!=iStart ) pParse->hasNonstd = 1; |
| 1713 | break; |
| 1714 | } |
| 1715 | if( x!=(-1) ) pParse->iErr = j; |
| 1716 | return -1; |
| 1717 | } |
| 1718 | j = x; |
| 1719 | if( z[j]==',' ){ |
| 1720 | continue; |
| 1721 | }else if( z[j]==']' ){ |
| 1722 | break; |
| 1723 | }else{ |
| 1724 | if( jsonIsspace(z[j]) ){ |
| 1725 | j += 1 + (u32)strspn(&z[j+1], jsonSpaces); |
| 1726 | if( z[j]==',' ){ |
| 1727 | continue; |
| 1728 | }else if( z[j]==']' ){ |
| 1729 | break; |
| 1730 | } |
| 1731 | } |
| 1732 | x = jsonTranslateTextToBlob(pParse, j); |
| 1733 | if( x==(-4) ){ |
| 1734 | j = pParse->iErr; |
| 1735 | continue; |
| 1736 | } |
| 1737 | if( x==(-3) ){ |
| 1738 | j = pParse->iErr; |
| 1739 | break; |
| 1740 | } |
| 1741 | } |
| 1742 | pParse->iErr = j; |
| 1743 | return -1; |
| 1744 | } |
| 1745 | jsonBlobChangePayloadSize(pParse, iThis, pParse->nBlob - iStart); |
| 1746 | pParse->iDepth--; |
| 1747 | return j+1; |
| 1748 | } |
| 1749 | case '\'': { |
| 1750 | u8 opcode; |
| 1751 | char cDelim; |
| 1752 | pParse->hasNonstd = 1; |
| 1753 | opcode = JSONB_TEXT; |
| 1754 | goto parse_string; |
| 1755 | case '"': |
| 1756 | /* Parse string */ |
| 1757 | opcode = JSONB_TEXT; |
| 1758 | parse_string: |
| 1759 | cDelim = z[i]; |
| 1760 | j = i+1; |
| 1761 | while( 1 /*exit-by-break*/ ){ |
| 1762 | if( jsonIsOk[(u8)z[j]] ){ |
| 1763 | if( !jsonIsOk[(u8)z[j+1]] ){ |
| 1764 | j += 1; |
| 1765 | }else if( !jsonIsOk[(u8)z[j+2]] ){ |
| 1766 | j += 2; |
| 1767 | }else{ |
| 1768 | j += 3; |
| 1769 | continue; |
| 1770 | } |
| 1771 | } |
| 1772 | c = z[j]; |
| 1773 | if( c==cDelim ){ |
| 1774 | break; |
| 1775 | }else if( c=='\\' ){ |
| 1776 | c = z[++j]; |
| 1777 | if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f' |
| 1778 | || c=='n' || c=='r' || c=='t' |
| 1779 | || (c=='u' && jsonIs4Hex(&z[j+1])) ){ |
| 1780 | if( opcode==JSONB_TEXT ) opcode = JSONB_TEXTJ; |
| 1781 | }else if( c=='\'' || c=='v' || c=='\n' |
| 1782 | #ifdef SQLITE_BUG_COMPATIBLE_20250510 |
| 1783 | || (c=='0') /* Legacy bug compatible */ |
| 1784 | #else |
| 1785 | || (c=='0' && !sqlite3Isdigit(z[j+1])) /* Correct implementation */ |
| 1786 | #endif |
| 1787 | || (0xe2==(u8)c && 0x80==(u8)z[j+1] |
| 1788 | && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2])) |
| 1789 | || (c=='x' && jsonIs2Hex(&z[j+1])) ){ |
| 1790 | opcode = JSONB_TEXT5; |
| 1791 | pParse->hasNonstd = 1; |
| 1792 | }else if( c=='\r' ){ |
| 1793 | if( z[j+1]=='\n' ) j++; |
| 1794 | opcode = JSONB_TEXT5; |
| 1795 | pParse->hasNonstd = 1; |
| 1796 | }else{ |
| 1797 | pParse->iErr = j; |
| 1798 | return -1; |
| 1799 | } |
| 1800 | }else if( c<=0x1f ){ |
| 1801 | if( c==0 ){ |
| 1802 | pParse->iErr = j; |
| 1803 | return -1; |
| 1804 | } |
| 1805 | /* Control characters are not allowed in canonical JSON string |
| 1806 | ** literals, but are allowed in JSON5 string literals. */ |
| 1807 | opcode = JSONB_TEXT5; |
| 1808 | pParse->hasNonstd = 1; |
| 1809 | }else if( c=='"' ){ |
| 1810 | opcode = JSONB_TEXT5; |
| 1811 | } |
| 1812 | j++; |
| 1813 | } |
| 1814 | jsonBlobAppendNode(pParse, opcode, j-1-i, &z[i+1]); |
| 1815 | return j+1; |
| 1816 | } |
| 1817 | case 't': { |
| 1818 | if( strncmp(z+i,"true",4)==0 && !sqlite3Isalnum(z[i+4]) ){ |
| 1819 | jsonBlobAppendOneByte(pParse, JSONB_TRUE); |
| 1820 | return i+4; |
| 1821 | } |
| 1822 | pParse->iErr = i; |
| 1823 | return -1; |
| 1824 | } |
| 1825 | case 'f': { |
| 1826 | if( strncmp(z+i,"false",5)==0 && !sqlite3Isalnum(z[i+5]) ){ |
| 1827 | jsonBlobAppendOneByte(pParse, JSONB_FALSE); |
| 1828 | return i+5; |
| 1829 | } |
| 1830 | pParse->iErr = i; |
| 1831 | return -1; |
| 1832 | } |
| 1833 | case '+': { |
| 1834 | u8 seenE; |
| 1835 | pParse->hasNonstd = 1; |
| 1836 | t = 0x00; /* Bit 0x01: JSON5. Bit 0x02: FLOAT */ |
| 1837 | goto parse_number; |
| 1838 | case '.': |
| 1839 | if( sqlite3Isdigit(z[i+1]) ){ |
| 1840 | pParse->hasNonstd = 1; |
| 1841 | t = 0x03; /* Bit 0x01: JSON5. Bit 0x02: FLOAT */ |
| 1842 | seenE = 0; |
| 1843 | goto parse_number_2; |
| 1844 | } |
| 1845 | pParse->iErr = i; |
| 1846 | return -1; |
| 1847 | case '-': |
| 1848 | case '0': |
| 1849 | case '1': |
| 1850 | case '2': |
| 1851 | case '3': |
| 1852 | case '4': |
| 1853 | case '5': |
| 1854 | case '6': |
| 1855 | case '7': |
| 1856 | case '8': |
| 1857 | case '9': |
| 1858 | /* Parse number */ |
| 1859 | t = 0x00; /* Bit 0x01: JSON5. Bit 0x02: FLOAT */ |
| 1860 | parse_number: |
| 1861 | seenE = 0; |
| 1862 | assert( '-' < '0' ); |
| 1863 | assert( '+' < '0' ); |
| 1864 | assert( '.' < '0' ); |
| 1865 | c = z[i]; |
| 1866 | |
| 1867 | if( c<='0' ){ |
| 1868 | if( c=='0' ){ |
| 1869 | if( (z[i+1]=='x' || z[i+1]=='X') && sqlite3Isxdigit(z[i+2]) ){ |
| 1870 | assert( t==0x00 ); |
| 1871 | pParse->hasNonstd = 1; |
| 1872 | t = 0x01; |
| 1873 | for(j=i+3; sqlite3Isxdigit(z[j]); j++){} |
| 1874 | goto parse_number_finish; |
| 1875 | }else if( sqlite3Isdigit(z[i+1]) ){ |
| 1876 | pParse->iErr = i+1; |
| 1877 | return -1; |
| 1878 | } |
| 1879 | }else{ |
| 1880 | if( !sqlite3Isdigit(z[i+1]) ){ |
| 1881 | assert( z[i]=='-' || z[i]=='+' ); |
| 1882 | /* JSON5 allows for "+Infinity" and "-Infinity" using exactly |
| 1883 | ** that case. SQLite also allows these in any case and it allows |
| 1884 | ** "+inf" and "-inf". */ |
| 1885 | if( (z[i+1]=='I' || z[i+1]=='i') |
| 1886 | && sqlite3StrNICmp(&z[i+1], "inf",3)==0 |
| 1887 | ){ |
| 1888 | pParse->hasNonstd = 1; |
| 1889 | if( z[i]=='-' ){ |
| 1890 | jsonBlobAppendNode(pParse, JSONB_FLOAT, 6, "-9e999"); |
| 1891 | }else{ |
| 1892 | jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999"); |
| 1893 | } |
| 1894 | return i + (sqlite3StrNICmp(&z[i+4],"inity",5)==0 ? 9 : 4); |
| 1895 | } |
| 1896 | if( z[i+1]=='.' ){ |
| 1897 | pParse->hasNonstd = 1; |
| 1898 | t |= 0x01; |
| 1899 | goto parse_number_2; |
| 1900 | } |
| 1901 | #if 0 |
| 1902 | /* Full JSON5 compliance requires support for +NaN and -NaN, even |
| 1903 | ** though the extra prefix is not used for anything. Enable this |
| 1904 | ** block of code to get SQLite to do the same thing. It never |
| 1905 | ** has in an official release, and the only accomplishment of |
| 1906 | ** enabling it would be to take up a few bytes more code space. */ |
| 1907 | if( sqlite3StrNICmp(&z[i+1],"NaN",3)==0 ){ |
| 1908 | pParse->hasNonstd = 1; |
| 1909 | jsonBlobAppendOneByte(pParse, JSONB_NULL); |
| 1910 | return i+4; |
| 1911 | } |
| 1912 | #endif |
| 1913 | pParse->iErr = i; |
| 1914 | return -1; |
| 1915 | } |
| 1916 | if( z[i+1]=='0' ){ |
| 1917 | if( sqlite3Isdigit(z[i+2]) ){ |
| 1918 | pParse->iErr = i+1; |
| 1919 | return -1; |
| 1920 | }else if( (z[i+2]=='x' || z[i+2]=='X') && sqlite3Isxdigit(z[i+3]) ){ |
| 1921 | pParse->hasNonstd = 1; |
| 1922 | t |= 0x01; |
| 1923 | for(j=i+4; sqlite3Isxdigit(z[j]); j++){} |
| 1924 | goto parse_number_finish; |
| 1925 | } |
| 1926 | } |
| 1927 | } |
| 1928 | } |
| 1929 | |
| 1930 | parse_number_2: |
| 1931 | for(j=i+1;; j++){ |
| 1932 | c = z[j]; |
| 1933 | if( sqlite3Isdigit(c) ) continue; |
| 1934 | if( c=='.' ){ |
| 1935 | if( (t & 0x02)!=0 ){ |
| 1936 | pParse->iErr = j; |
| 1937 | return -1; |
| 1938 | } |
| 1939 | t |= 0x02; |
| 1940 | continue; |
| 1941 | } |
| 1942 | if( c=='e' || c=='E' ){ |
| 1943 | if( z[j-1]<'0' ){ |
| 1944 | if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){ |
| 1945 | pParse->hasNonstd = 1; |
| 1946 | t |= 0x01; |
| 1947 | }else{ |
| 1948 | pParse->iErr = j; |
| 1949 | return -1; |
| 1950 | } |
| 1951 | } |
| 1952 | if( seenE ){ |
| 1953 | pParse->iErr = j; |
| 1954 | return -1; |
| 1955 | } |
| 1956 | t |= 0x02; |
| 1957 | seenE = 1; |
| 1958 | c = z[j+1]; |
| 1959 | if( c=='+' || c=='-' ){ |
| 1960 | j++; |
| 1961 | c = z[j+1]; |
| 1962 | } |
| 1963 | if( c<'0' || c>'9' ){ |
| 1964 | pParse->iErr = j; |
| 1965 | return -1; |
| 1966 | } |
| 1967 | continue; |
| 1968 | } |
| 1969 | break; |
| 1970 | } |
| 1971 | if( z[j-1]<'0' ){ |
| 1972 | if( ALWAYS(z[j-1]=='.') && ALWAYS(j-2>=i) && sqlite3Isdigit(z[j-2]) ){ |
| 1973 | pParse->hasNonstd = 1; |
| 1974 | t |= 0x01; |
| 1975 | }else{ |
| 1976 | pParse->iErr = j; |
| 1977 | return -1; |
| 1978 | } |
| 1979 | } |
| 1980 | parse_number_finish: |
| 1981 | assert( JSONB_INT+0x01==JSONB_INT5 ); |
| 1982 | assert( JSONB_FLOAT+0x01==JSONB_FLOAT5 ); |
| 1983 | assert( JSONB_INT+0x02==JSONB_FLOAT ); |
| 1984 | if( z[i]=='+' ) i++; |
| 1985 | jsonBlobAppendNode(pParse, JSONB_INT+t, j-i, &z[i]); |
| 1986 | return j; |
| 1987 | } |
| 1988 | case '}': { |
| 1989 | pParse->iErr = i; |
| 1990 | return -2; /* End of {...} */ |
| 1991 | } |
| 1992 | case ']': { |
| 1993 | pParse->iErr = i; |
| 1994 | return -3; /* End of [...] */ |
| 1995 | } |
| 1996 | case ',': { |
| 1997 | pParse->iErr = i; |
| 1998 | return -4; /* List separator */ |
| 1999 | } |
| 2000 | case ':': { |
| 2001 | pParse->iErr = i; |
| 2002 | return -5; /* Object label/value separator */ |
| 2003 | } |
| 2004 | case 0: { |
| 2005 | return 0; /* End of file */ |
| 2006 | } |
| 2007 | case 0x09: |
| 2008 | case 0x0a: |
| 2009 | case 0x0d: |
| 2010 | case 0x20: { |
| 2011 | i += 1 + (u32)strspn(&z[i+1], jsonSpaces); |
| 2012 | goto json_parse_restart; |
| 2013 | } |
| 2014 | case 0x0b: |
| 2015 | case 0x0c: |
| 2016 | case '/': |
| 2017 | case 0xc2: |
| 2018 | case 0xe1: |
| 2019 | case 0xe2: |
| 2020 | case 0xe3: |
| 2021 | case 0xef: { |
| 2022 | j = json5Whitespace(&z[i]); |
| 2023 | if( j>0 ){ |
| 2024 | i += j; |
| 2025 | pParse->hasNonstd = 1; |
| 2026 | goto json_parse_restart; |
| 2027 | } |
| 2028 | pParse->iErr = i; |
| 2029 | return -1; |
| 2030 | } |
| 2031 | case 'n': { |
| 2032 | if( strncmp(z+i,"null",4)==0 && !sqlite3Isalnum(z[i+4]) ){ |
| 2033 | jsonBlobAppendOneByte(pParse, JSONB_NULL); |
| 2034 | return i+4; |
| 2035 | } |
| 2036 | /* fall-through into the default case that checks for NaN */ |
| 2037 | /* no break */ deliberate_fall_through |
| 2038 | } |
| 2039 | default: { |
| 2040 | u32 k; |
| 2041 | int nn; |
| 2042 | c = z[i]; |
| 2043 | for(k=0; k<sizeof(aNanInfName)/sizeof(aNanInfName[0]); k++){ |
| 2044 | if( c!=aNanInfName[k].c1 && c!=aNanInfName[k].c2 ) continue; |
| 2045 | nn = aNanInfName[k].n; |
| 2046 | if( sqlite3StrNICmp(&z[i], aNanInfName[k].zMatch, nn)!=0 ){ |
| 2047 | continue; |
| 2048 | } |
| 2049 | if( sqlite3Isalnum(z[i+nn]) ) continue; |
| 2050 | if( aNanInfName[k].eType==JSONB_FLOAT ){ |
| 2051 | jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999"); |
| 2052 | }else{ |
| 2053 | jsonBlobAppendOneByte(pParse, JSONB_NULL); |
| 2054 | } |
| 2055 | pParse->hasNonstd = 1; |
| 2056 | return i + nn; |
| 2057 | } |
| 2058 | pParse->iErr = i; |
| 2059 | return -1; /* Syntax error */ |
| 2060 | } |
| 2061 | } /* End switch(z[i]) */ |
| 2062 | } |
| 2063 | |
| 2064 | |
| 2065 | /* |
| 2066 | ** Parse a complete JSON string. Return 0 on success or non-zero if there |
| 2067 | ** are any errors. If an error occurs, free all memory held by pParse, |
| 2068 | ** but not pParse itself. |
| 2069 | ** |
| 2070 | ** pParse must be initialized to an empty parse object prior to calling |
| 2071 | ** this routine. |
| 2072 | */ |
| 2073 | static int jsonConvertTextToBlob( |
| 2074 | JsonParse *pParse, /* Initialize and fill this JsonParse object */ |
| 2075 | sqlite3_context *pCtx /* Report errors here */ |
| 2076 | ){ |
| 2077 | int i; |
| 2078 | const char *zJson = pParse->zJson; |
| 2079 | i = jsonTranslateTextToBlob(pParse, 0); |
| 2080 | if( pParse->oom ) i = -1; |
| 2081 | if( i>0 ){ |
| 2082 | #ifdef SQLITE_DEBUG |
| 2083 | assert( pParse->iDepth==0 ); |
| 2084 | if( sqlite3Config.bJsonSelfcheck ){ |
| 2085 | assert( jsonbValidityCheck(pParse, 0, pParse->nBlob, 0)==0 ); |
| 2086 | } |
| 2087 | #endif |
| 2088 | while( jsonIsspace(zJson[i]) ) i++; |
| 2089 | if( zJson[i] ){ |
| 2090 | i += json5Whitespace(&zJson[i]); |
| 2091 | if( zJson[i] ){ |
| 2092 | if( pCtx ) sqlite3_result_error(pCtx, "malformed JSON", -1); |
| 2093 | jsonParseReset(pParse); |
| 2094 | return 1; |
| 2095 | } |
| 2096 | pParse->hasNonstd = 1; |
| 2097 | } |
| 2098 | } |
| 2099 | if( i<=0 ){ |
| 2100 | if( pCtx!=0 ){ |
| 2101 | if( pParse->oom ){ |
| 2102 | sqlite3_result_error_nomem(pCtx); |
| 2103 | }else{ |
| 2104 | sqlite3_result_error(pCtx, "malformed JSON", -1); |
| 2105 | } |
| 2106 | } |
| 2107 | jsonParseReset(pParse); |
| 2108 | return 1; |
| 2109 | } |
| 2110 | return 0; |
| 2111 | } |
| 2112 | |
| 2113 | /* |
| 2114 | ** The input string pStr is a well-formed JSON text string. Convert |
| 2115 | ** this into the JSONB format and make it the return value of the |
| 2116 | ** SQL function. |
| 2117 | */ |
| 2118 | static void jsonReturnStringAsBlob(JsonString *pStr){ |
| 2119 | JsonParse px; |
| 2120 | assert( pStr->eErr==0 ); |
| 2121 | memset(&px, 0, sizeof(px)); |
| 2122 | px.zJson = pStr->zBuf; |
| 2123 | px.nJson = pStr->nUsed; |
| 2124 | px.db = sqlite3_context_db_handle(pStr->pCtx); |
| 2125 | (void)jsonTranslateTextToBlob(&px, 0); |
| 2126 | if( px.oom ){ |
| 2127 | sqlite3DbFree(px.db, px.aBlob); |
| 2128 | sqlite3_result_error_nomem(pStr->pCtx); |
| 2129 | }else{ |
| 2130 | assert( px.nBlobAlloc>0 ); |
| 2131 | assert( !px.bReadOnly ); |
| 2132 | sqlite3_result_blob(pStr->pCtx, px.aBlob, px.nBlob, SQLITE_DYNAMIC); |
| 2133 | } |
| 2134 | } |
| 2135 | |
| 2136 | /* |
| 2137 | ** This a helper routine for jsonbPayloadSize() and |
| 2138 | ** jsonbPayloadSizeSemiInline(). This routine is called using tail |
| 2139 | ** recursion to handle the (relatively uncommon) cases where the |
| 2140 | ** the payload size is a 2, 4, or 8 byte integer. |
| 2141 | */ |
| 2142 | static u32 jsonbPayloadSizeWide( |
| 2143 | const JsonParse *pParse, /* JSON parsing context */ |
| 2144 | u32 i, /* Index of the node type-code */ |
| 2145 | u32 *pSz, /* Write payload size here */ |
| 2146 | u8 x /* pParse->aBlob[i]>>4 */ |
| 2147 | ){ |
| 2148 | u32 sz; |
| 2149 | u32 n; |
| 2150 | assert( i<pParse->nBlob ); |
| 2151 | assert( x==(pParse->aBlob[i]>>4) ); |
| 2152 | assert( x>=13 ); |
| 2153 | if( x==13 ){ |
| 2154 | if( i+2>=pParse->nBlob ){ |
| 2155 | *pSz = 0; |
| 2156 | return 0; |
| 2157 | } |
| 2158 | sz = (pParse->aBlob[i+1]<<8) + pParse->aBlob[i+2]; |
| 2159 | n = 3; |
| 2160 | }else if( x==14 ){ |
| 2161 | if( i+4>=pParse->nBlob ){ |
| 2162 | *pSz = 0; |
| 2163 | return 0; |
| 2164 | } |
| 2165 | sz = ((u32)pParse->aBlob[i+1]<<24) + (pParse->aBlob[i+2]<<16) + |
| 2166 | (pParse->aBlob[i+3]<<8) + pParse->aBlob[i+4]; |
| 2167 | n = 5; |
| 2168 | }else{ |
| 2169 | if( i+8>=pParse->nBlob |
| 2170 | || pParse->aBlob[i+1]!=0 |
| 2171 | || pParse->aBlob[i+2]!=0 |
| 2172 | || pParse->aBlob[i+3]!=0 |
| 2173 | || pParse->aBlob[i+4]!=0 |
| 2174 | ){ |
| 2175 | *pSz = 0; |
| 2176 | return 0; |
| 2177 | } |
| 2178 | sz = ((u32)pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) + |
| 2179 | (pParse->aBlob[i+7]<<8) + pParse->aBlob[i+8]; |
| 2180 | n = 9; |
| 2181 | } |
| 2182 | testcase( (i64)i+sz+n > pParse->nBlob ); |
| 2183 | testcase( (i64)i+sz+n > pParse->nBlob-pParse->delta |
| 2184 | && (i64)i+sz+n > pParse->nBlob ); |
| 2185 | testcase( pParse->delta>0 ); |
| 2186 | testcase( pParse->delta<0 ); |
| 2187 | /* Quirks with -Os and gcov cause the NO_TEST line below to show up as |
| 2188 | ** false-positive coverage miss. The testcases() macros above are |
| 2189 | ** sufficient to prove that the branch is in fact covered */ |
| 2190 | if( (i64)i+sz+n > pParse->nBlob |
| 2191 | && (i64)i+sz+n > pParse->nBlob-pParse->delta /*NO_TEST*/ |
| 2192 | ){ |
| 2193 | *pSz = 0; |
| 2194 | return 0; |
| 2195 | } |
| 2196 | *pSz = sz; |
| 2197 | return n; |
| 2198 | } |
| 2199 | |
| 2200 | /* |
| 2201 | ** This is the main routine for determining the size of a node in JSONB. |
| 2202 | ** The jsonbPayloadSizeWide() above is a helper. The two routines |
| 2203 | ** jsonbPayloadSizeInline() and jsonbPayloadSizeSemiInline() below are |
| 2204 | ** optional optimizations. It is important to keep all these routines in |
| 2205 | ** sync. Agents reading this code: Help us humans to remember that! |
| 2206 | ** |
| 2207 | ** The byte at index i is a node type-code. This routine |
| 2208 | ** determines the payload size for that node and writes that |
| 2209 | ** payload size in to *pSz. It returns the offset from i to the |
| 2210 | ** beginning of the payload. Return 0 on error. |
| 2211 | */ |
| 2212 | static u32 jsonbPayloadSize( |
| 2213 | const JsonParse *pParse, /* JSON parsing context */ |
| 2214 | u32 i, /* Index of the node type-code */ |
| 2215 | u32 *pSz /* Write payload size here */ |
| 2216 | ){ |
| 2217 | u8 x; |
| 2218 | u32 sz; |
| 2219 | u32 n; |
| 2220 | if( i>=pParse->nBlob ){ |
| 2221 | *pSz = 0; |
| 2222 | return 0; |
| 2223 | }else if( (x = pParse->aBlob[i]>>4)<=11 ){ |
| 2224 | sz = x; |
| 2225 | n = 1; |
| 2226 | }else if( x==12 ){ |
| 2227 | if( i+1>=pParse->nBlob ){ |
| 2228 | *pSz = 0; |
| 2229 | return 0; |
| 2230 | } |
| 2231 | sz = pParse->aBlob[i+1]; |
| 2232 | n = 2; |
| 2233 | }else{ |
| 2234 | return jsonbPayloadSizeWide(pParse, i, pSz, x); |
| 2235 | } |
| 2236 | if( (i64)i+sz+n > pParse->nBlob |
| 2237 | && (i64)i+sz+n > pParse->nBlob-pParse->delta |
| 2238 | ){ |
| 2239 | *pSz = 0; |
| 2240 | return 0; |
| 2241 | } |
| 2242 | *pSz = sz; |
| 2243 | return n; |
| 2244 | } |
| 2245 | |
| 2246 | #if SQLITE_USES_INLINE |
| 2247 | /* A separate inline version of jsonbPayloadSize(), used in one particulary |
| 2248 | ** performance-critical place. |
| 2249 | */ |
| 2250 | static SQLITE_INLINE u32 jsonbPayloadSizeInline( |
| 2251 | const JsonParse *pParse, /* JSON parsing context */ |
| 2252 | u32 i, /* Index of the node type-code */ |
| 2253 | u32 *pSz /* Write payload size here */ |
| 2254 | ){ |
| 2255 | u8 x; |
| 2256 | u32 sz; |
| 2257 | u32 n; |
| 2258 | if( i>=pParse->nBlob ){ |
| 2259 | *pSz = 0; |
| 2260 | return 0; |
| 2261 | }else if( (x = pParse->aBlob[i]>>4)<=11 ){ |
| 2262 | sz = x; |
| 2263 | n = 1; |
| 2264 | }else if( x==12 ){ |
| 2265 | if( i+1>=pParse->nBlob ){ |
| 2266 | *pSz = 0; |
| 2267 | return 0; |
| 2268 | } |
| 2269 | sz = pParse->aBlob[i+1]; |
| 2270 | n = 2; |
| 2271 | }else if( x==13 ){ |
| 2272 | if( i+2>=pParse->nBlob ){ |
| 2273 | *pSz = 0; |
| 2274 | return 0; |
| 2275 | } |
| 2276 | sz = (pParse->aBlob[i+1]<<8) + pParse->aBlob[i+2]; |
| 2277 | n = 3; |
| 2278 | }else if( x==14 ){ |
| 2279 | if( i+4>=pParse->nBlob ){ |
| 2280 | *pSz = 0; |
| 2281 | return 0; |
| 2282 | } |
| 2283 | sz = ((u32)pParse->aBlob[i+1]<<24) + (pParse->aBlob[i+2]<<16) + |
| 2284 | (pParse->aBlob[i+3]<<8) + pParse->aBlob[i+4]; |
| 2285 | n = 5; |
| 2286 | }else{ |
| 2287 | if( i+8>=pParse->nBlob |
| 2288 | || pParse->aBlob[i+1]!=0 |
| 2289 | || pParse->aBlob[i+2]!=0 |
| 2290 | || pParse->aBlob[i+3]!=0 |
| 2291 | || pParse->aBlob[i+4]!=0 |
| 2292 | ){ |
| 2293 | *pSz = 0; |
| 2294 | return 0; |
| 2295 | } |
| 2296 | sz = ((u32)pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) + |
| 2297 | (pParse->aBlob[i+7]<<8) + pParse->aBlob[i+8]; |
| 2298 | n = 9; |
| 2299 | } |
| 2300 | if( (i64)i+sz+n > pParse->nBlob |
| 2301 | && (i64)i+sz+n > pParse->nBlob-pParse->delta |
| 2302 | ){ |
| 2303 | *pSz = 0; |
| 2304 | return 0; |
| 2305 | } |
| 2306 | *pSz = sz; |
| 2307 | return n; |
| 2308 | } |
| 2309 | #else /* if !SQLITE_USES_INLINE */ |
| 2310 | /* On compilers that do not support in-lining, just call the original |
| 2311 | ** jsonbPayloadSize(). It's slower, but it gets the right answer. */ |
| 2312 | # define jsonbPayloadSizeInline(a,b,c) jsonbPayloadSize(a,b,c) |
| 2313 | #endif |
| 2314 | |
| 2315 | |
| 2316 | #if SQLITE_USES_INLINE |
| 2317 | /* A separate inline version of jsonbPayloadSize() that implements the more |
| 2318 | ** common paths inline but then calls out to a subroutine for the uncommon |
| 2319 | ** paths. |
| 2320 | ** |
| 2321 | ** * It is guaranteed that the i parameter is a valid index for |
| 2322 | ** pParse->aBlob[]. There is no possibility of running of the end |
| 2323 | ** of the allocation. |
| 2324 | ** |
| 2325 | ** * Large sizes (greater than 255) are uncommon and are handled |
| 2326 | ** by a subroutine call to the jsonbPayloadSizeWide(). |
| 2327 | */ |
| 2328 | static SQLITE_INLINE u32 jsonbPayloadSizeSemiInline( |
| 2329 | const JsonParse *pParse, /* JSON parsing context */ |
| 2330 | u32 i, /* Index of the node type-code */ |
| 2331 | u32 *pSz /* Write payload size here */ |
| 2332 | ){ |
| 2333 | u8 x; |
| 2334 | u32 sz; |
| 2335 | u32 n; |
| 2336 | assert( i<pParse->nBlob ); |
| 2337 | if( (x = pParse->aBlob[i]>>4)<=11 ){ |
| 2338 | sz = x; |
| 2339 | n = 1; |
| 2340 | }else if( x==12 ){ |
| 2341 | if( i+1>=pParse->nBlob ){ |
| 2342 | *pSz = 0; |
| 2343 | return 0; |
| 2344 | } |
| 2345 | sz = pParse->aBlob[i+1]; |
| 2346 | n = 2; |
| 2347 | }else{ |
| 2348 | return jsonbPayloadSizeWide(pParse,i,pSz,x); |
| 2349 | } |
| 2350 | if( (i64)i+sz+n > pParse->nBlob |
| 2351 | && (i64)i+sz+n > pParse->nBlob-pParse->delta |
| 2352 | ){ |
| 2353 | *pSz = 0; |
| 2354 | return 0; |
| 2355 | } |
| 2356 | *pSz = sz; |
| 2357 | return n; |
| 2358 | } |
| 2359 | #else /* if !SQLITE_USES_INLINE */ |
| 2360 | /* On compilers that do not support in-lining, just call the original |
| 2361 | ** jsonbPayloadSize(). It's slower, but it gets the right answer. */ |
| 2362 | # define jsonbPayloadSizeSemiInline(a,b,c) jsonbPayloadSize(a,b,c) |
| 2363 | #endif |
| 2364 | |
| 2365 | /* |
| 2366 | ** Convert a JSONB integer literal into either an integer (if it is small |
| 2367 | ** enough) or into a double. Include the sign. Return: |
| 2368 | ** |
| 2369 | ** 0 Value is an integer, results written into *pI. |
| 2370 | ** 1 Value is a double, results written into *pR. |
| 2371 | ** 2 Syntax error |
| 2372 | */ |
| 2373 | static int jsonConvertInteger(const char *zIn, u32 sz, i64 *pI, double *pR){ |
| 2374 | u32 k = 0; |
| 2375 | int bNeg = 0; |
| 2376 | sqlite3_uint64 u = 0; |
| 2377 | double rOverflow = 1.0; |
| 2378 | if( sz==0 ) return 2; |
| 2379 | if( zIn[0]=='-' ){ |
| 2380 | bNeg = 1; |
| 2381 | k = 1; |
| 2382 | }else if( zIn[0]=='+' ){ |
| 2383 | k = 1; |
| 2384 | } |
| 2385 | if( k+2<sz && zIn[k]=='0' && (zIn[k+1]=='x' || zIn[k+1]=='X') ){ |
| 2386 | k += 2; |
| 2387 | do{ |
| 2388 | if( !sqlite3Isxdigit(zIn[k]) ){ |
| 2389 | return 2; |
| 2390 | }else if( (u>>60)!=0 ){ |
| 2391 | rOverflow *= 16.0; |
| 2392 | }else{ |
| 2393 | u = u*16 + sqlite3HexToInt(zIn[k]); |
| 2394 | } |
| 2395 | k++; |
| 2396 | }while( k<sz ); |
| 2397 | }else if( k>=sz ){ |
| 2398 | return 2; |
| 2399 | }else{ |
| 2400 | do{ |
| 2401 | if( zIn[k]<'0' || zIn[k]>'9' ){ |
| 2402 | return 2; |
| 2403 | }else if( (u>>60)!=0 ){ |
| 2404 | rOverflow *= 10.0; |
| 2405 | }else{ |
| 2406 | u = u*10 + zIn[k] - '0'; |
| 2407 | } |
| 2408 | k++; |
| 2409 | }while( k<sz ); |
| 2410 | } |
| 2411 | if( rOverflow>1.0 |
| 2412 | || (u>0x7fffffffffffffffULL && (!bNeg || u>0x8000000000000000ULL)) |
| 2413 | ){ |
| 2414 | *pR = rOverflow * (double)u; |
| 2415 | if( bNeg ) *pR = -*pR; |
| 2416 | return 1; |
| 2417 | }else{ |
| 2418 | memcpy(pI, &u, sizeof(u)); |
| 2419 | if( bNeg && u!=0x8000000000000000ULL ) *pI = -*pI; |
| 2420 | return 0; |
| 2421 | } |
| 2422 | } |
| 2423 | |
| 2424 | /* |
| 2425 | ** Tail recursive code to implement the JSON_INT5 case of of |
| 2426 | ** jsonTranslateBlobInt5ToText(). This is split out because |
| 2427 | ** the resulting reduction in the stack frame size helps the |
| 2428 | ** caller to run faster. |
| 2429 | */ |
| 2430 | static SQLITE_NOINLINE u32 jsonTranslateBlobInt5ToText( |
| 2431 | JsonParse *pParse, /* the complete parse of the JSON */ |
| 2432 | u32 i, /* Start rendering at this index */ |
| 2433 | JsonString *pOut, /* Write JSON here */ |
| 2434 | u32 sz, /* Payload size */ |
| 2435 | u32 n /* Header size */ |
| 2436 | ){ |
| 2437 | int k; |
| 2438 | const char *zIn = (const char*)&pParse->aBlob[i+n]; |
| 2439 | i64 ival; |
| 2440 | double rval; |
| 2441 | k = jsonConvertInteger(zIn, sz, &ival, &rval); |
| 2442 | if( k==0 ){ |
| 2443 | jsonPrintf(100, pOut, "%lld", ival); |
| 2444 | }else if( k==1 ){ |
| 2445 | jsonPrintf(100, pOut, "%!0.17g", rval); |
| 2446 | }else{ |
| 2447 | pOut->eErr |= JSTRING_MALFORMED; |
| 2448 | } |
| 2449 | return i+n+sz; |
| 2450 | } |
| 2451 | |
| 2452 | |
| 2453 | /* |
| 2454 | ** Translate the binary JSONB representation of JSON beginning at |
| 2455 | ** pParse->aBlob[i] into a JSON text string. Append the JSON |
| 2456 | ** text onto the end of pOut. Return the index in pParse->aBlob[] |
| 2457 | ** of the first byte past the end of the element that is translated. |
| 2458 | ** |
| 2459 | ** If an error is detected in the BLOB input, the pOut->eErr flag |
| 2460 | ** might get set to JSTRING_MALFORMED. But not all BLOB input errors |
| 2461 | ** are detected. So a malformed JSONB input might either result |
| 2462 | ** in an error, or in incorrect JSON. |
| 2463 | ** |
| 2464 | ** The pOut->eErr JSTRING_OOM flag is set on a OOM. |
| 2465 | */ |
| 2466 | static u32 jsonTranslateBlobToText( |
| 2467 | JsonParse *pParse, /* the complete parse of the JSON */ |
| 2468 | u32 i, /* Start rendering at this index */ |
| 2469 | JsonString *pOut /* Write JSON here */ |
| 2470 | ){ |
| 2471 | u32 sz, n, j, iEnd; |
| 2472 | |
| 2473 | n = jsonbPayloadSizeInline(pParse, i, &sz); |
| 2474 | if( n==0 ){ |
| 2475 | pOut->eErr |= JSTRING_MALFORMED; |
| 2476 | return pParse->nBlob+1; |
| 2477 | } |
| 2478 | switch( pParse->aBlob[i] & 0x0f ){ |
| 2479 | case JSONB_NULL: { |
| 2480 | jsonAppendRawNZ(pOut, "null", 4); |
| 2481 | return i+1; |
| 2482 | } |
| 2483 | case JSONB_TRUE: { |
| 2484 | jsonAppendRawNZ(pOut, "true", 4); |
| 2485 | return i+1; |
| 2486 | } |
| 2487 | case JSONB_FALSE: { |
| 2488 | jsonAppendRawNZ(pOut, "false", 5); |
| 2489 | return i+1; |
| 2490 | } |
| 2491 | case JSONB_INT: |
| 2492 | case JSONB_FLOAT: { |
| 2493 | if( sz==0 ) goto malformed_jsonb; |
| 2494 | jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz); |
| 2495 | break; |
| 2496 | } |
| 2497 | case JSONB_INT5: { /* Integer literal in hexadecimal notation */ |
| 2498 | return jsonTranslateBlobInt5ToText(pParse, i, pOut, sz, n); |
| 2499 | } |
| 2500 | case JSONB_FLOAT5: { /* Float literal missing digits beside "." */ |
| 2501 | u32 k = 0; |
| 2502 | const char *zIn = (const char*)&pParse->aBlob[i+n]; |
| 2503 | if( sz==0 ) goto malformed_jsonb; |
| 2504 | if( zIn[0]=='-' ){ |
| 2505 | jsonAppendChar(pOut, '-'); |
| 2506 | if( sz<=1 ) goto malformed_jsonb; |
| 2507 | k = 1; |
| 2508 | } |
| 2509 | if( zIn[k]=='.' ){ |
| 2510 | jsonAppendChar(pOut, '0'); |
| 2511 | } |
| 2512 | for(; k<sz; k++){ |
| 2513 | jsonAppendChar(pOut, zIn[k]); |
| 2514 | if( zIn[k]=='.' && (k+1==sz || !sqlite3Isdigit(zIn[k+1])) ){ |
| 2515 | jsonAppendChar(pOut, '0'); |
| 2516 | } |
| 2517 | } |
| 2518 | break; |
| 2519 | } |
| 2520 | case JSONB_TEXT: |
| 2521 | case JSONB_TEXTJ: { |
| 2522 | if( pOut->nUsed+sz+2<=pOut->nAlloc || jsonStringGrow(pOut, sz+2)==0 ){ |
| 2523 | pOut->zBuf[pOut->nUsed] = '"'; |
| 2524 | memcpy(pOut->zBuf+pOut->nUsed+1,(const char*)&pParse->aBlob[i+n],sz); |
| 2525 | pOut->zBuf[pOut->nUsed+sz+1] = '"'; |
| 2526 | pOut->nUsed += sz+2; |
| 2527 | } |
| 2528 | break; |
| 2529 | } |
| 2530 | case JSONB_TEXT5: { |
| 2531 | const char *zIn; |
| 2532 | u32 k; |
| 2533 | u32 sz2 = sz; |
| 2534 | zIn = (const char*)&pParse->aBlob[i+n]; |
| 2535 | jsonAppendChar(pOut, '"'); |
| 2536 | while( sz2>0 ){ |
| 2537 | for(k=0; k<sz2 && (jsonIsOk[(u8)zIn[k]] || zIn[k]=='\''); k++){} |
| 2538 | if( k>0 ){ |
| 2539 | jsonAppendRawNZ(pOut, zIn, k); |
| 2540 | if( k>=sz2 ){ |
| 2541 | break; |
| 2542 | } |
| 2543 | zIn += k; |
| 2544 | sz2 -= k; |
| 2545 | } |
| 2546 | if( zIn[0]=='"' ){ |
| 2547 | jsonAppendRawNZ(pOut, "\\\"", 2); |
| 2548 | zIn++; |
| 2549 | sz2--; |
| 2550 | continue; |
| 2551 | } |
| 2552 | if( zIn[0]<=0x1f ){ |
| 2553 | if( pOut->nUsed+7>pOut->nAlloc && jsonStringGrow(pOut,7) ) break; |
| 2554 | jsonAppendControlChar(pOut, zIn[0]); |
| 2555 | zIn++; |
| 2556 | sz2--; |
| 2557 | continue; |
| 2558 | } |
| 2559 | assert( zIn[0]=='\\' ); |
| 2560 | assert( sz2>=1 ); |
| 2561 | if( sz2<2 ){ |
| 2562 | pOut->eErr |= JSTRING_MALFORMED; |
| 2563 | break; |
| 2564 | } |
| 2565 | switch( (u8)zIn[1] ){ |
| 2566 | case '\'': |
| 2567 | jsonAppendChar(pOut, '\''); |
| 2568 | break; |
| 2569 | case 'v': |
| 2570 | jsonAppendRawNZ(pOut, "\\u000b", 6); |
| 2571 | break; |
| 2572 | case 'x': |
| 2573 | if( sz2<4 ){ |
| 2574 | pOut->eErr |= JSTRING_MALFORMED; |
| 2575 | sz2 = 2; |
| 2576 | break; |
| 2577 | } |
| 2578 | jsonAppendRawNZ(pOut, "\\u00", 4); |
| 2579 | jsonAppendRawNZ(pOut, &zIn[2], 2); |
| 2580 | zIn += 2; |
| 2581 | sz2 -= 2; |
| 2582 | break; |
| 2583 | case '0': |
| 2584 | jsonAppendRawNZ(pOut, "\\u0000", 6); |
| 2585 | break; |
| 2586 | case '\r': |
| 2587 | if( sz2>2 && zIn[2]=='\n' ){ |
| 2588 | zIn++; |
| 2589 | sz2--; |
| 2590 | } |
| 2591 | break; |
| 2592 | case '\n': |
| 2593 | break; |
| 2594 | case 0xe2: |
| 2595 | /* '\' followed by either U+2028 or U+2029 is ignored as |
| 2596 | ** whitespace. Note that in UTF8, U+2028 is 0xe2 0x80 0x29. |
| 2597 | ** U+2029 is the same except for the last byte */ |
| 2598 | if( sz2<4 |
| 2599 | || 0x80!=(u8)zIn[2] |
| 2600 | || (0xa8!=(u8)zIn[3] && 0xa9!=(u8)zIn[3]) |
| 2601 | ){ |
| 2602 | pOut->eErr |= JSTRING_MALFORMED; |
| 2603 | sz2 = 2; |
| 2604 | break; |
| 2605 | } |
| 2606 | zIn += 2; |
| 2607 | sz2 -= 2; |
| 2608 | break; |
| 2609 | default: |
| 2610 | jsonAppendRawNZ(pOut, zIn, 2); |
| 2611 | break; |
| 2612 | } |
| 2613 | assert( sz2>=2 ); |
| 2614 | zIn += 2; |
| 2615 | sz2 -= 2; |
| 2616 | } |
| 2617 | jsonAppendChar(pOut, '"'); |
| 2618 | break; |
| 2619 | } |
| 2620 | case JSONB_TEXTRAW: { |
| 2621 | jsonAppendString(pOut, (const char*)&pParse->aBlob[i+n], sz); |
| 2622 | break; |
| 2623 | } |
| 2624 | case JSONB_ARRAY: { |
| 2625 | jsonAppendChar(pOut, '['); |
| 2626 | j = i+n; |
| 2627 | iEnd = j+sz; |
| 2628 | if( ++pParse->iDepth > JSON_MAX_DEPTH ){ |
| 2629 | jsonStringTooDeep(pOut); |
| 2630 | } |
| 2631 | while( j<iEnd && pOut->eErr==0 ){ |
| 2632 | j = jsonTranslateBlobToText(pParse, j, pOut); |
| 2633 | jsonAppendChar(pOut, ','); |
| 2634 | } |
| 2635 | pParse->iDepth--; |
| 2636 | if( j>iEnd ) pOut->eErr |= JSTRING_MALFORMED; |
| 2637 | if( sz>0 ) jsonStringTrimOneChar(pOut); |
| 2638 | jsonAppendChar(pOut, ']'); |
| 2639 | break; |
| 2640 | } |
| 2641 | case JSONB_OBJECT: { |
| 2642 | int x = 0; |
| 2643 | jsonAppendChar(pOut, '{'); |
| 2644 | j = i+n; |
| 2645 | iEnd = j+sz; |
| 2646 | if( ++pParse->iDepth > JSON_MAX_DEPTH ){ |
| 2647 | jsonStringTooDeep(pOut); |
| 2648 | } |
| 2649 | while( j<iEnd && pOut->eErr==0 ){ |
| 2650 | j = jsonTranslateBlobToText(pParse, j, pOut); |
| 2651 | jsonAppendChar(pOut, (x++ & 1) ? ',' : ':'); |
| 2652 | } |
| 2653 | pParse->iDepth--; |
| 2654 | if( (x & 1)!=0 || j>iEnd ) pOut->eErr |= JSTRING_MALFORMED; |
| 2655 | if( sz>0 ) jsonStringTrimOneChar(pOut); |
| 2656 | jsonAppendChar(pOut, '}'); |
| 2657 | break; |
| 2658 | } |
| 2659 | |
| 2660 | default: { |
| 2661 | malformed_jsonb: |
| 2662 | pOut->eErr |= JSTRING_MALFORMED; |
| 2663 | break; |
| 2664 | } |
| 2665 | } |
| 2666 | return i+n+sz; |
| 2667 | } |
| 2668 | |
| 2669 | /* Context for recursion of json_pretty() |
| 2670 | */ |
| 2671 | typedef struct JsonPretty JsonPretty; |
| 2672 | struct JsonPretty { |
| 2673 | JsonParse *pParse; /* The BLOB being rendered */ |
| 2674 | JsonString *pOut; /* Generate pretty output into this string */ |
| 2675 | const char *zIndent; /* Use this text for indentation */ |
| 2676 | u32 szIndent; /* Bytes in zIndent[] */ |
| 2677 | u32 nIndent; /* Current level of indentation */ |
| 2678 | }; |
| 2679 | |
| 2680 | /* Append indentation to the pretty JSON under construction */ |
| 2681 | static void jsonPrettyIndent(JsonPretty *pPretty){ |
| 2682 | u32 jj; |
| 2683 | for(jj=0; jj<pPretty->nIndent; jj++){ |
| 2684 | jsonAppendRaw(pPretty->pOut, pPretty->zIndent, pPretty->szIndent); |
| 2685 | } |
| 2686 | } |
| 2687 | |
| 2688 | /* |
| 2689 | ** Translate the binary JSONB representation of JSON beginning at |
| 2690 | ** pParse->aBlob[i] into a JSON text string. Append the JSON |
| 2691 | ** text onto the end of pOut. Return the index in pParse->aBlob[] |
| 2692 | ** of the first byte past the end of the element that is translated. |
| 2693 | ** |
| 2694 | ** This is a variant of jsonTranslateBlobToText() that "pretty-prints" |
| 2695 | ** the output. Extra whitespace is inserted to make the JSON easier |
| 2696 | ** for humans to read. |
| 2697 | ** |
| 2698 | ** If an error is detected in the BLOB input, the pOut->eErr flag |
| 2699 | ** might get set to JSTRING_MALFORMED. But not all BLOB input errors |
| 2700 | ** are detected. So a malformed JSONB input might either result |
| 2701 | ** in an error, or in incorrect JSON. |
| 2702 | ** |
| 2703 | ** The pOut->eErr JSTRING_OOM flag is set on a OOM. |
| 2704 | */ |
| 2705 | static u32 jsonTranslateBlobToPrettyText( |
| 2706 | JsonPretty *pPretty, /* Pretty-printing context */ |
| 2707 | u32 i /* Start rendering at this index */ |
| 2708 | ){ |
| 2709 | u32 sz, n, j, iEnd; |
| 2710 | JsonParse *pParse = pPretty->pParse; |
| 2711 | JsonString *pOut = pPretty->pOut; |
| 2712 | n = jsonbPayloadSize(pParse, i, &sz); |
| 2713 | if( n==0 ){ |
| 2714 | pOut->eErr |= JSTRING_MALFORMED; |
| 2715 | return pParse->nBlob+1; |
| 2716 | } |
| 2717 | switch( pParse->aBlob[i] & 0x0f ){ |
| 2718 | case JSONB_ARRAY: { |
| 2719 | j = i+n; |
| 2720 | iEnd = j+sz; |
| 2721 | jsonAppendChar(pOut, '['); |
| 2722 | if( j<iEnd ){ |
| 2723 | jsonAppendChar(pOut, '\n'); |
| 2724 | pPretty->nIndent++; |
| 2725 | if( pPretty->nIndent >= JSON_MAX_DEPTH ){ |
| 2726 | jsonStringTooDeep(pOut); |
| 2727 | } |
| 2728 | while( pOut->eErr==0 ){ |
| 2729 | jsonPrettyIndent(pPretty); |
| 2730 | j = jsonTranslateBlobToPrettyText(pPretty, j); |
| 2731 | if( j>=iEnd ){ |
| 2732 | if( j>iEnd ) pOut->eErr |= JSTRING_MALFORMED; |
| 2733 | break; |
| 2734 | } |
| 2735 | jsonAppendRawNZ(pOut, ",\n", 2); |
| 2736 | } |
| 2737 | jsonAppendChar(pOut, '\n'); |
| 2738 | pPretty->nIndent--; |
| 2739 | jsonPrettyIndent(pPretty); |
| 2740 | } |
| 2741 | jsonAppendChar(pOut, ']'); |
| 2742 | i = iEnd; |
| 2743 | break; |
| 2744 | } |
| 2745 | case JSONB_OBJECT: { |
| 2746 | j = i+n; |
| 2747 | iEnd = j+sz; |
| 2748 | jsonAppendChar(pOut, '{'); |
| 2749 | if( j<iEnd ){ |
| 2750 | jsonAppendChar(pOut, '\n'); |
| 2751 | pPretty->nIndent++; |
| 2752 | if( pPretty->nIndent >= JSON_MAX_DEPTH ){ |
| 2753 | jsonStringTooDeep(pOut); |
| 2754 | } |
| 2755 | while( pOut->eErr==0 ){ |
| 2756 | jsonPrettyIndent(pPretty); |
| 2757 | j = jsonTranslateBlobToText(pParse, j, pOut); |
| 2758 | if( j>iEnd ){ |
| 2759 | pOut->eErr |= JSTRING_MALFORMED; |
| 2760 | break; |
| 2761 | } |
| 2762 | jsonAppendRawNZ(pOut, ": ", 2); |
| 2763 | j = jsonTranslateBlobToPrettyText(pPretty, j); |
| 2764 | if( j>=iEnd ) break; |
| 2765 | jsonAppendRawNZ(pOut, ",\n", 2); |
| 2766 | } |
| 2767 | jsonAppendChar(pOut, '\n'); |
| 2768 | pPretty->nIndent--; |
| 2769 | jsonPrettyIndent(pPretty); |
| 2770 | } |
| 2771 | jsonAppendChar(pOut, '}'); |
| 2772 | i = iEnd; |
| 2773 | break; |
| 2774 | } |
| 2775 | default: { |
| 2776 | i = jsonTranslateBlobToText(pParse, i, pOut); |
| 2777 | break; |
| 2778 | } |
| 2779 | } |
| 2780 | return i; |
| 2781 | } |
| 2782 | |
| 2783 | /* |
| 2784 | ** Given that a JSONB_ARRAY object starts at offset i, return |
| 2785 | ** the number of entries in that array. |
| 2786 | */ |
| 2787 | static u32 jsonbArrayCount(JsonParse *pParse, u32 iRoot){ |
| 2788 | u32 n, sz, i, iEnd; |
| 2789 | u32 k = 0; |
| 2790 | n = jsonbPayloadSize(pParse, iRoot, &sz); |
| 2791 | iEnd = iRoot+n+sz; |
| 2792 | for(i=iRoot+n; n>0 && i<iEnd; i+=sz+n, k++){ |
| 2793 | n = jsonbPayloadSizeSemiInline(pParse, i, &sz); |
| 2794 | } |
| 2795 | return k; |
| 2796 | } |
| 2797 | |
| 2798 | /* |
| 2799 | ** Edit the payload size of the element at iRoot by the amount in |
| 2800 | ** pParse->delta. |
| 2801 | */ |
| 2802 | static void jsonAfterEditSizeAdjust(JsonParse *pParse, u32 iRoot){ |
| 2803 | u32 sz = 0; |
| 2804 | u32 nBlob; |
| 2805 | assert( pParse->delta!=0 ); |
| 2806 | assert( pParse->nBlobAlloc >= pParse->nBlob ); |
| 2807 | nBlob = pParse->nBlob; |
| 2808 | pParse->nBlob = pParse->nBlobAlloc; |
| 2809 | (void)jsonbPayloadSize(pParse, iRoot, &sz); |
| 2810 | pParse->nBlob = nBlob; |
| 2811 | sz += pParse->delta; |
| 2812 | pParse->delta += jsonBlobChangePayloadSize(pParse, iRoot, sz); |
| 2813 | } |
| 2814 | |
| 2815 | /* |
| 2816 | ** If the JSONB at aIns[0..nIns-1] can be expanded (by denormalizing the |
| 2817 | ** size field) by d bytes, then write the expansion into aOut[] and |
| 2818 | ** return true. In this way, an overwrite happens without changing the |
| 2819 | ** size of the JSONB, which reduces memcpy() operations and also make it |
| 2820 | ** faster and easier to update the B-Tree entry that contains the JSONB |
| 2821 | ** in the database. |
| 2822 | ** |
| 2823 | ** If the expansion of aIns[] by d bytes cannot be (easily) accomplished |
| 2824 | ** then return false. |
| 2825 | ** |
| 2826 | ** The d parameter is guaranteed to be between 1 and 8. |
| 2827 | ** |
| 2828 | ** This routine is an optimization. A correct answer is obtained if it |
| 2829 | ** always leaves the output unchanged and returns false. |
| 2830 | */ |
| 2831 | static int jsonBlobOverwrite( |
| 2832 | u8 *aOut, /* Overwrite here */ |
| 2833 | const u8 *aIns, /* New content */ |
| 2834 | u32 nIns, /* Bytes of new content */ |
| 2835 | u32 d /* Need to expand new content by this much */ |
| 2836 | ){ |
| 2837 | u32 szPayload; /* Bytes of payload */ |
| 2838 | u32 i; /* New header size, after expansion & a loop counter */ |
| 2839 | u8 szHdr; /* Size of header before expansion */ |
| 2840 | |
| 2841 | /* Lookup table for finding the upper 4 bits of the first byte of the |
| 2842 | ** expanded aIns[], based on the size of the expanded aIns[] header: |
| 2843 | ** |
| 2844 | ** 2 3 4 5 6 7 8 9 */ |
| 2845 | static const u8 aType[] = { 0xc0, 0xd0, 0, 0xe0, 0, 0, 0, 0xf0 }; |
| 2846 | |
| 2847 | if( (aIns[0]&0x0f)<=2 ) return 0; /* Cannot enlarge NULL, true, false */ |
| 2848 | switch( aIns[0]>>4 ){ |
| 2849 | default: { /* aIns[] header size 1 */ |
| 2850 | if( ((1<<d)&0x116)==0 ) return 0; /* d must be 1, 2, 4, or 8 */ |
| 2851 | i = d + 1; /* New hdr sz: 2, 3, 5, or 9 */ |
| 2852 | szHdr = 1; |
| 2853 | break; |
| 2854 | } |
| 2855 | case 12: { /* aIns[] header size is 2 */ |
| 2856 | if( ((1<<d)&0x8a)==0) return 0; /* d must be 1, 3, or 7 */ |
| 2857 | i = d + 2; /* New hdr sz: 2, 5, or 9 */ |
| 2858 | szHdr = 2; |
| 2859 | break; |
| 2860 | } |
| 2861 | case 13: { /* aIns[] header size is 3 */ |
| 2862 | if( d!=2 && d!=6 ) return 0; /* d must be 2 or 6 */ |
| 2863 | i = d + 3; /* New hdr sz: 5 or 9 */ |
| 2864 | szHdr = 3; |
| 2865 | break; |
| 2866 | } |
| 2867 | case 14: { /* aIns[] header size is 5 */ |
| 2868 | if( d!=4 ) return 0; /* d must be 4 */ |
| 2869 | i = 9; /* New hdr sz: 9 */ |
| 2870 | szHdr = 5; |
| 2871 | break; |
| 2872 | } |
| 2873 | case 15: { /* aIns[] header size is 9 */ |
| 2874 | return 0; /* No solution */ |
| 2875 | } |
| 2876 | } |
| 2877 | assert( i>=2 && i<=9 && aType[i-2]!=0 ); |
| 2878 | aOut[0] = (aIns[0] & 0x0f) | aType[i-2]; |
| 2879 | memcpy(&aOut[i], &aIns[szHdr], nIns-szHdr); |
| 2880 | szPayload = nIns - szHdr; |
| 2881 | while( 1/*edit-by-break*/ ){ |
| 2882 | i--; |
| 2883 | aOut[i] = szPayload & 0xff; |
| 2884 | if( i==1 ) break; |
| 2885 | szPayload >>= 8; |
| 2886 | } |
| 2887 | assert( (szPayload>>8)==0 ); |
| 2888 | return 1; |
| 2889 | } |
| 2890 | |
| 2891 | /* |
| 2892 | ** Modify the JSONB blob at pParse->aBlob by removing nDel bytes of |
| 2893 | ** content beginning at iDel, and replacing them with nIns bytes of |
| 2894 | ** content given by aIns. |
| 2895 | ** |
| 2896 | ** nDel may be zero, in which case no bytes are removed. But iDel is |
| 2897 | ** still important as new bytes will be insert beginning at iDel. |
| 2898 | ** |
| 2899 | ** aIns may be zero, in which case space is created to hold nIns bytes |
| 2900 | ** beginning at iDel, but that space is uninitialized. |
| 2901 | ** |
| 2902 | ** Set pParse->oom if an OOM occurs. |
| 2903 | */ |
| 2904 | static void jsonBlobEdit( |
| 2905 | JsonParse *pParse, /* The JSONB to be modified is in pParse->aBlob */ |
| 2906 | u32 iDel, /* First byte to be removed */ |
| 2907 | u32 nDel, /* Number of bytes to remove */ |
| 2908 | const u8 *aIns, /* Content to insert */ |
| 2909 | u32 nIns /* Bytes of content to insert */ |
| 2910 | ){ |
| 2911 | i64 d = (i64)nIns - (i64)nDel; |
| 2912 | assert( pParse->nBlob >= (u64)iDel + (u64)nDel ); |
| 2913 | if( d<0 && d>=(-8) && aIns!=0 |
| 2914 | && jsonBlobOverwrite(&pParse->aBlob[iDel], aIns, nIns, (int)-d) |
| 2915 | ){ |
| 2916 | return; |
| 2917 | } |
| 2918 | if( d!=0 ){ |
| 2919 | if( pParse->nBlob + d > pParse->nBlobAlloc ){ |
| 2920 | jsonBlobExpand(pParse, (u64)pParse->nBlob+d); |
| 2921 | if( pParse->oom ) return; |
| 2922 | } |
| 2923 | memmove(&pParse->aBlob[iDel+nIns], |
| 2924 | &pParse->aBlob[iDel+nDel], |
| 2925 | pParse->nBlob - (iDel+nDel)); |
| 2926 | pParse->nBlob += d; |
| 2927 | pParse->delta += d; |
| 2928 | } |
| 2929 | if( nIns && aIns ){ |
| 2930 | memcpy(&pParse->aBlob[iDel], aIns, nIns); |
| 2931 | } |
| 2932 | } |
| 2933 | |
| 2934 | /* |
| 2935 | ** Return the number of escaped newlines to be ignored. |
| 2936 | ** An escaped newline is a one of the following byte sequences: |
| 2937 | ** |
| 2938 | ** 0x5c 0x0a |
| 2939 | ** 0x5c 0x0d |
| 2940 | ** 0x5c 0x0d 0x0a |
| 2941 | ** 0x5c 0xe2 0x80 0xa8 |
| 2942 | ** 0x5c 0xe2 0x80 0xa9 |
| 2943 | */ |
| 2944 | static u32 jsonBytesToBypass(const char *z, u32 n){ |
| 2945 | u32 i = 0; |
| 2946 | while( i+1<n ){ |
| 2947 | if( z[i]!='\\' ) return i; |
| 2948 | if( z[i+1]=='\n' ){ |
| 2949 | i += 2; |
| 2950 | continue; |
| 2951 | } |
| 2952 | if( z[i+1]=='\r' ){ |
| 2953 | if( i+2<n && z[i+2]=='\n' ){ |
| 2954 | i += 3; |
| 2955 | }else{ |
| 2956 | i += 2; |
| 2957 | } |
| 2958 | continue; |
| 2959 | } |
| 2960 | if( 0xe2==(u8)z[i+1] |
| 2961 | && i+3<n |
| 2962 | && 0x80==(u8)z[i+2] |
| 2963 | && (0xa8==(u8)z[i+3] || 0xa9==(u8)z[i+3]) |
| 2964 | ){ |
| 2965 | i += 4; |
| 2966 | continue; |
| 2967 | } |
| 2968 | break; |
| 2969 | } |
| 2970 | return i; |
| 2971 | } |
| 2972 | |
| 2973 | /* |
| 2974 | ** Input z[0..n] defines JSON escape sequence including the leading '\\'. |
| 2975 | ** Decode that escape sequence into a single character. Write that |
| 2976 | ** character into *piOut. Return the number of bytes in the escape sequence. |
| 2977 | ** |
| 2978 | ** If there is a syntax error of some kind (for example too few characters |
| 2979 | ** after the '\\' to complete the encoding) then *piOut is set to |
| 2980 | ** JSON_INVALID_CHAR. |
| 2981 | */ |
| 2982 | static u32 jsonUnescapeOneChar(const char *z, u32 n, u32 *piOut){ |
| 2983 | assert( n>0 ); |
| 2984 | assert( z[0]=='\\' ); |
| 2985 | if( n<2 ){ |
| 2986 | *piOut = JSON_INVALID_CHAR; |
| 2987 | return n; |
| 2988 | } |
| 2989 | switch( (u8)z[1] ){ |
| 2990 | case 'u': { |
| 2991 | u32 v, vlo; |
| 2992 | if( n<6 ){ |
| 2993 | *piOut = JSON_INVALID_CHAR; |
| 2994 | return n; |
| 2995 | } |
| 2996 | v = jsonHexToInt4(&z[2]); |
| 2997 | if( (v & 0xfc00)==0xd800 |
| 2998 | && n>=12 |
| 2999 | && z[6]=='\\' |
| 3000 | && z[7]=='u' |
| 3001 | && ((vlo = jsonHexToInt4(&z[8]))&0xfc00)==0xdc00 |
| 3002 | ){ |
| 3003 | *piOut = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000; |
| 3004 | return 12; |
| 3005 | }else{ |
| 3006 | *piOut = v; |
| 3007 | return 6; |
| 3008 | } |
| 3009 | } |
| 3010 | case 'b': { *piOut = '\b'; return 2; } |
| 3011 | case 'f': { *piOut = '\f'; return 2; } |
| 3012 | case 'n': { *piOut = '\n'; return 2; } |
| 3013 | case 'r': { *piOut = '\r'; return 2; } |
| 3014 | case 't': { *piOut = '\t'; return 2; } |
| 3015 | case 'v': { *piOut = '\v'; return 2; } |
| 3016 | case '0': { |
| 3017 | /* JSON5 requires that the \0 escape not be followed by a digit. |
| 3018 | ** But SQLite did not enforce this restriction in versions 3.42.0 |
| 3019 | ** through 3.49.2. That was a bug. But some applications might have |
| 3020 | ** come to depend on that bug. Use the SQLITE_BUG_COMPATIBLE_20250510 |
| 3021 | ** option to restore the old buggy behavior. */ |
| 3022 | #ifdef SQLITE_BUG_COMPATIBLE_20250510 |
| 3023 | /* Legacy bug-compatible behavior */ |
| 3024 | *piOut = 0; |
| 3025 | #else |
| 3026 | /* Correct behavior */ |
| 3027 | *piOut = (n>2 && sqlite3Isdigit(z[2])) ? JSON_INVALID_CHAR : 0; |
| 3028 | #endif |
| 3029 | return 2; |
| 3030 | } |
| 3031 | case '\'': |
| 3032 | case '"': |
| 3033 | case '/': |
| 3034 | case '\\':{ *piOut = z[1]; return 2; } |
| 3035 | case 'x': { |
| 3036 | if( n<4 ){ |
| 3037 | *piOut = JSON_INVALID_CHAR; |
| 3038 | return n; |
| 3039 | } |
| 3040 | *piOut = (jsonHexToInt(z[2])<<4) | jsonHexToInt(z[3]); |
| 3041 | return 4; |
| 3042 | } |
| 3043 | case 0xe2: |
| 3044 | case '\r': |
| 3045 | case '\n': { |
| 3046 | u32 nSkip = jsonBytesToBypass(z, n); |
| 3047 | if( nSkip==0 ){ |
| 3048 | *piOut = JSON_INVALID_CHAR; |
| 3049 | return n; |
| 3050 | }else if( nSkip==n ){ |
| 3051 | *piOut = 0; |
| 3052 | return n; |
| 3053 | }else if( z[nSkip]=='\\' ){ |
| 3054 | return nSkip + jsonUnescapeOneChar(&z[nSkip], n-nSkip, piOut); |
| 3055 | }else{ |
| 3056 | int sz = sqlite3Utf8ReadLimited((u8*)&z[nSkip], n-nSkip, piOut); |
| 3057 | return nSkip + sz; |
| 3058 | } |
| 3059 | } |
| 3060 | default: { |
| 3061 | *piOut = JSON_INVALID_CHAR; |
| 3062 | return 2; |
| 3063 | } |
| 3064 | } |
| 3065 | } |
| 3066 | |
| 3067 | |
| 3068 | /* |
| 3069 | ** Compare two object labels. Return 1 if they are equal and |
| 3070 | ** 0 if they differ. |
| 3071 | ** |
| 3072 | ** In this version, we know that one or the other or both of the |
| 3073 | ** two comparands contains an escape sequence. |
| 3074 | */ |
| 3075 | static SQLITE_NOINLINE int jsonLabelCompareEscaped( |
| 3076 | const char *zLeft, /* The left label */ |
| 3077 | u32 nLeft, /* Size of the left label in bytes */ |
| 3078 | int rawLeft, /* True if zLeft contains no escapes */ |
| 3079 | const char *zRight, /* The right label */ |
| 3080 | u32 nRight, /* Size of the right label in bytes */ |
| 3081 | int rawRight /* True if zRight is escape-free */ |
| 3082 | ){ |
| 3083 | u32 cLeft, cRight; |
| 3084 | assert( rawLeft==0 || rawRight==0 ); |
| 3085 | while( 1 /*exit-by-return*/ ){ |
| 3086 | if( nLeft==0 ){ |
| 3087 | cLeft = 0; |
| 3088 | }else if( rawLeft || zLeft[0]!='\\' ){ |
| 3089 | cLeft = ((u8*)zLeft)[0]; |
| 3090 | if( cLeft>=0xc0 ){ |
| 3091 | int sz = sqlite3Utf8ReadLimited((u8*)zLeft, nLeft, &cLeft); |
| 3092 | zLeft += sz; |
| 3093 | nLeft -= sz; |
| 3094 | }else{ |
| 3095 | zLeft++; |
| 3096 | nLeft--; |
| 3097 | } |
| 3098 | }else{ |
| 3099 | u32 n = jsonUnescapeOneChar(zLeft, nLeft, &cLeft); |
| 3100 | zLeft += n; |
| 3101 | assert( n<=nLeft ); |
| 3102 | nLeft -= n; |
| 3103 | } |
| 3104 | if( nRight==0 ){ |
| 3105 | cRight = 0; |
| 3106 | }else if( rawRight || zRight[0]!='\\' ){ |
| 3107 | cRight = ((u8*)zRight)[0]; |
| 3108 | if( cRight>=0xc0 ){ |
| 3109 | int sz = sqlite3Utf8ReadLimited((u8*)zRight, nRight, &cRight); |
| 3110 | zRight += sz; |
| 3111 | nRight -= sz; |
| 3112 | }else{ |
| 3113 | zRight++; |
| 3114 | nRight--; |
| 3115 | } |
| 3116 | }else{ |
| 3117 | u32 n = jsonUnescapeOneChar(zRight, nRight, &cRight); |
| 3118 | zRight += n; |
| 3119 | assert( n<=nRight ); |
| 3120 | nRight -= n; |
| 3121 | } |
| 3122 | if( cLeft!=cRight ) return 0; |
| 3123 | if( cLeft==0 ) return 1; |
| 3124 | } |
| 3125 | } |
| 3126 | |
| 3127 | /* |
| 3128 | ** Compare two object labels. Return 1 if they are equal and |
| 3129 | ** 0 if they differ. Return -1 if an OOM occurs. |
| 3130 | */ |
| 3131 | static int jsonLabelCompare( |
| 3132 | const char *zLeft, /* The left label */ |
| 3133 | u32 nLeft, /* Size of the left label in bytes */ |
| 3134 | int rawLeft, /* True if zLeft contains no escapes */ |
| 3135 | const char *zRight, /* The right label */ |
| 3136 | u32 nRight, /* Size of the right label in bytes */ |
| 3137 | int rawRight /* True if zRight is escape-free */ |
| 3138 | ){ |
| 3139 | if( rawLeft && rawRight ){ |
| 3140 | /* Simpliest case: Neither label contains escapes. A simple |
| 3141 | ** memcmp() is sufficient. */ |
| 3142 | if( nLeft!=nRight ) return 0; |
| 3143 | return memcmp(zLeft, zRight, nLeft)==0; |
| 3144 | }else{ |
| 3145 | return jsonLabelCompareEscaped(zLeft, nLeft, rawLeft, |
| 3146 | zRight, nRight, rawRight); |
| 3147 | } |
| 3148 | } |
| 3149 | |
| 3150 | /* |
| 3151 | ** Error returns from jsonLookupStep() |
| 3152 | */ |
| 3153 | #define JSON_LOOKUP_ERROR 0xffffffff |
| 3154 | #define JSON_LOOKUP_NOTFOUND 0xfffffffe |
| 3155 | #define JSON_LOOKUP_NOTARRAY 0xfffffffd |
| 3156 | #define JSON_LOOKUP_TOODEEP 0xfffffffc |
| 3157 | #define JSON_LOOKUP_PATHERROR 0xfffffffb |
| 3158 | #define JSON_LOOKUP_ISERROR(x) ((x)>=JSON_LOOKUP_PATHERROR) |
| 3159 | |
| 3160 | /* Forward declaration */ |
| 3161 | static u32 jsonLookupStep(JsonParse*,u32,const char*,u32); |
| 3162 | |
| 3163 | |
| 3164 | /* This helper routine for jsonLookupStep() populates pIns with |
| 3165 | ** binary data that is to be inserted into pParse. |
| 3166 | ** |
| 3167 | ** In the common case, pIns just points to pParse->aIns and pParse->nIns. |
| 3168 | ** But if the zPath of the original edit operation includes path elements |
| 3169 | ** that go deeper, additional substructure must be created. |
| 3170 | ** |
| 3171 | ** For example: |
| 3172 | ** |
| 3173 | ** json_insert('{}', '$.a.b.c', 123); |
| 3174 | ** |
| 3175 | ** The search stops at '$.a' But additional substructure must be |
| 3176 | ** created for the ".b.c" part of the patch so that the final result |
| 3177 | ** is: {"a":{"b":{"c"::123}}}. This routine populates pIns with |
| 3178 | ** the binary equivalent of {"b":{"c":123}} so that it can be inserted. |
| 3179 | ** |
| 3180 | ** The caller is responsible for resetting pIns when it has finished |
| 3181 | ** using the substructure. |
| 3182 | */ |
| 3183 | static u32 jsonCreateEditSubstructure( |
| 3184 | JsonParse *pParse, /* The original JSONB that is being edited */ |
| 3185 | JsonParse *pIns, /* Populate this with the blob data to insert */ |
| 3186 | const char *zTail /* Tail of the path that determines substructure */ |
| 3187 | ){ |
| 3188 | static const u8 emptyObject[] = { JSONB_ARRAY, JSONB_OBJECT }; |
| 3189 | int rc; |
| 3190 | memset(pIns, 0, sizeof(*pIns)); |
| 3191 | pIns->db = pParse->db; |
| 3192 | if( zTail[0]==0 ){ |
| 3193 | /* No substructure. Just insert what is given in pParse. */ |
| 3194 | pIns->aBlob = pParse->aIns; |
| 3195 | pIns->nBlob = pParse->nIns; |
| 3196 | rc = 0; |
| 3197 | }else{ |
| 3198 | /* Construct the binary substructure */ |
| 3199 | pIns->nBlob = 1; |
| 3200 | pIns->aBlob = (u8*)&emptyObject[zTail[0]=='.']; |
| 3201 | pIns->eEdit = pParse->eEdit; |
| 3202 | pIns->nIns = pParse->nIns; |
| 3203 | pIns->aIns = pParse->aIns; |
| 3204 | pIns->iDepth = pParse->iDepth+1; |
| 3205 | if( pIns->iDepth >= JSON_MAX_DEPTH ){ |
| 3206 | return JSON_LOOKUP_TOODEEP; |
| 3207 | } |
| 3208 | rc = jsonLookupStep(pIns, 0, zTail, 0); |
| 3209 | pParse->iDepth--; |
| 3210 | pParse->oom |= pIns->oom; |
| 3211 | } |
| 3212 | return rc; /* Error code only */ |
| 3213 | } |
| 3214 | |
| 3215 | /* |
| 3216 | ** Search along zPath to find the Json element specified. Return an |
| 3217 | ** index into pParse->aBlob[] for the start of that element's value. |
| 3218 | ** |
| 3219 | ** If the value found by this routine is the value half of label/value pair |
| 3220 | ** within an object, then set pPath->iLabel to the start of the corresponding |
| 3221 | ** label, before returning. |
| 3222 | ** |
| 3223 | ** Return one of the JSON_LOOKUP error codes if problems are seen. |
| 3224 | ** |
| 3225 | ** This routine will also modify the blob. If pParse->eEdit is one of |
| 3226 | ** JEDIT_DEL, JEDIT_REPL, JEDIT_INS, JEDIT_SET, or JEDIT_AINS, then changes |
| 3227 | ** might be made to the selected value. If an edit is performed, then the |
| 3228 | ** return value does not necessarily point to the select element. If an edit |
| 3229 | ** is performed, the return value is only useful for detecting error |
| 3230 | ** conditions. |
| 3231 | */ |
| 3232 | static u32 jsonLookupStep( |
| 3233 | JsonParse *pParse, /* The JSON to search */ |
| 3234 | u32 iRoot, /* Begin the search at this element of aBlob[] */ |
| 3235 | const char *zPath, /* The path to search */ |
| 3236 | u32 iLabel /* Label if iRoot is a value of in an object */ |
| 3237 | ){ |
| 3238 | u32 i, j, k, nKey, sz, n, iEnd, rc; |
| 3239 | const char *zKey; |
| 3240 | u8 x; |
| 3241 | |
| 3242 | if( zPath[0]==0 ){ |
| 3243 | if( pParse->eEdit && jsonBlobMakeEditable(pParse, pParse->nIns) ){ |
| 3244 | n = jsonbPayloadSize(pParse, iRoot, &sz); |
| 3245 | sz += n; |
| 3246 | if( pParse->eEdit==JEDIT_DEL ){ |
| 3247 | if( iLabel>0 ){ |
| 3248 | sz += iRoot - iLabel; |
| 3249 | iRoot = iLabel; |
| 3250 | } |
| 3251 | jsonBlobEdit(pParse, iRoot, sz, 0, 0); |
| 3252 | }else if( pParse->eEdit==JEDIT_INS ){ |
| 3253 | /* Already exists, so json_insert() is a no-op */ |
| 3254 | }else if( pParse->eEdit==JEDIT_AINS ){ |
| 3255 | /* json_array_insert() */ |
| 3256 | if( zPath[-1]!=']' ){ |
| 3257 | return JSON_LOOKUP_NOTARRAY; |
| 3258 | }else{ |
| 3259 | jsonBlobEdit(pParse, iRoot, 0, pParse->aIns, pParse->nIns); |
| 3260 | } |
| 3261 | }else{ |
| 3262 | /* json_set() or json_replace() */ |
| 3263 | jsonBlobEdit(pParse, iRoot, sz, pParse->aIns, pParse->nIns); |
| 3264 | } |
| 3265 | } |
| 3266 | pParse->iLabel = iLabel; |
| 3267 | return iRoot; |
| 3268 | } |
| 3269 | if( zPath[0]=='.' ){ |
| 3270 | int rawKey = 1; |
| 3271 | x = pParse->aBlob[iRoot]; |
| 3272 | zPath++; |
| 3273 | if( zPath[0]=='"' ){ |
| 3274 | zKey = zPath + 1; |
| 3275 | for(i=1; zPath[i] && zPath[i]!='"'; i++){ |
| 3276 | if( zPath[i]=='\\' && zPath[i+1]!=0 ) i++; |
| 3277 | } |
| 3278 | nKey = i-1; |
| 3279 | if( zPath[i] ){ |
| 3280 | i++; |
| 3281 | }else{ |
| 3282 | return JSON_LOOKUP_PATHERROR; |
| 3283 | } |
| 3284 | testcase( nKey==0 ); |
| 3285 | rawKey = memchr(zKey, '\\', nKey)==0; |
| 3286 | }else{ |
| 3287 | zKey = zPath; |
| 3288 | for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){} |
| 3289 | nKey = i; |
| 3290 | if( nKey==0 ){ |
| 3291 | return JSON_LOOKUP_PATHERROR; |
| 3292 | } |
| 3293 | } |
| 3294 | if( (x & 0x0f)!=JSONB_OBJECT ) return JSON_LOOKUP_NOTFOUND; |
| 3295 | n = jsonbPayloadSize(pParse, iRoot, &sz); |
| 3296 | j = iRoot + n; /* j is the index of a label */ |
| 3297 | iEnd = j+sz; |
| 3298 | while( j<iEnd ){ |
| 3299 | int rawLabel; |
| 3300 | const char *zLabel; |
| 3301 | x = pParse->aBlob[j] & 0x0f; |
| 3302 | if( x<JSONB_TEXT || x>JSONB_TEXTRAW ) return JSON_LOOKUP_ERROR; |
| 3303 | n = jsonbPayloadSizeSemiInline(pParse, j, &sz); |
| 3304 | if( n==0 ) return JSON_LOOKUP_ERROR; |
| 3305 | k = j+n; /* k is the index of the label text */ |
| 3306 | if( k+sz>=iEnd ) return JSON_LOOKUP_ERROR; |
| 3307 | zLabel = (const char*)&pParse->aBlob[k]; |
| 3308 | rawLabel = x==JSONB_TEXT || x==JSONB_TEXTRAW; |
| 3309 | if( jsonLabelCompare(zKey, nKey, rawKey, zLabel, sz, rawLabel) ){ |
| 3310 | u32 v = k+sz; /* v is the index of the value */ |
| 3311 | if( ((pParse->aBlob[v])&0x0f)>JSONB_OBJECT ) return JSON_LOOKUP_ERROR; |
| 3312 | n = jsonbPayloadSize(pParse, v, &sz); |
| 3313 | if( n==0 || v+n+sz>iEnd ) return JSON_LOOKUP_ERROR; |
| 3314 | assert( j>0 ); |
| 3315 | if( ++pParse->iDepth >= JSON_MAX_DEPTH ){ |
| 3316 | return JSON_LOOKUP_TOODEEP; |
| 3317 | } |
| 3318 | rc = jsonLookupStep(pParse, v, &zPath[i], j); |
| 3319 | pParse->iDepth--; |
| 3320 | if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot); |
| 3321 | return rc; |
| 3322 | } |
| 3323 | j = k+sz; |
| 3324 | if( ((pParse->aBlob[j])&0x0f)>JSONB_OBJECT ) return JSON_LOOKUP_ERROR; |
| 3325 | n = jsonbPayloadSizeSemiInline(pParse, j, &sz); |
| 3326 | if( n==0 ) return JSON_LOOKUP_ERROR; |
| 3327 | j += n+sz; |
| 3328 | } |
| 3329 | if( j>iEnd ) return JSON_LOOKUP_ERROR; |
| 3330 | if( pParse->eEdit>=JEDIT_INS ){ |
| 3331 | u32 nIns; /* Total bytes to insert (label+value) */ |
| 3332 | JsonParse v; /* BLOB encoding of the value to be inserted */ |
| 3333 | JsonParse ix; /* Header of the label to be inserted */ |
| 3334 | testcase( pParse->eEdit==JEDIT_INS ); |
| 3335 | testcase( pParse->eEdit==JEDIT_SET ); |
| 3336 | testcase( pParse->eEdit==JEDIT_AINS ); |
| 3337 | if( pParse->eEdit==JEDIT_AINS && sqlite3_strglob("*]",&zPath[i])!=0 ){ |
| 3338 | return JSON_LOOKUP_NOTARRAY; |
| 3339 | } |
| 3340 | memset(&ix, 0, sizeof(ix)); |
| 3341 | ix.db = pParse->db; |
| 3342 | jsonBlobAppendNode(&ix, rawKey?JSONB_TEXTRAW:JSONB_TEXT5, nKey, 0); |
| 3343 | pParse->oom |= ix.oom; |
| 3344 | rc = jsonCreateEditSubstructure(pParse, &v, &zPath[i]); |
| 3345 | if( !JSON_LOOKUP_ISERROR(rc) |
| 3346 | && jsonBlobMakeEditable(pParse, ix.nBlob+nKey+v.nBlob) |
| 3347 | ){ |
| 3348 | assert( !pParse->oom ); |
| 3349 | nIns = ix.nBlob + nKey + v.nBlob; |
| 3350 | jsonBlobEdit(pParse, j, 0, 0, nIns); |
| 3351 | if( !pParse->oom ){ |
| 3352 | assert( pParse->aBlob!=0 ); /* Because pParse->oom!=0 */ |
| 3353 | assert( ix.aBlob!=0 ); /* Because pPasre->oom!=0 */ |
| 3354 | memcpy(&pParse->aBlob[j], ix.aBlob, ix.nBlob); |
| 3355 | k = j + ix.nBlob; |
| 3356 | memcpy(&pParse->aBlob[k], zKey, nKey); |
| 3357 | k += nKey; |
| 3358 | memcpy(&pParse->aBlob[k], v.aBlob, v.nBlob); |
| 3359 | if( ALWAYS(pParse->delta) ) jsonAfterEditSizeAdjust(pParse, iRoot); |
| 3360 | } |
| 3361 | } |
| 3362 | jsonParseReset(&v); |
| 3363 | jsonParseReset(&ix); |
| 3364 | return rc; |
| 3365 | } |
| 3366 | }else if( zPath[0]=='[' ){ |
| 3367 | u64 kk = 0; |
| 3368 | x = pParse->aBlob[iRoot] & 0x0f; |
| 3369 | if( x!=JSONB_ARRAY ) return JSON_LOOKUP_NOTFOUND; |
| 3370 | n = jsonbPayloadSize(pParse, iRoot, &sz); |
| 3371 | i = 1; |
| 3372 | while( sqlite3Isdigit(zPath[i]) ){ |
| 3373 | if( kk<0xffffffff ) kk = kk*10 + zPath[i] - '0'; |
| 3374 | /* ^^^^^^^^^^--- Allow kk to be bigger than any JSON array so that |
| 3375 | ** we get NOTFOUND instead of PATHERROR, without overflowing kk. */ |
| 3376 | i++; |
| 3377 | } |
| 3378 | if( i<2 || zPath[i]!=']' ){ |
| 3379 | if( zPath[1]=='#' ){ |
| 3380 | kk = jsonbArrayCount(pParse, iRoot); |
| 3381 | i = 2; |
| 3382 | if( zPath[2]=='-' && sqlite3Isdigit(zPath[3]) ){ |
| 3383 | u64 nn = 0; |
| 3384 | i = 3; |
| 3385 | do{ |
| 3386 | if( nn<0xffffffff ) nn = nn*10 + zPath[i] - '0'; |
| 3387 | /* ^^^^^^^^^^--- Allow nn to be bigger than any JSON array to |
| 3388 | ** get NOTFOUND instead of PATHERROR, without overflowing nn. */ |
| 3389 | i++; |
| 3390 | }while( sqlite3Isdigit(zPath[i]) ); |
| 3391 | if( nn>kk ) return JSON_LOOKUP_NOTFOUND; |
| 3392 | kk -= nn; |
| 3393 | } |
| 3394 | if( zPath[i]!=']' ){ |
| 3395 | return JSON_LOOKUP_PATHERROR; |
| 3396 | } |
| 3397 | }else{ |
| 3398 | return JSON_LOOKUP_PATHERROR; |
| 3399 | } |
| 3400 | } |
| 3401 | j = iRoot+n; |
| 3402 | iEnd = j+sz; |
| 3403 | while( j<iEnd ){ |
| 3404 | if( kk==0 ){ |
| 3405 | if( ++pParse->iDepth >= JSON_MAX_DEPTH ){ |
| 3406 | return JSON_LOOKUP_TOODEEP; |
| 3407 | } |
| 3408 | rc = jsonLookupStep(pParse, j, &zPath[i+1], 0); |
| 3409 | pParse->iDepth--; |
| 3410 | if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot); |
| 3411 | return rc; |
| 3412 | } |
| 3413 | kk--; |
| 3414 | n = jsonbPayloadSizeSemiInline(pParse, j, &sz); |
| 3415 | if( n==0 ) return JSON_LOOKUP_ERROR; |
| 3416 | j += n+sz; |
| 3417 | } |
| 3418 | if( j>iEnd ) return JSON_LOOKUP_ERROR; |
| 3419 | if( kk>0 ) return JSON_LOOKUP_NOTFOUND; |
| 3420 | if( pParse->eEdit>=JEDIT_INS ){ |
| 3421 | JsonParse v; |
| 3422 | testcase( pParse->eEdit==JEDIT_INS ); |
| 3423 | testcase( pParse->eEdit==JEDIT_AINS ); |
| 3424 | testcase( pParse->eEdit==JEDIT_SET ); |
| 3425 | rc = jsonCreateEditSubstructure(pParse, &v, &zPath[i+1]); |
| 3426 | if( !JSON_LOOKUP_ISERROR(rc) |
| 3427 | && jsonBlobMakeEditable(pParse, v.nBlob) |
| 3428 | ){ |
| 3429 | assert( !pParse->oom ); |
| 3430 | jsonBlobEdit(pParse, j, 0, v.aBlob, v.nBlob); |
| 3431 | } |
| 3432 | jsonParseReset(&v); |
| 3433 | if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot); |
| 3434 | return rc; |
| 3435 | } |
| 3436 | }else{ |
| 3437 | return JSON_LOOKUP_PATHERROR; |
| 3438 | } |
| 3439 | return JSON_LOOKUP_NOTFOUND; |
| 3440 | } |
| 3441 | |
| 3442 | /* |
| 3443 | ** Convert a JSON BLOB into text and make that text the return value |
| 3444 | ** of an SQL function. |
| 3445 | */ |
| 3446 | static void jsonReturnTextJsonFromBlob( |
| 3447 | sqlite3_context *ctx, |
| 3448 | const u8 *aBlob, |
| 3449 | u32 nBlob |
| 3450 | ){ |
| 3451 | JsonParse x; |
| 3452 | JsonString s; |
| 3453 | |
| 3454 | if( NEVER(aBlob==0) ) return; |
| 3455 | memset(&x, 0, sizeof(x)); |
| 3456 | x.aBlob = (u8*)aBlob; |
| 3457 | x.nBlob = nBlob; |
| 3458 | jsonStringInit(&s, ctx); |
| 3459 | jsonTranslateBlobToText(&x, 0, &s); |
| 3460 | jsonReturnString(&s, 0, 0); |
| 3461 | } |
| 3462 | |
| 3463 | |
| 3464 | /* |
| 3465 | ** Return the value of the BLOB node at index i. |
| 3466 | ** |
| 3467 | ** If the value is a primitive, return it as an SQL value. |
| 3468 | ** If the value is an array or object, return it as either |
| 3469 | ** JSON text or the BLOB encoding, depending on the eMode flag |
| 3470 | ** as follows: |
| 3471 | ** |
| 3472 | ** eMode==0 JSONB if the JSON_B flag is set in userdata or |
| 3473 | ** text if the JSON_B flag is omitted from userdata. |
| 3474 | ** |
| 3475 | ** eMode==1 Text |
| 3476 | ** |
| 3477 | ** eMode==2 JSONB |
| 3478 | */ |
| 3479 | static void jsonReturnFromBlob( |
| 3480 | JsonParse *pParse, /* Complete JSON parse tree */ |
| 3481 | u32 i, /* Index of the node */ |
| 3482 | sqlite3_context *pCtx, /* Return value for this function */ |
| 3483 | int eMode /* Format of return: text of JSONB */ |
| 3484 | ){ |
| 3485 | u32 n, sz; |
| 3486 | int rc; |
| 3487 | sqlite3 *db = sqlite3_context_db_handle(pCtx); |
| 3488 | |
| 3489 | assert( eMode>=0 && eMode<=2 ); |
| 3490 | n = jsonbPayloadSize(pParse, i, &sz); |
| 3491 | if( n==0 ){ |
| 3492 | sqlite3_result_error(pCtx, "malformed JSON", -1); |
| 3493 | return; |
| 3494 | } |
| 3495 | switch( pParse->aBlob[i] & 0x0f ){ |
| 3496 | case JSONB_NULL: { |
| 3497 | if( sz ) goto returnfromblob_malformed; |
| 3498 | sqlite3_result_null(pCtx); |
| 3499 | break; |
| 3500 | } |
| 3501 | case JSONB_TRUE: { |
| 3502 | if( sz ) goto returnfromblob_malformed; |
| 3503 | sqlite3_result_int(pCtx, 1); |
| 3504 | break; |
| 3505 | } |
| 3506 | case JSONB_FALSE: { |
| 3507 | if( sz ) goto returnfromblob_malformed; |
| 3508 | sqlite3_result_int(pCtx, 0); |
| 3509 | break; |
| 3510 | } |
| 3511 | case JSONB_INT5: |
| 3512 | case JSONB_INT: { |
| 3513 | sqlite3_int64 ival; |
| 3514 | double rval; |
| 3515 | int k; |
| 3516 | k = jsonConvertInteger((const char*)&pParse->aBlob[i+n], sz,&ival,&rval); |
| 3517 | if( k==0 ){ |
| 3518 | sqlite3_result_int64(pCtx, ival); |
| 3519 | }else if( k==1 ){ |
| 3520 | sqlite3_result_double(pCtx, rval); |
| 3521 | }else{ |
| 3522 | goto returnfromblob_malformed; |
| 3523 | } |
| 3524 | break; |
| 3525 | } |
| 3526 | case JSONB_FLOAT5: |
| 3527 | case JSONB_FLOAT: { |
| 3528 | double r; |
| 3529 | char *z; |
| 3530 | if( sz==0 ) goto returnfromblob_malformed; |
| 3531 | z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz); |
| 3532 | if( z==0 ) goto returnfromblob_oom; |
| 3533 | rc = sqlite3AtoF(z, &r); |
| 3534 | sqlite3DbFree(db, z); |
| 3535 | if( rc<=0 ) goto returnfromblob_malformed; |
| 3536 | sqlite3_result_double(pCtx, r); |
| 3537 | break; |
| 3538 | } |
| 3539 | case JSONB_TEXTRAW: |
| 3540 | case JSONB_TEXT: { |
| 3541 | sqlite3_result_text(pCtx, (char*)&pParse->aBlob[i+n], sz, |
| 3542 | SQLITE_TRANSIENT); |
| 3543 | break; |
| 3544 | } |
| 3545 | case JSONB_TEXT5: |
| 3546 | case JSONB_TEXTJ: { |
| 3547 | /* Translate JSON formatted string into raw text */ |
| 3548 | u32 iIn, iOut; |
| 3549 | const char *z; |
| 3550 | char *zOut; |
| 3551 | u32 nOut = sz; |
| 3552 | z = (const char*)&pParse->aBlob[i+n]; |
| 3553 | zOut = sqlite3DbMallocRaw(db, ((u64)nOut)+1); |
| 3554 | if( zOut==0 ) goto returnfromblob_oom; |
| 3555 | for(iIn=iOut=0; iIn<sz; iIn++){ |
| 3556 | char c = z[iIn]; |
| 3557 | if( c=='\\' ){ |
| 3558 | u32 v; |
| 3559 | u32 szEscape = jsonUnescapeOneChar(&z[iIn], sz-iIn, &v); |
| 3560 | if( v==0 && iIn+szEscape==sz |
| 3561 | && (z[iIn+1]=='\n' || z[iIn+1]=='\r' || (u8)z[iIn+1]==0xe2) |
| 3562 | ){ |
| 3563 | /* A JSON5 line continuation at the end of the string |
| 3564 | ** contributes no characters */ |
| 3565 | }else if( v<=0x7f ){ |
| 3566 | zOut[iOut++] = (char)v; |
| 3567 | }else if( v<=0x7ff ){ |
| 3568 | assert( szEscape>=2 ); |
| 3569 | zOut[iOut++] = (char)(0xc0 | (v>>6)); |
| 3570 | zOut[iOut++] = 0x80 | (v&0x3f); |
| 3571 | }else if( v<0x10000 ){ |
| 3572 | assert( szEscape>=3 ); |
| 3573 | zOut[iOut++] = 0xe0 | (v>>12); |
| 3574 | zOut[iOut++] = 0x80 | ((v>>6)&0x3f); |
| 3575 | zOut[iOut++] = 0x80 | (v&0x3f); |
| 3576 | }else if( v==JSON_INVALID_CHAR ){ |
| 3577 | /* Silently ignore illegal unicode */ |
| 3578 | }else{ |
| 3579 | assert( szEscape>=4 ); |
| 3580 | zOut[iOut++] = 0xf0 | (v>>18); |
| 3581 | zOut[iOut++] = 0x80 | ((v>>12)&0x3f); |
| 3582 | zOut[iOut++] = 0x80 | ((v>>6)&0x3f); |
| 3583 | zOut[iOut++] = 0x80 | (v&0x3f); |
| 3584 | } |
| 3585 | iIn += szEscape - 1; |
| 3586 | }else{ |
| 3587 | zOut[iOut++] = c; |
| 3588 | } |
| 3589 | } /* end for() */ |
| 3590 | assert( iOut<=nOut ); |
| 3591 | zOut[iOut] = 0; |
| 3592 | sqlite3_result_text(pCtx, zOut, iOut, SQLITE_DYNAMIC); |
| 3593 | break; |
| 3594 | } |
| 3595 | case JSONB_ARRAY: |
| 3596 | case JSONB_OBJECT: { |
| 3597 | if( eMode==0 ){ |
| 3598 | if( (SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx)) & JSON_BLOB)!=0 ){ |
| 3599 | eMode = 2; |
| 3600 | }else{ |
| 3601 | eMode = 1; |
| 3602 | } |
| 3603 | } |
| 3604 | if( eMode==2 ){ |
| 3605 | sqlite3_result_blob(pCtx, &pParse->aBlob[i], sz+n, SQLITE_TRANSIENT); |
| 3606 | }else{ |
| 3607 | jsonReturnTextJsonFromBlob(pCtx, &pParse->aBlob[i], sz+n); |
| 3608 | } |
| 3609 | break; |
| 3610 | } |
| 3611 | default: { |
| 3612 | goto returnfromblob_malformed; |
| 3613 | } |
| 3614 | } |
| 3615 | return; |
| 3616 | |
| 3617 | returnfromblob_oom: |
| 3618 | sqlite3_result_error_nomem(pCtx); |
| 3619 | return; |
| 3620 | |
| 3621 | returnfromblob_malformed: |
| 3622 | sqlite3_result_error(pCtx, "malformed JSON", -1); |
| 3623 | return; |
| 3624 | } |
| 3625 | |
| 3626 | /* |
| 3627 | ** pArg is a function argument that might be an SQL value or a JSON |
| 3628 | ** value. Figure out what it is and encode it as a JSONB blob. |
| 3629 | ** Return the results in pParse. |
| 3630 | ** |
| 3631 | ** pParse is uninitialized upon entry. This routine will handle the |
| 3632 | ** initialization of pParse. The result will be contained in |
| 3633 | ** pParse->aBlob and pParse->nBlob. pParse->aBlob might be dynamically |
| 3634 | ** allocated (if pParse->nBlobAlloc is greater than zero) in which case |
| 3635 | ** the caller is responsible for freeing the space allocated to pParse->aBlob |
| 3636 | ** when it has finished with it. Or pParse->aBlob might be a static string |
| 3637 | ** or a value obtained from sqlite3_value_blob(pArg). |
| 3638 | ** |
| 3639 | ** If the argument is a BLOB that is clearly not a JSONB, then this |
| 3640 | ** function might set an error message in ctx and return non-zero. |
| 3641 | ** It might also set an error message and return non-zero on an OOM error. |
| 3642 | */ |
| 3643 | static int jsonFunctionArgToBlob( |
| 3644 | sqlite3_context *ctx, |
| 3645 | sqlite3_value *pArg, |
| 3646 | JsonParse *pParse |
| 3647 | ){ |
| 3648 | int eType = sqlite3_value_type(pArg); |
| 3649 | static u8 aNull[] = { 0x00 }; |
| 3650 | memset(pParse, 0, sizeof(pParse[0])); |
| 3651 | pParse->db = sqlite3_context_db_handle(ctx); |
| 3652 | switch( eType ){ |
| 3653 | default: { |
| 3654 | pParse->aBlob = aNull; |
| 3655 | pParse->nBlob = 1; |
| 3656 | return 0; |
| 3657 | } |
| 3658 | case SQLITE_BLOB: { |
| 3659 | if( !jsonArgIsJsonb(pArg, pParse) ){ |
| 3660 | sqlite3_result_error(ctx, "JSON cannot hold BLOB values", -1); |
| 3661 | return 1; |
| 3662 | } |
| 3663 | break; |
| 3664 | } |
| 3665 | case SQLITE_TEXT: { |
| 3666 | const char *zJson = (const char*)sqlite3_value_text(pArg); |
| 3667 | int nJson = sqlite3_value_bytes(pArg); |
| 3668 | if( zJson==0 ) return 1; |
| 3669 | if( sqlite3_value_subtype(pArg)==JSON_SUBTYPE ){ |
| 3670 | pParse->zJson = (char*)zJson; |
| 3671 | pParse->nJson = nJson; |
| 3672 | if( jsonConvertTextToBlob(pParse, ctx) ){ |
| 3673 | sqlite3_result_error(ctx, "malformed JSON", -1); |
| 3674 | sqlite3DbFree(pParse->db, pParse->aBlob); |
| 3675 | memset(pParse, 0, sizeof(pParse[0])); |
| 3676 | return 1; |
| 3677 | } |
| 3678 | }else{ |
| 3679 | jsonBlobAppendNode(pParse, JSONB_TEXTRAW, nJson, zJson); |
| 3680 | } |
| 3681 | break; |
| 3682 | } |
| 3683 | case SQLITE_FLOAT: { |
| 3684 | if( NEVER(sqlite3IsNaN(sqlite3_value_double(pArg))) ){ |
| 3685 | jsonBlobAppendNode(pParse, JSONB_NULL, 0, 0); |
| 3686 | }else{ |
| 3687 | int n = sqlite3_value_bytes(pArg); |
| 3688 | const char *z = (const char*)sqlite3_value_text(pArg); |
| 3689 | if( z==0 ) return 1; |
| 3690 | if( z[0]=='I' ){ |
| 3691 | jsonBlobAppendNode(pParse, JSONB_FLOAT, 5, "9e999"); |
| 3692 | }else if( z[0]=='-' && z[1]=='I' ){ |
| 3693 | jsonBlobAppendNode(pParse, JSONB_FLOAT, 6, "-9e999"); |
| 3694 | }else{ |
| 3695 | jsonBlobAppendNode(pParse, JSONB_FLOAT, n, z); |
| 3696 | } |
| 3697 | } |
| 3698 | break; |
| 3699 | } |
| 3700 | case SQLITE_INTEGER: { |
| 3701 | int n = sqlite3_value_bytes(pArg); |
| 3702 | const char *z = (const char*)sqlite3_value_text(pArg); |
| 3703 | if( z==0 ) return 1; |
| 3704 | jsonBlobAppendNode(pParse, JSONB_INT, n, z); |
| 3705 | break; |
| 3706 | } |
| 3707 | } |
| 3708 | if( pParse->oom ){ |
| 3709 | sqlite3_result_error_nomem(ctx); |
| 3710 | return 1; |
| 3711 | }else{ |
| 3712 | return 0; |
| 3713 | } |
| 3714 | } |
| 3715 | |
| 3716 | /* |
| 3717 | ** Generate a path error. |
| 3718 | ** |
| 3719 | ** The specifics of the error are determined by the rc argument. |
| 3720 | ** |
| 3721 | ** rc error |
| 3722 | ** ----------------- ---------------------- |
| 3723 | ** JSON_LOOKUP_ARRAY "not an array" |
| 3724 | ** JSON_LOOKUP_TOODEEP "JSON nested too deep" |
| 3725 | ** JSON_LOOKUP_ERROR "malformed JSON" |
| 3726 | ** otherwise... "bad JSON path" |
| 3727 | ** |
| 3728 | ** If ctx is not NULL then push the error message into ctx and return NULL. |
| 3729 | ** If ctx is NULL, then return the text of the error message. |
| 3730 | */ |
| 3731 | static char *jsonBadPathError( |
| 3732 | sqlite3_context *ctx, /* The function call containing the error */ |
| 3733 | const char *zPath, /* The path with the problem */ |
| 3734 | int rc /* Maybe JSON_LOOKUP_NOTARRAY */ |
| 3735 | ){ |
| 3736 | char *zMsg; |
| 3737 | if( rc==(int)JSON_LOOKUP_NOTARRAY ){ |
| 3738 | zMsg = sqlite3_mprintf("not an array element: %Q", zPath); |
| 3739 | }else if( rc==(int)JSON_LOOKUP_ERROR ){ |
| 3740 | zMsg = sqlite3_mprintf("malformed JSON"); |
| 3741 | }else if( rc==(int)JSON_LOOKUP_TOODEEP ){ |
| 3742 | zMsg = sqlite3_mprintf("JSON path too deep"); |
| 3743 | }else{ |
| 3744 | zMsg = sqlite3_mprintf("bad JSON path: %Q", zPath); |
| 3745 | } |
| 3746 | if( ctx==0 ) return zMsg; |
| 3747 | if( zMsg ){ |
| 3748 | sqlite3_result_error(ctx, zMsg, -1); |
| 3749 | sqlite3_free(zMsg); |
| 3750 | }else{ |
| 3751 | sqlite3_result_error_nomem(ctx); |
| 3752 | } |
| 3753 | return 0; |
| 3754 | } |
| 3755 | |
| 3756 | /* argv[0] is a BLOB that seems likely to be a JSONB. Subsequent |
| 3757 | ** arguments come in pairs where each pair contains a JSON path and |
| 3758 | ** content to insert or set at that patch. Do the updates |
| 3759 | ** and return the result. |
| 3760 | ** |
| 3761 | ** The specific operation is determined by eEdit, which can be one |
| 3762 | ** of JEDIT_INS, JEDIT_REPL, JEDIT_SET, or JEDIT_AINS. |
| 3763 | */ |
| 3764 | static void jsonInsertIntoBlob( |
| 3765 | sqlite3_context *ctx, |
| 3766 | int argc, |
| 3767 | sqlite3_value **argv, |
| 3768 | int eEdit /* JEDIT_INS, JEDIT_REPL, JEDIT_SET, JEDIT_AINS */ |
| 3769 | ){ |
| 3770 | int i; |
| 3771 | u32 rc = 0; |
| 3772 | const char *zPath = 0; |
| 3773 | int flgs; |
| 3774 | JsonParse *p; |
| 3775 | JsonParse ax; |
| 3776 | |
| 3777 | assert( (argc&1)==1 ); |
| 3778 | flgs = argc==1 ? 0 : JSON_EDITABLE; |
| 3779 | p = jsonParseFuncArg(ctx, argv[0], flgs); |
| 3780 | if( p==0 ) return; |
| 3781 | for(i=1; i<argc-1; i+=2){ |
| 3782 | if( sqlite3_value_type(argv[i])==SQLITE_NULL ) continue; |
| 3783 | zPath = (const char*)sqlite3_value_text(argv[i]); |
| 3784 | if( zPath==0 ){ |
| 3785 | sqlite3_result_error_nomem(ctx); |
| 3786 | jsonParseFree(p); |
| 3787 | return; |
| 3788 | } |
| 3789 | if( zPath[0]!='$' ) goto jsonInsertIntoBlob_patherror; |
| 3790 | if( jsonFunctionArgToBlob(ctx, argv[i+1], &ax) ){ |
| 3791 | jsonParseReset(&ax); |
| 3792 | jsonParseFree(p); |
| 3793 | return; |
| 3794 | } |
| 3795 | if( zPath[1]==0 ){ |
| 3796 | if( eEdit==JEDIT_REPL || eEdit==JEDIT_SET ){ |
| 3797 | jsonBlobEdit(p, 0, p->nBlob, ax.aBlob, ax.nBlob); |
| 3798 | } |
| 3799 | rc = 0; |
| 3800 | }else{ |
| 3801 | p->eEdit = eEdit; |
| 3802 | p->nIns = ax.nBlob; |
| 3803 | p->aIns = ax.aBlob; |
| 3804 | p->delta = 0; |
| 3805 | p->iDepth = 0; |
| 3806 | rc = jsonLookupStep(p, 0, zPath+1, 0); |
| 3807 | } |
| 3808 | jsonParseReset(&ax); |
| 3809 | if( rc==JSON_LOOKUP_NOTFOUND ) continue; |
| 3810 | if( JSON_LOOKUP_ISERROR(rc) ) goto jsonInsertIntoBlob_patherror; |
| 3811 | } |
| 3812 | jsonReturnParse(ctx, p); |
| 3813 | jsonParseFree(p); |
| 3814 | return; |
| 3815 | |
| 3816 | jsonInsertIntoBlob_patherror: |
| 3817 | jsonParseFree(p); |
| 3818 | jsonBadPathError(ctx, zPath, rc); |
| 3819 | return; |
| 3820 | } |
| 3821 | |
| 3822 | /* |
| 3823 | ** If pArg is a blob that seems like a JSONB blob, then initialize |
| 3824 | ** p to point to that JSONB and return TRUE. If pArg does not seem like |
| 3825 | ** a JSONB blob, then return FALSE. |
| 3826 | ** |
| 3827 | ** For small BLOBs (having no more than 7 bytes of payload) a full |
| 3828 | ** validity check is done. So for small BLOBs this routine only returns |
| 3829 | ** true if the value is guaranteed to be a valid JSONB. For larger BLOBs |
| 3830 | ** (8 byte or more of payload) only the size of the outermost element is |
| 3831 | ** checked to verify that the BLOB is superficially valid JSONB. |
| 3832 | ** |
| 3833 | ** A full JSONB validation is done on smaller BLOBs because those BLOBs might |
| 3834 | ** also be text JSON that has been incorrectly cast into a BLOB. |
| 3835 | ** (See tag-20240123-a and https://sqlite.org/forum/forumpost/012136abd5) |
| 3836 | ** If the BLOB is 9 bytes are larger, then it is not possible for the |
| 3837 | ** superficial size check done here to pass if the input is really text |
| 3838 | ** JSON so we do not need to look deeper in that case. |
| 3839 | ** |
| 3840 | ** Why we only need to do full JSONB validation for smaller BLOBs: |
| 3841 | ** |
| 3842 | ** The first byte of valid JSON text must be one of: '{', '[', '"', ' ', '\n', |
| 3843 | ** '\r', '\t', '-', or a digit '0' through '9'. Of these, only a subset |
| 3844 | ** can also be the first byte of JSONB: '{', '[', and digits '3' |
| 3845 | ** through '9'. In every one of those cases, the payload size is 7 bytes |
| 3846 | ** or less. So if we do full JSONB validation for every BLOB where the |
| 3847 | ** payload is less than 7 bytes, we will never get a false positive for |
| 3848 | ** JSONB on an input that is really text JSON. |
| 3849 | */ |
| 3850 | static int jsonArgIsJsonb(sqlite3_value *pArg, JsonParse *p){ |
| 3851 | u32 n, sz = 0; |
| 3852 | u8 c; |
| 3853 | if( sqlite3_value_type(pArg)!=SQLITE_BLOB ) return 0; |
| 3854 | p->aBlob = (u8*)sqlite3_value_blob(pArg); |
| 3855 | p->nBlob = (u32)sqlite3_value_bytes(pArg); |
| 3856 | if( p->nBlob>0 |
| 3857 | && ALWAYS(p->aBlob!=0) |
| 3858 | && ((c = p->aBlob[0]) & 0x0f)<=JSONB_OBJECT |
| 3859 | && (n = jsonbPayloadSize(p, 0, &sz))>0 |
| 3860 | && sz+n==p->nBlob |
| 3861 | && ((c & 0x0f)>JSONB_FALSE || sz==0) |
| 3862 | && (sz>7 |
| 3863 | || (c!=0x7b && c!=0x5b && !sqlite3Isdigit(c)) |
| 3864 | || jsonbValidityCheck(p, 0, p->nBlob, 1)==0) |
| 3865 | ){ |
| 3866 | return 1; |
| 3867 | } |
| 3868 | p->aBlob = 0; |
| 3869 | p->nBlob = 0; |
| 3870 | return 0; |
| 3871 | } |
| 3872 | |
| 3873 | /* |
| 3874 | ** Generate a JsonParse object, containing valid JSONB in aBlob and nBlob, |
| 3875 | ** from the SQL function argument pArg. Return a pointer to the new |
| 3876 | ** JsonParse object. |
| 3877 | ** |
| 3878 | ** Ownership of the new JsonParse object is passed to the caller. The |
| 3879 | ** caller should invoke jsonParseFree() on the return value when it |
| 3880 | ** has finished using it. |
| 3881 | ** |
| 3882 | ** If any errors are detected, an appropriate error messages is set |
| 3883 | ** using sqlite3_result_error() or the equivalent and this routine |
| 3884 | ** returns NULL. This routine also returns NULL if the pArg argument |
| 3885 | ** is an SQL NULL value, but no error message is set in that case. This |
| 3886 | ** is so that SQL functions that are given NULL arguments will return |
| 3887 | ** a NULL value. |
| 3888 | */ |
| 3889 | static JsonParse *jsonParseFuncArg( |
| 3890 | sqlite3_context *ctx, |
| 3891 | sqlite3_value *pArg, |
| 3892 | u32 flgs |
| 3893 | ){ |
| 3894 | int eType; /* Datatype of pArg */ |
| 3895 | JsonParse *p = 0; /* Value to be returned */ |
| 3896 | JsonParse *pFromCache = 0; /* Value taken from cache */ |
| 3897 | sqlite3 *db; /* The database connection */ |
| 3898 | |
| 3899 | assert( ctx!=0 ); |
| 3900 | eType = sqlite3_value_type(pArg); |
| 3901 | if( eType==SQLITE_NULL ){ |
| 3902 | return 0; |
| 3903 | } |
| 3904 | if( (flgs & JSON_NOCACHE)==0 ){ |
| 3905 | pFromCache = jsonCacheSearch(ctx, pArg); |
| 3906 | } |
| 3907 | if( pFromCache ){ |
| 3908 | pFromCache->nJPRef++; |
| 3909 | if( (flgs & JSON_EDITABLE)==0 ){ |
| 3910 | return pFromCache; |
| 3911 | } |
| 3912 | } |
| 3913 | db = sqlite3_context_db_handle(ctx); |
| 3914 | rebuild_from_cache: |
| 3915 | p = sqlite3DbMallocZero(db, sizeof(*p)); |
| 3916 | if( p==0 ) goto json_pfa_oom; |
| 3917 | memset(p, 0, sizeof(*p)); |
| 3918 | p->db = db; |
| 3919 | p->nJPRef = 1; |
| 3920 | if( pFromCache!=0 ){ |
| 3921 | u32 nBlob = pFromCache->nBlob; |
| 3922 | p->aBlob = sqlite3DbMallocRaw(db, nBlob); |
| 3923 | if( p->aBlob==0 ) goto json_pfa_oom; |
| 3924 | memcpy(p->aBlob, pFromCache->aBlob, nBlob); |
| 3925 | p->nBlobAlloc = p->nBlob = nBlob; |
| 3926 | p->hasNonstd = pFromCache->hasNonstd; |
| 3927 | jsonParseFree(pFromCache); |
| 3928 | return p; |
| 3929 | } |
| 3930 | if( eType==SQLITE_BLOB ){ |
| 3931 | if( jsonArgIsJsonb(pArg,p) ){ |
| 3932 | if( (flgs & JSON_EDITABLE)!=0 && jsonBlobMakeEditable(p, 0)==0 ){ |
| 3933 | goto json_pfa_oom; |
| 3934 | } |
| 3935 | return p; |
| 3936 | } |
| 3937 | /* If the blob is not valid JSONB, fall through into trying to cast |
| 3938 | ** the blob into text which is then interpreted as JSON. (tag-20240123-a) |
| 3939 | ** |
| 3940 | ** This goes against all historical documentation about how the SQLite |
| 3941 | ** JSON functions were suppose to work. From the beginning, blob was |
| 3942 | ** reserved for expansion and a blob value should have raised an error. |
| 3943 | ** But it did not, due to a bug. And many applications came to depend |
| 3944 | ** upon this buggy behavior, especially when using the CLI and reading |
| 3945 | ** JSON text using readfile(), which returns a blob. For this reason |
| 3946 | ** we will continue to support the bug moving forward. |
| 3947 | ** See for example https://sqlite.org/forum/forumpost/012136abd5292b8d |
| 3948 | */ |
| 3949 | } |
| 3950 | p->zJson = (char*)sqlite3_value_text(pArg); |
| 3951 | p->nJson = sqlite3_value_bytes(pArg); |
| 3952 | if( db->mallocFailed ) goto json_pfa_oom; |
| 3953 | if( p->nJson==0 ) goto json_pfa_malformed; |
| 3954 | assert( p->zJson!=0 ); |
| 3955 | if( jsonConvertTextToBlob(p, (flgs & JSON_KEEPERROR) ? 0 : ctx) ){ |
| 3956 | if( flgs & JSON_KEEPERROR ){ |
| 3957 | p->nErr = 1; |
| 3958 | return p; |
| 3959 | }else{ |
| 3960 | jsonParseFree(p); |
| 3961 | return 0; |
| 3962 | } |
| 3963 | }else{ |
| 3964 | int isRCStr = sqlite3ValueIsOfClass(pArg, sqlite3RCStrUnref); |
| 3965 | int rc; |
| 3966 | if( !isRCStr ){ |
| 3967 | char *zNew = sqlite3RCStrNew( p->nJson ); |
| 3968 | if( zNew==0 ) goto json_pfa_oom; |
| 3969 | memcpy(zNew, p->zJson, p->nJson); |
| 3970 | p->zJson = zNew; |
| 3971 | p->zJson[p->nJson] = 0; |
| 3972 | }else{ |
| 3973 | sqlite3RCStrRef(p->zJson); |
| 3974 | } |
| 3975 | p->bJsonIsRCStr = 1; |
| 3976 | rc = jsonCacheInsert(ctx, p); |
| 3977 | if( rc==SQLITE_NOMEM ) goto json_pfa_oom; |
| 3978 | if( flgs & JSON_EDITABLE ){ |
| 3979 | pFromCache = p; |
| 3980 | p = 0; |
| 3981 | goto rebuild_from_cache; |
| 3982 | } |
| 3983 | } |
| 3984 | return p; |
| 3985 | |
| 3986 | json_pfa_malformed: |
| 3987 | if( flgs & JSON_KEEPERROR ){ |
| 3988 | p->nErr = 1; |
| 3989 | return p; |
| 3990 | }else{ |
| 3991 | jsonParseFree(p); |
| 3992 | sqlite3_result_error(ctx, "malformed JSON", -1); |
| 3993 | return 0; |
| 3994 | } |
| 3995 | |
| 3996 | json_pfa_oom: |
| 3997 | jsonParseFree(pFromCache); |
| 3998 | jsonParseFree(p); |
| 3999 | sqlite3_result_error_nomem(ctx); |
| 4000 | return 0; |
| 4001 | } |
| 4002 | |
| 4003 | /* |
| 4004 | ** Make the return value of a JSON function either the raw JSONB blob |
| 4005 | ** or make it JSON text, depending on whether the JSON_BLOB flag is |
| 4006 | ** set on the function. |
| 4007 | */ |
| 4008 | static void jsonReturnParse( |
| 4009 | sqlite3_context *ctx, |
| 4010 | JsonParse *p |
| 4011 | ){ |
| 4012 | int flgs; |
| 4013 | if( p->oom ){ |
| 4014 | sqlite3_result_error_nomem(ctx); |
| 4015 | return; |
| 4016 | } |
| 4017 | flgs = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); |
| 4018 | if( flgs & JSON_BLOB ){ |
| 4019 | if( p->nBlobAlloc>0 && !p->bReadOnly ){ |
| 4020 | sqlite3_result_blob(ctx, p->aBlob, p->nBlob, SQLITE_DYNAMIC); |
| 4021 | p->nBlobAlloc = 0; |
| 4022 | }else{ |
| 4023 | sqlite3_result_blob(ctx, p->aBlob, p->nBlob, SQLITE_TRANSIENT); |
| 4024 | } |
| 4025 | }else{ |
| 4026 | JsonString s; |
| 4027 | jsonStringInit(&s, ctx); |
| 4028 | p->delta = 0; |
| 4029 | jsonTranslateBlobToText(p, 0, &s); |
| 4030 | jsonReturnString(&s, p, ctx); |
| 4031 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4032 | } |
| 4033 | } |
| 4034 | |
| 4035 | /**************************************************************************** |
| 4036 | ** SQL functions used for testing and debugging |
| 4037 | ****************************************************************************/ |
| 4038 | |
| 4039 | #if SQLITE_DEBUG |
| 4040 | /* |
| 4041 | ** Decode JSONB bytes in aBlob[] starting at iStart through but not |
| 4042 | ** including iEnd. Indent the |
| 4043 | ** content by nIndent spaces. |
| 4044 | */ |
| 4045 | static void jsonDebugPrintBlob( |
| 4046 | JsonParse *pParse, /* JSON content */ |
| 4047 | u32 iStart, /* Start rendering here */ |
| 4048 | u32 iEnd, /* Do not render this byte or any byte after this one */ |
| 4049 | int nIndent, /* Indent by this many spaces */ |
| 4050 | sqlite3_str *pOut /* Generate output into this sqlite3_str object */ |
| 4051 | ){ |
| 4052 | while( iStart<iEnd ){ |
| 4053 | u32 i, n, nn, sz = 0; |
| 4054 | int showContent = 1; |
| 4055 | u8 x = pParse->aBlob[iStart] & 0x0f; |
| 4056 | u32 savedNBlob = pParse->nBlob; |
| 4057 | sqlite3_str_appendf(pOut, "%5d:%*s", iStart, nIndent, ""); |
| 4058 | if( pParse->nBlobAlloc>pParse->nBlob ){ |
| 4059 | pParse->nBlob = pParse->nBlobAlloc; |
| 4060 | } |
| 4061 | nn = n = jsonbPayloadSize(pParse, iStart, &sz); |
| 4062 | if( nn==0 ) nn = 1; |
| 4063 | if( sz>0 && x<JSONB_ARRAY ){ |
| 4064 | nn += sz; |
| 4065 | } |
| 4066 | for(i=0; i<nn; i++){ |
| 4067 | sqlite3_str_appendf(pOut, " %02x", pParse->aBlob[iStart+i]); |
| 4068 | } |
| 4069 | if( n==0 ){ |
| 4070 | sqlite3_str_appendf(pOut, " ERROR invalid node size\n"); |
| 4071 | iStart = n==0 ? iStart+1 : iEnd; |
| 4072 | continue; |
| 4073 | } |
| 4074 | pParse->nBlob = savedNBlob; |
| 4075 | if( iStart+n+sz>iEnd ){ |
| 4076 | iEnd = iStart+n+sz; |
| 4077 | if( iEnd>pParse->nBlob ){ |
| 4078 | if( pParse->nBlobAlloc>0 && iEnd>pParse->nBlobAlloc ){ |
| 4079 | iEnd = pParse->nBlobAlloc; |
| 4080 | }else{ |
| 4081 | iEnd = pParse->nBlob; |
| 4082 | } |
| 4083 | } |
| 4084 | } |
| 4085 | sqlite3_str_appendall(pOut," <-- "); |
| 4086 | switch( x ){ |
| 4087 | case JSONB_NULL: sqlite3_str_appendall(pOut,"null"); break; |
| 4088 | case JSONB_TRUE: sqlite3_str_appendall(pOut,"true"); break; |
| 4089 | case JSONB_FALSE: sqlite3_str_appendall(pOut,"false"); break; |
| 4090 | case JSONB_INT: sqlite3_str_appendall(pOut,"int"); break; |
| 4091 | case JSONB_INT5: sqlite3_str_appendall(pOut,"int5"); break; |
| 4092 | case JSONB_FLOAT: sqlite3_str_appendall(pOut,"float"); break; |
| 4093 | case JSONB_FLOAT5: sqlite3_str_appendall(pOut,"float5"); break; |
| 4094 | case JSONB_TEXT: sqlite3_str_appendall(pOut,"text"); break; |
| 4095 | case JSONB_TEXTJ: sqlite3_str_appendall(pOut,"textj"); break; |
| 4096 | case JSONB_TEXT5: sqlite3_str_appendall(pOut,"text5"); break; |
| 4097 | case JSONB_TEXTRAW: sqlite3_str_appendall(pOut,"textraw"); break; |
| 4098 | case JSONB_ARRAY: { |
| 4099 | sqlite3_str_appendf(pOut,"array, %u bytes\n", sz); |
| 4100 | jsonDebugPrintBlob(pParse, iStart+n, iStart+n+sz, nIndent+2, pOut); |
| 4101 | showContent = 0; |
| 4102 | break; |
| 4103 | } |
| 4104 | case JSONB_OBJECT: { |
| 4105 | sqlite3_str_appendf(pOut, "object, %u bytes\n", sz); |
| 4106 | jsonDebugPrintBlob(pParse, iStart+n, iStart+n+sz, nIndent+2, pOut); |
| 4107 | showContent = 0; |
| 4108 | break; |
| 4109 | } |
| 4110 | default: { |
| 4111 | sqlite3_str_appendall(pOut, "ERROR: unknown node type\n"); |
| 4112 | showContent = 0; |
| 4113 | break; |
| 4114 | } |
| 4115 | } |
| 4116 | if( showContent ){ |
| 4117 | if( sz==0 && x<=JSONB_FALSE ){ |
| 4118 | sqlite3_str_append(pOut, "\n", 1); |
| 4119 | }else{ |
| 4120 | u32 j; |
| 4121 | sqlite3_str_appendall(pOut, ": \""); |
| 4122 | for(j=iStart+n; j<iStart+n+sz; j++){ |
| 4123 | u8 c = pParse->aBlob[j]; |
| 4124 | if( c<0x20 || c>=0x7f ) c = '.'; |
| 4125 | sqlite3_str_append(pOut, (char*)&c, 1); |
| 4126 | } |
| 4127 | sqlite3_str_append(pOut, "\"\n", 2); |
| 4128 | } |
| 4129 | } |
| 4130 | iStart += n + sz; |
| 4131 | } |
| 4132 | } |
| 4133 | static void jsonShowParse(JsonParse *pParse){ |
| 4134 | sqlite3_str out; |
| 4135 | char zBuf[1000]; |
| 4136 | if( pParse==0 ){ |
| 4137 | printf("NULL pointer\n"); |
| 4138 | return; |
| 4139 | }else{ |
| 4140 | printf("nBlobAlloc = %u\n", pParse->nBlobAlloc); |
| 4141 | printf("nBlob = %u\n", pParse->nBlob); |
| 4142 | printf("delta = %d\n", pParse->delta); |
| 4143 | if( pParse->nBlob==0 ) return; |
| 4144 | printf("content (bytes 0..%u):\n", pParse->nBlob-1); |
| 4145 | } |
| 4146 | sqlite3StrAccumInit(&out, 0, zBuf, sizeof(zBuf), 1000000); |
| 4147 | jsonDebugPrintBlob(pParse, 0, pParse->nBlob, 0, &out); |
| 4148 | printf("%s", sqlite3_str_value(&out)); |
| 4149 | sqlite3_str_reset(&out); |
| 4150 | } |
| 4151 | #endif /* SQLITE_DEBUG */ |
| 4152 | |
| 4153 | #ifdef SQLITE_DEBUG |
| 4154 | /* |
| 4155 | ** SQL function: json_parse(JSON) |
| 4156 | ** |
| 4157 | ** Parse JSON using jsonParseFuncArg(). Return text that is a |
| 4158 | ** human-readable dump of the binary JSONB for the input parameter. |
| 4159 | */ |
| 4160 | static void jsonParseFunc( |
| 4161 | sqlite3_context *ctx, |
| 4162 | int argc, |
| 4163 | sqlite3_value **argv |
| 4164 | ){ |
| 4165 | JsonParse *p; /* The parse */ |
| 4166 | sqlite3_str out; |
| 4167 | |
| 4168 | assert( argc>=1 ); |
| 4169 | sqlite3StrAccumInit(&out, 0, 0, 0, 1000000); |
| 4170 | p = jsonParseFuncArg(ctx, argv[0], 0); |
| 4171 | if( p==0 ) return; |
| 4172 | if( argc==1 ){ |
| 4173 | jsonDebugPrintBlob(p, 0, p->nBlob, 0, &out); |
| 4174 | sqlite3_result_text64(ctx,out.zText,out.nChar,SQLITE_TRANSIENT,SQLITE_UTF8); |
| 4175 | }else{ |
| 4176 | jsonShowParse(p); |
| 4177 | } |
| 4178 | jsonParseFree(p); |
| 4179 | sqlite3_str_reset(&out); |
| 4180 | } |
| 4181 | #endif /* SQLITE_DEBUG */ |
| 4182 | |
| 4183 | /**************************************************************************** |
| 4184 | ** Scalar SQL function implementations |
| 4185 | ****************************************************************************/ |
| 4186 | |
| 4187 | /* |
| 4188 | ** Implementation of the json_quote(VALUE) function. Return a JSON value |
| 4189 | ** corresponding to the SQL value input. Mostly this means putting |
| 4190 | ** double-quotes around strings and returning the unquoted string "null" |
| 4191 | ** when given a NULL input. |
| 4192 | */ |
| 4193 | static void jsonQuoteFunc( |
| 4194 | sqlite3_context *ctx, |
| 4195 | int argc, |
| 4196 | sqlite3_value **argv |
| 4197 | ){ |
| 4198 | JsonString jx; |
| 4199 | UNUSED_PARAMETER(argc); |
| 4200 | |
| 4201 | jsonStringInit(&jx, ctx); |
| 4202 | jsonAppendSqlValue(&jx, argv[0]); |
| 4203 | jsonReturnString(&jx, 0, 0); |
| 4204 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4205 | } |
| 4206 | |
| 4207 | /* |
| 4208 | ** Implementation of the json_array(VALUE,...) function. Return a JSON |
| 4209 | ** array that contains all values given in arguments. Or if any argument |
| 4210 | ** is a BLOB, throw an error. |
| 4211 | */ |
| 4212 | static void jsonArrayFunc( |
| 4213 | sqlite3_context *ctx, |
| 4214 | int argc, |
| 4215 | sqlite3_value **argv |
| 4216 | ){ |
| 4217 | int i; |
| 4218 | JsonString jx; |
| 4219 | |
| 4220 | jsonStringInit(&jx, ctx); |
| 4221 | jsonAppendChar(&jx, '['); |
| 4222 | for(i=0; i<argc; i++){ |
| 4223 | jsonAppendSeparator(&jx); |
| 4224 | jsonAppendSqlValue(&jx, argv[i]); |
| 4225 | } |
| 4226 | jsonAppendChar(&jx, ']'); |
| 4227 | jsonReturnString(&jx, 0, 0); |
| 4228 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4229 | } |
| 4230 | |
| 4231 | /* |
| 4232 | ** json_array_length(JSON) |
| 4233 | ** json_array_length(JSON, PATH) |
| 4234 | ** |
| 4235 | ** Return the number of elements in the top-level JSON array. |
| 4236 | ** Return 0 if the input is not a well-formed JSON array. |
| 4237 | */ |
| 4238 | static void jsonArrayLengthFunc( |
| 4239 | sqlite3_context *ctx, |
| 4240 | int argc, |
| 4241 | sqlite3_value **argv |
| 4242 | ){ |
| 4243 | JsonParse *p; /* The parse */ |
| 4244 | sqlite3_int64 cnt = 0; |
| 4245 | u32 i; |
| 4246 | u8 eErr = 0; |
| 4247 | |
| 4248 | p = jsonParseFuncArg(ctx, argv[0], 0); |
| 4249 | if( p==0 ) return; |
| 4250 | if( argc==2 ){ |
| 4251 | const char *zPath = (const char*)sqlite3_value_text(argv[1]); |
| 4252 | if( zPath==0 ){ |
| 4253 | jsonParseFree(p); |
| 4254 | return; |
| 4255 | } |
| 4256 | i = jsonLookupStep(p, 0, zPath[0]=='$' ? zPath+1 : "@", 0); |
| 4257 | if( JSON_LOOKUP_ISERROR(i) ){ |
| 4258 | if( i==JSON_LOOKUP_NOTFOUND ){ |
| 4259 | /* no-op */ |
| 4260 | }else{ |
| 4261 | jsonBadPathError(ctx, zPath, i); |
| 4262 | } |
| 4263 | eErr = 1; |
| 4264 | i = 0; |
| 4265 | } |
| 4266 | }else{ |
| 4267 | i = 0; |
| 4268 | } |
| 4269 | if( (p->aBlob[i] & 0x0f)==JSONB_ARRAY ){ |
| 4270 | cnt = jsonbArrayCount(p, i); |
| 4271 | } |
| 4272 | if( !eErr ) sqlite3_result_int64(ctx, cnt); |
| 4273 | jsonParseFree(p); |
| 4274 | } |
| 4275 | |
| 4276 | /* True if the string is all alphanumerics and underscores */ |
| 4277 | static int jsonAllAlphanum(const char *z, int n){ |
| 4278 | int i; |
| 4279 | for(i=0; i<n && (sqlite3Isalnum(z[i]) || z[i]=='_'); i++){} |
| 4280 | return i==n; |
| 4281 | } |
| 4282 | |
| 4283 | /* |
| 4284 | ** json_extract(JSON, PATH, ...) |
| 4285 | ** "->"(JSON,PATH) |
| 4286 | ** "->>"(JSON,PATH) |
| 4287 | ** |
| 4288 | ** Return the element described by PATH. Return NULL if that PATH element |
| 4289 | ** is not found. |
| 4290 | ** |
| 4291 | ** If JSON_JSON is set or if more that one PATH argument is supplied then |
| 4292 | ** always return a JSON representation of the result. If JSON_SQL is set, |
| 4293 | ** then always return an SQL representation of the result. If neither flag |
| 4294 | ** is present and argc==2, then return JSON for objects and arrays and SQL |
| 4295 | ** for all other values. |
| 4296 | ** |
| 4297 | ** When multiple PATH arguments are supplied, the result is a JSON array |
| 4298 | ** containing the result of each PATH. |
| 4299 | ** |
| 4300 | ** Abbreviated JSON path expressions are allows if JSON_ABPATH, for |
| 4301 | ** compatibility with PG. |
| 4302 | */ |
| 4303 | static void jsonExtractFunc( |
| 4304 | sqlite3_context *ctx, |
| 4305 | int argc, |
| 4306 | sqlite3_value **argv |
| 4307 | ){ |
| 4308 | JsonParse *p = 0; /* The parse */ |
| 4309 | int flags; /* Flags associated with the function */ |
| 4310 | int i; /* Loop counter */ |
| 4311 | JsonString jx; /* String for array result */ |
| 4312 | |
| 4313 | if( argc<2 ) return; |
| 4314 | p = jsonParseFuncArg(ctx, argv[0], 0); |
| 4315 | if( p==0 ) return; |
| 4316 | flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); |
| 4317 | jsonStringInit(&jx, ctx); |
| 4318 | if( argc>2 ){ |
| 4319 | jsonAppendChar(&jx, '['); |
| 4320 | } |
| 4321 | for(i=1; i<argc; i++){ |
| 4322 | /* With a single PATH argument */ |
| 4323 | const char *zPath = (const char*)sqlite3_value_text(argv[i]); |
| 4324 | int nPath; |
| 4325 | u32 j; |
| 4326 | if( zPath==0 ) goto json_extract_error; |
| 4327 | nPath = sqlite3Strlen30(zPath); |
| 4328 | if( zPath[0]=='$' ){ |
| 4329 | j = jsonLookupStep(p, 0, zPath+1, 0); |
| 4330 | }else if( (flags & JSON_ABPATH) ){ |
| 4331 | /* The -> and ->> operators accept abbreviated PATH arguments. This |
| 4332 | ** is mostly for compatibility with PostgreSQL, but also for |
| 4333 | ** convenience. |
| 4334 | ** |
| 4335 | ** NUMBER ==> $[NUMBER] // PG compatible |
| 4336 | ** LABEL ==> $.LABEL // PG compatible |
| 4337 | ** [NUMBER] ==> $[NUMBER] // Not PG. Purely for convenience |
| 4338 | ** |
| 4339 | ** Updated 2024-05-27: If the NUMBER is negative, then PG counts from |
| 4340 | ** the right of the array. Hence for negative NUMBER: |
| 4341 | ** |
| 4342 | ** NUMBER ==> $[#NUMBER] // PG compatible |
| 4343 | */ |
| 4344 | jsonStringInit(&jx, ctx); |
| 4345 | if( sqlite3_value_type(argv[i])==SQLITE_INTEGER ){ |
| 4346 | jsonAppendRawNZ(&jx, "[", 1); |
| 4347 | if( zPath[0]=='-' ) jsonAppendRawNZ(&jx,"#",1); |
| 4348 | jsonAppendRaw(&jx, zPath, nPath); |
| 4349 | jsonAppendRawNZ(&jx, "]", 2); |
| 4350 | }else if( jsonAllAlphanum(zPath, nPath) ){ |
| 4351 | jsonAppendRawNZ(&jx, ".", 1); |
| 4352 | jsonAppendRaw(&jx, zPath, nPath); |
| 4353 | }else if( zPath[0]=='[' && nPath>=3 && zPath[nPath-1]==']' ){ |
| 4354 | jsonAppendRaw(&jx, zPath, nPath); |
| 4355 | }else{ |
| 4356 | jsonAppendRawNZ(&jx, ".\"", 2); |
| 4357 | jsonAppendRaw(&jx, zPath, nPath); |
| 4358 | jsonAppendRawNZ(&jx, "\"", 1); |
| 4359 | } |
| 4360 | jsonStringTerminate(&jx); |
| 4361 | j = jsonLookupStep(p, 0, jx.zBuf, 0); |
| 4362 | jsonStringReset(&jx); |
| 4363 | }else{ |
| 4364 | jsonBadPathError(ctx, zPath, 0); |
| 4365 | goto json_extract_error; |
| 4366 | } |
| 4367 | if( j<p->nBlob ){ |
| 4368 | if( argc==2 ){ |
| 4369 | if( flags & JSON_JSON ){ |
| 4370 | jsonStringInit(&jx, ctx); |
| 4371 | jsonTranslateBlobToText(p, j, &jx); |
| 4372 | jsonReturnString(&jx, 0, 0); |
| 4373 | jsonStringReset(&jx); |
| 4374 | assert( (flags & JSON_BLOB)==0 ); |
| 4375 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4376 | }else{ |
| 4377 | jsonReturnFromBlob(p, j, ctx, 0); |
| 4378 | if( (flags & (JSON_SQL|JSON_BLOB))==0 |
| 4379 | && (p->aBlob[j]&0x0f)>=JSONB_ARRAY |
| 4380 | ){ |
| 4381 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4382 | } |
| 4383 | } |
| 4384 | }else{ |
| 4385 | jsonAppendSeparator(&jx); |
| 4386 | jsonTranslateBlobToText(p, j, &jx); |
| 4387 | } |
| 4388 | }else if( j==JSON_LOOKUP_NOTFOUND ){ |
| 4389 | if( argc==2 ){ |
| 4390 | goto json_extract_error; /* Return NULL if not found */ |
| 4391 | }else{ |
| 4392 | jsonAppendSeparator(&jx); |
| 4393 | jsonAppendRawNZ(&jx, "null", 4); |
| 4394 | } |
| 4395 | }else{ |
| 4396 | jsonBadPathError(ctx, zPath, j); |
| 4397 | goto json_extract_error; |
| 4398 | } |
| 4399 | } |
| 4400 | if( argc>2 ){ |
| 4401 | jsonAppendChar(&jx, ']'); |
| 4402 | jsonReturnString(&jx, 0, 0); |
| 4403 | if( (flags & JSON_BLOB)==0 ){ |
| 4404 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4405 | } |
| 4406 | } |
| 4407 | json_extract_error: |
| 4408 | jsonStringReset(&jx); |
| 4409 | jsonParseFree(p); |
| 4410 | return; |
| 4411 | } |
| 4412 | |
| 4413 | /* |
| 4414 | ** Return codes for jsonMergePatch() |
| 4415 | */ |
| 4416 | #define JSON_MERGE_OK 0 /* Success */ |
| 4417 | #define JSON_MERGE_BADTARGET 1 /* Malformed TARGET blob */ |
| 4418 | #define JSON_MERGE_BADPATCH 2 /* Malformed PATCH blob */ |
| 4419 | #define JSON_MERGE_OOM 3 /* Out-of-memory condition */ |
| 4420 | #define JSON_MERGE_TOODEEP 4 /* Nested too deep */ |
| 4421 | |
| 4422 | /* |
| 4423 | ** RFC-7396 MergePatch for two JSONB blobs. |
| 4424 | ** |
| 4425 | ** pTarget is the target. pPatch is the patch. The target is updated |
| 4426 | ** in place. The patch is read-only. |
| 4427 | ** |
| 4428 | ** The original RFC-7396 algorithm is this: |
| 4429 | ** |
| 4430 | ** define MergePatch(Target, Patch): |
| 4431 | ** if Patch is an Object: |
| 4432 | ** if Target is not an Object: |
| 4433 | ** Target = {} # Ignore the contents and set it to an empty Object |
| 4434 | ** for each Name/Value pair in Patch: |
| 4435 | ** if Value is null: |
| 4436 | ** if Name exists in Target: |
| 4437 | ** remove the Name/Value pair from Target |
| 4438 | ** else: |
| 4439 | ** Target[Name] = MergePatch(Target[Name], Value) |
| 4440 | ** return Target |
| 4441 | ** else: |
| 4442 | ** return Patch |
| 4443 | ** |
| 4444 | ** Here is an equivalent algorithm restructured to show the actual |
| 4445 | ** implementation: |
| 4446 | ** |
| 4447 | ** 01 define MergePatch(Target, Patch): |
| 4448 | ** 02 if Patch is not an Object: |
| 4449 | ** 03 return Patch |
| 4450 | ** 04 else: // if Patch is an Object |
| 4451 | ** 05 if Target is not an Object: |
| 4452 | ** 06 Target = {} |
| 4453 | ** 07 for each Name/Value pair in Patch: |
| 4454 | ** 08 if Name exists in Target: |
| 4455 | ** 09 if Value is null: |
| 4456 | ** 10 remove the Name/Value pair from Target |
| 4457 | ** 11 else |
| 4458 | ** 12 Target[name] = MergePatch(Target[Name], Value) |
| 4459 | ** 13 else if Value is not NULL: |
| 4460 | ** 14 if Value is not an Object: |
| 4461 | ** 15 Target[name] = Value |
| 4462 | ** 16 else: |
| 4463 | ** 17 Target[name] = MergePatch('{}',value) |
| 4464 | ** 18 return Target |
| 4465 | ** | |
| 4466 | ** ^---- Line numbers referenced in comments in the implementation |
| 4467 | */ |
| 4468 | static int jsonMergePatch( |
| 4469 | JsonParse *pTarget, /* The JSON parser that contains the TARGET */ |
| 4470 | u32 iTarget, /* Index of TARGET in pTarget->aBlob[] */ |
| 4471 | const JsonParse *pPatch, /* The PATCH */ |
| 4472 | u32 iPatch, /* Index of PATCH in pPatch->aBlob[] */ |
| 4473 | u32 iDepth /* Nesting depth */ |
| 4474 | ){ |
| 4475 | u8 x; /* Type of a single node */ |
| 4476 | u32 n, sz=0; /* Return values from jsonbPayloadSize() */ |
| 4477 | u32 iTCursor; /* Cursor position while scanning the target object */ |
| 4478 | u32 iTStart; /* First label in the target object */ |
| 4479 | u32 iTEndBE; /* Original first byte past end of target, before edit */ |
| 4480 | u32 iTEnd; /* Current first byte past end of target */ |
| 4481 | u8 eTLabel; /* Node type of the target label */ |
| 4482 | u32 iTLabel = 0; /* Index of the label */ |
| 4483 | u32 nTLabel = 0; /* Header size in bytes for the target label */ |
| 4484 | u32 szTLabel = 0; /* Size of the target label payload */ |
| 4485 | u32 iTValue = 0; /* Index of the target value */ |
| 4486 | u32 nTValue = 0; /* Header size of the target value */ |
| 4487 | u32 szTValue = 0; /* Payload size for the target value */ |
| 4488 | |
| 4489 | u32 iPCursor; /* Cursor position while scanning the patch */ |
| 4490 | u32 iPEnd; /* First byte past the end of the patch */ |
| 4491 | u8 ePLabel; /* Node type of the patch label */ |
| 4492 | u32 iPLabel; /* Start of patch label */ |
| 4493 | u32 nPLabel; /* Size of header on the patch label */ |
| 4494 | u32 szPLabel; /* Payload size of the patch label */ |
| 4495 | u32 iPValue; /* Start of patch value */ |
| 4496 | u32 nPValue; /* Header size for the patch value */ |
| 4497 | u32 szPValue; /* Payload size of the patch value */ |
| 4498 | |
| 4499 | assert( iTarget>=0 && iTarget<pTarget->nBlob ); |
| 4500 | assert( iPatch>=0 && iPatch<pPatch->nBlob ); |
| 4501 | x = pPatch->aBlob[iPatch] & 0x0f; |
| 4502 | if( x!=JSONB_OBJECT ){ /* Algorithm line 02 */ |
| 4503 | u32 szPatch; /* Total size of the patch, header+payload */ |
| 4504 | u32 szTarget; /* Total size of the target, header+payload */ |
| 4505 | n = jsonbPayloadSize(pPatch, iPatch, &sz); |
| 4506 | szPatch = n+sz; |
| 4507 | sz = 0; |
| 4508 | n = jsonbPayloadSize(pTarget, iTarget, &sz); |
| 4509 | szTarget = n+sz; |
| 4510 | jsonBlobEdit(pTarget, iTarget, szTarget, pPatch->aBlob+iPatch, szPatch); |
| 4511 | return pTarget->oom ? JSON_MERGE_OOM : JSON_MERGE_OK; /* Line 03 */ |
| 4512 | } |
| 4513 | x = pTarget->aBlob[iTarget] & 0x0f; |
| 4514 | if( x!=JSONB_OBJECT ){ /* Algorithm line 05 */ |
| 4515 | n = jsonbPayloadSize(pTarget, iTarget, &sz); |
| 4516 | jsonBlobEdit(pTarget, iTarget+n, sz, 0, 0); |
| 4517 | x = pTarget->aBlob[iTarget]; |
| 4518 | pTarget->aBlob[iTarget] = (x & 0xf0) | JSONB_OBJECT; |
| 4519 | } |
| 4520 | n = jsonbPayloadSize(pPatch, iPatch, &sz); |
| 4521 | if( NEVER(n==0) ) return JSON_MERGE_BADPATCH; |
| 4522 | iPCursor = iPatch+n; |
| 4523 | iPEnd = iPCursor+sz; |
| 4524 | n = jsonbPayloadSize(pTarget, iTarget, &sz); |
| 4525 | if( NEVER(n==0) ) return JSON_MERGE_BADTARGET; |
| 4526 | iTStart = iTarget+n; |
| 4527 | iTEndBE = iTStart+sz; |
| 4528 | |
| 4529 | while( iPCursor<iPEnd ){ /* Algorithm line 07 */ |
| 4530 | iPLabel = iPCursor; |
| 4531 | ePLabel = pPatch->aBlob[iPCursor] & 0x0f; |
| 4532 | if( ePLabel<JSONB_TEXT || ePLabel>JSONB_TEXTRAW ){ |
| 4533 | return JSON_MERGE_BADPATCH; |
| 4534 | } |
| 4535 | nPLabel = jsonbPayloadSize(pPatch, iPCursor, &szPLabel); |
| 4536 | if( nPLabel==0 ) return JSON_MERGE_BADPATCH; |
| 4537 | iPValue = iPCursor + nPLabel + szPLabel; |
| 4538 | if( iPValue>=iPEnd ) return JSON_MERGE_BADPATCH; |
| 4539 | nPValue = jsonbPayloadSize(pPatch, iPValue, &szPValue); |
| 4540 | if( nPValue==0 ) return JSON_MERGE_BADPATCH; |
| 4541 | iPCursor = iPValue + nPValue + szPValue; |
| 4542 | if( iPCursor>iPEnd ) return JSON_MERGE_BADPATCH; |
| 4543 | |
| 4544 | iTCursor = iTStart; |
| 4545 | iTEnd = iTEndBE + pTarget->delta; |
| 4546 | while( iTCursor<iTEnd ){ |
| 4547 | int isEqual; /* true if the patch and target labels match */ |
| 4548 | iTLabel = iTCursor; |
| 4549 | eTLabel = pTarget->aBlob[iTCursor] & 0x0f; |
| 4550 | if( eTLabel<JSONB_TEXT || eTLabel>JSONB_TEXTRAW ){ |
| 4551 | return JSON_MERGE_BADTARGET; |
| 4552 | } |
| 4553 | nTLabel = jsonbPayloadSize(pTarget, iTCursor, &szTLabel); |
| 4554 | if( nTLabel==0 ) return JSON_MERGE_BADTARGET; |
| 4555 | iTValue = iTLabel + nTLabel + szTLabel; |
| 4556 | if( iTValue>=iTEnd ) return JSON_MERGE_BADTARGET; |
| 4557 | nTValue = jsonbPayloadSize(pTarget, iTValue, &szTValue); |
| 4558 | if( nTValue==0 ) return JSON_MERGE_BADTARGET; |
| 4559 | if( iTValue + nTValue + szTValue > iTEnd ) return JSON_MERGE_BADTARGET; |
| 4560 | isEqual = jsonLabelCompare( |
| 4561 | (const char*)&pPatch->aBlob[iPLabel+nPLabel], |
| 4562 | szPLabel, |
| 4563 | (ePLabel==JSONB_TEXT || ePLabel==JSONB_TEXTRAW), |
| 4564 | (const char*)&pTarget->aBlob[iTLabel+nTLabel], |
| 4565 | szTLabel, |
| 4566 | (eTLabel==JSONB_TEXT || eTLabel==JSONB_TEXTRAW)); |
| 4567 | if( isEqual ) break; |
| 4568 | iTCursor = iTValue + nTValue + szTValue; |
| 4569 | } |
| 4570 | x = pPatch->aBlob[iPValue] & 0x0f; |
| 4571 | if( iTCursor<iTEnd ){ |
| 4572 | /* A match was found. Algorithm line 08 */ |
| 4573 | if( x==0 ){ |
| 4574 | /* Patch value is NULL. Algorithm line 09 */ |
| 4575 | jsonBlobEdit(pTarget, iTLabel, nTLabel+szTLabel+nTValue+szTValue, 0,0); |
| 4576 | /* vvvvvv----- No OOM on a delete-only edit */ |
| 4577 | if( NEVER(pTarget->oom) ) return JSON_MERGE_OOM; |
| 4578 | }else{ |
| 4579 | /* Algorithm line 12 */ |
| 4580 | int rc, savedDelta = pTarget->delta; |
| 4581 | pTarget->delta = 0; |
| 4582 | if( iDepth>=JSON_MAX_DEPTH ) return JSON_MERGE_TOODEEP; |
| 4583 | rc = jsonMergePatch(pTarget, iTValue, pPatch, iPValue, iDepth+1); |
| 4584 | if( rc ) return rc; |
| 4585 | pTarget->delta += savedDelta; |
| 4586 | } |
| 4587 | }else if( x>0 ){ /* Algorithm line 13 */ |
| 4588 | /* No match and patch value is not NULL */ |
| 4589 | u32 szNew = szPLabel+nPLabel; |
| 4590 | if( (pPatch->aBlob[iPValue] & 0x0f)!=JSONB_OBJECT ){ /* Line 14 */ |
| 4591 | jsonBlobEdit(pTarget, iTEnd, 0, 0, szPValue+nPValue+szNew); |
| 4592 | if( pTarget->oom ) return JSON_MERGE_OOM; |
| 4593 | memcpy(&pTarget->aBlob[iTEnd], &pPatch->aBlob[iPLabel], szNew); |
| 4594 | memcpy(&pTarget->aBlob[iTEnd+szNew], |
| 4595 | &pPatch->aBlob[iPValue], szPValue+nPValue); |
| 4596 | }else{ |
| 4597 | int rc, savedDelta; |
| 4598 | jsonBlobEdit(pTarget, iTEnd, 0, 0, szNew+1); |
| 4599 | if( pTarget->oom ) return JSON_MERGE_OOM; |
| 4600 | memcpy(&pTarget->aBlob[iTEnd], &pPatch->aBlob[iPLabel], szNew); |
| 4601 | pTarget->aBlob[iTEnd+szNew] = 0x00; |
| 4602 | savedDelta = pTarget->delta; |
| 4603 | pTarget->delta = 0; |
| 4604 | if( iDepth>=JSON_MAX_DEPTH ) return JSON_MERGE_TOODEEP; |
| 4605 | rc = jsonMergePatch(pTarget, iTEnd+szNew,pPatch,iPValue,iDepth+1); |
| 4606 | if( rc ) return rc; |
| 4607 | pTarget->delta += savedDelta; |
| 4608 | } |
| 4609 | } |
| 4610 | } |
| 4611 | if( pTarget->delta ) jsonAfterEditSizeAdjust(pTarget, iTarget); |
| 4612 | return pTarget->oom ? JSON_MERGE_OOM : JSON_MERGE_OK; |
| 4613 | } |
| 4614 | |
| 4615 | |
| 4616 | /* |
| 4617 | ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON |
| 4618 | ** object that is the result of running the RFC 7396 MergePatch() algorithm |
| 4619 | ** on the two arguments. |
| 4620 | */ |
| 4621 | static void jsonPatchFunc( |
| 4622 | sqlite3_context *ctx, |
| 4623 | int argc, |
| 4624 | sqlite3_value **argv |
| 4625 | ){ |
| 4626 | JsonParse *pTarget; /* The TARGET */ |
| 4627 | JsonParse *pPatch; /* The PATCH */ |
| 4628 | int rc; /* Result code */ |
| 4629 | |
| 4630 | UNUSED_PARAMETER(argc); |
| 4631 | assert( argc==2 ); |
| 4632 | pTarget = jsonParseFuncArg(ctx, argv[0], JSON_EDITABLE); |
| 4633 | if( pTarget==0 ) return; |
| 4634 | pPatch = jsonParseFuncArg(ctx, argv[1], 0); |
| 4635 | if( pPatch ){ |
| 4636 | rc = jsonMergePatch(pTarget, 0, pPatch, 0, 0); |
| 4637 | if( rc==JSON_MERGE_OK ){ |
| 4638 | jsonReturnParse(ctx, pTarget); |
| 4639 | }else if( rc==JSON_MERGE_OOM ){ |
| 4640 | sqlite3_result_error_nomem(ctx); |
| 4641 | }else if( rc==JSON_MERGE_TOODEEP ){ |
| 4642 | sqlite3_result_error(ctx, "JSON nested too deep", -1); |
| 4643 | }else{ |
| 4644 | sqlite3_result_error(ctx, "malformed JSON", -1); |
| 4645 | } |
| 4646 | jsonParseFree(pPatch); |
| 4647 | } |
| 4648 | jsonParseFree(pTarget); |
| 4649 | } |
| 4650 | |
| 4651 | |
| 4652 | /* |
| 4653 | ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON |
| 4654 | ** object that contains all name/value given in arguments. Or if any name |
| 4655 | ** is not a string or if any value is a BLOB, throw an error. |
| 4656 | */ |
| 4657 | static void jsonObjectFunc( |
| 4658 | sqlite3_context *ctx, |
| 4659 | int argc, |
| 4660 | sqlite3_value **argv |
| 4661 | ){ |
| 4662 | int i; |
| 4663 | JsonString jx; |
| 4664 | const char *z; |
| 4665 | u32 n; |
| 4666 | |
| 4667 | if( argc&1 ){ |
| 4668 | sqlite3_result_error(ctx, "json_object() requires an even number " |
| 4669 | "of arguments", -1); |
| 4670 | return; |
| 4671 | } |
| 4672 | jsonStringInit(&jx, ctx); |
| 4673 | jsonAppendChar(&jx, '{'); |
| 4674 | for(i=0; i<argc; i+=2){ |
| 4675 | if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){ |
| 4676 | sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1); |
| 4677 | jsonStringReset(&jx); |
| 4678 | return; |
| 4679 | } |
| 4680 | jsonAppendSeparator(&jx); |
| 4681 | z = (const char*)sqlite3_value_text(argv[i]); |
| 4682 | n = sqlite3_value_bytes(argv[i]); |
| 4683 | jsonAppendString(&jx, z, n); |
| 4684 | jsonAppendChar(&jx, ':'); |
| 4685 | jsonAppendSqlValue(&jx, argv[i+1]); |
| 4686 | } |
| 4687 | jsonAppendChar(&jx, '}'); |
| 4688 | jsonReturnString(&jx, 0, 0); |
| 4689 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 4690 | } |
| 4691 | |
| 4692 | |
| 4693 | /* |
| 4694 | ** json_remove(JSON, PATH, ...) |
| 4695 | ** |
| 4696 | ** Remove the named elements from JSON and return the result. malformed |
| 4697 | ** JSON or PATH arguments result in an error. |
| 4698 | */ |
| 4699 | static void jsonRemoveFunc( |
| 4700 | sqlite3_context *ctx, |
| 4701 | int argc, |
| 4702 | sqlite3_value **argv |
| 4703 | ){ |
| 4704 | JsonParse *p; /* The parse */ |
| 4705 | const char *zPath = 0; /* Path of element to be removed */ |
| 4706 | int i; /* Loop counter */ |
| 4707 | u32 rc; /* Subroutine return code */ |
| 4708 | |
| 4709 | if( argc<1 ) return; |
| 4710 | p = jsonParseFuncArg(ctx, argv[0], argc>1 ? JSON_EDITABLE : 0); |
| 4711 | if( p==0 ) return; |
| 4712 | for(i=1; i<argc; i++){ |
| 4713 | zPath = (const char*)sqlite3_value_text(argv[i]); |
| 4714 | if( zPath==0 ){ |
| 4715 | goto json_remove_done; |
| 4716 | } |
| 4717 | if( zPath[0]!='$' ){ |
| 4718 | goto json_remove_patherror; |
| 4719 | } |
| 4720 | if( zPath[1]==0 ){ |
| 4721 | /* json_remove(j,'$') returns NULL */ |
| 4722 | goto json_remove_done; |
| 4723 | } |
| 4724 | p->eEdit = JEDIT_DEL; |
| 4725 | p->delta = 0; |
| 4726 | rc = jsonLookupStep(p, 0, zPath+1, 0); |
| 4727 | if( JSON_LOOKUP_ISERROR(rc) ){ |
| 4728 | if( rc==JSON_LOOKUP_NOTFOUND ){ |
| 4729 | continue; /* No-op */ |
| 4730 | }else{ |
| 4731 | jsonBadPathError(ctx, zPath, rc); |
| 4732 | } |
| 4733 | goto json_remove_done; |
| 4734 | } |
| 4735 | } |
| 4736 | jsonReturnParse(ctx, p); |
| 4737 | jsonParseFree(p); |
| 4738 | return; |
| 4739 | |
| 4740 | json_remove_patherror: |
| 4741 | jsonBadPathError(ctx, zPath, 0); |
| 4742 | |
| 4743 | json_remove_done: |
| 4744 | jsonParseFree(p); |
| 4745 | return; |
| 4746 | } |
| 4747 | |
| 4748 | /* |
| 4749 | ** json_replace(JSON, PATH, VALUE, ...) |
| 4750 | ** |
| 4751 | ** Replace the value at PATH with VALUE. If PATH does not already exist, |
| 4752 | ** this routine is a no-op. If JSON or PATH is malformed, throw an error. |
| 4753 | */ |
| 4754 | static void jsonReplaceFunc( |
| 4755 | sqlite3_context *ctx, |
| 4756 | int argc, |
| 4757 | sqlite3_value **argv |
| 4758 | ){ |
| 4759 | if( argc<1 ) return; |
| 4760 | if( (argc&1)==0 ) { |
| 4761 | jsonWrongNumArgs(ctx, "replace"); |
| 4762 | return; |
| 4763 | } |
| 4764 | jsonInsertIntoBlob(ctx, argc, argv, JEDIT_REPL); |
| 4765 | } |
| 4766 | |
| 4767 | |
| 4768 | /* |
| 4769 | ** json_set(JSON, PATH, VALUE, ...) |
| 4770 | ** |
| 4771 | ** Set the value at PATH to VALUE. Create the PATH if it does not already |
| 4772 | ** exist. Overwrite existing values that do exist. |
| 4773 | ** If JSON or PATH is malformed, throw an error. |
| 4774 | ** |
| 4775 | ** json_insert(JSON, PATH, VALUE, ...) |
| 4776 | ** |
| 4777 | ** Create PATH and initialize it to VALUE. If PATH already exists, this |
| 4778 | ** routine is a no-op. If JSON or PATH is malformed, throw an error. |
| 4779 | */ |
| 4780 | static void jsonSetFunc( |
| 4781 | sqlite3_context *ctx, |
| 4782 | int argc, |
| 4783 | sqlite3_value **argv |
| 4784 | ){ |
| 4785 | int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); |
| 4786 | int eInsType = JSON_INSERT_TYPE(flags); |
| 4787 | static const char *azInsType[] = { "insert", "set", "array_insert" }; |
| 4788 | static const u8 aEditType[] = { JEDIT_INS, JEDIT_SET, JEDIT_AINS }; |
| 4789 | |
| 4790 | if( argc<1 ) return; |
| 4791 | assert( eInsType>=0 && eInsType<=2 ); |
| 4792 | if( (argc&1)==0 ) { |
| 4793 | jsonWrongNumArgs(ctx, azInsType[eInsType]); |
| 4794 | return; |
| 4795 | } |
| 4796 | jsonInsertIntoBlob(ctx, argc, argv, aEditType[eInsType]); |
| 4797 | } |
| 4798 | |
| 4799 | /* |
| 4800 | ** json_type(JSON) |
| 4801 | ** json_type(JSON, PATH) |
| 4802 | ** |
| 4803 | ** Return the top-level "type" of a JSON string. json_type() raises an |
| 4804 | ** error if either the JSON or PATH inputs are not well-formed. |
| 4805 | */ |
| 4806 | static void jsonTypeFunc( |
| 4807 | sqlite3_context *ctx, |
| 4808 | int argc, |
| 4809 | sqlite3_value **argv |
| 4810 | ){ |
| 4811 | JsonParse *p; /* The parse */ |
| 4812 | const char *zPath = 0; |
| 4813 | u32 i; |
| 4814 | |
| 4815 | p = jsonParseFuncArg(ctx, argv[0], 0); |
| 4816 | if( p==0 ) return; |
| 4817 | if( argc==2 ){ |
| 4818 | zPath = (const char*)sqlite3_value_text(argv[1]); |
| 4819 | if( zPath==0 ) goto json_type_done; |
| 4820 | if( zPath[0]!='$' ){ |
| 4821 | jsonBadPathError(ctx, zPath, 0); |
| 4822 | goto json_type_done; |
| 4823 | } |
| 4824 | i = jsonLookupStep(p, 0, zPath+1, 0); |
| 4825 | if( JSON_LOOKUP_ISERROR(i) ){ |
| 4826 | if( i==JSON_LOOKUP_NOTFOUND ){ |
| 4827 | /* no-op */ |
| 4828 | }else{ |
| 4829 | jsonBadPathError(ctx, zPath, i); |
| 4830 | } |
| 4831 | goto json_type_done; |
| 4832 | } |
| 4833 | }else{ |
| 4834 | i = 0; |
| 4835 | } |
| 4836 | sqlite3_result_text(ctx, jsonbType[p->aBlob[i]&0x0f], -1, SQLITE_STATIC); |
| 4837 | json_type_done: |
| 4838 | jsonParseFree(p); |
| 4839 | } |
| 4840 | |
| 4841 | /* |
| 4842 | ** json_pretty(JSON) |
| 4843 | ** json_pretty(JSON, INDENT) |
| 4844 | ** |
| 4845 | ** Return text that is a pretty-printed rendering of the input JSON. |
| 4846 | ** If the argument is not valid JSON, return NULL. |
| 4847 | ** |
| 4848 | ** The INDENT argument is text that is used for indentation. If omitted, |
| 4849 | ** it defaults to four spaces (the same as PostgreSQL). |
| 4850 | */ |
| 4851 | static void jsonPrettyFunc( |
| 4852 | sqlite3_context *ctx, |
| 4853 | int argc, |
| 4854 | sqlite3_value **argv |
| 4855 | ){ |
| 4856 | JsonString s; /* The output string */ |
| 4857 | JsonPretty x; /* Pretty printing context */ |
| 4858 | |
| 4859 | memset(&x, 0, sizeof(x)); |
| 4860 | x.pParse = jsonParseFuncArg(ctx, argv[0], 0); |
| 4861 | if( x.pParse==0 ) return; |
| 4862 | x.pOut = &s; |
| 4863 | jsonStringInit(&s, ctx); |
| 4864 | if( argc==1 || (x.zIndent = (const char*)sqlite3_value_text(argv[1]))==0 ){ |
| 4865 | x.zIndent = " "; |
| 4866 | x.szIndent = 4; |
| 4867 | }else{ |
| 4868 | x.szIndent = (u32)strlen(x.zIndent); |
| 4869 | } |
| 4870 | jsonTranslateBlobToPrettyText(&x, 0); |
| 4871 | jsonReturnString(&s, 0, 0); |
| 4872 | jsonParseFree(x.pParse); |
| 4873 | } |
| 4874 | |
| 4875 | /* |
| 4876 | ** json_valid(JSON) |
| 4877 | ** json_valid(JSON, FLAGS) |
| 4878 | ** |
| 4879 | ** Check the JSON argument to see if it is well-formed. The FLAGS argument |
| 4880 | ** encodes the various constraints on what is meant by "well-formed": |
| 4881 | ** |
| 4882 | ** 0x01 Canonical RFC-8259 JSON text |
| 4883 | ** 0x02 JSON text with optional JSON-5 extensions |
| 4884 | ** 0x04 Superficially appears to be JSONB |
| 4885 | ** 0x08 Strictly well-formed JSONB |
| 4886 | ** |
| 4887 | ** If the FLAGS argument is omitted, it defaults to 1. Useful values for |
| 4888 | ** FLAGS include: |
| 4889 | ** |
| 4890 | ** 1 Strict canonical JSON text |
| 4891 | ** 2 JSON text perhaps with JSON-5 extensions |
| 4892 | ** 4 Superficially appears to be JSONB |
| 4893 | ** 5 Canonical JSON text or superficial JSONB |
| 4894 | ** 6 JSON-5 text or superficial JSONB |
| 4895 | ** 8 Strict JSONB |
| 4896 | ** 9 Canonical JSON text or strict JSONB |
| 4897 | ** 10 JSON-5 text or strict JSONB |
| 4898 | ** |
| 4899 | ** Other flag combinations are redundant. For example, every canonical |
| 4900 | ** JSON text is also well-formed JSON-5 text, so FLAG values 2 and 3 |
| 4901 | ** are the same. Similarly, any input that passes a strict JSONB validation |
| 4902 | ** will also pass the superficial validation so 12 through 15 are the same |
| 4903 | ** as 8 through 11 respectively. |
| 4904 | ** |
| 4905 | ** This routine runs in linear time to validate text and when doing strict |
| 4906 | ** JSONB validation. Superficial JSONB validation is constant time, |
| 4907 | ** assuming the BLOB is already in memory. The performance advantage |
| 4908 | ** of superficial JSONB validation is why that option is provided. |
| 4909 | ** Application developers can choose to do fast superficial validation or |
| 4910 | ** slower strict validation, according to their specific needs. |
| 4911 | ** |
| 4912 | ** Only the lower four bits of the FLAGS argument are currently used. |
| 4913 | ** Higher bits are reserved for future expansion. To facilitate |
| 4914 | ** compatibility, the current implementation raises an error if any bit |
| 4915 | ** in FLAGS is set other than the lower four bits. |
| 4916 | ** |
| 4917 | ** The original circa 2015 implementation of the JSON routines in |
| 4918 | ** SQLite only supported canonical RFC-8259 JSON text and the json_valid() |
| 4919 | ** function only accepted one argument. That is why the default value |
| 4920 | ** for the FLAGS argument is 1, since FLAGS=1 causes this routine to only |
| 4921 | ** recognize canonical RFC-8259 JSON text as valid. The extra FLAGS |
| 4922 | ** argument was added when the JSON routines were extended to support |
| 4923 | ** JSON5-like extensions and binary JSONB stored in BLOBs. |
| 4924 | ** |
| 4925 | ** Return Values: |
| 4926 | ** |
| 4927 | ** * Raise an error if FLAGS is outside the range of 1 to 15. |
| 4928 | ** * Return NULL if the input is NULL |
| 4929 | ** * Return 1 if the input is well-formed. |
| 4930 | ** * Return 0 if the input is not well-formed. |
| 4931 | */ |
| 4932 | static void jsonValidFunc( |
| 4933 | sqlite3_context *ctx, |
| 4934 | int argc, |
| 4935 | sqlite3_value **argv |
| 4936 | ){ |
| 4937 | JsonParse *p; /* The parse */ |
| 4938 | u8 flags = 1; |
| 4939 | u8 res = 0; |
| 4940 | if( argc==2 ){ |
| 4941 | i64 f = sqlite3_value_int64(argv[1]); |
| 4942 | if( f<1 || f>15 ){ |
| 4943 | sqlite3_result_error(ctx, "FLAGS parameter to json_valid() must be" |
| 4944 | " between 1 and 15", -1); |
| 4945 | return; |
| 4946 | } |
| 4947 | flags = f & 0x0f; |
| 4948 | } |
| 4949 | switch( sqlite3_value_type(argv[0]) ){ |
| 4950 | case SQLITE_NULL: { |
| 4951 | #ifdef SQLITE_LEGACY_JSON_VALID |
| 4952 | /* Incorrect legacy behavior was to return FALSE for a NULL input */ |
| 4953 | sqlite3_result_int(ctx, 0); |
| 4954 | #endif |
| 4955 | return; |
| 4956 | } |
| 4957 | case SQLITE_BLOB: { |
| 4958 | JsonParse py; |
| 4959 | memset(&py, 0, sizeof(py)); |
| 4960 | if( jsonArgIsJsonb(argv[0], &py) ){ |
| 4961 | if( flags & 0x04 ){ |
| 4962 | /* Superficial checking only - accomplished by the |
| 4963 | ** jsonArgIsJsonb() call above. */ |
| 4964 | res = 1; |
| 4965 | }else if( flags & 0x08 ){ |
| 4966 | /* Strict checking. Check by translating BLOB->TEXT->BLOB. If |
| 4967 | ** no errors occur, call that a "strict check". */ |
| 4968 | res = 0==jsonbValidityCheck(&py, 0, py.nBlob, 1); |
| 4969 | } |
| 4970 | break; |
| 4971 | } |
| 4972 | /* Fall through into interpreting the input as text. See note |
| 4973 | ** above at tag-20240123-a. */ |
| 4974 | /* no break */ deliberate_fall_through |
| 4975 | } |
| 4976 | default: { |
| 4977 | JsonParse px; |
| 4978 | if( (flags & 0x3)==0 ) break; |
| 4979 | memset(&px, 0, sizeof(px)); |
| 4980 | |
| 4981 | p = jsonParseFuncArg(ctx, argv[0], JSON_KEEPERROR|JSON_NOCACHE); |
| 4982 | if( p ){ |
| 4983 | if( p->oom ){ |
| 4984 | sqlite3_result_error_nomem(ctx); |
| 4985 | }else if( p->nErr ){ |
| 4986 | /* no-op */ |
| 4987 | }else if( (flags & 0x02)!=0 || p->hasNonstd==0 ){ |
| 4988 | res = 1; |
| 4989 | } |
| 4990 | jsonParseFree(p); |
| 4991 | }else{ |
| 4992 | sqlite3_result_error_nomem(ctx); |
| 4993 | } |
| 4994 | break; |
| 4995 | } |
| 4996 | } |
| 4997 | sqlite3_result_int(ctx, res); |
| 4998 | } |
| 4999 | |
| 5000 | /* |
| 5001 | ** json_error_position(JSON) |
| 5002 | ** |
| 5003 | ** If the argument is NULL, return NULL |
| 5004 | ** |
| 5005 | ** If the argument is BLOB, do a full validity check and return non-zero |
| 5006 | ** if the check fails. The return value is the approximate 1-based offset |
| 5007 | ** to the byte of the element that contains the first error. |
| 5008 | ** |
| 5009 | ** Otherwise interpret the argument is TEXT (even if it is numeric) and |
| 5010 | ** return the 1-based character position for where the parser first recognized |
| 5011 | ** that the input was not valid JSON, or return 0 if the input text looks |
| 5012 | ** ok. JSON-5 extensions are accepted. |
| 5013 | */ |
| 5014 | static void jsonErrorFunc( |
| 5015 | sqlite3_context *ctx, |
| 5016 | int argc, |
| 5017 | sqlite3_value **argv |
| 5018 | ){ |
| 5019 | i64 iErrPos = 0; /* Error position to be returned */ |
| 5020 | JsonParse s; |
| 5021 | |
| 5022 | assert( argc==1 ); |
| 5023 | UNUSED_PARAMETER(argc); |
| 5024 | memset(&s, 0, sizeof(s)); |
| 5025 | s.db = sqlite3_context_db_handle(ctx); |
| 5026 | if( jsonArgIsJsonb(argv[0], &s) ){ |
| 5027 | iErrPos = (i64)jsonbValidityCheck(&s, 0, s.nBlob, 1); |
| 5028 | }else{ |
| 5029 | s.zJson = (char*)sqlite3_value_text(argv[0]); |
| 5030 | if( s.zJson==0 ) return; /* NULL input or OOM */ |
| 5031 | s.nJson = sqlite3_value_bytes(argv[0]); |
| 5032 | if( jsonConvertTextToBlob(&s,0) ){ |
| 5033 | if( s.oom ){ |
| 5034 | iErrPos = -1; |
| 5035 | }else{ |
| 5036 | /* Convert byte-offset s.iErr into a character offset */ |
| 5037 | u32 k; |
| 5038 | assert( s.zJson!=0 ); /* Because s.oom is false */ |
| 5039 | for(k=0; k<s.iErr && ALWAYS(s.zJson[k]); k++){ |
| 5040 | if( (s.zJson[k] & 0xc0)!=0x80 ) iErrPos++; |
| 5041 | } |
| 5042 | iErrPos++; |
| 5043 | } |
| 5044 | } |
| 5045 | } |
| 5046 | jsonParseReset(&s); |
| 5047 | if( iErrPos<0 ){ |
| 5048 | sqlite3_result_error_nomem(ctx); |
| 5049 | }else{ |
| 5050 | sqlite3_result_int64(ctx, iErrPos); |
| 5051 | } |
| 5052 | } |
| 5053 | |
| 5054 | /**************************************************************************** |
| 5055 | ** Aggregate SQL function implementations |
| 5056 | ****************************************************************************/ |
| 5057 | /* |
| 5058 | ** json_group_array(VALUE) |
| 5059 | ** |
| 5060 | ** Return a JSON array composed of all values in the aggregate. |
| 5061 | */ |
| 5062 | static void jsonArrayStep( |
| 5063 | sqlite3_context *ctx, |
| 5064 | int argc, |
| 5065 | sqlite3_value **argv |
| 5066 | ){ |
| 5067 | JsonString *pStr; |
| 5068 | UNUSED_PARAMETER(argc); |
| 5069 | pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); |
| 5070 | if( pStr ){ |
| 5071 | if( pStr->zBuf==0 ){ |
| 5072 | jsonStringInit(pStr, ctx); |
| 5073 | jsonAppendChar(pStr, '['); |
| 5074 | }else if( pStr->nUsed>1 ){ |
| 5075 | jsonAppendChar(pStr, ','); |
| 5076 | } |
| 5077 | pStr->pCtx = ctx; |
| 5078 | jsonAppendSqlValue(pStr, argv[0]); |
| 5079 | } |
| 5080 | } |
| 5081 | static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){ |
| 5082 | JsonString *pStr; |
| 5083 | int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); |
| 5084 | pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); |
| 5085 | if( pStr ){ |
| 5086 | pStr->pCtx = ctx; |
| 5087 | jsonAppendRawNZ(pStr, "]", 2); |
| 5088 | jsonStringTrimOneChar(pStr); |
| 5089 | if( pStr->eErr ){ |
| 5090 | jsonReturnString(pStr, 0, 0); |
| 5091 | return; |
| 5092 | }else if( flags & JSON_BLOB ){ |
| 5093 | jsonReturnStringAsBlob(pStr); |
| 5094 | if( isFinal ){ |
| 5095 | if( !pStr->bStatic ) sqlite3RCStrUnref(pStr->zBuf); |
| 5096 | }else{ |
| 5097 | jsonStringTrimOneChar(pStr); |
| 5098 | } |
| 5099 | return; |
| 5100 | }else if( isFinal ){ |
| 5101 | sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, |
| 5102 | pStr->bStatic ? SQLITE_TRANSIENT : |
| 5103 | sqlite3RCStrUnref); |
| 5104 | pStr->bStatic = 1; |
| 5105 | }else{ |
| 5106 | sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); |
| 5107 | jsonStringTrimOneChar(pStr); |
| 5108 | } |
| 5109 | }else if( flags & JSON_BLOB ){ |
| 5110 | static const u8 emptyArray = 0x0b; |
| 5111 | sqlite3_result_blob(ctx, &emptyArray, 1, SQLITE_STATIC); |
| 5112 | }else{ |
| 5113 | sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC); |
| 5114 | } |
| 5115 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 5116 | } |
| 5117 | static void jsonArrayValue(sqlite3_context *ctx){ |
| 5118 | jsonArrayCompute(ctx, 0); |
| 5119 | } |
| 5120 | static void jsonArrayFinal(sqlite3_context *ctx){ |
| 5121 | jsonArrayCompute(ctx, 1); |
| 5122 | } |
| 5123 | |
| 5124 | #ifndef SQLITE_OMIT_WINDOWFUNC |
| 5125 | /* |
| 5126 | ** This method works for both json_group_array() and json_group_object(). |
| 5127 | ** It works by removing the first element of the group by searching forward |
| 5128 | ** to the first comma (",") that is not within a string and deleting all |
| 5129 | ** text through that comma. |
| 5130 | */ |
| 5131 | static void jsonGroupInverse( |
| 5132 | sqlite3_context *ctx, |
| 5133 | int argc, |
| 5134 | sqlite3_value **argv |
| 5135 | ){ |
| 5136 | unsigned int i; |
| 5137 | int inStr = 0; |
| 5138 | int nNest = 0; |
| 5139 | char *z; |
| 5140 | char c; |
| 5141 | JsonString *pStr; |
| 5142 | UNUSED_PARAMETER(argc); |
| 5143 | UNUSED_PARAMETER(argv); |
| 5144 | pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); |
| 5145 | /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will |
| 5146 | ** always have been called to initialize it */ |
| 5147 | if( NEVER(!pStr) ) return; |
| 5148 | z = pStr->zBuf; |
| 5149 | for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){ |
| 5150 | if( c=='"' ){ |
| 5151 | inStr = !inStr; |
| 5152 | }else if( c=='\\' ){ |
| 5153 | i++; |
| 5154 | }else if( !inStr ){ |
| 5155 | if( c=='{' || c=='[' ) nNest++; |
| 5156 | if( c=='}' || c==']' ) nNest--; |
| 5157 | } |
| 5158 | } |
| 5159 | if( i<pStr->nUsed ){ |
| 5160 | pStr->nUsed -= i; |
| 5161 | memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1); |
| 5162 | z[pStr->nUsed] = 0; |
| 5163 | }else{ |
| 5164 | pStr->nUsed = 1; |
| 5165 | } |
| 5166 | } |
| 5167 | #else |
| 5168 | # define jsonGroupInverse 0 |
| 5169 | #endif |
| 5170 | |
| 5171 | |
| 5172 | /* |
| 5173 | ** json_group_obj(NAME,VALUE) |
| 5174 | ** |
| 5175 | ** Return a JSON object composed of all names and values in the aggregate. |
| 5176 | ** |
| 5177 | ** Rows for which NAME is NULL do not result in a new entry. However, we |
| 5178 | ** do initially insert a "@" entry into the growing string for each null entry |
| 5179 | ** and change the first character of the string to "@" to signal that the |
| 5180 | ** string contains null entries. The "@" markers are needed in order to |
| 5181 | ** correctly process xInverse() requests. The initial "@" is converted |
| 5182 | ** back into "{" and the "@" null values are removed by jsonObjectCompute(). |
| 5183 | */ |
| 5184 | static void jsonObjectStep( |
| 5185 | sqlite3_context *ctx, |
| 5186 | int argc, |
| 5187 | sqlite3_value **argv |
| 5188 | ){ |
| 5189 | JsonString *pStr; |
| 5190 | const char *z; |
| 5191 | u32 n; |
| 5192 | UNUSED_PARAMETER(argc); |
| 5193 | pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); |
| 5194 | if( pStr ){ |
| 5195 | z = (const char*)sqlite3_value_text(argv[0]); |
| 5196 | n = sqlite3Strlen30(z); |
| 5197 | if( pStr->zBuf==0 ){ |
| 5198 | jsonStringInit(pStr, ctx); |
| 5199 | jsonAppendChar(pStr, '{'); |
| 5200 | }else if( pStr->nUsed>1 ){ |
| 5201 | jsonAppendChar(pStr, ','); |
| 5202 | } |
| 5203 | pStr->pCtx = ctx; |
| 5204 | if( z!=0 ){ |
| 5205 | jsonAppendString(pStr, z, n); |
| 5206 | jsonAppendChar(pStr, ':'); |
| 5207 | jsonAppendSqlValue(pStr, argv[1]); |
| 5208 | }else{ |
| 5209 | pStr->zBuf[0] = '@'; |
| 5210 | jsonAppendRawNZ(pStr, "@", 1); |
| 5211 | } |
| 5212 | } |
| 5213 | } |
| 5214 | static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){ |
| 5215 | JsonString *pStr; |
| 5216 | int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); |
| 5217 | pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); |
| 5218 | if( pStr ){ |
| 5219 | JsonString *pOgStr = pStr; |
| 5220 | JsonString tmpStr; |
| 5221 | jsonAppendRawNZ(pOgStr, "}", 2); /* Ensure it is zero-terminated */ |
| 5222 | jsonStringTrimOneChar(pOgStr); /* Remove the zero terminator */ |
| 5223 | pStr->pCtx = ctx; |
| 5224 | if( pStr->eErr ){ |
| 5225 | jsonReturnString(pStr, 0, 0); |
| 5226 | return; |
| 5227 | } |
| 5228 | if( pStr->zBuf[0]!='{' ){ |
| 5229 | /* The string contains null entries that need to be removed */ |
| 5230 | u64 i, j; |
| 5231 | int inStr = 0; |
| 5232 | if( !isFinal ){ |
| 5233 | /* Work with a temporary copy of the string if this is not the |
| 5234 | ** final result */ |
| 5235 | jsonStringInit(&tmpStr, ctx); |
| 5236 | jsonAppendRawNZ(&tmpStr, pStr->zBuf, pStr->nUsed+1); |
| 5237 | pStr = &tmpStr; |
| 5238 | if( pStr->eErr ){ |
| 5239 | jsonReturnString(pStr, 0, 0); |
| 5240 | return; |
| 5241 | } |
| 5242 | jsonStringTrimOneChar(pStr); /* Remove zero terminator */ |
| 5243 | } |
| 5244 | /* Fix up the string by changing the initial "@" flag back to |
| 5245 | ** to "{" and removing all subsequence "@" entries, with their |
| 5246 | ** associated comma delimeters. */ |
| 5247 | pStr->zBuf[0] = '{'; |
| 5248 | for(i=j=1; i<pStr->nUsed; i++){ |
| 5249 | char c = pStr->zBuf[i]; |
| 5250 | if( c=='"' ){ |
| 5251 | inStr = !inStr; |
| 5252 | pStr->zBuf[j++] = '"'; |
| 5253 | }else if( c=='\\' ){ |
| 5254 | pStr->zBuf[j++] = '\\'; |
| 5255 | pStr->zBuf[j++] = pStr->zBuf[++i]; |
| 5256 | }else if( c=='@' && !inStr ){ |
| 5257 | assert( i+1<pStr->nUsed ); |
| 5258 | if( pStr->zBuf[i+1]==',' ){ |
| 5259 | i++; |
| 5260 | }else if( pStr->zBuf[j-1]==',' ){ |
| 5261 | j--; |
| 5262 | } |
| 5263 | }else{ |
| 5264 | pStr->zBuf[j++] = c; |
| 5265 | } |
| 5266 | } |
| 5267 | pStr->zBuf[j] = 0; /* Restore zero terminator */ |
| 5268 | pStr->nUsed = j; /* Truncate the string */ |
| 5269 | } |
| 5270 | if( flags & JSON_BLOB ){ |
| 5271 | jsonReturnStringAsBlob(pStr); |
| 5272 | if( isFinal ){ |
| 5273 | if( !pStr->bStatic ) sqlite3RCStrUnref(pStr->zBuf); |
| 5274 | }else{ |
| 5275 | jsonStringTrimOneChar(pOgStr); |
| 5276 | } |
| 5277 | }else if( isFinal ){ |
| 5278 | sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, |
| 5279 | pStr->bStatic ? SQLITE_TRANSIENT : |
| 5280 | sqlite3RCStrUnref); |
| 5281 | pStr->bStatic = 1; |
| 5282 | }else{ |
| 5283 | sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); |
| 5284 | jsonStringTrimOneChar(pOgStr); |
| 5285 | } |
| 5286 | if( pStr!=pOgStr ) jsonStringReset(pStr); |
| 5287 | }else if( flags & JSON_BLOB ){ |
| 5288 | static const unsigned char emptyObject = 0x0c; |
| 5289 | sqlite3_result_blob(ctx, &emptyObject, 1, SQLITE_STATIC); |
| 5290 | }else{ |
| 5291 | sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC); |
| 5292 | } |
| 5293 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 5294 | } |
| 5295 | static void jsonObjectValue(sqlite3_context *ctx){ |
| 5296 | jsonObjectCompute(ctx, 0); |
| 5297 | } |
| 5298 | static void jsonObjectFinal(sqlite3_context *ctx){ |
| 5299 | jsonObjectCompute(ctx, 1); |
| 5300 | } |
| 5301 | |
| 5302 | |
| 5303 | |
| 5304 | #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 5305 | /**************************************************************************** |
| 5306 | ** The json_each virtual table |
| 5307 | ****************************************************************************/ |
| 5308 | typedef struct JsonParent JsonParent; |
| 5309 | struct JsonParent { |
| 5310 | u32 iHead; /* Start of object or array */ |
| 5311 | u32 iValue; /* Start of the value */ |
| 5312 | u32 iEnd; /* First byte past the end */ |
| 5313 | u32 nPath; /* Length of path */ |
| 5314 | i64 iKey; /* Key for JSONB_ARRAY */ |
| 5315 | }; |
| 5316 | |
| 5317 | typedef struct JsonEachCursor JsonEachCursor; |
| 5318 | struct JsonEachCursor { |
| 5319 | sqlite3_vtab_cursor base; /* Base class - must be first */ |
| 5320 | u32 iRowid; /* The rowid */ |
| 5321 | u32 i; /* Index in sParse.aBlob[] of current row */ |
| 5322 | u32 iEnd; /* EOF when i equals or exceeds this value */ |
| 5323 | u32 nRoot; /* Size of the root path in bytes */ |
| 5324 | u8 eType; /* Type of the container for element i */ |
| 5325 | u8 bRecursive; /* True for json_tree(). False for json_each() */ |
| 5326 | u8 eMode; /* 1 for json_each(). 2 for jsonb_each() */ |
| 5327 | u32 nParent; /* Current nesting depth */ |
| 5328 | u32 nParentAlloc; /* Space allocated for aParent[] */ |
| 5329 | JsonParent *aParent; /* Parent elements of i */ |
| 5330 | sqlite3 *db; /* Database connection */ |
| 5331 | JsonString path; /* Current path */ |
| 5332 | JsonParse sParse; /* Parse of the input JSON */ |
| 5333 | }; |
| 5334 | typedef struct JsonEachConnection JsonEachConnection; |
| 5335 | struct JsonEachConnection { |
| 5336 | sqlite3_vtab base; /* Base class - must be first */ |
| 5337 | sqlite3 *db; /* Database connection */ |
| 5338 | u8 eMode; /* 1 for json_each(). 2 for jsonb_each() */ |
| 5339 | u8 bRecursive; /* True for json_tree(). False for json_each() */ |
| 5340 | }; |
| 5341 | |
| 5342 | |
| 5343 | /* Constructor for the json_each virtual table */ |
| 5344 | static int jsonEachConnect( |
| 5345 | sqlite3 *db, |
| 5346 | void *pAux, |
| 5347 | int argc, const char *const*argv, |
| 5348 | sqlite3_vtab **ppVtab, |
| 5349 | char **pzErr |
| 5350 | ){ |
| 5351 | JsonEachConnection *pNew; |
| 5352 | int rc; |
| 5353 | |
| 5354 | /* Column numbers */ |
| 5355 | #define JEACH_KEY 0 |
| 5356 | #define JEACH_VALUE 1 |
| 5357 | #define JEACH_TYPE 2 |
| 5358 | #define JEACH_ATOM 3 |
| 5359 | #define JEACH_ID 4 |
| 5360 | #define JEACH_PARENT 5 |
| 5361 | #define JEACH_FULLKEY 6 |
| 5362 | #define JEACH_PATH 7 |
| 5363 | /* The xBestIndex method assumes that the JSON and ROOT columns are |
| 5364 | ** the last two columns in the table. Should this ever changes, be |
| 5365 | ** sure to update the xBestIndex method. */ |
| 5366 | #define JEACH_JSON 8 |
| 5367 | #define JEACH_ROOT 9 |
| 5368 | |
| 5369 | UNUSED_PARAMETER(pzErr); |
| 5370 | UNUSED_PARAMETER(argv); |
| 5371 | UNUSED_PARAMETER(argc); |
| 5372 | UNUSED_PARAMETER(pAux); |
| 5373 | rc = sqlite3_declare_vtab(db, |
| 5374 | "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path," |
| 5375 | "json HIDDEN,root HIDDEN)"); |
| 5376 | if( rc==SQLITE_OK ){ |
| 5377 | pNew = (JsonEachConnection*)sqlite3DbMallocZero(db, sizeof(*pNew)); |
| 5378 | *ppVtab = (sqlite3_vtab*)pNew; |
| 5379 | if( pNew==0 ) return SQLITE_NOMEM; |
| 5380 | sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); |
| 5381 | pNew->db = db; |
| 5382 | pNew->eMode = argv[0][4]=='b' ? 2 : 1; |
| 5383 | pNew->bRecursive = argv[0][4+pNew->eMode]=='t'; |
| 5384 | } |
| 5385 | return rc; |
| 5386 | } |
| 5387 | |
| 5388 | /* destructor for json_each virtual table */ |
| 5389 | static int jsonEachDisconnect(sqlite3_vtab *pVtab){ |
| 5390 | JsonEachConnection *p = (JsonEachConnection*)pVtab; |
| 5391 | sqlite3DbFree(p->db, pVtab); |
| 5392 | return SQLITE_OK; |
| 5393 | } |
| 5394 | |
| 5395 | /* constructor for a JsonEachCursor object for json_each()/json_tree(). */ |
| 5396 | static int jsonEachOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ |
| 5397 | JsonEachConnection *pVtab = (JsonEachConnection*)p; |
| 5398 | JsonEachCursor *pCur; |
| 5399 | |
| 5400 | UNUSED_PARAMETER(p); |
| 5401 | pCur = sqlite3DbMallocZero(pVtab->db, sizeof(*pCur)); |
| 5402 | if( pCur==0 ) return SQLITE_NOMEM; |
| 5403 | pCur->db = pVtab->db; |
| 5404 | pCur->eMode = pVtab->eMode; |
| 5405 | pCur->bRecursive = pVtab->bRecursive; |
| 5406 | jsonStringZero(&pCur->path); |
| 5407 | *ppCursor = &pCur->base; |
| 5408 | return SQLITE_OK; |
| 5409 | } |
| 5410 | |
| 5411 | /* Reset a JsonEachCursor back to its original state. Free any memory |
| 5412 | ** held. */ |
| 5413 | static void jsonEachCursorReset(JsonEachCursor *p){ |
| 5414 | jsonParseReset(&p->sParse); |
| 5415 | jsonStringReset(&p->path); |
| 5416 | sqlite3DbFree(p->db, p->aParent); |
| 5417 | p->iRowid = 0; |
| 5418 | p->i = 0; |
| 5419 | p->aParent = 0; |
| 5420 | p->nParent = 0; |
| 5421 | p->nParentAlloc = 0; |
| 5422 | p->iEnd = 0; |
| 5423 | p->eType = 0; |
| 5424 | } |
| 5425 | |
| 5426 | /* Destructor for a jsonEachCursor object */ |
| 5427 | static int jsonEachClose(sqlite3_vtab_cursor *cur){ |
| 5428 | JsonEachCursor *p = (JsonEachCursor*)cur; |
| 5429 | jsonEachCursorReset(p); |
| 5430 | |
| 5431 | sqlite3DbFree(p->db, cur); |
| 5432 | return SQLITE_OK; |
| 5433 | } |
| 5434 | |
| 5435 | /* Return TRUE if the jsonEachCursor object has been advanced off the end |
| 5436 | ** of the JSON object */ |
| 5437 | static int jsonEachEof(sqlite3_vtab_cursor *cur){ |
| 5438 | JsonEachCursor *p = (JsonEachCursor*)cur; |
| 5439 | return p->i >= p->iEnd; |
| 5440 | } |
| 5441 | |
| 5442 | /* |
| 5443 | ** If the cursor is currently pointing at the label of a object entry, |
| 5444 | ** then return the index of the value. For all other cases, return the |
| 5445 | ** current pointer position, which is the value. |
| 5446 | */ |
| 5447 | static int jsonSkipLabel(JsonEachCursor *p){ |
| 5448 | if( p->eType==JSONB_OBJECT ){ |
| 5449 | u32 sz = 0; |
| 5450 | u32 n = jsonbPayloadSize(&p->sParse, p->i, &sz); |
| 5451 | sz += p->i + n; |
| 5452 | if( sz >= p->sParse.nBlob ) sz = p->i; |
| 5453 | return sz; |
| 5454 | }else{ |
| 5455 | return p->i; |
| 5456 | } |
| 5457 | } |
| 5458 | |
| 5459 | /* |
| 5460 | ** Append the path name for the current element. |
| 5461 | */ |
| 5462 | static void jsonAppendPathName(JsonEachCursor *p){ |
| 5463 | assert( p->nParent>0 ); |
| 5464 | assert( p->eType==JSONB_ARRAY || p->eType==JSONB_OBJECT ); |
| 5465 | if( p->eType==JSONB_ARRAY ){ |
| 5466 | jsonPrintf(30, &p->path, "[%lld]", p->aParent[p->nParent-1].iKey); |
| 5467 | }else{ |
| 5468 | u32 n, sz = 0, k, i; |
| 5469 | const char *z; |
| 5470 | int needQuote = 0; |
| 5471 | n = jsonbPayloadSize(&p->sParse, p->i, &sz); |
| 5472 | k = p->i + n; |
| 5473 | z = (const char*)&p->sParse.aBlob[k]; |
| 5474 | if( sz==0 || !sqlite3Isalpha(z[0]) ){ |
| 5475 | needQuote = 1; |
| 5476 | }else{ |
| 5477 | for(i=0; i<sz; i++){ |
| 5478 | if( !sqlite3Isalnum(z[i]) ){ |
| 5479 | needQuote = 1; |
| 5480 | break; |
| 5481 | } |
| 5482 | } |
| 5483 | } |
| 5484 | if( needQuote ){ |
| 5485 | jsonPrintf(sz+4,&p->path,".\"%.*s\"", sz, z); |
| 5486 | }else{ |
| 5487 | jsonPrintf(sz+2,&p->path,".%.*s", sz, z); |
| 5488 | } |
| 5489 | } |
| 5490 | } |
| 5491 | |
| 5492 | /* Report a "malformed JSON" or OOM error against the cursor. |
| 5493 | */ |
| 5494 | static int jsonEachMalformedInput(sqlite3_vtab_cursor *cur){ |
| 5495 | sqlite3_free(cur->pVtab->zErrMsg); |
| 5496 | cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON"); |
| 5497 | jsonEachCursorReset((JsonEachCursor*)cur); |
| 5498 | return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; |
| 5499 | } |
| 5500 | |
| 5501 | /* Advance the cursor to the next element for json_tree() */ |
| 5502 | static int jsonEachNext(sqlite3_vtab_cursor *cur){ |
| 5503 | JsonEachCursor *p = (JsonEachCursor*)cur; |
| 5504 | int rc = SQLITE_OK; |
| 5505 | if( p->bRecursive ){ |
| 5506 | u8 x; |
| 5507 | u8 levelChange = 0; |
| 5508 | u32 n, sz = 0; |
| 5509 | u32 i = jsonSkipLabel(p); |
| 5510 | x = p->sParse.aBlob[i] & 0x0f; |
| 5511 | n = jsonbPayloadSize(&p->sParse, i, &sz); |
| 5512 | if( n==0 )return jsonEachMalformedInput(cur); |
| 5513 | if( x==JSONB_OBJECT || x==JSONB_ARRAY ){ |
| 5514 | JsonParent *pParent; |
| 5515 | if( p->nParent>=p->nParentAlloc ){ |
| 5516 | JsonParent *pNew; |
| 5517 | u64 nNew; |
| 5518 | nNew = p->nParentAlloc*2 + 3; |
| 5519 | pNew = sqlite3DbRealloc(p->db, p->aParent, sizeof(JsonParent)*nNew); |
| 5520 | if( pNew==0 ) return SQLITE_NOMEM; |
| 5521 | p->nParentAlloc = (u32)nNew; |
| 5522 | p->aParent = pNew; |
| 5523 | } |
| 5524 | levelChange = 1; |
| 5525 | pParent = &p->aParent[p->nParent]; |
| 5526 | pParent->iHead = p->i; |
| 5527 | pParent->iValue = i; |
| 5528 | pParent->iEnd = i + n + sz; |
| 5529 | pParent->iKey = -1; |
| 5530 | pParent->nPath = (u32)p->path.nUsed; |
| 5531 | if( p->eType && p->nParent ){ |
| 5532 | jsonAppendPathName(p); |
| 5533 | if( p->path.eErr ) rc = SQLITE_NOMEM; |
| 5534 | } |
| 5535 | p->nParent++; |
| 5536 | p->i = i + n; |
| 5537 | }else{ |
| 5538 | p->i = i + n + sz; |
| 5539 | } |
| 5540 | while( p->nParent>0 && p->i >= p->aParent[p->nParent-1].iEnd ){ |
| 5541 | p->nParent--; |
| 5542 | p->path.nUsed = p->aParent[p->nParent].nPath; |
| 5543 | levelChange = 1; |
| 5544 | } |
| 5545 | if( levelChange ){ |
| 5546 | if( p->nParent>0 ){ |
| 5547 | JsonParent *pParent = &p->aParent[p->nParent-1]; |
| 5548 | u32 iVal = pParent->iValue; |
| 5549 | p->eType = p->sParse.aBlob[iVal] & 0x0f; |
| 5550 | }else{ |
| 5551 | p->eType = 0; |
| 5552 | } |
| 5553 | } |
| 5554 | }else{ |
| 5555 | u32 n, sz = 0; |
| 5556 | u32 i = jsonSkipLabel(p); |
| 5557 | n = jsonbPayloadSize(&p->sParse, i, &sz); |
| 5558 | if( n==0 )return jsonEachMalformedInput(cur); |
| 5559 | p->i = i + n + sz; |
| 5560 | } |
| 5561 | if( p->eType==JSONB_ARRAY && p->nParent ){ |
| 5562 | p->aParent[p->nParent-1].iKey++; |
| 5563 | } |
| 5564 | p->iRowid++; |
| 5565 | return rc; |
| 5566 | } |
| 5567 | |
| 5568 | /* Length of the path for rowid==0 in bRecursive mode. |
| 5569 | */ |
| 5570 | static int jsonEachPathLength(JsonEachCursor *p){ |
| 5571 | u32 n = p->path.nUsed; |
| 5572 | char *z = p->path.zBuf; |
| 5573 | if( p->iRowid==0 && p->bRecursive && n>=2 ){ |
| 5574 | while( ALWAYS(n>1) ){ |
| 5575 | n--; |
| 5576 | if( z[n]=='[' || z[n]=='.' ){ |
| 5577 | u32 x; |
| 5578 | char cSaved = z[n]; |
| 5579 | z[n] = 0; |
| 5580 | assert( p->sParse.eEdit==0 ); |
| 5581 | x = jsonLookupStep(&p->sParse, 0, z+1, 0); |
| 5582 | z[n] = cSaved; |
| 5583 | if( !JSON_LOOKUP_ISERROR(x) ) break; |
| 5584 | } |
| 5585 | } |
| 5586 | } |
| 5587 | return n; |
| 5588 | } |
| 5589 | |
| 5590 | /* Return the value of a column */ |
| 5591 | static int jsonEachColumn( |
| 5592 | sqlite3_vtab_cursor *cur, /* The cursor */ |
| 5593 | sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ |
| 5594 | int iColumn /* Which column to return */ |
| 5595 | ){ |
| 5596 | JsonEachCursor *p = (JsonEachCursor*)cur; |
| 5597 | switch( iColumn ){ |
| 5598 | case JEACH_KEY: { |
| 5599 | if( p->nParent==0 ){ |
| 5600 | u32 n, j; |
| 5601 | if( p->nRoot==1 ) break; |
| 5602 | j = jsonEachPathLength(p); |
| 5603 | n = p->nRoot - j; |
| 5604 | if( n==0 ){ |
| 5605 | break; |
| 5606 | }else if( p->path.zBuf[j]=='[' ){ |
| 5607 | i64 x; |
| 5608 | sqlite3Atoi64(&p->path.zBuf[j+1], &x, n-1, SQLITE_UTF8); |
| 5609 | sqlite3_result_int64(ctx, x); |
| 5610 | }else if( p->path.zBuf[j+1]=='"' ){ |
| 5611 | sqlite3_result_text(ctx, &p->path.zBuf[j+2], n-3, SQLITE_TRANSIENT); |
| 5612 | }else{ |
| 5613 | sqlite3_result_text(ctx, &p->path.zBuf[j+1], n-1, SQLITE_TRANSIENT); |
| 5614 | } |
| 5615 | break; |
| 5616 | } |
| 5617 | if( p->eType==JSONB_OBJECT ){ |
| 5618 | jsonReturnFromBlob(&p->sParse, p->i, ctx, 1); |
| 5619 | }else if( p->eType==JSONB_ARRAY ){ |
| 5620 | sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iKey); |
| 5621 | }else{ |
| 5622 | sqlite3_result_error(ctx, "malformed JSON", -1); |
| 5623 | } |
| 5624 | break; |
| 5625 | } |
| 5626 | case JEACH_VALUE: { |
| 5627 | u32 i = jsonSkipLabel(p); |
| 5628 | jsonReturnFromBlob(&p->sParse, i, ctx, p->eMode); |
| 5629 | if( (p->sParse.aBlob[i] & 0x0f)>=JSONB_ARRAY ){ |
| 5630 | sqlite3_result_subtype(ctx, JSON_SUBTYPE); |
| 5631 | } |
| 5632 | break; |
| 5633 | } |
| 5634 | case JEACH_TYPE: { |
| 5635 | u32 i = jsonSkipLabel(p); |
| 5636 | u8 eType = p->sParse.aBlob[i] & 0x0f; |
| 5637 | sqlite3_result_text(ctx, jsonbType[eType], -1, SQLITE_STATIC); |
| 5638 | break; |
| 5639 | } |
| 5640 | case JEACH_ATOM: { |
| 5641 | u32 i = jsonSkipLabel(p); |
| 5642 | if( (p->sParse.aBlob[i] & 0x0f)<JSONB_ARRAY ){ |
| 5643 | jsonReturnFromBlob(&p->sParse, i, ctx, 1); |
| 5644 | } |
| 5645 | break; |
| 5646 | } |
| 5647 | case JEACH_ID: { |
| 5648 | sqlite3_result_int64(ctx, (sqlite3_int64)p->i); |
| 5649 | break; |
| 5650 | } |
| 5651 | case JEACH_PARENT: { |
| 5652 | if( p->nParent>0 && p->bRecursive ){ |
| 5653 | sqlite3_result_int64(ctx, p->aParent[p->nParent-1].iHead); |
| 5654 | } |
| 5655 | break; |
| 5656 | } |
| 5657 | case JEACH_FULLKEY: { |
| 5658 | u64 nBase = p->path.nUsed; |
| 5659 | if( p->nParent ) jsonAppendPathName(p); |
| 5660 | sqlite3_result_text64(ctx, p->path.zBuf, p->path.nUsed, |
| 5661 | SQLITE_TRANSIENT, SQLITE_UTF8); |
| 5662 | p->path.nUsed = nBase; |
| 5663 | break; |
| 5664 | } |
| 5665 | case JEACH_PATH: { |
| 5666 | u32 n = jsonEachPathLength(p); |
| 5667 | sqlite3_result_text64(ctx, p->path.zBuf, n, |
| 5668 | SQLITE_TRANSIENT, SQLITE_UTF8); |
| 5669 | break; |
| 5670 | } |
| 5671 | default: { |
| 5672 | sqlite3_result_text(ctx, p->path.zBuf, p->nRoot, SQLITE_TRANSIENT); |
| 5673 | break; |
| 5674 | } |
| 5675 | case JEACH_JSON: { |
| 5676 | if( p->sParse.zJson==0 ){ |
| 5677 | sqlite3_result_blob(ctx, p->sParse.aBlob, p->sParse.nBlob, |
| 5678 | SQLITE_TRANSIENT); |
| 5679 | }else{ |
| 5680 | sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_TRANSIENT); |
| 5681 | } |
| 5682 | break; |
| 5683 | } |
| 5684 | } |
| 5685 | return SQLITE_OK; |
| 5686 | } |
| 5687 | |
| 5688 | /* Return the current rowid value */ |
| 5689 | static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ |
| 5690 | JsonEachCursor *p = (JsonEachCursor*)cur; |
| 5691 | *pRowid = p->iRowid; |
| 5692 | return SQLITE_OK; |
| 5693 | } |
| 5694 | |
| 5695 | /* The query strategy is to look for an equality constraint on the json |
| 5696 | ** column. Without such a constraint, the table cannot operate. idxNum is |
| 5697 | ** 1 if the constraint is found, 3 if the constraint and zRoot are found, |
| 5698 | ** and 0 otherwise. |
| 5699 | */ |
| 5700 | static int jsonEachBestIndex( |
| 5701 | sqlite3_vtab *tab, |
| 5702 | sqlite3_index_info *pIdxInfo |
| 5703 | ){ |
| 5704 | int i; /* Loop counter or computed array index */ |
| 5705 | int aIdx[2]; /* Index of constraints for JSON and ROOT */ |
| 5706 | int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */ |
| 5707 | int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */ |
| 5708 | const struct sqlite3_index_constraint *pConstraint; |
| 5709 | |
| 5710 | /* This implementation assumes that JSON and ROOT are the last two |
| 5711 | ** columns in the table */ |
| 5712 | assert( JEACH_ROOT == JEACH_JSON+1 ); |
| 5713 | UNUSED_PARAMETER(tab); |
| 5714 | aIdx[0] = aIdx[1] = -1; |
| 5715 | pConstraint = pIdxInfo->aConstraint; |
| 5716 | for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ |
| 5717 | int iCol; |
| 5718 | int iMask; |
| 5719 | if( pConstraint->iColumn < JEACH_JSON ) continue; |
| 5720 | iCol = pConstraint->iColumn - JEACH_JSON; |
| 5721 | assert( iCol==0 || iCol==1 ); |
| 5722 | testcase( iCol==0 ); |
| 5723 | iMask = 1 << iCol; |
| 5724 | if( pConstraint->usable==0 ){ |
| 5725 | unusableMask |= iMask; |
| 5726 | }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ |
| 5727 | aIdx[iCol] = i; |
| 5728 | idxMask |= iMask; |
| 5729 | } |
| 5730 | } |
| 5731 | if( pIdxInfo->nOrderBy>0 |
| 5732 | && pIdxInfo->aOrderBy[0].iColumn<0 |
| 5733 | && pIdxInfo->aOrderBy[0].desc==0 |
| 5734 | ){ |
| 5735 | pIdxInfo->orderByConsumed = 1; |
| 5736 | } |
| 5737 | |
| 5738 | if( (unusableMask & ~idxMask)!=0 ){ |
| 5739 | /* If there are any unusable constraints on JSON or ROOT, then reject |
| 5740 | ** this entire plan */ |
| 5741 | return SQLITE_CONSTRAINT; |
| 5742 | } |
| 5743 | if( aIdx[0]<0 ){ |
| 5744 | /* No JSON input. Leave estimatedCost at the huge value that it was |
| 5745 | ** initialized to to discourage the query planner from selecting this |
| 5746 | ** plan. */ |
| 5747 | pIdxInfo->idxNum = 0; |
| 5748 | }else{ |
| 5749 | pIdxInfo->estimatedCost = 1.0; |
| 5750 | i = aIdx[0]; |
| 5751 | pIdxInfo->aConstraintUsage[i].argvIndex = 1; |
| 5752 | pIdxInfo->aConstraintUsage[i].omit = 1; |
| 5753 | if( aIdx[1]<0 ){ |
| 5754 | pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */ |
| 5755 | }else{ |
| 5756 | i = aIdx[1]; |
| 5757 | pIdxInfo->aConstraintUsage[i].argvIndex = 2; |
| 5758 | pIdxInfo->aConstraintUsage[i].omit = 1; |
| 5759 | pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */ |
| 5760 | } |
| 5761 | } |
| 5762 | return SQLITE_OK; |
| 5763 | } |
| 5764 | |
| 5765 | /* Start a search on a new JSON string */ |
| 5766 | static int jsonEachFilter( |
| 5767 | sqlite3_vtab_cursor *cur, |
| 5768 | int idxNum, const char *idxStr, |
| 5769 | int argc, sqlite3_value **argv |
| 5770 | ){ |
| 5771 | JsonEachCursor *p = (JsonEachCursor*)cur; |
| 5772 | const char *zRoot = 0; |
| 5773 | u32 i, n, sz; |
| 5774 | |
| 5775 | UNUSED_PARAMETER(idxStr); |
| 5776 | UNUSED_PARAMETER(argc); |
| 5777 | jsonEachCursorReset(p); |
| 5778 | if( idxNum==0 ) return SQLITE_OK; |
| 5779 | memset(&p->sParse, 0, sizeof(p->sParse)); |
| 5780 | p->sParse.nJPRef = 1; |
| 5781 | p->sParse.db = p->db; |
| 5782 | if( jsonArgIsJsonb(argv[0], &p->sParse) ){ |
| 5783 | /* We have JSONB */ |
| 5784 | }else{ |
| 5785 | p->sParse.zJson = (char*)sqlite3_value_text(argv[0]); |
| 5786 | p->sParse.nJson = sqlite3_value_bytes(argv[0]); |
| 5787 | if( p->sParse.zJson==0 ){ |
| 5788 | p->i = p->iEnd = 0; |
| 5789 | return SQLITE_OK; |
| 5790 | } |
| 5791 | if( jsonConvertTextToBlob(&p->sParse, 0) ){ |
| 5792 | if( p->sParse.oom ){ |
| 5793 | return SQLITE_NOMEM; |
| 5794 | } |
| 5795 | return jsonEachMalformedInput(cur); |
| 5796 | } |
| 5797 | } |
| 5798 | if( idxNum==3 ){ |
| 5799 | zRoot = (const char*)sqlite3_value_text(argv[1]); |
| 5800 | if( zRoot==0 ) return SQLITE_OK; |
| 5801 | if( zRoot[0]!='$' ){ |
| 5802 | sqlite3_free(cur->pVtab->zErrMsg); |
| 5803 | cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot, 0); |
| 5804 | jsonEachCursorReset(p); |
| 5805 | return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; |
| 5806 | } |
| 5807 | p->nRoot = sqlite3Strlen30(zRoot); |
| 5808 | if( zRoot[1]==0 ){ |
| 5809 | i = p->i = 0; |
| 5810 | p->eType = 0; |
| 5811 | }else{ |
| 5812 | i = jsonLookupStep(&p->sParse, 0, zRoot+1, 0); |
| 5813 | if( JSON_LOOKUP_ISERROR(i) ){ |
| 5814 | if( i==JSON_LOOKUP_NOTFOUND ){ |
| 5815 | p->i = 0; |
| 5816 | p->eType = 0; |
| 5817 | p->iEnd = 0; |
| 5818 | return SQLITE_OK; |
| 5819 | } |
| 5820 | sqlite3_free(cur->pVtab->zErrMsg); |
| 5821 | cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot, 0); |
| 5822 | jsonEachCursorReset(p); |
| 5823 | return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; |
| 5824 | } |
| 5825 | if( p->sParse.iLabel ){ |
| 5826 | p->i = p->sParse.iLabel; |
| 5827 | p->eType = JSONB_OBJECT; |
| 5828 | }else{ |
| 5829 | p->i = i; |
| 5830 | p->eType = JSONB_ARRAY; |
| 5831 | } |
| 5832 | } |
| 5833 | jsonAppendRaw(&p->path, zRoot, p->nRoot); |
| 5834 | }else{ |
| 5835 | i = p->i = 0; |
| 5836 | p->eType = 0; |
| 5837 | p->nRoot = 1; |
| 5838 | jsonAppendRaw(&p->path, "$", 1); |
| 5839 | } |
| 5840 | p->nParent = 0; |
| 5841 | n = jsonbPayloadSize(&p->sParse, i, &sz); |
| 5842 | p->iEnd = i+n+sz; |
| 5843 | if( (p->sParse.aBlob[i] & 0x0f)>=JSONB_ARRAY && !p->bRecursive ){ |
| 5844 | p->i = i + n; |
| 5845 | p->eType = p->sParse.aBlob[i] & 0x0f; |
| 5846 | p->aParent = sqlite3DbMallocZero(p->db, sizeof(JsonParent)); |
| 5847 | if( p->aParent==0 ) return SQLITE_NOMEM; |
| 5848 | p->nParent = 1; |
| 5849 | p->nParentAlloc = 1; |
| 5850 | p->aParent[0].iKey = 0; |
| 5851 | p->aParent[0].iEnd = p->iEnd; |
| 5852 | p->aParent[0].iHead = p->i; |
| 5853 | p->aParent[0].iValue = i; |
| 5854 | } |
| 5855 | return SQLITE_OK; |
| 5856 | } |
| 5857 | |
| 5858 | /* The methods of the json_each virtual table */ |
| 5859 | static sqlite3_module jsonEachModule = { |
| 5860 | 0, /* iVersion */ |
| 5861 | 0, /* xCreate */ |
| 5862 | jsonEachConnect, /* xConnect */ |
| 5863 | jsonEachBestIndex, /* xBestIndex */ |
| 5864 | jsonEachDisconnect, /* xDisconnect */ |
| 5865 | 0, /* xDestroy */ |
| 5866 | jsonEachOpen, /* xOpen - open a cursor */ |
| 5867 | jsonEachClose, /* xClose - close a cursor */ |
| 5868 | jsonEachFilter, /* xFilter - configure scan constraints */ |
| 5869 | jsonEachNext, /* xNext - advance a cursor */ |
| 5870 | jsonEachEof, /* xEof - check for end of scan */ |
| 5871 | jsonEachColumn, /* xColumn - read data */ |
| 5872 | jsonEachRowid, /* xRowid - read data */ |
| 5873 | 0, /* xUpdate */ |
| 5874 | 0, /* xBegin */ |
| 5875 | 0, /* xSync */ |
| 5876 | 0, /* xCommit */ |
| 5877 | 0, /* xRollback */ |
| 5878 | 0, /* xFindMethod */ |
| 5879 | 0, /* xRename */ |
| 5880 | 0, /* xSavepoint */ |
| 5881 | 0, /* xRelease */ |
| 5882 | 0, /* xRollbackTo */ |
| 5883 | 0, /* xShadowName */ |
| 5884 | 0 /* xIntegrity */ |
| 5885 | }; |
| 5886 | #endif /* SQLITE_OMIT_VIRTUALTABLE */ |
| 5887 | #endif /* !defined(SQLITE_OMIT_JSON) */ |
| 5888 | |
| 5889 | /* |
| 5890 | ** Register JSON functions. |
| 5891 | */ |
| 5892 | void sqlite3RegisterJsonFunctions(void){ |
| 5893 | #ifndef SQLITE_OMIT_JSON |
| 5894 | static FuncDef aJsonFunc[] = { |
| 5895 | /* sqlite3_result_subtype() ----, ,--- sqlite3_value_subtype() */ |
| 5896 | /* | | */ |
| 5897 | /* Uses cache ------, | | ,---- Returns JSONB */ |
| 5898 | /* | | | | */ |
| 5899 | /* Number of arguments ---, | | | | ,--- Flags */ |
| 5900 | /* | | | | | | */ |
| 5901 | JFUNCTION(json, 1,1,1, 0,0,0, jsonRemoveFunc), |
| 5902 | JFUNCTION(jsonb, 1,1,0, 0,1,0, jsonRemoveFunc), |
| 5903 | JFUNCTION(json_array, -1,0,1, 1,0,0, jsonArrayFunc), |
| 5904 | JFUNCTION(jsonb_array, -1,0,1, 1,1,0, jsonArrayFunc), |
| 5905 | JFUNCTION(json_array_insert, -1,1,1, 1,0,JSON_AINS, jsonSetFunc), |
| 5906 | JFUNCTION(jsonb_array_insert,-1,1,0, 1,1,JSON_AINS, jsonSetFunc), |
| 5907 | JFUNCTION(json_array_length, 1,1,0, 0,0,0, jsonArrayLengthFunc), |
| 5908 | JFUNCTION(json_array_length, 2,1,0, 0,0,0, jsonArrayLengthFunc), |
| 5909 | JFUNCTION(json_error_position,1,1,0, 0,0,0, jsonErrorFunc), |
| 5910 | JFUNCTION(json_extract, -1,1,1, 0,0,0, jsonExtractFunc), |
| 5911 | JFUNCTION(jsonb_extract, -1,1,0, 0,1,0, jsonExtractFunc), |
| 5912 | JFUNCTION(->, 2,1,1, 0,0,JSON_JSON, jsonExtractFunc), |
| 5913 | JFUNCTION(->>, 2,1,0, 0,0,JSON_SQL, jsonExtractFunc), |
| 5914 | JFUNCTION(json_insert, -1,1,1, 1,0,0, jsonSetFunc), |
| 5915 | JFUNCTION(jsonb_insert, -1,1,0, 1,1,0, jsonSetFunc), |
| 5916 | JFUNCTION(json_object, -1,0,1, 1,0,0, jsonObjectFunc), |
| 5917 | JFUNCTION(jsonb_object, -1,0,1, 1,1,0, jsonObjectFunc), |
| 5918 | JFUNCTION(json_patch, 2,1,1, 0,0,0, jsonPatchFunc), |
| 5919 | JFUNCTION(jsonb_patch, 2,1,0, 0,1,0, jsonPatchFunc), |
| 5920 | JFUNCTION(json_pretty, 1,1,0, 0,0,0, jsonPrettyFunc), |
| 5921 | JFUNCTION(json_pretty, 2,1,0, 0,0,0, jsonPrettyFunc), |
| 5922 | JFUNCTION(json_quote, 1,0,1, 1,0,0, jsonQuoteFunc), |
| 5923 | JFUNCTION(json_remove, -1,1,1, 0,0,0, jsonRemoveFunc), |
| 5924 | JFUNCTION(jsonb_remove, -1,1,0, 0,1,0, jsonRemoveFunc), |
| 5925 | JFUNCTION(json_replace, -1,1,1, 1,0,0, jsonReplaceFunc), |
| 5926 | JFUNCTION(jsonb_replace, -1,1,0, 1,1,0, jsonReplaceFunc), |
| 5927 | JFUNCTION(json_set, -1,1,1, 1,0,JSON_ISSET, jsonSetFunc), |
| 5928 | JFUNCTION(jsonb_set, -1,1,0, 1,1,JSON_ISSET, jsonSetFunc), |
| 5929 | JFUNCTION(json_type, 1,1,0, 0,0,0, jsonTypeFunc), |
| 5930 | JFUNCTION(json_type, 2,1,0, 0,0,0, jsonTypeFunc), |
| 5931 | JFUNCTION(json_valid, 1,1,0, 0,0,0, jsonValidFunc), |
| 5932 | JFUNCTION(json_valid, 2,1,0, 0,0,0, jsonValidFunc), |
| 5933 | #if SQLITE_DEBUG |
| 5934 | JFUNCTION(json_parse, 1,1,0, 0,0,0, jsonParseFunc), |
| 5935 | #endif |
| 5936 | WAGGREGATE(json_group_array, 1, 0, 0, |
| 5937 | jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse, |
| 5938 | SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8| |
| 5939 | SQLITE_DETERMINISTIC), |
| 5940 | WAGGREGATE(jsonb_group_array, 1, JSON_BLOB, 0, |
| 5941 | jsonArrayStep, jsonArrayFinal, jsonArrayValue, jsonGroupInverse, |
| 5942 | SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC), |
| 5943 | WAGGREGATE(json_group_object, 2, 0, 0, |
| 5944 | jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse, |
| 5945 | SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8|SQLITE_DETERMINISTIC), |
| 5946 | WAGGREGATE(jsonb_group_object,2, JSON_BLOB, 0, |
| 5947 | jsonObjectStep, jsonObjectFinal, jsonObjectValue, jsonGroupInverse, |
| 5948 | SQLITE_SUBTYPE|SQLITE_RESULT_SUBTYPE|SQLITE_UTF8| |
| 5949 | SQLITE_DETERMINISTIC) |
| 5950 | }; |
| 5951 | sqlite3InsertBuiltinFuncs(aJsonFunc, ArraySize(aJsonFunc)); |
| 5952 | #endif |
| 5953 | } |
| 5954 | |
| 5955 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) |
| 5956 | /* |
| 5957 | ** Register the JSON table-valued function named zName and return a |
| 5958 | ** pointer to its Module object. Return NULL if something goes wrong. |
| 5959 | */ |
| 5960 | Module *sqlite3JsonVtabRegister(sqlite3 *db, const char *zName){ |
| 5961 | unsigned int i; |
| 5962 | static const char *azModule[] = { |
| 5963 | "json_each", "json_tree", "jsonb_each", "jsonb_tree" |
| 5964 | }; |
| 5965 | assert( sqlite3HashFind(&db->aModule, zName)==0 ); |
| 5966 | for(i=0; i<sizeof(azModule)/sizeof(azModule[0]); i++){ |
| 5967 | if( sqlite3StrICmp(azModule[i],zName)==0 ){ |
| 5968 | return sqlite3VtabCreateModule(db, azModule[i], &jsonEachModule, 0, 0); |
| 5969 | } |
| 5970 | } |
| 5971 | return 0; |
| 5972 | } |
| 5973 | #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */ |