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