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 #include <math.h> 000020 #include "vdbeInt.h" 000021 000022 /* 000023 ** Return the collating function associated with a function. 000024 */ 000025 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ 000026 VdbeOp *pOp; 000027 assert( context->pVdbe!=0 ); 000028 pOp = &context->pVdbe->aOp[context->iOp-1]; 000029 assert( pOp->opcode==OP_CollSeq ); 000030 assert( pOp->p4type==P4_COLLSEQ ); 000031 return pOp->p4.pColl; 000032 } 000033 000034 /* 000035 ** Indicate that the accumulator load should be skipped on this 000036 ** iteration of the aggregate loop. 000037 */ 000038 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ 000039 assert( context->isError<=0 ); 000040 context->isError = -1; 000041 context->skipFlag = 1; 000042 } 000043 000044 /* 000045 ** Implementation of the non-aggregate min() and max() functions 000046 */ 000047 static void minmaxFunc( 000048 sqlite3_context *context, 000049 int argc, 000050 sqlite3_value **argv 000051 ){ 000052 int i; 000053 int mask; /* 0 for min() or 0xffffffff for max() */ 000054 int iBest; 000055 CollSeq *pColl; 000056 000057 assert( argc>1 ); 000058 mask = sqlite3_user_data(context)==0 ? 0 : -1; 000059 pColl = sqlite3GetFuncCollSeq(context); 000060 assert( pColl ); 000061 assert( mask==-1 || mask==0 ); 000062 iBest = 0; 000063 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 000064 for(i=1; i<argc; i++){ 000065 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return; 000066 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){ 000067 testcase( mask==0 ); 000068 iBest = i; 000069 } 000070 } 000071 sqlite3_result_value(context, argv[iBest]); 000072 } 000073 000074 /* 000075 ** Return the type of the argument. 000076 */ 000077 static void typeofFunc( 000078 sqlite3_context *context, 000079 int NotUsed, 000080 sqlite3_value **argv 000081 ){ 000082 static const char *azType[] = { "integer", "real", "text", "blob", "null" }; 000083 int i = sqlite3_value_type(argv[0]) - 1; 000084 UNUSED_PARAMETER(NotUsed); 000085 assert( i>=0 && i<ArraySize(azType) ); 000086 assert( SQLITE_INTEGER==1 ); 000087 assert( SQLITE_FLOAT==2 ); 000088 assert( SQLITE_TEXT==3 ); 000089 assert( SQLITE_BLOB==4 ); 000090 assert( SQLITE_NULL==5 ); 000091 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns 000092 ** the datatype code for the initial datatype of the sqlite3_value object 000093 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT, 000094 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */ 000095 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC); 000096 } 000097 000098 000099 /* 000100 ** Implementation of the length() function 000101 */ 000102 static void lengthFunc( 000103 sqlite3_context *context, 000104 int argc, 000105 sqlite3_value **argv 000106 ){ 000107 assert( argc==1 ); 000108 UNUSED_PARAMETER(argc); 000109 switch( sqlite3_value_type(argv[0]) ){ 000110 case SQLITE_BLOB: 000111 case SQLITE_INTEGER: 000112 case SQLITE_FLOAT: { 000113 sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); 000114 break; 000115 } 000116 case SQLITE_TEXT: { 000117 const unsigned char *z = sqlite3_value_text(argv[0]); 000118 const unsigned char *z0; 000119 unsigned char c; 000120 if( z==0 ) return; 000121 z0 = z; 000122 while( (c = *z)!=0 ){ 000123 z++; 000124 if( c>=0xc0 ){ 000125 while( (*z & 0xc0)==0x80 ){ z++; z0++; } 000126 } 000127 } 000128 sqlite3_result_int(context, (int)(z-z0)); 000129 break; 000130 } 000131 default: { 000132 sqlite3_result_null(context); 000133 break; 000134 } 000135 } 000136 } 000137 000138 /* 000139 ** Implementation of the abs() function. 000140 ** 000141 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of 000142 ** the numeric argument X. 000143 */ 000144 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000145 assert( argc==1 ); 000146 UNUSED_PARAMETER(argc); 000147 switch( sqlite3_value_type(argv[0]) ){ 000148 case SQLITE_INTEGER: { 000149 i64 iVal = sqlite3_value_int64(argv[0]); 000150 if( iVal<0 ){ 000151 if( iVal==SMALLEST_INT64 ){ 000152 /* IMP: R-31676-45509 If X is the integer -9223372036854775808 000153 ** then abs(X) throws an integer overflow error since there is no 000154 ** equivalent positive 64-bit two complement value. */ 000155 sqlite3_result_error(context, "integer overflow", -1); 000156 return; 000157 } 000158 iVal = -iVal; 000159 } 000160 sqlite3_result_int64(context, iVal); 000161 break; 000162 } 000163 case SQLITE_NULL: { 000164 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ 000165 sqlite3_result_null(context); 000166 break; 000167 } 000168 default: { 000169 /* Because sqlite3_value_double() returns 0.0 if the argument is not 000170 ** something that can be converted into a number, we have: 000171 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob 000172 ** that cannot be converted to a numeric value. 000173 */ 000174 double rVal = sqlite3_value_double(argv[0]); 000175 if( rVal<0 ) rVal = -rVal; 000176 sqlite3_result_double(context, rVal); 000177 break; 000178 } 000179 } 000180 } 000181 000182 /* 000183 ** Implementation of the instr() function. 000184 ** 000185 ** instr(haystack,needle) finds the first occurrence of needle 000186 ** in haystack and returns the number of previous characters plus 1, 000187 ** or 0 if needle does not occur within haystack. 000188 ** 000189 ** If both haystack and needle are BLOBs, then the result is one more than 000190 ** the number of bytes in haystack prior to the first occurrence of needle, 000191 ** or 0 if needle never occurs in haystack. 000192 */ 000193 static void instrFunc( 000194 sqlite3_context *context, 000195 int argc, 000196 sqlite3_value **argv 000197 ){ 000198 const unsigned char *zHaystack; 000199 const unsigned char *zNeedle; 000200 int nHaystack; 000201 int nNeedle; 000202 int typeHaystack, typeNeedle; 000203 int N = 1; 000204 int isText; 000205 unsigned char firstChar; 000206 sqlite3_value *pC1 = 0; 000207 sqlite3_value *pC2 = 0; 000208 000209 UNUSED_PARAMETER(argc); 000210 typeHaystack = sqlite3_value_type(argv[0]); 000211 typeNeedle = sqlite3_value_type(argv[1]); 000212 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; 000213 nHaystack = sqlite3_value_bytes(argv[0]); 000214 nNeedle = sqlite3_value_bytes(argv[1]); 000215 if( nNeedle>0 ){ 000216 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ 000217 zHaystack = sqlite3_value_blob(argv[0]); 000218 zNeedle = sqlite3_value_blob(argv[1]); 000219 isText = 0; 000220 }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){ 000221 zHaystack = sqlite3_value_text(argv[0]); 000222 zNeedle = sqlite3_value_text(argv[1]); 000223 isText = 1; 000224 }else{ 000225 pC1 = sqlite3_value_dup(argv[0]); 000226 zHaystack = sqlite3_value_text(pC1); 000227 if( zHaystack==0 ) goto endInstrOOM; 000228 nHaystack = sqlite3_value_bytes(pC1); 000229 pC2 = sqlite3_value_dup(argv[1]); 000230 zNeedle = sqlite3_value_text(pC2); 000231 if( zNeedle==0 ) goto endInstrOOM; 000232 nNeedle = sqlite3_value_bytes(pC2); 000233 isText = 1; 000234 } 000235 if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM; 000236 firstChar = zNeedle[0]; 000237 while( nNeedle<=nHaystack 000238 && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0) 000239 ){ 000240 N++; 000241 do{ 000242 nHaystack--; 000243 zHaystack++; 000244 }while( isText && (zHaystack[0]&0xc0)==0x80 ); 000245 } 000246 if( nNeedle>nHaystack ) N = 0; 000247 } 000248 sqlite3_result_int(context, N); 000249 endInstr: 000250 sqlite3_value_free(pC1); 000251 sqlite3_value_free(pC2); 000252 return; 000253 endInstrOOM: 000254 sqlite3_result_error_nomem(context); 000255 goto endInstr; 000256 } 000257 000258 /* 000259 ** Implementation of the printf() function. 000260 */ 000261 static void printfFunc( 000262 sqlite3_context *context, 000263 int argc, 000264 sqlite3_value **argv 000265 ){ 000266 PrintfArguments x; 000267 StrAccum str; 000268 const char *zFormat; 000269 int n; 000270 sqlite3 *db = sqlite3_context_db_handle(context); 000271 000272 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 000273 x.nArg = argc-1; 000274 x.nUsed = 0; 000275 x.apArg = argv+1; 000276 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); 000277 str.printfFlags = SQLITE_PRINTF_SQLFUNC; 000278 sqlite3_str_appendf(&str, zFormat, &x); 000279 n = str.nChar; 000280 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, 000281 SQLITE_DYNAMIC); 000282 } 000283 } 000284 000285 /* 000286 ** Implementation of the substr() function. 000287 ** 000288 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. 000289 ** p1 is 1-indexed. So substr(x,1,1) returns the first character 000290 ** of x. If x is text, then we actually count UTF-8 characters. 000291 ** If x is a blob, then we count bytes. 000292 ** 000293 ** If p1 is negative, then we begin abs(p1) from the end of x[]. 000294 ** 000295 ** If p2 is negative, return the p2 characters preceding p1. 000296 */ 000297 static void substrFunc( 000298 sqlite3_context *context, 000299 int argc, 000300 sqlite3_value **argv 000301 ){ 000302 const unsigned char *z; 000303 const unsigned char *z2; 000304 int len; 000305 int p0type; 000306 i64 p1, p2; 000307 int negP2 = 0; 000308 000309 assert( argc==3 || argc==2 ); 000310 if( sqlite3_value_type(argv[1])==SQLITE_NULL 000311 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) 000312 ){ 000313 return; 000314 } 000315 p0type = sqlite3_value_type(argv[0]); 000316 p1 = sqlite3_value_int(argv[1]); 000317 if( p0type==SQLITE_BLOB ){ 000318 len = sqlite3_value_bytes(argv[0]); 000319 z = sqlite3_value_blob(argv[0]); 000320 if( z==0 ) return; 000321 assert( len==sqlite3_value_bytes(argv[0]) ); 000322 }else{ 000323 z = sqlite3_value_text(argv[0]); 000324 if( z==0 ) return; 000325 len = 0; 000326 if( p1<0 ){ 000327 for(z2=z; *z2; len++){ 000328 SQLITE_SKIP_UTF8(z2); 000329 } 000330 } 000331 } 000332 #ifdef SQLITE_SUBSTR_COMPATIBILITY 000333 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as 000334 ** as substr(X,1,N) - it returns the first N characters of X. This 000335 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] 000336 ** from 2009-02-02 for compatibility of applications that exploited the 000337 ** old buggy behavior. */ 000338 if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */ 000339 #endif 000340 if( argc==3 ){ 000341 p2 = sqlite3_value_int(argv[2]); 000342 if( p2<0 ){ 000343 p2 = -p2; 000344 negP2 = 1; 000345 } 000346 }else{ 000347 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; 000348 } 000349 if( p1<0 ){ 000350 p1 += len; 000351 if( p1<0 ){ 000352 p2 += p1; 000353 if( p2<0 ) p2 = 0; 000354 p1 = 0; 000355 } 000356 }else if( p1>0 ){ 000357 p1--; 000358 }else if( p2>0 ){ 000359 p2--; 000360 } 000361 if( negP2 ){ 000362 p1 -= p2; 000363 if( p1<0 ){ 000364 p2 += p1; 000365 p1 = 0; 000366 } 000367 } 000368 assert( p1>=0 && p2>=0 ); 000369 if( p0type!=SQLITE_BLOB ){ 000370 while( *z && p1 ){ 000371 SQLITE_SKIP_UTF8(z); 000372 p1--; 000373 } 000374 for(z2=z; *z2 && p2; p2--){ 000375 SQLITE_SKIP_UTF8(z2); 000376 } 000377 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, 000378 SQLITE_UTF8); 000379 }else{ 000380 if( p1+p2>len ){ 000381 p2 = len-p1; 000382 if( p2<0 ) p2 = 0; 000383 } 000384 sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); 000385 } 000386 } 000387 000388 /* 000389 ** Implementation of the round() function 000390 */ 000391 #ifndef SQLITE_OMIT_FLOATING_POINT 000392 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000393 int n = 0; 000394 double r; 000395 char *zBuf; 000396 assert( argc==1 || argc==2 ); 000397 if( argc==2 ){ 000398 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; 000399 n = sqlite3_value_int(argv[1]); 000400 if( n>30 ) n = 30; 000401 if( n<0 ) n = 0; 000402 } 000403 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 000404 r = sqlite3_value_double(argv[0]); 000405 /* If Y==0 and X will fit in a 64-bit int, 000406 ** handle the rounding directly, 000407 ** otherwise use printf. 000408 */ 000409 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){ 000410 /* The value has no fractional part so there is nothing to round */ 000411 }else if( n==0 ){ 000412 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5))); 000413 }else{ 000414 zBuf = sqlite3_mprintf("%.*f",n,r); 000415 if( zBuf==0 ){ 000416 sqlite3_result_error_nomem(context); 000417 return; 000418 } 000419 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); 000420 sqlite3_free(zBuf); 000421 } 000422 sqlite3_result_double(context, r); 000423 } 000424 #endif 000425 000426 /* 000427 ** Allocate nByte bytes of space using sqlite3Malloc(). If the 000428 ** allocation fails, call sqlite3_result_error_nomem() to notify 000429 ** the database handle that malloc() has failed and return NULL. 000430 ** If nByte is larger than the maximum string or blob length, then 000431 ** raise an SQLITE_TOOBIG exception and return NULL. 000432 */ 000433 static void *contextMalloc(sqlite3_context *context, i64 nByte){ 000434 char *z; 000435 sqlite3 *db = sqlite3_context_db_handle(context); 000436 assert( nByte>0 ); 000437 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); 000438 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); 000439 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 000440 sqlite3_result_error_toobig(context); 000441 z = 0; 000442 }else{ 000443 z = sqlite3Malloc(nByte); 000444 if( !z ){ 000445 sqlite3_result_error_nomem(context); 000446 } 000447 } 000448 return z; 000449 } 000450 000451 /* 000452 ** Implementation of the upper() and lower() SQL functions. 000453 */ 000454 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000455 char *z1; 000456 const char *z2; 000457 int i, n; 000458 UNUSED_PARAMETER(argc); 000459 z2 = (char*)sqlite3_value_text(argv[0]); 000460 n = sqlite3_value_bytes(argv[0]); 000461 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 000462 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 000463 if( z2 ){ 000464 z1 = contextMalloc(context, ((i64)n)+1); 000465 if( z1 ){ 000466 for(i=0; i<n; i++){ 000467 z1[i] = (char)sqlite3Toupper(z2[i]); 000468 } 000469 sqlite3_result_text(context, z1, n, sqlite3_free); 000470 } 000471 } 000472 } 000473 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 000474 char *z1; 000475 const char *z2; 000476 int i, n; 000477 UNUSED_PARAMETER(argc); 000478 z2 = (char*)sqlite3_value_text(argv[0]); 000479 n = sqlite3_value_bytes(argv[0]); 000480 /* Verify that the call to _bytes() does not invalidate the _text() pointer */ 000481 assert( z2==(char*)sqlite3_value_text(argv[0]) ); 000482 if( z2 ){ 000483 z1 = contextMalloc(context, ((i64)n)+1); 000484 if( z1 ){ 000485 for(i=0; i<n; i++){ 000486 z1[i] = sqlite3Tolower(z2[i]); 000487 } 000488 sqlite3_result_text(context, z1, n, sqlite3_free); 000489 } 000490 } 000491 } 000492 000493 /* 000494 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented 000495 ** as VDBE code so that unused argument values do not have to be computed. 000496 ** However, we still need some kind of function implementation for this 000497 ** routines in the function table. The noopFunc macro provides this. 000498 ** noopFunc will never be called so it doesn't matter what the implementation 000499 ** is. We might as well use the "version()" function as a substitute. 000500 */ 000501 #define noopFunc versionFunc /* Substitute function - never called */ 000502 000503 /* 000504 ** Implementation of random(). Return a random integer. 000505 */ 000506 static void randomFunc( 000507 sqlite3_context *context, 000508 int NotUsed, 000509 sqlite3_value **NotUsed2 000510 ){ 000511 sqlite_int64 r; 000512 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000513 sqlite3_randomness(sizeof(r), &r); 000514 if( r<0 ){ 000515 /* We need to prevent a random number of 0x8000000000000000 000516 ** (or -9223372036854775808) since when you do abs() of that 000517 ** number of you get the same value back again. To do this 000518 ** in a way that is testable, mask the sign bit off of negative 000519 ** values, resulting in a positive value. Then take the 000520 ** 2s complement of that positive value. The end result can 000521 ** therefore be no less than -9223372036854775807. 000522 */ 000523 r = -(r & LARGEST_INT64); 000524 } 000525 sqlite3_result_int64(context, r); 000526 } 000527 000528 /* 000529 ** Implementation of randomblob(N). Return a random blob 000530 ** that is N bytes long. 000531 */ 000532 static void randomBlob( 000533 sqlite3_context *context, 000534 int argc, 000535 sqlite3_value **argv 000536 ){ 000537 sqlite3_int64 n; 000538 unsigned char *p; 000539 assert( argc==1 ); 000540 UNUSED_PARAMETER(argc); 000541 n = sqlite3_value_int64(argv[0]); 000542 if( n<1 ){ 000543 n = 1; 000544 } 000545 p = contextMalloc(context, n); 000546 if( p ){ 000547 sqlite3_randomness(n, p); 000548 sqlite3_result_blob(context, (char*)p, n, sqlite3_free); 000549 } 000550 } 000551 000552 /* 000553 ** Implementation of the last_insert_rowid() SQL function. The return 000554 ** value is the same as the sqlite3_last_insert_rowid() API function. 000555 */ 000556 static void last_insert_rowid( 000557 sqlite3_context *context, 000558 int NotUsed, 000559 sqlite3_value **NotUsed2 000560 ){ 000561 sqlite3 *db = sqlite3_context_db_handle(context); 000562 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000563 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a 000564 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface 000565 ** function. */ 000566 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db)); 000567 } 000568 000569 /* 000570 ** Implementation of the changes() SQL function. 000571 ** 000572 ** IMP: R-62073-11209 The changes() SQL function is a wrapper 000573 ** around the sqlite3_changes() C/C++ function and hence follows the same 000574 ** rules for counting changes. 000575 */ 000576 static void changes( 000577 sqlite3_context *context, 000578 int NotUsed, 000579 sqlite3_value **NotUsed2 000580 ){ 000581 sqlite3 *db = sqlite3_context_db_handle(context); 000582 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000583 sqlite3_result_int(context, sqlite3_changes(db)); 000584 } 000585 000586 /* 000587 ** Implementation of the total_changes() SQL function. The return value is 000588 ** the same as the sqlite3_total_changes() API function. 000589 */ 000590 static void total_changes( 000591 sqlite3_context *context, 000592 int NotUsed, 000593 sqlite3_value **NotUsed2 000594 ){ 000595 sqlite3 *db = sqlite3_context_db_handle(context); 000596 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000597 /* IMP: R-52756-41993 This function is a wrapper around the 000598 ** sqlite3_total_changes() C/C++ interface. */ 000599 sqlite3_result_int(context, sqlite3_total_changes(db)); 000600 } 000601 000602 /* 000603 ** A structure defining how to do GLOB-style comparisons. 000604 */ 000605 struct compareInfo { 000606 u8 matchAll; /* "*" or "%" */ 000607 u8 matchOne; /* "?" or "_" */ 000608 u8 matchSet; /* "[" or 0 */ 000609 u8 noCase; /* true to ignore case differences */ 000610 }; 000611 000612 /* 000613 ** For LIKE and GLOB matching on EBCDIC machines, assume that every 000614 ** character is exactly one byte in size. Also, provde the Utf8Read() 000615 ** macro for fast reading of the next character in the common case where 000616 ** the next character is ASCII. 000617 */ 000618 #if defined(SQLITE_EBCDIC) 000619 # define sqlite3Utf8Read(A) (*((*A)++)) 000620 # define Utf8Read(A) (*(A++)) 000621 #else 000622 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A)) 000623 #endif 000624 000625 static const struct compareInfo globInfo = { '*', '?', '[', 0 }; 000626 /* The correct SQL-92 behavior is for the LIKE operator to ignore 000627 ** case. Thus 'a' LIKE 'A' would be true. */ 000628 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 }; 000629 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator 000630 ** is case sensitive causing 'a' LIKE 'A' to be false */ 000631 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 }; 000632 000633 /* 000634 ** Possible error returns from patternMatch() 000635 */ 000636 #define SQLITE_MATCH 0 000637 #define SQLITE_NOMATCH 1 000638 #define SQLITE_NOWILDCARDMATCH 2 000639 000640 /* 000641 ** Compare two UTF-8 strings for equality where the first string is 000642 ** a GLOB or LIKE expression. Return values: 000643 ** 000644 ** SQLITE_MATCH: Match 000645 ** SQLITE_NOMATCH: No match 000646 ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards. 000647 ** 000648 ** Globbing rules: 000649 ** 000650 ** '*' Matches any sequence of zero or more characters. 000651 ** 000652 ** '?' Matches exactly one character. 000653 ** 000654 ** [...] Matches one character from the enclosed list of 000655 ** characters. 000656 ** 000657 ** [^...] Matches one character not in the enclosed list. 000658 ** 000659 ** With the [...] and [^...] matching, a ']' character can be included 000660 ** in the list by making it the first character after '[' or '^'. A 000661 ** range of characters can be specified using '-'. Example: 000662 ** "[a-z]" matches any single lower-case letter. To match a '-', make 000663 ** it the last character in the list. 000664 ** 000665 ** Like matching rules: 000666 ** 000667 ** '%' Matches any sequence of zero or more characters 000668 ** 000669 *** '_' Matches any one character 000670 ** 000671 ** Ec Where E is the "esc" character and c is any other 000672 ** character, including '%', '_', and esc, match exactly c. 000673 ** 000674 ** The comments within this routine usually assume glob matching. 000675 ** 000676 ** This routine is usually quick, but can be N**2 in the worst case. 000677 */ 000678 static int patternCompare( 000679 const u8 *zPattern, /* The glob pattern */ 000680 const u8 *zString, /* The string to compare against the glob */ 000681 const struct compareInfo *pInfo, /* Information about how to do the compare */ 000682 u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */ 000683 ){ 000684 u32 c, c2; /* Next pattern and input string chars */ 000685 u32 matchOne = pInfo->matchOne; /* "?" or "_" */ 000686 u32 matchAll = pInfo->matchAll; /* "*" or "%" */ 000687 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ 000688 const u8 *zEscaped = 0; /* One past the last escaped input char */ 000689 000690 while( (c = Utf8Read(zPattern))!=0 ){ 000691 if( c==matchAll ){ /* Match "*" */ 000692 /* Skip over multiple "*" characters in the pattern. If there 000693 ** are also "?" characters, skip those as well, but consume a 000694 ** single character of the input string for each "?" skipped */ 000695 while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){ 000696 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ 000697 return SQLITE_NOWILDCARDMATCH; 000698 } 000699 } 000700 if( c==0 ){ 000701 return SQLITE_MATCH; /* "*" at the end of the pattern matches */ 000702 }else if( c==matchOther ){ 000703 if( pInfo->matchSet==0 ){ 000704 c = sqlite3Utf8Read(&zPattern); 000705 if( c==0 ) return SQLITE_NOWILDCARDMATCH; 000706 }else{ 000707 /* "[...]" immediately follows the "*". We have to do a slow 000708 ** recursive search in this case, but it is an unusual case. */ 000709 assert( matchOther<0x80 ); /* '[' is a single-byte character */ 000710 while( *zString ){ 000711 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); 000712 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 000713 SQLITE_SKIP_UTF8(zString); 000714 } 000715 return SQLITE_NOWILDCARDMATCH; 000716 } 000717 } 000718 000719 /* At this point variable c contains the first character of the 000720 ** pattern string past the "*". Search in the input string for the 000721 ** first matching character and recursively continue the match from 000722 ** that point. 000723 ** 000724 ** For a case-insensitive search, set variable cx to be the same as 000725 ** c but in the other case and search the input string for either 000726 ** c or cx. 000727 */ 000728 if( c<=0x80 ){ 000729 char zStop[3]; 000730 int bMatch; 000731 if( noCase ){ 000732 zStop[0] = sqlite3Toupper(c); 000733 zStop[1] = sqlite3Tolower(c); 000734 zStop[2] = 0; 000735 }else{ 000736 zStop[0] = c; 000737 zStop[1] = 0; 000738 } 000739 while(1){ 000740 zString += strcspn((const char*)zString, zStop); 000741 if( zString[0]==0 ) break; 000742 zString++; 000743 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 000744 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 000745 } 000746 }else{ 000747 int bMatch; 000748 while( (c2 = Utf8Read(zString))!=0 ){ 000749 if( c2!=c ) continue; 000750 bMatch = patternCompare(zPattern,zString,pInfo,matchOther); 000751 if( bMatch!=SQLITE_NOMATCH ) return bMatch; 000752 } 000753 } 000754 return SQLITE_NOWILDCARDMATCH; 000755 } 000756 if( c==matchOther ){ 000757 if( pInfo->matchSet==0 ){ 000758 c = sqlite3Utf8Read(&zPattern); 000759 if( c==0 ) return SQLITE_NOMATCH; 000760 zEscaped = zPattern; 000761 }else{ 000762 u32 prior_c = 0; 000763 int seen = 0; 000764 int invert = 0; 000765 c = sqlite3Utf8Read(&zString); 000766 if( c==0 ) return SQLITE_NOMATCH; 000767 c2 = sqlite3Utf8Read(&zPattern); 000768 if( c2=='^' ){ 000769 invert = 1; 000770 c2 = sqlite3Utf8Read(&zPattern); 000771 } 000772 if( c2==']' ){ 000773 if( c==']' ) seen = 1; 000774 c2 = sqlite3Utf8Read(&zPattern); 000775 } 000776 while( c2 && c2!=']' ){ 000777 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ 000778 c2 = sqlite3Utf8Read(&zPattern); 000779 if( c>=prior_c && c<=c2 ) seen = 1; 000780 prior_c = 0; 000781 }else{ 000782 if( c==c2 ){ 000783 seen = 1; 000784 } 000785 prior_c = c2; 000786 } 000787 c2 = sqlite3Utf8Read(&zPattern); 000788 } 000789 if( c2==0 || (seen ^ invert)==0 ){ 000790 return SQLITE_NOMATCH; 000791 } 000792 continue; 000793 } 000794 } 000795 c2 = Utf8Read(zString); 000796 if( c==c2 ) continue; 000797 if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ 000798 continue; 000799 } 000800 if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; 000801 return SQLITE_NOMATCH; 000802 } 000803 return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; 000804 } 000805 000806 /* 000807 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and 000808 ** non-zero if there is no match. 000809 */ 000810 int sqlite3_strglob(const char *zGlobPattern, const char *zString){ 000811 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); 000812 } 000813 000814 /* 000815 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for 000816 ** a miss - like strcmp(). 000817 */ 000818 int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ 000819 return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); 000820 } 000821 000822 /* 000823 ** Count the number of times that the LIKE operator (or GLOB which is 000824 ** just a variation of LIKE) gets called. This is used for testing 000825 ** only. 000826 */ 000827 #ifdef SQLITE_TEST 000828 int sqlite3_like_count = 0; 000829 #endif 000830 000831 000832 /* 000833 ** Implementation of the like() SQL function. This function implements 000834 ** the build-in LIKE operator. The first argument to the function is the 000835 ** pattern and the second argument is the string. So, the SQL statements: 000836 ** 000837 ** A LIKE B 000838 ** 000839 ** is implemented as like(B,A). 000840 ** 000841 ** This same function (with a different compareInfo structure) computes 000842 ** the GLOB operator. 000843 */ 000844 static void likeFunc( 000845 sqlite3_context *context, 000846 int argc, 000847 sqlite3_value **argv 000848 ){ 000849 const unsigned char *zA, *zB; 000850 u32 escape; 000851 int nPat; 000852 sqlite3 *db = sqlite3_context_db_handle(context); 000853 struct compareInfo *pInfo = sqlite3_user_data(context); 000854 000855 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 000856 if( sqlite3_value_type(argv[0])==SQLITE_BLOB 000857 || sqlite3_value_type(argv[1])==SQLITE_BLOB 000858 ){ 000859 #ifdef SQLITE_TEST 000860 sqlite3_like_count++; 000861 #endif 000862 sqlite3_result_int(context, 0); 000863 return; 000864 } 000865 #endif 000866 000867 /* Limit the length of the LIKE or GLOB pattern to avoid problems 000868 ** of deep recursion and N*N behavior in patternCompare(). 000869 */ 000870 nPat = sqlite3_value_bytes(argv[0]); 000871 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); 000872 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); 000873 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ 000874 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); 000875 return; 000876 } 000877 if( argc==3 ){ 000878 /* The escape character string must consist of a single UTF-8 character. 000879 ** Otherwise, return an error. 000880 */ 000881 const unsigned char *zEsc = sqlite3_value_text(argv[2]); 000882 if( zEsc==0 ) return; 000883 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ 000884 sqlite3_result_error(context, 000885 "ESCAPE expression must be a single character", -1); 000886 return; 000887 } 000888 escape = sqlite3Utf8Read(&zEsc); 000889 }else{ 000890 escape = pInfo->matchSet; 000891 } 000892 zB = sqlite3_value_text(argv[0]); 000893 zA = sqlite3_value_text(argv[1]); 000894 if( zA && zB ){ 000895 #ifdef SQLITE_TEST 000896 sqlite3_like_count++; 000897 #endif 000898 sqlite3_result_int(context, 000899 patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); 000900 } 000901 } 000902 000903 /* 000904 ** Implementation of the NULLIF(x,y) function. The result is the first 000905 ** argument if the arguments are different. The result is NULL if the 000906 ** arguments are equal to each other. 000907 */ 000908 static void nullifFunc( 000909 sqlite3_context *context, 000910 int NotUsed, 000911 sqlite3_value **argv 000912 ){ 000913 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 000914 UNUSED_PARAMETER(NotUsed); 000915 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ 000916 sqlite3_result_value(context, argv[0]); 000917 } 000918 } 000919 000920 /* 000921 ** Implementation of the sqlite_version() function. The result is the version 000922 ** of the SQLite library that is running. 000923 */ 000924 static void versionFunc( 000925 sqlite3_context *context, 000926 int NotUsed, 000927 sqlite3_value **NotUsed2 000928 ){ 000929 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000930 /* IMP: R-48699-48617 This function is an SQL wrapper around the 000931 ** sqlite3_libversion() C-interface. */ 000932 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); 000933 } 000934 000935 /* 000936 ** Implementation of the sqlite_source_id() function. The result is a string 000937 ** that identifies the particular version of the source code used to build 000938 ** SQLite. 000939 */ 000940 static void sourceidFunc( 000941 sqlite3_context *context, 000942 int NotUsed, 000943 sqlite3_value **NotUsed2 000944 ){ 000945 UNUSED_PARAMETER2(NotUsed, NotUsed2); 000946 /* IMP: R-24470-31136 This function is an SQL wrapper around the 000947 ** sqlite3_sourceid() C interface. */ 000948 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); 000949 } 000950 000951 /* 000952 ** Implementation of the sqlite_log() function. This is a wrapper around 000953 ** sqlite3_log(). The return value is NULL. The function exists purely for 000954 ** its side-effects. 000955 */ 000956 static void errlogFunc( 000957 sqlite3_context *context, 000958 int argc, 000959 sqlite3_value **argv 000960 ){ 000961 UNUSED_PARAMETER(argc); 000962 UNUSED_PARAMETER(context); 000963 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); 000964 } 000965 000966 /* 000967 ** Implementation of the sqlite_compileoption_used() function. 000968 ** The result is an integer that identifies if the compiler option 000969 ** was used to build SQLite. 000970 */ 000971 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 000972 static void compileoptionusedFunc( 000973 sqlite3_context *context, 000974 int argc, 000975 sqlite3_value **argv 000976 ){ 000977 const char *zOptName; 000978 assert( argc==1 ); 000979 UNUSED_PARAMETER(argc); 000980 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL 000981 ** function is a wrapper around the sqlite3_compileoption_used() C/C++ 000982 ** function. 000983 */ 000984 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ 000985 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); 000986 } 000987 } 000988 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 000989 000990 /* 000991 ** Implementation of the sqlite_compileoption_get() function. 000992 ** The result is a string that identifies the compiler options 000993 ** used to build SQLite. 000994 */ 000995 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 000996 static void compileoptiongetFunc( 000997 sqlite3_context *context, 000998 int argc, 000999 sqlite3_value **argv 001000 ){ 001001 int n; 001002 assert( argc==1 ); 001003 UNUSED_PARAMETER(argc); 001004 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function 001005 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. 001006 */ 001007 n = sqlite3_value_int(argv[0]); 001008 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); 001009 } 001010 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 001011 001012 /* Array for converting from half-bytes (nybbles) into ASCII hex 001013 ** digits. */ 001014 static const char hexdigits[] = { 001015 '0', '1', '2', '3', '4', '5', '6', '7', 001016 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 001017 }; 001018 001019 /* 001020 ** Implementation of the QUOTE() function. This function takes a single 001021 ** argument. If the argument is numeric, the return value is the same as 001022 ** the argument. If the argument is NULL, the return value is the string 001023 ** "NULL". Otherwise, the argument is enclosed in single quotes with 001024 ** single-quote escapes. 001025 */ 001026 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ 001027 assert( argc==1 ); 001028 UNUSED_PARAMETER(argc); 001029 switch( sqlite3_value_type(argv[0]) ){ 001030 case SQLITE_FLOAT: { 001031 double r1, r2; 001032 char zBuf[50]; 001033 r1 = sqlite3_value_double(argv[0]); 001034 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); 001035 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); 001036 if( r1!=r2 ){ 001037 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); 001038 } 001039 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); 001040 break; 001041 } 001042 case SQLITE_INTEGER: { 001043 sqlite3_result_value(context, argv[0]); 001044 break; 001045 } 001046 case SQLITE_BLOB: { 001047 char *zText = 0; 001048 char const *zBlob = sqlite3_value_blob(argv[0]); 001049 int nBlob = sqlite3_value_bytes(argv[0]); 001050 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ 001051 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 001052 if( zText ){ 001053 int i; 001054 for(i=0; i<nBlob; i++){ 001055 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F]; 001056 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; 001057 } 001058 zText[(nBlob*2)+2] = '\''; 001059 zText[(nBlob*2)+3] = '\0'; 001060 zText[0] = 'X'; 001061 zText[1] = '\''; 001062 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); 001063 sqlite3_free(zText); 001064 } 001065 break; 001066 } 001067 case SQLITE_TEXT: { 001068 int i,j; 001069 u64 n; 001070 const unsigned char *zArg = sqlite3_value_text(argv[0]); 001071 char *z; 001072 001073 if( zArg==0 ) return; 001074 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } 001075 z = contextMalloc(context, ((i64)i)+((i64)n)+3); 001076 if( z ){ 001077 z[0] = '\''; 001078 for(i=0, j=1; zArg[i]; i++){ 001079 z[j++] = zArg[i]; 001080 if( zArg[i]=='\'' ){ 001081 z[j++] = '\''; 001082 } 001083 } 001084 z[j++] = '\''; 001085 z[j] = 0; 001086 sqlite3_result_text(context, z, j, sqlite3_free); 001087 } 001088 break; 001089 } 001090 default: { 001091 assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); 001092 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); 001093 break; 001094 } 001095 } 001096 } 001097 001098 /* 001099 ** The unicode() function. Return the integer unicode code-point value 001100 ** for the first character of the input string. 001101 */ 001102 static void unicodeFunc( 001103 sqlite3_context *context, 001104 int argc, 001105 sqlite3_value **argv 001106 ){ 001107 const unsigned char *z = sqlite3_value_text(argv[0]); 001108 (void)argc; 001109 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); 001110 } 001111 001112 /* 001113 ** The char() function takes zero or more arguments, each of which is 001114 ** an integer. It constructs a string where each character of the string 001115 ** is the unicode character for the corresponding integer argument. 001116 */ 001117 static void charFunc( 001118 sqlite3_context *context, 001119 int argc, 001120 sqlite3_value **argv 001121 ){ 001122 unsigned char *z, *zOut; 001123 int i; 001124 zOut = z = sqlite3_malloc64( argc*4+1 ); 001125 if( z==0 ){ 001126 sqlite3_result_error_nomem(context); 001127 return; 001128 } 001129 for(i=0; i<argc; i++){ 001130 sqlite3_int64 x; 001131 unsigned c; 001132 x = sqlite3_value_int64(argv[i]); 001133 if( x<0 || x>0x10ffff ) x = 0xfffd; 001134 c = (unsigned)(x & 0x1fffff); 001135 if( c<0x00080 ){ 001136 *zOut++ = (u8)(c&0xFF); 001137 }else if( c<0x00800 ){ 001138 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); 001139 *zOut++ = 0x80 + (u8)(c & 0x3F); 001140 }else if( c<0x10000 ){ 001141 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); 001142 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 001143 *zOut++ = 0x80 + (u8)(c & 0x3F); 001144 }else{ 001145 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); 001146 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); 001147 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); 001148 *zOut++ = 0x80 + (u8)(c & 0x3F); 001149 } \ 001150 } 001151 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); 001152 } 001153 001154 /* 001155 ** The hex() function. Interpret the argument as a blob. Return 001156 ** a hexadecimal rendering as text. 001157 */ 001158 static void hexFunc( 001159 sqlite3_context *context, 001160 int argc, 001161 sqlite3_value **argv 001162 ){ 001163 int i, n; 001164 const unsigned char *pBlob; 001165 char *zHex, *z; 001166 assert( argc==1 ); 001167 UNUSED_PARAMETER(argc); 001168 pBlob = sqlite3_value_blob(argv[0]); 001169 n = sqlite3_value_bytes(argv[0]); 001170 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ 001171 z = zHex = contextMalloc(context, ((i64)n)*2 + 1); 001172 if( zHex ){ 001173 for(i=0; i<n; i++, pBlob++){ 001174 unsigned char c = *pBlob; 001175 *(z++) = hexdigits[(c>>4)&0xf]; 001176 *(z++) = hexdigits[c&0xf]; 001177 } 001178 *z = 0; 001179 sqlite3_result_text(context, zHex, n*2, sqlite3_free); 001180 } 001181 } 001182 001183 /* 001184 ** The zeroblob(N) function returns a zero-filled blob of size N bytes. 001185 */ 001186 static void zeroblobFunc( 001187 sqlite3_context *context, 001188 int argc, 001189 sqlite3_value **argv 001190 ){ 001191 i64 n; 001192 int rc; 001193 assert( argc==1 ); 001194 UNUSED_PARAMETER(argc); 001195 n = sqlite3_value_int64(argv[0]); 001196 if( n<0 ) n = 0; 001197 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ 001198 if( rc ){ 001199 sqlite3_result_error_code(context, rc); 001200 } 001201 } 001202 001203 /* 001204 ** The replace() function. Three arguments are all strings: call 001205 ** them A, B, and C. The result is also a string which is derived 001206 ** from A by replacing every occurrence of B with C. The match 001207 ** must be exact. Collating sequences are not used. 001208 */ 001209 static void replaceFunc( 001210 sqlite3_context *context, 001211 int argc, 001212 sqlite3_value **argv 001213 ){ 001214 const unsigned char *zStr; /* The input string A */ 001215 const unsigned char *zPattern; /* The pattern string B */ 001216 const unsigned char *zRep; /* The replacement string C */ 001217 unsigned char *zOut; /* The output */ 001218 int nStr; /* Size of zStr */ 001219 int nPattern; /* Size of zPattern */ 001220 int nRep; /* Size of zRep */ 001221 i64 nOut; /* Maximum size of zOut */ 001222 int loopLimit; /* Last zStr[] that might match zPattern[] */ 001223 int i, j; /* Loop counters */ 001224 unsigned cntExpand; /* Number zOut expansions */ 001225 sqlite3 *db = sqlite3_context_db_handle(context); 001226 001227 assert( argc==3 ); 001228 UNUSED_PARAMETER(argc); 001229 zStr = sqlite3_value_text(argv[0]); 001230 if( zStr==0 ) return; 001231 nStr = sqlite3_value_bytes(argv[0]); 001232 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ 001233 zPattern = sqlite3_value_text(argv[1]); 001234 if( zPattern==0 ){ 001235 assert( sqlite3_value_type(argv[1])==SQLITE_NULL 001236 || sqlite3_context_db_handle(context)->mallocFailed ); 001237 return; 001238 } 001239 if( zPattern[0]==0 ){ 001240 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); 001241 sqlite3_result_value(context, argv[0]); 001242 return; 001243 } 001244 nPattern = sqlite3_value_bytes(argv[1]); 001245 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ 001246 zRep = sqlite3_value_text(argv[2]); 001247 if( zRep==0 ) return; 001248 nRep = sqlite3_value_bytes(argv[2]); 001249 assert( zRep==sqlite3_value_text(argv[2]) ); 001250 nOut = nStr + 1; 001251 assert( nOut<SQLITE_MAX_LENGTH ); 001252 zOut = contextMalloc(context, (i64)nOut); 001253 if( zOut==0 ){ 001254 return; 001255 } 001256 loopLimit = nStr - nPattern; 001257 cntExpand = 0; 001258 for(i=j=0; i<=loopLimit; i++){ 001259 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ 001260 zOut[j++] = zStr[i]; 001261 }else{ 001262 if( nRep>nPattern ){ 001263 nOut += nRep - nPattern; 001264 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); 001265 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); 001266 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ 001267 sqlite3_result_error_toobig(context); 001268 sqlite3_free(zOut); 001269 return; 001270 } 001271 cntExpand++; 001272 if( (cntExpand&(cntExpand-1))==0 ){ 001273 /* Grow the size of the output buffer only on substitutions 001274 ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */ 001275 u8 *zOld; 001276 zOld = zOut; 001277 zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1)); 001278 if( zOut==0 ){ 001279 sqlite3_result_error_nomem(context); 001280 sqlite3_free(zOld); 001281 return; 001282 } 001283 } 001284 } 001285 memcpy(&zOut[j], zRep, nRep); 001286 j += nRep; 001287 i += nPattern-1; 001288 } 001289 } 001290 assert( j+nStr-i+1<=nOut ); 001291 memcpy(&zOut[j], &zStr[i], nStr-i); 001292 j += nStr - i; 001293 assert( j<=nOut ); 001294 zOut[j] = 0; 001295 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); 001296 } 001297 001298 /* 001299 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. 001300 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. 001301 */ 001302 static void trimFunc( 001303 sqlite3_context *context, 001304 int argc, 001305 sqlite3_value **argv 001306 ){ 001307 const unsigned char *zIn; /* Input string */ 001308 const unsigned char *zCharSet; /* Set of characters to trim */ 001309 int nIn; /* Number of bytes in input */ 001310 int flags; /* 1: trimleft 2: trimright 3: trim */ 001311 int i; /* Loop counter */ 001312 unsigned char *aLen = 0; /* Length of each character in zCharSet */ 001313 unsigned char **azChar = 0; /* Individual characters in zCharSet */ 001314 int nChar; /* Number of characters in zCharSet */ 001315 001316 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 001317 return; 001318 } 001319 zIn = sqlite3_value_text(argv[0]); 001320 if( zIn==0 ) return; 001321 nIn = sqlite3_value_bytes(argv[0]); 001322 assert( zIn==sqlite3_value_text(argv[0]) ); 001323 if( argc==1 ){ 001324 static const unsigned char lenOne[] = { 1 }; 001325 static unsigned char * const azOne[] = { (u8*)" " }; 001326 nChar = 1; 001327 aLen = (u8*)lenOne; 001328 azChar = (unsigned char **)azOne; 001329 zCharSet = 0; 001330 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ 001331 return; 001332 }else{ 001333 const unsigned char *z; 001334 for(z=zCharSet, nChar=0; *z; nChar++){ 001335 SQLITE_SKIP_UTF8(z); 001336 } 001337 if( nChar>0 ){ 001338 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); 001339 if( azChar==0 ){ 001340 return; 001341 } 001342 aLen = (unsigned char*)&azChar[nChar]; 001343 for(z=zCharSet, nChar=0; *z; nChar++){ 001344 azChar[nChar] = (unsigned char *)z; 001345 SQLITE_SKIP_UTF8(z); 001346 aLen[nChar] = (u8)(z - azChar[nChar]); 001347 } 001348 } 001349 } 001350 if( nChar>0 ){ 001351 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); 001352 if( flags & 1 ){ 001353 while( nIn>0 ){ 001354 int len = 0; 001355 for(i=0; i<nChar; i++){ 001356 len = aLen[i]; 001357 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break; 001358 } 001359 if( i>=nChar ) break; 001360 zIn += len; 001361 nIn -= len; 001362 } 001363 } 001364 if( flags & 2 ){ 001365 while( nIn>0 ){ 001366 int len = 0; 001367 for(i=0; i<nChar; i++){ 001368 len = aLen[i]; 001369 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break; 001370 } 001371 if( i>=nChar ) break; 001372 nIn -= len; 001373 } 001374 } 001375 if( zCharSet ){ 001376 sqlite3_free(azChar); 001377 } 001378 } 001379 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); 001380 } 001381 001382 001383 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 001384 /* 001385 ** The "unknown" function is automatically substituted in place of 001386 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN 001387 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used. 001388 ** When the "sqlite3" command-line shell is built using this functionality, 001389 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries 001390 ** involving application-defined functions to be examined in a generic 001391 ** sqlite3 shell. 001392 */ 001393 static void unknownFunc( 001394 sqlite3_context *context, 001395 int argc, 001396 sqlite3_value **argv 001397 ){ 001398 /* no-op */ 001399 } 001400 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ 001401 001402 001403 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It 001404 ** is only available if the SQLITE_SOUNDEX compile-time option is used 001405 ** when SQLite is built. 001406 */ 001407 #ifdef SQLITE_SOUNDEX 001408 /* 001409 ** Compute the soundex encoding of a word. 001410 ** 001411 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the 001412 ** soundex encoding of the string X. 001413 */ 001414 static void soundexFunc( 001415 sqlite3_context *context, 001416 int argc, 001417 sqlite3_value **argv 001418 ){ 001419 char zResult[8]; 001420 const u8 *zIn; 001421 int i, j; 001422 static const unsigned char iCode[] = { 001423 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001424 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001425 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001426 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 001427 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 001428 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 001429 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 001430 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, 001431 }; 001432 assert( argc==1 ); 001433 zIn = (u8*)sqlite3_value_text(argv[0]); 001434 if( zIn==0 ) zIn = (u8*)""; 001435 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} 001436 if( zIn[i] ){ 001437 u8 prevcode = iCode[zIn[i]&0x7f]; 001438 zResult[0] = sqlite3Toupper(zIn[i]); 001439 for(j=1; j<4 && zIn[i]; i++){ 001440 int code = iCode[zIn[i]&0x7f]; 001441 if( code>0 ){ 001442 if( code!=prevcode ){ 001443 prevcode = code; 001444 zResult[j++] = code + '0'; 001445 } 001446 }else{ 001447 prevcode = 0; 001448 } 001449 } 001450 while( j<4 ){ 001451 zResult[j++] = '0'; 001452 } 001453 zResult[j] = 0; 001454 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); 001455 }else{ 001456 /* IMP: R-64894-50321 The string "?000" is returned if the argument 001457 ** is NULL or contains no ASCII alphabetic characters. */ 001458 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); 001459 } 001460 } 001461 #endif /* SQLITE_SOUNDEX */ 001462 001463 #ifndef SQLITE_OMIT_LOAD_EXTENSION 001464 /* 001465 ** A function that loads a shared-library extension then returns NULL. 001466 */ 001467 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ 001468 const char *zFile = (const char *)sqlite3_value_text(argv[0]); 001469 const char *zProc; 001470 sqlite3 *db = sqlite3_context_db_handle(context); 001471 char *zErrMsg = 0; 001472 001473 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc 001474 ** flag is set. See the sqlite3_enable_load_extension() API. 001475 */ 001476 if( (db->flags & SQLITE_LoadExtFunc)==0 ){ 001477 sqlite3_result_error(context, "not authorized", -1); 001478 return; 001479 } 001480 001481 if( argc==2 ){ 001482 zProc = (const char *)sqlite3_value_text(argv[1]); 001483 }else{ 001484 zProc = 0; 001485 } 001486 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ 001487 sqlite3_result_error(context, zErrMsg, -1); 001488 sqlite3_free(zErrMsg); 001489 } 001490 } 001491 #endif 001492 001493 001494 /* 001495 ** An instance of the following structure holds the context of a 001496 ** sum() or avg() aggregate computation. 001497 */ 001498 typedef struct SumCtx SumCtx; 001499 struct SumCtx { 001500 double rSum; /* Floating point sum */ 001501 i64 iSum; /* Integer sum */ 001502 i64 cnt; /* Number of elements summed */ 001503 u8 overflow; /* True if integer overflow seen */ 001504 u8 approx; /* True if non-integer value was input to the sum */ 001505 }; 001506 001507 /* 001508 ** Routines used to compute the sum, average, and total. 001509 ** 001510 ** The SUM() function follows the (broken) SQL standard which means 001511 ** that it returns NULL if it sums over no inputs. TOTAL returns 001512 ** 0.0 in that case. In addition, TOTAL always returns a float where 001513 ** SUM might return an integer if it never encounters a floating point 001514 ** value. TOTAL never fails, but SUM might through an exception if 001515 ** it overflows an integer. 001516 */ 001517 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 001518 SumCtx *p; 001519 int type; 001520 assert( argc==1 ); 001521 UNUSED_PARAMETER(argc); 001522 p = sqlite3_aggregate_context(context, sizeof(*p)); 001523 type = sqlite3_value_numeric_type(argv[0]); 001524 if( p && type!=SQLITE_NULL ){ 001525 p->cnt++; 001526 if( type==SQLITE_INTEGER ){ 001527 i64 v = sqlite3_value_int64(argv[0]); 001528 p->rSum += v; 001529 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ 001530 p->approx = p->overflow = 1; 001531 } 001532 }else{ 001533 p->rSum += sqlite3_value_double(argv[0]); 001534 p->approx = 1; 001535 } 001536 } 001537 } 001538 #ifndef SQLITE_OMIT_WINDOWFUNC 001539 static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ 001540 SumCtx *p; 001541 int type; 001542 assert( argc==1 ); 001543 UNUSED_PARAMETER(argc); 001544 p = sqlite3_aggregate_context(context, sizeof(*p)); 001545 type = sqlite3_value_numeric_type(argv[0]); 001546 /* p is always non-NULL because sumStep() will have been called first 001547 ** to initialize it */ 001548 if( ALWAYS(p) && type!=SQLITE_NULL ){ 001549 assert( p->cnt>0 ); 001550 p->cnt--; 001551 assert( type==SQLITE_INTEGER || p->approx ); 001552 if( type==SQLITE_INTEGER && p->approx==0 ){ 001553 i64 v = sqlite3_value_int64(argv[0]); 001554 p->rSum -= v; 001555 p->iSum -= v; 001556 }else{ 001557 p->rSum -= sqlite3_value_double(argv[0]); 001558 } 001559 } 001560 } 001561 #else 001562 # define sumInverse 0 001563 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001564 static void sumFinalize(sqlite3_context *context){ 001565 SumCtx *p; 001566 p = sqlite3_aggregate_context(context, 0); 001567 if( p && p->cnt>0 ){ 001568 if( p->overflow ){ 001569 sqlite3_result_error(context,"integer overflow",-1); 001570 }else if( p->approx ){ 001571 sqlite3_result_double(context, p->rSum); 001572 }else{ 001573 sqlite3_result_int64(context, p->iSum); 001574 } 001575 } 001576 } 001577 static void avgFinalize(sqlite3_context *context){ 001578 SumCtx *p; 001579 p = sqlite3_aggregate_context(context, 0); 001580 if( p && p->cnt>0 ){ 001581 sqlite3_result_double(context, p->rSum/(double)p->cnt); 001582 } 001583 } 001584 static void totalFinalize(sqlite3_context *context){ 001585 SumCtx *p; 001586 p = sqlite3_aggregate_context(context, 0); 001587 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ 001588 sqlite3_result_double(context, p ? p->rSum : (double)0); 001589 } 001590 001591 /* 001592 ** The following structure keeps track of state information for the 001593 ** count() aggregate function. 001594 */ 001595 typedef struct CountCtx CountCtx; 001596 struct CountCtx { 001597 i64 n; 001598 #ifdef SQLITE_DEBUG 001599 int bInverse; /* True if xInverse() ever called */ 001600 #endif 001601 }; 001602 001603 /* 001604 ** Routines to implement the count() aggregate function. 001605 */ 001606 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ 001607 CountCtx *p; 001608 p = sqlite3_aggregate_context(context, sizeof(*p)); 001609 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ 001610 p->n++; 001611 } 001612 001613 #ifndef SQLITE_OMIT_DEPRECATED 001614 /* The sqlite3_aggregate_count() function is deprecated. But just to make 001615 ** sure it still operates correctly, verify that its count agrees with our 001616 ** internal count when using count(*) and when the total count can be 001617 ** expressed as a 32-bit integer. */ 001618 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse 001619 || p->n==sqlite3_aggregate_count(context) ); 001620 #endif 001621 } 001622 static void countFinalize(sqlite3_context *context){ 001623 CountCtx *p; 001624 p = sqlite3_aggregate_context(context, 0); 001625 sqlite3_result_int64(context, p ? p->n : 0); 001626 } 001627 #ifndef SQLITE_OMIT_WINDOWFUNC 001628 static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){ 001629 CountCtx *p; 001630 p = sqlite3_aggregate_context(ctx, sizeof(*p)); 001631 /* p is always non-NULL since countStep() will have been called first */ 001632 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){ 001633 p->n--; 001634 #ifdef SQLITE_DEBUG 001635 p->bInverse = 1; 001636 #endif 001637 } 001638 } 001639 #else 001640 # define countInverse 0 001641 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001642 001643 /* 001644 ** Routines to implement min() and max() aggregate functions. 001645 */ 001646 static void minmaxStep( 001647 sqlite3_context *context, 001648 int NotUsed, 001649 sqlite3_value **argv 001650 ){ 001651 Mem *pArg = (Mem *)argv[0]; 001652 Mem *pBest; 001653 UNUSED_PARAMETER(NotUsed); 001654 001655 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); 001656 if( !pBest ) return; 001657 001658 if( sqlite3_value_type(pArg)==SQLITE_NULL ){ 001659 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); 001660 }else if( pBest->flags ){ 001661 int max; 001662 int cmp; 001663 CollSeq *pColl = sqlite3GetFuncCollSeq(context); 001664 /* This step function is used for both the min() and max() aggregates, 001665 ** the only difference between the two being that the sense of the 001666 ** comparison is inverted. For the max() aggregate, the 001667 ** sqlite3_user_data() function returns (void *)-1. For min() it 001668 ** returns (void *)db, where db is the sqlite3* database pointer. 001669 ** Therefore the next statement sets variable 'max' to 1 for the max() 001670 ** aggregate, or 0 for min(). 001671 */ 001672 max = sqlite3_user_data(context)!=0; 001673 cmp = sqlite3MemCompare(pBest, pArg, pColl); 001674 if( (max && cmp<0) || (!max && cmp>0) ){ 001675 sqlite3VdbeMemCopy(pBest, pArg); 001676 }else{ 001677 sqlite3SkipAccumulatorLoad(context); 001678 } 001679 }else{ 001680 pBest->db = sqlite3_context_db_handle(context); 001681 sqlite3VdbeMemCopy(pBest, pArg); 001682 } 001683 } 001684 static void minMaxValueFinalize(sqlite3_context *context, int bValue){ 001685 sqlite3_value *pRes; 001686 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); 001687 if( pRes ){ 001688 if( pRes->flags ){ 001689 sqlite3_result_value(context, pRes); 001690 } 001691 if( bValue==0 ) sqlite3VdbeMemRelease(pRes); 001692 } 001693 } 001694 #ifndef SQLITE_OMIT_WINDOWFUNC 001695 static void minMaxValue(sqlite3_context *context){ 001696 minMaxValueFinalize(context, 1); 001697 } 001698 #else 001699 # define minMaxValue 0 001700 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001701 static void minMaxFinalize(sqlite3_context *context){ 001702 minMaxValueFinalize(context, 0); 001703 } 001704 001705 /* 001706 ** group_concat(EXPR, ?SEPARATOR?) 001707 */ 001708 static void groupConcatStep( 001709 sqlite3_context *context, 001710 int argc, 001711 sqlite3_value **argv 001712 ){ 001713 const char *zVal; 001714 StrAccum *pAccum; 001715 const char *zSep; 001716 int nVal, nSep; 001717 assert( argc==1 || argc==2 ); 001718 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 001719 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); 001720 001721 if( pAccum ){ 001722 sqlite3 *db = sqlite3_context_db_handle(context); 001723 int firstTerm = pAccum->mxAlloc==0; 001724 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; 001725 if( !firstTerm ){ 001726 if( argc==2 ){ 001727 zSep = (char*)sqlite3_value_text(argv[1]); 001728 nSep = sqlite3_value_bytes(argv[1]); 001729 }else{ 001730 zSep = ","; 001731 nSep = 1; 001732 } 001733 if( zSep ) sqlite3_str_append(pAccum, zSep, nSep); 001734 } 001735 zVal = (char*)sqlite3_value_text(argv[0]); 001736 nVal = sqlite3_value_bytes(argv[0]); 001737 if( zVal ) sqlite3_str_append(pAccum, zVal, nVal); 001738 } 001739 } 001740 #ifndef SQLITE_OMIT_WINDOWFUNC 001741 static void groupConcatInverse( 001742 sqlite3_context *context, 001743 int argc, 001744 sqlite3_value **argv 001745 ){ 001746 int n; 001747 StrAccum *pAccum; 001748 assert( argc==1 || argc==2 ); 001749 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; 001750 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); 001751 /* pAccum is always non-NULL since groupConcatStep() will have always 001752 ** run frist to initialize it */ 001753 if( ALWAYS(pAccum) ){ 001754 n = sqlite3_value_bytes(argv[0]); 001755 if( argc==2 ){ 001756 n += sqlite3_value_bytes(argv[1]); 001757 }else{ 001758 n++; 001759 } 001760 if( n>=(int)pAccum->nChar ){ 001761 pAccum->nChar = 0; 001762 }else{ 001763 pAccum->nChar -= n; 001764 memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar); 001765 } 001766 if( pAccum->nChar==0 ) pAccum->mxAlloc = 0; 001767 } 001768 } 001769 #else 001770 # define groupConcatInverse 0 001771 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001772 static void groupConcatFinalize(sqlite3_context *context){ 001773 StrAccum *pAccum; 001774 pAccum = sqlite3_aggregate_context(context, 0); 001775 if( pAccum ){ 001776 if( pAccum->accError==SQLITE_TOOBIG ){ 001777 sqlite3_result_error_toobig(context); 001778 }else if( pAccum->accError==SQLITE_NOMEM ){ 001779 sqlite3_result_error_nomem(context); 001780 }else{ 001781 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 001782 sqlite3_free); 001783 } 001784 } 001785 } 001786 #ifndef SQLITE_OMIT_WINDOWFUNC 001787 static void groupConcatValue(sqlite3_context *context){ 001788 sqlite3_str *pAccum; 001789 pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0); 001790 if( pAccum ){ 001791 if( pAccum->accError==SQLITE_TOOBIG ){ 001792 sqlite3_result_error_toobig(context); 001793 }else if( pAccum->accError==SQLITE_NOMEM ){ 001794 sqlite3_result_error_nomem(context); 001795 }else{ 001796 const char *zText = sqlite3_str_value(pAccum); 001797 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); 001798 } 001799 } 001800 } 001801 #else 001802 # define groupConcatValue 0 001803 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001804 001805 /* 001806 ** This routine does per-connection function registration. Most 001807 ** of the built-in functions above are part of the global function set. 001808 ** This routine only deals with those that are not global. 001809 */ 001810 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ 001811 int rc = sqlite3_overload_function(db, "MATCH", 2); 001812 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); 001813 if( rc==SQLITE_NOMEM ){ 001814 sqlite3OomFault(db); 001815 } 001816 } 001817 001818 /* 001819 ** Re-register the built-in LIKE functions. The caseSensitive 001820 ** parameter determines whether or not the LIKE operator is case 001821 ** sensitive. 001822 */ 001823 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ 001824 struct compareInfo *pInfo; 001825 int flags; 001826 if( caseSensitive ){ 001827 pInfo = (struct compareInfo*)&likeInfoAlt; 001828 flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE; 001829 }else{ 001830 pInfo = (struct compareInfo*)&likeInfoNorm; 001831 flags = SQLITE_FUNC_LIKE; 001832 } 001833 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); 001834 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); 001835 sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags; 001836 sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags; 001837 } 001838 001839 /* 001840 ** pExpr points to an expression which implements a function. If 001841 ** it is appropriate to apply the LIKE optimization to that function 001842 ** then set aWc[0] through aWc[2] to the wildcard characters and the 001843 ** escape character and then return TRUE. If the function is not a 001844 ** LIKE-style function then return FALSE. 001845 ** 001846 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE 001847 ** operator if c is a string literal that is exactly one byte in length. 001848 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is 001849 ** no ESCAPE clause. 001850 ** 001851 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for 001852 ** the function (default for LIKE). If the function makes the distinction 001853 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to 001854 ** false. 001855 */ 001856 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ 001857 FuncDef *pDef; 001858 int nExpr; 001859 if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){ 001860 return 0; 001861 } 001862 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 001863 nExpr = pExpr->x.pList->nExpr; 001864 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0); 001865 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ 001866 return 0; 001867 } 001868 if( nExpr<3 ){ 001869 aWc[3] = 0; 001870 }else{ 001871 Expr *pEscape = pExpr->x.pList->a[2].pExpr; 001872 char *zEscape; 001873 if( pEscape->op!=TK_STRING ) return 0; 001874 zEscape = pEscape->u.zToken; 001875 if( zEscape[0]==0 || zEscape[1]!=0 ) return 0; 001876 aWc[3] = zEscape[0]; 001877 } 001878 001879 /* The memcpy() statement assumes that the wildcard characters are 001880 ** the first three statements in the compareInfo structure. The 001881 ** asserts() that follow verify that assumption 001882 */ 001883 memcpy(aWc, pDef->pUserData, 3); 001884 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); 001885 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); 001886 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); 001887 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; 001888 return 1; 001889 } 001890 001891 /* 001892 ** All of the FuncDef structures in the aBuiltinFunc[] array above 001893 ** to the global function hash table. This occurs at start-time (as 001894 ** a consequence of calling sqlite3_initialize()). 001895 ** 001896 ** After this routine runs 001897 */ 001898 void sqlite3RegisterBuiltinFunctions(void){ 001899 /* 001900 ** The following array holds FuncDef structures for all of the functions 001901 ** defined in this file. 001902 ** 001903 ** The array cannot be constant since changes are made to the 001904 ** FuncDef.pHash elements at start-time. The elements of this array 001905 ** are read-only after initialization is complete. 001906 ** 001907 ** For peak efficiency, put the most frequently used function last. 001908 */ 001909 static FuncDef aBuiltinFunc[] = { 001910 #ifdef SQLITE_SOUNDEX 001911 FUNCTION(soundex, 1, 0, 0, soundexFunc ), 001912 #endif 001913 #ifndef SQLITE_OMIT_LOAD_EXTENSION 001914 VFUNCTION(load_extension, 1, 0, 0, loadExt ), 001915 VFUNCTION(load_extension, 2, 0, 0, loadExt ), 001916 #endif 001917 #if SQLITE_USER_AUTHENTICATION 001918 FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), 001919 #endif 001920 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS 001921 DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), 001922 DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), 001923 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ 001924 FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), 001925 FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), 001926 FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), 001927 #ifdef SQLITE_DEBUG 001928 FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY), 001929 #endif 001930 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 001931 FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET| 001932 SQLITE_FUNC_TYPEOF), 001933 #endif 001934 FUNCTION(ltrim, 1, 1, 0, trimFunc ), 001935 FUNCTION(ltrim, 2, 1, 0, trimFunc ), 001936 FUNCTION(rtrim, 1, 2, 0, trimFunc ), 001937 FUNCTION(rtrim, 2, 2, 0, trimFunc ), 001938 FUNCTION(trim, 1, 3, 0, trimFunc ), 001939 FUNCTION(trim, 2, 3, 0, trimFunc ), 001940 FUNCTION(min, -1, 0, 1, minmaxFunc ), 001941 FUNCTION(min, 0, 0, 1, 0 ), 001942 WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, 001943 SQLITE_FUNC_MINMAX ), 001944 FUNCTION(max, -1, 1, 1, minmaxFunc ), 001945 FUNCTION(max, 0, 1, 1, 0 ), 001946 WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, 001947 SQLITE_FUNC_MINMAX ), 001948 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), 001949 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), 001950 FUNCTION(instr, 2, 0, 0, instrFunc ), 001951 FUNCTION(printf, -1, 0, 0, printfFunc ), 001952 FUNCTION(unicode, 1, 0, 0, unicodeFunc ), 001953 FUNCTION(char, -1, 0, 0, charFunc ), 001954 FUNCTION(abs, 1, 0, 0, absFunc ), 001955 #ifndef SQLITE_OMIT_FLOATING_POINT 001956 FUNCTION(round, 1, 0, 0, roundFunc ), 001957 FUNCTION(round, 2, 0, 0, roundFunc ), 001958 #endif 001959 FUNCTION(upper, 1, 0, 0, upperFunc ), 001960 FUNCTION(lower, 1, 0, 0, lowerFunc ), 001961 FUNCTION(hex, 1, 0, 0, hexFunc ), 001962 FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), 001963 VFUNCTION(random, 0, 0, 0, randomFunc ), 001964 VFUNCTION(randomblob, 1, 0, 0, randomBlob ), 001965 FUNCTION(nullif, 2, 0, 1, nullifFunc ), 001966 DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), 001967 DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), 001968 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), 001969 FUNCTION(quote, 1, 0, 0, quoteFunc ), 001970 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), 001971 VFUNCTION(changes, 0, 0, 0, changes ), 001972 VFUNCTION(total_changes, 0, 0, 0, total_changes ), 001973 FUNCTION(replace, 3, 0, 0, replaceFunc ), 001974 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), 001975 FUNCTION(substr, 2, 0, 0, substrFunc ), 001976 FUNCTION(substr, 3, 0, 0, substrFunc ), 001977 WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0), 001978 WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0), 001979 WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0), 001980 WAGGREGATE(count, 0,0,0, countStep, 001981 countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ), 001982 WAGGREGATE(count, 1,0,0, countStep, 001983 countFinalize, countFinalize, countInverse, 0 ), 001984 WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, 001985 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), 001986 WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, 001987 groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), 001988 001989 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 001990 #ifdef SQLITE_CASE_SENSITIVE_LIKE 001991 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 001992 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), 001993 #else 001994 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), 001995 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), 001996 #endif 001997 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 001998 FUNCTION(unknown, -1, 0, 0, unknownFunc ), 001999 #endif 002000 FUNCTION(coalesce, 1, 0, 0, 0 ), 002001 FUNCTION(coalesce, 0, 0, 0, 0 ), 002002 FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), 002003 }; 002004 #ifndef SQLITE_OMIT_ALTERTABLE 002005 sqlite3AlterFunctions(); 002006 #endif 002007 sqlite3WindowFunctions(); 002008 sqlite3RegisterDateTimeFunctions(); 002009 sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); 002010 002011 #if 0 /* Enable to print out how the built-in functions are hashed */ 002012 { 002013 int i; 002014 FuncDef *p; 002015 for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ 002016 printf("FUNC-HASH %02d:", i); 002017 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){ 002018 int n = sqlite3Strlen30(p->zName); 002019 int h = p->zName[0] + n; 002020 printf(" %s(%d)", p->zName, h); 002021 } 002022 printf("\n"); 002023 } 002024 } 002025 #endif 002026 }