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