Back to index

lightning-sunbird  0.9+nobinonly
func.c
Go to the documentation of this file.
00001 /*
00002 ** 2002 February 23
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains the C functions that implement various SQL
00013 ** functions of SQLite.  
00014 **
00015 ** There is only one exported symbol in this file - the function
00016 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
00017 ** All other code has file scope.
00018 **
00019 ** $Id: func.c,v 1.128 2006/05/11 13:25:39 drh Exp $
00020 */
00021 #include "sqliteInt.h"
00022 #include <ctype.h>
00023 /* #include <math.h> */
00024 #include <stdlib.h>
00025 #include <assert.h>
00026 #include "vdbeInt.h"
00027 #include "os.h"
00028 
00029 /*
00030 ** Return the collating function associated with a function.
00031 */
00032 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
00033   return context->pColl;
00034 }
00035 
00036 /*
00037 ** Implementation of the non-aggregate min() and max() functions
00038 */
00039 static void minmaxFunc(
00040   sqlite3_context *context,
00041   int argc,
00042   sqlite3_value **argv
00043 ){
00044   int i;
00045   int mask;    /* 0 for min() or 0xffffffff for max() */
00046   int iBest;
00047   CollSeq *pColl;
00048 
00049   if( argc==0 ) return;
00050   mask = sqlite3_user_data(context)==0 ? 0 : -1;
00051   pColl = sqlite3GetFuncCollSeq(context);
00052   assert( pColl );
00053   assert( mask==-1 || mask==0 );
00054   iBest = 0;
00055   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
00056   for(i=1; i<argc; i++){
00057     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
00058     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
00059       iBest = i;
00060     }
00061   }
00062   sqlite3_result_value(context, argv[iBest]);
00063 }
00064 
00065 /*
00066 ** Return the type of the argument.
00067 */
00068 static void typeofFunc(
00069   sqlite3_context *context,
00070   int argc,
00071   sqlite3_value **argv
00072 ){
00073   const char *z = 0;
00074   switch( sqlite3_value_type(argv[0]) ){
00075     case SQLITE_NULL:    z = "null";    break;
00076     case SQLITE_INTEGER: z = "integer"; break;
00077     case SQLITE_TEXT:    z = "text";    break;
00078     case SQLITE_FLOAT:   z = "real";    break;
00079     case SQLITE_BLOB:    z = "blob";    break;
00080   }
00081   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
00082 }
00083 
00084 
00085 /*
00086 ** Implementation of the length() function
00087 */
00088 static void lengthFunc(
00089   sqlite3_context *context,
00090   int argc,
00091   sqlite3_value **argv
00092 ){
00093   int len;
00094 
00095   assert( argc==1 );
00096   switch( sqlite3_value_type(argv[0]) ){
00097     case SQLITE_BLOB:
00098     case SQLITE_INTEGER:
00099     case SQLITE_FLOAT: {
00100       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
00101       break;
00102     }
00103     case SQLITE_TEXT: {
00104       const unsigned char *z = sqlite3_value_text(argv[0]);
00105       for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
00106       sqlite3_result_int(context, len);
00107       break;
00108     }
00109     default: {
00110       sqlite3_result_null(context);
00111       break;
00112     }
00113   }
00114 }
00115 
00116 /*
00117 ** Implementation of the abs() function
00118 */
00119 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
00120   assert( argc==1 );
00121   switch( sqlite3_value_type(argv[0]) ){
00122     case SQLITE_INTEGER: {
00123       i64 iVal = sqlite3_value_int64(argv[0]);
00124       if( iVal<0 ){
00125         if( (iVal<<1)==0 ){
00126           sqlite3_result_error(context, "integer overflow", -1);
00127           return;
00128         }
00129         iVal = -iVal;
00130       } 
00131       sqlite3_result_int64(context, iVal);
00132       break;
00133     }
00134     case SQLITE_NULL: {
00135       sqlite3_result_null(context);
00136       break;
00137     }
00138     default: {
00139       double rVal = sqlite3_value_double(argv[0]);
00140       if( rVal<0 ) rVal = -rVal;
00141       sqlite3_result_double(context, rVal);
00142       break;
00143     }
00144   }
00145 }
00146 
00147 /*
00148 ** Implementation of the substr() function
00149 */
00150 static void substrFunc(
00151   sqlite3_context *context,
00152   int argc,
00153   sqlite3_value **argv
00154 ){
00155   const unsigned char *z;
00156   const unsigned char *z2;
00157   int i;
00158   int p1, p2, len;
00159 
00160   assert( argc==3 );
00161   z = sqlite3_value_text(argv[0]);
00162   if( z==0 ) return;
00163   p1 = sqlite3_value_int(argv[1]);
00164   p2 = sqlite3_value_int(argv[2]);
00165   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
00166   if( p1<0 ){
00167     p1 += len;
00168     if( p1<0 ){
00169       p2 += p1;
00170       p1 = 0;
00171     }
00172   }else if( p1>0 ){
00173     p1--;
00174   }
00175   if( p1+p2>len ){
00176     p2 = len-p1;
00177   }
00178   for(i=0; i<p1 && z[i]; i++){
00179     if( (z[i]&0xc0)==0x80 ) p1++;
00180   }
00181   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
00182   for(; i<p1+p2 && z[i]; i++){
00183     if( (z[i]&0xc0)==0x80 ) p2++;
00184   }
00185   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
00186   if( p2<0 ) p2 = 0;
00187   sqlite3_result_text(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
00188 }
00189 
00190 /*
00191 ** Implementation of the round() function
00192 */
00193 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
00194   int n = 0;
00195   double r;
00196   char zBuf[500];  /* larger than the %f representation of the largest double */
00197   assert( argc==1 || argc==2 );
00198   if( argc==2 ){
00199     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
00200     n = sqlite3_value_int(argv[1]);
00201     if( n>30 ) n = 30;
00202     if( n<0 ) n = 0;
00203   }
00204   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
00205   r = sqlite3_value_double(argv[0]);
00206   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
00207   sqlite3AtoF(zBuf, &r);
00208   sqlite3_result_double(context, r);
00209 }
00210 
00211 /*
00212 ** Implementation of the upper() and lower() SQL functions.
00213 */
00214 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
00215   unsigned char *z;
00216   int i;
00217   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
00218   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
00219   if( z==0 ) return;
00220   strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
00221   for(i=0; z[i]; i++){
00222     z[i] = toupper(z[i]);
00223   }
00224   sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
00225   sqliteFree(z);
00226 }
00227 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
00228   unsigned char *z;
00229   int i;
00230   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
00231   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
00232   if( z==0 ) return;
00233   strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
00234   for(i=0; z[i]; i++){
00235     z[i] = tolower(z[i]);
00236   }
00237   sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
00238   sqliteFree(z);
00239 }
00240 
00241 /*
00242 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
00243 ** All three do the same thing.  They return the first non-NULL
00244 ** argument.
00245 */
00246 static void ifnullFunc(
00247   sqlite3_context *context,
00248   int argc,
00249   sqlite3_value **argv
00250 ){
00251   int i;
00252   for(i=0; i<argc; i++){
00253     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
00254       sqlite3_result_value(context, argv[i]);
00255       break;
00256     }
00257   }
00258 }
00259 
00260 /*
00261 ** Implementation of random().  Return a random integer.  
00262 */
00263 static void randomFunc(
00264   sqlite3_context *context,
00265   int argc,
00266   sqlite3_value **argv
00267 ){
00268   sqlite_int64 r;
00269   sqlite3Randomness(sizeof(r), &r);
00270   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
00271                           /* can always do abs() of the result */
00272   sqlite3_result_int64(context, r);
00273 }
00274 
00275 /*
00276 ** Implementation of the last_insert_rowid() SQL function.  The return
00277 ** value is the same as the sqlite3_last_insert_rowid() API function.
00278 */
00279 static void last_insert_rowid(
00280   sqlite3_context *context, 
00281   int arg, 
00282   sqlite3_value **argv
00283 ){
00284   sqlite3 *db = sqlite3_user_data(context);
00285   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
00286 }
00287 
00288 /*
00289 ** Implementation of the changes() SQL function.  The return value is the
00290 ** same as the sqlite3_changes() API function.
00291 */
00292 static void changes(
00293   sqlite3_context *context,
00294   int arg,
00295   sqlite3_value **argv
00296 ){
00297   sqlite3 *db = sqlite3_user_data(context);
00298   sqlite3_result_int(context, sqlite3_changes(db));
00299 }
00300 
00301 /*
00302 ** Implementation of the total_changes() SQL function.  The return value is
00303 ** the same as the sqlite3_total_changes() API function.
00304 */
00305 static void total_changes(
00306   sqlite3_context *context,
00307   int arg,
00308   sqlite3_value **argv
00309 ){
00310   sqlite3 *db = sqlite3_user_data(context);
00311   sqlite3_result_int(context, sqlite3_total_changes(db));
00312 }
00313 
00314 /*
00315 ** A structure defining how to do GLOB-style comparisons.
00316 */
00317 struct compareInfo {
00318   u8 matchAll;
00319   u8 matchOne;
00320   u8 matchSet;
00321   u8 noCase;
00322 };
00323 
00324 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
00325 /* The correct SQL-92 behavior is for the LIKE operator to ignore
00326 ** case.  Thus  'a' LIKE 'A' would be true. */
00327 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
00328 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
00329 ** is case sensitive causing 'a' LIKE 'A' to be false */
00330 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
00331 
00332 /*
00333 ** X is a pointer to the first byte of a UTF-8 character.  Increment
00334 ** X so that it points to the next character.  This only works right
00335 ** if X points to a well-formed UTF-8 string.
00336 */
00337 #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
00338 #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
00339 
00340 
00341 /*
00342 ** Compare two UTF-8 strings for equality where the first string can
00343 ** potentially be a "glob" expression.  Return true (1) if they
00344 ** are the same and false (0) if they are different.
00345 **
00346 ** Globbing rules:
00347 **
00348 **      '*'       Matches any sequence of zero or more characters.
00349 **
00350 **      '?'       Matches exactly one character.
00351 **
00352 **     [...]      Matches one character from the enclosed list of
00353 **                characters.
00354 **
00355 **     [^...]     Matches one character not in the enclosed list.
00356 **
00357 ** With the [...] and [^...] matching, a ']' character can be included
00358 ** in the list by making it the first character after '[' or '^'.  A
00359 ** range of characters can be specified using '-'.  Example:
00360 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
00361 ** it the last character in the list.
00362 **
00363 ** This routine is usually quick, but can be N**2 in the worst case.
00364 **
00365 ** Hints: to match '*' or '?', put them in "[]".  Like this:
00366 **
00367 **         abc[*]xyz        Matches "abc*xyz" only
00368 */
00369 static int patternCompare(
00370   const u8 *zPattern,              /* The glob pattern */
00371   const u8 *zString,               /* The string to compare against the glob */
00372   const struct compareInfo *pInfo, /* Information about how to do the compare */
00373   const int esc                    /* The escape character */
00374 ){
00375   register int c;
00376   int invert;
00377   int seen;
00378   int c2;
00379   u8 matchOne = pInfo->matchOne;
00380   u8 matchAll = pInfo->matchAll;
00381   u8 matchSet = pInfo->matchSet;
00382   u8 noCase = pInfo->noCase; 
00383   int prevEscape = 0;     /* True if the previous character was 'escape' */
00384 
00385   while( (c = *zPattern)!=0 ){
00386     if( !prevEscape && c==matchAll ){
00387       while( (c=zPattern[1]) == matchAll || c == matchOne ){
00388         if( c==matchOne ){
00389           if( *zString==0 ) return 0;
00390           sqliteNextChar(zString);
00391         }
00392         zPattern++;
00393       }
00394       if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
00395         u8 const *zTemp = &zPattern[1];
00396         sqliteNextChar(zTemp);
00397         c = *zTemp;
00398       }
00399       if( c==0 ) return 1;
00400       if( c==matchSet ){
00401         assert( esc==0 );   /* This is GLOB, not LIKE */
00402         while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
00403           sqliteNextChar(zString);
00404         }
00405         return *zString!=0;
00406       }else{
00407         while( (c2 = *zString)!=0 ){
00408           if( noCase ){
00409             c2 = sqlite3UpperToLower[c2];
00410             c = sqlite3UpperToLower[c];
00411             while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
00412           }else{
00413             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
00414           }
00415           if( c2==0 ) return 0;
00416           if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
00417           sqliteNextChar(zString);
00418         }
00419         return 0;
00420       }
00421     }else if( !prevEscape && c==matchOne ){
00422       if( *zString==0 ) return 0;
00423       sqliteNextChar(zString);
00424       zPattern++;
00425     }else if( c==matchSet ){
00426       int prior_c = 0;
00427       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
00428       seen = 0;
00429       invert = 0;
00430       c = sqliteCharVal(zString);
00431       if( c==0 ) return 0;
00432       c2 = *++zPattern;
00433       if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
00434       if( c2==']' ){
00435         if( c==']' ) seen = 1;
00436         c2 = *++zPattern;
00437       }
00438       while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
00439         if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
00440           zPattern++;
00441           c2 = sqliteCharVal(zPattern);
00442           if( c>=prior_c && c<=c2 ) seen = 1;
00443           prior_c = 0;
00444         }else if( c==c2 ){
00445           seen = 1;
00446           prior_c = c2;
00447         }else{
00448           prior_c = c2;
00449         }
00450         sqliteNextChar(zPattern);
00451       }
00452       if( c2==0 || (seen ^ invert)==0 ) return 0;
00453       sqliteNextChar(zString);
00454       zPattern++;
00455     }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
00456       prevEscape = 1;
00457       sqliteNextChar(zPattern);
00458     }else{
00459       if( noCase ){
00460         if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
00461       }else{
00462         if( c != *zString ) return 0;
00463       }
00464       zPattern++;
00465       zString++;
00466       prevEscape = 0;
00467     }
00468   }
00469   return *zString==0;
00470 }
00471 
00472 /*
00473 ** Count the number of times that the LIKE operator (or GLOB which is
00474 ** just a variation of LIKE) gets called.  This is used for testing
00475 ** only.
00476 */
00477 #ifdef SQLITE_TEST
00478 int sqlite3_like_count = 0;
00479 #endif
00480 
00481 
00482 /*
00483 ** Implementation of the like() SQL function.  This function implements
00484 ** the build-in LIKE operator.  The first argument to the function is the
00485 ** pattern and the second argument is the string.  So, the SQL statements:
00486 **
00487 **       A LIKE B
00488 **
00489 ** is implemented as like(B,A).
00490 **
00491 ** This same function (with a different compareInfo structure) computes
00492 ** the GLOB operator.
00493 */
00494 static void likeFunc(
00495   sqlite3_context *context, 
00496   int argc, 
00497   sqlite3_value **argv
00498 ){
00499   const unsigned char *zA = sqlite3_value_text(argv[0]);
00500   const unsigned char *zB = sqlite3_value_text(argv[1]);
00501   int escape = 0;
00502   if( argc==3 ){
00503     /* The escape character string must consist of a single UTF-8 character.
00504     ** Otherwise, return an error.
00505     */
00506     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
00507     if( sqlite3utf8CharLen((char*)zEsc, -1)!=1 ){
00508       sqlite3_result_error(context, 
00509           "ESCAPE expression must be a single character", -1);
00510       return;
00511     }
00512     escape = sqlite3ReadUtf8(zEsc);
00513   }
00514   if( zA && zB ){
00515     struct compareInfo *pInfo = sqlite3_user_data(context);
00516 #ifdef SQLITE_TEST
00517     sqlite3_like_count++;
00518 #endif
00519     sqlite3_result_int(context, patternCompare(zA, zB, pInfo, escape));
00520   }
00521 }
00522 
00523 /*
00524 ** Implementation of the NULLIF(x,y) function.  The result is the first
00525 ** argument if the arguments are different.  The result is NULL if the
00526 ** arguments are equal to each other.
00527 */
00528 static void nullifFunc(
00529   sqlite3_context *context,
00530   int argc,
00531   sqlite3_value **argv
00532 ){
00533   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
00534   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
00535     sqlite3_result_value(context, argv[0]);
00536   }
00537 }
00538 
00539 /*
00540 ** Implementation of the VERSION(*) function.  The result is the version
00541 ** of the SQLite library that is running.
00542 */
00543 static void versionFunc(
00544   sqlite3_context *context,
00545   int argc,
00546   sqlite3_value **argv
00547 ){
00548   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
00549 }
00550 
00551 
00552 /*
00553 ** EXPERIMENTAL - This is not an official function.  The interface may
00554 ** change.  This function may disappear.  Do not write code that depends
00555 ** on this function.
00556 **
00557 ** Implementation of the QUOTE() function.  This function takes a single
00558 ** argument.  If the argument is numeric, the return value is the same as
00559 ** the argument.  If the argument is NULL, the return value is the string
00560 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
00561 ** single-quote escapes.
00562 */
00563 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
00564   if( argc<1 ) return;
00565   switch( sqlite3_value_type(argv[0]) ){
00566     case SQLITE_NULL: {
00567       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
00568       break;
00569     }
00570     case SQLITE_INTEGER:
00571     case SQLITE_FLOAT: {
00572       sqlite3_result_value(context, argv[0]);
00573       break;
00574     }
00575     case SQLITE_BLOB: {
00576       static const char hexdigits[] = { 
00577         '0', '1', '2', '3', '4', '5', '6', '7',
00578         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
00579       };
00580       char *zText = 0;
00581       int nBlob = sqlite3_value_bytes(argv[0]);
00582       char const *zBlob = sqlite3_value_blob(argv[0]);
00583 
00584       zText = (char *)sqliteMalloc((2*nBlob)+4); 
00585       if( !zText ){
00586         sqlite3_result_error(context, "out of memory", -1);
00587       }else{
00588         int i;
00589         for(i=0; i<nBlob; i++){
00590           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
00591           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
00592         }
00593         zText[(nBlob*2)+2] = '\'';
00594         zText[(nBlob*2)+3] = '\0';
00595         zText[0] = 'X';
00596         zText[1] = '\'';
00597         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
00598         sqliteFree(zText);
00599       }
00600       break;
00601     }
00602     case SQLITE_TEXT: {
00603       int i,j,n;
00604       const unsigned char *zArg = sqlite3_value_text(argv[0]);
00605       char *z;
00606 
00607       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
00608       z = sqliteMalloc( i+n+3 );
00609       if( z==0 ) return;
00610       z[0] = '\'';
00611       for(i=0, j=1; zArg[i]; i++){
00612         z[j++] = zArg[i];
00613         if( zArg[i]=='\'' ){
00614           z[j++] = '\'';
00615         }
00616       }
00617       z[j++] = '\'';
00618       z[j] = 0;
00619       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
00620       sqliteFree(z);
00621     }
00622   }
00623 }
00624 
00625 #ifdef SQLITE_SOUNDEX
00626 /*
00627 ** Compute the soundex encoding of a word.
00628 */
00629 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
00630   char zResult[8];
00631   const u8 *zIn;
00632   int i, j;
00633   static const unsigned char iCode[] = {
00634     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
00635     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
00636     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
00637     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
00638     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
00639     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
00640     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
00641     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
00642   };
00643   assert( argc==1 );
00644   zIn = (u8*)sqlite3_value_text(argv[0]);
00645   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
00646   if( zIn[i] ){
00647     zResult[0] = toupper(zIn[i]);
00648     for(j=1; j<4 && zIn[i]; i++){
00649       int code = iCode[zIn[i]&0x7f];
00650       if( code>0 ){
00651         zResult[j++] = code + '0';
00652       }
00653     }
00654     while( j<4 ){
00655       zResult[j++] = '0';
00656     }
00657     zResult[j] = 0;
00658     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
00659   }else{
00660     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
00661   }
00662 }
00663 #endif
00664 
00665 #ifdef SQLITE_TEST
00666 /*
00667 ** This function generates a string of random characters.  Used for
00668 ** generating test data.
00669 */
00670 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
00671   static const unsigned char zSrc[] = 
00672      "abcdefghijklmnopqrstuvwxyz"
00673      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
00674      "0123456789"
00675      ".-!,:*^+=_|?/<> ";
00676   int iMin, iMax, n, r, i;
00677   unsigned char zBuf[1000];
00678   if( argc>=1 ){
00679     iMin = sqlite3_value_int(argv[0]);
00680     if( iMin<0 ) iMin = 0;
00681     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
00682   }else{
00683     iMin = 1;
00684   }
00685   if( argc>=2 ){
00686     iMax = sqlite3_value_int(argv[1]);
00687     if( iMax<iMin ) iMax = iMin;
00688     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
00689   }else{
00690     iMax = 50;
00691   }
00692   n = iMin;
00693   if( iMax>iMin ){
00694     sqlite3Randomness(sizeof(r), &r);
00695     r &= 0x7fffffff;
00696     n += r%(iMax + 1 - iMin);
00697   }
00698   assert( n<sizeof(zBuf) );
00699   sqlite3Randomness(n, zBuf);
00700   for(i=0; i<n; i++){
00701     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
00702   }
00703   zBuf[n] = 0;
00704   sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
00705 }
00706 #endif /* SQLITE_TEST */
00707 
00708 #ifdef SQLITE_TEST
00709 /*
00710 ** The following two SQL functions are used to test returning a text
00711 ** result with a destructor. Function 'test_destructor' takes one argument
00712 ** and returns the same argument interpreted as TEXT. A destructor is
00713 ** passed with the sqlite3_result_text() call.
00714 **
00715 ** SQL function 'test_destructor_count' returns the number of outstanding 
00716 ** allocations made by 'test_destructor';
00717 **
00718 ** WARNING: Not threadsafe.
00719 */
00720 static int test_destructor_count_var = 0;
00721 static void destructor(void *p){
00722   char *zVal = (char *)p;
00723   assert(zVal);
00724   zVal--;
00725   sqliteFree(zVal);
00726   test_destructor_count_var--;
00727 }
00728 static void test_destructor(
00729   sqlite3_context *pCtx, 
00730   int nArg,
00731   sqlite3_value **argv
00732 ){
00733   char *zVal;
00734   int len;
00735   sqlite3 *db = sqlite3_user_data(pCtx);
00736  
00737   test_destructor_count_var++;
00738   assert( nArg==1 );
00739   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
00740   len = sqlite3ValueBytes(argv[0], ENC(db)); 
00741   zVal = sqliteMalloc(len+3);
00742   zVal[len] = 0;
00743   zVal[len-1] = 0;
00744   assert( zVal );
00745   zVal++;
00746   memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
00747   if( ENC(db)==SQLITE_UTF8 ){
00748     sqlite3_result_text(pCtx, zVal, -1, destructor);
00749 #ifndef SQLITE_OMIT_UTF16
00750   }else if( ENC(db)==SQLITE_UTF16LE ){
00751     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
00752   }else{
00753     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
00754 #endif /* SQLITE_OMIT_UTF16 */
00755   }
00756 }
00757 static void test_destructor_count(
00758   sqlite3_context *pCtx, 
00759   int nArg,
00760   sqlite3_value **argv
00761 ){
00762   sqlite3_result_int(pCtx, test_destructor_count_var);
00763 }
00764 #endif /* SQLITE_TEST */
00765 
00766 #ifdef SQLITE_TEST
00767 /*
00768 ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
00769 ** interface.
00770 **
00771 ** The test_auxdata() SQL function attempts to register each of its arguments
00772 ** as auxiliary data.  If there are no prior registrations of aux data for
00773 ** that argument (meaning the argument is not a constant or this is its first
00774 ** call) then the result for that argument is 0.  If there is a prior
00775 ** registration, the result for that argument is 1.  The overall result
00776 ** is the individual argument results separated by spaces.
00777 */
00778 static void free_test_auxdata(void *p) {sqliteFree(p);}
00779 static void test_auxdata(
00780   sqlite3_context *pCtx, 
00781   int nArg,
00782   sqlite3_value **argv
00783 ){
00784   int i;
00785   char *zRet = sqliteMalloc(nArg*2);
00786   if( !zRet ) return;
00787   for(i=0; i<nArg; i++){
00788     char const *z = (char*)sqlite3_value_text(argv[i]);
00789     if( z ){
00790       char *zAux = sqlite3_get_auxdata(pCtx, i);
00791       if( zAux ){
00792         zRet[i*2] = '1';
00793         if( strcmp(zAux, z) ){
00794           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
00795           return;
00796         }
00797       }else{
00798         zRet[i*2] = '0';
00799         zAux = sqliteStrDup(z);
00800         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
00801       }
00802       zRet[i*2+1] = ' ';
00803     }
00804   }
00805   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
00806 }
00807 #endif /* SQLITE_TEST */
00808 
00809 #ifdef SQLITE_TEST
00810 /*
00811 ** A function to test error reporting from user functions. This function
00812 ** returns a copy of it's first argument as an error.
00813 */
00814 static void test_error(
00815   sqlite3_context *pCtx, 
00816   int nArg,
00817   sqlite3_value **argv
00818 ){
00819   sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
00820 }
00821 #endif /* SQLITE_TEST */
00822 
00823 /*
00824 ** An instance of the following structure holds the context of a
00825 ** sum() or avg() aggregate computation.
00826 */
00827 typedef struct SumCtx SumCtx;
00828 struct SumCtx {
00829   double rSum;      /* Floating point sum */
00830   i64 iSum;         /* Integer sum */   
00831   i64 cnt;          /* Number of elements summed */
00832   u8 overflow;      /* True if integer overflow seen */
00833   u8 approx;        /* True if non-integer value was input to the sum */
00834 };
00835 
00836 /*
00837 ** Routines used to compute the sum, average, and total.
00838 **
00839 ** The SUM() function follows the (broken) SQL standard which means
00840 ** that it returns NULL if it sums over no inputs.  TOTAL returns
00841 ** 0.0 in that case.  In addition, TOTAL always returns a float where
00842 ** SUM might return an integer if it never encounters a floating point
00843 ** value.  TOTAL never fails, but SUM might through an exception if
00844 ** it overflows an integer.
00845 */
00846 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
00847   SumCtx *p;
00848   int type;
00849   assert( argc==1 );
00850   p = sqlite3_aggregate_context(context, sizeof(*p));
00851   type = sqlite3_value_numeric_type(argv[0]);
00852   if( p && type!=SQLITE_NULL ){
00853     p->cnt++;
00854     if( type==SQLITE_INTEGER ){
00855       i64 v = sqlite3_value_int64(argv[0]);
00856       p->rSum += v;
00857       if( (p->approx|p->overflow)==0 ){
00858         i64 iNewSum = p->iSum + v;
00859         int s1 = p->iSum >> (sizeof(i64)*8-1);
00860         int s2 = v       >> (sizeof(i64)*8-1);
00861         int s3 = iNewSum >> (sizeof(i64)*8-1);
00862         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
00863         p->iSum = iNewSum;
00864       }
00865     }else{
00866       p->rSum += sqlite3_value_double(argv[0]);
00867       p->approx = 1;
00868     }
00869   }
00870 }
00871 static void sumFinalize(sqlite3_context *context){
00872   SumCtx *p;
00873   p = sqlite3_aggregate_context(context, 0);
00874   if( p && p->cnt>0 ){
00875     if( p->overflow ){
00876       sqlite3_result_error(context,"integer overflow",-1);
00877     }else if( p->approx ){
00878       sqlite3_result_double(context, p->rSum);
00879     }else{
00880       sqlite3_result_int64(context, p->iSum);
00881     }
00882   }
00883 }
00884 static void avgFinalize(sqlite3_context *context){
00885   SumCtx *p;
00886   p = sqlite3_aggregate_context(context, 0);
00887   if( p && p->cnt>0 ){
00888     sqlite3_result_double(context, p->rSum/(double)p->cnt);
00889   }
00890 }
00891 static void totalFinalize(sqlite3_context *context){
00892   SumCtx *p;
00893   p = sqlite3_aggregate_context(context, 0);
00894   sqlite3_result_double(context, p ? p->rSum : 0.0);
00895 }
00896 
00897 /*
00898 ** The following structure keeps track of state information for the
00899 ** count() aggregate function.
00900 */
00901 typedef struct CountCtx CountCtx;
00902 struct CountCtx {
00903   i64 n;
00904 };
00905 
00906 /*
00907 ** Routines to implement the count() aggregate function.
00908 */
00909 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
00910   CountCtx *p;
00911   p = sqlite3_aggregate_context(context, sizeof(*p));
00912   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
00913     p->n++;
00914   }
00915 }   
00916 static void countFinalize(sqlite3_context *context){
00917   CountCtx *p;
00918   p = sqlite3_aggregate_context(context, 0);
00919   sqlite3_result_int64(context, p ? p->n : 0);
00920 }
00921 
00922 /*
00923 ** Routines to implement min() and max() aggregate functions.
00924 */
00925 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
00926   Mem *pArg  = (Mem *)argv[0];
00927   Mem *pBest;
00928 
00929   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
00930   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
00931   if( !pBest ) return;
00932 
00933   if( pBest->flags ){
00934     int max;
00935     int cmp;
00936     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
00937     /* This step function is used for both the min() and max() aggregates,
00938     ** the only difference between the two being that the sense of the
00939     ** comparison is inverted. For the max() aggregate, the
00940     ** sqlite3_user_data() function returns (void *)-1. For min() it
00941     ** returns (void *)db, where db is the sqlite3* database pointer.
00942     ** Therefore the next statement sets variable 'max' to 1 for the max()
00943     ** aggregate, or 0 for min().
00944     */
00945     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
00946     cmp = sqlite3MemCompare(pBest, pArg, pColl);
00947     if( (max && cmp<0) || (!max && cmp>0) ){
00948       sqlite3VdbeMemCopy(pBest, pArg);
00949     }
00950   }else{
00951     sqlite3VdbeMemCopy(pBest, pArg);
00952   }
00953 }
00954 static void minMaxFinalize(sqlite3_context *context){
00955   sqlite3_value *pRes;
00956   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
00957   if( pRes ){
00958     if( pRes->flags ){
00959       sqlite3_result_value(context, pRes);
00960     }
00961     sqlite3VdbeMemRelease(pRes);
00962   }
00963 }
00964 
00965 
00966 /*
00967 ** This function registered all of the above C functions as SQL
00968 ** functions.  This should be the only routine in this file with
00969 ** external linkage.
00970 */
00971 void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
00972   static const struct {
00973      char *zName;
00974      signed char nArg;
00975      u8 argType;           /* 0: none.  1: db  2: (-1) */
00976      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
00977      u8 needCollSeq;
00978      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
00979   } aFuncs[] = {
00980     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
00981     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
00982     { "max",               -1, 2, SQLITE_UTF8,    1, minmaxFunc },
00983     { "max",                0, 2, SQLITE_UTF8,    1, 0          },
00984     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
00985     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
00986     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
00987 #ifndef SQLITE_OMIT_UTF16
00988     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
00989 #endif
00990     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
00991     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
00992     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
00993     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
00994     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
00995     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
00996     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
00997     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
00998     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
00999     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
01000     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
01001     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
01002     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
01003     { "last_insert_rowid",  0, 1, SQLITE_UTF8,    0, last_insert_rowid },
01004     { "changes",            0, 1, SQLITE_UTF8,    0, changes    },
01005     { "total_changes",      0, 1, SQLITE_UTF8,    0, total_changes },
01006 #ifdef SQLITE_SOUNDEX
01007     { "soundex",            1, 0, SQLITE_UTF8, 0, soundexFunc},
01008 #endif
01009 #ifdef SQLITE_TEST
01010     { "randstr",               2, 0, SQLITE_UTF8, 0, randStr    },
01011     { "test_destructor",       1, 1, SQLITE_UTF8, 0, test_destructor},
01012     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
01013     { "test_auxdata",         -1, 0, SQLITE_UTF8, 0, test_auxdata},
01014     { "test_error",            1, 0, SQLITE_UTF8, 0, test_error},
01015 #endif
01016   };
01017   static const struct {
01018     char *zName;
01019     signed char nArg;
01020     u8 argType;
01021     u8 needCollSeq;
01022     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
01023     void (*xFinalize)(sqlite3_context*);
01024   } aAggs[] = {
01025     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
01026     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
01027     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
01028     { "total",  1, 0, 0, sumStep,      totalFinalize    },
01029     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
01030     { "count",  0, 0, 0, countStep,    countFinalize  },
01031     { "count",  1, 0, 0, countStep,    countFinalize  },
01032   };
01033   int i;
01034 
01035   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
01036     void *pArg = 0;
01037     switch( aFuncs[i].argType ){
01038       case 1: pArg = db; break;
01039       case 2: pArg = (void *)(-1); break;
01040     }
01041     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
01042         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
01043     if( aFuncs[i].needCollSeq ){
01044       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName, 
01045           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
01046       if( pFunc && aFuncs[i].needCollSeq ){
01047         pFunc->needCollSeq = 1;
01048       }
01049     }
01050   }
01051 #ifndef SQLITE_OMIT_ALTERTABLE
01052   sqlite3AlterFunctions(db);
01053 #endif
01054 #ifndef SQLITE_OMIT_PARSER
01055   sqlite3AttachFunctions(db);
01056 #endif
01057   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
01058     void *pArg = 0;
01059     switch( aAggs[i].argType ){
01060       case 1: pArg = db; break;
01061       case 2: pArg = (void *)(-1); break;
01062     }
01063     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8, 
01064         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
01065     if( aAggs[i].needCollSeq ){
01066       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
01067           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
01068       if( pFunc && aAggs[i].needCollSeq ){
01069         pFunc->needCollSeq = 1;
01070       }
01071     }
01072   }
01073   sqlite3RegisterDateTimeFunctions(db);
01074 #ifdef SQLITE_SSE
01075   (void)sqlite3SseFunctions(db);
01076 #endif
01077 #ifdef SQLITE_CASE_SENSITIVE_LIKE
01078   sqlite3RegisterLikeFunctions(db, 1);
01079 #else
01080   sqlite3RegisterLikeFunctions(db, 0);
01081 #endif
01082 }
01083 
01084 /*
01085 ** Set the LIKEOPT flag on the 2-argument function with the given name.
01086 */
01087 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
01088   FuncDef *pDef;
01089   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
01090   if( pDef ){
01091     pDef->flags = flagVal;
01092   }
01093 }
01094 
01095 /*
01096 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
01097 ** parameter determines whether or not the LIKE operator is case
01098 ** sensitive.  GLOB is always case sensitive.
01099 */
01100 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
01101   struct compareInfo *pInfo;
01102   if( caseSensitive ){
01103     pInfo = (struct compareInfo*)&likeInfoAlt;
01104   }else{
01105     pInfo = (struct compareInfo*)&likeInfoNorm;
01106   }
01107   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
01108   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
01109   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
01110       (struct compareInfo*)&globInfo, likeFunc, 0,0);
01111   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
01112   setLikeOptFlag(db, "like", 
01113       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
01114 }
01115 
01116 /*
01117 ** pExpr points to an expression which implements a function.  If
01118 ** it is appropriate to apply the LIKE optimization to that function
01119 ** then set aWc[0] through aWc[2] to the wildcard characters and
01120 ** return TRUE.  If the function is not a LIKE-style function then
01121 ** return FALSE.
01122 */
01123 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
01124   FuncDef *pDef;
01125   if( pExpr->op!=TK_FUNCTION ){
01126     return 0;
01127   }
01128   if( pExpr->pList->nExpr!=2 ){
01129     return 0;
01130   }
01131   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
01132                              SQLITE_UTF8, 0);
01133   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
01134     return 0;
01135   }
01136 
01137   /* The memcpy() statement assumes that the wildcard characters are
01138   ** the first three statements in the compareInfo structure.  The
01139   ** asserts() that follow verify that assumption
01140   */
01141   memcpy(aWc, pDef->pUserData, 3);
01142   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
01143   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
01144   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
01145   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
01146   return 1;
01147 }