AryaWu/sqlite
0
1/*2** 2002 February 233**4** The author disclaims copyright to this source code. In place of5** 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** This file contains the C-language implementations for many of the SQL13** functions of SQLite. (Some function, and in particular the date and14** time functions, are implemented separately.)15*/16#include "sqliteInt.h"17#include <stdlib.h>18#include <assert.h>19#ifndef SQLITE_OMIT_FLOATING_POINT20#include <math.h>21#endif22#include "vdbeInt.h"23 24/*25** Return the collating function associated with a function.26*/27static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){28 VdbeOp *pOp;29 assert( context->pVdbe!=0 );30 pOp = &context->pVdbe->aOp[context->iOp-1];31 assert( pOp->opcode==OP_CollSeq );32 assert( pOp->p4type==P4_COLLSEQ );33 return pOp->p4.pColl;34}35 36/*37** Indicate that the accumulator load should be skipped on this38** iteration of the aggregate loop.39*/40static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){41 assert( context->isError<=0 );42 context->isError = -1;43 context->skipFlag = 1;44}45 46/*47** Implementation of the non-aggregate min() and max() functions48*/49static void minmaxFunc(50 sqlite3_context *context,51 int argc,52 sqlite3_value **argv53){54 int i;55 int mask; /* 0 for min() or 0xffffffff for max() */56 int iBest;57 CollSeq *pColl;58 59 assert( argc>1 );60 mask = sqlite3_user_data(context)==0 ? 0 : -1;61 pColl = sqlite3GetFuncCollSeq(context);62 assert( pColl );63 assert( mask==-1 || mask==0 );64 iBest = 0;65 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;66 for(i=1; i<argc; i++){67 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;68 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){69 testcase( mask==0 );70 iBest = i;71 }72 }73 sqlite3_result_value(context, argv[iBest]);74}75 76/*77** Return the type of the argument.78*/79static void typeofFunc(80 sqlite3_context *context,81 int NotUsed,82 sqlite3_value **argv83){84 static const char *azType[] = { "integer", "real", "text", "blob", "null" };85 int i = sqlite3_value_type(argv[0]) - 1;86 UNUSED_PARAMETER(NotUsed);87 assert( i>=0 && i<ArraySize(azType) );88 assert( SQLITE_INTEGER==1 );89 assert( SQLITE_FLOAT==2 );90 assert( SQLITE_TEXT==3 );91 assert( SQLITE_BLOB==4 );92 assert( SQLITE_NULL==5 );93 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns94 ** the datatype code for the initial datatype of the sqlite3_value object95 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,96 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */97 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);98}99 100/* subtype(X)101**102** Return the subtype of X103*/104static void subtypeFunc(105 sqlite3_context *context,106 int argc,107 sqlite3_value **argv108){109 UNUSED_PARAMETER(argc);110 sqlite3_result_int(context, sqlite3_value_subtype(argv[0]));111}112 113/*114** Implementation of the length() function115*/116static void lengthFunc(117 sqlite3_context *context,118 int argc,119 sqlite3_value **argv120){121 assert( argc==1 );122 UNUSED_PARAMETER(argc);123 switch( sqlite3_value_type(argv[0]) ){124 case SQLITE_BLOB:125 case SQLITE_INTEGER:126 case SQLITE_FLOAT: {127 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));128 break;129 }130 case SQLITE_TEXT: {131 const unsigned char *z = sqlite3_value_text(argv[0]);132 const unsigned char *z0;133 unsigned char c;134 if( z==0 ) return;135 z0 = z;136 while( (c = *z)!=0 ){137 z++;138 if( c>=0xc0 ){139 while( (*z & 0xc0)==0x80 ){ z++; z0++; }140 }141 }142 sqlite3_result_int(context, (int)(z-z0));143 break;144 }145 default: {146 sqlite3_result_null(context);147 break;148 }149 }150}151 152/*153** Implementation of the octet_length() function154*/155static void bytelengthFunc(156 sqlite3_context *context,157 int argc,158 sqlite3_value **argv159){160 assert( argc==1 );161 UNUSED_PARAMETER(argc);162 switch( sqlite3_value_type(argv[0]) ){163 case SQLITE_BLOB: {164 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));165 break;166 }167 case SQLITE_INTEGER:168 case SQLITE_FLOAT: {169 i64 m = sqlite3_context_db_handle(context)->enc<=SQLITE_UTF8 ? 1 : 2;170 sqlite3_result_int64(context, sqlite3_value_bytes(argv[0])*m);171 break;172 }173 case SQLITE_TEXT: {174 if( sqlite3_value_encoding(argv[0])<=SQLITE_UTF8 ){175 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));176 }else{177 sqlite3_result_int(context, sqlite3_value_bytes16(argv[0]));178 }179 break;180 }181 default: {182 sqlite3_result_null(context);183 break;184 }185 }186}187 188/*189** Implementation of the abs() function.190**191** IMP: R-23979-26855 The abs(X) function returns the absolute value of192** the numeric argument X.193*/194static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){195 assert( argc==1 );196 UNUSED_PARAMETER(argc);197 switch( sqlite3_value_type(argv[0]) ){198 case SQLITE_INTEGER: {199 i64 iVal = sqlite3_value_int64(argv[0]);200 if( iVal<0 ){201 if( iVal==SMALLEST_INT64 ){202 /* IMP: R-31676-45509 If X is the integer -9223372036854775808203 ** then abs(X) throws an integer overflow error since there is no204 ** equivalent positive 64-bit two complement value. */205 sqlite3_result_error(context, "integer overflow", -1);206 return;207 }208 iVal = -iVal;209 }210 sqlite3_result_int64(context, iVal);211 break;212 }213 case SQLITE_NULL: {214 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */215 sqlite3_result_null(context);216 break;217 }218 default: {219 /* Because sqlite3_value_double() returns 0.0 if the argument is not220 ** something that can be converted into a number, we have:221 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob222 ** that cannot be converted to a numeric value.223 */224 double rVal = sqlite3_value_double(argv[0]);225 if( rVal<0 ) rVal = -rVal;226 sqlite3_result_double(context, rVal);227 break;228 }229 }230}231 232/*233** Implementation of the instr() function.234**235** instr(haystack,needle) finds the first occurrence of needle236** in haystack and returns the number of previous characters plus 1,237** or 0 if needle does not occur within haystack.238**239** If both haystack and needle are BLOBs, then the result is one more than240** the number of bytes in haystack prior to the first occurrence of needle,241** or 0 if needle never occurs in haystack.242*/243static void instrFunc(244 sqlite3_context *context,245 int argc,246 sqlite3_value **argv247){248 const unsigned char *zHaystack;249 const unsigned char *zNeedle;250 int nHaystack;251 int nNeedle;252 int typeHaystack, typeNeedle;253 int N = 1;254 int isText;255 unsigned char firstChar;256 sqlite3_value *pC1 = 0;257 sqlite3_value *pC2 = 0;258 259 UNUSED_PARAMETER(argc);260 typeHaystack = sqlite3_value_type(argv[0]);261 typeNeedle = sqlite3_value_type(argv[1]);262 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;263 nHaystack = sqlite3_value_bytes(argv[0]);264 nNeedle = sqlite3_value_bytes(argv[1]);265 if( nNeedle>0 ){266 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){267 zHaystack = sqlite3_value_blob(argv[0]);268 zNeedle = sqlite3_value_blob(argv[1]);269 isText = 0;270 }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){271 zHaystack = sqlite3_value_text(argv[0]);272 zNeedle = sqlite3_value_text(argv[1]);273 isText = 1;274 }else{275 pC1 = sqlite3_value_dup(argv[0]);276 zHaystack = sqlite3_value_text(pC1);277 if( zHaystack==0 ) goto endInstrOOM;278 nHaystack = sqlite3_value_bytes(pC1);279 pC2 = sqlite3_value_dup(argv[1]);280 zNeedle = sqlite3_value_text(pC2);281 if( zNeedle==0 ) goto endInstrOOM;282 nNeedle = sqlite3_value_bytes(pC2);283 isText = 1;284 }285 if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;286 firstChar = zNeedle[0];287 while( nNeedle<=nHaystack288 && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)289 ){290 N++;291 do{292 nHaystack--;293 zHaystack++;294 }while( isText && (zHaystack[0]&0xc0)==0x80 );295 }296 if( nNeedle>nHaystack ) N = 0;297 }298 sqlite3_result_int(context, N);299endInstr:300 sqlite3_value_free(pC1);301 sqlite3_value_free(pC2);302 return;303endInstrOOM:304 sqlite3_result_error_nomem(context);305 goto endInstr;306}307 308/*309** Implementation of the printf() (a.k.a. format()) SQL function.310*/311static void printfFunc(312 sqlite3_context *context,313 int argc,314 sqlite3_value **argv315){316 PrintfArguments x;317 StrAccum str;318 const char *zFormat;319 int n;320 sqlite3 *db = sqlite3_context_db_handle(context);321 322 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){323 x.nArg = argc-1;324 x.nUsed = 0;325 x.apArg = argv+1;326 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);327 str.printfFlags = SQLITE_PRINTF_SQLFUNC;328 sqlite3_str_appendf(&str, zFormat, &x);329 n = str.nChar;330 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,331 SQLITE_DYNAMIC);332 }333}334 335/*336** Implementation of the substr() function.337**338** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.339** p1 is 1-indexed. So substr(x,1,1) returns the first character340** of x. If x is text, then we actually count UTF-8 characters.341** If x is a blob, then we count bytes.342**343** If p1 is negative, then we begin abs(p1) from the end of x[].344**345** If p2 is negative, return the p2 characters preceding p1.346*/347static void substrFunc(348 sqlite3_context *context,349 int argc,350 sqlite3_value **argv351){352 const unsigned char *z;353 const unsigned char *z2;354 int len;355 int p0type;356 i64 p1, p2;357 358 assert( argc==3 || argc==2 );359 p0type = sqlite3_value_type(argv[0]);360 p1 = sqlite3_value_int64(argv[1]);361 if( p0type==SQLITE_BLOB ){362 len = sqlite3_value_bytes(argv[0]);363 z = sqlite3_value_blob(argv[0]);364 if( z==0 ) return;365 assert( len==sqlite3_value_bytes(argv[0]) );366 }else{367 z = sqlite3_value_text(argv[0]);368 if( z==0 ) return;369 len = 0;370 if( p1<0 ){371 for(z2=z; *z2; len++){372 SQLITE_SKIP_UTF8(z2);373 }374 }375 }376 if( argc==3 ){377 p2 = sqlite3_value_int64(argv[2]);378 if( p2==0 && sqlite3_value_type(argv[2])==SQLITE_NULL ) return;379 }else{380 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];381 }382 if( p1==0 ){383#ifdef SQLITE_SUBSTR_COMPATIBILITY384 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as385 ** as substr(X,1,N) - it returns the first N characters of X. This386 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]387 ** from 2009-02-02 for compatibility of applications that exploited the388 ** old buggy behavior. */389 p1 = 1; /* <rdar://problem/6778339> */390#endif391 if( sqlite3_value_type(argv[1])==SQLITE_NULL ) return;392 }393 if( p1<0 ){394 p1 += len;395 if( p1<0 ){396 if( p2<0 ){397 p2 = 0;398 }else{399 p2 += p1;400 }401 p1 = 0;402 }403 }else if( p1>0 ){404 p1--;405 }else if( p2>0 ){406 p2--;407 }408 if( p2<0 ){409 if( p2<-p1 ){410 p2 = p1;411 }else{412 p2 = -p2;413 }414 p1 -= p2;415 }416 assert( p1>=0 && p2>=0 );417 if( p0type!=SQLITE_BLOB ){418 while( *z && p1 ){419 SQLITE_SKIP_UTF8(z);420 p1--;421 }422 for(z2=z; *z2 && p2; p2--){423 SQLITE_SKIP_UTF8(z2);424 }425 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,426 SQLITE_UTF8);427 }else{428 if( p1>=len ){429 p1 = p2 = 0;430 }else if( p2>len-p1 ){431 p2 = len-p1;432 assert( p2>0 );433 }434 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);435 }436}437 438/*439** Implementation of the round() function440*/441#ifndef SQLITE_OMIT_FLOATING_POINT442static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){443 i64 n = 0;444 double r;445 char *zBuf;446 assert( argc==1 || argc==2 );447 if( argc==2 ){448 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;449 n = sqlite3_value_int64(argv[1]);450 if( n>30 ) n = 30;451 if( n<0 ) n = 0;452 }453 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;454 r = sqlite3_value_double(argv[0]);455 /* If Y==0 and X will fit in a 64-bit int,456 ** handle the rounding directly,457 ** otherwise use printf.458 */459 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){460 /* The value has no fractional part so there is nothing to round */461 }else if( n==0 ){ 462 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));463 }else{464 zBuf = sqlite3_mprintf("%!.*f",(int)n,r);465 if( zBuf==0 ){466 sqlite3_result_error_nomem(context);467 return;468 }469 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);470 sqlite3_free(zBuf);471 }472 sqlite3_result_double(context, r);473}474#endif475 476/*477** Allocate nByte bytes of space using sqlite3Malloc(). If the478** allocation fails, call sqlite3_result_error_nomem() to notify479** the database handle that malloc() has failed and return NULL.480** If nByte is larger than the maximum string or blob length, then481** raise an SQLITE_TOOBIG exception and return NULL.482*/483static void *contextMalloc(sqlite3_context *context, i64 nByte){484 char *z;485 sqlite3 *db = sqlite3_context_db_handle(context);486 assert( nByte>0 );487 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );488 testcase( nByte==(i64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );489 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){490 sqlite3_result_error_toobig(context);491 z = 0;492 }else{493 z = sqlite3Malloc(nByte);494 if( !z ){495 sqlite3_result_error_nomem(context);496 }497 }498 return z;499}500 501/*502** Implementation of the upper() and lower() SQL functions.503*/504static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){505 char *z1;506 const char *z2;507 int i, n;508 UNUSED_PARAMETER(argc);509 z2 = (char*)sqlite3_value_text(argv[0]);510 n = sqlite3_value_bytes(argv[0]);511 /* Verify that the call to _bytes() does not invalidate the _text() pointer */512 assert( z2==(char*)sqlite3_value_text(argv[0]) );513 if( z2 ){514 z1 = contextMalloc(context, ((i64)n)+1);515 if( z1 ){516 for(i=0; i<n; i++){517 z1[i] = (char)sqlite3Toupper(z2[i]);518 }519 sqlite3_result_text(context, z1, n, sqlite3_free);520 }521 }522}523static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){524 char *z1;525 const char *z2;526 int i, n;527 UNUSED_PARAMETER(argc);528 z2 = (char*)sqlite3_value_text(argv[0]);529 n = sqlite3_value_bytes(argv[0]);530 /* Verify that the call to _bytes() does not invalidate the _text() pointer */531 assert( z2==(char*)sqlite3_value_text(argv[0]) );532 if( z2 ){533 z1 = contextMalloc(context, ((i64)n)+1);534 if( z1 ){535 for(i=0; i<n; i++){536 z1[i] = sqlite3Tolower(z2[i]);537 }538 sqlite3_result_text(context, z1, n, sqlite3_free);539 }540 }541}542 543/*544** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented545** as VDBE code so that unused argument values do not have to be computed.546** However, we still need some kind of function implementation for this547** routines in the function table. The noopFunc macro provides this.548** noopFunc will never be called so it doesn't matter what the implementation549** is. We might as well use the "version()" function as a substitute.550*/551#define noopFunc versionFunc /* Substitute function - never called */552 553/*554** Implementation of random(). Return a random integer. 555*/556static void randomFunc(557 sqlite3_context *context,558 int NotUsed,559 sqlite3_value **NotUsed2560){561 sqlite_int64 r;562 UNUSED_PARAMETER2(NotUsed, NotUsed2);563 sqlite3_randomness(sizeof(r), &r);564 if( r<0 ){565 /* We need to prevent a random number of 0x8000000000000000566 ** (or -9223372036854775808) since when you do abs() of that567 ** number of you get the same value back again. To do this568 ** in a way that is testable, mask the sign bit off of negative569 ** values, resulting in a positive value. Then take the570 ** 2s complement of that positive value. The end result can571 ** therefore be no less than -9223372036854775807.572 */573 r = -(r & LARGEST_INT64);574 }575 sqlite3_result_int64(context, r);576}577 578/*579** Implementation of randomblob(N). Return a random blob580** that is N bytes long.581*/582static void randomBlob(583 sqlite3_context *context,584 int argc,585 sqlite3_value **argv586){587 sqlite3_int64 n;588 unsigned char *p;589 assert( argc==1 );590 UNUSED_PARAMETER(argc);591 n = sqlite3_value_int64(argv[0]);592 if( n<1 ){593 n = 1;594 }595 p = contextMalloc(context, n);596 if( p ){597 sqlite3_randomness(n, p);598 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);599 }600}601 602/*603** Implementation of the last_insert_rowid() SQL function. The return604** value is the same as the sqlite3_last_insert_rowid() API function.605*/606static void last_insert_rowid(607 sqlite3_context *context,608 int NotUsed,609 sqlite3_value **NotUsed2610){611 sqlite3 *db = sqlite3_context_db_handle(context);612 UNUSED_PARAMETER2(NotUsed, NotUsed2);613 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a614 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface615 ** function. */616 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));617}618 619/*620** Implementation of the changes() SQL function.621**622** IMP: R-32760-32347 The changes() SQL function is a wrapper623** around the sqlite3_changes64() C/C++ function and hence follows the624** same rules for counting changes.625*/626static void changes(627 sqlite3_context *context,628 int NotUsed,629 sqlite3_value **NotUsed2630){631 sqlite3 *db = sqlite3_context_db_handle(context);632 UNUSED_PARAMETER2(NotUsed, NotUsed2);633 sqlite3_result_int64(context, sqlite3_changes64(db));634}635 636/*637** Implementation of the total_changes() SQL function. The return value is638** the same as the sqlite3_total_changes64() API function.639*/640static void total_changes(641 sqlite3_context *context,642 int NotUsed,643 sqlite3_value **NotUsed2644){645 sqlite3 *db = sqlite3_context_db_handle(context);646 UNUSED_PARAMETER2(NotUsed, NotUsed2);647 /* IMP: R-11217-42568 This function is a wrapper around the648 ** sqlite3_total_changes64() C/C++ interface. */649 sqlite3_result_int64(context, sqlite3_total_changes64(db));650}651 652/*653** A structure defining how to do GLOB-style comparisons.654*/655struct compareInfo {656 u8 matchAll; /* "*" or "%" */657 u8 matchOne; /* "?" or "_" */658 u8 matchSet; /* "[" or 0 */659 u8 noCase; /* true to ignore case differences */660};661 662/*663** For LIKE and GLOB matching on EBCDIC machines, assume that every664** character is exactly one byte in size. Also, provide the Utf8Read()665** macro for fast reading of the next character in the common case where666** the next character is ASCII.667*/668#if defined(SQLITE_EBCDIC)669# define sqlite3Utf8Read(A) (*((*A)++))670# define Utf8Read(A) (*(A++))671#else672# define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))673#endif674 675static const struct compareInfo globInfo = { '*', '?', '[', 0 };676/* The correct SQL-92 behavior is for the LIKE operator to ignore677** case. Thus 'a' LIKE 'A' would be true. */678static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };679/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator680** is case sensitive causing 'a' LIKE 'A' to be false */681static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };682 683/*684** Possible error returns from patternMatch()685*/686#define SQLITE_MATCH 0687#define SQLITE_NOMATCH 1688#define SQLITE_NOWILDCARDMATCH 2689 690/*691** Compare two UTF-8 strings for equality where the first string is692** a GLOB or LIKE expression. Return values:693**694** SQLITE_MATCH: Match695** SQLITE_NOMATCH: No match696** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.697**698** Globbing rules:699**700** '*' Matches any sequence of zero or more characters.701**702** '?' Matches exactly one character.703**704** [...] Matches one character from the enclosed list of705** characters.706**707** [^...] Matches one character not in the enclosed list.708**709** With the [...] and [^...] matching, a ']' character can be included710** in the list by making it the first character after '[' or '^'. A711** range of characters can be specified using '-'. Example:712** "[a-z]" matches any single lower-case letter. To match a '-', make713** it the last character in the list.714**715** Like matching rules:716**717** '%' Matches any sequence of zero or more characters718**719*** '_' Matches any one character720**721** Ec Where E is the "esc" character and c is any other722** character, including '%', '_', and esc, match exactly c.723**724** The comments within this routine usually assume glob matching.725**726** This routine is usually quick, but can be N**2 in the worst case.727*/728static int patternCompare(729 const u8 *zPattern, /* The glob pattern */730 const u8 *zString, /* The string to compare against the glob */731 const struct compareInfo *pInfo, /* Information about how to do the compare */732 u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */733){734 u32 c, c2; /* Next pattern and input string chars */735 u32 matchOne = pInfo->matchOne; /* "?" or "_" */736 u32 matchAll = pInfo->matchAll; /* "*" or "%" */737 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */738 const u8 *zEscaped = 0; /* One past the last escaped input char */739 740 while( (c = Utf8Read(zPattern))!=0 ){741 if( c==matchAll ){ /* Match "*" */742 /* Skip over multiple "*" characters in the pattern. If there743 ** are also "?" characters, skip those as well, but consume a744 ** single character of the input string for each "?" skipped */745 while( (c=Utf8Read(zPattern)) == matchAll746 || (c == matchOne && matchOne!=0) ){747 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){748 return SQLITE_NOWILDCARDMATCH;749 }750 }751 if( c==0 ){752 return SQLITE_MATCH; /* "*" at the end of the pattern matches */753 }else if( c==matchOther ){754 if( pInfo->matchSet==0 ){755 c = sqlite3Utf8Read(&zPattern);756 if( c==0 ) return SQLITE_NOWILDCARDMATCH;757 }else{758 /* "[...]" immediately follows the "*". We have to do a slow759 ** recursive search in this case, but it is an unusual case. */760 assert( matchOther<0x80 ); /* '[' is a single-byte character */761 while( *zString ){762 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);763 if( bMatch!=SQLITE_NOMATCH ) return bMatch;764 SQLITE_SKIP_UTF8(zString);765 }766 return SQLITE_NOWILDCARDMATCH;767 }768 }769 770 /* At this point variable c contains the first character of the771 ** pattern string past the "*". Search in the input string for the772 ** first matching character and recursively continue the match from773 ** that point.774 **775 ** For a case-insensitive search, set variable cx to be the same as776 ** c but in the other case and search the input string for either777 ** c or cx.778 */779 if( c<0x80 ){780 char zStop[3];781 int bMatch;782 if( noCase ){783 zStop[0] = sqlite3Toupper(c);784 zStop[1] = sqlite3Tolower(c);785 zStop[2] = 0;786 }else{787 zStop[0] = c;788 zStop[1] = 0;789 }790 while(1){791 zString += strcspn((const char*)zString, zStop);792 if( zString[0]==0 ) break;793 zString++;794 bMatch = patternCompare(zPattern,zString,pInfo,matchOther);795 if( bMatch!=SQLITE_NOMATCH ) return bMatch;796 }797 }else{798 int bMatch;799 while( (c2 = Utf8Read(zString))!=0 ){800 if( c2!=c ) continue;801 bMatch = patternCompare(zPattern,zString,pInfo,matchOther);802 if( bMatch!=SQLITE_NOMATCH ) return bMatch;803 }804 }805 return SQLITE_NOWILDCARDMATCH;806 }807 if( c==matchOther ){808 if( pInfo->matchSet==0 ){809 c = sqlite3Utf8Read(&zPattern);810 if( c==0 ) return SQLITE_NOMATCH;811 zEscaped = zPattern;812 }else{813 u32 prior_c = 0;814 int seen = 0;815 int invert = 0;816 c = sqlite3Utf8Read(&zString);817 if( c==0 ) return SQLITE_NOMATCH;818 c2 = sqlite3Utf8Read(&zPattern);819 if( c2=='^' ){820 invert = 1;821 c2 = sqlite3Utf8Read(&zPattern);822 }823 if( c2==']' ){824 if( c==']' ) seen = 1;825 c2 = sqlite3Utf8Read(&zPattern);826 }827 while( c2 && c2!=']' ){828 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){829 c2 = sqlite3Utf8Read(&zPattern);830 if( c>=prior_c && c<=c2 ) seen = 1;831 prior_c = 0;832 }else{833 if( c==c2 ){834 seen = 1;835 }836 prior_c = c2;837 }838 c2 = sqlite3Utf8Read(&zPattern);839 }840 if( c2==0 || (seen ^ invert)==0 ){841 return SQLITE_NOMATCH;842 }843 continue;844 }845 }846 c2 = Utf8Read(zString);847 if( c==c2 ) continue;848 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){849 continue;850 }851 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;852 return SQLITE_NOMATCH;853 }854 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;855}856 857/*858** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and859** non-zero if there is no match.860*/861int sqlite3_strglob(const char *zGlobPattern, const char *zString){862 if( zString==0 ){863 return zGlobPattern!=0;864 }else if( zGlobPattern==0 ){865 return 1;866 }else {867 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');868 }869}870 871/*872** The sqlite3_strlike() interface. Return 0 on a match and non-zero for873** a miss - like strcmp().874*/875int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){876 if( zStr==0 ){877 return zPattern!=0;878 }else if( zPattern==0 ){879 return 1;880 }else{881 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);882 }883}884 885/*886** Count the number of times that the LIKE operator (or GLOB which is887** just a variation of LIKE) gets called. This is used for testing888** only.889*/890#ifdef SQLITE_TEST891int sqlite3_like_count = 0;892#endif893 894 895/*896** Implementation of the like() SQL function. This function implements897** the built-in LIKE operator. The first argument to the function is the898** pattern and the second argument is the string. So, the SQL statements:899**900** A LIKE B901**902** is implemented as like(B,A).903**904** This same function (with a different compareInfo structure) computes905** the GLOB operator.906*/907static void likeFunc(908 sqlite3_context *context,909 int argc,910 sqlite3_value **argv911){912 const unsigned char *zA, *zB;913 u32 escape;914 int nPat;915 sqlite3 *db = sqlite3_context_db_handle(context);916 struct compareInfo *pInfo = sqlite3_user_data(context);917 struct compareInfo backupInfo;918 919#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS920 if( sqlite3_value_type(argv[0])==SQLITE_BLOB921 || sqlite3_value_type(argv[1])==SQLITE_BLOB922 ){923#ifdef SQLITE_TEST924 sqlite3_like_count++;925#endif926 sqlite3_result_int(context, 0);927 return;928 }929#endif930 931 /* Limit the length of the LIKE or GLOB pattern to avoid problems932 ** of deep recursion and N*N behavior in patternCompare().933 */934 nPat = sqlite3_value_bytes(argv[0]);935 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );936 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );937 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){938 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);939 return;940 }941 if( argc==3 ){942 /* The escape character string must consist of a single UTF-8 character.943 ** Otherwise, return an error.944 */945 const unsigned char *zEsc = sqlite3_value_text(argv[2]);946 if( zEsc==0 ) return;947 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){948 sqlite3_result_error(context,949 "ESCAPE expression must be a single character", -1);950 return;951 }952 escape = sqlite3Utf8Read(&zEsc);953 if( escape==pInfo->matchAll || escape==pInfo->matchOne ){954 memcpy(&backupInfo, pInfo, sizeof(backupInfo));955 pInfo = &backupInfo;956 if( escape==pInfo->matchAll ) pInfo->matchAll = 0;957 if( escape==pInfo->matchOne ) pInfo->matchOne = 0;958 }959 }else{960 escape = pInfo->matchSet;961 }962 zB = sqlite3_value_text(argv[0]);963 zA = sqlite3_value_text(argv[1]);964 if( zA && zB ){965#ifdef SQLITE_TEST966 sqlite3_like_count++;967#endif968 sqlite3_result_int(context,969 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);970 }971}972 973/*974** Implementation of the NULLIF(x,y) function. The result is the first975** argument if the arguments are different. The result is NULL if the976** arguments are equal to each other.977*/978static void nullifFunc(979 sqlite3_context *context,980 int NotUsed,981 sqlite3_value **argv982){983 CollSeq *pColl = sqlite3GetFuncCollSeq(context);984 UNUSED_PARAMETER(NotUsed);985 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){986 sqlite3_result_value(context, argv[0]);987 }988}989 990/*991** Implementation of the sqlite_version() function. The result is the version992** of the SQLite library that is running.993*/994static void versionFunc(995 sqlite3_context *context,996 int NotUsed,997 sqlite3_value **NotUsed2998){999 UNUSED_PARAMETER2(NotUsed, NotUsed2);1000 /* IMP: R-48699-48617 This function is an SQL wrapper around the1001 ** sqlite3_libversion() C-interface. */1002 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);1003}1004 1005/*1006** Implementation of the sqlite_source_id() function. The result is a string1007** that identifies the particular version of the source code used to build1008** SQLite.1009*/1010static void sourceidFunc(1011 sqlite3_context *context,1012 int NotUsed,1013 sqlite3_value **NotUsed21014){1015 UNUSED_PARAMETER2(NotUsed, NotUsed2);1016 /* IMP: R-24470-31136 This function is an SQL wrapper around the1017 ** sqlite3_sourceid() C interface. */1018 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);1019}1020 1021/*1022** Implementation of the sqlite_log() function. This is a wrapper around1023** sqlite3_log(). The return value is NULL. The function exists purely for1024** its side-effects.1025*/1026static void errlogFunc(1027 sqlite3_context *context,1028 int argc,1029 sqlite3_value **argv1030){1031 UNUSED_PARAMETER(argc);1032 UNUSED_PARAMETER(context);1033 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));1034}1035 1036/*1037** Implementation of the sqlite_compileoption_used() function.1038** The result is an integer that identifies if the compiler option1039** was used to build SQLite.1040*/1041#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS1042static void compileoptionusedFunc(1043 sqlite3_context *context,1044 int argc,1045 sqlite3_value **argv1046){1047 const char *zOptName;1048 assert( argc==1 );1049 UNUSED_PARAMETER(argc);1050 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL1051 ** function is a wrapper around the sqlite3_compileoption_used() C/C++1052 ** function.1053 */1054 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){1055 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));1056 }1057}1058#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */1059 1060/*1061** Implementation of the sqlite_compileoption_get() function.1062** The result is a string that identifies the compiler options1063** used to build SQLite.1064*/1065#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS1066static void compileoptiongetFunc(1067 sqlite3_context *context,1068 int argc,1069 sqlite3_value **argv1070){1071 int n;1072 assert( argc==1 );1073 UNUSED_PARAMETER(argc);1074 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function1075 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.1076 */1077 n = sqlite3_value_int(argv[0]);1078 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);1079}1080#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */1081 1082/* Array for converting from half-bytes (nybbles) into ASCII hex1083** digits. */1084static const char hexdigits[] = {1085 '0', '1', '2', '3', '4', '5', '6', '7',1086 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'1087};1088 1089/*1090** Append to pStr text that is the SQL literal representation of the1091** value contained in pValue.1092*/1093void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue, int bEscape){1094 /* As currently implemented, the string must be initially empty.1095 ** we might relax this requirement in the future, but that will1096 ** require enhancements to the implementation. */1097 assert( pStr!=0 && pStr->nChar==0 );1098 1099 switch( sqlite3_value_type(pValue) ){1100 case SQLITE_FLOAT: {1101 double r1, r2;1102 const char *zVal;1103 r1 = sqlite3_value_double(pValue);1104 sqlite3_str_appendf(pStr, "%!0.15g", r1);1105 zVal = sqlite3_str_value(pStr);1106 if( zVal ){1107 sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);1108 if( r1!=r2 ){1109 sqlite3_str_reset(pStr);1110 sqlite3_str_appendf(pStr, "%!0.20e", r1);1111 }1112 }1113 break;1114 }1115 case SQLITE_INTEGER: {1116 sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue));1117 break;1118 }1119 case SQLITE_BLOB: {1120 char const *zBlob = sqlite3_value_blob(pValue);1121 i64 nBlob = sqlite3_value_bytes(pValue);1122 assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */1123 sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4);1124 if( pStr->accError==0 ){1125 char *zText = pStr->zText;1126 int i;1127 for(i=0; i<nBlob; i++){1128 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];1129 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];1130 }1131 zText[(nBlob*2)+2] = '\'';1132 zText[(nBlob*2)+3] = '\0';1133 zText[0] = 'X';1134 zText[1] = '\'';1135 pStr->nChar = nBlob*2 + 3;1136 }1137 break;1138 }1139 case SQLITE_TEXT: {1140 const unsigned char *zArg = sqlite3_value_text(pValue);1141 sqlite3_str_appendf(pStr, bEscape ? "%#Q" : "%Q", zArg);1142 break;1143 }1144 default: {1145 assert( sqlite3_value_type(pValue)==SQLITE_NULL );1146 sqlite3_str_append(pStr, "NULL", 4);1147 break;1148 }1149 }1150}1151 1152/*1153** Return true if z[] begins with N hexadecimal digits, and write1154** a decoding of those digits into *pVal. Or return false if any1155** one of the first N characters in z[] is not a hexadecimal digit.1156*/1157static int isNHex(const char *z, int N, u32 *pVal){1158 int i;1159 u32 v = 0;1160 for(i=0; i<N; i++){1161 if( !sqlite3Isxdigit(z[i]) ) return 0;1162 v = (v<<4) + sqlite3HexToInt(z[i]);1163 }1164 *pVal = v;1165 return 1;1166}1167 1168/*1169** Implementation of the UNISTR() function.1170**1171** This is intended to be a work-alike of the UNISTR() function in1172** PostgreSQL. Quoting from the PG documentation (PostgreSQL 17 -1173** scraped on 2025-02-22):1174**1175** Evaluate escaped Unicode characters in the argument. Unicode1176** characters can be specified as \XXXX (4 hexadecimal digits),1177** \+XXXXXX (6 hexadecimal digits), \uXXXX (4 hexadecimal digits),1178** or \UXXXXXXXX (8 hexadecimal digits). To specify a backslash,1179** write two backslashes. All other characters are taken literally.1180*/1181static void unistrFunc(1182 sqlite3_context *context,1183 int argc,1184 sqlite3_value **argv1185){1186 char *zOut;1187 const char *zIn;1188 int nIn;1189 int i, j, n;1190 u32 v;1191 1192 assert( argc==1 );1193 UNUSED_PARAMETER( argc );1194 zIn = (const char*)sqlite3_value_text(argv[0]);1195 if( zIn==0 ) return;1196 nIn = sqlite3_value_bytes(argv[0]);1197 zOut = sqlite3_malloc64(nIn+1);1198 if( zOut==0 ){1199 sqlite3_result_error_nomem(context);1200 return;