000001 /* 000002 ** 2002 February 23 000003 ** 000004 ** The author disclaims copyright to this source code. In place of 000005 ** a legal notice, here is a blessing: 000006 ** 000007 ** May you do good and not evil. 000008 ** May you find forgiveness for yourself and forgive others. 000009 ** May you share freely, never taking more than you give. 000010 ** 000011 ************************************************************************* 000012 ** This file contains the C-language implementations for many of the SQL 000013 ** functions of SQLite. (Some function, and in particular the date and 000014 ** time functions, are implemented separately.) 000015 */ 000016 #include "sqliteInt.h" 000017 #include <stdlib.h> 000018 #include <assert.h> 000019 #ifndef SQLITE_OMIT_FLOATING_POINT 000020 #include <math.h> 000021 #endif 000022 #include "vdbeInt.h" 000023 000024 /* 000025 ** Return the collating function associated with a function. 000026 */ 000027 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ 000028 VdbeOp *pOp; 000029 assert( context->pVdbe!=0 ); 000030 pOp = &context->pVdbe->aOp[context->iOp-1]; 000031 assert( pOp->opcode==OP_CollSeq ); 000032 assert( pOp->p4type==P4_COLLSEQ ); 000033 return pOp->p4.pColl; 000034 } 000035 000036 /* 000037 ** Indicate that the accumulator load should be skipped on this 000038 ** iteration of the aggregate loop. 000039 */ 000040 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ 000041 assert( context->isError<=0 ); 000042 context->isError = -1; 000043 context->skipFlag = 1; 000044 } 000045 000046 /* 000047 ** Implementation of the non-aggregate min() and max() functions 000048 */ 000049 static void minmaxFunc( 000050 sqlite3_context *context, 000051 int argc, 000052 sqlite3_value **argv 000053 ){ 000054 int i; 000055 int mask; /* 0 for min() or 0xffffffff for max() */ 000056 int iBest; 000057 CollSeq *pColl; 000058 000059 assert( argc>1 ); 000060 mask = sqlite3_user_data(context)==0 ? 0 : -1; 000061 pColl = sqlite3GetFuncCollSeq(context); 000062 assert( pColl ); 000063 assert( mask==-1 || mask==0 ); 000064 iBest = 0; 000065 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 000066 for(i=1; i<argc; i++){ 000067 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return; 000068 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){ 000069 testcase( mask==0 ); 000070 iBest = i; 000071 } 000072 } 000073 sqlite3_result_value(context, argv[iBest]); 000074 } 000075 000076 /* 000077 ** Return the type of the argument. 000078 */ 000079 static void typeofFunc( 000080 sqlite3_context *context, 000081 int NotUsed, 000082 sqlite3_value **argv 000083 ){ 000084 static const char *azType[] = { "integer", "real", "text", "blob", "null" }; 000085 int i = sqlite3_value_type(argv[0]) - 1; 000086 UNUSED_PARAMETER(NotUsed); 000087 assert( i>=0 && i<ArraySize(azType) ); 000088 assert( SQLITE_INTEGER==1 ); 000089 assert( SQLITE_FLOAT==2 ); 000090 assert( SQLITE_TEXT==3 ); 000091 assert( SQLITE_BLOB==4 ); 000092 assert( SQLITE_NULL==5 ); 000093 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns 000094 ** the datatype code for the initial datatype of the sqlite3_value object 000095 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT, 000096 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */ 000097 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC); 000098 } 000099 000100 /* subtype(X) 000101 ** 000102 ** Return the subtype of X 000103 */ 000104 static void subtypeFunc( 000105 sqlite3_context *context, 000106 int argc, 000107 sqlite3_value **argv 000108 ){ 000109 UNUSED_PARAMETER(argc); 000110 sqlite3_result_int(context, sqlite3_value_subtype(argv[0])); 000111 } 000112 000113 /* 000114 ** Implementation of the length() function 000115 */ 000116 static void lengthFunc( 000117 sqlite3_context *context, 000118 int argc, 000119 sqlite3_value **argv 000120 ){ 000121 assert( argc==1 ); 000122 UNUSED_PARAMETER(argc); 000123 switch( sqlite3_value_type(argv[0]) ){ 000124 case SQLITE_BLOB: 000125 case SQLITE_INTEGER: 000126 case SQLITE_FLOAT: { 000127 sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); 000128 break; 000129 } 000130 case SQLITE_TEXT: { 000131 const unsigned char *z = sqlite3_value_text(argv[0]); 000132 const unsigned char *z0; 000133 unsigned char c; 000134 if( z==0 ) return; 000135 z0 = z; 000136 while( (c = *z)!=0 ){ 000137 z++; 000138 if( c>=0xc0 ){ 000139 while( (*z & 0xc0)==0x80 ){ z++; z0++; } 000140 } 000141 } 000142 sqlite3_result_int(context, (int)(z-z0)); 000143 break; 000144 } 000145 default: { 000146 sqlite3_result_null(context); 000147 break; 000148 } 000149 } 000150 } 000151 000152 /* 000153 ** Implementation of the octet_length() function 000154 */ 000155 static void bytelengthFunc( 000156 sqlite3_context *context, 000157 int argc, 000158 sqlite3_value **argv 000159 ){ 000160 assert( argc==1 ); 000161 UNUSED_PARAMETER(argc); 000162 switch( sqlite3_value_type(argv[0]) ){ 000163 case SQLITE_BLOB: { 000164 sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); 000165 break; 000166 } 000167 case SQLITE_INTEGER: 000168 case SQLITE_FLOAT: { 000169 i64 m = sqlite3_context_db_handle(context)->enc<=SQLITE_UTF8 ? 1 : 2; 000170 sqlite3_result_int64(context, sqlite3_value_bytes(argv[0])*m); 000171 break; 000172 } 000173 case SQLITE_TEXT: { 000174 if( sqlite3_value_encoding(argv[0])<=SQLITE_UTF8 ){ 000175 sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); 000176 }else{ 000177 sqlite3_result_int(context, sqlite3_value_bytes16(argv[0])); 000178 } 000179 break; 000180 } 000181 default: { 000182 sqlite3_result_null(context); 000183 break; 000184 } 000185 } 000186 } 000187 000188 /* 000189 ** Implementation of the abs() function. 000190 ** 000191 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of 000192 ** the numeric argument X. 000193 */ 000194 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000195 assert( argc==1 ); 000196 UNUSED_PARAMETER(argc); 000197 switch( sqlite3_value_type(argv[0]) ){ 000198 case SQLITE_INTEGER: { 000199 i64 iVal = sqlite3_value_int64(argv[0]); 000200 if( iVal<0 ){ 000201 if( iVal==SMALLEST_INT64 ){ 000202 /* IMP: R-31676-45509 If X is the integer -9223372036854775808 000203 ** then abs(X) throws an integer overflow error since there is no 000204 ** equivalent positive 64-bit two complement value. */ 000205 sqlite3_result_error(context, "integer overflow", -1); 000206 return; 000207 } 000208 iVal = -iVal; 000209 } 000210 sqlite3_result_int64(context, iVal); 000211 break; 000212 } 000213 case SQLITE_NULL: { 000214 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ 000215 sqlite3_result_null(context); 000216 break; 000217 } 000218 default: { 000219 /* Because sqlite3_value_double() returns 0.0 if the argument is not 000220 ** something that can be converted into a number, we have: 000221 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob 000222 ** that cannot be converted to a numeric value. 000223 */ 000224 double rVal = sqlite3_value_double(argv[0]); 000225 if( rVal<0 ) rVal = -rVal; 000226 sqlite3_result_double(context, rVal); 000227 break; 000228 } 000229 } 000230 } 000231 000232 /* 000233 ** Implementation of the instr() function. 000234 ** 000235 ** instr(haystack,needle) finds the first occurrence of needle 000236 ** in haystack and returns the number of previous characters plus 1, 000237 ** or 0 if needle does not occur within haystack. 000238 ** 000239 ** If both haystack and needle are BLOBs, then the result is one more than 000240 ** the number of bytes in haystack prior to the first occurrence of needle, 000241 ** or 0 if needle never occurs in haystack. 000242 */ 000243 static void instrFunc( 000244 sqlite3_context *context, 000245 int argc, 000246 sqlite3_value **argv 000247 ){ 000248 const unsigned char *zHaystack; 000249 const unsigned char *zNeedle; 000250 int nHaystack; 000251 int nNeedle; 000252 int typeHaystack, typeNeedle; 000253 int N = 1; 000254 int isText; 000255 unsigned char firstChar; 000256 sqlite3_value *pC1 = 0; 000257 sqlite3_value *pC2 = 0; 000258 000259 UNUSED_PARAMETER(argc); 000260 typeHaystack = sqlite3_value_type(argv[0]); 000261 typeNeedle = sqlite3_value_type(argv[1]); 000262 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; 000263 nHaystack = sqlite3_value_bytes(argv[0]); 000264 nNeedle = sqlite3_value_bytes(argv[1]); 000265 if( nNeedle>0 ){ 000266 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ 000267 zHaystack = sqlite3_value_blob(argv[0]); 000268 zNeedle = sqlite3_value_blob(argv[1]); 000269 isText = 0; 000270 }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){ 000271 zHaystack = sqlite3_value_text(argv[0]); 000272 zNeedle = sqlite3_value_text(argv[1]); 000273 isText = 1; 000274 }else{ 000275 pC1 = sqlite3_value_dup(argv[0]); 000276 zHaystack = sqlite3_value_text(pC1); 000277 if( zHaystack==0 ) goto endInstrOOM; 000278 nHaystack = sqlite3_value_bytes(pC1); 000279 pC2 = sqlite3_value_dup(argv[1]); 000280 zNeedle = sqlite3_value_text(pC2); 000281 if( zNeedle==0 ) goto endInstrOOM; 000282 nNeedle = sqlite3_value_bytes(pC2); 000283 isText = 1; 000284 } 000285 if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM; 000286 firstChar = zNeedle[0]; 000287 while( nNeedle<=nHaystack 000288 && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0) 000289 ){ 000290 N++; 000291 do{ 000292 nHaystack--; 000293 zHaystack++; 000294 }while( isText && (zHaystack[0]&0xc0)==0x80 ); 000295 } 000296 if( nNeedle>nHaystack ) N = 0; 000297 } 000298 sqlite3_result_int(context, N); 000299 endInstr: 000300 sqlite3_value_free(pC1); 000301 sqlite3_value_free(pC2); 000302 return; 000303 endInstrOOM: 000304 sqlite3_result_error_nomem(context); 000305 goto endInstr; 000306 } 000307 000308 /* 000309 ** Implementation of the printf() (a.k.a. format()) SQL function. 000310 */ 000311 static void printfFunc( 000312 sqlite3_context *context, 000313 int argc, 000314 sqlite3_value **argv 000315 ){ 000316 PrintfArguments x; 000317 StrAccum str; 000318 const char *zFormat; 000319 int n; 000320 sqlite3 *db = sqlite3_context_db_handle(context); 000321 000322 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 000323 x.nArg = argc-1; 000324 x.nUsed = 0; 000325 x.apArg = argv+1; 000326 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); 000327 str.printfFlags = SQLITE_PRINTF_SQLFUNC; 000328 sqlite3_str_appendf(&str, zFormat, &x); 000329 n = str.nChar; 000330 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, 000331 SQLITE_DYNAMIC); 000332 } 000333 } 000334 000335 /* 000336 ** Implementation of the substr() function. 000337 ** 000338 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. 000339 ** p1 is 1-indexed. So substr(x,1,1) returns the first character 000340 ** of x. If x is text, then we actually count UTF-8 characters. 000341 ** If x is a blob, then we count bytes. 000342 ** 000343 ** If p1 is negative, then we begin abs(p1) from the end of x[]. 000344 ** 000345 ** If p2 is negative, return the p2 characters preceding p1. 000346 */ 000347 static void substrFunc( 000348 sqlite3_context *context, 000349 int argc, 000350 sqlite3_value **argv 000351 ){ 000352 const unsigned char *z; 000353 const unsigned char *z2; 000354 int len; 000355 int p0type; 000356 i64 p1, p2; 000357 int negP2 = 0; 000358 000359 assert( argc==3 || argc==2 ); 000360 if( sqlite3_value_type(argv[1])==SQLITE_NULL 000361 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) 000362 ){ 000363 return; 000364 } 000365 p0type = sqlite3_value_type(argv[0]); 000366 p1 = sqlite3_value_int(argv[1]); 000367 if( p0type==SQLITE_BLOB ){ 000368 len = sqlite3_value_bytes(argv[0]); 000369 z = sqlite3_value_blob(argv[0]); 000370 if( z==0 ) return; 000371 assert( len==sqlite3_value_bytes(argv[0]) ); 000372 }else{ 000373 z = sqlite3_value_text(argv[0]); 000374 if( z==0 ) return; 000375 len = 0; 000376 if( p1<0 ){ 000377 for(z2=z; *z2; len++){ 000378 SQLITE_SKIP_UTF8(z2); 000379 } 000380 } 000381 } 000382 #ifdef SQLITE_SUBSTR_COMPATIBILITY 000383 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as 000384 ** as substr(X,1,N) - it returns the first N characters of X. This 000385 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] 000386 ** from 2009-02-02 for compatibility of applications that exploited the 000387 ** old buggy behavior. */ 000388 if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */ 000389 #endif 000390 if( argc==3 ){ 000391 p2 = sqlite3_value_int(argv[2]); 000392 if( p2<0 ){ 000393 p2 = -p2; 000394 negP2 = 1; 000395 } 000396 }else{ 000397 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; 000398 } 000399 if( p1<0 ){ 000400 p1 += len; 000401 if( p1<0 ){ 000402 p2 += p1; 000403 if( p2<0 ) p2 = 0; 000404 p1 = 0; 000405 } 000406 }else if( p1>0 ){ 000407 p1--; 000408 }else if( p2>0 ){ 000409 p2--; 000410 } 000411 if( negP2 ){ 000412 p1 -= p2; 000413 if( p1<0 ){ 000414 p2 += p1; 000415 p1 = 0; 000416 } 000417 } 000418 assert( p1>=0 && p2>=0 ); 000419 if( p0type!=SQLITE_BLOB ){ 000420 while( *z && p1 ){ 000421 SQLITE_SKIP_UTF8(z); 000422 p1--; 000423 } 000424 for(z2=z; *z2 && p2; p2--){ 000425 SQLITE_SKIP_UTF8(z2); 000426 } 000427 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, 000428 SQLITE_UTF8); 000429 }else{ 000430 if( p1+p2>len ){ 000431 p2 = len-p1; 000432 if( p2<0 ) p2 = 0; 000433 } 000434 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); 000435 } 000436 } 000437 000438 /* 000439 ** Implementation of the round() function 000440 */ 000441 #ifndef SQLITE_OMIT_FLOATING_POINT 000442 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000443 int n = 0; 000444 double r; 000445 char *zBuf; 000446 assert( argc==1 || argc==2 ); 000447 if( argc==2 ){ 000448 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; 000449 n = sqlite3_value_int(argv[1]); 000450 if( n>30 ) n = 30; 000451 if( n<0 ) n = 0; 000452 } 000453 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 000454 r = sqlite3_value_double(argv[0]); 000455 /* If Y==0 and X will fit in a 64-bit int, 000456 ** handle the rounding directly, 000457 ** otherwise use printf. 000458 */ 000459 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){ 000460 /* The value has no fractional part so there is nothing to round */ 000461 }else if( n==0 ){ 000462 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5))); 000463 }else{ 000464 zBuf = sqlite3_mprintf("%!.*f",n,r); 000465 if( zBuf==0 ){ 000466 sqlite3_result_error_nomem(context); 000467 return; 000468 } 000469 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); 000470 sqlite3_free(zBuf); 000471 } 000472 sqlite3_result_double(context, r); 000473 } 000474 #endif 000475 000476 /* 000477 ** Allocate nByte bytes of space using sqlite3Malloc(). If the 000478 ** allocation fails, call sqlite3_result_error_nomem() to notify 000479 ** the database handle that malloc() has failed and return NULL. 000480 ** If nByte is larger than the maximum string or blob length, then 000481 ** raise an SQLITE_TOOBIG exception and return NULL. 000482 */ 000483 static void *contextMalloc(sqlite3_context *context, i64 nByte){ 000484 char *z; 000485 sqlite3 *db = sqlite3_context_db_handle(context); 000486 assert( nByte>0 ); 000487 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); 000488 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); 000489 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 000490 sqlite3_result_error_toobig(context); 000491 z = 0; 000492 }else{ 000493 z = sqlite3Malloc(nByte); 000494 if( !z ){ 000495 sqlite3_result_error_nomem(context); 000496 } 000497 } 000498 return z; 000499 } 000500 000501 /* 000502 ** Implementation of the upper() and lower() SQL functions. 000503 */ 000504 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000505 char *z1; 000506 const char *z2; 000507 int i, n; 000508 UNUSED_PARAMETER(argc); 000509 z2 = (char*)sqlite3_value_text(argv[0]); 000510 n = sqlite3_value_bytes(argv[0]); 000511 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 000512 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 000513 if( z2 ){ 000514 z1 = contextMalloc(context, ((i64)n)+1); 000515 if( z1 ){ 000516 for(i=0; i<n; i++){ 000517 z1[i] = (char)sqlite3Toupper(z2[i]); 000518 } 000519 sqlite3_result_text(context, z1, n, sqlite3_free); 000520 } 000521 } 000522 } 000523 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000524 char *z1; 000525 const char *z2; 000526 int i, n; 000527 UNUSED_PARAMETER(argc); 000528 z2 = (char*)sqlite3_value_text(argv[0]); 000529 n = sqlite3_value_bytes(argv[0]); 000530 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 000531 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 000532 if( z2 ){ 000533 z1 = contextMalloc(context, ((i64)n)+1); 000534 if( z1 ){ 000535 for(i=0; i<n; i++){ 000536 z1[i] = sqlite3Tolower(z2[i]); 000537 } 000538 sqlite3_result_text(context, z1, n, sqlite3_free); 000539 } 000540 } 000541 } 000542 000543 /* 000544 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented 000545 ** as VDBE code so that unused argument values do not have to be computed. 000546 ** However, we still need some kind of function implementation for this 000547 ** routines in the function table. The noopFunc macro provides this. 000548 ** noopFunc will never be called so it doesn't matter what the implementation 000549 ** is. We might as well use the "version()" function as a substitute. 000550 */ 000551 #define noopFunc versionFunc /* Substitute function - never called */ 000552 000553 /* 000554 ** Implementation of random(). Return a random integer. 000555 */ 000556 static void randomFunc( 000557 sqlite3_context *context, 000558 int NotUsed, 000559 sqlite3_value **NotUsed2 000560 ){ 000561 sqlite_int64 r; 000562 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000563 sqlite3_randomness(sizeof(r), &r); 000564 if( r<0 ){ 000565 /* We need to prevent a random number of 0x8000000000000000 000566 ** (or -9223372036854775808) since when you do abs() of that 000567 ** number of you get the same value back again. To do this 000568 ** in a way that is testable, mask the sign bit off of negative 000569 ** values, resulting in a positive value. Then take the 000570 ** 2s complement of that positive value. The end result can 000571 ** therefore be no less than -9223372036854775807. 000572 */ 000573 r = -(r & LARGEST_INT64); 000574 } 000575 sqlite3_result_int64(context, r); 000576 } 000577 000578 /* 000579 ** Implementation of randomblob(N). Return a random blob 000580 ** that is N bytes long. 000581 */ 000582 static void randomBlob( 000583 sqlite3_context *context, 000584 int argc, 000585 sqlite3_value **argv 000586 ){ 000587 sqlite3_int64 n; 000588 unsigned char *p; 000589 assert( argc==1 ); 000590 UNUSED_PARAMETER(argc); 000591 n = sqlite3_value_int64(argv[0]); 000592 if( n<1 ){ 000593 n = 1; 000594 } 000595 p = contextMalloc(context, n); 000596 if( p ){ 000597 sqlite3_randomness(n, p); 000598 sqlite3_result_blob(context, (char*)p, n, sqlite3_free); 000599 } 000600 } 000601 000602 /* 000603 ** Implementation of the last_insert_rowid() SQL function. The return 000604 ** value is the same as the sqlite3_last_insert_rowid() API function. 000605 */ 000606 static void last_insert_rowid( 000607 sqlite3_context *context, 000608 int NotUsed, 000609 sqlite3_value **NotUsed2 000610 ){ 000611 sqlite3 *db = sqlite3_context_db_handle(context); 000612 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000613 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a 000614 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface 000615 ** function. */ 000616 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db)); 000617 } 000618 000619 /* 000620 ** Implementation of the changes() SQL function. 000621 ** 000622 ** IMP: R-32760-32347 The changes() SQL function is a wrapper 000623 ** around the sqlite3_changes64() C/C++ function and hence follows the 000624 ** same rules for counting changes. 000625 */ 000626 static void changes( 000627 sqlite3_context *context, 000628 int NotUsed, 000629 sqlite3_value **NotUsed2 000630 ){ 000631 sqlite3 *db = sqlite3_context_db_handle(context); 000632 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000633 sqlite3_result_int64(context, sqlite3_changes64(db)); 000634 } 000635 000636 /* 000637 ** Implementation of the total_changes() SQL function. The return value is 000638 ** the same as the sqlite3_total_changes64() API function. 000639 */ 000640 static void total_changes( 000641 sqlite3_context *context, 000642 int NotUsed, 000643 sqlite3_value **NotUsed2 000644 ){ 000645 sqlite3 *db = sqlite3_context_db_handle(context); 000646 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000647 /* IMP: R-11217-42568 This function is a wrapper around the 000648 ** sqlite3_total_changes64() C/C++ interface. */ 000649 sqlite3_result_int64(context, sqlite3_total_changes64(db)); 000650 } 000651 000652 /* 000653 ** A structure defining how to do GLOB-style comparisons. 000654 */ 000655 struct compareInfo { 000656 u8 matchAll; /* "*" or "%" */ 000657 u8 matchOne; /* "?" or "_" */ 000658 u8 matchSet; /* "[" or 0 */ 000659 u8 noCase; /* true to ignore case differences */ 000660 }; 000661 000662 /* 000663 ** For LIKE and GLOB matching on EBCDIC machines, assume that every 000664 ** character is exactly one byte in size. Also, provide the Utf8Read() 000665 ** macro for fast reading of the next character in the common case where 000666 ** the next character is ASCII. 000667 */ 000668 #if defined(SQLITE_EBCDIC) 000669 # define sqlite3Utf8Read(A) (*((*A)++)) 000670 # define Utf8Read(A) (*(A++)) 000671 #else 000672 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A)) 000673 #endif 000674 000675 static const struct compareInfo globInfo = { '*', '?', '[', 0 }; 000676 /* The correct SQL-92 behavior is for the LIKE operator to ignore 000677 ** case. Thus 'a' LIKE 'A' would be true. */ 000678 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 }; 000679 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator 000680 ** is case sensitive causing 'a' LIKE 'A' to be false */ 000681 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 }; 000682 000683 /* 000684 ** Possible error returns from patternMatch() 000685 */ 000686 #define SQLITE_MATCH 0 000687 #define SQLITE_NOMATCH 1 000688 #define SQLITE_NOWILDCARDMATCH 2 000689 000690 /* 000691 ** Compare two UTF-8 strings for equality where the first string is 000692 ** a GLOB or LIKE expression. Return values: 000693 ** 000694 ** SQLITE_MATCH: Match 000695 ** SQLITE_NOMATCH: No match 000696 ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards. 000697 ** 000698 ** Globbing rules: 000699 ** 000700 ** '*' Matches any sequence of zero or more characters. 000701 ** 000702 ** '?' Matches exactly one character. 000703 ** 000704 ** [...] Matches one character from the enclosed list of 000705 ** characters. 000706 ** 000707 ** [^...] Matches one character not in the enclosed list. 000708 ** 000709 ** With the [...] and [^...] matching, a ']' character can be included 000710 ** in the list by making it the first character after '[' or '^'. A 000711 ** range of characters can be specified using '-'. Example: 000712 ** "[a-z]" matches any single lower-case letter. To match a '-', make 000713 ** it the last character in the list. 000714 ** 000715 ** Like matching rules: 000716 ** 000717 ** '%' Matches any sequence of zero or more characters 000718 ** 000719 *** '_' Matches any one character 000720 ** 000721 ** Ec Where E is the "esc" character and c is any other 000722 ** character, including '%', '_', and esc, match exactly c. 000723 ** 000724 ** The comments within this routine usually assume glob matching. 000725 ** 000726 ** This routine is usually quick, but can be N**2 in the worst case. 000727 */ 000728 static int patternCompare( 000729 const u8 *zPattern, /* The glob pattern */ 000730 const u8 *zString, /* The string to compare against the glob */ 000731 const struct compareInfo *pInfo, /* Information about how to do the compare */ 000732 u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */ 000733 ){ 000734 u32 c, c2; /* Next pattern and input string chars */ 000735 u32 matchOne = pInfo->matchOne; /* "?" or "_" */ 000736 u32 matchAll = pInfo->matchAll; /* "*" or "%" */ 000737 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ 000738 const u8 *zEscaped = 0; /* One past the last escaped input char */ 000739 000740 while( (c = Utf8Read(zPattern))!=0 ){ 000741 if( c==matchAll ){ /* Match "*" */ 000742 /* Skip over multiple "*" characters in the pattern. If there 000743 ** are also "?" characters, skip those as well, but consume a 000744 ** single character of the input string for each "?" skipped */ 000745 while( (c=Utf8Read(zPattern)) == matchAll 000746 || (c == matchOne && matchOne!=0) ){ 000747 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ 000748 return SQLITE_NOWILDCARDMATCH; 000749 } 000750 } 000751 if( c==0 ){ 000752 return SQLITE_MATCH; /* "*" at the end of the pattern matches */ 000753 }else if( c==matchOther ){ 000754 if( pInfo->matchSet==0 ){ 000755 c = sqlite3Utf8Read(&zPattern); 000756 if( c==0 ) return SQLITE_NOWILDCARDMATCH; 000757 }else{ 000758 /* "[...]" immediately follows the "*". We have to do a slow 000759 ** recursive search in this case, but it is an unusual case. */ 000760 assert( matchOther<0x80 ); /* '[' is a single-byte character */ 000761 while( *zString ){ 000762 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); 000763 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 000764 SQLITE_SKIP_UTF8(zString); 000765 } 000766 return SQLITE_NOWILDCARDMATCH; 000767 } 000768 } 000769 000770 /* At this point variable c contains the first character of the 000771 ** pattern string past the "*". Search in the input string for the 000772 ** first matching character and recursively continue the match from 000773 ** that point. 000774 ** 000775 ** For a case-insensitive search, set variable cx to be the same as 000776 ** c but in the other case and search the input string for either 000777 ** c or cx. 000778 */ 000779 if( c<0x80 ){ 000780 char zStop[3]; 000781 int bMatch; 000782 if( noCase ){ 000783 zStop[0] = sqlite3Toupper(c); 000784 zStop[1] = sqlite3Tolower(c); 000785 zStop[2] = 0; 000786 }else{ 000787 zStop[0] = c; 000788 zStop[1] = 0; 000789 } 000790 while(1){ 000791 zString += strcspn((const char*)zString, zStop); 000792 if( zString[0]==0 ) break; 000793 zString++; 000794 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 000795 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 000796 } 000797 }else{ 000798 int bMatch; 000799 while( (c2 = Utf8Read(zString))!=0 ){ 000800 if( c2!=c ) continue; 000801 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 000802 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 000803 } 000804 } 000805 return SQLITE_NOWILDCARDMATCH; 000806 } 000807 if( c==matchOther ){ 000808 if( pInfo->matchSet==0 ){ 000809 c = sqlite3Utf8Read(&zPattern); 000810 if( c==0 ) return SQLITE_NOMATCH; 000811 zEscaped = zPattern; 000812 }else{ 000813 u32 prior_c = 0; 000814 int seen = 0; 000815 int invert = 0; 000816 c = sqlite3Utf8Read(&zString); 000817 if( c==0 ) return SQLITE_NOMATCH; 000818 c2 = sqlite3Utf8Read(&zPattern); 000819 if( c2=='^' ){ 000820 invert = 1; 000821 c2 = sqlite3Utf8Read(&zPattern); 000822 } 000823 if( c2==']' ){ 000824 if( c==']' ) seen = 1; 000825 c2 = sqlite3Utf8Read(&zPattern); 000826 } 000827 while( c2 && c2!=']' ){ 000828 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ 000829 c2 = sqlite3Utf8Read(&zPattern); 000830 if( c>=prior_c && c<=c2 ) seen = 1; 000831 prior_c = 0; 000832 }else{ 000833 if( c==c2 ){ 000834 seen = 1; 000835 } 000836 prior_c = c2; 000837 } 000838 c2 = sqlite3Utf8Read(&zPattern); 000839 } 000840 if( c2==0 || (seen ^ invert)==0 ){ 000841 return SQLITE_NOMATCH; 000842 } 000843 continue; 000844 } 000845 } 000846 c2 = Utf8Read(zString); 000847 if( c==c2 ) continue; 000848 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ 000849 continue; 000850 } 000851 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; 000852 return SQLITE_NOMATCH; 000853 } 000854 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; 000855 } 000856 000857 /* 000858 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and 000859 ** non-zero if there is no match. 000860 */ 000861 int sqlite3_strglob(const char *zGlobPattern, const char *zString){ 000862 if( zString==0 ){ 000863 return zGlobPattern!=0; 000864 }else if( zGlobPattern==0 ){ 000865 return 1; 000866 }else { 000867 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); 000868 } 000869 } 000870 000871 /* 000872 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for 000873 ** a miss - like strcmp(). 000874 */ 000875 int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ 000876 if( zStr==0 ){ 000877 return zPattern!=0; 000878 }else if( zPattern==0 ){ 000879 return 1; 000880 }else{ 000881 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); 000882 } 000883 } 000884 000885 /* 000886 ** Count the number of times that the LIKE operator (or GLOB which is 000887 ** just a variation of LIKE) gets called. This is used for testing 000888 ** only. 000889 */ 000890 #ifdef SQLITE_TEST 000891 int sqlite3_like_count = 0; 000892 #endif 000893 000894 000895 /* 000896 ** Implementation of the like() SQL function. This function implements 000897 ** the built-in LIKE operator. The first argument to the function is the 000898 ** pattern and the second argument is the string. So, the SQL statements: 000899 ** 000900 ** A LIKE B 000901 ** 000902 ** is implemented as like(B,A). 000903 ** 000904 ** This same function (with a different compareInfo structure) computes 000905 ** the GLOB operator. 000906 */ 000907 static void likeFunc( 000908 sqlite3_context *context, 000909 int argc, 000910 sqlite3_value **argv 000911 ){ 000912 const unsigned char *zA, *zB; 000913 u32 escape; 000914 int nPat; 000915 sqlite3 *db = sqlite3_context_db_handle(context); 000916 struct compareInfo *pInfo = sqlite3_user_data(context); 000917 struct compareInfo backupInfo; 000918 000919 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 000920 if( sqlite3_value_type(argv[0])==SQLITE_BLOB 000921 || sqlite3_value_type(argv[1])==SQLITE_BLOB 000922 ){ 000923 #ifdef SQLITE_TEST 000924 sqlite3_like_count++; 000925 #endif 000926 sqlite3_result_int(context, 0); 000927 return; 000928 } 000929 #endif 000930 000931 /* Limit the length of the LIKE or GLOB pattern to avoid problems 000932 ** of deep recursion and N*N behavior in patternCompare(). 000933 */ 000934 nPat = sqlite3_value_bytes(argv[0]); 000935 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); 000936 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); 000937 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ 000938 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); 000939 return; 000940 } 000941 if( argc==3 ){ 000942 /* The escape character string must consist of a single UTF-8 character. 000943 ** Otherwise, return an error. 000944 */ 000945 const unsigned char *zEsc = sqlite3_value_text(argv[2]); 000946 if( zEsc==0 ) return; 000947 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ 000948 sqlite3_result_error(context, 000949 "ESCAPE expression must be a single character", -1); 000950 return; 000951 } 000952 escape = sqlite3Utf8Read(&zEsc); 000953 if( escape==pInfo->matchAll || escape==pInfo->matchOne ){ 000954 memcpy(&backupInfo, pInfo, sizeof(backupInfo)); 000955 pInfo = &backupInfo; 000956 if( escape==pInfo->matchAll ) pInfo->matchAll = 0; 000957 if( escape==pInfo->matchOne ) pInfo->matchOne = 0; 000958 } 000959 }else{ 000960 escape = pInfo->matchSet; 000961 } 000962 zB = sqlite3_value_text(argv[0]); 000963 zA = sqlite3_value_text(argv[1]); 000964 if( zA && zB ){ 000965 #ifdef SQLITE_TEST 000966 sqlite3_like_count++; 000967 #endif 000968 sqlite3_result_int(context, 000969 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); 000970 } 000971 } 000972 000973 /* 000974 ** Implementation of the NULLIF(x,y) function. The result is the first 000975 ** argument if the arguments are different. The result is NULL if the 000976 ** arguments are equal to each other. 000977 */ 000978 static void nullifFunc( 000979 sqlite3_context *context, 000980 int NotUsed, 000981 sqlite3_value **argv 000982 ){ 000983 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 000984 UNUSED_PARAMETER(NotUsed); 000985 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ 000986 sqlite3_result_value(context, argv[0]); 000987 } 000988 } 000989 000990 /* 000991 ** Implementation of the sqlite_version() function. The result is the version 000992 ** of the SQLite library that is running. 000993 */ 000994 static void versionFunc( 000995 sqlite3_context *context, 000996 int NotUsed, 000997 sqlite3_value **NotUsed2 000998 ){ 000999 UNUSED_PARAMETER2(NotUsed, NotUsed2); 001000 /* IMP: R-48699-48617 This function is an SQL wrapper around the 001001 ** sqlite3_libversion() C-interface. */ 001002 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); 001003 } 001004 001005 /* 001006 ** Implementation of the sqlite_source_id() function. The result is a string 001007 ** that identifies the particular version of the source code used to build 001008 ** SQLite. 001009 */ 001010 static void sourceidFunc( 001011 sqlite3_context *context, 001012 int NotUsed, 001013 sqlite3_value **NotUsed2 001014 ){ 001015 UNUSED_PARAMETER2(NotUsed, NotUsed2); 001016 /* IMP: R-24470-31136 This function is an SQL wrapper around the 001017 ** sqlite3_sourceid() C interface. */ 001018 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); 001019 } 001020 001021 /* 001022 ** Implementation of the sqlite_log() function. This is a wrapper around 001023 ** sqlite3_log(). The return value is NULL. The function exists purely for 001024 ** its side-effects. 001025 */ 001026 static void errlogFunc( 001027 sqlite3_context *context, 001028 int argc, 001029 sqlite3_value **argv 001030 ){ 001031 UNUSED_PARAMETER(argc); 001032 UNUSED_PARAMETER(context); 001033 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); 001034 } 001035 001036 /* 001037 ** Implementation of the sqlite_compileoption_used() function. 001038 ** The result is an integer that identifies if the compiler option 001039 ** was used to build SQLite. 001040 */ 001041 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 001042 static void compileoptionusedFunc( 001043 sqlite3_context *context, 001044 int argc, 001045 sqlite3_value **argv 001046 ){ 001047 const char *zOptName; 001048 assert( argc==1 ); 001049 UNUSED_PARAMETER(argc); 001050 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL 001051 ** function is a wrapper around the sqlite3_compileoption_used() C/C++ 001052 ** function. 001053 */ 001054 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 001055 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); 001056 } 001057 } 001058 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 001059 001060 /* 001061 ** Implementation of the sqlite_compileoption_get() function. 001062 ** The result is a string that identifies the compiler options 001063 ** used to build SQLite. 001064 */ 001065 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 001066 static void compileoptiongetFunc( 001067 sqlite3_context *context, 001068 int argc, 001069 sqlite3_value **argv 001070 ){ 001071 int n; 001072 assert( argc==1 ); 001073 UNUSED_PARAMETER(argc); 001074 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function 001075 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. 001076 */ 001077 n = sqlite3_value_int(argv[0]); 001078 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); 001079 } 001080 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 001081 001082 /* Array for converting from half-bytes (nybbles) into ASCII hex 001083 ** digits. */ 001084 static const char hexdigits[] = { 001085 '0', '1', '2', '3', '4', '5', '6', '7', 001086 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 001087 }; 001088 001089 /* 001090 ** Append to pStr text that is the SQL literal representation of the 001091 ** value contained in pValue. 001092 */ 001093 void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){ 001094 /* As currently implemented, the string must be initially empty. 001095 ** we might relax this requirement in the future, but that will 001096 ** require enhancements to the implementation. */ 001097 assert( pStr!=0 && pStr->nChar==0 ); 001098 001099 switch( sqlite3_value_type(pValue) ){ 001100 case SQLITE_FLOAT: { 001101 double r1, r2; 001102 const char *zVal; 001103 r1 = sqlite3_value_double(pValue); 001104 sqlite3_str_appendf(pStr, "%!.15g", r1); 001105 zVal = sqlite3_str_value(pStr); 001106 if( zVal ){ 001107 sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8); 001108 if( r1!=r2 ){ 001109 sqlite3_str_reset(pStr); 001110 sqlite3_str_appendf(pStr, "%!.20e", r1); 001111 } 001112 } 001113 break; 001114 } 001115 case SQLITE_INTEGER: { 001116 sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue)); 001117 break; 001118 } 001119 case SQLITE_BLOB: { 001120 char const *zBlob = sqlite3_value_blob(pValue); 001121 i64 nBlob = sqlite3_value_bytes(pValue); 001122 assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */ 001123 sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4); 001124 if( pStr->accError==0 ){ 001125 char *zText = pStr->zText; 001126 int i; 001127 for(i=0; i<nBlob; i++){ 001128 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F]; 001129 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; 001130 } 001131 zText[(nBlob*2)+2] = '\''; 001132 zText[(nBlob*2)+3] = '\0'; 001133 zText[0] = 'X'; 001134 zText[1] = '\''; 001135 pStr->nChar = nBlob*2 + 3; 001136 } 001137 break; 001138 } 001139 case SQLITE_TEXT: { 001140 const unsigned char *zArg = sqlite3_value_text(pValue); 001141 sqlite3_str_appendf(pStr, "%Q", zArg); 001142 break; 001143 } 001144 default: { 001145 assert( sqlite3_value_type(pValue)==SQLITE_NULL ); 001146 sqlite3_str_append(pStr, "NULL", 4); 001147 break; 001148 } 001149 } 001150 } 001151 001152 /* 001153 ** Implementation of the QUOTE() function. 001154 ** 001155 ** The quote(X) function returns the text of an SQL literal which is the 001156 ** value of its argument suitable for inclusion into an SQL statement. 001157 ** Strings are surrounded by single-quotes with escapes on interior quotes 001158 ** as needed. BLOBs are encoded as hexadecimal literals. Strings with 001159 ** embedded NUL characters cannot be represented as string literals in SQL 001160 ** and hence the returned string literal is truncated prior to the first NUL. 001161 */ 001162 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 001163 sqlite3_str str; 001164 sqlite3 *db = sqlite3_context_db_handle(context); 001165 assert( argc==1 ); 001166 UNUSED_PARAMETER(argc); 001167 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); 001168 sqlite3QuoteValue(&str,argv[0]); 001169 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar, 001170 SQLITE_DYNAMIC); 001171 if( str.accError!=SQLITE_OK ){ 001172 sqlite3_result_null(context); 001173 sqlite3_result_error_code(context, str.accError); 001174 } 001175 } 001176 001177 /* 001178 ** The unicode() function. Return the integer unicode code-point value 001179 ** for the first character of the input string. 001180 */ 001181 static void unicodeFunc( 001182 sqlite3_context *context, 001183 int argc, 001184 sqlite3_value **argv 001185 ){ 001186 const unsigned char *z = sqlite3_value_text(argv[0]); 001187 (void)argc; 001188 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); 001189 } 001190 001191 /* 001192 ** The char() function takes zero or more arguments, each of which is 001193 ** an integer. It constructs a string where each character of the string 001194 ** is the unicode character for the corresponding integer argument. 001195 */ 001196 static void charFunc( 001197 sqlite3_context *context, 001198 int argc, 001199 sqlite3_value **argv 001200 ){ 001201 unsigned char *z, *zOut; 001202 int i; 001203 zOut = z = sqlite3_malloc64( argc*4+1 ); 001204 if( z==0 ){ 001205 sqlite3_result_error_nomem(context); 001206 return; 001207 } 001208 for(i=0; i<argc; i++){ 001209 sqlite3_int64 x; 001210 unsigned c; 001211 x = sqlite3_value_int64(argv[i]); 001212 if( x<0 || x>0x10ffff ) x = 0xfffd; 001213 c = (unsigned)(x & 0x1fffff); 001214 if( c<0x00080 ){ 001215 *zOut++ = (u8)(c&0xFF); 001216 }else if( c<0x00800 ){ 001217 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); 001218 *zOut++ = 0x80 + (u8)(c & 0x3F); 001219 }else if( c<0x10000 ){ 001220 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); 001221 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 001222 *zOut++ = 0x80 + (u8)(c & 0x3F); 001223 }else{ 001224 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); 001225 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); 001226 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 001227 *zOut++ = 0x80 + (u8)(c & 0x3F); 001228 } \ 001229 } 001230 *zOut = 0; 001231 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); 001232 } 001233 001234 /* 001235 ** The hex() function. Interpret the argument as a blob. Return 001236 ** a hexadecimal rendering as text. 001237 */ 001238 static void hexFunc( 001239 sqlite3_context *context, 001240 int argc, 001241 sqlite3_value **argv 001242 ){ 001243 int i, n; 001244 const unsigned char *pBlob; 001245 char *zHex, *z; 001246 assert( argc==1 ); 001247 UNUSED_PARAMETER(argc); 001248 pBlob = sqlite3_value_blob(argv[0]); 001249 n = sqlite3_value_bytes(argv[0]); 001250 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ 001251 z = zHex = contextMalloc(context, ((i64)n)*2 + 1); 001252 if( zHex ){ 001253 for(i=0; i<n; i++, pBlob++){ 001254 unsigned char c = *pBlob; 001255 *(z++) = hexdigits[(c>>4)&0xf]; 001256 *(z++) = hexdigits[c&0xf]; 001257 } 001258 *z = 0; 001259 sqlite3_result_text(context, zHex, n*2, sqlite3_free); 001260 } 001261 } 001262 001263 /* 001264 ** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr 001265 ** contains character ch, or 0 if it does not. 001266 */ 001267 static int strContainsChar(const u8 *zStr, int nStr, u32 ch){ 001268 const u8 *zEnd = &zStr[nStr]; 001269 const u8 *z = zStr; 001270 while( z<zEnd ){ 001271 u32 tst = Utf8Read(z); 001272 if( tst==ch ) return 1; 001273 } 001274 return 0; 001275 } 001276 001277 /* 001278 ** The unhex() function. This function may be invoked with either one or 001279 ** two arguments. In both cases the first argument is interpreted as text 001280 ** a text value containing a set of pairs of hexadecimal digits which are 001281 ** decoded and returned as a blob. 001282 ** 001283 ** If there is only a single argument, then it must consist only of an 001284 ** even number of hexadecimal digits. Otherwise, return NULL. 001285 ** 001286 ** Or, if there is a second argument, then any character that appears in 001287 ** the second argument is also allowed to appear between pairs of hexadecimal 001288 ** digits in the first argument. If any other character appears in the 001289 ** first argument, or if one of the allowed characters appears between 001290 ** two hexadecimal digits that make up a single byte, NULL is returned. 001291 ** 001292 ** The following expressions are all true: 001293 ** 001294 ** unhex('ABCD') IS x'ABCD' 001295 ** unhex('AB CD') IS NULL 001296 ** unhex('AB CD', ' ') IS x'ABCD' 001297 ** unhex('A BCD', ' ') IS NULL 001298 */ 001299 static void unhexFunc( 001300 sqlite3_context *pCtx, 001301 int argc, 001302 sqlite3_value **argv 001303 ){ 001304 const u8 *zPass = (const u8*)""; 001305 int nPass = 0; 001306 const u8 *zHex = sqlite3_value_text(argv[0]); 001307 int nHex = sqlite3_value_bytes(argv[0]); 001308 #ifdef SQLITE_DEBUG 001309 const u8 *zEnd = zHex ? &zHex[nHex] : 0; 001310 #endif 001311 u8 *pBlob = 0; 001312 u8 *p = 0; 001313 001314 assert( argc==1 || argc==2 ); 001315 if( argc==2 ){ 001316 zPass = sqlite3_value_text(argv[1]); 001317 nPass = sqlite3_value_bytes(argv[1]); 001318 } 001319 if( !zHex || !zPass ) return; 001320 001321 p = pBlob = contextMalloc(pCtx, (nHex/2)+1); 001322 if( pBlob ){ 001323 u8 c; /* Most significant digit of next byte */ 001324 u8 d; /* Least significant digit of next byte */ 001325 001326 while( (c = *zHex)!=0x00 ){ 001327 while( !sqlite3Isxdigit(c) ){ 001328 u32 ch = Utf8Read(zHex); 001329 assert( zHex<=zEnd ); 001330 if( !strContainsChar(zPass, nPass, ch) ) goto unhex_null; 001331 c = *zHex; 001332 if( c==0x00 ) goto unhex_done; 001333 } 001334 zHex++; 001335 assert( *zEnd==0x00 ); 001336 assert( zHex<=zEnd ); 001337 d = *(zHex++); 001338 if( !sqlite3Isxdigit(d) ) goto unhex_null; 001339 *(p++) = (sqlite3HexToInt(c)<<4) | sqlite3HexToInt(d); 001340 } 001341 } 001342 001343 unhex_done: 001344 sqlite3_result_blob(pCtx, pBlob, (p - pBlob), sqlite3_free); 001345 return; 001346 001347 unhex_null: 001348 sqlite3_free(pBlob); 001349 return; 001350 } 001351 001352 001353 /* 001354 ** The zeroblob(N) function returns a zero-filled blob of size N bytes. 001355 */ 001356 static void zeroblobFunc( 001357 sqlite3_context *context, 001358 int argc, 001359 sqlite3_value **argv 001360 ){ 001361 i64 n; 001362 int rc; 001363 assert( argc==1 ); 001364 UNUSED_PARAMETER(argc); 001365 n = sqlite3_value_int64(argv[0]); 001366 if( n<0 ) n = 0; 001367 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ 001368 if( rc ){ 001369 sqlite3_result_error_code(context, rc); 001370 } 001371 } 001372 001373 /* 001374 ** The replace() function. Three arguments are all strings: call 001375 ** them A, B, and C. The result is also a string which is derived 001376 ** from A by replacing every occurrence of B with C. The match 001377 ** must be exact. Collating sequences are not used. 001378 */ 001379 static void replaceFunc( 001380 sqlite3_context *context, 001381 int argc, 001382 sqlite3_value **argv 001383 ){ 001384 const unsigned char *zStr; /* The input string A */ 001385 const unsigned char *zPattern; /* The pattern string B */ 001386 const unsigned char *zRep; /* The replacement string C */ 001387 unsigned char *zOut; /* The output */ 001388 int nStr; /* Size of zStr */ 001389 int nPattern; /* Size of zPattern */ 001390 int nRep; /* Size of zRep */ 001391 i64 nOut; /* Maximum size of zOut */ 001392 int loopLimit; /* Last zStr[] that might match zPattern[] */ 001393 int i, j; /* Loop counters */ 001394 unsigned cntExpand; /* Number zOut expansions */ 001395 sqlite3 *db = sqlite3_context_db_handle(context); 001396 001397 assert( argc==3 ); 001398 UNUSED_PARAMETER(argc); 001399 zStr = sqlite3_value_text(argv[0]); 001400 if( zStr==0 ) return; 001401 nStr = sqlite3_value_bytes(argv[0]); 001402 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ 001403 zPattern = sqlite3_value_text(argv[1]); 001404 if( zPattern==0 ){ 001405 assert( sqlite3_value_type(argv[1])==SQLITE_NULL 001406 || sqlite3_context_db_handle(context)->mallocFailed ); 001407 return; 001408 } 001409 if( zPattern[0]==0 ){ 001410 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); 001411 sqlite3_result_value(context, argv[0]); 001412 return; 001413 } 001414 nPattern = sqlite3_value_bytes(argv[1]); 001415 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ 001416 zRep = sqlite3_value_text(argv[2]); 001417 if( zRep==0 ) return; 001418 nRep = sqlite3_value_bytes(argv[2]); 001419 assert( zRep==sqlite3_value_text(argv[2]) ); 001420 nOut = nStr + 1; 001421 assert( nOut<SQLITE_MAX_LENGTH ); 001422 zOut = contextMalloc(context, (i64)nOut); 001423 if( zOut==0 ){ 001424 return; 001425 } 001426 loopLimit = nStr - nPattern; 001427 cntExpand = 0; 001428 for(i=j=0; i<=loopLimit; i++){ 001429 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ 001430 zOut[j++] = zStr[i]; 001431 }else{ 001432 if( nRep>nPattern ){ 001433 nOut += nRep - nPattern; 001434 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); 001435 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); 001436 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 001437 sqlite3_result_error_toobig(context); 001438 sqlite3_free(zOut); 001439 return; 001440 } 001441 cntExpand++; 001442 if( (cntExpand&(cntExpand-1))==0 ){ 001443 /* Grow the size of the output buffer only on substitutions 001444 ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */ 001445 u8 *zOld; 001446 zOld = zOut; 001447 zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1)); 001448 if( zOut==0 ){ 001449 sqlite3_result_error_nomem(context); 001450 sqlite3_free(zOld); 001451 return; 001452 } 001453 } 001454 } 001455 memcpy(&zOut[j], zRep, nRep); 001456 j += nRep; 001457 i += nPattern-1; 001458 } 001459 } 001460 assert( j+nStr-i+1<=nOut ); 001461 memcpy(&zOut[j], &zStr[i], nStr-i); 001462 j += nStr - i; 001463 assert( j<=nOut ); 001464 zOut[j] = 0; 001465 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); 001466 } 001467 001468 /* 001469 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. 001470 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. 001471 */ 001472 static void trimFunc( 001473 sqlite3_context *context, 001474 int argc, 001475 sqlite3_value **argv 001476 ){ 001477 const unsigned char *zIn; /* Input string */ 001478 const unsigned char *zCharSet; /* Set of characters to trim */ 001479 unsigned int nIn; /* Number of bytes in input */ 001480 int flags; /* 1: trimleft 2: trimright 3: trim */ 001481 int i; /* Loop counter */ 001482 unsigned int *aLen = 0; /* Length of each character in zCharSet */ 001483 unsigned char **azChar = 0; /* Individual characters in zCharSet */ 001484 int nChar; /* Number of characters in zCharSet */ 001485 001486 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 001487 return; 001488 } 001489 zIn = sqlite3_value_text(argv[0]); 001490 if( zIn==0 ) return; 001491 nIn = (unsigned)sqlite3_value_bytes(argv[0]); 001492 assert( zIn==sqlite3_value_text(argv[0]) ); 001493 if( argc==1 ){ 001494 static const unsigned lenOne[] = { 1 }; 001495 static unsigned char * const azOne[] = { (u8*)" " }; 001496 nChar = 1; 001497 aLen = (unsigned*)lenOne; 001498 azChar = (unsigned char **)azOne; 001499 zCharSet = 0; 001500 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ 001501 return; 001502 }else{ 001503 const unsigned char *z; 001504 for(z=zCharSet, nChar=0; *z; nChar++){ 001505 SQLITE_SKIP_UTF8(z); 001506 } 001507 if( nChar>0 ){ 001508 azChar = contextMalloc(context, 001509 ((i64)nChar)*(sizeof(char*)+sizeof(unsigned))); 001510 if( azChar==0 ){ 001511 return; 001512 } 001513 aLen = (unsigned*)&azChar[nChar]; 001514 for(z=zCharSet, nChar=0; *z; nChar++){ 001515 azChar[nChar] = (unsigned char *)z; 001516 SQLITE_SKIP_UTF8(z); 001517 aLen[nChar] = (unsigned)(z - azChar[nChar]); 001518 } 001519 } 001520 } 001521 if( nChar>0 ){ 001522 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); 001523 if( flags & 1 ){ 001524 while( nIn>0 ){ 001525 unsigned int len = 0; 001526 for(i=0; i<nChar; i++){ 001527 len = aLen[i]; 001528 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break; 001529 } 001530 if( i>=nChar ) break; 001531 zIn += len; 001532 nIn -= len; 001533 } 001534 } 001535 if( flags & 2 ){ 001536 while( nIn>0 ){ 001537 unsigned int len = 0; 001538 for(i=0; i<nChar; i++){ 001539 len = aLen[i]; 001540 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break; 001541 } 001542 if( i>=nChar ) break; 001543 nIn -= len; 001544 } 001545 } 001546 if( zCharSet ){ 001547 sqlite3_free(azChar); 001548 } 001549 } 001550 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); 001551 } 001552 001553 001554 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 001555 /* 001556 ** The "unknown" function is automatically substituted in place of 001557 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN 001558 ** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used. 001559 ** When the "sqlite3" command-line shell is built using this functionality, 001560 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries 001561 ** involving application-defined functions to be examined in a generic 001562 ** sqlite3 shell. 001563 */ 001564 static void unknownFunc( 001565 sqlite3_context *context, 001566 int argc, 001567 sqlite3_value **argv 001568 ){ 001569 /* no-op */ 001570 (void)context; 001571 (void)argc; 001572 (void)argv; 001573 } 001574 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ 001575 001576 001577 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It 001578 ** is only available if the SQLITE_SOUNDEX compile-time option is used 001579 ** when SQLite is built. 001580 */ 001581 #ifdef SQLITE_SOUNDEX 001582 /* 001583 ** Compute the soundex encoding of a word. 001584 ** 001585 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the 001586 ** soundex encoding of the string X. 001587 */ 001588 static void soundexFunc( 001589 sqlite3_context *context, 001590 int argc, 001591 sqlite3_value **argv 001592 ){ 001593 char zResult[8]; 001594 const u8 *zIn; 001595 int i, j; 001596 static const unsigned char iCode[] = { 001597 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001598 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001599 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001600 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001601 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 001602 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 001603 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 001604 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 001605 }; 001606 assert( argc==1 ); 001607 zIn = (u8*)sqlite3_value_text(argv[0]); 001608 if( zIn==0 ) zIn = (u8*)""; 001609 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} 001610 if( zIn[i] ){ 001611 u8 prevcode = iCode[zIn[i]&0x7f]; 001612 zResult[0] = sqlite3Toupper(zIn[i]); 001613 for(j=1; j<4 && zIn[i]; i++){ 001614 int code = iCode[zIn[i]&0x7f]; 001615 if( code>0 ){ 001616 if( code!=prevcode ){ 001617 prevcode = code; 001618 zResult[j++] = code + '0'; 001619 } 001620 }else{ 001621 prevcode = 0; 001622 } 001623 } 001624 while( j<4 ){ 001625 zResult[j++] = '0'; 001626 } 001627 zResult[j] = 0; 001628 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); 001629 }else{ 001630 /* IMP: R-64894-50321 The string "?000" is returned if the argument 001631 ** is NULL or contains no ASCII alphabetic characters. */ 001632 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); 001633 } 001634 } 001635 #endif /* SQLITE_SOUNDEX */ 001636 001637 #ifndef SQLITE_OMIT_LOAD_EXTENSION 001638 /* 001639 ** A function that loads a shared-library extension then returns NULL. 001640 */ 001641 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ 001642 const char *zFile = (const char *)sqlite3_value_text(argv[0]); 001643 const char *zProc; 001644 sqlite3 *db = sqlite3_context_db_handle(context); 001645 char *zErrMsg = 0; 001646 001647 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc 001648 ** flag is set. See the sqlite3_enable_load_extension() API. 001649 */ 001650 if( (db->flags & SQLITE_LoadExtFunc)==0 ){ 001651 sqlite3_result_error(context, "not authorized", -1); 001652 return; 001653 } 001654 001655 if( argc==2 ){ 001656 zProc = (const char *)sqlite3_value_text(argv[1]); 001657 }else{ 001658 zProc = 0; 001659 } 001660 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ 001661 sqlite3_result_error(context, zErrMsg, -1); 001662 sqlite3_free(zErrMsg); 001663 } 001664 } 001665 #endif 001666 001667 001668 /* 001669 ** An instance of the following structure holds the context of a 001670 ** sum() or avg() aggregate computation. 001671 */ 001672 typedef struct SumCtx SumCtx; 001673 struct SumCtx { 001674 double rSum; /* Running sum as as a double */ 001675 double rErr; /* Error term for Kahan-Babushka-Neumaier summation */ 001676 i64 iSum; /* Running sum as a signed integer */ 001677 i64 cnt; /* Number of elements summed */ 001678 u8 approx; /* True if any non-integer value was input to the sum */ 001679 u8 ovrfl; /* Integer overflow seen */ 001680 }; 001681 001682 /* 001683 ** Do one step of the Kahan-Babushka-Neumaier summation. 001684 ** 001685 ** https://en.wikipedia.org/wiki/Kahan_summation_algorithm 001686 ** 001687 ** Variables are marked "volatile" to defeat c89 x86 floating point 001688 ** optimizations can mess up this algorithm. 001689 */ 001690 static void kahanBabuskaNeumaierStep( 001691 volatile SumCtx *pSum, 001692 volatile double r 001693 ){ 001694 volatile double s = pSum->rSum; 001695 volatile double t = s + r; 001696 if( fabs(s) > fabs(r) ){ 001697 pSum->rErr += (s - t) + r; 001698 }else{ 001699 pSum->rErr += (r - t) + s; 001700 } 001701 pSum->rSum = t; 001702 } 001703 001704 /* 001705 ** Add a (possibly large) integer to the running sum. 001706 */ 001707 static void kahanBabuskaNeumaierStepInt64(volatile SumCtx *pSum, i64 iVal){ 001708 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){ 001709 i64 iBig, iSm; 001710 iSm = iVal % 16384; 001711 iBig = iVal - iSm; 001712 kahanBabuskaNeumaierStep(pSum, iBig); 001713 kahanBabuskaNeumaierStep(pSum, iSm); 001714 }else{ 001715 kahanBabuskaNeumaierStep(pSum, (double)iVal); 001716 } 001717 } 001718 001719 /* 001720 ** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer 001721 */ 001722 static void kahanBabuskaNeumaierInit( 001723 volatile SumCtx *p, 001724 i64 iVal 001725 ){ 001726 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){ 001727 i64 iSm = iVal % 16384; 001728 p->rSum = (double)(iVal - iSm); 001729 p->rErr = (double)iSm; 001730 }else{ 001731 p->rSum = (double)iVal; 001732 p->rErr = 0.0; 001733 } 001734 } 001735 001736 /* 001737 ** Routines used to compute the sum, average, and total. 001738 ** 001739 ** The SUM() function follows the (broken) SQL standard which means 001740 ** that it returns NULL if it sums over no inputs. TOTAL returns 001741 ** 0.0 in that case. In addition, TOTAL always returns a float where 001742 ** SUM might return an integer if it never encounters a floating point 001743 ** value. TOTAL never fails, but SUM might through an exception if 001744 ** it overflows an integer. 001745 */ 001746 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 001747 SumCtx *p; 001748 int type; 001749 assert( argc==1 ); 001750 UNUSED_PARAMETER(argc); 001751 p = sqlite3_aggregate_context(context, sizeof(*p)); 001752 type = sqlite3_value_numeric_type(argv[0]); 001753 if( p && type!=SQLITE_NULL ){ 001754 p->cnt++; 001755 if( p->approx==0 ){ 001756 if( type!=SQLITE_INTEGER ){ 001757 kahanBabuskaNeumaierInit(p, p->iSum); 001758 p->approx = 1; 001759 kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0])); 001760 }else{ 001761 i64 x = p->iSum; 001762 if( sqlite3AddInt64(&x, sqlite3_value_int64(argv[0]))==0 ){ 001763 p->iSum = x; 001764 }else{ 001765 p->ovrfl = 1; 001766 kahanBabuskaNeumaierInit(p, p->iSum); 001767 p->approx = 1; 001768 kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0])); 001769 } 001770 } 001771 }else{ 001772 if( type==SQLITE_INTEGER ){ 001773 kahanBabuskaNeumaierStepInt64(p, sqlite3_value_int64(argv[0])); 001774 }else{ 001775 p->ovrfl = 0; 001776 kahanBabuskaNeumaierStep(p, sqlite3_value_double(argv[0])); 001777 } 001778 } 001779 } 001780 } 001781 #ifndef SQLITE_OMIT_WINDOWFUNC 001782 static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ 001783 SumCtx *p; 001784 int type; 001785 assert( argc==1 ); 001786 UNUSED_PARAMETER(argc); 001787 p = sqlite3_aggregate_context(context, sizeof(*p)); 001788 type = sqlite3_value_numeric_type(argv[0]); 001789 /* p is always non-NULL because sumStep() will have been called first 001790 ** to initialize it */ 001791 if( ALWAYS(p) && type!=SQLITE_NULL ){ 001792 assert( p->cnt>0 ); 001793 p->cnt--; 001794 if( !p->approx ){ 001795 p->iSum -= sqlite3_value_int64(argv[0]); 001796 }else if( type==SQLITE_INTEGER ){ 001797 i64 iVal = sqlite3_value_int64(argv[0]); 001798 if( iVal!=SMALLEST_INT64 ){ 001799 kahanBabuskaNeumaierStepInt64(p, -iVal); 001800 }else{ 001801 kahanBabuskaNeumaierStepInt64(p, LARGEST_INT64); 001802 kahanBabuskaNeumaierStepInt64(p, 1); 001803 } 001804 }else{ 001805 kahanBabuskaNeumaierStep(p, -sqlite3_value_double(argv[0])); 001806 } 001807 } 001808 } 001809 #else 001810 # define sumInverse 0 001811 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001812 static void sumFinalize(sqlite3_context *context){ 001813 SumCtx *p; 001814 p = sqlite3_aggregate_context(context, 0); 001815 if( p && p->cnt>0 ){ 001816 if( p->approx ){ 001817 if( p->ovrfl ){ 001818 sqlite3_result_error(context,"integer overflow",-1); 001819 }else if( !sqlite3IsNaN(p->rErr) ){ 001820 sqlite3_result_double(context, p->rSum+p->rErr); 001821 }else{ 001822 sqlite3_result_double(context, p->rSum); 001823 } 001824 }else{ 001825 sqlite3_result_int64(context, p->iSum); 001826 } 001827 } 001828 } 001829 static void avgFinalize(sqlite3_context *context){ 001830 SumCtx *p; 001831 p = sqlite3_aggregate_context(context, 0); 001832 if( p && p->cnt>0 ){ 001833 double r; 001834 if( p->approx ){ 001835 r = p->rSum; 001836 if( !sqlite3IsNaN(p->rErr) ) r += p->rErr; 001837 }else{ 001838 r = (double)(p->iSum); 001839 } 001840 sqlite3_result_double(context, r/(double)p->cnt); 001841 } 001842 } 001843 static void totalFinalize(sqlite3_context *context){ 001844 SumCtx *p; 001845 double r = 0.0; 001846 p = sqlite3_aggregate_context(context, 0); 001847 if( p ){ 001848 if( p->approx ){ 001849 r = p->rSum; 001850 if( !sqlite3IsNaN(p->rErr) ) r += p->rErr; 001851 }else{ 001852 r = (double)(p->iSum); 001853 } 001854 } 001855 sqlite3_result_double(context, r); 001856 } 001857 001858 /* 001859 ** The following structure keeps track of state information for the 001860 ** count() aggregate function. 001861 */ 001862 typedef struct CountCtx CountCtx; 001863 struct CountCtx { 001864 i64 n; 001865 #ifdef SQLITE_DEBUG 001866 int bInverse; /* True if xInverse() ever called */ 001867 #endif 001868 }; 001869 001870 /* 001871 ** Routines to implement the count() aggregate function. 001872 */ 001873 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 001874 CountCtx *p; 001875 p = sqlite3_aggregate_context(context, sizeof(*p)); 001876 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ 001877 p->n++; 001878 } 001879 001880 #ifndef SQLITE_OMIT_DEPRECATED 001881 /* The sqlite3_aggregate_count() function is deprecated. But just to make 001882 ** sure it still operates correctly, verify that its count agrees with our 001883 ** internal count when using count(*) and when the total count can be 001884 ** expressed as a 32-bit integer. */ 001885 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse 001886 || p->n==sqlite3_aggregate_count(context) ); 001887 #endif 001888 } 001889 static void countFinalize(sqlite3_context *context){ 001890 CountCtx *p; 001891 p = sqlite3_aggregate_context(context, 0); 001892 sqlite3_result_int64(context, p ? p->n : 0); 001893 } 001894 #ifndef SQLITE_OMIT_WINDOWFUNC 001895 static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){ 001896 CountCtx *p; 001897 p = sqlite3_aggregate_context(ctx, sizeof(*p)); 001898 /* p is always non-NULL since countStep() will have been called first */ 001899 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){ 001900 p->n--; 001901 #ifdef SQLITE_DEBUG 001902 p->bInverse = 1; 001903 #endif 001904 } 001905 } 001906 #else 001907 # define countInverse 0 001908 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001909 001910 /* 001911 ** Routines to implement min() and max() aggregate functions. 001912 */ 001913 static void minmaxStep( 001914 sqlite3_context *context, 001915 int NotUsed, 001916 sqlite3_value **argv 001917 ){ 001918 Mem *pArg = (Mem *)argv[0]; 001919 Mem *pBest; 001920 UNUSED_PARAMETER(NotUsed); 001921 001922 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); 001923 if( !pBest ) return; 001924 001925 if( sqlite3_value_type(pArg)==SQLITE_NULL ){ 001926 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); 001927 }else if( pBest->flags ){ 001928 int max; 001929 int cmp; 001930 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 001931 /* This step function is used for both the min() and max() aggregates, 001932 ** the only difference between the two being that the sense of the 001933 ** comparison is inverted. For the max() aggregate, the 001934 ** sqlite3_user_data() function returns (void *)-1. For min() it 001935 ** returns (void *)db, where db is the sqlite3* database pointer. 001936 ** Therefore the next statement sets variable 'max' to 1 for the max() 001937 ** aggregate, or 0 for min(). 001938 */ 001939 max = sqlite3_user_data(context)!=0; 001940 cmp = sqlite3MemCompare(pBest, pArg, pColl); 001941 if( (max && cmp<0) || (!max && cmp>0) ){ 001942 sqlite3VdbeMemCopy(pBest, pArg); 001943 }else{ 001944 sqlite3SkipAccumulatorLoad(context); 001945 } 001946 }else{ 001947 pBest->db = sqlite3_context_db_handle(context); 001948 sqlite3VdbeMemCopy(pBest, pArg); 001949 } 001950 } 001951 static void minMaxValueFinalize(sqlite3_context *context, int bValue){ 001952 sqlite3_value *pRes; 001953 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); 001954 if( pRes ){ 001955 if( pRes->flags ){ 001956 sqlite3_result_value(context, pRes); 001957 } 001958 if( bValue==0 ) sqlite3VdbeMemRelease(pRes); 001959 } 001960 } 001961 #ifndef SQLITE_OMIT_WINDOWFUNC 001962 static void minMaxValue(sqlite3_context *context){ 001963 minMaxValueFinalize(context, 1); 001964 } 001965 #else 001966 # define minMaxValue 0 001967 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001968 static void minMaxFinalize(sqlite3_context *context){ 001969 minMaxValueFinalize(context, 0); 001970 } 001971 001972 /* 001973 ** group_concat(EXPR, ?SEPARATOR?) 001974 ** 001975 ** The SEPARATOR goes before the EXPR string. This is tragic. The 001976 ** groupConcatInverse() implementation would have been easier if the 001977 ** SEPARATOR were appended after EXPR. And the order is undocumented, 001978 ** so we could change it, in theory. But the old behavior has been 001979 ** around for so long that we dare not, for fear of breaking something. 001980 */ 001981 typedef struct { 001982 StrAccum str; /* The accumulated concatenation */ 001983 #ifndef SQLITE_OMIT_WINDOWFUNC 001984 int nAccum; /* Number of strings presently concatenated */ 001985 int nFirstSepLength; /* Used to detect separator length change */ 001986 /* If pnSepLengths!=0, refs an array of inter-string separator lengths, 001987 ** stored as actually incorporated into presently accumulated result. 001988 ** (Hence, its slots in use number nAccum-1 between method calls.) 001989 ** If pnSepLengths==0, nFirstSepLength is the length used throughout. 001990 */ 001991 int *pnSepLengths; 001992 #endif 001993 } GroupConcatCtx; 001994 001995 static void groupConcatStep( 001996 sqlite3_context *context, 001997 int argc, 001998 sqlite3_value **argv 001999 ){ 002000 const char *zVal; 002001 GroupConcatCtx *pGCC; 002002 const char *zSep; 002003 int nVal, nSep; 002004 assert( argc==1 || argc==2 ); 002005 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 002006 pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC)); 002007 if( pGCC ){ 002008 sqlite3 *db = sqlite3_context_db_handle(context); 002009 int firstTerm = pGCC->str.mxAlloc==0; 002010 pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; 002011 if( argc==1 ){ 002012 if( !firstTerm ){ 002013 sqlite3_str_appendchar(&pGCC->str, 1, ','); 002014 } 002015 #ifndef SQLITE_OMIT_WINDOWFUNC 002016 else{ 002017 pGCC->nFirstSepLength = 1; 002018 } 002019 #endif 002020 }else if( !firstTerm ){ 002021 zSep = (char*)sqlite3_value_text(argv[1]); 002022 nSep = sqlite3_value_bytes(argv[1]); 002023 if( zSep ){ 002024 sqlite3_str_append(&pGCC->str, zSep, nSep); 002025 } 002026 #ifndef SQLITE_OMIT_WINDOWFUNC 002027 else{ 002028 nSep = 0; 002029 } 002030 if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){ 002031 int *pnsl = pGCC->pnSepLengths; 002032 if( pnsl == 0 ){ 002033 /* First separator length variation seen, start tracking them. */ 002034 pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int)); 002035 if( pnsl!=0 ){ 002036 int i = 0, nA = pGCC->nAccum-1; 002037 while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength; 002038 } 002039 }else{ 002040 pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int)); 002041 } 002042 if( pnsl!=0 ){ 002043 if( ALWAYS(pGCC->nAccum>0) ){ 002044 pnsl[pGCC->nAccum-1] = nSep; 002045 } 002046 pGCC->pnSepLengths = pnsl; 002047 }else{ 002048 sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM); 002049 } 002050 } 002051 #endif 002052 } 002053 #ifndef SQLITE_OMIT_WINDOWFUNC 002054 else{ 002055 pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]); 002056 } 002057 pGCC->nAccum += 1; 002058 #endif 002059 zVal = (char*)sqlite3_value_text(argv[0]); 002060 nVal = sqlite3_value_bytes(argv[0]); 002061 if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal); 002062 } 002063 } 002064 002065 #ifndef SQLITE_OMIT_WINDOWFUNC 002066 static void groupConcatInverse( 002067 sqlite3_context *context, 002068 int argc, 002069 sqlite3_value **argv 002070 ){ 002071 GroupConcatCtx *pGCC; 002072 assert( argc==1 || argc==2 ); 002073 (void)argc; /* Suppress unused parameter warning */ 002074 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 002075 pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC)); 002076 /* pGCC is always non-NULL since groupConcatStep() will have always 002077 ** run first to initialize it */ 002078 if( ALWAYS(pGCC) ){ 002079 int nVS; 002080 /* Must call sqlite3_value_text() to convert the argument into text prior 002081 ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */ 002082 (void)sqlite3_value_text(argv[0]); 002083 nVS = sqlite3_value_bytes(argv[0]); 002084 pGCC->nAccum -= 1; 002085 if( pGCC->pnSepLengths!=0 ){ 002086 assert(pGCC->nAccum >= 0); 002087 if( pGCC->nAccum>0 ){ 002088 nVS += *pGCC->pnSepLengths; 002089 memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1, 002090 (pGCC->nAccum-1)*sizeof(int)); 002091 } 002092 }else{ 002093 /* If removing single accumulated string, harmlessly over-do. */ 002094 nVS += pGCC->nFirstSepLength; 002095 } 002096 if( nVS>=(int)pGCC->str.nChar ){ 002097 pGCC->str.nChar = 0; 002098 }else{ 002099 pGCC->str.nChar -= nVS; 002100 memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar); 002101 } 002102 if( pGCC->str.nChar==0 ){ 002103 pGCC->str.mxAlloc = 0; 002104 sqlite3_free(pGCC->pnSepLengths); 002105 pGCC->pnSepLengths = 0; 002106 } 002107 } 002108 } 002109 #else 002110 # define groupConcatInverse 0 002111 #endif /* SQLITE_OMIT_WINDOWFUNC */ 002112 static void groupConcatFinalize(sqlite3_context *context){ 002113 GroupConcatCtx *pGCC 002114 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0); 002115 if( pGCC ){ 002116 sqlite3ResultStrAccum(context, &pGCC->str); 002117 #ifndef SQLITE_OMIT_WINDOWFUNC 002118 sqlite3_free(pGCC->pnSepLengths); 002119 #endif 002120 } 002121 } 002122 #ifndef SQLITE_OMIT_WINDOWFUNC 002123 static void groupConcatValue(sqlite3_context *context){ 002124 GroupConcatCtx *pGCC 002125 = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0); 002126 if( pGCC ){ 002127 StrAccum *pAccum = &pGCC->str; 002128 if( pAccum->accError==SQLITE_TOOBIG ){ 002129 sqlite3_result_error_toobig(context); 002130 }else if( pAccum->accError==SQLITE_NOMEM ){ 002131 sqlite3_result_error_nomem(context); 002132 }else{ 002133 const char *zText = sqlite3_str_value(pAccum); 002134 sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT); 002135 } 002136 } 002137 } 002138 #else 002139 # define groupConcatValue 0 002140 #endif /* SQLITE_OMIT_WINDOWFUNC */ 002141 002142 /* 002143 ** This routine does per-connection function registration. Most 002144 ** of the built-in functions above are part of the global function set. 002145 ** This routine only deals with those that are not global. 002146 */ 002147 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ 002148 int rc = sqlite3_overload_function(db, "MATCH", 2); 002149 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); 002150 if( rc==SQLITE_NOMEM ){ 002151 sqlite3OomFault(db); 002152 } 002153 } 002154 002155 /* 002156 ** Re-register the built-in LIKE functions. The caseSensitive 002157 ** parameter determines whether or not the LIKE operator is case 002158 ** sensitive. 002159 */ 002160 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ 002161 FuncDef *pDef; 002162 struct compareInfo *pInfo; 002163 int flags; 002164 int nArg; 002165 if( caseSensitive ){ 002166 pInfo = (struct compareInfo*)&likeInfoAlt; 002167 flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE; 002168 }else{ 002169 pInfo = (struct compareInfo*)&likeInfoNorm; 002170 flags = SQLITE_FUNC_LIKE; 002171 } 002172 for(nArg=2; nArg<=3; nArg++){ 002173 sqlite3CreateFunc(db, "like", nArg, SQLITE_UTF8, pInfo, likeFunc, 002174 0, 0, 0, 0, 0); 002175 pDef = sqlite3FindFunction(db, "like", nArg, SQLITE_UTF8, 0); 002176 pDef->funcFlags |= flags; 002177 pDef->funcFlags &= ~SQLITE_FUNC_UNSAFE; 002178 } 002179 } 002180 002181 /* 002182 ** pExpr points to an expression which implements a function. If 002183 ** it is appropriate to apply the LIKE optimization to that function 002184 ** then set aWc[0] through aWc[2] to the wildcard characters and the 002185 ** escape character and then return TRUE. If the function is not a 002186 ** LIKE-style function then return FALSE. 002187 ** 002188 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE 002189 ** operator if c is a string literal that is exactly one byte in length. 002190 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is 002191 ** no ESCAPE clause. 002192 ** 002193 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for 002194 ** the function (default for LIKE). If the function makes the distinction 002195 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to 002196 ** false. 002197 */ 002198 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ 002199 FuncDef *pDef; 002200 int nExpr; 002201 assert( pExpr!=0 ); 002202 assert( pExpr->op==TK_FUNCTION ); 002203 assert( ExprUseXList(pExpr) ); 002204 if( !pExpr->x.pList ){ 002205 return 0; 002206 } 002207 nExpr = pExpr->x.pList->nExpr; 002208 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 002209 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0); 002210 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 002211 if( pDef==0 ) return 0; 002212 #endif 002213 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ 002214 return 0; 002215 } 002216 002217 /* The memcpy() statement assumes that the wildcard characters are 002218 ** the first three statements in the compareInfo structure. The 002219 ** asserts() that follow verify that assumption 002220 */ 002221 memcpy(aWc, pDef->pUserData, 3); 002222 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); 002223 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); 002224 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); 002225 002226 if( nExpr<3 ){ 002227 aWc[3] = 0; 002228 }else{ 002229 Expr *pEscape = pExpr->x.pList->a[2].pExpr; 002230 char *zEscape; 002231 if( pEscape->op!=TK_STRING ) return 0; 002232 assert( !ExprHasProperty(pEscape, EP_IntValue) ); 002233 zEscape = pEscape->u.zToken; 002234 if( zEscape[0]==0 || zEscape[1]!=0 ) return 0; 002235 if( zEscape[0]==aWc[0] ) return 0; 002236 if( zEscape[0]==aWc[1] ) return 0; 002237 aWc[3] = zEscape[0]; 002238 } 002239 002240 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; 002241 return 1; 002242 } 002243 002244 /* Mathematical Constants */ 002245 #ifndef M_PI 002246 # define M_PI 3.141592653589793238462643383279502884 002247 #endif 002248 #ifndef M_LN10 002249 # define M_LN10 2.302585092994045684017991454684364208 002250 #endif 002251 #ifndef M_LN2 002252 # define M_LN2 0.693147180559945309417232121458176568 002253 #endif 002254 002255 002256 /* Extra math functions that require linking with -lm 002257 */ 002258 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS 002259 /* 002260 ** Implementation SQL functions: 002261 ** 002262 ** ceil(X) 002263 ** ceiling(X) 002264 ** floor(X) 002265 ** 002266 ** The sqlite3_user_data() pointer is a pointer to the libm implementation 002267 ** of the underlying C function. 002268 */ 002269 static void ceilingFunc( 002270 sqlite3_context *context, 002271 int argc, 002272 sqlite3_value **argv 002273 ){ 002274 assert( argc==1 ); 002275 switch( sqlite3_value_numeric_type(argv[0]) ){ 002276 case SQLITE_INTEGER: { 002277 sqlite3_result_int64(context, sqlite3_value_int64(argv[0])); 002278 break; 002279 } 002280 case SQLITE_FLOAT: { 002281 double (*x)(double) = (double(*)(double))sqlite3_user_data(context); 002282 sqlite3_result_double(context, x(sqlite3_value_double(argv[0]))); 002283 break; 002284 } 002285 default: { 002286 break; 002287 } 002288 } 002289 } 002290 002291 /* 002292 ** On some systems, ceil() and floor() are intrinsic function. You are 002293 ** unable to take a pointer to these functions. Hence, we here wrap them 002294 ** in our own actual functions. 002295 */ 002296 static double xCeil(double x){ return ceil(x); } 002297 static double xFloor(double x){ return floor(x); } 002298 002299 /* 002300 ** Some systems do not have log2() and log10() in their standard math 002301 ** libraries. 002302 */ 002303 #if defined(HAVE_LOG10) && HAVE_LOG10==0 002304 # define log10(X) (0.4342944819032517867*log(X)) 002305 #endif 002306 #if defined(HAVE_LOG2) && HAVE_LOG2==0 002307 # define log2(X) (1.442695040888963456*log(X)) 002308 #endif 002309 002310 002311 /* 002312 ** Implementation of SQL functions: 002313 ** 002314 ** ln(X) - natural logarithm 002315 ** log(X) - log X base 10 002316 ** log10(X) - log X base 10 002317 ** log(B,X) - log X base B 002318 */ 002319 static void logFunc( 002320 sqlite3_context *context, 002321 int argc, 002322 sqlite3_value **argv 002323 ){ 002324 double x, b, ans; 002325 assert( argc==1 || argc==2 ); 002326 switch( sqlite3_value_numeric_type(argv[0]) ){ 002327 case SQLITE_INTEGER: 002328 case SQLITE_FLOAT: 002329 x = sqlite3_value_double(argv[0]); 002330 if( x<=0.0 ) return; 002331 break; 002332 default: 002333 return; 002334 } 002335 if( argc==2 ){ 002336 switch( sqlite3_value_numeric_type(argv[0]) ){ 002337 case SQLITE_INTEGER: 002338 case SQLITE_FLOAT: 002339 b = log(x); 002340 if( b<=0.0 ) return; 002341 x = sqlite3_value_double(argv[1]); 002342 if( x<=0.0 ) return; 002343 break; 002344 default: 002345 return; 002346 } 002347 ans = log(x)/b; 002348 }else{ 002349 switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context)) ){ 002350 case 1: 002351 ans = log10(x); 002352 break; 002353 case 2: 002354 ans = log2(x); 002355 break; 002356 default: 002357 ans = log(x); 002358 break; 002359 } 002360 } 002361 sqlite3_result_double(context, ans); 002362 } 002363 002364 /* 002365 ** Functions to converts degrees to radians and radians to degrees. 002366 */ 002367 static double degToRad(double x){ return x*(M_PI/180.0); } 002368 static double radToDeg(double x){ return x*(180.0/M_PI); } 002369 002370 /* 002371 ** Implementation of 1-argument SQL math functions: 002372 ** 002373 ** exp(X) - Compute e to the X-th power 002374 */ 002375 static void math1Func( 002376 sqlite3_context *context, 002377 int argc, 002378 sqlite3_value **argv 002379 ){ 002380 int type0; 002381 double v0, ans; 002382 double (*x)(double); 002383 assert( argc==1 ); 002384 type0 = sqlite3_value_numeric_type(argv[0]); 002385 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return; 002386 v0 = sqlite3_value_double(argv[0]); 002387 x = (double(*)(double))sqlite3_user_data(context); 002388 ans = x(v0); 002389 sqlite3_result_double(context, ans); 002390 } 002391 002392 /* 002393 ** Implementation of 2-argument SQL math functions: 002394 ** 002395 ** power(X,Y) - Compute X to the Y-th power 002396 */ 002397 static void math2Func( 002398 sqlite3_context *context, 002399 int argc, 002400 sqlite3_value **argv 002401 ){ 002402 int type0, type1; 002403 double v0, v1, ans; 002404 double (*x)(double,double); 002405 assert( argc==2 ); 002406 type0 = sqlite3_value_numeric_type(argv[0]); 002407 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return; 002408 type1 = sqlite3_value_numeric_type(argv[1]); 002409 if( type1!=SQLITE_INTEGER && type1!=SQLITE_FLOAT ) return; 002410 v0 = sqlite3_value_double(argv[0]); 002411 v1 = sqlite3_value_double(argv[1]); 002412 x = (double(*)(double,double))sqlite3_user_data(context); 002413 ans = x(v0, v1); 002414 sqlite3_result_double(context, ans); 002415 } 002416 002417 /* 002418 ** Implementation of 0-argument pi() function. 002419 */ 002420 static void piFunc( 002421 sqlite3_context *context, 002422 int argc, 002423 sqlite3_value **argv 002424 ){ 002425 assert( argc==0 ); 002426 (void)argv; 002427 sqlite3_result_double(context, M_PI); 002428 } 002429 002430 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */ 002431 002432 /* 002433 ** Implementation of sign(X) function. 002434 */ 002435 static void signFunc( 002436 sqlite3_context *context, 002437 int argc, 002438 sqlite3_value **argv 002439 ){ 002440 int type0; 002441 double x; 002442 UNUSED_PARAMETER(argc); 002443 assert( argc==1 ); 002444 type0 = sqlite3_value_numeric_type(argv[0]); 002445 if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return; 002446 x = sqlite3_value_double(argv[0]); 002447 sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0); 002448 } 002449 002450 #ifdef SQLITE_DEBUG 002451 /* 002452 ** Implementation of fpdecode(x,y,z) function. 002453 ** 002454 ** x is a real number that is to be decoded. y is the precision. 002455 ** z is the maximum real precision. 002456 */ 002457 static void fpdecodeFunc( 002458 sqlite3_context *context, 002459 int argc, 002460 sqlite3_value **argv 002461 ){ 002462 FpDecode s; 002463 double x; 002464 int y, z; 002465 char zBuf[100]; 002466 UNUSED_PARAMETER(argc); 002467 assert( argc==3 ); 002468 x = sqlite3_value_double(argv[0]); 002469 y = sqlite3_value_int(argv[1]); 002470 z = sqlite3_value_int(argv[2]); 002471 sqlite3FpDecode(&s, x, y, z); 002472 if( s.isSpecial==2 ){ 002473 sqlite3_snprintf(sizeof(zBuf), zBuf, "NaN"); 002474 }else{ 002475 sqlite3_snprintf(sizeof(zBuf), zBuf, "%c%.*s/%d", s.sign, s.n, s.z, s.iDP); 002476 } 002477 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); 002478 } 002479 #endif /* SQLITE_DEBUG */ 002480 002481 /* 002482 ** All of the FuncDef structures in the aBuiltinFunc[] array above 002483 ** to the global function hash table. This occurs at start-time (as 002484 ** a consequence of calling sqlite3_initialize()). 002485 ** 002486 ** After this routine runs 002487 */ 002488 void sqlite3RegisterBuiltinFunctions(void){ 002489 /* 002490 ** The following array holds FuncDef structures for all of the functions 002491 ** defined in this file. 002492 ** 002493 ** The array cannot be constant since changes are made to the 002494 ** FuncDef.pHash elements at start-time. The elements of this array 002495 ** are read-only after initialization is complete. 002496 ** 002497 ** For peak efficiency, put the most frequently used function last. 002498 */ 002499 static FuncDef aBuiltinFunc[] = { 002500 /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/ 002501 #if !defined(SQLITE_UNTESTABLE) 002502 TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0), 002503 TEST_FUNC(expr_compare, 2, INLINEFUNC_expr_compare, 0), 002504 TEST_FUNC(expr_implies_expr, 2, INLINEFUNC_expr_implies_expr, 0), 002505 TEST_FUNC(affinity, 1, INLINEFUNC_affinity, 0), 002506 #endif /* !defined(SQLITE_UNTESTABLE) */ 002507 /***** Regular functions *****/ 002508 #ifdef SQLITE_SOUNDEX 002509 FUNCTION(soundex, 1, 0, 0, soundexFunc ), 002510 #endif 002511 #ifndef SQLITE_OMIT_LOAD_EXTENSION 002512 SFUNCTION(load_extension, 1, 0, 0, loadExt ), 002513 SFUNCTION(load_extension, 2, 0, 0, loadExt ), 002514 #endif 002515 #if SQLITE_USER_AUTHENTICATION 002516 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), 002517 #endif 002518 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 002519 DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), 002520 DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), 002521 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 002522 INLINE_FUNC(unlikely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), 002523 INLINE_FUNC(likelihood, 2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), 002524 INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), 002525 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 002526 INLINE_FUNC(sqlite_offset, 1, INLINEFUNC_sqlite_offset, 0 ), 002527 #endif 002528 FUNCTION(ltrim, 1, 1, 0, trimFunc ), 002529 FUNCTION(ltrim, 2, 1, 0, trimFunc ), 002530 FUNCTION(rtrim, 1, 2, 0, trimFunc ), 002531 FUNCTION(rtrim, 2, 2, 0, trimFunc ), 002532 FUNCTION(trim, 1, 3, 0, trimFunc ), 002533 FUNCTION(trim, 2, 3, 0, trimFunc ), 002534 FUNCTION(min, -1, 0, 1, minmaxFunc ), 002535 FUNCTION(min, 0, 0, 1, 0 ), 002536 WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, 002537 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ), 002538 FUNCTION(max, -1, 1, 1, minmaxFunc ), 002539 FUNCTION(max, 0, 1, 1, 0 ), 002540 WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, 002541 SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ), 002542 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), 002543 FUNCTION2(subtype, 1, 0, 0, subtypeFunc, SQLITE_FUNC_TYPEOF), 002544 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), 002545 FUNCTION2(octet_length, 1, 0, 0, bytelengthFunc,SQLITE_FUNC_BYTELEN), 002546 FUNCTION(instr, 2, 0, 0, instrFunc ), 002547 FUNCTION(printf, -1, 0, 0, printfFunc ), 002548 FUNCTION(format, -1, 0, 0, printfFunc ), 002549 FUNCTION(unicode, 1, 0, 0, unicodeFunc ), 002550 FUNCTION(char, -1, 0, 0, charFunc ), 002551 FUNCTION(abs, 1, 0, 0, absFunc ), 002552 #ifdef SQLITE_DEBUG 002553 FUNCTION(fpdecode, 3, 0, 0, fpdecodeFunc ), 002554 #endif 002555 #ifndef SQLITE_OMIT_FLOATING_POINT 002556 FUNCTION(round, 1, 0, 0, roundFunc ), 002557 FUNCTION(round, 2, 0, 0, roundFunc ), 002558 #endif 002559 FUNCTION(upper, 1, 0, 0, upperFunc ), 002560 FUNCTION(lower, 1, 0, 0, lowerFunc ), 002561 FUNCTION(hex, 1, 0, 0, hexFunc ), 002562 FUNCTION(unhex, 1, 0, 0, unhexFunc ), 002563 FUNCTION(unhex, 2, 0, 0, unhexFunc ), 002564 INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, 0 ), 002565 VFUNCTION(random, 0, 0, 0, randomFunc ), 002566 VFUNCTION(randomblob, 1, 0, 0, randomBlob ), 002567 FUNCTION(nullif, 2, 0, 1, nullifFunc ), 002568 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), 002569 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), 002570 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), 002571 FUNCTION(quote, 1, 0, 0, quoteFunc ), 002572 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), 002573 VFUNCTION(changes, 0, 0, 0, changes ), 002574 VFUNCTION(total_changes, 0, 0, 0, total_changes ), 002575 FUNCTION(replace, 3, 0, 0, replaceFunc ), 002576 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), 002577 FUNCTION(substr, 2, 0, 0, substrFunc ), 002578 FUNCTION(substr, 3, 0, 0, substrFunc ), 002579 FUNCTION(substring, 2, 0, 0, substrFunc ), 002580 FUNCTION(substring, 3, 0, 0, substrFunc ), 002581 WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0), 002582 WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0), 002583 WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0), 002584 WAGGREGATE(count, 0,0,0, countStep, 002585 countFinalize, countFinalize, countInverse, 002586 SQLITE_FUNC_COUNT|SQLITE_FUNC_ANYORDER ), 002587 WAGGREGATE(count, 1,0,0, countStep, 002588 countFinalize, countFinalize, countInverse, SQLITE_FUNC_ANYORDER ), 002589 WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, 002590 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), 002591 WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, 002592 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), 002593 002594 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 002595 #ifdef SQLITE_CASE_SENSITIVE_LIKE 002596 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 002597 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 002598 #else 002599 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), 002600 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), 002601 #endif 002602 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 002603 FUNCTION(unknown, -1, 0, 0, unknownFunc ), 002604 #endif 002605 FUNCTION(coalesce, 1, 0, 0, 0 ), 002606 FUNCTION(coalesce, 0, 0, 0, 0 ), 002607 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS 002608 MFUNCTION(ceil, 1, xCeil, ceilingFunc ), 002609 MFUNCTION(ceiling, 1, xCeil, ceilingFunc ), 002610 MFUNCTION(floor, 1, xFloor, ceilingFunc ), 002611 #if SQLITE_HAVE_C99_MATH_FUNCS 002612 MFUNCTION(trunc, 1, trunc, ceilingFunc ), 002613 #endif 002614 FUNCTION(ln, 1, 0, 0, logFunc ), 002615 FUNCTION(log, 1, 1, 0, logFunc ), 002616 FUNCTION(log10, 1, 1, 0, logFunc ), 002617 FUNCTION(log2, 1, 2, 0, logFunc ), 002618 FUNCTION(log, 2, 0, 0, logFunc ), 002619 MFUNCTION(exp, 1, exp, math1Func ), 002620 MFUNCTION(pow, 2, pow, math2Func ), 002621 MFUNCTION(power, 2, pow, math2Func ), 002622 MFUNCTION(mod, 2, fmod, math2Func ), 002623 MFUNCTION(acos, 1, acos, math1Func ), 002624 MFUNCTION(asin, 1, asin, math1Func ), 002625 MFUNCTION(atan, 1, atan, math1Func ), 002626 MFUNCTION(atan2, 2, atan2, math2Func ), 002627 MFUNCTION(cos, 1, cos, math1Func ), 002628 MFUNCTION(sin, 1, sin, math1Func ), 002629 MFUNCTION(tan, 1, tan, math1Func ), 002630 MFUNCTION(cosh, 1, cosh, math1Func ), 002631 MFUNCTION(sinh, 1, sinh, math1Func ), 002632 MFUNCTION(tanh, 1, tanh, math1Func ), 002633 #if SQLITE_HAVE_C99_MATH_FUNCS 002634 MFUNCTION(acosh, 1, acosh, math1Func ), 002635 MFUNCTION(asinh, 1, asinh, math1Func ), 002636 MFUNCTION(atanh, 1, atanh, math1Func ), 002637 #endif 002638 MFUNCTION(sqrt, 1, sqrt, math1Func ), 002639 MFUNCTION(radians, 1, degToRad, math1Func ), 002640 MFUNCTION(degrees, 1, radToDeg, math1Func ), 002641 FUNCTION(pi, 0, 0, 0, piFunc ), 002642 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */ 002643 FUNCTION(sign, 1, 0, 0, signFunc ), 002644 INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ), 002645 INLINE_FUNC(iif, 3, INLINEFUNC_iif, 0 ), 002646 }; 002647 #ifndef SQLITE_OMIT_ALTERTABLE 002648 sqlite3AlterFunctions(); 002649 #endif 002650 sqlite3WindowFunctions(); 002651 sqlite3RegisterDateTimeFunctions(); 002652 sqlite3RegisterJsonFunctions(); 002653 sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); 002654 002655 #if 0 /* Enable to print out how the built-in functions are hashed */ 002656 { 002657 int i; 002658 FuncDef *p; 002659 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ 002660 printf("FUNC-HASH %02d:", i); 002661 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){ 002662 int n = sqlite3Strlen30(p->zName); 002663 int h = p->zName[0] + n; 002664 assert( p->funcFlags & SQLITE_FUNC_BUILTIN ); 002665 printf(" %s(%d)", p->zName, h); 002666 } 002667 printf("\n"); 002668 } 002669 } 002670 #endif 002671 }