os/persistentdata/persistentstorage/sql/SQLite364/func.c
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/persistentdata/persistentstorage/sql/SQLite364/func.c	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,1396 @@
     1.4 +/*
     1.5 +** 2002 February 23
     1.6 +**
     1.7 +** The author disclaims copyright to this source code.  In place of
     1.8 +** a legal notice, here is a blessing:
     1.9 +**
    1.10 +**    May you do good and not evil.
    1.11 +**    May you find forgiveness for yourself and forgive others.
    1.12 +**    May you share freely, never taking more than you give.
    1.13 +**
    1.14 +*************************************************************************
    1.15 +** This file contains the C functions that implement various SQL
    1.16 +** functions of SQLite.  
    1.17 +**
    1.18 +** There is only one exported symbol in this file - the function
    1.19 +** sqliteRegisterBuildinFunctions() found at the bottom of the file.
    1.20 +** All other code has file scope.
    1.21 +**
    1.22 +** $Id: func.c,v 1.203 2008/09/03 17:11:16 drh Exp $
    1.23 +*/
    1.24 +#include "sqliteInt.h"
    1.25 +#include <ctype.h>
    1.26 +#include <stdlib.h>
    1.27 +#include <assert.h>
    1.28 +#include "vdbeInt.h"
    1.29 +
    1.30 +/*
    1.31 +** Return the collating function associated with a function.
    1.32 +*/
    1.33 +static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
    1.34 +  return context->pColl;
    1.35 +}
    1.36 +
    1.37 +/*
    1.38 +** Implementation of the non-aggregate min() and max() functions
    1.39 +*/
    1.40 +static void minmaxFunc(
    1.41 +  sqlite3_context *context,
    1.42 +  int argc,
    1.43 +  sqlite3_value **argv
    1.44 +){
    1.45 +  int i;
    1.46 +  int mask;    /* 0 for min() or 0xffffffff for max() */
    1.47 +  int iBest;
    1.48 +  CollSeq *pColl;
    1.49 +
    1.50 +  if( argc==0 ) return;
    1.51 +  mask = sqlite3_user_data(context)==0 ? 0 : -1;
    1.52 +  pColl = sqlite3GetFuncCollSeq(context);
    1.53 +  assert( pColl );
    1.54 +  assert( mask==-1 || mask==0 );
    1.55 +  iBest = 0;
    1.56 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
    1.57 +  for(i=1; i<argc; i++){
    1.58 +    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
    1.59 +    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
    1.60 +      iBest = i;
    1.61 +    }
    1.62 +  }
    1.63 +  sqlite3_result_value(context, argv[iBest]);
    1.64 +}
    1.65 +
    1.66 +/*
    1.67 +** Return the type of the argument.
    1.68 +*/
    1.69 +static void typeofFunc(
    1.70 +  sqlite3_context *context,
    1.71 +  int argc,
    1.72 +  sqlite3_value **argv
    1.73 +){
    1.74 +  const char *z = 0;
    1.75 +  switch( sqlite3_value_type(argv[0]) ){
    1.76 +    case SQLITE_NULL:    z = "null";    break;
    1.77 +    case SQLITE_INTEGER: z = "integer"; break;
    1.78 +    case SQLITE_TEXT:    z = "text";    break;
    1.79 +    case SQLITE_FLOAT:   z = "real";    break;
    1.80 +    case SQLITE_BLOB:    z = "blob";    break;
    1.81 +  }
    1.82 +  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
    1.83 +}
    1.84 +
    1.85 +
    1.86 +/*
    1.87 +** Implementation of the length() function
    1.88 +*/
    1.89 +static void lengthFunc(
    1.90 +  sqlite3_context *context,
    1.91 +  int argc,
    1.92 +  sqlite3_value **argv
    1.93 +){
    1.94 +  int len;
    1.95 +
    1.96 +  assert( argc==1 );
    1.97 +  switch( sqlite3_value_type(argv[0]) ){
    1.98 +    case SQLITE_BLOB:
    1.99 +    case SQLITE_INTEGER:
   1.100 +    case SQLITE_FLOAT: {
   1.101 +      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   1.102 +      break;
   1.103 +    }
   1.104 +    case SQLITE_TEXT: {
   1.105 +      const unsigned char *z = sqlite3_value_text(argv[0]);
   1.106 +      if( z==0 ) return;
   1.107 +      len = 0;
   1.108 +      while( *z ){
   1.109 +        len++;
   1.110 +        SQLITE_SKIP_UTF8(z);
   1.111 +      }
   1.112 +      sqlite3_result_int(context, len);
   1.113 +      break;
   1.114 +    }
   1.115 +    default: {
   1.116 +      sqlite3_result_null(context);
   1.117 +      break;
   1.118 +    }
   1.119 +  }
   1.120 +}
   1.121 +
   1.122 +/*
   1.123 +** Implementation of the abs() function
   1.124 +*/
   1.125 +static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   1.126 +  assert( argc==1 );
   1.127 +  switch( sqlite3_value_type(argv[0]) ){
   1.128 +    case SQLITE_INTEGER: {
   1.129 +      i64 iVal = sqlite3_value_int64(argv[0]);
   1.130 +      if( iVal<0 ){
   1.131 +        if( (iVal<<1)==0 ){
   1.132 +          sqlite3_result_error(context, "integer overflow", -1);
   1.133 +          return;
   1.134 +        }
   1.135 +        iVal = -iVal;
   1.136 +      } 
   1.137 +      sqlite3_result_int64(context, iVal);
   1.138 +      break;
   1.139 +    }
   1.140 +    case SQLITE_NULL: {
   1.141 +      sqlite3_result_null(context);
   1.142 +      break;
   1.143 +    }
   1.144 +    default: {
   1.145 +      double rVal = sqlite3_value_double(argv[0]);
   1.146 +      if( rVal<0 ) rVal = -rVal;
   1.147 +      sqlite3_result_double(context, rVal);
   1.148 +      break;
   1.149 +    }
   1.150 +  }
   1.151 +}
   1.152 +
   1.153 +/*
   1.154 +** Implementation of the substr() function.
   1.155 +**
   1.156 +** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   1.157 +** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   1.158 +** of x.  If x is text, then we actually count UTF-8 characters.
   1.159 +** If x is a blob, then we count bytes.
   1.160 +**
   1.161 +** If p1 is negative, then we begin abs(p1) from the end of x[].
   1.162 +*/
   1.163 +static void substrFunc(
   1.164 +  sqlite3_context *context,
   1.165 +  int argc,
   1.166 +  sqlite3_value **argv
   1.167 +){
   1.168 +  const unsigned char *z;
   1.169 +  const unsigned char *z2;
   1.170 +  int len;
   1.171 +  int p0type;
   1.172 +  i64 p1, p2;
   1.173 +
   1.174 +  assert( argc==3 || argc==2 );
   1.175 +  p0type = sqlite3_value_type(argv[0]);
   1.176 +  if( p0type==SQLITE_BLOB ){
   1.177 +    len = sqlite3_value_bytes(argv[0]);
   1.178 +    z = sqlite3_value_blob(argv[0]);
   1.179 +    if( z==0 ) return;
   1.180 +    assert( len==sqlite3_value_bytes(argv[0]) );
   1.181 +  }else{
   1.182 +    z = sqlite3_value_text(argv[0]);
   1.183 +    if( z==0 ) return;
   1.184 +    len = 0;
   1.185 +    for(z2=z; *z2; len++){
   1.186 +      SQLITE_SKIP_UTF8(z2);
   1.187 +    }
   1.188 +  }
   1.189 +  p1 = sqlite3_value_int(argv[1]);
   1.190 +  if( argc==3 ){
   1.191 +    p2 = sqlite3_value_int(argv[2]);
   1.192 +  }else{
   1.193 +    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   1.194 +  }
   1.195 +  if( p1<0 ){
   1.196 +    p1 += len;
   1.197 +    if( p1<0 ){
   1.198 +      p2 += p1;
   1.199 +      p1 = 0;
   1.200 +    }
   1.201 +  }else if( p1>0 ){
   1.202 +    p1--;
   1.203 +  }
   1.204 +  if( p1+p2>len ){
   1.205 +    p2 = len-p1;
   1.206 +  }
   1.207 +  if( p0type!=SQLITE_BLOB ){
   1.208 +    while( *z && p1 ){
   1.209 +      SQLITE_SKIP_UTF8(z);
   1.210 +      p1--;
   1.211 +    }
   1.212 +    for(z2=z; *z2 && p2; p2--){
   1.213 +      SQLITE_SKIP_UTF8(z2);
   1.214 +    }
   1.215 +    sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
   1.216 +  }else{
   1.217 +    if( p2<0 ) p2 = 0;
   1.218 +    sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
   1.219 +  }
   1.220 +}
   1.221 +
   1.222 +/*
   1.223 +** Implementation of the round() function
   1.224 +*/
   1.225 +static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   1.226 +  int n = 0;
   1.227 +  double r;
   1.228 +  char zBuf[500];  /* larger than the %f representation of the largest double */
   1.229 +  assert( argc==1 || argc==2 );
   1.230 +  if( argc==2 ){
   1.231 +    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   1.232 +    n = sqlite3_value_int(argv[1]);
   1.233 +    if( n>30 ) n = 30;
   1.234 +    if( n<0 ) n = 0;
   1.235 +  }
   1.236 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   1.237 +  r = sqlite3_value_double(argv[0]);
   1.238 +  sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
   1.239 +  sqlite3AtoF(zBuf, &r);
   1.240 +  sqlite3_result_double(context, r);
   1.241 +}
   1.242 +
   1.243 +/*
   1.244 +** Allocate nByte bytes of space using sqlite3_malloc(). If the
   1.245 +** allocation fails, call sqlite3_result_error_nomem() to notify
   1.246 +** the database handle that malloc() has failed.
   1.247 +*/
   1.248 +static void *contextMalloc(sqlite3_context *context, i64 nByte){
   1.249 +  char *z;
   1.250 +  if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
   1.251 +    sqlite3_result_error_toobig(context);
   1.252 +    z = 0;
   1.253 +  }else{
   1.254 +    z = sqlite3Malloc(nByte);
   1.255 +    if( !z && nByte>0 ){
   1.256 +      sqlite3_result_error_nomem(context);
   1.257 +    }
   1.258 +  }
   1.259 +  return z;
   1.260 +}
   1.261 +
   1.262 +/*
   1.263 +** Implementation of the upper() and lower() SQL functions.
   1.264 +*/
   1.265 +static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   1.266 +  char *z1;
   1.267 +  const char *z2;
   1.268 +  int i, n;
   1.269 +  if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
   1.270 +  z2 = (char*)sqlite3_value_text(argv[0]);
   1.271 +  n = sqlite3_value_bytes(argv[0]);
   1.272 +  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   1.273 +  assert( z2==(char*)sqlite3_value_text(argv[0]) );
   1.274 +  if( z2 ){
   1.275 +    z1 = contextMalloc(context, ((i64)n)+1);
   1.276 +    if( z1 ){
   1.277 +      memcpy(z1, z2, n+1);
   1.278 +      for(i=0; z1[i]; i++){
   1.279 +        z1[i] = toupper(z1[i]);
   1.280 +      }
   1.281 +      sqlite3_result_text(context, z1, -1, sqlite3_free);
   1.282 +    }
   1.283 +  }
   1.284 +}
   1.285 +static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   1.286 +  char *z1;
   1.287 +  const char *z2;
   1.288 +  int i, n;
   1.289 +  if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
   1.290 +  z2 = (char*)sqlite3_value_text(argv[0]);
   1.291 +  n = sqlite3_value_bytes(argv[0]);
   1.292 +  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   1.293 +  assert( z2==(char*)sqlite3_value_text(argv[0]) );
   1.294 +  if( z2 ){
   1.295 +    z1 = contextMalloc(context, ((i64)n)+1);
   1.296 +    if( z1 ){
   1.297 +      memcpy(z1, z2, n+1);
   1.298 +      for(i=0; z1[i]; i++){
   1.299 +        z1[i] = tolower(z1[i]);
   1.300 +      }
   1.301 +      sqlite3_result_text(context, z1, -1, sqlite3_free);
   1.302 +    }
   1.303 +  }
   1.304 +}
   1.305 +
   1.306 +/*
   1.307 +** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
   1.308 +** All three do the same thing.  They return the first non-NULL
   1.309 +** argument.
   1.310 +*/
   1.311 +static void ifnullFunc(
   1.312 +  sqlite3_context *context,
   1.313 +  int argc,
   1.314 +  sqlite3_value **argv
   1.315 +){
   1.316 +  int i;
   1.317 +  for(i=0; i<argc; i++){
   1.318 +    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
   1.319 +      sqlite3_result_value(context, argv[i]);
   1.320 +      break;
   1.321 +    }
   1.322 +  }
   1.323 +}
   1.324 +
   1.325 +/*
   1.326 +** Implementation of random().  Return a random integer.  
   1.327 +*/
   1.328 +static void randomFunc(
   1.329 +  sqlite3_context *context,
   1.330 +  int argc,
   1.331 +  sqlite3_value **argv
   1.332 +){
   1.333 +  sqlite_int64 r;
   1.334 +  sqlite3_randomness(sizeof(r), &r);
   1.335 +  if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
   1.336 +                          /* can always do abs() of the result */
   1.337 +  sqlite3_result_int64(context, r);
   1.338 +}
   1.339 +
   1.340 +/*
   1.341 +** Implementation of randomblob(N).  Return a random blob
   1.342 +** that is N bytes long.
   1.343 +*/
   1.344 +static void randomBlob(
   1.345 +  sqlite3_context *context,
   1.346 +  int argc,
   1.347 +  sqlite3_value **argv
   1.348 +){
   1.349 +  int n;
   1.350 +  unsigned char *p;
   1.351 +  assert( argc==1 );
   1.352 +  n = sqlite3_value_int(argv[0]);
   1.353 +  if( n<1 ){
   1.354 +    n = 1;
   1.355 +  }
   1.356 +  p = contextMalloc(context, n);
   1.357 +  if( p ){
   1.358 +    sqlite3_randomness(n, p);
   1.359 +    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   1.360 +  }
   1.361 +}
   1.362 +
   1.363 +/*
   1.364 +** Implementation of the last_insert_rowid() SQL function.  The return
   1.365 +** value is the same as the sqlite3_last_insert_rowid() API function.
   1.366 +*/
   1.367 +static void last_insert_rowid(
   1.368 +  sqlite3_context *context, 
   1.369 +  int arg, 
   1.370 +  sqlite3_value **argv
   1.371 +){
   1.372 +  sqlite3 *db = sqlite3_context_db_handle(context);
   1.373 +  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   1.374 +}
   1.375 +
   1.376 +/*
   1.377 +** Implementation of the changes() SQL function.  The return value is the
   1.378 +** same as the sqlite3_changes() API function.
   1.379 +*/
   1.380 +static void changes(
   1.381 +  sqlite3_context *context,
   1.382 +  int arg,
   1.383 +  sqlite3_value **argv
   1.384 +){
   1.385 +  sqlite3 *db = sqlite3_context_db_handle(context);
   1.386 +  sqlite3_result_int(context, sqlite3_changes(db));
   1.387 +}
   1.388 +
   1.389 +/*
   1.390 +** Implementation of the total_changes() SQL function.  The return value is
   1.391 +** the same as the sqlite3_total_changes() API function.
   1.392 +*/
   1.393 +static void total_changes(
   1.394 +  sqlite3_context *context,
   1.395 +  int arg,
   1.396 +  sqlite3_value **argv
   1.397 +){
   1.398 +  sqlite3 *db = sqlite3_context_db_handle(context);
   1.399 +  sqlite3_result_int(context, sqlite3_total_changes(db));
   1.400 +}
   1.401 +
   1.402 +/*
   1.403 +** A structure defining how to do GLOB-style comparisons.
   1.404 +*/
   1.405 +struct compareInfo {
   1.406 +  u8 matchAll;
   1.407 +  u8 matchOne;
   1.408 +  u8 matchSet;
   1.409 +  u8 noCase;
   1.410 +};
   1.411 +
   1.412 +/*
   1.413 +** For LIKE and GLOB matching on EBCDIC machines, assume that every
   1.414 +** character is exactly one byte in size.  Also, all characters are
   1.415 +** able to participate in upper-case-to-lower-case mappings in EBCDIC
   1.416 +** whereas only characters less than 0x80 do in ASCII.
   1.417 +*/
   1.418 +#if defined(SQLITE_EBCDIC)
   1.419 +# define sqlite3Utf8Read(A,B,C)  (*(A++))
   1.420 +# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
   1.421 +#else
   1.422 +# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
   1.423 +#endif
   1.424 +
   1.425 +static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   1.426 +/* The correct SQL-92 behavior is for the LIKE operator to ignore
   1.427 +** case.  Thus  'a' LIKE 'A' would be true. */
   1.428 +static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   1.429 +/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   1.430 +** is case sensitive causing 'a' LIKE 'A' to be false */
   1.431 +static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   1.432 +
   1.433 +/*
   1.434 +** Compare two UTF-8 strings for equality where the first string can
   1.435 +** potentially be a "glob" expression.  Return true (1) if they
   1.436 +** are the same and false (0) if they are different.
   1.437 +**
   1.438 +** Globbing rules:
   1.439 +**
   1.440 +**      '*'       Matches any sequence of zero or more characters.
   1.441 +**
   1.442 +**      '?'       Matches exactly one character.
   1.443 +**
   1.444 +**     [...]      Matches one character from the enclosed list of
   1.445 +**                characters.
   1.446 +**
   1.447 +**     [^...]     Matches one character not in the enclosed list.
   1.448 +**
   1.449 +** With the [...] and [^...] matching, a ']' character can be included
   1.450 +** in the list by making it the first character after '[' or '^'.  A
   1.451 +** range of characters can be specified using '-'.  Example:
   1.452 +** "[a-z]" matches any single lower-case letter.  To match a '-', make
   1.453 +** it the last character in the list.
   1.454 +**
   1.455 +** This routine is usually quick, but can be N**2 in the worst case.
   1.456 +**
   1.457 +** Hints: to match '*' or '?', put them in "[]".  Like this:
   1.458 +**
   1.459 +**         abc[*]xyz        Matches "abc*xyz" only
   1.460 +*/
   1.461 +static int patternCompare(
   1.462 +  const u8 *zPattern,              /* The glob pattern */
   1.463 +  const u8 *zString,               /* The string to compare against the glob */
   1.464 +  const struct compareInfo *pInfo, /* Information about how to do the compare */
   1.465 +  const int esc                    /* The escape character */
   1.466 +){
   1.467 +  int c, c2;
   1.468 +  int invert;
   1.469 +  int seen;
   1.470 +  u8 matchOne = pInfo->matchOne;
   1.471 +  u8 matchAll = pInfo->matchAll;
   1.472 +  u8 matchSet = pInfo->matchSet;
   1.473 +  u8 noCase = pInfo->noCase; 
   1.474 +  int prevEscape = 0;     /* True if the previous character was 'escape' */
   1.475 +
   1.476 +  while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
   1.477 +    if( !prevEscape && c==matchAll ){
   1.478 +      while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
   1.479 +               || c == matchOne ){
   1.480 +        if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
   1.481 +          return 0;
   1.482 +        }
   1.483 +      }
   1.484 +      if( c==0 ){
   1.485 +        return 1;
   1.486 +      }else if( c==esc ){
   1.487 +        c = sqlite3Utf8Read(zPattern, 0, &zPattern);
   1.488 +        if( c==0 ){
   1.489 +          return 0;
   1.490 +        }
   1.491 +      }else if( c==matchSet ){
   1.492 +        assert( esc==0 );         /* This is GLOB, not LIKE */
   1.493 +        assert( matchSet<0x80 );  /* '[' is a single-byte character */
   1.494 +        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   1.495 +          SQLITE_SKIP_UTF8(zString);
   1.496 +        }
   1.497 +        return *zString!=0;
   1.498 +      }
   1.499 +      while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
   1.500 +        if( noCase ){
   1.501 +          GlogUpperToLower(c2);
   1.502 +          GlogUpperToLower(c);
   1.503 +          while( c2 != 0 && c2 != c ){
   1.504 +            c2 = sqlite3Utf8Read(zString, 0, &zString);
   1.505 +            GlogUpperToLower(c2);
   1.506 +          }
   1.507 +        }else{
   1.508 +          while( c2 != 0 && c2 != c ){
   1.509 +            c2 = sqlite3Utf8Read(zString, 0, &zString);
   1.510 +          }
   1.511 +        }
   1.512 +        if( c2==0 ) return 0;
   1.513 +        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   1.514 +      }
   1.515 +      return 0;
   1.516 +    }else if( !prevEscape && c==matchOne ){
   1.517 +      if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
   1.518 +        return 0;
   1.519 +      }
   1.520 +    }else if( c==matchSet ){
   1.521 +      int prior_c = 0;
   1.522 +      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   1.523 +      seen = 0;
   1.524 +      invert = 0;
   1.525 +      c = sqlite3Utf8Read(zString, 0, &zString);
   1.526 +      if( c==0 ) return 0;
   1.527 +      c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
   1.528 +      if( c2=='^' ){
   1.529 +        invert = 1;
   1.530 +        c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
   1.531 +      }
   1.532 +      if( c2==']' ){
   1.533 +        if( c==']' ) seen = 1;
   1.534 +        c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
   1.535 +      }
   1.536 +      while( c2 && c2!=']' ){
   1.537 +        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   1.538 +          c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
   1.539 +          if( c>=prior_c && c<=c2 ) seen = 1;
   1.540 +          prior_c = 0;
   1.541 +        }else{
   1.542 +          if( c==c2 ){
   1.543 +            seen = 1;
   1.544 +          }
   1.545 +          prior_c = c2;
   1.546 +        }
   1.547 +        c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
   1.548 +      }
   1.549 +      if( c2==0 || (seen ^ invert)==0 ){
   1.550 +        return 0;
   1.551 +      }
   1.552 +    }else if( esc==c && !prevEscape ){
   1.553 +      prevEscape = 1;
   1.554 +    }else{
   1.555 +      c2 = sqlite3Utf8Read(zString, 0, &zString);
   1.556 +      if( noCase ){
   1.557 +        GlogUpperToLower(c);
   1.558 +        GlogUpperToLower(c2);
   1.559 +      }
   1.560 +      if( c!=c2 ){
   1.561 +        return 0;
   1.562 +      }
   1.563 +      prevEscape = 0;
   1.564 +    }
   1.565 +  }
   1.566 +  return *zString==0;
   1.567 +}
   1.568 +
   1.569 +/*
   1.570 +** Count the number of times that the LIKE operator (or GLOB which is
   1.571 +** just a variation of LIKE) gets called.  This is used for testing
   1.572 +** only.
   1.573 +*/
   1.574 +#ifdef SQLITE_TEST
   1.575 +int sqlite3_like_count = 0;
   1.576 +#endif
   1.577 +
   1.578 +
   1.579 +/*
   1.580 +** Implementation of the like() SQL function.  This function implements
   1.581 +** the build-in LIKE operator.  The first argument to the function is the
   1.582 +** pattern and the second argument is the string.  So, the SQL statements:
   1.583 +**
   1.584 +**       A LIKE B
   1.585 +**
   1.586 +** is implemented as like(B,A).
   1.587 +**
   1.588 +** This same function (with a different compareInfo structure) computes
   1.589 +** the GLOB operator.
   1.590 +*/
   1.591 +void likeFunc(
   1.592 +  sqlite3_context *context, 
   1.593 +  int argc, 
   1.594 +  sqlite3_value **argv
   1.595 +){
   1.596 +  const unsigned char *zA, *zB;
   1.597 +  int escape = 0;
   1.598 +  sqlite3 *db = sqlite3_context_db_handle(context);
   1.599 +
   1.600 +  zB = sqlite3_value_text(argv[0]);
   1.601 +  zA = sqlite3_value_text(argv[1]);
   1.602 +
   1.603 +  /* Limit the length of the LIKE or GLOB pattern to avoid problems
   1.604 +  ** of deep recursion and N*N behavior in patternCompare().
   1.605 +  */
   1.606 +  if( sqlite3_value_bytes(argv[0]) >
   1.607 +        db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   1.608 +    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   1.609 +    return;
   1.610 +  }
   1.611 +  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   1.612 +
   1.613 +  if( argc==3 ){
   1.614 +    /* The escape character string must consist of a single UTF-8 character.
   1.615 +    ** Otherwise, return an error.
   1.616 +    */
   1.617 +    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   1.618 +    if( zEsc==0 ) return;
   1.619 +    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   1.620 +      sqlite3_result_error(context, 
   1.621 +          "ESCAPE expression must be a single character", -1);
   1.622 +      return;
   1.623 +    }
   1.624 +    escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
   1.625 +  }
   1.626 +  if( zA && zB ){
   1.627 +    struct compareInfo *pInfo = sqlite3_user_data(context);
   1.628 +#ifdef SQLITE_TEST
   1.629 +    sqlite3_like_count++;
   1.630 +#endif
   1.631 +    
   1.632 +    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   1.633 +  }
   1.634 +}
   1.635 +
   1.636 +/*
   1.637 +** Implementation of the NULLIF(x,y) function.  The result is the first
   1.638 +** argument if the arguments are different.  The result is NULL if the
   1.639 +** arguments are equal to each other.
   1.640 +*/
   1.641 +static void nullifFunc(
   1.642 +  sqlite3_context *context,
   1.643 +  int argc,
   1.644 +  sqlite3_value **argv
   1.645 +){
   1.646 +  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   1.647 +  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   1.648 +    sqlite3_result_value(context, argv[0]);
   1.649 +  }
   1.650 +}
   1.651 +
   1.652 +/*
   1.653 +** Implementation of the VERSION(*) function.  The result is the version
   1.654 +** of the SQLite library that is running.
   1.655 +*/
   1.656 +static void versionFunc(
   1.657 +  sqlite3_context *context,
   1.658 +  int argc,
   1.659 +  sqlite3_value **argv
   1.660 +){
   1.661 +  sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
   1.662 +}
   1.663 +
   1.664 +/* Array for converting from half-bytes (nybbles) into ASCII hex
   1.665 +** digits. */
   1.666 +static const char hexdigits[] = {
   1.667 +  '0', '1', '2', '3', '4', '5', '6', '7',
   1.668 +  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
   1.669 +};
   1.670 +
   1.671 +/*
   1.672 +** EXPERIMENTAL - This is not an official function.  The interface may
   1.673 +** change.  This function may disappear.  Do not write code that depends
   1.674 +** on this function.
   1.675 +**
   1.676 +** Implementation of the QUOTE() function.  This function takes a single
   1.677 +** argument.  If the argument is numeric, the return value is the same as
   1.678 +** the argument.  If the argument is NULL, the return value is the string
   1.679 +** "NULL".  Otherwise, the argument is enclosed in single quotes with
   1.680 +** single-quote escapes.
   1.681 +*/
   1.682 +static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   1.683 +  if( argc<1 ) return;
   1.684 +  switch( sqlite3_value_type(argv[0]) ){
   1.685 +    case SQLITE_NULL: {
   1.686 +      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   1.687 +      break;
   1.688 +    }
   1.689 +    case SQLITE_INTEGER:
   1.690 +    case SQLITE_FLOAT: {
   1.691 +      sqlite3_result_value(context, argv[0]);
   1.692 +      break;
   1.693 +    }
   1.694 +    case SQLITE_BLOB: {
   1.695 +      char *zText = 0;
   1.696 +      char const *zBlob = sqlite3_value_blob(argv[0]);
   1.697 +      int nBlob = sqlite3_value_bytes(argv[0]);
   1.698 +      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   1.699 +      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
   1.700 +      if( zText ){
   1.701 +        int i;
   1.702 +        for(i=0; i<nBlob; i++){
   1.703 +          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   1.704 +          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   1.705 +        }
   1.706 +        zText[(nBlob*2)+2] = '\'';
   1.707 +        zText[(nBlob*2)+3] = '\0';
   1.708 +        zText[0] = 'X';
   1.709 +        zText[1] = '\'';
   1.710 +        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   1.711 +        sqlite3_free(zText);
   1.712 +      }
   1.713 +      break;
   1.714 +    }
   1.715 +    case SQLITE_TEXT: {
   1.716 +      int i,j;
   1.717 +      u64 n;
   1.718 +      const unsigned char *zArg = sqlite3_value_text(argv[0]);
   1.719 +      char *z;
   1.720 +
   1.721 +      if( zArg==0 ) return;
   1.722 +      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   1.723 +      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   1.724 +      if( z ){
   1.725 +        z[0] = '\'';
   1.726 +        for(i=0, j=1; zArg[i]; i++){
   1.727 +          z[j++] = zArg[i];
   1.728 +          if( zArg[i]=='\'' ){
   1.729 +            z[j++] = '\'';
   1.730 +          }
   1.731 +        }
   1.732 +        z[j++] = '\'';
   1.733 +        z[j] = 0;
   1.734 +        sqlite3_result_text(context, z, j, sqlite3_free);
   1.735 +      }
   1.736 +    }
   1.737 +  }
   1.738 +}
   1.739 +
   1.740 +/*
   1.741 +** The hex() function.  Interpret the argument as a blob.  Return
   1.742 +** a hexadecimal rendering as text.
   1.743 +*/
   1.744 +static void hexFunc(
   1.745 +  sqlite3_context *context,
   1.746 +  int argc,
   1.747 +  sqlite3_value **argv
   1.748 +){
   1.749 +  int i, n;
   1.750 +  const unsigned char *pBlob;
   1.751 +  char *zHex, *z;
   1.752 +  assert( argc==1 );
   1.753 +  pBlob = sqlite3_value_blob(argv[0]);
   1.754 +  n = sqlite3_value_bytes(argv[0]);
   1.755 +  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   1.756 +  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   1.757 +  if( zHex ){
   1.758 +    for(i=0; i<n; i++, pBlob++){
   1.759 +      unsigned char c = *pBlob;
   1.760 +      *(z++) = hexdigits[(c>>4)&0xf];
   1.761 +      *(z++) = hexdigits[c&0xf];
   1.762 +    }
   1.763 +    *z = 0;
   1.764 +    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   1.765 +  }
   1.766 +}
   1.767 +
   1.768 +/*
   1.769 +** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   1.770 +*/
   1.771 +static void zeroblobFunc(
   1.772 +  sqlite3_context *context,
   1.773 +  int argc,
   1.774 +  sqlite3_value **argv
   1.775 +){
   1.776 +  i64 n;
   1.777 +  assert( argc==1 );
   1.778 +  n = sqlite3_value_int64(argv[0]);
   1.779 +  if( n>SQLITE_MAX_LENGTH ){
   1.780 +    sqlite3_result_error_toobig(context);
   1.781 +  }else{
   1.782 +    sqlite3_result_zeroblob(context, n);
   1.783 +  }
   1.784 +}
   1.785 +
   1.786 +/*
   1.787 +** The replace() function.  Three arguments are all strings: call
   1.788 +** them A, B, and C. The result is also a string which is derived
   1.789 +** from A by replacing every occurance of B with C.  The match
   1.790 +** must be exact.  Collating sequences are not used.
   1.791 +*/
   1.792 +static void replaceFunc(
   1.793 +  sqlite3_context *context,
   1.794 +  int argc,
   1.795 +  sqlite3_value **argv
   1.796 +){
   1.797 +  const unsigned char *zStr;        /* The input string A */
   1.798 +  const unsigned char *zPattern;    /* The pattern string B */
   1.799 +  const unsigned char *zRep;        /* The replacement string C */
   1.800 +  unsigned char *zOut;              /* The output */
   1.801 +  int nStr;                /* Size of zStr */
   1.802 +  int nPattern;            /* Size of zPattern */
   1.803 +  int nRep;                /* Size of zRep */
   1.804 +  i64 nOut;                /* Maximum size of zOut */
   1.805 +  int loopLimit;           /* Last zStr[] that might match zPattern[] */
   1.806 +  int i, j;                /* Loop counters */
   1.807 +
   1.808 +  assert( argc==3 );
   1.809 +  zStr = sqlite3_value_text(argv[0]);
   1.810 +  if( zStr==0 ) return;
   1.811 +  nStr = sqlite3_value_bytes(argv[0]);
   1.812 +  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   1.813 +  zPattern = sqlite3_value_text(argv[1]);
   1.814 +  if( zPattern==0 || zPattern[0]==0 ) return;
   1.815 +  nPattern = sqlite3_value_bytes(argv[1]);
   1.816 +  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   1.817 +  zRep = sqlite3_value_text(argv[2]);
   1.818 +  if( zRep==0 ) return;
   1.819 +  nRep = sqlite3_value_bytes(argv[2]);
   1.820 +  assert( zRep==sqlite3_value_text(argv[2]) );
   1.821 +  nOut = nStr + 1;
   1.822 +  assert( nOut<SQLITE_MAX_LENGTH );
   1.823 +  zOut = contextMalloc(context, (i64)nOut);
   1.824 +  if( zOut==0 ){
   1.825 +    return;
   1.826 +  }
   1.827 +  loopLimit = nStr - nPattern;  
   1.828 +  for(i=j=0; i<=loopLimit; i++){
   1.829 +    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   1.830 +      zOut[j++] = zStr[i];
   1.831 +    }else{
   1.832 +      u8 *zOld;
   1.833 +      sqlite3 *db = sqlite3_context_db_handle(context);
   1.834 +      nOut += nRep - nPattern;
   1.835 +      if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
   1.836 +        sqlite3_result_error_toobig(context);
   1.837 +        sqlite3DbFree(db, zOut);
   1.838 +        return;
   1.839 +      }
   1.840 +      zOld = zOut;
   1.841 +      zOut = sqlite3_realloc(zOut, (int)nOut);
   1.842 +      if( zOut==0 ){
   1.843 +        sqlite3_result_error_nomem(context);
   1.844 +        sqlite3DbFree(db, zOld);
   1.845 +        return;
   1.846 +      }
   1.847 +      memcpy(&zOut[j], zRep, nRep);
   1.848 +      j += nRep;
   1.849 +      i += nPattern-1;
   1.850 +    }
   1.851 +  }
   1.852 +  assert( j+nStr-i+1==nOut );
   1.853 +  memcpy(&zOut[j], &zStr[i], nStr-i);
   1.854 +  j += nStr - i;
   1.855 +  assert( j<=nOut );
   1.856 +  zOut[j] = 0;
   1.857 +  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   1.858 +}
   1.859 +
   1.860 +/*
   1.861 +** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   1.862 +** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   1.863 +*/
   1.864 +static void trimFunc(
   1.865 +  sqlite3_context *context,
   1.866 +  int argc,
   1.867 +  sqlite3_value **argv
   1.868 +){
   1.869 +  const unsigned char *zIn;         /* Input string */
   1.870 +  const unsigned char *zCharSet;    /* Set of characters to trim */
   1.871 +  int nIn;                          /* Number of bytes in input */
   1.872 +  int flags;                        /* 1: trimleft  2: trimright  3: trim */
   1.873 +  int i;                            /* Loop counter */
   1.874 +  unsigned char *aLen;              /* Length of each character in zCharSet */
   1.875 +  unsigned char **azChar;           /* Individual characters in zCharSet */
   1.876 +  int nChar;                        /* Number of characters in zCharSet */
   1.877 +
   1.878 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   1.879 +    return;
   1.880 +  }
   1.881 +  zIn = sqlite3_value_text(argv[0]);
   1.882 +  if( zIn==0 ) return;
   1.883 +  nIn = sqlite3_value_bytes(argv[0]);
   1.884 +  assert( zIn==sqlite3_value_text(argv[0]) );
   1.885 +  if( argc==1 ){
   1.886 +    static const unsigned char lenOne[] = { 1 };
   1.887 +    static unsigned char * const azOne[] = { (u8*)" " };
   1.888 +    nChar = 1;
   1.889 +    aLen = (u8*)lenOne;
   1.890 +    azChar = (unsigned char **)azOne;
   1.891 +    zCharSet = 0;
   1.892 +  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   1.893 +    return;
   1.894 +  }else{
   1.895 +    const unsigned char *z;
   1.896 +    for(z=zCharSet, nChar=0; *z; nChar++){
   1.897 +      SQLITE_SKIP_UTF8(z);
   1.898 +    }
   1.899 +    if( nChar>0 ){
   1.900 +      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   1.901 +      if( azChar==0 ){
   1.902 +        return;
   1.903 +      }
   1.904 +      aLen = (unsigned char*)&azChar[nChar];
   1.905 +      for(z=zCharSet, nChar=0; *z; nChar++){
   1.906 +        azChar[nChar] = (unsigned char *)z;
   1.907 +        SQLITE_SKIP_UTF8(z);
   1.908 +        aLen[nChar] = z - azChar[nChar];
   1.909 +      }
   1.910 +    }
   1.911 +  }
   1.912 +  if( nChar>0 ){
   1.913 +    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   1.914 +    if( flags & 1 ){
   1.915 +      while( nIn>0 ){
   1.916 +        int len;
   1.917 +        for(i=0; i<nChar; i++){
   1.918 +          len = aLen[i];
   1.919 +          if( memcmp(zIn, azChar[i], len)==0 ) break;
   1.920 +        }
   1.921 +        if( i>=nChar ) break;
   1.922 +        zIn += len;
   1.923 +        nIn -= len;
   1.924 +      }
   1.925 +    }
   1.926 +    if( flags & 2 ){
   1.927 +      while( nIn>0 ){
   1.928 +        int len;
   1.929 +        for(i=0; i<nChar; i++){
   1.930 +          len = aLen[i];
   1.931 +          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   1.932 +        }
   1.933 +        if( i>=nChar ) break;
   1.934 +        nIn -= len;
   1.935 +      }
   1.936 +    }
   1.937 +    if( zCharSet ){
   1.938 +      sqlite3_free(azChar);
   1.939 +    }
   1.940 +  }
   1.941 +  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   1.942 +}
   1.943 +
   1.944 +
   1.945 +#ifdef SQLITE_SOUNDEX
   1.946 +/*
   1.947 +** Compute the soundex encoding of a word.
   1.948 +*/
   1.949 +static void soundexFunc(
   1.950 +  sqlite3_context *context,
   1.951 +  int argc,
   1.952 +  sqlite3_value **argv
   1.953 +){
   1.954 +  char zResult[8];
   1.955 +  const u8 *zIn;
   1.956 +  int i, j;
   1.957 +  static const unsigned char iCode[] = {
   1.958 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   1.959 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   1.960 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   1.961 +    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   1.962 +    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   1.963 +    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   1.964 +    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   1.965 +    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   1.966 +  };
   1.967 +  assert( argc==1 );
   1.968 +  zIn = (u8*)sqlite3_value_text(argv[0]);
   1.969 +  if( zIn==0 ) zIn = (u8*)"";
   1.970 +  for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
   1.971 +  if( zIn[i] ){
   1.972 +    u8 prevcode = iCode[zIn[i]&0x7f];
   1.973 +    zResult[0] = toupper(zIn[i]);
   1.974 +    for(j=1; j<4 && zIn[i]; i++){
   1.975 +      int code = iCode[zIn[i]&0x7f];
   1.976 +      if( code>0 ){
   1.977 +        if( code!=prevcode ){
   1.978 +          prevcode = code;
   1.979 +          zResult[j++] = code + '0';
   1.980 +        }
   1.981 +      }else{
   1.982 +        prevcode = 0;
   1.983 +      }
   1.984 +    }
   1.985 +    while( j<4 ){
   1.986 +      zResult[j++] = '0';
   1.987 +    }
   1.988 +    zResult[j] = 0;
   1.989 +    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   1.990 +  }else{
   1.991 +    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   1.992 +  }
   1.993 +}
   1.994 +#endif
   1.995 +
   1.996 +#ifndef SQLITE_OMIT_LOAD_EXTENSION
   1.997 +/*
   1.998 +** A function that loads a shared-library extension then returns NULL.
   1.999 +*/
  1.1000 +static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  1.1001 +  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  1.1002 +  const char *zProc;
  1.1003 +  sqlite3 *db = sqlite3_context_db_handle(context);
  1.1004 +  char *zErrMsg = 0;
  1.1005 +
  1.1006 +  if( argc==2 ){
  1.1007 +    zProc = (const char *)sqlite3_value_text(argv[1]);
  1.1008 +  }else{
  1.1009 +    zProc = 0;
  1.1010 +  }
  1.1011 +  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  1.1012 +    sqlite3_result_error(context, zErrMsg, -1);
  1.1013 +    sqlite3_free(zErrMsg);
  1.1014 +  }
  1.1015 +}
  1.1016 +#endif
  1.1017 +
  1.1018 +
  1.1019 +/*
  1.1020 +** An instance of the following structure holds the context of a
  1.1021 +** sum() or avg() aggregate computation.
  1.1022 +*/
  1.1023 +typedef struct SumCtx SumCtx;
  1.1024 +struct SumCtx {
  1.1025 +  double rSum;      /* Floating point sum */
  1.1026 +  i64 iSum;         /* Integer sum */   
  1.1027 +  i64 cnt;          /* Number of elements summed */
  1.1028 +  u8 overflow;      /* True if integer overflow seen */
  1.1029 +  u8 approx;        /* True if non-integer value was input to the sum */
  1.1030 +};
  1.1031 +
  1.1032 +/*
  1.1033 +** Routines used to compute the sum, average, and total.
  1.1034 +**
  1.1035 +** The SUM() function follows the (broken) SQL standard which means
  1.1036 +** that it returns NULL if it sums over no inputs.  TOTAL returns
  1.1037 +** 0.0 in that case.  In addition, TOTAL always returns a float where
  1.1038 +** SUM might return an integer if it never encounters a floating point
  1.1039 +** value.  TOTAL never fails, but SUM might through an exception if
  1.1040 +** it overflows an integer.
  1.1041 +*/
  1.1042 +static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  1.1043 +  SumCtx *p;
  1.1044 +  int type;
  1.1045 +  assert( argc==1 );
  1.1046 +  p = sqlite3_aggregate_context(context, sizeof(*p));
  1.1047 +  type = sqlite3_value_numeric_type(argv[0]);
  1.1048 +  if( p && type!=SQLITE_NULL ){
  1.1049 +    p->cnt++;
  1.1050 +    if( type==SQLITE_INTEGER ){
  1.1051 +      i64 v = sqlite3_value_int64(argv[0]);
  1.1052 +      p->rSum += v;
  1.1053 +      if( (p->approx|p->overflow)==0 ){
  1.1054 +        i64 iNewSum = p->iSum + v;
  1.1055 +        int s1 = p->iSum >> (sizeof(i64)*8-1);
  1.1056 +        int s2 = v       >> (sizeof(i64)*8-1);
  1.1057 +        int s3 = iNewSum >> (sizeof(i64)*8-1);
  1.1058 +        p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
  1.1059 +        p->iSum = iNewSum;
  1.1060 +      }
  1.1061 +    }else{
  1.1062 +      p->rSum += sqlite3_value_double(argv[0]);
  1.1063 +      p->approx = 1;
  1.1064 +    }
  1.1065 +  }
  1.1066 +}
  1.1067 +static void sumFinalize(sqlite3_context *context){
  1.1068 +  SumCtx *p;
  1.1069 +  p = sqlite3_aggregate_context(context, 0);
  1.1070 +  if( p && p->cnt>0 ){
  1.1071 +    if( p->overflow ){
  1.1072 +      sqlite3_result_error(context,"integer overflow",-1);
  1.1073 +    }else if( p->approx ){
  1.1074 +      sqlite3_result_double(context, p->rSum);
  1.1075 +    }else{
  1.1076 +      sqlite3_result_int64(context, p->iSum);
  1.1077 +    }
  1.1078 +  }
  1.1079 +}
  1.1080 +static void avgFinalize(sqlite3_context *context){
  1.1081 +  SumCtx *p;
  1.1082 +  p = sqlite3_aggregate_context(context, 0);
  1.1083 +  if( p && p->cnt>0 ){
  1.1084 +    sqlite3_result_double(context, p->rSum/(double)p->cnt);
  1.1085 +  }
  1.1086 +}
  1.1087 +static void totalFinalize(sqlite3_context *context){
  1.1088 +  SumCtx *p;
  1.1089 +  p = sqlite3_aggregate_context(context, 0);
  1.1090 +  sqlite3_result_double(context, p ? p->rSum : 0.0);
  1.1091 +}
  1.1092 +
  1.1093 +/*
  1.1094 +** The following structure keeps track of state information for the
  1.1095 +** count() aggregate function.
  1.1096 +*/
  1.1097 +typedef struct CountCtx CountCtx;
  1.1098 +struct CountCtx {
  1.1099 +  i64 n;
  1.1100 +};
  1.1101 +
  1.1102 +/*
  1.1103 +** Routines to implement the count() aggregate function.
  1.1104 +*/
  1.1105 +static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  1.1106 +  CountCtx *p;
  1.1107 +  p = sqlite3_aggregate_context(context, sizeof(*p));
  1.1108 +  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  1.1109 +    p->n++;
  1.1110 +  }
  1.1111 +}   
  1.1112 +static void countFinalize(sqlite3_context *context){
  1.1113 +  CountCtx *p;
  1.1114 +  p = sqlite3_aggregate_context(context, 0);
  1.1115 +  sqlite3_result_int64(context, p ? p->n : 0);
  1.1116 +}
  1.1117 +
  1.1118 +/*
  1.1119 +** Routines to implement min() and max() aggregate functions.
  1.1120 +*/
  1.1121 +static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  1.1122 +  Mem *pArg  = (Mem *)argv[0];
  1.1123 +  Mem *pBest;
  1.1124 +
  1.1125 +  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  1.1126 +  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  1.1127 +  if( !pBest ) return;
  1.1128 +
  1.1129 +  if( pBest->flags ){
  1.1130 +    int max;
  1.1131 +    int cmp;
  1.1132 +    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  1.1133 +    /* This step function is used for both the min() and max() aggregates,
  1.1134 +    ** the only difference between the two being that the sense of the
  1.1135 +    ** comparison is inverted. For the max() aggregate, the
  1.1136 +    ** sqlite3_user_data() function returns (void *)-1. For min() it
  1.1137 +    ** returns (void *)db, where db is the sqlite3* database pointer.
  1.1138 +    ** Therefore the next statement sets variable 'max' to 1 for the max()
  1.1139 +    ** aggregate, or 0 for min().
  1.1140 +    */
  1.1141 +    max = sqlite3_user_data(context)!=0;
  1.1142 +    cmp = sqlite3MemCompare(pBest, pArg, pColl);
  1.1143 +    if( (max && cmp<0) || (!max && cmp>0) ){
  1.1144 +      sqlite3VdbeMemCopy(pBest, pArg);
  1.1145 +    }
  1.1146 +  }else{
  1.1147 +    sqlite3VdbeMemCopy(pBest, pArg);
  1.1148 +  }
  1.1149 +}
  1.1150 +static void minMaxFinalize(sqlite3_context *context){
  1.1151 +  sqlite3_value *pRes;
  1.1152 +  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  1.1153 +  if( pRes ){
  1.1154 +    if( pRes->flags ){
  1.1155 +      sqlite3_result_value(context, pRes);
  1.1156 +    }
  1.1157 +    sqlite3VdbeMemRelease(pRes);
  1.1158 +  }
  1.1159 +}
  1.1160 +
  1.1161 +/*
  1.1162 +** group_concat(EXPR, ?SEPARATOR?)
  1.1163 +*/
  1.1164 +static void groupConcatStep(
  1.1165 +  sqlite3_context *context,
  1.1166 +  int argc,
  1.1167 +  sqlite3_value **argv
  1.1168 +){
  1.1169 +  const char *zVal;
  1.1170 +  StrAccum *pAccum;
  1.1171 +  const char *zSep;
  1.1172 +  int nVal, nSep, i;
  1.1173 +  if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  1.1174 +  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  1.1175 +
  1.1176 +  if( pAccum ){
  1.1177 +    sqlite3 *db = sqlite3_context_db_handle(context);
  1.1178 +    pAccum->useMalloc = 1;
  1.1179 +    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  1.1180 +    if( pAccum->nChar ){
  1.1181 +      if( argc>1 ){
  1.1182 +        zSep = (char*)sqlite3_value_text(argv[argc-1]);
  1.1183 +        nSep = sqlite3_value_bytes(argv[argc-1]);
  1.1184 +      }else{
  1.1185 +        zSep = ",";
  1.1186 +        nSep = 1;
  1.1187 +      }
  1.1188 +      sqlite3StrAccumAppend(pAccum, zSep, nSep);
  1.1189 +    }
  1.1190 +    i = 0;
  1.1191 +    do{
  1.1192 +      zVal = (char*)sqlite3_value_text(argv[i]);
  1.1193 +      nVal = sqlite3_value_bytes(argv[i]);
  1.1194 +      sqlite3StrAccumAppend(pAccum, zVal, nVal);
  1.1195 +      i++;
  1.1196 +    }while( i<argc-1 );
  1.1197 +  }
  1.1198 +}
  1.1199 +static void groupConcatFinalize(sqlite3_context *context){
  1.1200 +  StrAccum *pAccum;
  1.1201 +  pAccum = sqlite3_aggregate_context(context, 0);
  1.1202 +  if( pAccum ){
  1.1203 +    if( pAccum->tooBig ){
  1.1204 +      sqlite3_result_error_toobig(context);
  1.1205 +    }else if( pAccum->mallocFailed ){
  1.1206 +      sqlite3_result_error_nomem(context);
  1.1207 +    }else{    
  1.1208 +      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
  1.1209 +                          sqlite3_free);
  1.1210 +    }
  1.1211 +  }
  1.1212 +}
  1.1213 +
  1.1214 +/*
  1.1215 +** This function registered all of the above C functions as SQL
  1.1216 +** functions.  This should be the only routine in this file with
  1.1217 +** external linkage.
  1.1218 +*/
  1.1219 +void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  1.1220 +#ifndef SQLITE_OMIT_ALTERTABLE
  1.1221 +  sqlite3AlterFunctions(db);
  1.1222 +#endif
  1.1223 +#ifndef SQLITE_OMIT_PARSER
  1.1224 +  sqlite3AttachFunctions(db);
  1.1225 +#endif
  1.1226 +  if( !db->mallocFailed ){
  1.1227 +    int rc = sqlite3_overload_function(db, "MATCH", 2);
  1.1228 +    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  1.1229 +    if( rc==SQLITE_NOMEM ){
  1.1230 +      db->mallocFailed = 1;
  1.1231 +    }
  1.1232 +  }
  1.1233 +#ifdef SQLITE_SSE
  1.1234 +  (void)sqlite3SseFunctions(db);
  1.1235 +#endif
  1.1236 +}
  1.1237 +
  1.1238 +/*
  1.1239 +** Set the LIKEOPT flag on the 2-argument function with the given name.
  1.1240 +*/
  1.1241 +static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
  1.1242 +  FuncDef *pDef;
  1.1243 +  pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
  1.1244 +  if( pDef ){
  1.1245 +    pDef->flags = flagVal;
  1.1246 +  }
  1.1247 +}
  1.1248 +
  1.1249 +/*
  1.1250 +** Register the built-in LIKE and GLOB functions.  The caseSensitive
  1.1251 +** parameter determines whether or not the LIKE operator is case
  1.1252 +** sensitive.  GLOB is always case sensitive.
  1.1253 +*/
  1.1254 +void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  1.1255 +  struct compareInfo *pInfo;
  1.1256 +  if( caseSensitive ){
  1.1257 +    pInfo = (struct compareInfo*)&likeInfoAlt;
  1.1258 +  }else{
  1.1259 +    pInfo = (struct compareInfo*)&likeInfoNorm;
  1.1260 +  }
  1.1261 +  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
  1.1262 +  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
  1.1263 +  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
  1.1264 +      (struct compareInfo*)&globInfo, likeFunc, 0,0);
  1.1265 +  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  1.1266 +  setLikeOptFlag(db, "like", 
  1.1267 +      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  1.1268 +}
  1.1269 +
  1.1270 +/*
  1.1271 +** pExpr points to an expression which implements a function.  If
  1.1272 +** it is appropriate to apply the LIKE optimization to that function
  1.1273 +** then set aWc[0] through aWc[2] to the wildcard characters and
  1.1274 +** return TRUE.  If the function is not a LIKE-style function then
  1.1275 +** return FALSE.
  1.1276 +*/
  1.1277 +int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  1.1278 +  FuncDef *pDef;
  1.1279 +  if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
  1.1280 +    return 0;
  1.1281 +  }
  1.1282 +  if( pExpr->pList->nExpr!=2 ){
  1.1283 +    return 0;
  1.1284 +  }
  1.1285 +  pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
  1.1286 +                             SQLITE_UTF8, 0);
  1.1287 +  if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  1.1288 +    return 0;
  1.1289 +  }
  1.1290 +
  1.1291 +  /* The memcpy() statement assumes that the wildcard characters are
  1.1292 +  ** the first three statements in the compareInfo structure.  The
  1.1293 +  ** asserts() that follow verify that assumption
  1.1294 +  */
  1.1295 +  memcpy(aWc, pDef->pUserData, 3);
  1.1296 +  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  1.1297 +  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  1.1298 +  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  1.1299 +  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  1.1300 +  return 1;
  1.1301 +}
  1.1302 +
  1.1303 +/*
  1.1304 +** All all of the FuncDef structures in the aBuiltinFunc[] array above
  1.1305 +** to the global function hash table.  This occurs at start-time (as
  1.1306 +** a consequence of calling sqlite3_initialize()).
  1.1307 +**
  1.1308 +** After this routine runs
  1.1309 +*/
  1.1310 +void sqlite3RegisterGlobalFunctions(void){
  1.1311 +  /*
  1.1312 +  ** The following array holds FuncDef structures for all of the functions
  1.1313 +  ** defined in this file.
  1.1314 +  **
  1.1315 +  ** The array cannot be constant since changes are made to the
  1.1316 +  ** FuncDef.pHash elements at start-time.  The elements of this array
  1.1317 +  ** are read-only after initialization is complete.
  1.1318 +  */
  1.1319 +  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  1.1320 +    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
  1.1321 +    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
  1.1322 +    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
  1.1323 +    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
  1.1324 +    FUNCTION(trim,               1, 3, 0, trimFunc         ),
  1.1325 +    FUNCTION(trim,               2, 3, 0, trimFunc         ),
  1.1326 +    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
  1.1327 +    FUNCTION(min,                0, 0, 1, 0                ),
  1.1328 +    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
  1.1329 +    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
  1.1330 +    FUNCTION(max,                0, 1, 1, 0                ),
  1.1331 +    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
  1.1332 +    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
  1.1333 +    FUNCTION(length,             1, 0, 0, lengthFunc       ),
  1.1334 +    FUNCTION(substr,             2, 0, 0, substrFunc       ),
  1.1335 +    FUNCTION(substr,             3, 0, 0, substrFunc       ),
  1.1336 +    FUNCTION(abs,                1, 0, 0, absFunc          ),
  1.1337 +    FUNCTION(round,              1, 0, 0, roundFunc        ),
  1.1338 +    FUNCTION(round,              2, 0, 0, roundFunc        ),
  1.1339 +    FUNCTION(upper,              1, 0, 0, upperFunc        ),
  1.1340 +    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
  1.1341 +    FUNCTION(coalesce,           1, 0, 0, 0                ),
  1.1342 +    FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
  1.1343 +    FUNCTION(coalesce,           0, 0, 0, 0                ),
  1.1344 +    FUNCTION(hex,                1, 0, 0, hexFunc          ),
  1.1345 +    FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
  1.1346 +    FUNCTION(random,            -1, 0, 0, randomFunc       ),
  1.1347 +    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
  1.1348 +    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
  1.1349 +    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
  1.1350 +    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
  1.1351 +    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
  1.1352 +    FUNCTION(changes,            0, 0, 0, changes          ),
  1.1353 +    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
  1.1354 +    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
  1.1355 +    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
  1.1356 +  #ifdef SQLITE_SOUNDEX
  1.1357 +    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
  1.1358 +  #endif
  1.1359 +  #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1.1360 +    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
  1.1361 +    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
  1.1362 +  #endif
  1.1363 +    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
  1.1364 +    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
  1.1365 +    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
  1.1366 +    AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
  1.1367 +    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
  1.1368 +    AGGREGATE(group_concat,     -1, 0, 0, groupConcatStep, groupConcatFinalize),
  1.1369 +  
  1.1370 +    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  1.1371 +  #ifdef SQLITE_CASE_SENSITIVE_LIKE
  1.1372 +    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  1.1373 +    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  1.1374 +  #else
  1.1375 +    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  1.1376 +    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  1.1377 +  #endif
  1.1378 +  };
  1.1379 +
  1.1380 +  int i;
  1.1381 +  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  1.1382 +  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  1.1383 +
  1.1384 +  for(i=0; i<ArraySize(aBuiltinFunc); i++){
  1.1385 +    sqlite3FuncDefInsert(pHash, &aFunc[i]);
  1.1386 +  }
  1.1387 +  sqlite3RegisterDateTimeFunctions();
  1.1388 +}
  1.1389 +
  1.1390 +int sqlite3RegisterInternalUtf8Like(sqlite3 *db){
  1.1391 +  int rc;
  1.1392 +  void *pCtx = (void *)&likeInfoNorm;
  1.1393 +  rc = sqlite3_create_function(db, "like", 2, SQLITE_UTF8, pCtx, likeFunc, 0, 0);
  1.1394 +  if( rc!=SQLITE_OK ) return rc;
  1.1395 +  rc = sqlite3_create_function(db, "like", 3, SQLITE_UTF8, pCtx, likeFunc, 0, 0);
  1.1396 +  if( rc!=SQLITE_OK ) return rc;
  1.1397 +  setLikeOptFlag(db, "like", SQLITE_FUNC_LIKE);
  1.1398 +  return SQLITE_OK;
  1.1399 +}