Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/func.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / func.c` 3620 lines ยท 114152 bytes Raw Blame History 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 18 #include 19 #ifndef SQLITE_OMIT_FLOATING_POINT 20 #include 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=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 && ienc<=SQLITE_UTF8 ? 1 : 2; 174 sqlite3_result_int64(context, sqlite3_value_bytes(argv[0])*m); 175 break; 176 } 177 case SQLITE_TEXT: { 178 if( sqlite3_value_encoding(argv[0])<=SQLITE_UTF8 ){ 179 sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); 180 }else{ 181 sqlite3_result_int(context, sqlite3_value_bytes16(argv[0])); 182 } 183 break; 184 } 185 default: { 186 sqlite3_result_null(context); 187 break; 188 } 189 } 190 } 191 192 /* 193 ** Implementation of the abs() function. 194 ** 195 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of 196 ** the numeric argument X. 197 */ 198 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 199 assert( argc==1 ); 200 UNUSED_PARAMETER(argc); 201 switch( sqlite3_value_type(argv[0]) ){ 202 case SQLITE_INTEGER: { 203 i64 iVal = sqlite3_value_int64(argv[0]); 204 if( iVal<0 ){ 205 if( iVal==SMALLEST_INT64 ){ 206 /* IMP: R-31676-45509 If X is the integer -`9223372036854775808` 207 ** then abs(X) throws an integer overflow error since there is no 208 ** equivalent positive 64-bit two complement value. */ 209 sqlite3_result_error(context, "integer overflow", -1); 210 return; 211 } 212 iVal = -iVal; 213 } 214 sqlite3_result_int64(context, iVal); 215 break; 216 } 217 case SQLITE_NULL: { 218 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ 219 sqlite3_result_null(context); 220 break; 221 } 222 default: { 223 /* Because sqlite3_value_double() returns 0.0 if the argument is not 224 ** something that can be converted into a number, we have: 225 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob 226 ** that cannot be converted to a numeric value. 227 */ 228 double rVal = sqlite3_value_double(argv[0]); 229 if( signbit(rVal) ) rVal = -rVal; 230 sqlite3_result_double(context, rVal); 231 break; 232 } 233 } 234 } 235 236 /* 237 ** Implementation of the instr() function. 238 ** 239 ** instr(haystack,needle) finds the first occurrence of needle 240 ** in haystack and returns the number of previous characters plus 1, 241 ** or 0 if needle does not occur within haystack. 242 ** 243 ** If both haystack and needle are BLOBs, then the result is one more than 244 ** the number of bytes in haystack prior to the first occurrence of needle, 245 ** or 0 if needle never occurs in haystack. 246 */ 247 static void instrFunc( 248 sqlite3_context *context, 249 int argc, 250 sqlite3_value **argv 251 ){ 252 const unsigned char *zHaystack; 253 const unsigned char *zNeedle; 254 int nHaystack; 255 int nNeedle; 256 int typeHaystack, typeNeedle; 257 int N = 1; 258 int isText; 259 unsigned char firstChar; 260 sqlite3_value *pC1 = 0; 261 sqlite3_value *pC2 = 0; 262 263 UNUSED_PARAMETER(argc); 264 typeHaystack = sqlite3_value_type(argv[0]); 265 typeNeedle = sqlite3_value_type(argv[1]); 266 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; 267 nHaystack = sqlite3_value_bytes(argv[0]); 268 nNeedle = sqlite3_value_bytes(argv[1]); 269 if( nNeedle>0 ){ 270 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ 271 zHaystack = sqlite3_value_blob(argv[0]); 272 zNeedle = sqlite3_value_blob(argv[1]); 273 isText = 0; 274 }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){ 275 zHaystack = sqlite3_value_text(argv[0]); 276 zNeedle = sqlite3_value_text(argv[1]); 277 isText = 1; 278 }else{ 279 pC1 = sqlite3_value_dup(argv[0]); 280 zHaystack = sqlite3_value_text(pC1); 281 if( zHaystack==0 ) goto endInstrOOM; 282 nHaystack = sqlite3_value_bytes(pC1); 283 pC2 = sqlite3_value_dup(argv[1]); 284 zNeedle = sqlite3_value_text(pC2); 285 if( zNeedle==0 ) goto endInstrOOM; 286 nNeedle = sqlite3_value_bytes(pC2); 287 isText = 1; 288 } 289 if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM; 290 firstChar = zNeedle[0]; 291 while( nNeedle<=nHaystack 292 && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0) 293 ){ 294 N++; 295 do{ 296 nHaystack--; 297 zHaystack++; 298 }while( isText && (zHaystack[0]&0xc0)==0x80 ); 299 } 300 if( nNeedle>nHaystack ) N = 0; 301 } 302 sqlite3_result_int(context, N); 303 endInstr: 304 sqlite3_value_free(pC1); 305 sqlite3_value_free(pC2); 306 return; 307 endInstrOOM: 308 sqlite3_result_error_nomem(context); 309 goto endInstr; 310 } 311 312 /* 313 ** Implementation of the printf() (a.k.a. format()) SQL function. 314 */ 315 static void printfFunc( 316 sqlite3_context *context, 317 int argc, 318 sqlite3_value **argv 319 ){ 320 PrintfArguments x; 321 StrAccum str; 322 const char *zFormat; 323 sqlite3 *db = sqlite3_context_db_handle(context); 324 325 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 326 x.nArg = argc-1; 327 x.nUsed = 0; 328 x.apArg = argv+1; 329 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); 330 str.printfFlags = SQLITE_PRINTF_SQLFUNC; 331 sqlite3_str_appendf(&str, zFormat, &x); 332 sqlite3_result_str(context, &str, SQLITE_XFER); 333 } 334 } 335 336 /* Return true if any of the eight bytes in word is NUL or non-ASCII. */ 337 static SQLITE_INLINE int containsNulOrNonAscii(u64 word){ 338 const u64 byteOnes = UINT64_C(0x0101010101010101); 339 const u64 byteHighBits = UINT64_C(0x8080808080808080); 340 /* NUL causes a borrow into a high bit; non-ASCII already has one set. */ 341 return ((word | (word - byteOnes)) & byteHighBits)!=0; 342 } 343 344 /* 345 ** Implementation of the substr() function. 346 ** 347 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. 348 ** p1 is 1-indexed. So substr(x,1,1) returns the first character 349 ** of x. If x is text, then we actually count UTF-8 characters. 350 ** If x is a blob, then we count bytes. 351 ** 352 ** If p1 is negative, then we begin abs(p1) from the end of x[]. 353 ** 354 ** If p2 is negative, return the p2 characters preceding p1. 355 */ 356 static void substrFunc( 357 sqlite3_context *context, 358 int argc, 359 sqlite3_value **argv 360 ){ 361 const unsigned char *z; 362 const unsigned char *z2; 363 int len; 364 int p0type; 365 i64 p1, p2; 366 367 assert( argc==3 || argc==2 ); 368 p0type = sqlite3_value_type(argv[0]); 369 p1 = sqlite3_value_int64(argv[1]); 370 if( p0type==SQLITE_BLOB ){ 371 len = sqlite3_value_bytes(argv[0]); 372 if( len==0){ 373 /* sqlite3_value_blob() returns a NULL pointer for a zero-length blob. 374 ** But the call to sqlite3_result_blob() below interprets a NULL pointer 375 ** as an SQL NULL. So set z to point to some non-NULL location here. */ 376 z = (const unsigned char*)""; 377 }else{ 378 z = sqlite3_value_blob(argv[0]); 379 if( z==0 ) return; 380 } 381 assert( len==sqlite3_value_bytes(argv[0]) ); 382 }else{ 383 z = sqlite3_value_text(argv[0]); 384 if( z==0 ) return; 385 len = 0; 386 if( p1<0 ){ 387 for(z2=z; *z2; len++){ 388 SQLITE_SKIP_UTF8(z2); 389 } 390 } 391 } 392 if( argc==3 ){ 393 p2 = sqlite3_value_int64(argv[2]); 394 if( p2==0 && sqlite3_value_type(argv[2])==SQLITE_NULL ) return; 395 }else{ 396 p2 = LARGEST_INT64; 397 } 398 if( p1==0 ){ 399 #ifdef SQLITE_SUBSTR_COMPATIBILITY 400 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as 401 ** as substr(X,1,N) - it returns the first N characters of X. This 402 ** is essentially a back-out of the bug-fix in check-in [`5fc125d362df4b8`] 403 ** from 2009-02-02 for compatibility of applications that exploited the 404 ** old buggy behavior. */ 405 p1 = 1; /* */ 406 #endif 407 if( sqlite3_value_type(argv[1])==SQLITE_NULL ) return; 408 } 409 if( p1<0 ){ 410 p1 += len; 411 if( p1<0 ){ 412 if( p2<0 ){ 413 p2 = 0; 414 }else if( argc==3 ){ 415 p2 += p1; 416 } 417 p1 = 0; 418 } 419 }else if( p1>0 ){ 420 p1--; 421 }else if( p2>0 ){ 422 p2--; 423 } 424 if( p2<0 ){ 425 if( p2<-p1 ){ 426 p2 = p1; 427 }else{ 428 p2 = -p2; 429 } 430 p1 -= p2; 431 } 432 assert( p1>=0 && p2>=0 ); 433 if( p0type!=SQLITE_BLOB ){ 434 if( p1>=8 ){ 435 /* Skip 8 characters at a time while all 8 bytes are in 0x01..0x7f */ 436 const unsigned char *zEnd = z + sqlite3_value_bytes(argv[0]); 437 while( p1>=8 && zEnd-z>=8 ){ 438 u64 word; 439 memcpy(&word, z, sizeof(word)); 440 /* Handle NUL and UTF-8 with the scalar loop below. */ 441 if( containsNulOrNonAscii(word) ){ 442 break; 443 } 444 z += 8; 445 p1 -= 8; 446 } 447 } 448 for( ; p1>0; p1--){ 449 /* vvvvvv---- See tag-`20260418`-01 */ 450 if( (u8)(z[0]-1)<(0x80-1) ){ 451 z++; 452 }else if( z[0]==0 ){ 453 break; 454 }else{ 455 do{ z++; }while( (z[0]&0xc0)==0x80 ); 456 } 457 } 458 for(z2=z; p2>0; p2--){ 459 /* vvvvvv---- See tag-`20260418`-01 */ 460 if( (u8)(z2[0]-1)<(0x80-1) ){ 461 z2++; 462 }else if( z2[0]==0 ){ 463 break; 464 }else{ 465 do{ z2++; }while( (z2[0]&0xc0)==0x80 ); 466 } 467 } 468 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, 469 SQLITE_UTF8); 470 }else{ 471 if( p1>=len ){ 472 p1 = p2 = 0; 473 }else if( p2>len-p1 ){ 474 p2 = len-p1; 475 assert( p2>0 ); 476 } 477 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); 478 } 479 } 480 481 /* 482 ** Implementation of the round() function 483 */ 484 #ifndef SQLITE_OMIT_FLOATING_POINT 485 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 486 i64 n = 0; 487 double r; 488 char *zBuf; 489 assert( argc==1 || argc==2 ); 490 if( argc==2 ){ 491 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; 492 n = sqlite3_value_int64(argv[1]); 493 if( n>30 ) n = 30; 494 if( n<0 ) n = 0; 495 } 496 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 497 r = sqlite3_value_double(argv[0]); 498 /* If Y==0 and X will fit in a 64-bit int, 499 ** handle the rounding directly, 500 ** otherwise use printf. 501 */ 502 if( r<-`4503599627370496`.0 || r>+`4503599627370496`.0 ){ 503 /* The value has no fractional part so there is nothing to round */ 504 }else{ 505 zBuf = sqlite3_mprintf("%#!.*f",(int)n,r); 506 if( zBuf==0 ){ 507 sqlite3_result_error_nomem(context); 508 return; 509 } 510 sqlite3AtoF(zBuf, &r); 511 sqlite3_free(zBuf); 512 } 513 sqlite3_result_double(context, r); 514 } 515 #endif 516 517 /* 518 ** Allocate nByte bytes of space using sqlite3Malloc(). If the 519 ** allocation fails, call sqlite3_result_error_nomem() to notify 520 ** the database handle that malloc() has failed and return NULL. 521 ** If nByte is larger than the maximum string or blob length, then 522 ** raise an SQLITE_TOOBIG exception and return NULL. 523 */ 524 static void *contextMalloc(sqlite3_context *context, i64 nByte){ 525 char *z; 526 sqlite3 *db = sqlite3_context_db_handle(context); 527 assert( nByte>0 ); 528 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); 529 testcase( nByte==(i64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); 530 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 531 sqlite3_result_error_toobig(context); 532 z = 0; 533 }else{ 534 z = sqlite3Malloc(nByte); 535 if( !z ){ 536 sqlite3_result_error_nomem(context); 537 } 538 } 539 return z; 540 } 541 542 /* 543 ** Implementation of the upper() and lower() SQL functions. 544 */ 545 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 546 char *z1; 547 const char *z2; 548 int i, n; 549 UNUSED_PARAMETER(argc); 550 z2 = (char*)sqlite3_value_text(argv[0]); 551 n = sqlite3_value_bytes(argv[0]); 552 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 553 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 554 if( z2 ){ 555 z1 = contextMalloc(context, ((i64)n)+1); 556 if( z1 ){ 557 for(i=0; imatchOne; /* "?" or "_" */ 777 u32 matchAll = pInfo->matchAll; /* "*" or "%" */ 778 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ 779 const u8 *zEscaped = 0; /* One past the last escaped input char */ 780 781 while( (c = Utf8Read(zPattern))!=0 ){ 782 if( c==matchAll ){ /* Match "*" */ 783 /* Skip over multiple "*" characters in the pattern. If there 784 ** are also "?" characters, skip those as well, but consume a 785 ** single character of the input string for each "?" skipped */ 786 while( (c=Utf8Read(zPattern)) == matchAll 787 || (c == matchOne && matchOne!=0) ){ 788 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ 789 return SQLITE_NOWILDCARDMATCH; 790 } 791 } 792 if( c==0 ){ 793 return SQLITE_MATCH; /* "*" at the end of the pattern matches */ 794 }else if( c==matchOther ){ 795 if( pInfo->matchSet==0 ){ 796 c = sqlite3Utf8Read(&zPattern); 797 if( c==0 ) return SQLITE_NOWILDCARDMATCH; 798 }else{ 799 /* "[...]" immediately follows the "*". We have to do a slow 800 ** recursive search in this case, but it is an unusual case. */ 801 assert( matchOther<0x80 ); /* '[' is a single-byte character */ 802 while( *zString ){ 803 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); 804 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 805 SQLITE_SKIP_UTF8(zString); 806 } 807 return SQLITE_NOWILDCARDMATCH; 808 } 809 } 810 811 /* At this point variable c contains the first character of the 812 ** pattern string past the "*". Search in the input string for the 813 ** first matching character and recursively continue the match from 814 ** that point. 815 ** 816 ** For a case-insensitive search, set variable cx to be the same as 817 ** c but in the other case and search the input string for either 818 ** c or cx. 819 */ 820 if( c<0x80 ){ 821 char zStop[3]; 822 int bMatch; 823 /* If the next pattern character is an ordinary ASCII character, 824 ** then a candidate position can only match if the next input 825 ** character is nx or ny. Check that inline, to avoid most of the 826 ** recursive calls. nx==0 disables this check. */ 827 u8 nx = zPattern[0], ny = nx; 828 if( nx>=0x80 || nx==matchAll || nx==matchOne || nx==matchOther ){ 829 nx = 0; 830 } 831 if( noCase ){ 832 zStop[0] = sqlite3Toupper(c); 833 zStop[1] = sqlite3Tolower(c); 834 zStop[2] = 0; 835 nx = sqlite3Toupper(nx); 836 ny = sqlite3Tolower(ny); 837 }else{ 838 zStop[0] = c; 839 zStop[1] = 0; 840 } 841 while(1){ 842 zString += strcspn((const char*)zString, zStop); 843 if( zString[0]==0 ) break; 844 zString++; 845 if( nx && zString[0]!=nx && zString[0]!=ny ) continue; 846 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 847 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 848 } 849 }else{ 850 int bMatch; 851 while( (c2 = Utf8Read(zString))!=0 ){ 852 if( c2!=c ) continue; 853 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 854 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 855 } 856 } 857 return SQLITE_NOWILDCARDMATCH; 858 } 859 if( c==matchOther ){ 860 if( pInfo->matchSet==0 ){ 861 c = sqlite3Utf8Read(&zPattern); 862 if( c==0 ) return SQLITE_NOMATCH; 863 zEscaped = zPattern; 864 }else{ 865 u32 prior_c = 0; 866 int seen = 0; 867 int invert = 0; 868 c = sqlite3Utf8Read(&zString); 869 if( c==0 ) return SQLITE_NOMATCH; 870 c2 = sqlite3Utf8Read(&zPattern); 871 if( c2=='^' ){ 872 invert = 1; 873 c2 = sqlite3Utf8Read(&zPattern); 874 } 875 if( c2==']' ){ 876 if( c==']' ) seen = 1; 877 c2 = sqlite3Utf8Read(&zPattern); 878 } 879 while( c2 && c2!=']' ){ 880 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ 881 c2 = sqlite3Utf8Read(&zPattern); 882 if( c>=prior_c && c<=c2 ) seen = 1; 883 prior_c = 0; 884 }else{ 885 if( c==c2 ){ 886 seen = 1; 887 } 888 prior_c = c2; 889 } 890 c2 = sqlite3Utf8Read(&zPattern); 891 } 892 if( c2==0 || (seen ^ invert)==0 ){ 893 return SQLITE_NOMATCH; 894 } 895 continue; 896 } 897 } 898 c2 = Utf8Read(zString); 899 if( c==c2 ) continue; 900 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ 901 continue; 902 } 903 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; 904 return SQLITE_NOMATCH; 905 } 906 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; 907 } 908 909 /* 910 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and 911 ** non-zero if there is no match. 912 */ 913 int sqlite3_strglob(const char *zGlobPattern, const char *zString){ 914 if( zString==0 ){ 915 return zGlobPattern!=0; 916 }else if( zGlobPattern==0 ){ 917 return 1; 918 }else { 919 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); 920 } 921 } 922 923 /* 924 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for 925 ** a miss - like strcmp(). 926 */ 927 int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ 928 if( zStr==0 ){ 929 return zPattern!=0; 930 }else if( zPattern==0 ){ 931 return 1; 932 }else{ 933 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); 934 } 935 } 936 937 /* 938 ** Count the number of times that the LIKE operator (or GLOB which is 939 ** just a variation of LIKE) gets called. This is used for testing 940 ** only. 941 */ 942 #ifdef SQLITE_TEST 943 int sqlite3_like_count = 0; 944 #endif 945 946 947 /* 948 ** Implementation of the like() SQL function. This function implements 949 ** the built-in LIKE operator. The first argument to the function is the 950 ** pattern and the second argument is the string. So, the SQL statements: 951 ** 952 ** A LIKE B 953 ** 954 ** is implemented as like(B,A). 955 ** 956 ** This same function (with a different compareInfo structure) computes 957 ** the GLOB operator. 958 */ 959 static void likeFunc( 960 sqlite3_context *context, 961 int argc, 962 sqlite3_value **argv 963 ){ 964 const unsigned char *zA, *zB; 965 u32 escape; 966 int nPat; 967 sqlite3 *db = sqlite3_context_db_handle(context); 968 struct compareInfo *pInfo = sqlite3_user_data(context); 969 struct compareInfo backupInfo; 970 971 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 972 if( sqlite3_value_type(argv[0])==SQLITE_BLOB 973 || sqlite3_value_type(argv[1])==SQLITE_BLOB 974 ){ 975 #ifdef SQLITE_TEST 976 sqlite3_like_count++; 977 #endif 978 sqlite3_result_int(context, 0); 979 return; 980 } 981 #endif 982 983 /* Limit the length of the LIKE or GLOB pattern to avoid problems 984 ** of deep recursion and N*N behavior in patternCompare(). 985 */ 986 nPat = sqlite3_value_bytes(argv[0]); 987 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); 988 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); 989 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ 990 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); 991 return; 992 } 993 if( argc==3 ){ 994 /* The escape character string must consist of a single UTF-8 character. 995 ** Otherwise, return an error. 996 */ 997 const unsigned char *zEsc = sqlite3_value_text(argv[2]); 998 if( zEsc==0 ) return; 999 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ 1000 sqlite3_result_error(context, 1001 "ESCAPE expression must be a single character", -1); 1002 return; 1003 } 1004 escape = sqlite3Utf8Read(&zEsc); 1005 if( escape==pInfo->matchAll || escape==pInfo->matchOne ){ 1006 memcpy(&backupInfo, pInfo, sizeof(backupInfo)); 1007 pInfo = &backupInfo; 1008 if( escape==pInfo->matchAll ) pInfo->matchAll = 0; 1009 if( escape==pInfo->matchOne ) pInfo->matchOne = 0; 1010 } 1011 }else{ 1012 escape = pInfo->matchSet; 1013 } 1014 zB = sqlite3_value_text(argv[0]); 1015 zA = sqlite3_value_text(argv[1]); 1016 if( zA && zB ){ 1017 #ifdef SQLITE_TEST 1018 sqlite3_like_count++; 1019 #endif 1020 sqlite3_result_int(context, 1021 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); 1022 } 1023 } 1024 1025 /* 1026 ** Implementation of the NULLIF(x,y) function. The result is the first 1027 ** argument if the arguments are different. The result is NULL if the 1028 ** arguments are equal to each other. 1029 */ 1030 static void nullifFunc( 1031 sqlite3_context *context, 1032 int NotUsed, 1033 sqlite3_value **argv 1034 ){ 1035 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 1036 UNUSED_PARAMETER(NotUsed); 1037 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ 1038 sqlite3_result_value(context, argv[0]); 1039 } 1040 } 1041 1042 /* 1043 ** Implementation of the sqlite_version() function. The result is the version 1044 ** of the SQLite library that is running. 1045 */ 1046 static void versionFunc( 1047 sqlite3_context *context, 1048 int NotUsed, 1049 sqlite3_value **NotUsed2 1050 ){ 1051 UNUSED_PARAMETER2(NotUsed, NotUsed2); 1052 /* IMP: R-48699-48617 This function is an SQL wrapper around the 1053 ** sqlite3_libversion() C-interface. */ 1054 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); 1055 } 1056 1057 /* 1058 ** Implementation of the sqlite_source_id() function. The result is a string 1059 ** that identifies the particular version of the source code used to build 1060 ** SQLite. 1061 */ 1062 static void sourceidFunc( 1063 sqlite3_context *context, 1064 int NotUsed, 1065 sqlite3_value **NotUsed2 1066 ){ 1067 UNUSED_PARAMETER2(NotUsed, NotUsed2); 1068 /* IMP: R-24470-31136 This function is an SQL wrapper around the 1069 ** sqlite3_sourceid() C interface. */ 1070 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); 1071 } 1072 1073 /* 1074 ** Implementation of the sqlite_log() function. This is a wrapper around 1075 ** sqlite3_log(). The return value is NULL. The function exists purely for 1076 ** its side-effects. 1077 */ 1078 static void errlogFunc( 1079 sqlite3_context *context, 1080 int argc, 1081 sqlite3_value **argv 1082 ){ 1083 UNUSED_PARAMETER(argc); 1084 UNUSED_PARAMETER(context); 1085 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); 1086 } 1087 1088 /* 1089 ** Implementation of the sqlite_compileoption_used() function. 1090 ** The result is an integer that identifies if the compiler option 1091 ** was used to build SQLite. 1092 */ 1093 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 1094 static void compileoptionusedFunc( 1095 sqlite3_context *context, 1096 int argc, 1097 sqlite3_value **argv 1098 ){ 1099 const char *zOptName; 1100 assert( argc==1 ); 1101 UNUSED_PARAMETER(argc); 1102 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL 1103 ** function is a wrapper around the sqlite3_compileoption_used() C/C++ 1104 ** function. 1105 */ 1106 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 1107 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); 1108 } 1109 } 1110 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 1111 1112 /* 1113 ** Implementation of the sqlite_compileoption_get() function. 1114 ** The result is a string that identifies the compiler options 1115 ** used to build SQLite. 1116 */ 1117 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 1118 static void compileoptiongetFunc( 1119 sqlite3_context *context, 1120 int argc, 1121 sqlite3_value **argv 1122 ){ 1123 i64 n; 1124 const char *zRes; 1125 assert( argc==1 ); 1126 UNUSED_PARAMETER(argc); 1127 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function 1128 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. 1129 */ 1130 n = sqlite3_value_int64(argv[0]); 1131 /* Use a negative lower bound to assist testing of the 1132 ** sqlite3_compileoption_get() C-language interface and its handling 1133 ** of negative inputs. 1134 ** vvvvv */ 1135 zRes = (n>=(-10) && n<10000) ? sqlite3_compileoption_get((int)n) : 0; 1136 sqlite3_result_text(context, zRes, -1, SQLITE_STATIC); 1137 } 1138 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 1139 1140 /* Array for converting from half-bytes (nybbles) into ASCII hex 1141 ** digits. */ 1142 static const char hexdigits[] = { 1143 '0', '1', '2', '3', '4', '5', '6', '7', 1144 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 1145 }; 1146 1147 /* 1148 ** Append to pStr text that is the SQL literal representation of the 1149 ** value contained in pValue. 1150 */ 1151 void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue, int bEscape){ 1152 /* As currently implemented, the string must be initially empty. 1153 ** we might relax this requirement in the future, but that will 1154 ** require enhancements to the implementation. */ 1155 assert( pStr!=0 && pStr->nChar==0 ); 1156 1157 switch( sqlite3_value_type(pValue) ){ 1158 case SQLITE_FLOAT: { 1159 /* ,--- Show infinity as 9.0e+999 1160 ** | 1161 ** | ,--- 17 precision guarantees round-trip 1162 ** v v */ 1163 sqlite3_str_appendf(pStr, "%!0.17g", sqlite3_value_double(pValue)); 1164 break; 1165 } 1166 case SQLITE_INTEGER: { 1167 sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue)); 1168 break; 1169 } 1170 case SQLITE_BLOB: { 1171 char const *zBlob = sqlite3_value_blob(pValue); 1172 i64 nBlob = sqlite3_value_bytes(pValue); 1173 assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */ 1174 sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4); 1175 if( pStr->accError==0 ){ 1176 char *zText = pStr->zText; 1177 int i; 1178 for(i=0; i>4)&0x0F]; 1180 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; 1181 } 1182 zText[(nBlob*2)+2] = '\''; 1183 zText[(nBlob*2)+3] = '\0'; 1184 zText[0] = 'X'; 1185 zText[1] = '\''; 1186 pStr->nChar = nBlob*2 + 3; 1187 } 1188 break; 1189 } 1190 case SQLITE_TEXT: { 1191 const unsigned char *zArg = sqlite3_value_text(pValue); 1192 sqlite3_str_appendf(pStr, bEscape ? "%#Q" : "%Q", zArg); 1193 break; 1194 } 1195 default: { 1196 assert( sqlite3_value_type(pValue)==SQLITE_NULL ); 1197 sqlite3_str_append(pStr, "NULL", 4); 1198 break; 1199 } 1200 } 1201 } 1202 1203 /* 1204 ** Return true if z[] begins with N hexadecimal digits, and write 1205 ** a decoding of those digits into *pVal. Or return false if any 1206 ** one of the first N characters in z[] is not a hexadecimal digit. 1207 */ 1208 static int isNHex(const char *z, int N, u32 *pVal){ 1209 int i; 1210 u32 v = 0; 1211 for(i=0; i0 ){ 1264 memmove(&zOut[j], &zIn[i], n); 1265 j += n; 1266 i += n; 1267 } 1268 if( zIn[i+1]=='\\' ){ 1269 i += 2; 1270 zOut[j++] = '\\'; 1271 }else if( sqlite3Isxdigit(zIn[i+1]) ){ 1272 if( !isNHex(&zIn[i+1], 4, &v) ) goto unistr_error; 1273 i += 5; 1274 j += sqlite3AppendOneUtf8Character(&zOut[j], v); 1275 }else if( zIn[i+1]=='+' ){ 1276 if( !isNHex(&zIn[i+2], 6, &v) ) goto unistr_error; 1277 i += 8; 1278 j += sqlite3AppendOneUtf8Character(&zOut[j], v); 1279 }else if( zIn[i+1]=='u' ){ 1280 if( !isNHex(&zIn[i+2], 4, &v) ) goto unistr_error; 1281 i += 6; 1282 j += sqlite3AppendOneUtf8Character(&zOut[j], v); 1283 }else if( zIn[i+1]=='U' ){ 1284 if( !isNHex(&zIn[i+2], 8, &v) ) goto unistr_error; 1285 i += 10; 1286 j += sqlite3AppendOneUtf8Character(&zOut[j], v); 1287 }else{ 1288 goto unistr_error; 1289 } 1290 } 1291 zOut[j] = 0; 1292 sqlite3_result_text64(context, zOut, j, sqlite3_free, SQLITE_UTF8_ZT); 1293 return; 1294 1295 unistr_error: 1296 sqlite3_free(zOut); 1297 sqlite3_result_error(context, "invalid Unicode escape", -1); 1298 return; 1299 } 1300 1301 1302 /* 1303 ** Implementation of the QUOTE() function. 1304 ** 1305 ** The quote(X) function returns the text of an SQL literal which is the 1306 ** value of its argument suitable for inclusion into an SQL statement. 1307 ** Strings are surrounded by single-quotes with escapes on interior quotes 1308 ** as needed. BLOBs are encoded as hexadecimal literals. Strings with 1309 ** embedded NUL characters cannot be represented as string literals in SQL 1310 ** and hence the returned string literal is truncated prior to the first NUL. 1311 ** 1312 ** If sqlite3_user_data() is non-zero, then the UNISTR_QUOTE() function is 1313 ** implemented instead. The difference is that UNISTR_QUOTE() uses the 1314 ** UNISTR() function to escape control characters. 1315 */ 1316 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 1317 sqlite3_str str; 1318 sqlite3 *db = sqlite3_context_db_handle(context); 1319 assert( argc==1 ); 1320 UNUSED_PARAMETER(argc); 1321 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); 1322 sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context))); 1323 sqlite3_result_str(context, &str, SQLITE_XFER); 1324 } 1325 1326 /* 1327 ** The unicode() function. Return the integer unicode code-point value 1328 ** for the first character of the input string. 1329 */ 1330 static void unicodeFunc( 1331 sqlite3_context *context, 1332 int argc, 1333 sqlite3_value **argv 1334 ){ 1335 const unsigned char *z = sqlite3_value_text(argv[0]); 1336 (void)argc; 1337 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); 1338 } 1339 1340 /* 1341 ** The char() function takes zero or more arguments, each of which is 1342 ** an integer. It constructs a string where each character of the string 1343 ** is the unicode character for the corresponding integer argument. 1344 */ 1345 static void charFunc( 1346 sqlite3_context *context, 1347 int argc, 1348 sqlite3_value **argv 1349 ){ 1350 unsigned char *z, *zOut; 1351 int i; 1352 zOut = z = sqlite3_malloc64( argc*4+1 ); 1353 if( z==0 ){ 1354 sqlite3_result_error_nomem(context); 1355 return; 1356 } 1357 for(i=0; i0x10ffff ) x = 0xfffd; 1362 c = (unsigned)(x & 0x1fffff); 1363 if( c<0x00080 ){ 1364 *zOut++ = (u8)(c&0xFF); 1365 }else if( c<0x00800 ){ 1366 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); 1367 *zOut++ = 0x80 + (u8)(c & 0x3F); 1368 }else if( c<0x10000 ){ 1369 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); 1370 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 1371 *zOut++ = 0x80 + (u8)(c & 0x3F); 1372 }else{ 1373 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); 1374 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); 1375 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 1376 *zOut++ = 0x80 + (u8)(c & 0x3F); 1377 } \ 1378 } 1379 *zOut = 0; 1380 sqlite3_result_text64(context, (char*)z, zOut-z,sqlite3_free,SQLITE_UTF8_ZT); 1381 } 1382 1383 /* 1384 ** The hex() function. Interpret the argument as a blob. Return 1385 ** a hexadecimal rendering as text. 1386 */ 1387 static void hexFunc( 1388 sqlite3_context *context, 1389 int argc, 1390 sqlite3_value **argv 1391 ){ 1392 int i, n; 1393 const unsigned char *pBlob; 1394 char *zHex, *z; 1395 assert( argc==1 ); 1396 UNUSED_PARAMETER(argc); 1397 pBlob = sqlite3_value_blob(argv[0]); 1398 n = sqlite3_value_bytes(argv[0]); 1399 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ 1400 z = zHex = contextMalloc(context, ((i64)n)*2 + 1); 1401 if( zHex ){ 1402 for(i=0; i>4)&0xf]; 1405 *(z++) = hexdigits[c&0xf]; 1406 } 1407 *z = 0; 1408 sqlite3_result_text64(context, zHex, (u64)(z-zHex), 1409 sqlite3_free, SQLITE_UTF8_ZT); 1410 } 1411 } 1412 1413 /* 1414 ** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr 1415 ** contains character ch, or 0 if it does not. 1416 */ 1417 static int strContainsChar(const u8 *zStr, int nStr, u32 ch){ 1418 const u8 *zEnd = &zStr[nStr]; 1419 const u8 *z = zStr; 1420 while( zmallocFailed ); 1557 return; 1558 } 1559 if( zPattern[0]==0 ){ 1560 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); 1561 sqlite3_result_text(context, (const char*)zStr, nStr, SQLITE_TRANSIENT); 1562 return; 1563 } 1564 nPattern = sqlite3_value_bytes(argv[1]); 1565 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ 1566 zRep = sqlite3_value_text(argv[2]); 1567 if( zRep==0 ) return; 1568 nRep = sqlite3_value_bytes(argv[2]); 1569 assert( zRep==sqlite3_value_text(argv[2]) ); 1570 nOut = nStr + 1; 1571 assert( nOutnPattern ){ 1583 nOut += nRep - nPattern; 1584 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); 1585 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); 1586 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 1587 sqlite3_result_error_toobig(context); 1588 sqlite3_free(zOut); 1589 return; 1590 } 1591 cntExpand++; 1592 if( (cntExpand&(cntExpand-1))==0 ){ 1593 /* Grow the size of the output buffer only on substitutions 1594 ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */ 1595 u8 *zOld; 1596 zOld = zOut; 1597 zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1)); 1598 if( zOut==0 ){ 1599 sqlite3_result_error_nomem(context); 1600 sqlite3_free(zOld); 1601 return; 1602 } 1603 } 1604 } 1605 memcpy(&zOut[j], zRep, nRep); 1606 j += nRep; 1607 i += nPattern-1; 1608 } 1609 } 1610 assert( j+nStr-i+1<=nOut ); 1611 memcpy(&zOut[j], &zStr[i], nStr-i); 1612 j += nStr - i; 1613 assert( j<=nOut ); 1614 zOut[j] = 0; 1615 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); 1616 } 1617 1618 /* 1619 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. 1620 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. 1621 */ 1622 static void trimFunc( 1623 sqlite3_context *context, 1624 int argc, 1625 sqlite3_value **argv 1626 ){ 1627 const unsigned char *zIn; /* Input string */ 1628 const unsigned char *zCharSet; /* Set of characters to trim */ 1629 unsigned int nIn; /* Number of bytes in input */ 1630 int flags; /* 1: trimleft 2: trimright 3: trim */ 1631 int i; /* Loop counter */ 1632 unsigned int *aLen = 0; /* Length of each character in zCharSet */ 1633 unsigned char **azChar = 0; /* Individual characters in zCharSet */ 1634 int nChar; /* Number of characters in zCharSet */ 1635 1636 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1637 return; 1638 } 1639 zIn = sqlite3_value_text(argv[0]); 1640 if( zIn==0 ) return; 1641 nIn = (unsigned)sqlite3_value_bytes(argv[0]); 1642 assert( zIn==sqlite3_value_text(argv[0]) ); 1643 if( argc==1 ){ 1644 static const unsigned lenOne[] = { 1 }; 1645 static unsigned char * const azOne[] = { (u8*)" " }; 1646 nChar = 1; 1647 aLen = (unsigned*)lenOne; 1648 azChar = (unsigned char **)azOne; 1649 zCharSet = 0; 1650 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ 1651 return; 1652 }else{ 1653 const unsigned char *z; 1654 for(z=zCharSet, nChar=0; *z; nChar++){ 1655 SQLITE_SKIP_UTF8(z); 1656 } 1657 if( nChar>0 ){ 1658 azChar = contextMalloc(context, 1659 ((i64)nChar)*(sizeof(char*)+sizeof(unsigned))); 1660 if( azChar==0 ){ 1661 return; 1662 } 1663 aLen = (unsigned*)&azChar[nChar]; 1664 for(z=zCharSet, nChar=0; *z; nChar++){ 1665 azChar[nChar] = (unsigned char *)z; 1666 SQLITE_SKIP_UTF8(z); 1667 aLen[nChar] = (unsigned)(z - azChar[nChar]); 1668 } 1669 } 1670 } 1671 if( nChar>0 ){ 1672 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); 1673 if( flags & 1 ){ 1674 while( nIn>0 ){ 1675 unsigned int len = 0; 1676 for(i=0; i=nChar ) break; 1681 zIn += len; 1682 nIn -= len; 1683 } 1684 } 1685 if( flags & 2 ){ 1686 while( nIn>0 ){ 1687 unsigned int len = 0; 1688 for(i=0; i=nChar ) break; 1693 nIn -= len; 1694 } 1695 } 1696 if( zCharSet ){ 1697 sqlite3_free(azChar); 1698 } 1699 } 1700 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); 1701 } 1702 1703 /* The core implementation of the CONCAT(...) and CONCAT_WS(SEP,...) 1704 ** functions. 1705 ** 1706 ** Return a string value that is the concatenation of all non-null 1707 ** entries in argv[]. Use zSep as the separator. 1708 */ 1709 static void concatFuncCore( 1710 sqlite3_context *context, 1711 int argc, 1712 sqlite3_value **argv, 1713 int nSep, 1714 const char *zSep 1715 ){ 1716 i64 j, n = 0; 1717 int i; 1718 int bNotNull = 0; /* True after at least NOT NULL argument seen */ 1719 char *z; 1720 for(i=0; i0 ){ 1736 memcpy(&z[j], zSep, nSep); 1737 j += nSep; 1738 } 1739 memcpy(&z[j], v, k); 1740 j += k; 1741 bNotNull = 1; 1742 } 1743 } 1744 } 1745 z[j] = 0; 1746 assert( j<=n ); 1747 sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8_ZT); 1748 } 1749 1750 /* 1751 ** The CONCAT(...) function. Generate a string result that is the 1752 ** concatentation of all non-null arguments. 1753 */ 1754 static void concatFunc( 1755 sqlite3_context *context, 1756 int argc, 1757 sqlite3_value **argv 1758 ){ 1759 concatFuncCore(context, argc, argv, 0, ""); 1760 } 1761 1762 /* 1763 ** The CONCAT_WS(separator, ...) function. 1764 ** 1765 ** Generate a string that is the concatenation of 2nd through the Nth 1766 ** argument. Use the first argument (which must be non-NULL) as the 1767 ** separator. 1768 */ 1769 static void concatwsFunc( 1770 sqlite3_context *context, 1771 int argc, 1772 sqlite3_value **argv 1773 ){ 1774 int nSep = sqlite3_value_bytes(argv[0]); 1775 const char *zSep = (const char*)sqlite3_value_text(argv[0]); 1776 if( zSep==0 ) return; 1777 concatFuncCore(context, argc-1, argv+1, nSep, zSep); 1778 } 1779 1780 1781 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 1782 /* 1783 ** The "unknown" function is automatically substituted in place of 1784 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN 1785 ** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used. 1786 ** When the "sqlite3" command-line shell is built using this functionality, 1787 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries 1788 ** involving application-defined functions to be examined in a generic 1789 ** sqlite3 shell. 1790 */ 1791 static void unknownFunc( 1792 sqlite3_context *context, 1793 int argc, 1794 sqlite3_value **argv 1795 ){ 1796 /* no-op */ 1797 (void)context; 1798 (void)argc; 1799 (void)argv; 1800 } 1801 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ 1802 1803 1804 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It 1805 ** is only available if the SQLITE_SOUNDEX compile-time option is used 1806 ** when SQLite is built. 1807 */ 1808 #ifdef SQLITE_SOUNDEX 1809 /* 1810 ** Compute the soundex encoding of a word. 1811 ** 1812 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the 1813 ** soundex encoding of the string X. 1814 */ 1815 static void soundexFunc( 1816 sqlite3_context *context, 1817 int argc, 1818 sqlite3_value **argv 1819 ){ 1820 char zResult[8]; 1821 const u8 *zIn; 1822 int i, j; 1823 static const unsigned char iCode[] = { 1824 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1825 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1826 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1827 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1828 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1829 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 1830 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1831 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 1832 }; 1833 assert( argc==1 ); 1834 zIn = (u8*)sqlite3_value_text(argv[0]); 1835 if( zIn==0 ) zIn = (u8*)""; 1836 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} 1837 if( zIn[i] ){ 1838 u8 prevcode = iCode[zIn[i]&0x7f]; 1839 zResult[0] = sqlite3Toupper(zIn[i]); 1840 for(j=1; j<4 && zIn[i]; i++){ 1841 int code = iCode[zIn[i]&0x7f]; 1842 if( code>0 ){ 1843 if( code!=prevcode ){ 1844 prevcode = code; 1845 zResult[j++] = code + '0'; 1846 } 1847 }else{ 1848 prevcode = 0; 1849 } 1850 } 1851 while( j<4 ){ 1852 zResult[j++] = '0'; 1853 } 1854 zResult[j] = 0; 1855 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); 1856 }else{ 1857 /* IMP: R-64894-50321 The string "?000" is returned if the argument 1858 ** is NULL or contains no ASCII alphabetic characters. */ 1859 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); 1860 } 1861 } 1862 #endif /* SQLITE_SOUNDEX */ 1863 1864 #if defined(SQLITE_DEBUG) || defined(SQLITE_BUILTIN_OOM_FUNCTION) 1865 /* 1866 ** This SQL function just invokes sqlite3OomFault() and then returns 1867 ** NULL. Used for testing only. 1868 */ 1869 static void oomFunc( 1870 sqlite3_context *context, 1871 int argc, 1872 sqlite3_value **argv 1873 ){ 1874 sqlite3 *db = sqlite3_context_db_handle(context); 1875 sqlite3OomFault(db); 1876 } 1877 #endif /* SQLITE_DEBUG || SQLITE_BUILTIN_OOM_FUNCTION */ 1878 1879 #ifndef SQLITE_OMIT_LOAD_EXTENSION 1880 /* 1881 ** A function that loads a shared-library extension then returns NULL. 1882 */ 1883 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ 1884 const char *zFile = (const char *)sqlite3_value_text(argv[0]); 1885 const char *zProc; 1886 sqlite3 *db = sqlite3_context_db_handle(context); 1887 char *zErrMsg = 0; 1888 1889 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc 1890 ** flag is set. See the sqlite3_enable_load_extension() API. 1891 */ 1892 if( (db->flags & SQLITE_LoadExtFunc)==0 ){ 1893 sqlite3_result_error(context, "not authorized", -1); 1894 return; 1895 } 1896 1897 if( argc==2 ){ 1898 zProc = (const char *)sqlite3_value_text(argv[1]); 1899 }else{ 1900 zProc = 0; 1901 } 1902 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ 1903 sqlite3_result_error(context, zErrMsg, -1); 1904 sqlite3_free(zErrMsg); 1905 } 1906 } 1907 #endif 1908 1909 1910 /* 1911 ** An instance of the following structure holds the context of a 1912 ** sum() or avg() aggregate computation. 1913 */ 1914 typedef struct SumCtx SumCtx; 1915 struct SumCtx { 1916 double rSum; /* Running sum as as a double */ 1917 double rErr; /* Error term for Kahan-Babushka-Neumaier summation */ 1918 i64 iSum; /* Running sum as a signed integer */ 1919 i64 cnt; /* Number of elements summed */ 1920 u8 approx; /* True if any non-integer value was input to the sum */ 1921 u8 ovrfl; /* Integer overflow seen */ 1922 }; 1923 1924 /* 1925 ** Do one step of the Kahan-Babushka-Neumaier summation. 1926 ** 1927 ** https://en.wikipedia.org/wiki/Kahan_summation_algorithm 1928 ** 1929 ** Variables are marked "volatile" to defeat c89 x86 floating point 1930 ** optimizations can mess up this algorithm. 1931 */ 1932 static void kahanBabuskaNeumaierStep( 1933 volatile SumCtx *pSum, 1934 volatile double r 1935 ){ 1936 volatile double s = pSum->rSum; 1937 volatile double t = s + r; 1938 if( fabs(s) > fabs(r) ){ 1939 pSum->rErr += (s - t) + r; 1940 }else{ 1941 pSum->rErr += (r - t) + s; 1942 } 1943 pSum->rSum = t; 1944 } 1945 1946 /* 1947 ** Add a (possibly large) integer to the running sum. 1948 */ 1949 static void kahanBabuskaNeumaierStepInt64(volatile SumCtx *pSum, i64 iVal){ 1950 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){ 1951 i64 iBig, iSm; 1952 iSm = iVal % 16384; 1953 iBig = iVal - iSm; 1954 kahanBabuskaNeumaierStep(pSum, iBig); 1955 kahanBabuskaNeumaierStep(pSum, iSm); 1956 }else{ 1957 kahanBabuskaNeumaierStep(pSum, (double)iVal); 1958 } 1959 } 1960 1961 /* 1962 ** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer 1963 */ 1964 static void kahanBabuskaNeumaierInit( 1965 volatile SumCtx *p, 1966 i64 iVal 1967 ){ 1968 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){ 1969 i64 iSm = iVal % 16384; 1970 p->rSum = (double)(iVal - iSm); 1971 p->rErr = (double)iSm; 1972 }else{ 1973 p->rSum = (double)iVal; 1974 p->rErr = 0.0; 1975 } 1976 } 1977 1978 /* 1979 ** Routines used to compute the sum, average, and total. 1980 ** 1981 ** The SUM() function follows the (broken) SQL standard which means 1982 ** that it returns NULL if it sums over no inputs. TOTAL returns 1983 ** 0.0 in that case. In addition, TOTAL always returns a float where 1984 ** SUM might return an integer if it never encounters a floating point 1985 ** value. TOTAL never fails, but SUM might throw an exception if 1986 ** it overflows an integer. 1987 */ 1988 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 1989 SumCtx *p; 1990 int type; 1991 assert( argc==1 ); 1992 UNUSED_PARAMETER(argc); 1993 p = sqlite3_aggregate_context(context, sizeof(*p)); 1994 type = sqlite3_value_numeric_type(argv[0]); 1995 if( p && type!=SQLITE_NULL ){ 1996 p->cnt++; 1997 if( p->approx==0 ){ 1998 if( type!=SQLITE_INTEGER ){ 1999 kahanBabuskaNeumaierInit(p, p->iSum); 2000 p->approx = 1; 2001 kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0])); 2002 }else{ 2003 i64 x = p->iSum; 2004 if( sqlite3AddInt64(&x, sqlite3_value_int64(argv[0]))==0 ){ 2005 p->iSum = x; 2006 }else{ 2007 p->ovrfl = 1; 2008 kahanBabuskaNeumaierInit(p, p->iSum); 2009 p->approx = 1; 2010 kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0])); 2011 } 2012 } 2013 }else{ 2014 if( type==SQLITE_INTEGER ){ 2015 kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0])); 2016 }else{ 2017 p->ovrfl = 0; 2018 kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0])); 2019 } 2020 } 2021 } 2022 } 2023 #ifndef SQLITE_OMIT_WINDOWFUNC 2024 static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ 2025 SumCtx *p; 2026 int type; 2027 assert( argc==1 ); 2028 UNUSED_PARAMETER(argc); 2029 p = sqlite3_aggregate_context(context, sizeof(*p)); 2030 type = sqlite3_value_numeric_type(argv[0]); 2031 /* p is always non-NULL because sumStep() will have been called first 2032 ** to initialize it */ 2033 if( ALWAYS(p) && type!=SQLITE_NULL ){ 2034 assert( p->cnt>0 ); 2035 p->cnt--; 2036 if( !p->approx ){ 2037 i64 x = p->iSum; 2038 if( sqlite3SubInt64(&x, sqlite3_value_int64(argv[0]))==0 ){ 2039 p->iSum = x; 2040 return; 2041 } 2042 p->ovrfl = 1; 2043 p->approx = 1; 2044 kahanBabuskaNeumaierInit(p, p->iSum); 2045 } 2046 if( type==SQLITE_INTEGER ){ 2047 i64 iVal = sqlite3_value_int64(argv[0]); 2048 if( iVal!=SMALLEST_INT64 ){ 2049 kahanBabuskaNeumaierStepInt64(p, -iVal); 2050 }else{ 2051 kahanBabuskaNeumaierStepInt64(p, LARGEST_INT64); 2052 kahanBabuskaNeumaierStepInt64(p, 1); 2053 } 2054 }else{ 2055 kahanBabuskaNeumaierStep(p, -sqlite3_value_double(argv[0])); 2056 } 2057 } 2058 } 2059 #else 2060 # define sumInverse 0 2061 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2062 static void sumFinalize(sqlite3_context *context){ 2063 SumCtx *p; 2064 p = sqlite3_aggregate_context(context, 0); 2065 if( p && p->cnt>0 ){ 2066 if( p->approx ){ 2067 if( p->ovrfl ){ 2068 sqlite3_result_error(context,"integer overflow",-1); 2069 }else if( !sqlite3IsOverflow(p->rErr) ){ 2070 sqlite3_result_double(context, p->rSum+p->rErr); 2071 }else{ 2072 sqlite3_result_double(context, p->rSum); 2073 } 2074 }else{ 2075 sqlite3_result_int64(context, p->iSum); 2076 } 2077 } 2078 } 2079 static void avgFinalize(sqlite3_context *context){ 2080 SumCtx *p; 2081 p = sqlite3_aggregate_context(context, 0); 2082 if( p && p->cnt>0 ){ 2083 double r; 2084 if( p->approx ){ 2085 r = p->rSum; 2086 if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr; 2087 }else{ 2088 r = (double)(p->iSum); 2089 } 2090 sqlite3_result_double(context, r/(double)p->cnt); 2091 } 2092 } 2093 static void totalFinalize(sqlite3_context *context){ 2094 SumCtx *p; 2095 double r = 0.0; 2096 p = sqlite3_aggregate_context(context, 0); 2097 if( p ){ 2098 if( p->approx ){ 2099 r = p->rSum; 2100 if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr; 2101 }else{ 2102 r = (double)(p->iSum); 2103 } 2104 } 2105 sqlite3_result_double(context, r); 2106 } 2107 2108 /* 2109 ** The following structure keeps track of state information for the 2110 ** count() aggregate function. 2111 */ 2112 typedef struct CountCtx CountCtx; 2113 struct CountCtx { 2114 i64 n; 2115 #ifdef SQLITE_DEBUG 2116 int bInverse; /* True if xInverse() ever called */ 2117 #endif 2118 }; 2119 2120 /* 2121 ** Routines to implement the count() aggregate function. 2122 */ 2123 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 2124 CountCtx *p; 2125 p = sqlite3_aggregate_context(context, sizeof(*p)); 2126 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ 2127 p->n++; 2128 } 2129 2130 #ifndef SQLITE_OMIT_DEPRECATED 2131 /* The sqlite3_aggregate_count() function is deprecated. But just to make 2132 ** sure it still operates correctly, verify that its count agrees with our 2133 ** internal count when using count(*) and when the total count can be 2134 ** expressed as a 32-bit integer. */ 2135 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse 2136 || p->n==sqlite3_aggregate_count(context) ); 2137 #endif 2138 } 2139 static void countFinalize(sqlite3_context *context){ 2140 CountCtx *p; 2141 p = sqlite3_aggregate_context(context, 0); 2142 sqlite3_result_int64(context, p ? p->n : 0); 2143 } 2144 #ifndef SQLITE_OMIT_WINDOWFUNC 2145 static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){ 2146 CountCtx *p; 2147 p = sqlite3_aggregate_context(ctx, sizeof(*p)); 2148 /* p is always non-NULL since countStep() will have been called first */ 2149 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){ 2150 p->n--; 2151 #ifdef SQLITE_DEBUG 2152 p->bInverse = 1; 2153 #endif 2154 } 2155 } 2156 #else 2157 # define countInverse 0 2158 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2159 2160 /* 2161 ** Routines to implement min() and max() aggregate functions. 2162 */ 2163 static void minmaxStep( 2164 sqlite3_context *context, 2165 int NotUsed, 2166 sqlite3_value **argv 2167 ){ 2168 Mem *pArg = (Mem *)argv[0]; 2169 Mem *pBest; 2170 UNUSED_PARAMETER(NotUsed); 2171 2172 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); 2173 if( !pBest ) return; 2174 2175 if( sqlite3_value_type(pArg)==SQLITE_NULL ){ 2176 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); 2177 }else if( pBest->flags ){ 2178 int max; 2179 int cmp; 2180 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 2181 /* This step function is used for both the min() and max() aggregates, 2182 ** the only difference between the two being that the sense of the 2183 ** comparison is inverted. For the max() aggregate, the 2184 ** sqlite3_user_data() function returns (void *)-1. For min() it 2185 ** returns (void *)db, where db is the sqlite3* database pointer. 2186 ** Therefore the next statement sets variable 'max' to 1 for the max() 2187 ** aggregate, or 0 for min(). 2188 */ 2189 max = sqlite3_user_data(context)!=0; 2190 cmp = sqlite3MemCompare(pBest, pArg, pColl); 2191 if( (max && cmp<0) || (!max && cmp>0) ){ 2192 sqlite3VdbeMemCopy(pBest, pArg); 2193 }else{ 2194 sqlite3SkipAccumulatorLoad(context); 2195 } 2196 }else{ 2197 pBest->db = sqlite3_context_db_handle(context); 2198 sqlite3VdbeMemCopy(pBest, pArg); 2199 } 2200 } 2201 static void minMaxValueFinalize(sqlite3_context *context, int bValue){ 2202 sqlite3_value *pRes; 2203 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); 2204 if( pRes ){ 2205 if( pRes->flags ){ 2206 sqlite3_result_value(context, pRes); 2207 } 2208 if( bValue==0 ) sqlite3VdbeMemRelease(pRes); 2209 } 2210 } 2211 #ifndef SQLITE_OMIT_WINDOWFUNC 2212 static void minMaxValue(sqlite3_context *context){ 2213 minMaxValueFinalize(context, 1); 2214 } 2215 #else 2216 # define minMaxValue 0 2217 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2218 static void minMaxFinalize(sqlite3_context *context){ 2219 minMaxValueFinalize(context, 0); 2220 } 2221 2222 /* 2223 ** group_concat(EXPR, ?SEPARATOR?) 2224 ** string_agg(EXPR, SEPARATOR) 2225 ** 2226 ** Content is accumulated in GroupConcatCtx.str with the SEPARATOR 2227 ** coming before the EXPR value, except for the first entry which 2228 ** omits the SEPARATOR. 2229 ** 2230 ** It is tragic that the SEPARATOR goes before the EXPR string. The 2231 ** groupConcatInverse() implementation would have been easier if the 2232 ** SEPARATOR were appended after EXPR. And the order is undocumented, 2233 ** so we could change it, in theory. But the old behavior has been 2234 ** around for so long that we dare not, for fear of breaking something. 2235 */ 2236 typedef struct { 2237 StrAccum str; /* The accumulated concatenation */ 2238 #ifndef SQLITE_OMIT_WINDOWFUNC 2239 int nAccum; /* Number of strings presently concatenated */ 2240 int nFirstSepLength; /* Used to detect separator length change */ 2241 /* If pnSepLengths!=0, refs an array of inter-string separator lengths, 2242 ** stored as actually incorporated into presently accumulated result. 2243 ** (Hence, its slots in use number nAccum-1 between method calls.) 2244 ** If pnSepLengths==0, nFirstSepLength is the length used throughout. 2245 */ 2246 int *pnSepLengths; 2247 #endif 2248 } GroupConcatCtx; 2249 2250 static void groupConcatStep( 2251 sqlite3_context *context, 2252 int argc, 2253 sqlite3_value **argv 2254 ){ 2255 const char *zVal; 2256 GroupConcatCtx *pGCC; 2257 const char *zSep; 2258 int nVal, nSep; 2259 assert( argc==1 || argc==2 ); 2260 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 2261 pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC)); 2262 if( pGCC ){ 2263 sqlite3 *db = sqlite3_context_db_handle(context); 2264 int firstTerm = pGCC->str.mxAlloc==0; 2265 pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; 2266 if( argc==1 ){ 2267 if( !firstTerm ){ 2268 sqlite3_str_appendchar(&pGCC->str, 1, ','); 2269 } 2270 #ifndef SQLITE_OMIT_WINDOWFUNC 2271 else{ 2272 pGCC->nFirstSepLength = 1; 2273 } 2274 #endif 2275 }else if( !firstTerm ){ 2276 zSep = (char*)sqlite3_value_text(argv[1]); 2277 nSep = sqlite3_value_bytes(argv[1]); 2278 if( zSep ){ 2279 sqlite3_str_append(&pGCC->str, zSep, nSep); 2280 } 2281 #ifndef SQLITE_OMIT_WINDOWFUNC 2282 else{ 2283 nSep = 0; 2284 } 2285 if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){ 2286 int *pnsl = pGCC->pnSepLengths; 2287 if( pnsl == 0 ){ 2288 /* First separator length variation seen, start tracking them. */ 2289 pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int)); 2290 if( pnsl!=0 ){ 2291 int i = 0, nA = pGCC->nAccum-1; 2292 while( inFirstSepLength; 2293 } 2294 }else{ 2295 pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int)); 2296 } 2297 if( pnsl!=0 ){ 2298 if( ALWAYS(pGCC->nAccum>0) ){ 2299 pnsl[pGCC->nAccum-1] = nSep; 2300 } 2301 pGCC->pnSepLengths = pnsl; 2302 }else{ 2303 sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM); 2304 } 2305 } 2306 #endif 2307 } 2308 #ifndef SQLITE_OMIT_WINDOWFUNC 2309 else{ 2310 pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]); 2311 } 2312 pGCC->nAccum += 1; 2313 #endif 2314 zVal = (char*)sqlite3_value_text(argv[0]); 2315 nVal = sqlite3_value_bytes(argv[0]); 2316 if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal); 2317 } 2318 } 2319 2320 #ifndef SQLITE_OMIT_WINDOWFUNC 2321 static void groupConcatInverse( 2322 sqlite3_context *context, 2323 int argc, 2324 sqlite3_value **argv 2325 ){ 2326 GroupConcatCtx *pGCC; 2327 assert( argc==1 || argc==2 ); 2328 (void)argc; /* Suppress unused parameter warning */ 2329 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 2330 pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC)); 2331 /* pGCC is always non-NULL since groupConcatStep() will have always 2332 ** run first to initialize it */ 2333 if( ALWAYS(pGCC) ){ 2334 int nVS; /* Number of characters to remove */ 2335 /* Must call sqlite3_value_text() to convert the argument into text prior 2336 ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */ 2337 (void)sqlite3_value_text(argv[0]); 2338 nVS = sqlite3_value_bytes(argv[0]); 2339 pGCC->nAccum -= 1; 2340 if( pGCC->pnSepLengths!=0 ){ 2341 assert(pGCC->nAccum >= 0); 2342 if( pGCC->nAccum>0 ){ 2343 nVS += *pGCC->pnSepLengths; 2344 memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1, 2345 (pGCC->nAccum-1)*sizeof(int)); 2346 } 2347 }else{ 2348 /* If removing single accumulated string, harmlessly over-do. */ 2349 nVS += pGCC->nFirstSepLength; 2350 } 2351 if( nVS>=(int)pGCC->str.nChar ){ 2352 pGCC->str.nChar = 0; 2353 }else{ 2354 pGCC->str.nChar -= nVS; 2355 memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar); 2356 } 2357 if( pGCC->nAccum==0 ){ 2358 pGCC->str.mxAlloc = 0; 2359 sqlite3_free(pGCC->pnSepLengths); 2360 pGCC->pnSepLengths = 0; 2361 } 2362 } 2363 } 2364 #else 2365 # define groupConcatInverse 0 2366 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2367 static void groupConcatFinalize(sqlite3_context *context){ 2368 GroupConcatCtx *pGCC 2369 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0); 2370 if( pGCC ){ 2371 sqlite3_result_str(context, &pGCC->str, SQLITE_XFER); 2372 #ifndef SQLITE_OMIT_WINDOWFUNC 2373 sqlite3_free(pGCC->pnSepLengths); 2374 #endif 2375 } 2376 } 2377 #ifndef SQLITE_OMIT_WINDOWFUNC 2378 static void groupConcatValue(sqlite3_context *context){ 2379 GroupConcatCtx *pGCC 2380 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0); 2381 if( pGCC && pGCC->nAccum>0 ){ 2382 sqlite3_result_str(context, &pGCC->str, SQLITE_COPY); 2383 } 2384 } 2385 #else 2386 # define groupConcatValue 0 2387 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2388 2389 /* 2390 ** This routine does per-connection function registration. Most 2391 ** of the built-in functions above are part of the global function set. 2392 ** This routine only deals with those that are not global. 2393 */ 2394 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ 2395 int rc = sqlite3_overload_function(db, "MATCH", 2); 2396 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); 2397 if( rc==SQLITE_NOMEM ){ 2398 sqlite3OomFault(db); 2399 } 2400 } 2401 2402 /* 2403 ** Re-register the built-in LIKE functions. The caseSensitive 2404 ** parameter determines whether or not the LIKE operator is case 2405 ** sensitive. 2406 */ 2407 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ 2408 FuncDef *pDef; 2409 struct compareInfo *pInfo; 2410 int flags; 2411 int nArg; 2412 if( caseSensitive ){ 2413 pInfo = (struct compareInfo*)&likeInfoAlt; 2414 flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE; 2415 }else{ 2416 pInfo = (struct compareInfo*)&likeInfoNorm; 2417 flags = SQLITE_FUNC_LIKE; 2418 } 2419 for(nArg=2; nArg<=3; nArg++){ 2420 sqlite3CreateFunc(db, "like", nArg, SQLITE_UTF8, pInfo, likeFunc, 2421 0, 0, 0, 0, 0); 2422 pDef = sqlite3FindFunction(db, "like", nArg, SQLITE_UTF8, 0); 2423 assert( pDef!=0 ); /* The sqlite3CreateFunc() call above cannot fail 2424 ** because the "like" SQL-function already exists */ 2425 pDef->funcFlags |= flags; 2426 pDef->funcFlags &= ~SQLITE_FUNC_UNSAFE; 2427 } 2428 } 2429 2430 /* 2431 ** pExpr points to an expression which implements a function. If 2432 ** it is appropriate to apply the LIKE optimization to that function 2433 ** then set aWc[0] through aWc[2] to the wildcard characters and the 2434 ** escape character and then return TRUE. If the function is not a 2435 ** LIKE-style function then return FALSE. 2436 ** 2437 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE 2438 ** operator if c is a string literal that is exactly one byte in length. 2439 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is 2440 ** no ESCAPE clause. 2441 ** 2442 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for 2443 ** the function (default for LIKE). If the function makes the distinction 2444 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to 2445 ** false. 2446 */ 2447 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ 2448 FuncDef *pDef; 2449 int nExpr; 2450 assert( pExpr!=0 ); 2451 assert( pExpr->op==TK_FUNCTION ); 2452 assert( ExprUseXList(pExpr) ); 2453 if( !pExpr->x.pList ){ 2454 return 0; 2455 } 2456 nExpr = pExpr->x.pList->nExpr; 2457 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2458 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0); 2459 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 2460 if( pDef==0 ) return 0; 2461 #endif 2462 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ 2463 return 0; 2464 } 2465 2466 /* The memcpy() statement assumes that the wildcard characters are 2467 ** the first three statements in the compareInfo structure. The 2468 ** asserts() that follow verify that assumption 2469 */ 2470 memcpy(aWc, pDef->pUserData, 3); 2471 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); 2472 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); 2473 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); 2474 2475 if( nExpr<3 ){ 2476 aWc[3] = 0; 2477 }else{ 2478 Expr *pEscape = pExpr->x.pList->a[2].pExpr; 2479 char *zEscape; 2480 if( pEscape->op!=TK_STRING ) return 0; 2481 assert( !ExprHasProperty(pEscape, EP_IntValue) ); 2482 zEscape = pEscape->u.zToken; 2483 if( zEscape[0]==0 || zEscape[1]!=0 ) return 0; 2484 if( zEscape[0]==aWc[0] ) return 0; 2485 if( zEscape[0]==aWc[1] ) return 0; 2486 aWc[3] = zEscape[0]; 2487 } 2488 2489 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; 2490 return 1; 2491 } 2492 2493 /* Mathematical Constants */ 2494 #ifndef M_PI 2495 # define M_PI 3.`141592653589793238462643383279502884` 2496 #endif 2497 #ifndef M_LN10 2498 # define M_LN10 2.`302585092994045684017991454684364208` 2499 #endif 2500 #ifndef M_LN2 2501 # define M_LN2 0.`693147180559945309417232121458176568` 2502 #endif 2503 2504 2505 /* Extra math functions that require linking with -lm 2506 */ 2507 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS 2508 /* 2509 ** Implementation SQL functions: 2510 ** 2511 ** ceil(X) 2512 ** ceiling(X) 2513 ** floor(X) 2514 ** 2515 ** The sqlite3_user_data() pointer is a pointer to the libm implementation 2516 ** of the underlying C function. 2517 */ 2518 static void ceilingFunc( 2519 sqlite3_context *context, 2520 int argc, 2521 sqlite3_value **argv 2522 ){ 2523 assert( argc==1 ); 2524 switch( sqlite3_value_numeric_type(argv[0]) ){ 2525 case SQLITE_INTEGER: { 2526 sqlite3_result_int64(context, sqlite3_value_int64(argv[0])); 2527 break; 2528 } 2529 case SQLITE_FLOAT: { 2530 double (*x)(double) = (double(*)(double))sqlite3_user_data(context); 2531 sqlite3_result_double(context, x(sqlite3_value_double(argv[0]))); 2532 break; 2533 } 2534 default: { 2535 break; 2536 } 2537 } 2538 } 2539 2540 /* 2541 ** On some systems, ceil() and floor() are intrinsic function. You are 2542 ** unable to take a pointer to these functions. Hence, we here wrap them 2543 ** in our own actual functions. 2544 */ 2545 static double xCeil(double x){ return ceil(x); } 2546 static double xFloor(double x){ return floor(x); } 2547 2548 /* 2549 ** Some systems do not have log2() and log10() in their standard math 2550 ** libraries. 2551 */ 2552 #if defined(HAVE_LOG10) && HAVE_LOG10==0 2553 # define log10(X) (0.`4342944819032517867`*log(X)) 2554 #endif 2555 #if defined(HAVE_LOG2) && HAVE_LOG2==0 2556 # define log2(X) (1.`442695040888963456`*log(X)) 2557 #endif 2558 2559 2560 /* 2561 ** Implementation of SQL functions: 2562 ** 2563 ** ln(X) - natural logarithm 2564 ** log(X) - log X base 10 2565 ** log10(X) - log X base 10 2566 ** log(B,X) - log X base B 2567 */ 2568 static void logFunc( 2569 sqlite3_context *context, 2570 int argc, 2571 sqlite3_value **argv 2572 ){ 2573 double x, b, ans; 2574 assert( argc==1 || argc==2 ); 2575 switch( sqlite3_value_numeric_type(argv[0]) ){ 2576 case SQLITE_INTEGER: 2577 case SQLITE_FLOAT: 2578 x = sqlite3_value_double(argv[0]); 2579 if( x<=0.0 ) return; 2580 break; 2581 default: 2582 return; 2583 } 2584 if( argc==2 ){ 2585 switch( sqlite3_value_numeric_type(argv[1]) ){ 2586 case SQLITE_INTEGER: 2587 case SQLITE_FLOAT: 2588 b = log(x); 2589 if( b==0.0 ) return; 2590 x = sqlite3_value_double(argv[1]); 2591 if( x<=0.0 ) return; 2592 break; 2593 default: 2594 return; 2595 } 2596 ans = log(x)/b; 2597 }else{ 2598 switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context)) ){ 2599 case 1: 2600 ans = log10(x); 2601 break; 2602 case 2: 2603 ans = log2(x); 2604 break; 2605 default: 2606 ans = log(x); 2607 break; 2608 } 2609 } 2610 sqlite3_result_double(context, ans); 2611 } 2612 2613 /* 2614 ** Functions to converts degrees to radians and radians to degrees. 2615 */ 2616 static double degToRad(double x){ return x*(M_PI/180.0); } 2617 static double radToDeg(double x){ return x*(180.0/M_PI); } 2618 2619 /* 2620 ** Implementation of 1-argument SQL math functions: 2621 ** 2622 ** exp(X) - Compute e to the X-th power 2623 */ 2624 static void math1Func( 2625 sqlite3_context *context, 2626 int argc, 2627 sqlite3_value **argv 2628 ){ 2629 int type0; 2630 double v0, ans; 2631 double (*x)(double); 2632 assert( argc==1 ); 2633 type0 = sqlite3_value_numeric_type(argv[0]); 2634 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return; 2635 v0 = sqlite3_value_double(argv[0]); 2636 x = (double(*)(double))sqlite3_user_data(context); 2637 ans = x(v0); 2638 sqlite3_result_double(context, ans); 2639 } 2640 2641 /* 2642 ** Implementation of 2-argument SQL math functions: 2643 ** 2644 ** power(X,Y) - Compute X to the Y-th power 2645 */ 2646 static void math2Func( 2647 sqlite3_context *context, 2648 int argc, 2649 sqlite3_value **argv 2650 ){ 2651 int type0, type1; 2652 double v0, v1, ans; 2653 double (*x)(double,double); 2654 assert( argc==2 ); 2655 type0 = sqlite3_value_numeric_type(argv[0]); 2656 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return; 2657 type1 = sqlite3_value_numeric_type(argv[1]); 2658 if( type1!=SQLITE_INTEGER && type1!=SQLITE_FLOAT ) return; 2659 v0 = sqlite3_value_double(argv[0]); 2660 v1 = sqlite3_value_double(argv[1]); 2661 x = (double(*)(double,double))sqlite3_user_data(context); 2662 ans = x(v0, v1); 2663 sqlite3_result_double(context, ans); 2664 } 2665 2666 /* 2667 ** Implementation of 0-argument pi() function. 2668 */ 2669 static void piFunc( 2670 sqlite3_context *context, 2671 int argc, 2672 sqlite3_value **argv 2673 ){ 2674 assert( argc==0 ); 2675 (void)argv; 2676 sqlite3_result_double(context, M_PI); 2677 } 2678 2679 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */ 2680 2681 /* 2682 ** Implementation of sign(X) function. 2683 */ 2684 static void signFunc( 2685 sqlite3_context *context, 2686 int argc, 2687 sqlite3_value **argv 2688 ){ 2689 int type0; 2690 double x; 2691 UNUSED_PARAMETER(argc); 2692 assert( argc==1 ); 2693 type0 = sqlite3_value_numeric_type(argv[0]); 2694 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return; 2695 x = sqlite3_value_double(argv[0]); 2696 sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0); 2697 } 2698 2699 #if defined(SQLITE_ENABLE_PERCENTILE) 2700 /*********************************************************************** 2701 ** This section implements the percentile(Y,P) SQL function and similar. 2702 ** Requirements: 2703 ** 2704 ** (1) The percentile(Y,P) function is an aggregate function taking 2705 ** exactly two arguments. 2706 ** 2707 ** (2) If the P argument to percentile(Y,P) is not the same for every 2708 ** row in the aggregate then an error is thrown. The word "same" 2709 ** in the previous sentence means that the value differ by less 2710 ** than 0.001. 2711 ** 2712 ** (3) If the P argument to percentile(Y,P) evaluates to anything other 2713 ** than a number in the range of 0.0 to 100.0 inclusive then an 2714 ** error is thrown. 2715 ** 2716 ** (4) If any Y argument to percentile(Y,P) evaluates to a value that 2717 ** is not NULL and is not numeric then an error is thrown. 2718 ** 2719 ** (5) If any Y argument to percentile(Y,P) evaluates to plus or minus 2720 ** infinity then an error is thrown. (SQLite always interprets NaN 2721 ** values as NULL.) 2722 ** 2723 ** (6) Both Y and P in percentile(Y,P) can be arbitrary expressions, 2724 ** including CASE WHEN expressions. 2725 ** 2726 ** (7) The percentile(Y,P) aggregate is able to handle inputs of at least 2727 ** one million (1,000,000) rows. 2728 ** 2729 ** (8) If there are no non-NULL values for Y, then percentile(Y,P) 2730 ** returns NULL. 2731 ** 2732 ** (9) If there is exactly one non-NULL value for Y, the percentile(Y,P) 2733 ** returns the one Y value. 2734 ** 2735 ** (10) If there N non-NULL values of Y where N is two or more and 2736 ** the Y values are ordered from least to greatest and a graph is 2737 ** drawn from 0 to N-1 such that the height of the graph at J is 2738 ** the J-th Y value and such that straight lines are drawn between 2739 ** adjacent Y values, then the percentile(Y,P) function returns 2740 ** the height of the graph at P*(N-1)/100. 2741 ** 2742 ** (11) The percentile(Y,P) function always returns either a floating 2743 ** point number or NULL. 2744 ** 2745 ** (12) The percentile(Y,P) is implemented as a single C99 source-code 2746 ** file that compiles into a shared-library or DLL that can be loaded 2747 ** into SQLite using the sqlite3_load_extension() interface. 2748 ** 2749 ** (13) A separate median(Y) function is the equivalent percentile(Y,50). 2750 ** 2751 ** (14) A separate percentile_cont(Y,P) function is equivalent to 2752 ** percentile(Y,P/100.0). In other words, the fraction value in 2753 ** the second argument is in the range of 0 to 1 instead of 0 to 100. 2754 ** 2755 ** (15) A separate percentile_disc(Y,P) function is like 2756 ** percentile_cont(Y,P) except that instead of returning the weighted 2757 ** average of the nearest two input values, it returns the next lower 2758 ** value. So the percentile_disc(Y,P) will always return a value 2759 ** that was one of the inputs. 2760 ** 2761 ** (16) All of median(), percentile(Y,P), percentile_cont(Y,P) and 2762 ** percentile_disc(Y,P) can be used as window functions. 2763 ** 2764 ** Differences from standard SQL: 2765 ** 2766 ** * The percentile_cont(X,P) function is equivalent to the following in 2767 ** standard SQL: 2768 ** 2769 ** (percentile_cont(P) WITHIN GROUP (ORDER BY X)) 2770 ** 2771 ** The SQLite syntax is much more compact. The standard SQL syntax 2772 ** is also supported if SQLite is compiled with the 2773 ** -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES option. 2774 ** 2775 ** * No median(X) function exists in the SQL standard. App developers 2776 ** are expected to write "percentile_cont(0.5)WITHIN GROUP(ORDER BY X)". 2777 ** 2778 ** * No percentile(Y,P) function exists in the SQL standard. Instead of 2779 ** percential(Y,P), developers must write this: 2780 ** "percentile_cont(P/100.0) WITHIN GROUP (ORDER BY Y)". Note that 2781 ** the fraction parameter to percentile() goes from 0 to 100 whereas 2782 ** the fraction parameter in SQL standard percentile_cont() goes from 2783 ** 0 to 1. 2784 ** 2785 ** Implementation notes as of 2024-08-31: 2786 ** 2787 ** * The regular aggregate-function versions of these routines work 2788 ** by accumulating all values in an array of doubles, then sorting 2789 ** that array using quicksort before computing the answer. Thus 2790 ** the runtime is O(NlogN) where N is the number of rows of input. 2791 ** 2792 ** * For the window-function versions of these routines, the array of 2793 ** inputs is sorted as soon as the first value is computed. Thereafter, 2794 ** the array is kept in sorted order using an insert-sort. This 2795 ** results in O(N*K) performance where K is the size of the window. 2796 ** One can imagine alternative implementations that give O(N*logN*logK) 2797 ** performance, but they require more complex logic and data structures. 2798 ** The developers have elected to keep the asymptotically slower 2799 ** algorithm for now, for simplicity, under the theory that window 2800 ** functions are seldom used and when they are, the window size K is 2801 ** often small. The developers might revisit that decision later, 2802 ** should the need arise. 2803 */ 2804 2805 /* The following object is the group context for a single percentile() 2806 ** aggregate. Remember all input Y values until the very end. 2807 ** Those values are accumulated in the Percentile.a[] array. 2808 */ 2809 typedef struct Percentile Percentile; 2810 struct Percentile { 2811 u64 nAlloc; /* Number of slots allocated for a[] */ 2812 u64 nUsed; /* Number of slots actually used in a[] */ 2813 char bSorted; /* True if a[] is already in sorted order */ 2814 char bKeepSorted; /* True if advantageous to keep a[] sorted */ 2815 char bPctValid; /* True if rPct is valid */ 2816 double rPct; /* Fraction. 0.0 to 1.0 */ 2817 double *a; /* Array of Y values */ 2818 }; 2819 2820 /* 2821 ** Return TRUE if the input floating-point number is an infinity. 2822 */ 2823 static int percentIsInfinity(double r){ 2824 sqlite3_uint64 u; 2825 assert( sizeof(u)==sizeof(r) ); 2826 memcpy(&u, &r, sizeof(u)); 2827 return ((u>>52)&0x7ff)==0x7ff; 2828 } 2829 2830 /* 2831 ** Return TRUE if two doubles differ by 0.001 or less. 2832 */ 2833 static int percentSameValue(double a, double b){ 2834 a -= b; 2835 return a>=-0.001 && a<=0.001; 2836 } 2837 2838 /* 2839 ** Search p (which must have p->bSorted) looking for an entry with 2840 ** value y. Return the index of that entry. 2841 ** 2842 ** If bExact is true, return -1 if the entry is not found. 2843 ** 2844 ** If bExact is false, return the index at which a new entry with 2845 ** value y should be insert in order to keep the values in sorted 2846 ** order. The smallest return value in this case will be 0, and 2847 ** the largest return value will be p->nUsed. 2848 */ 2849 static i64 percentBinarySearch(Percentile *p, double y, int bExact){ 2850 i64 iFirst = 0; /* First element of search range */ 2851 i64 iLast = (i64)p->nUsed - 1; /* Last element of search range */ 2852 while( iLast>=iFirst ){ 2853 i64 iMid = (iFirst+iLast)/2; 2854 double x = p->a[iMid]; 2855 if( xy ){ 2858 iLast = iMid - 1; 2859 }else{ 2860 return iMid; 2861 } 2862 } 2863 if( bExact ) return -1; 2864 return iFirst; 2865 } 2866 2867 /* 2868 ** Generate an error for a percentile function. 2869 ** 2870 ** The error format string must have exactly one occurrence of "%%s()" 2871 ** (with two '%' characters). That substring will be replaced by the name 2872 ** of the function. 2873 */ 2874 static void percentError(sqlite3_context *pCtx, const char *zFormat, ...){ 2875 char *zMsg1; 2876 char *zMsg2; 2877 va_list ap; 2878 2879 va_start(ap, zFormat); 2880 zMsg1 = sqlite3_vmprintf(zFormat, ap); 2881 va_end(ap); 2882 zMsg2 = zMsg1 ? sqlite3_mprintf(zMsg1, sqlite3VdbeFuncName(pCtx)) : 0; 2883 sqlite3_result_error(pCtx, zMsg2, -1); 2884 sqlite3_free(zMsg1); 2885 sqlite3_free(zMsg2); 2886 } 2887 2888 /* 2889 ** The "step" function for percentile(Y,P) is called once for each 2890 ** input row. 2891 */ 2892 static void percentStep(sqlite3_context *pCtx, int argc, sqlite3_value **argv){ 2893 Percentile *p; 2894 double rPct; 2895 int eType; 2896 double y; 2897 assert( argc==2 || argc==1 ); 2898 2899 if( argc==1 ){ 2900 /* Requirement 13: median(Y) is the same as percentile(Y,50). */ 2901 rPct = 0.5; 2902 }else{ 2903 /* P must be a number between 0 and 100 for percentile() or between 2904 ** 0.0 and 1.0 for percentile_cont() and percentile_disc(). 2905 ** 2906 ** The user-data is an integer which is 10 times the upper bound. 2907 */ 2908 double mxFrac = (SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx))&2)? 100.0 : 1.0; 2909 eType = sqlite3_value_numeric_type(argv[1]); 2910 rPct = sqlite3_value_double(argv[1])/mxFrac; 2911 if( (eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT) 2912 || rPct<0.0 || rPct>1.0 2913 ){ 2914 percentError(pCtx, "the fraction argument to %%s()" 2915 " is not between 0.0 and %.1f", 2916 (double)mxFrac); 2917 return; 2918 } 2919 } 2920 2921 /* Allocate the session context. */ 2922 p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 2923 if( p==0 ) return; 2924 2925 /* Remember the P value. Throw an error if the P value is different 2926 ** from any prior row, per Requirement (2). */ 2927 if( !p->bPctValid ){ 2928 p->rPct = rPct; 2929 p->bPctValid = 1; 2930 }else if( !percentSameValue(p->rPct,rPct) ){ 2931 percentError(pCtx, "the fraction argument to %%s()" 2932 " is not the same for all input rows"); 2933 return; 2934 } 2935 2936 /* Ignore rows for which Y is NULL */ 2937 eType = sqlite3_value_type(argv[0]); 2938 if( eType==SQLITE_NULL ) return; 2939 2940 /* If not NULL, then Y must be numeric. Otherwise throw an error. 2941 ** Requirement 4 */ 2942 if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){ 2943 percentError(pCtx, "input to %%s() is not numeric"); 2944 return; 2945 } 2946 2947 /* Throw an error if the Y value is infinity or NaN */ 2948 y = sqlite3_value_double(argv[0]); 2949 if( percentIsInfinity(y) ){ 2950 percentError(pCtx, "Inf input to %%s()"); 2951 return; 2952 } 2953 2954 /* Allocate and store the Y */ 2955 if( p->nUsed>=p->nAlloc ){ 2956 u64 n = p->nAlloc*2 + 250; 2957 double *a = sqlite3_realloc64(p->a, sizeof(double)*n); 2958 if( a==0 ){ 2959 sqlite3_free(p->a); 2960 memset(p, 0, sizeof(*p)); 2961 sqlite3_result_error_nomem(pCtx); 2962 return; 2963 } 2964 p->nAlloc = n; 2965 p->a = a; 2966 } 2967 if( p->nUsed==0 ){ 2968 p->a[p->nUsed++] = y; 2969 p->bSorted = 1; 2970 }else if( !p->bSorted || y>=p->a[p->nUsed-1] ){ 2971 p->a[p->nUsed++] = y; 2972 }else if( p->bKeepSorted ){ 2973 i64 i; 2974 i = percentBinarySearch(p, y, 0); 2975 if( i<(int)p->nUsed ){ 2976 memmove(&p->a[i+1], &p->a[i], (p->nUsed-i)*sizeof(p->a[0])); 2977 } 2978 p->a[i] = y; 2979 p->nUsed++; 2980 }else{ 2981 p->a[p->nUsed++] = y; 2982 p->bSorted = 0; 2983 } 2984 } 2985 2986 /* 2987 ** Interchange two doubles. 2988 */ 2989 #define SWAP_DOUBLE(X,Y) {double ttt=(X);(X)=(Y);(Y)=ttt;} 2990 2991 /* 2992 ** Sort an array of doubles. 2993 ** 2994 ** Algorithm: quicksort 2995 ** 2996 ** This is implemented separately rather than using the qsort() routine 2997 ** from the standard library because: 2998 ** 2999 ** (1) To avoid a dependency on qsort() 3000 ** (2) To avoid the function call to the comparison routine for each 3001 ** comparison. 3002 ** 3003 ** If parameter iReq is non-negative, then the caller will only access 3004 ** elements a[iReq] and a[iReq+1] (if it exists) of the sorted array and 3005 ** so it is not necessary to position any other elements. Or if iReq is 3006 ** negative, then the final array must be fully sorted. 3007 */ 3008 static void percentSort( 3009 double *a, /* Array to sort */ 3010 unsigned int n, /* Number of elements in array a[] */ 3011 int iReq /* Element caller cares about (or -ve) */ 3012 ){ 3013 int iLt; /* Entries before a[iLt] are less than or equal to rPivot */ 3014 int iGt; /* Entries a[iGt] and after are greater or equal to rPivot */ 3015 int i; /* Loop counter */ 3016 double rPivot; /* The pivot value */ 3017 3018 assert( n>=2 ); 3019 do{ 3020 /* Put the first, middle, and last elements in sorted order. 3021 ** After doing so, return immediately if the array contains 3022 ** three or fewer elements as there is nothing more to do. 3023 */ 3024 if( a[0]>a[n-1] ){ 3025 SWAP_DOUBLE(a[0],a[n-1]) 3026 } 3027 if( n==2 ) return; 3028 iGt = n-1; 3029 i = n/2; 3030 if( a[0]>a[i] ){ 3031 SWAP_DOUBLE(a[0],a[i]) 3032 }else if( a[i]>a[iGt] ){ 3033 SWAP_DOUBLE(a[i],a[iGt]) 3034 } 3035 if( n==3 ) return; 3036 3037 /* Take the value of the middle element as the pivot. Shuffle 3038 ** values around so that all elements less than the pivot come 3039 ** before all elements greater than the pivot. 3040 */ 3041 rPivot = a[i]; 3042 iLt = i = 1; 3043 do{ 3044 if( a[i]iLt ) SWAP_DOUBLE(a[i],a[iLt]) 3046 iLt++; 3047 i++; 3048 }else if( a[i]>rPivot ){ 3049 do{ 3050 iGt--; 3051 }while( iGt>i && a[iGt]>rPivot ); 3052 SWAP_DOUBLE(a[i],a[iGt]) 3053 }else{ 3054 i++; 3055 } 3056 }while( i0 && iLtiLt+1 ); 3060 assert( a[iLt]==rPivot ); 3061 assert( a[iLt-1]<=rPivot ); 3062 assert( a[iGt]>=rPivot ); 3063 assert( a[iLt+1]>=rPivot ); 3064 3065 if( iReq>=0 ){ 3066 /* In this case, the only elements that the caller requires sorted into 3067 ** the correct positions are elements a[iReq] and a[iReq+1]. At this 3068 ** point we know that element a[iLt] is in the correct position and 3069 ** all elements smaller than a[iLt] are in the left-hand partition. 3070 ** So if (iReq=iLt), then elements iReq and iReq+1 are either in the 3074 ** right partition or the equal partition (elements for which 3075 ** iLt<=iElem(int)(n/2) ){ 3090 if( n-iGt>=2 ) percentSort(a+iGt, n-iGt, -1); 3091 n = iLt; 3092 }else{ 3093 if( iLt>=2 ) percentSort(a, iLt, -1); 3094 a += iGt; 3095 n -= iGt; 3096 } 3097 } 3098 }while( n>=2 ); 3099 } 3100 3101 /* 3102 ** The "inverse" function for percentile(Y,P) is called to remove a 3103 ** row that was previously inserted by "step". 3104 */ 3105 static void percentInverse(sqlite3_context *pCtx,int argc,sqlite3_value **argv){ 3106 Percentile *p; 3107 int eType; 3108 double y; 3109 i64 i; 3110 assert( argc==2 || argc==1 ); 3111 3112 /* Allocate the session context. */ 3113 p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 3114 assert( p!=0 ); 3115 3116 /* Ignore rows for which Y is NULL */ 3117 eType = sqlite3_value_type(argv[0]); 3118 if( eType==SQLITE_NULL ) return; 3119 3120 /* If not NULL, then Y must be numeric. Otherwise throw an error. 3121 ** Requirement 4 */ 3122 if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){ 3123 return; 3124 } 3125 3126 /* Ignore the Y value if it is infinity or NaN */ 3127 y = sqlite3_value_double(argv[0]); 3128 if( percentIsInfinity(y) ){ 3129 return; 3130 } 3131 if( p->bSorted==0 ){ 3132 assert( p->nUsed>1 ); 3133 percentSort(p->a, p->nUsed, -1); 3134 p->bSorted = 1; 3135 } 3136 p->bKeepSorted = 1; 3137 3138 /* Find and remove the row */ 3139 i = percentBinarySearch(p, y, 1); 3140 if( i>=0 ){ 3141 p->nUsed--; 3142 if( i<(int)p->nUsed ){ 3143 memmove(&p->a[i], &p->a[i+1], (p->nUsed - i)*sizeof(p->a[0])); 3144 } 3145 } 3146 } 3147 3148 /* 3149 ** Compute the final output of percentile(). Clean up all allocated 3150 ** memory if and only if bIsFinal is true. 3151 */ 3152 static void percentCompute(sqlite3_context *pCtx, int bIsFinal){ 3153 Percentile *p; 3154 int settings = SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx))&1; /* Discrete? */ 3155 unsigned i1, i2; 3156 double v1, v2; 3157 double ix, vx; 3158 p = (Percentile*)sqlite3_aggregate_context(pCtx, 0); 3159 if( p==0 ) return; 3160 if( p->a==0 ) return; 3161 if( p->nUsed ){ 3162 ix = p->rPct*(p->nUsed-1); 3163 i1 = (unsigned)ix; 3164 if( p->bSorted==0 ){ 3165 /* In cases where bIsFinal is non-zero, setting Percentile.bSorted 3166 ** after the percentSort() call here is not technically correct, as 3167 ** the array is not fully sorted. But in this case the object will be 3168 ** freed below anyway, so it doesn't matter. */ 3169 assert( p->nUsed>1 ); 3170 percentSort(p->a, p->nUsed, (bIsFinal ? (int)i1 : -1)); 3171 p->bSorted = 1; 3172 } 3173 if( settings & 1 ){ 3174 vx = p->a[i1]; 3175 }else{ 3176 i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1; 3177 v1 = p->a[i1]; 3178 v2 = p->a[i2]; 3179 vx = v1 + (v2-v1)*(ix-i1); 3180 } 3181 sqlite3_result_double(pCtx, vx); 3182 } 3183 if( bIsFinal ){ 3184 sqlite3_free(p->a); 3185 memset(p, 0, sizeof(*p)); 3186 }else{ 3187 p->bKeepSorted = 1; 3188 } 3189 } 3190 static void percentFinal(sqlite3_context *pCtx){ 3191 percentCompute(pCtx, 1); 3192 } 3193 static void percentValue(sqlite3_context *pCtx){ 3194 percentCompute(pCtx, 0); 3195 } 3196 /****** End of percentile family of functions ******/ 3197 #endif /* SQLITE_ENABLE_PERCENTILE */ 3198 3199 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) 3200 /* 3201 ** Implementation of sqlite_filestat(SCHEMA). 3202 ** 3203 ** Return JSON text that describes low-level debug/diagnostic information 3204 ** about the sqlite3_file object associated with SCHEMA. 3205 */ 3206 static void filestatFunc( 3207 sqlite3_context *context, 3208 int argc, 3209 sqlite3_value **argv 3210 ){ 3211 sqlite3 *db = sqlite3_context_db_handle(context); 3212 const char *zDbName; 3213 sqlite3_str *pStr; 3214 Btree *pBtree; 3215 3216 zDbName = (const char*)sqlite3_value_text(argv[0]); 3217 pBtree = sqlite3DbNameToBtree(db, zDbName); 3218 if( pBtree ){ 3219 Pager *pPager; 3220 sqlite3_file *fd; 3221 int rc; 3222 sqlite3BtreeEnter(pBtree); 3223 pPager = sqlite3BtreePager(pBtree); 3224 assert( pPager!=0 ); 3225 fd = sqlite3PagerFile(pPager); 3226 pStr = sqlite3_str_new(db); 3227 if( sqlite3_str_errcode(pStr) ){ 3228 sqlite3_result_error_nomem(context); 3229 }else{ 3230 sqlite3_str_append(pStr, "{\"db\":", 6); 3231 rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr); 3232 if( rc ) sqlite3_str_append(pStr, "null", 4); 3233 fd = sqlite3PagerJrnlFile(pPager); 3234 if( fd && fd->pMethods!=0 ){ 3235 sqlite3_str_appendall(pStr, ",\"journal\":"); 3236 rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr); 3237 if( rc ) sqlite3_str_append(pStr, "null", 4); 3238 } 3239 sqlite3_str_append(pStr, "}", 1); 3240 sqlite3_result_str(context, pStr, SQLITE_FINISH); 3241 } 3242 sqlite3BtreeLeave(pBtree); 3243 }else{ 3244 sqlite3_result_text(context, "{}", 2, SQLITE_STATIC); 3245 } 3246 } 3247 #endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ 3248 3249 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) 3250 /* 3251 ** Implementation of sqlite_walstat(SCHEMA). 3252 ** 3253 ** Return JSON text that describes the current state of a WAL file. 3254 ** This function is for debugging and analysis only. It is not part 3255 ** of production builds. This function is not part of the SQLite API 3256 ** and is likely to change or be removed in future versions of SQLite. 3257 */ 3258 static void walstatFunc( 3259 sqlite3_context *context, 3260 int argc, 3261 sqlite3_value **argv 3262 ){ 3263 sqlite3 *db = sqlite3_context_db_handle(context); 3264 const char *zDbName; 3265 sqlite3_str *pStr; 3266 Btree *pBtree; 3267 3268 zDbName = (const char*)sqlite3_value_text(argv[0]); 3269 pBtree = sqlite3DbNameToBtree(db, zDbName); 3270 if( pBtree ){ 3271 Pager *pPager; 3272 sqlite3BtreeEnter(pBtree); 3273 pPager = sqlite3BtreePager(pBtree); 3274 assert( pPager!=0 ); 3275 pStr = sqlite3_str_new(db); 3276 if( sqlite3_str_errcode(pStr) ){ 3277 sqlite3_result_error_nomem(context); 3278 }else{ 3279 sqlite3_str_append(pStr, "{", 1); 3280 sqlite3PagerWalStat(pPager, pStr); 3281 sqlite3_str_append(pStr, "}", 1); 3282 sqlite3_result_str(context, pStr, SQLITE_FINISH); 3283 } 3284 sqlite3BtreeLeave(pBtree); 3285 }else{ 3286 sqlite3_result_text(context, "{}", 2, SQLITE_STATIC); 3287 } 3288 } 3289 #endif /* SQLITE_DEBUG || SQLITE_ENABLE_WALSTAT */ 3290 3291 #ifdef SQLITE_DEBUG 3292 /* 3293 ** Implementation of fpdecode(x,y,z) function. 3294 ** 3295 ** x is a real number that is to be decoded. y is the precision. 3296 ** z is the maximum real precision. Return a string that shows the 3297 ** results of the sqlite3FpDecode() function. 3298 ** 3299 ** Used for testing and debugging only, specifically testing and debugging 3300 ** of the sqlite3FpDecode() function. This SQL function does not appear 3301 ** in production builds. This function is not an API and is subject to 3302 ** modification or removal in future versions of SQLite. 3303 */ 3304 static void fpdecodeFunc( 3305 sqlite3_context *context, 3306 int argc, 3307 sqlite3_value **argv 3308 ){ 3309 FpDecode s; 3310 double x; 3311 int y, z; 3312 char zBuf[100]; 3313 UNUSED_PARAMETER(argc); 3314 assert( argc==3 ); 3315 x = sqlite3_value_double(argv[0]); 3316 y = sqlite3_value_int(argv[1]); 3317 z = sqlite3_value_int(argv[2]); 3318 if( z<=0 ) z = 1; 3319 if( y<-`100000000` ) y = -`100000000`; /* Same limit as printf() */ 3320 sqlite3FpDecode(&s, x, y, z); 3321 if( s.isSpecial==2 ){ 3322 sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN"); 3323 }else{ 3324 sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP); 3325 } 3326 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); 3327 } 3328 #endif /* SQLITE_DEBUG */ 3329 3330 #ifdef SQLITE_DEBUG 3331 /* 3332 ** Implementation of parseuri(uri,flags) function. 3333 ** 3334 ** Required Arguments: 3335 ** "uri" The URI to parse. 3336 ** "flags" Bitmask of flags, as if to sqlite3_open_v2(). 3337 ** 3338 ** Additional arguments beyond the first two make calls to 3339 ** sqlite3_uri_key() for integers and sqlite3_uri_parameter for 3340 ** anything else. 3341 ** 3342 ** The result is a string showing the results of calling sqlite3ParseUri(). 3343 ** 3344 ** Used for testing and debugging only, specifically testing and debugging 3345 ** of the sqlite3ParseUri() function. This SQL function does not appear 3346 ** in production builds. This function is not an API and is subject to 3347 ** modification or removal in future versions of SQLite. 3348 */ 3349 static void parseuriFunc( 3350 sqlite3_context *ctx, 3351 int argc, 3352 sqlite3_value **argv 3353 ){ 3354 sqlite3_str *pResult; 3355 const char *zVfs; 3356 const char *zUri; 3357 unsigned int flgs; 3358 int rc; 3359 sqlite3_vfs *pVfs = 0; 3360 char *zFile = 0; 3361 char *zErr = 0; 3362 3363 if( argc<2 ) return; 3364 pVfs = sqlite3_vfs_find(0); 3365 assert( pVfs ); 3366 zVfs = pVfs->zName; 3367 zUri = (const char*)sqlite3_value_text(argv[0]); 3368 if( zUri==0 ) return; 3369 flgs = (unsigned int)sqlite3_value_int(argv[1]); 3370 rc = sqlite3ParseUri(zVfs, zUri, &flgs, &pVfs, &zFile, &zErr); 3371 pResult = sqlite3_str_new(0); 3372 if( !sqlite3_str_errcode(pResult) ){ 3373 int i; 3374 sqlite3_str_appendf(pResult, "rc=%d", rc); 3375 sqlite3_str_appendf(pResult, ", flags=0x%x", flgs); 3376 sqlite3_str_appendf(pResult, ", vfs=%Q", pVfs ? pVfs->zName: 0); 3377 sqlite3_str_appendf(pResult, ", err=%Q", zErr); 3378 sqlite3_str_appendf(pResult, ", file=%Q", zFile); 3379 if( zFile ){ 3380 const char *z = zFile; 3381 z += sqlite3Strlen30(z)+1; 3382 while( z[0] ){ 3383 sqlite3_str_appendf(pResult, ", %Q", z); 3384 z += sqlite3Strlen30(z)+1; 3385 } 3386 for(i=2; iu.pHash){ 3611 int n = sqlite3Strlen30(p->zName); 3612 int h = p->zName[0] + n; 3613 assert( p->funcFlags & SQLITE_FUNC_BUILTIN ); 3614 printf(" %s(%d)", p->zName, h); 3615 } 3616 printf("\n"); 3617 } 3618 } 3619 #endif 3620 }