1 /* 2 ** 2002 February 23 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 ** This file contains the C-language implementations for many of the SQL 13 ** functions of SQLite. (Some function, and in particular the date and 14 ** time functions, are implemented separately.) 15 */ 16 #include "sqliteInt.h" 17 #include <stdlib.h> 18 #include <assert.h> 19 #include <math.h> 20 #include "vdbeInt.h" 21 22 /* 23 ** Return the collating function associated with a function. 24 */ 25 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ 26 VdbeOp *pOp; 27 assert( context->pVdbe!=0 ); 28 pOp = &context->pVdbe->aOp[context->iOp-1]; 29 assert( pOp->opcode==OP_CollSeq ); 30 assert( pOp->p4type==P4_COLLSEQ ); 31 return pOp->p4.pColl; 32 } 33 34 /* 35 ** Indicate that the accumulator load should be skipped on this 36 ** iteration of the aggregate loop. 37 */ 38 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ 39 assert( context->isError<=0 ); 40 context->isError = -1; 41 context->skipFlag = 1; 42 } 43 44 /* 45 ** Implementation of the non-aggregate min() and max() functions 46 */ 47 static void minmaxFunc( 48 sqlite3_context *context, 49 int argc, 50 sqlite3_value **argv 51 ){ 52 int i; 53 int mask; /* 0 for min() or 0xffffffff for max() */ 54 int iBest; 55 CollSeq *pColl; 56 57 assert( argc>1 ); 58 mask = sqlite3_user_data(context)==0 ? 0 : -1; 59 pColl = sqlite3GetFuncCollSeq(context); 60 assert( pColl ); 61 assert( mask==-1 || mask==0 ); 62 iBest = 0; 63 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 64 for(i=1; i<argc; i++){ 65 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return; 66 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){ 67 testcase( mask==0 ); 68 iBest = i; 69 } 70 } 71 sqlite3_result_value(context, argv[iBest]); 72 } 73 74 /* 75 ** Return the type of the argument. 76 */ 77 static void typeofFunc( 78 sqlite3_context *context, 79 int NotUsed, 80 sqlite3_value **argv 81 ){ 82 static const char *azType[] = { "integer", "real", "text", "blob", "null" }; 83 int i = sqlite3_value_type(argv[0]) - 1; 84 UNUSED_PARAMETER(NotUsed); 85 assert( i>=0 && i<ArraySize(azType) ); 86 assert( SQLITE_INTEGER==1 ); 87 assert( SQLITE_FLOAT==2 ); 88 assert( SQLITE_TEXT==3 ); 89 assert( SQLITE_BLOB==4 ); 90 assert( SQLITE_NULL==5 ); 91 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns 92 ** the datatype code for the initial datatype of the sqlite3_value object 93 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT, 94 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */ 95 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC); 96 } 97 98 99 /* 100 ** Implementation of the length() function 101 */ 102 static void lengthFunc( 103 sqlite3_context *context, 104 int argc, 105 sqlite3_value **argv 106 ){ 107 assert( argc==1 ); 108 UNUSED_PARAMETER(argc); 109 switch( sqlite3_value_type(argv[0]) ){ 110 case SQLITE_BLOB: 111 case SQLITE_INTEGER: 112 case SQLITE_FLOAT: { 113 sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); 114 break; 115 } 116 case SQLITE_TEXT: { 117 const unsigned char *z = sqlite3_value_text(argv[0]); 118 const unsigned char *z0; 119 unsigned char c; 120 if( z==0 ) return; 121 z0 = z; 122 while( (c = *z)!=0 ){ 123 z++; 124 if( c>=0xc0 ){ 125 while( (*z & 0xc0)==0x80 ){ z++; z0++; } 126 } 127 } 128 sqlite3_result_int(context, (int)(z-z0)); 129 break; 130 } 131 default: { 132 sqlite3_result_null(context); 133 break; 134 } 135 } 136 } 137 138 /* 139 ** Implementation of the abs() function. 140 ** 141 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of 142 ** the numeric argument X. 143 */ 144 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 145 assert( argc==1 ); 146 UNUSED_PARAMETER(argc); 147 switch( sqlite3_value_type(argv[0]) ){ 148 case SQLITE_INTEGER: { 149 i64 iVal = sqlite3_value_int64(argv[0]); 150 if( iVal<0 ){ 151 if( iVal==SMALLEST_INT64 ){ 152 /* IMP: R-31676-45509 If X is the integer -9223372036854775808 153 ** then abs(X) throws an integer overflow error since there is no 154 ** equivalent positive 64-bit two complement value. */ 155 sqlite3_result_error(context, "integer overflow", -1); 156 return; 157 } 158 iVal = -iVal; 159 } 160 sqlite3_result_int64(context, iVal); 161 break; 162 } 163 case SQLITE_NULL: { 164 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ 165 sqlite3_result_null(context); 166 break; 167 } 168 default: { 169 /* Because sqlite3_value_double() returns 0.0 if the argument is not 170 ** something that can be converted into a number, we have: 171 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob 172 ** that cannot be converted to a numeric value. 173 */ 174 double rVal = sqlite3_value_double(argv[0]); 175 if( rVal<0 ) rVal = -rVal; 176 sqlite3_result_double(context, rVal); 177 break; 178 } 179 } 180 } 181 182 /* 183 ** Implementation of the instr() function. 184 ** 185 ** instr(haystack,needle) finds the first occurrence of needle 186 ** in haystack and returns the number of previous characters plus 1, 187 ** or 0 if needle does not occur within haystack. 188 ** 189 ** If both haystack and needle are BLOBs, then the result is one more than 190 ** the number of bytes in haystack prior to the first occurrence of needle, 191 ** or 0 if needle never occurs in haystack. 192 */ 193 static void instrFunc( 194 sqlite3_context *context, 195 int argc, 196 sqlite3_value **argv 197 ){ 198 const unsigned char *zHaystack; 199 const unsigned char *zNeedle; 200 int nHaystack; 201 int nNeedle; 202 int typeHaystack, typeNeedle; 203 int N = 1; 204 int isText; 205 unsigned char firstChar; 206 207 UNUSED_PARAMETER(argc); 208 typeHaystack = sqlite3_value_type(argv[0]); 209 typeNeedle = sqlite3_value_type(argv[1]); 210 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; 211 nHaystack = sqlite3_value_bytes(argv[0]); 212 nNeedle = sqlite3_value_bytes(argv[1]); 213 if( nNeedle>0 ){ 214 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ 215 zHaystack = sqlite3_value_blob(argv[0]); 216 zNeedle = sqlite3_value_blob(argv[1]); 217 isText = 0; 218 }else{ 219 zHaystack = sqlite3_value_text(argv[0]); 220 zNeedle = sqlite3_value_text(argv[1]); 221 isText = 1; 222 } 223 if( zNeedle==0 || (nHaystack && zHaystack==0) ) return; 224 firstChar = zNeedle[0]; 225 while( nNeedle<=nHaystack 226 && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0) 227 ){ 228 N++; 229 do{ 230 nHaystack--; 231 zHaystack++; 232 }while( isText && (zHaystack[0]&0xc0)==0x80 ); 233 } 234 if( nNeedle>nHaystack ) N = 0; 235 } 236 sqlite3_result_int(context, N); 237 } 238 239 /* 240 ** Implementation of the printf() function. 241 */ 242 static void printfFunc( 243 sqlite3_context *context, 244 int argc, 245 sqlite3_value **argv 246 ){ 247 PrintfArguments x; 248 StrAccum str; 249 const char *zFormat; 250 int n; 251 sqlite3 *db = sqlite3_context_db_handle(context); 252 253 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 254 x.nArg = argc-1; 255 x.nUsed = 0; 256 x.apArg = argv+1; 257 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); 258 str.printfFlags = SQLITE_PRINTF_SQLFUNC; 259 sqlite3_str_appendf(&str, zFormat, &x); 260 n = str.nChar; 261 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, 262 SQLITE_DYNAMIC); 263 } 264 } 265 266 /* 267 ** Implementation of the substr() function. 268 ** 269 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. 270 ** p1 is 1-indexed. So substr(x,1,1) returns the first character 271 ** of x. If x is text, then we actually count UTF-8 characters. 272 ** If x is a blob, then we count bytes. 273 ** 274 ** If p1 is negative, then we begin abs(p1) from the end of x[]. 275 ** 276 ** If p2 is negative, return the p2 characters preceding p1. 277 */ 278 static void substrFunc( 279 sqlite3_context *context, 280 int argc, 281 sqlite3_value **argv 282 ){ 283 const unsigned char *z; 284 const unsigned char *z2; 285 int len; 286 int p0type; 287 i64 p1, p2; 288 int negP2 = 0; 289 290 assert( argc==3 || argc==2 ); 291 if( sqlite3_value_type(argv[1])==SQLITE_NULL 292 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) 293 ){ 294 return; 295 } 296 p0type = sqlite3_value_type(argv[0]); 297 p1 = sqlite3_value_int(argv[1]); 298 if( p0type==SQLITE_BLOB ){ 299 len = sqlite3_value_bytes(argv[0]); 300 z = sqlite3_value_blob(argv[0]); 301 if( z==0 ) return; 302 assert( len==sqlite3_value_bytes(argv[0]) ); 303 }else{ 304 z = sqlite3_value_text(argv[0]); 305 if( z==0 ) return; 306 len = 0; 307 if( p1<0 ){ 308 for(z2=z; *z2; len++){ 309 SQLITE_SKIP_UTF8(z2); 310 } 311 } 312 } 313 #ifdef SQLITE_SUBSTR_COMPATIBILITY 314 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as 315 ** as substr(X,1,N) - it returns the first N characters of X. This 316 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] 317 ** from 2009-02-02 for compatibility of applications that exploited the 318 ** old buggy behavior. */ 319 if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */ 320 #endif 321 if( argc==3 ){ 322 p2 = sqlite3_value_int(argv[2]); 323 if( p2<0 ){ 324 p2 = -p2; 325 negP2 = 1; 326 } 327 }else{ 328 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; 329 } 330 if( p1<0 ){ 331 p1 += len; 332 if( p1<0 ){ 333 p2 += p1; 334 if( p2<0 ) p2 = 0; 335 p1 = 0; 336 } 337 }else if( p1>0 ){ 338 p1--; 339 }else if( p2>0 ){ 340 p2--; 341 } 342 if( negP2 ){ 343 p1 -= p2; 344 if( p1<0 ){ 345 p2 += p1; 346 p1 = 0; 347 } 348 } 349 assert( p1>=0 && p2>=0 ); 350 if( p0type!=SQLITE_BLOB ){ 351 while( *z && p1 ){ 352 SQLITE_SKIP_UTF8(z); 353 p1--; 354 } 355 for(z2=z; *z2 && p2; p2--){ 356 SQLITE_SKIP_UTF8(z2); 357 } 358 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, 359 SQLITE_UTF8); 360 }else{ 361 if( p1+p2>len ){ 362 p2 = len-p1; 363 if( p2<0 ) p2 = 0; 364 } 365 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); 366 } 367 } 368 369 /* 370 ** Implementation of the round() function 371 */ 372 #ifndef SQLITE_OMIT_FLOATING_POINT 373 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 374 int n = 0; 375 double r; 376 char *zBuf; 377 assert( argc==1 || argc==2 ); 378 if( argc==2 ){ 379 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; 380 n = sqlite3_value_int(argv[1]); 381 if( n>30 ) n = 30; 382 if( n<0 ) n = 0; 383 } 384 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 385 r = sqlite3_value_double(argv[0]); 386 /* If Y==0 and X will fit in a 64-bit int, 387 ** handle the rounding directly, 388 ** otherwise use printf. 389 */ 390 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){ 391 /* The value has no fractional part so there is nothing to round */ 392 }else if( n==0 ){ 393 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5))); 394 }else{ 395 zBuf = sqlite3_mprintf("%.*f",n,r); 396 if( zBuf==0 ){ 397 sqlite3_result_error_nomem(context); 398 return; 399 } 400 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); 401 sqlite3_free(zBuf); 402 } 403 sqlite3_result_double(context, r); 404 } 405 #endif 406 407 /* 408 ** Allocate nByte bytes of space using sqlite3Malloc(). If the 409 ** allocation fails, call sqlite3_result_error_nomem() to notify 410 ** the database handle that malloc() has failed and return NULL. 411 ** If nByte is larger than the maximum string or blob length, then 412 ** raise an SQLITE_TOOBIG exception and return NULL. 413 */ 414 static void *contextMalloc(sqlite3_context *context, i64 nByte){ 415 char *z; 416 sqlite3 *db = sqlite3_context_db_handle(context); 417 assert( nByte>0 ); 418 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); 419 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); 420 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 421 sqlite3_result_error_toobig(context); 422 z = 0; 423 }else{ 424 z = sqlite3Malloc(nByte); 425 if( !z ){ 426 sqlite3_result_error_nomem(context); 427 } 428 } 429 return z; 430 } 431 432 /* 433 ** Implementation of the upper() and lower() SQL functions. 434 */ 435 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 436 char *z1; 437 const char *z2; 438 int i, n; 439 UNUSED_PARAMETER(argc); 440 z2 = (char*)sqlite3_value_text(argv[0]); 441 n = sqlite3_value_bytes(argv[0]); 442 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 443 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 444 if( z2 ){ 445 z1 = contextMalloc(context, ((i64)n)+1); 446 if( z1 ){ 447 for(i=0; i<n; i++){ 448 z1[i] = (char)sqlite3Toupper(z2[i]); 449 } 450 sqlite3_result_text(context, z1, n, sqlite3_free); 451 } 452 } 453 } 454 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 455 char *z1; 456 const char *z2; 457 int i, n; 458 UNUSED_PARAMETER(argc); 459 z2 = (char*)sqlite3_value_text(argv[0]); 460 n = sqlite3_value_bytes(argv[0]); 461 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 462 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 463 if( z2 ){ 464 z1 = contextMalloc(context, ((i64)n)+1); 465 if( z1 ){ 466 for(i=0; i<n; i++){ 467 z1[i] = sqlite3Tolower(z2[i]); 468 } 469 sqlite3_result_text(context, z1, n, sqlite3_free); 470 } 471 } 472 } 473 474 /* 475 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented 476 ** as VDBE code so that unused argument values do not have to be computed. 477 ** However, we still need some kind of function implementation for this 478 ** routines in the function table. The noopFunc macro provides this. 479 ** noopFunc will never be called so it doesn't matter what the implementation 480 ** is. We might as well use the "version()" function as a substitute. 481 */ 482 #define noopFunc versionFunc /* Substitute function - never called */ 483 484 /* 485 ** Implementation of random(). Return a random integer. 486 */ 487 static void randomFunc( 488 sqlite3_context *context, 489 int NotUsed, 490 sqlite3_value **NotUsed2 491 ){ 492 sqlite_int64 r; 493 UNUSED_PARAMETER2(NotUsed, NotUsed2); 494 sqlite3_randomness(sizeof(r), &r); 495 if( r<0 ){ 496 /* We need to prevent a random number of 0x8000000000000000 497 ** (or -9223372036854775808) since when you do abs() of that 498 ** number of you get the same value back again. To do this 499 ** in a way that is testable, mask the sign bit off of negative 500 ** values, resulting in a positive value. Then take the 501 ** 2s complement of that positive value. The end result can 502 ** therefore be no less than -9223372036854775807. 503 */ 504 r = -(r & LARGEST_INT64); 505 } 506 sqlite3_result_int64(context, r); 507 } 508 509 /* 510 ** Implementation of randomblob(N). Return a random blob 511 ** that is N bytes long. 512 */ 513 static void randomBlob( 514 sqlite3_context *context, 515 int argc, 516 sqlite3_value **argv 517 ){ 518 sqlite3_int64 n; 519 unsigned char *p; 520 assert( argc==1 ); 521 UNUSED_PARAMETER(argc); 522 n = sqlite3_value_int64(argv[0]); 523 if( n<1 ){ 524 n = 1; 525 } 526 p = contextMalloc(context, n); 527 if( p ){ 528 sqlite3_randomness(n, p); 529 sqlite3_result_blob(context, (char*)p, n, sqlite3_free); 530 } 531 } 532 533 /* 534 ** Implementation of the last_insert_rowid() SQL function. The return 535 ** value is the same as the sqlite3_last_insert_rowid() API function. 536 */ 537 static void last_insert_rowid( 538 sqlite3_context *context, 539 int NotUsed, 540 sqlite3_value **NotUsed2 541 ){ 542 sqlite3 *db = sqlite3_context_db_handle(context); 543 UNUSED_PARAMETER2(NotUsed, NotUsed2); 544 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a 545 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface 546 ** function. */ 547 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db)); 548 } 549 550 /* 551 ** Implementation of the changes() SQL function. 552 ** 553 ** IMP: R-62073-11209 The changes() SQL function is a wrapper 554 ** around the sqlite3_changes() C/C++ function and hence follows the same 555 ** rules for counting changes. 556 */ 557 static void changes( 558 sqlite3_context *context, 559 int NotUsed, 560 sqlite3_value **NotUsed2 561 ){ 562 sqlite3 *db = sqlite3_context_db_handle(context); 563 UNUSED_PARAMETER2(NotUsed, NotUsed2); 564 sqlite3_result_int(context, sqlite3_changes(db)); 565 } 566 567 /* 568 ** Implementation of the total_changes() SQL function. The return value is 569 ** the same as the sqlite3_total_changes() API function. 570 */ 571 static void total_changes( 572 sqlite3_context *context, 573 int NotUsed, 574 sqlite3_value **NotUsed2 575 ){ 576 sqlite3 *db = sqlite3_context_db_handle(context); 577 UNUSED_PARAMETER2(NotUsed, NotUsed2); 578 /* IMP: R-52756-41993 This function is a wrapper around the 579 ** sqlite3_total_changes() C/C++ interface. */ 580 sqlite3_result_int(context, sqlite3_total_changes(db)); 581 } 582 583 /* 584 ** A structure defining how to do GLOB-style comparisons. 585 */ 586 struct compareInfo { 587 u8 matchAll; /* "*" or "%" */ 588 u8 matchOne; /* "?" or "_" */ 589 u8 matchSet; /* "[" or 0 */ 590 u8 noCase; /* true to ignore case differences */ 591 }; 592 593 /* 594 ** For LIKE and GLOB matching on EBCDIC machines, assume that every 595 ** character is exactly one byte in size. Also, provde the Utf8Read() 596 ** macro for fast reading of the next character in the common case where 597 ** the next character is ASCII. 598 */ 599 #if defined(SQLITE_EBCDIC) 600 # define sqlite3Utf8Read(A) (*((*A)++)) 601 # define Utf8Read(A) (*(A++)) 602 #else 603 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A)) 604 #endif 605 606 static const struct compareInfo globInfo = { '*', '?', '[', 0 }; 607 /* The correct SQL-92 behavior is for the LIKE operator to ignore 608 ** case. Thus 'a' LIKE 'A' would be true. */ 609 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 }; 610 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator 611 ** is case sensitive causing 'a' LIKE 'A' to be false */ 612 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 }; 613 614 /* 615 ** Possible error returns from patternMatch() 616 */ 617 #define SQLITE_MATCH 0 618 #define SQLITE_NOMATCH 1 619 #define SQLITE_NOWILDCARDMATCH 2 620 621 /* 622 ** Compare two UTF-8 strings for equality where the first string is 623 ** a GLOB or LIKE expression. Return values: 624 ** 625 ** SQLITE_MATCH: Match 626 ** SQLITE_NOMATCH: No match 627 ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards. 628 ** 629 ** Globbing rules: 630 ** 631 ** '*' Matches any sequence of zero or more characters. 632 ** 633 ** '?' Matches exactly one character. 634 ** 635 ** [...] Matches one character from the enclosed list of 636 ** characters. 637 ** 638 ** [^...] Matches one character not in the enclosed list. 639 ** 640 ** With the [...] and [^...] matching, a ']' character can be included 641 ** in the list by making it the first character after '[' or '^'. A 642 ** range of characters can be specified using '-'. Example: 643 ** "[a-z]" matches any single lower-case letter. To match a '-', make 644 ** it the last character in the list. 645 ** 646 ** Like matching rules: 647 ** 648 ** '%' Matches any sequence of zero or more characters 649 ** 650 *** '_' Matches any one character 651 ** 652 ** Ec Where E is the "esc" character and c is any other 653 ** character, including '%', '_', and esc, match exactly c. 654 ** 655 ** The comments within this routine usually assume glob matching. 656 ** 657 ** This routine is usually quick, but can be N**2 in the worst case. 658 */ 659 static int patternCompare( 660 const u8 *zPattern, /* The glob pattern */ 661 const u8 *zString, /* The string to compare against the glob */ 662 const struct compareInfo *pInfo, /* Information about how to do the compare */ 663 u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */ 664 ){ 665 u32 c, c2; /* Next pattern and input string chars */ 666 u32 matchOne = pInfo->matchOne; /* "?" or "_" */ 667 u32 matchAll = pInfo->matchAll; /* "*" or "%" */ 668 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ 669 const u8 *zEscaped = 0; /* One past the last escaped input char */ 670 671 while( (c = Utf8Read(zPattern))!=0 ){ 672 if( c==matchAll ){ /* Match "*" */ 673 /* Skip over multiple "*" characters in the pattern. If there 674 ** are also "?" characters, skip those as well, but consume a 675 ** single character of the input string for each "?" skipped */ 676 while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){ 677 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ 678 return SQLITE_NOWILDCARDMATCH; 679 } 680 } 681 if( c==0 ){ 682 return SQLITE_MATCH; /* "*" at the end of the pattern matches */ 683 }else if( c==matchOther ){ 684 if( pInfo->matchSet==0 ){ 685 c = sqlite3Utf8Read(&zPattern); 686 if( c==0 ) return SQLITE_NOWILDCARDMATCH; 687 }else{ 688 /* "[...]" immediately follows the "*". We have to do a slow 689 ** recursive search in this case, but it is an unusual case. */ 690 assert( matchOther<0x80 ); /* '[' is a single-byte character */ 691 while( *zString ){ 692 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); 693 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 694 SQLITE_SKIP_UTF8(zString); 695 } 696 return SQLITE_NOWILDCARDMATCH; 697 } 698 } 699 700 /* At this point variable c contains the first character of the 701 ** pattern string past the "*". Search in the input string for the 702 ** first matching character and recursively continue the match from 703 ** that point. 704 ** 705 ** For a case-insensitive search, set variable cx to be the same as 706 ** c but in the other case and search the input string for either 707 ** c or cx. 708 */ 709 if( c<=0x80 ){ 710 char zStop[3]; 711 int bMatch; 712 if( noCase ){ 713 zStop[0] = sqlite3Toupper(c); 714 zStop[1] = sqlite3Tolower(c); 715 zStop[2] = 0; 716 }else{ 717 zStop[0] = c; 718 zStop[1] = 0; 719 } 720 while(1){ 721 zString += strcspn((const char*)zString, zStop); 722 if( zString[0]==0 ) break; 723 zString++; 724 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 725 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 726 } 727 }else{ 728 int bMatch; 729 while( (c2 = Utf8Read(zString))!=0 ){ 730 if( c2!=c ) continue; 731 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 732 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 733 } 734 } 735 return SQLITE_NOWILDCARDMATCH; 736 } 737 if( c==matchOther ){ 738 if( pInfo->matchSet==0 ){ 739 c = sqlite3Utf8Read(&zPattern); 740 if( c==0 ) return SQLITE_NOMATCH; 741 zEscaped = zPattern; 742 }else{ 743 u32 prior_c = 0; 744 int seen = 0; 745 int invert = 0; 746 c = sqlite3Utf8Read(&zString); 747 if( c==0 ) return SQLITE_NOMATCH; 748 c2 = sqlite3Utf8Read(&zPattern); 749 if( c2=='^' ){ 750 invert = 1; 751 c2 = sqlite3Utf8Read(&zPattern); 752 } 753 if( c2==']' ){ 754 if( c==']' ) seen = 1; 755 c2 = sqlite3Utf8Read(&zPattern); 756 } 757 while( c2 && c2!=']' ){ 758 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ 759 c2 = sqlite3Utf8Read(&zPattern); 760 if( c>=prior_c && c<=c2 ) seen = 1; 761 prior_c = 0; 762 }else{ 763 if( c==c2 ){ 764 seen = 1; 765 } 766 prior_c = c2; 767 } 768 c2 = sqlite3Utf8Read(&zPattern); 769 } 770 if( c2==0 || (seen ^ invert)==0 ){ 771 return SQLITE_NOMATCH; 772 } 773 continue; 774 } 775 } 776 c2 = Utf8Read(zString); 777 if( c==c2 ) continue; 778 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ 779 continue; 780 } 781 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; 782 return SQLITE_NOMATCH; 783 } 784 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; 785 } 786 787 /* 788 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and 789 ** non-zero if there is no match. 790 */ 791 int sqlite3_strglob(const char *zGlobPattern, const char *zString){ 792 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); 793 } 794 795 /* 796 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for 797 ** a miss - like strcmp(). 798 */ 799 int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ 800 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); 801 } 802 803 /* 804 ** Count the number of times that the LIKE operator (or GLOB which is 805 ** just a variation of LIKE) gets called. This is used for testing 806 ** only. 807 */ 808 #ifdef SQLITE_TEST 809 int sqlite3_like_count = 0; 810 #endif 811 812 813 /* 814 ** Implementation of the like() SQL function. This function implements 815 ** the build-in LIKE operator. The first argument to the function is the 816 ** pattern and the second argument is the string. So, the SQL statements: 817 ** 818 ** A LIKE B 819 ** 820 ** is implemented as like(B,A). 821 ** 822 ** This same function (with a different compareInfo structure) computes 823 ** the GLOB operator. 824 */ 825 static void likeFunc( 826 sqlite3_context *context, 827 int argc, 828 sqlite3_value **argv 829 ){ 830 const unsigned char *zA, *zB; 831 u32 escape; 832 int nPat; 833 sqlite3 *db = sqlite3_context_db_handle(context); 834 struct compareInfo *pInfo = sqlite3_user_data(context); 835 836 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 837 if( sqlite3_value_type(argv[0])==SQLITE_BLOB 838 || sqlite3_value_type(argv[1])==SQLITE_BLOB 839 ){ 840 #ifdef SQLITE_TEST 841 sqlite3_like_count++; 842 #endif 843 sqlite3_result_int(context, 0); 844 return; 845 } 846 #endif 847 848 /* Limit the length of the LIKE or GLOB pattern to avoid problems 849 ** of deep recursion and N*N behavior in patternCompare(). 850 */ 851 nPat = sqlite3_value_bytes(argv[0]); 852 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); 853 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); 854 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ 855 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); 856 return; 857 } 858 if( argc==3 ){ 859 /* The escape character string must consist of a single UTF-8 character. 860 ** Otherwise, return an error. 861 */ 862 const unsigned char *zEsc = sqlite3_value_text(argv[2]); 863 if( zEsc==0 ) return; 864 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ 865 sqlite3_result_error(context, 866 "ESCAPE expression must be a single character", -1); 867 return; 868 } 869 escape = sqlite3Utf8Read(&zEsc); 870 }else{ 871 escape = pInfo->matchSet; 872 } 873 zB = sqlite3_value_text(argv[0]); 874 zA = sqlite3_value_text(argv[1]); 875 if( zA && zB ){ 876 #ifdef SQLITE_TEST 877 sqlite3_like_count++; 878 #endif 879 sqlite3_result_int(context, 880 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); 881 } 882 } 883 884 /* 885 ** Implementation of the NULLIF(x,y) function. The result is the first 886 ** argument if the arguments are different. The result is NULL if the 887 ** arguments are equal to each other. 888 */ 889 static void nullifFunc( 890 sqlite3_context *context, 891 int NotUsed, 892 sqlite3_value **argv 893 ){ 894 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 895 UNUSED_PARAMETER(NotUsed); 896 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ 897 sqlite3_result_value(context, argv[0]); 898 } 899 } 900 901 /* 902 ** Implementation of the sqlite_version() function. The result is the version 903 ** of the SQLite library that is running. 904 */ 905 static void versionFunc( 906 sqlite3_context *context, 907 int NotUsed, 908 sqlite3_value **NotUsed2 909 ){ 910 UNUSED_PARAMETER2(NotUsed, NotUsed2); 911 /* IMP: R-48699-48617 This function is an SQL wrapper around the 912 ** sqlite3_libversion() C-interface. */ 913 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); 914 } 915 916 /* 917 ** Implementation of the sqlite_source_id() function. The result is a string 918 ** that identifies the particular version of the source code used to build 919 ** SQLite. 920 */ 921 static void sourceidFunc( 922 sqlite3_context *context, 923 int NotUsed, 924 sqlite3_value **NotUsed2 925 ){ 926 UNUSED_PARAMETER2(NotUsed, NotUsed2); 927 /* IMP: R-24470-31136 This function is an SQL wrapper around the 928 ** sqlite3_sourceid() C interface. */ 929 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); 930 } 931 932 /* 933 ** Implementation of the sqlite_log() function. This is a wrapper around 934 ** sqlite3_log(). The return value is NULL. The function exists purely for 935 ** its side-effects. 936 */ 937 static void errlogFunc( 938 sqlite3_context *context, 939 int argc, 940 sqlite3_value **argv 941 ){ 942 UNUSED_PARAMETER(argc); 943 UNUSED_PARAMETER(context); 944 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); 945 } 946 947 /* 948 ** Implementation of the sqlite_compileoption_used() function. 949 ** The result is an integer that identifies if the compiler option 950 ** was used to build SQLite. 951 */ 952 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 953 static void compileoptionusedFunc( 954 sqlite3_context *context, 955 int argc, 956 sqlite3_value **argv 957 ){ 958 const char *zOptName; 959 assert( argc==1 ); 960 UNUSED_PARAMETER(argc); 961 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL 962 ** function is a wrapper around the sqlite3_compileoption_used() C/C++ 963 ** function. 964 */ 965 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 966 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); 967 } 968 } 969 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 970 971 /* 972 ** Implementation of the sqlite_compileoption_get() function. 973 ** The result is a string that identifies the compiler options 974 ** used to build SQLite. 975 */ 976 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 977 static void compileoptiongetFunc( 978 sqlite3_context *context, 979 int argc, 980 sqlite3_value **argv 981 ){ 982 int n; 983 assert( argc==1 ); 984 UNUSED_PARAMETER(argc); 985 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function 986 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. 987 */ 988 n = sqlite3_value_int(argv[0]); 989 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); 990 } 991 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 992 993 /* Array for converting from half-bytes (nybbles) into ASCII hex 994 ** digits. */ 995 static const char hexdigits[] = { 996 '0', '1', '2', '3', '4', '5', '6', '7', 997 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 998 }; 999 1000 /* 1001 ** Implementation of the QUOTE() function. This function takes a single 1002 ** argument. If the argument is numeric, the return value is the same as 1003 ** the argument. If the argument is NULL, the return value is the string 1004 ** "NULL". Otherwise, the argument is enclosed in single quotes with 1005 ** single-quote escapes. 1006 */ 1007 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 1008 assert( argc==1 ); 1009 UNUSED_PARAMETER(argc); 1010 switch( sqlite3_value_type(argv[0]) ){ 1011 case SQLITE_FLOAT: { 1012 double r1, r2; 1013 char zBuf[50]; 1014 r1 = sqlite3_value_double(argv[0]); 1015 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); 1016 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); 1017 if( r1!=r2 ){ 1018 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); 1019 } 1020 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); 1021 break; 1022 } 1023 case SQLITE_INTEGER: { 1024 sqlite3_result_value(context, argv[0]); 1025 break; 1026 } 1027 case SQLITE_BLOB: { 1028 char *zText = 0; 1029 char const *zBlob = sqlite3_value_blob(argv[0]); 1030 int nBlob = sqlite3_value_bytes(argv[0]); 1031 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ 1032 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 1033 if( zText ){ 1034 int i; 1035 for(i=0; i<nBlob; i++){ 1036 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F]; 1037 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; 1038 } 1039 zText[(nBlob*2)+2] = '\''; 1040 zText[(nBlob*2)+3] = '\0'; 1041 zText[0] = 'X'; 1042 zText[1] = '\''; 1043 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); 1044 sqlite3_free(zText); 1045 } 1046 break; 1047 } 1048 case SQLITE_TEXT: { 1049 int i,j; 1050 u64 n; 1051 const unsigned char *zArg = sqlite3_value_text(argv[0]); 1052 char *z; 1053 1054 if( zArg==0 ) return; 1055 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } 1056 z = contextMalloc(context, ((i64)i)+((i64)n)+3); 1057 if( z ){ 1058 z[0] = '\''; 1059 for(i=0, j=1; zArg[i]; i++){ 1060 z[j++] = zArg[i]; 1061 if( zArg[i]=='\'' ){ 1062 z[j++] = '\''; 1063 } 1064 } 1065 z[j++] = '\''; 1066 z[j] = 0; 1067 sqlite3_result_text(context, z, j, sqlite3_free); 1068 } 1069 break; 1070 } 1071 default: { 1072 assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); 1073 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); 1074 break; 1075 } 1076 } 1077 } 1078 1079 /* 1080 ** The unicode() function. Return the integer unicode code-point value 1081 ** for the first character of the input string. 1082 */ 1083 static void unicodeFunc( 1084 sqlite3_context *context, 1085 int argc, 1086 sqlite3_value **argv 1087 ){ 1088 const unsigned char *z = sqlite3_value_text(argv[0]); 1089 (void)argc; 1090 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); 1091 } 1092 1093 /* 1094 ** The char() function takes zero or more arguments, each of which is 1095 ** an integer. It constructs a string where each character of the string 1096 ** is the unicode character for the corresponding integer argument. 1097 */ 1098 static void charFunc( 1099 sqlite3_context *context, 1100 int argc, 1101 sqlite3_value **argv 1102 ){ 1103 unsigned char *z, *zOut; 1104 int i; 1105 zOut = z = sqlite3_malloc64( argc*4+1 ); 1106 if( z==0 ){ 1107 sqlite3_result_error_nomem(context); 1108 return; 1109 } 1110 for(i=0; i<argc; i++){ 1111 sqlite3_int64 x; 1112 unsigned c; 1113 x = sqlite3_value_int64(argv[i]); 1114 if( x<0 || x>0x10ffff ) x = 0xfffd; 1115 c = (unsigned)(x & 0x1fffff); 1116 if( c<0x00080 ){ 1117 *zOut++ = (u8)(c&0xFF); 1118 }else if( c<0x00800 ){ 1119 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); 1120 *zOut++ = 0x80 + (u8)(c & 0x3F); 1121 }else if( c<0x10000 ){ 1122 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); 1123 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 1124 *zOut++ = 0x80 + (u8)(c & 0x3F); 1125 }else{ 1126 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); 1127 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); 1128 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 1129 *zOut++ = 0x80 + (u8)(c & 0x3F); 1130 } \ 1131 } 1132 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); 1133 } 1134 1135 /* 1136 ** The hex() function. Interpret the argument as a blob. Return 1137 ** a hexadecimal rendering as text. 1138 */ 1139 static void hexFunc( 1140 sqlite3_context *context, 1141 int argc, 1142 sqlite3_value **argv 1143 ){ 1144 int i, n; 1145 const unsigned char *pBlob; 1146 char *zHex, *z; 1147 assert( argc==1 ); 1148 UNUSED_PARAMETER(argc); 1149 pBlob = sqlite3_value_blob(argv[0]); 1150 n = sqlite3_value_bytes(argv[0]); 1151 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ 1152 z = zHex = contextMalloc(context, ((i64)n)*2 + 1); 1153 if( zHex ){ 1154 for(i=0; i<n; i++, pBlob++){ 1155 unsigned char c = *pBlob; 1156 *(z++) = hexdigits[(c>>4)&0xf]; 1157 *(z++) = hexdigits[c&0xf]; 1158 } 1159 *z = 0; 1160 sqlite3_result_text(context, zHex, n*2, sqlite3_free); 1161 } 1162 } 1163 1164 /* 1165 ** The zeroblob(N) function returns a zero-filled blob of size N bytes. 1166 */ 1167 static void zeroblobFunc( 1168 sqlite3_context *context, 1169 int argc, 1170 sqlite3_value **argv 1171 ){ 1172 i64 n; 1173 int rc; 1174 assert( argc==1 ); 1175 UNUSED_PARAMETER(argc); 1176 n = sqlite3_value_int64(argv[0]); 1177 if( n<0 ) n = 0; 1178 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ 1179 if( rc ){ 1180 sqlite3_result_error_code(context, rc); 1181 } 1182 } 1183 1184 /* 1185 ** The replace() function. Three arguments are all strings: call 1186 ** them A, B, and C. The result is also a string which is derived 1187 ** from A by replacing every occurrence of B with C. The match 1188 ** must be exact. Collating sequences are not used. 1189 */ 1190 static void replaceFunc( 1191 sqlite3_context *context, 1192 int argc, 1193 sqlite3_value **argv 1194 ){ 1195 const unsigned char *zStr; /* The input string A */ 1196 const unsigned char *zPattern; /* The pattern string B */ 1197 const unsigned char *zRep; /* The replacement string C */ 1198 unsigned char *zOut; /* The output */ 1199 int nStr; /* Size of zStr */ 1200 int nPattern; /* Size of zPattern */ 1201 int nRep; /* Size of zRep */ 1202 i64 nOut; /* Maximum size of zOut */ 1203 int loopLimit; /* Last zStr[] that might match zPattern[] */ 1204 int i, j; /* Loop counters */ 1205 unsigned cntExpand; /* Number zOut expansions */ 1206 sqlite3 *db = sqlite3_context_db_handle(context); 1207 1208 assert( argc==3 ); 1209 UNUSED_PARAMETER(argc); 1210 zStr = sqlite3_value_text(argv[0]); 1211 if( zStr==0 ) return; 1212 nStr = sqlite3_value_bytes(argv[0]); 1213 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ 1214 zPattern = sqlite3_value_text(argv[1]); 1215 if( zPattern==0 ){ 1216 assert( sqlite3_value_type(argv[1])==SQLITE_NULL 1217 || sqlite3_context_db_handle(context)->mallocFailed ); 1218 return; 1219 } 1220 if( zPattern[0]==0 ){ 1221 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); 1222 sqlite3_result_value(context, argv[0]); 1223 return; 1224 } 1225 nPattern = sqlite3_value_bytes(argv[1]); 1226 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ 1227 zRep = sqlite3_value_text(argv[2]); 1228 if( zRep==0 ) return; 1229 nRep = sqlite3_value_bytes(argv[2]); 1230 assert( zRep==sqlite3_value_text(argv[2]) ); 1231 nOut = nStr + 1; 1232 assert( nOut<SQLITE_MAX_LENGTH ); 1233 zOut = contextMalloc(context, (i64)nOut); 1234 if( zOut==0 ){ 1235 return; 1236 } 1237 loopLimit = nStr - nPattern; 1238 cntExpand = 0; 1239 for(i=j=0; i<=loopLimit; i++){ 1240 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ 1241 zOut[j++] = zStr[i]; 1242 }else{ 1243 if( nRep>nPattern ){ 1244 nOut += nRep - nPattern; 1245 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); 1246 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); 1247 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 1248 sqlite3_result_error_toobig(context); 1249 sqlite3_free(zOut); 1250 return; 1251 } 1252 cntExpand++; 1253 if( (cntExpand&(cntExpand-1))==0 ){ 1254 /* Grow the size of the output buffer only on substitutions 1255 ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */ 1256 u8 *zOld; 1257 zOld = zOut; 1258 zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1)); 1259 if( zOut==0 ){ 1260 sqlite3_result_error_nomem(context); 1261 sqlite3_free(zOld); 1262 return; 1263 } 1264 } 1265 } 1266 memcpy(&zOut[j], zRep, nRep); 1267 j += nRep; 1268 i += nPattern-1; 1269 } 1270 } 1271 assert( j+nStr-i+1<=nOut ); 1272 memcpy(&zOut[j], &zStr[i], nStr-i); 1273 j += nStr - i; 1274 assert( j<=nOut ); 1275 zOut[j] = 0; 1276 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); 1277 } 1278 1279 /* 1280 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. 1281 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. 1282 */ 1283 static void trimFunc( 1284 sqlite3_context *context, 1285 int argc, 1286 sqlite3_value **argv 1287 ){ 1288 const unsigned char *zIn; /* Input string */ 1289 const unsigned char *zCharSet; /* Set of characters to trim */ 1290 int nIn; /* Number of bytes in input */ 1291 int flags; /* 1: trimleft 2: trimright 3: trim */ 1292 int i; /* Loop counter */ 1293 unsigned char *aLen = 0; /* Length of each character in zCharSet */ 1294 unsigned char **azChar = 0; /* Individual characters in zCharSet */ 1295 int nChar; /* Number of characters in zCharSet */ 1296 1297 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1298 return; 1299 } 1300 zIn = sqlite3_value_text(argv[0]); 1301 if( zIn==0 ) return; 1302 nIn = sqlite3_value_bytes(argv[0]); 1303 assert( zIn==sqlite3_value_text(argv[0]) ); 1304 if( argc==1 ){ 1305 static const unsigned char lenOne[] = { 1 }; 1306 static unsigned char * const azOne[] = { (u8*)" " }; 1307 nChar = 1; 1308 aLen = (u8*)lenOne; 1309 azChar = (unsigned char **)azOne; 1310 zCharSet = 0; 1311 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ 1312 return; 1313 }else{ 1314 const unsigned char *z; 1315 for(z=zCharSet, nChar=0; *z; nChar++){ 1316 SQLITE_SKIP_UTF8(z); 1317 } 1318 if( nChar>0 ){ 1319 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); 1320 if( azChar==0 ){ 1321 return; 1322 } 1323 aLen = (unsigned char*)&azChar[nChar]; 1324 for(z=zCharSet, nChar=0; *z; nChar++){ 1325 azChar[nChar] = (unsigned char *)z; 1326 SQLITE_SKIP_UTF8(z); 1327 aLen[nChar] = (u8)(z - azChar[nChar]); 1328 } 1329 } 1330 } 1331 if( nChar>0 ){ 1332 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); 1333 if( flags & 1 ){ 1334 while( nIn>0 ){ 1335 int len = 0; 1336 for(i=0; i<nChar; i++){ 1337 len = aLen[i]; 1338 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break; 1339 } 1340 if( i>=nChar ) break; 1341 zIn += len; 1342 nIn -= len; 1343 } 1344 } 1345 if( flags & 2 ){ 1346 while( nIn>0 ){ 1347 int len = 0; 1348 for(i=0; i<nChar; i++){ 1349 len = aLen[i]; 1350 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break; 1351 } 1352 if( i>=nChar ) break; 1353 nIn -= len; 1354 } 1355 } 1356 if( zCharSet ){ 1357 sqlite3_free(azChar); 1358 } 1359 } 1360 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); 1361 } 1362 1363 1364 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 1365 /* 1366 ** The "unknown" function is automatically substituted in place of 1367 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN 1368 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used. 1369 ** When the "sqlite3" command-line shell is built using this functionality, 1370 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries 1371 ** involving application-defined functions to be examined in a generic 1372 ** sqlite3 shell. 1373 */ 1374 static void unknownFunc( 1375 sqlite3_context *context, 1376 int argc, 1377 sqlite3_value **argv 1378 ){ 1379 /* no-op */ 1380 } 1381 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ 1382 1383 1384 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It 1385 ** is only available if the SQLITE_SOUNDEX compile-time option is used 1386 ** when SQLite is built. 1387 */ 1388 #ifdef SQLITE_SOUNDEX 1389 /* 1390 ** Compute the soundex encoding of a word. 1391 ** 1392 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the 1393 ** soundex encoding of the string X. 1394 */ 1395 static void soundexFunc( 1396 sqlite3_context *context, 1397 int argc, 1398 sqlite3_value **argv 1399 ){ 1400 char zResult[8]; 1401 const u8 *zIn; 1402 int i, j; 1403 static const unsigned char iCode[] = { 1404 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1405 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1406 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1407 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1408 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1409 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 1410 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1411 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 1412 }; 1413 assert( argc==1 ); 1414 zIn = (u8*)sqlite3_value_text(argv[0]); 1415 if( zIn==0 ) zIn = (u8*)""; 1416 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} 1417 if( zIn[i] ){ 1418 u8 prevcode = iCode[zIn[i]&0x7f]; 1419 zResult[0] = sqlite3Toupper(zIn[i]); 1420 for(j=1; j<4 && zIn[i]; i++){ 1421 int code = iCode[zIn[i]&0x7f]; 1422 if( code>0 ){ 1423 if( code!=prevcode ){ 1424 prevcode = code; 1425 zResult[j++] = code + '0'; 1426 } 1427 }else{ 1428 prevcode = 0; 1429 } 1430 } 1431 while( j<4 ){ 1432 zResult[j++] = '0'; 1433 } 1434 zResult[j] = 0; 1435 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); 1436 }else{ 1437 /* IMP: R-64894-50321 The string "?000" is returned if the argument 1438 ** is NULL or contains no ASCII alphabetic characters. */ 1439 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); 1440 } 1441 } 1442 #endif /* SQLITE_SOUNDEX */ 1443 1444 #ifndef SQLITE_OMIT_LOAD_EXTENSION 1445 /* 1446 ** A function that loads a shared-library extension then returns NULL. 1447 */ 1448 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ 1449 const char *zFile = (const char *)sqlite3_value_text(argv[0]); 1450 const char *zProc; 1451 sqlite3 *db = sqlite3_context_db_handle(context); 1452 char *zErrMsg = 0; 1453 1454 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc 1455 ** flag is set. See the sqlite3_enable_load_extension() API. 1456 */ 1457 if( (db->flags & SQLITE_LoadExtFunc)==0 ){ 1458 sqlite3_result_error(context, "not authorized", -1); 1459 return; 1460 } 1461 1462 if( argc==2 ){ 1463 zProc = (const char *)sqlite3_value_text(argv[1]); 1464 }else{ 1465 zProc = 0; 1466 } 1467 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ 1468 sqlite3_result_error(context, zErrMsg, -1); 1469 sqlite3_free(zErrMsg); 1470 } 1471 } 1472 #endif 1473 1474 1475 /* 1476 ** An instance of the following structure holds the context of a 1477 ** sum() or avg() aggregate computation. 1478 */ 1479 typedef struct SumCtx SumCtx; 1480 struct SumCtx { 1481 double rSum; /* Floating point sum */ 1482 i64 iSum; /* Integer sum */ 1483 i64 cnt; /* Number of elements summed */ 1484 u8 overflow; /* True if integer overflow seen */ 1485 u8 approx; /* True if non-integer value was input to the sum */ 1486 }; 1487 1488 /* 1489 ** Routines used to compute the sum, average, and total. 1490 ** 1491 ** The SUM() function follows the (broken) SQL standard which means 1492 ** that it returns NULL if it sums over no inputs. TOTAL returns 1493 ** 0.0 in that case. In addition, TOTAL always returns a float where 1494 ** SUM might return an integer if it never encounters a floating point 1495 ** value. TOTAL never fails, but SUM might through an exception if 1496 ** it overflows an integer. 1497 */ 1498 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 1499 SumCtx *p; 1500 int type; 1501 assert( argc==1 ); 1502 UNUSED_PARAMETER(argc); 1503 p = sqlite3_aggregate_context(context, sizeof(*p)); 1504 type = sqlite3_value_numeric_type(argv[0]); 1505 if( p && type!=SQLITE_NULL ){ 1506 p->cnt++; 1507 if( type==SQLITE_INTEGER ){ 1508 i64 v = sqlite3_value_int64(argv[0]); 1509 p->rSum += v; 1510 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ 1511 p->approx = p->overflow = 1; 1512 } 1513 }else{ 1514 p->rSum += sqlite3_value_double(argv[0]); 1515 p->approx = 1; 1516 } 1517 } 1518 } 1519 #ifndef SQLITE_OMIT_WINDOWFUNC 1520 static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ 1521 SumCtx *p; 1522 int type; 1523 assert( argc==1 ); 1524 UNUSED_PARAMETER(argc); 1525 p = sqlite3_aggregate_context(context, sizeof(*p)); 1526 type = sqlite3_value_numeric_type(argv[0]); 1527 /* p is always non-NULL because sumStep() will have been called first 1528 ** to initialize it */ 1529 if( ALWAYS(p) && type!=SQLITE_NULL ){ 1530 assert( p->cnt>0 ); 1531 p->cnt--; 1532 assert( type==SQLITE_INTEGER || p->approx ); 1533 if( type==SQLITE_INTEGER && p->approx==0 ){ 1534 i64 v = sqlite3_value_int64(argv[0]); 1535 p->rSum -= v; 1536 p->iSum -= v; 1537 }else{ 1538 p->rSum -= sqlite3_value_double(argv[0]); 1539 } 1540 } 1541 } 1542 #else 1543 # define sumInverse 0 1544 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1545 static void sumFinalize(sqlite3_context *context){ 1546 SumCtx *p; 1547 p = sqlite3_aggregate_context(context, 0); 1548 if( p && p->cnt>0 ){ 1549 if( p->overflow ){ 1550 sqlite3_result_error(context,"integer overflow",-1); 1551 }else if( p->approx ){ 1552 sqlite3_result_double(context, p->rSum); 1553 }else{ 1554 sqlite3_result_int64(context, p->iSum); 1555 } 1556 } 1557 } 1558 static void avgFinalize(sqlite3_context *context){ 1559 SumCtx *p; 1560 p = sqlite3_aggregate_context(context, 0); 1561 if( p && p->cnt>0 ){ 1562 sqlite3_result_double(context, p->rSum/(double)p->cnt); 1563 } 1564 } 1565 static void totalFinalize(sqlite3_context *context){ 1566 SumCtx *p; 1567 p = sqlite3_aggregate_context(context, 0); 1568 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ 1569 sqlite3_result_double(context, p ? p->rSum : (double)0); 1570 } 1571 1572 /* 1573 ** The following structure keeps track of state information for the 1574 ** count() aggregate function. 1575 */ 1576 typedef struct CountCtx CountCtx; 1577 struct CountCtx { 1578 i64 n; 1579 #ifdef SQLITE_DEBUG 1580 int bInverse; /* True if xInverse() ever called */ 1581 #endif 1582 }; 1583 1584 /* 1585 ** Routines to implement the count() aggregate function. 1586 */ 1587 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 1588 CountCtx *p; 1589 p = sqlite3_aggregate_context(context, sizeof(*p)); 1590 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ 1591 p->n++; 1592 } 1593 1594 #ifndef SQLITE_OMIT_DEPRECATED 1595 /* The sqlite3_aggregate_count() function is deprecated. But just to make 1596 ** sure it still operates correctly, verify that its count agrees with our 1597 ** internal count when using count(*) and when the total count can be 1598 ** expressed as a 32-bit integer. */ 1599 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse 1600 || p->n==sqlite3_aggregate_count(context) ); 1601 #endif 1602 } 1603 static void countFinalize(sqlite3_context *context){ 1604 CountCtx *p; 1605 p = sqlite3_aggregate_context(context, 0); 1606 sqlite3_result_int64(context, p ? p->n : 0); 1607 } 1608 #ifndef SQLITE_OMIT_WINDOWFUNC 1609 static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){ 1610 CountCtx *p; 1611 p = sqlite3_aggregate_context(ctx, sizeof(*p)); 1612 /* p is always non-NULL since countStep() will have been called first */ 1613 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){ 1614 p->n--; 1615 #ifdef SQLITE_DEBUG 1616 p->bInverse = 1; 1617 #endif 1618 } 1619 } 1620 #else 1621 # define countInverse 0 1622 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1623 1624 /* 1625 ** Routines to implement min() and max() aggregate functions. 1626 */ 1627 static void minmaxStep( 1628 sqlite3_context *context, 1629 int NotUsed, 1630 sqlite3_value **argv 1631 ){ 1632 Mem *pArg = (Mem *)argv[0]; 1633 Mem *pBest; 1634 UNUSED_PARAMETER(NotUsed); 1635 1636 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); 1637 if( !pBest ) return; 1638 1639 if( sqlite3_value_type(pArg)==SQLITE_NULL ){ 1640 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); 1641 }else if( pBest->flags ){ 1642 int max; 1643 int cmp; 1644 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 1645 /* This step function is used for both the min() and max() aggregates, 1646 ** the only difference between the two being that the sense of the 1647 ** comparison is inverted. For the max() aggregate, the 1648 ** sqlite3_user_data() function returns (void *)-1. For min() it 1649 ** returns (void *)db, where db is the sqlite3* database pointer. 1650 ** Therefore the next statement sets variable 'max' to 1 for the max() 1651 ** aggregate, or 0 for min(). 1652 */ 1653 max = sqlite3_user_data(context)!=0; 1654 cmp = sqlite3MemCompare(pBest, pArg, pColl); 1655 if( (max && cmp<0) || (!max && cmp>0) ){ 1656 sqlite3VdbeMemCopy(pBest, pArg); 1657 }else{ 1658 sqlite3SkipAccumulatorLoad(context); 1659 } 1660 }else{ 1661 pBest->db = sqlite3_context_db_handle(context); 1662 sqlite3VdbeMemCopy(pBest, pArg); 1663 } 1664 } 1665 static void minMaxValueFinalize(sqlite3_context *context, int bValue){ 1666 sqlite3_value *pRes; 1667 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); 1668 if( pRes ){ 1669 if( pRes->flags ){ 1670 sqlite3_result_value(context, pRes); 1671 } 1672 if( bValue==0 ) sqlite3VdbeMemRelease(pRes); 1673 } 1674 } 1675 #ifndef SQLITE_OMIT_WINDOWFUNC 1676 static void minMaxValue(sqlite3_context *context){ 1677 minMaxValueFinalize(context, 1); 1678 } 1679 #else 1680 # define minMaxValue 0 1681 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1682 static void minMaxFinalize(sqlite3_context *context){ 1683 minMaxValueFinalize(context, 0); 1684 } 1685 1686 /* 1687 ** group_concat(EXPR, ?SEPARATOR?) 1688 */ 1689 static void groupConcatStep( 1690 sqlite3_context *context, 1691 int argc, 1692 sqlite3_value **argv 1693 ){ 1694 const char *zVal; 1695 StrAccum *pAccum; 1696 const char *zSep; 1697 int nVal, nSep; 1698 assert( argc==1 || argc==2 ); 1699 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 1700 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); 1701 1702 if( pAccum ){ 1703 sqlite3 *db = sqlite3_context_db_handle(context); 1704 int firstTerm = pAccum->mxAlloc==0; 1705 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; 1706 if( !firstTerm ){ 1707 if( argc==2 ){ 1708 zSep = (char*)sqlite3_value_text(argv[1]); 1709 nSep = sqlite3_value_bytes(argv[1]); 1710 }else{ 1711 zSep = ","; 1712 nSep = 1; 1713 } 1714 if( zSep ) sqlite3_str_append(pAccum, zSep, nSep); 1715 } 1716 zVal = (char*)sqlite3_value_text(argv[0]); 1717 nVal = sqlite3_value_bytes(argv[0]); 1718 if( zVal ) sqlite3_str_append(pAccum, zVal, nVal); 1719 } 1720 } 1721 #ifndef SQLITE_OMIT_WINDOWFUNC 1722 static void groupConcatInverse( 1723 sqlite3_context *context, 1724 int argc, 1725 sqlite3_value **argv 1726 ){ 1727 int n; 1728 StrAccum *pAccum; 1729 assert( argc==1 || argc==2 ); 1730 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 1731 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); 1732 /* pAccum is always non-NULL since groupConcatStep() will have always 1733 ** run frist to initialize it */ 1734 if( ALWAYS(pAccum) ){ 1735 n = sqlite3_value_bytes(argv[0]); 1736 if( argc==2 ){ 1737 n += sqlite3_value_bytes(argv[1]); 1738 }else{ 1739 n++; 1740 } 1741 if( n>=(int)pAccum->nChar ){ 1742 pAccum->nChar = 0; 1743 }else{ 1744 pAccum->nChar -= n; 1745 memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar); 1746 } 1747 if( pAccum->nChar==0 ) pAccum->mxAlloc = 0; 1748 } 1749 } 1750 #else 1751 # define groupConcatInverse 0 1752 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1753 static void groupConcatFinalize(sqlite3_context *context){ 1754 StrAccum *pAccum; 1755 pAccum = sqlite3_aggregate_context(context, 0); 1756 if( pAccum ){ 1757 if( pAccum->accError==SQLITE_TOOBIG ){ 1758 sqlite3_result_error_toobig(context); 1759 }else if( pAccum->accError==SQLITE_NOMEM ){ 1760 sqlite3_result_error_nomem(context); 1761 }else{ 1762 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 1763 sqlite3_free); 1764 } 1765 } 1766 } 1767 #ifndef SQLITE_OMIT_WINDOWFUNC 1768 static void groupConcatValue(sqlite3_context *context){ 1769 sqlite3_str *pAccum; 1770 pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0); 1771 if( pAccum ){ 1772 if( pAccum->accError==SQLITE_TOOBIG ){ 1773 sqlite3_result_error_toobig(context); 1774 }else if( pAccum->accError==SQLITE_NOMEM ){ 1775 sqlite3_result_error_nomem(context); 1776 }else{ 1777 const char *zText = sqlite3_str_value(pAccum); 1778 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); 1779 } 1780 } 1781 } 1782 #else 1783 # define groupConcatValue 0 1784 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1785 1786 /* 1787 ** This routine does per-connection function registration. Most 1788 ** of the built-in functions above are part of the global function set. 1789 ** This routine only deals with those that are not global. 1790 */ 1791 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ 1792 int rc = sqlite3_overload_function(db, "MATCH", 2); 1793 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); 1794 if( rc==SQLITE_NOMEM ){ 1795 sqlite3OomFault(db); 1796 } 1797 } 1798 1799 /* 1800 ** Re-register the built-in LIKE functions. The caseSensitive 1801 ** parameter determines whether or not the LIKE operator is case 1802 ** sensitive. 1803 */ 1804 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ 1805 struct compareInfo *pInfo; 1806 int flags; 1807 if( caseSensitive ){ 1808 pInfo = (struct compareInfo*)&likeInfoAlt; 1809 flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE; 1810 }else{ 1811 pInfo = (struct compareInfo*)&likeInfoNorm; 1812 flags = SQLITE_FUNC_LIKE; 1813 } 1814 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); 1815 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); 1816 sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags; 1817 sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags; 1818 } 1819 1820 /* 1821 ** pExpr points to an expression which implements a function. If 1822 ** it is appropriate to apply the LIKE optimization to that function 1823 ** then set aWc[0] through aWc[2] to the wildcard characters and the 1824 ** escape character and then return TRUE. If the function is not a 1825 ** LIKE-style function then return FALSE. 1826 ** 1827 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE 1828 ** operator if c is a string literal that is exactly one byte in length. 1829 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is 1830 ** no ESCAPE clause. 1831 ** 1832 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for 1833 ** the function (default for LIKE). If the function makes the distinction 1834 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to 1835 ** false. 1836 */ 1837 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ 1838 FuncDef *pDef; 1839 int nExpr; 1840 if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){ 1841 return 0; 1842 } 1843 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 1844 nExpr = pExpr->x.pList->nExpr; 1845 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0); 1846 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ 1847 return 0; 1848 } 1849 if( nExpr<3 ){ 1850 aWc[3] = 0; 1851 }else{ 1852 Expr *pEscape = pExpr->x.pList->a[2].pExpr; 1853 char *zEscape; 1854 if( pEscape->op!=TK_STRING ) return 0; 1855 zEscape = pEscape->u.zToken; 1856 if( zEscape[0]==0 || zEscape[1]!=0 ) return 0; 1857 aWc[3] = zEscape[0]; 1858 } 1859 1860 /* The memcpy() statement assumes that the wildcard characters are 1861 ** the first three statements in the compareInfo structure. The 1862 ** asserts() that follow verify that assumption 1863 */ 1864 memcpy(aWc, pDef->pUserData, 3); 1865 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); 1866 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); 1867 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); 1868 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; 1869 return 1; 1870 } 1871 1872 /* 1873 ** All of the FuncDef structures in the aBuiltinFunc[] array above 1874 ** to the global function hash table. This occurs at start-time (as 1875 ** a consequence of calling sqlite3_initialize()). 1876 ** 1877 ** After this routine runs 1878 */ 1879 void sqlite3RegisterBuiltinFunctions(void){ 1880 /* 1881 ** The following array holds FuncDef structures for all of the functions 1882 ** defined in this file. 1883 ** 1884 ** The array cannot be constant since changes are made to the 1885 ** FuncDef.pHash elements at start-time. The elements of this array 1886 ** are read-only after initialization is complete. 1887 ** 1888 ** For peak efficiency, put the most frequently used function last. 1889 */ 1890 static FuncDef aBuiltinFunc[] = { 1891 #ifdef SQLITE_SOUNDEX 1892 FUNCTION(soundex, 1, 0, 0, soundexFunc ), 1893 #endif 1894 #ifndef SQLITE_OMIT_LOAD_EXTENSION 1895 VFUNCTION(load_extension, 1, 0, 0, loadExt ), 1896 VFUNCTION(load_extension, 2, 0, 0, loadExt ), 1897 #endif 1898 #if SQLITE_USER_AUTHENTICATION 1899 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), 1900 #endif 1901 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 1902 DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), 1903 DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), 1904 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 1905 FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), 1906 FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), 1907 FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), 1908 #ifdef SQLITE_DEBUG 1909 FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY), 1910 #endif 1911 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 1912 FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET| 1913 SQLITE_FUNC_TYPEOF), 1914 #endif 1915 FUNCTION(ltrim, 1, 1, 0, trimFunc ), 1916 FUNCTION(ltrim, 2, 1, 0, trimFunc ), 1917 FUNCTION(rtrim, 1, 2, 0, trimFunc ), 1918 FUNCTION(rtrim, 2, 2, 0, trimFunc ), 1919 FUNCTION(trim, 1, 3, 0, trimFunc ), 1920 FUNCTION(trim, 2, 3, 0, trimFunc ), 1921 FUNCTION(min, -1, 0, 1, minmaxFunc ), 1922 FUNCTION(min, 0, 0, 1, 0 ), 1923 WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, 1924 SQLITE_FUNC_MINMAX ), 1925 FUNCTION(max, -1, 1, 1, minmaxFunc ), 1926 FUNCTION(max, 0, 1, 1, 0 ), 1927 WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, 1928 SQLITE_FUNC_MINMAX ), 1929 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), 1930 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), 1931 FUNCTION(instr, 2, 0, 0, instrFunc ), 1932 FUNCTION(printf, -1, 0, 0, printfFunc ), 1933 FUNCTION(unicode, 1, 0, 0, unicodeFunc ), 1934 FUNCTION(char, -1, 0, 0, charFunc ), 1935 FUNCTION(abs, 1, 0, 0, absFunc ), 1936 #ifndef SQLITE_OMIT_FLOATING_POINT 1937 FUNCTION(round, 1, 0, 0, roundFunc ), 1938 FUNCTION(round, 2, 0, 0, roundFunc ), 1939 #endif 1940 FUNCTION(upper, 1, 0, 0, upperFunc ), 1941 FUNCTION(lower, 1, 0, 0, lowerFunc ), 1942 FUNCTION(hex, 1, 0, 0, hexFunc ), 1943 FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), 1944 VFUNCTION(random, 0, 0, 0, randomFunc ), 1945 VFUNCTION(randomblob, 1, 0, 0, randomBlob ), 1946 FUNCTION(nullif, 2, 0, 1, nullifFunc ), 1947 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), 1948 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), 1949 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), 1950 FUNCTION(quote, 1, 0, 0, quoteFunc ), 1951 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), 1952 VFUNCTION(changes, 0, 0, 0, changes ), 1953 VFUNCTION(total_changes, 0, 0, 0, total_changes ), 1954 FUNCTION(replace, 3, 0, 0, replaceFunc ), 1955 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), 1956 FUNCTION(substr, 2, 0, 0, substrFunc ), 1957 FUNCTION(substr, 3, 0, 0, substrFunc ), 1958 WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0), 1959 WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0), 1960 WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0), 1961 WAGGREGATE(count, 0,0,0, countStep, 1962 countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ), 1963 WAGGREGATE(count, 1,0,0, countStep, 1964 countFinalize, countFinalize, countInverse, 0 ), 1965 WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, 1966 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), 1967 WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, 1968 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), 1969 1970 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 1971 #ifdef SQLITE_CASE_SENSITIVE_LIKE 1972 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 1973 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 1974 #else 1975 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), 1976 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), 1977 #endif 1978 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 1979 FUNCTION(unknown, -1, 0, 0, unknownFunc ), 1980 #endif 1981 FUNCTION(coalesce, 1, 0, 0, 0 ), 1982 FUNCTION(coalesce, 0, 0, 0, 0 ), 1983 FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), 1984 }; 1985 #ifndef SQLITE_OMIT_ALTERTABLE 1986 sqlite3AlterFunctions(); 1987 #endif 1988 sqlite3WindowFunctions(); 1989 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4) 1990 sqlite3AnalyzeFunctions(); 1991 #endif 1992 sqlite3RegisterDateTimeFunctions(); 1993 sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); 1994 1995 #if 0 /* Enable to print out how the built-in functions are hashed */ 1996 { 1997 int i; 1998 FuncDef *p; 1999 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ 2000 printf("FUNC-HASH %02d:", i); 2001 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){ 2002 int n = sqlite3Strlen30(p->zName); 2003 int h = p->zName[0] + n; 2004 printf(" %s(%d)", p->zName, h); 2005 } 2006 printf("\n"); 2007 } 2008 } 2009 #endif 2010 } 2011