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