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