xref: /sqlite-3.40.0/src/func.c (revision 592ac8cb)
1dc04c583Sdrh /*
2dc04c583Sdrh ** 2002 February 23
3dc04c583Sdrh **
4dc04c583Sdrh ** The author disclaims copyright to this source code.  In place of
5dc04c583Sdrh ** a legal notice, here is a blessing:
6dc04c583Sdrh **
7dc04c583Sdrh **    May you do good and not evil.
8dc04c583Sdrh **    May you find forgiveness for yourself and forgive others.
9dc04c583Sdrh **    May you share freely, never taking more than you give.
10dc04c583Sdrh **
11dc04c583Sdrh *************************************************************************
12dc04c583Sdrh ** This file contains the C functions that implement various SQL
13dc04c583Sdrh ** functions of SQLite.
14dc04c583Sdrh **
15dc04c583Sdrh ** There is only one exported symbol in this file - the function
16dc04c583Sdrh ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
17dc04c583Sdrh ** All other code has file scope.
18dc04c583Sdrh **
19*592ac8cbSdrh ** $Id: func.c,v 1.103 2005/08/13 03:07:47 drh Exp $
20dc04c583Sdrh */
21b659e9bfSdrh #include "sqliteInt.h"
22dc04c583Sdrh #include <ctype.h>
23d3a149efSdrh #include <math.h>
24d3a149efSdrh #include <stdlib.h>
250bce8354Sdrh #include <assert.h>
2688208050Sdanielk1977 #include "vdbeInt.h"
27771d8c3bSdrh #include "os.h"
280bce8354Sdrh 
29dc1bdc4fSdanielk1977 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
30dc1bdc4fSdanielk1977   return context->pColl;
31dc1bdc4fSdanielk1977 }
32dc1bdc4fSdanielk1977 
330bce8354Sdrh /*
340bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
350bce8354Sdrh */
36f9b596ebSdrh static void minmaxFunc(
37f9b596ebSdrh   sqlite3_context *context,
38f9b596ebSdrh   int argc,
39f9b596ebSdrh   sqlite3_value **argv
40f9b596ebSdrh ){
410bce8354Sdrh   int i;
42268380caSdrh   int mask;    /* 0 for min() or 0xffffffff for max() */
43f9b596ebSdrh   int iBest;
44dc1bdc4fSdanielk1977   CollSeq *pColl;
450bce8354Sdrh 
4689425d5eSdrh   if( argc==0 ) return;
47c44af71cSdrh   mask = sqlite3_user_data(context)==0 ? 0 : -1;
48dc1bdc4fSdanielk1977   pColl = sqlite3GetFuncCollSeq(context);
49dc1bdc4fSdanielk1977   assert( pColl );
50c572ef7fSdanielk1977   assert( mask==-1 || mask==0 );
51f9b596ebSdrh   iBest = 0;
529c054830Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
53f9b596ebSdrh   for(i=1; i<argc; i++){
549c054830Sdrh     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
55dc1bdc4fSdanielk1977     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
56f9b596ebSdrh       iBest = i;
570bce8354Sdrh     }
580bce8354Sdrh   }
59f4479501Sdrh   sqlite3_result_value(context, argv[iBest]);
600bce8354Sdrh }
610bce8354Sdrh 
62268380caSdrh /*
63268380caSdrh ** Return the type of the argument.
64268380caSdrh */
65f9b596ebSdrh static void typeofFunc(
66f9b596ebSdrh   sqlite3_context *context,
67f9b596ebSdrh   int argc,
68f9b596ebSdrh   sqlite3_value **argv
69f9b596ebSdrh ){
7035bb9d02Sdanielk1977   const char *z = 0;
7135bb9d02Sdanielk1977   switch( sqlite3_value_type(argv[0]) ){
729c054830Sdrh     case SQLITE_NULL:    z = "null";    break;
739c054830Sdrh     case SQLITE_INTEGER: z = "integer"; break;
749c054830Sdrh     case SQLITE_TEXT:    z = "text";    break;
759c054830Sdrh     case SQLITE_FLOAT:   z = "real";    break;
769c054830Sdrh     case SQLITE_BLOB:    z = "blob";    break;
7735bb9d02Sdanielk1977   }
78d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
790bce8354Sdrh }
800bce8354Sdrh 
815708d2deSdrh 
825708d2deSdrh /*
830bce8354Sdrh ** Implementation of the length() function
840bce8354Sdrh */
85f9b596ebSdrh static void lengthFunc(
86f9b596ebSdrh   sqlite3_context *context,
87f9b596ebSdrh   int argc,
88f9b596ebSdrh   sqlite3_value **argv
89f9b596ebSdrh ){
900bce8354Sdrh   int len;
910bce8354Sdrh 
920bce8354Sdrh   assert( argc==1 );
93f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
949c054830Sdrh     case SQLITE_BLOB:
959c054830Sdrh     case SQLITE_INTEGER:
969c054830Sdrh     case SQLITE_FLOAT: {
97f4479501Sdrh       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
98f9b596ebSdrh       break;
99f9b596ebSdrh     }
1009c054830Sdrh     case SQLITE_TEXT: {
1014f26d6c4Sdrh       const char *z = sqlite3_value_text(argv[0]);
1020bce8354Sdrh       for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
103f4479501Sdrh       sqlite3_result_int(context, len);
104f9b596ebSdrh       break;
105f9b596ebSdrh     }
106f9b596ebSdrh     default: {
107f9b596ebSdrh       sqlite3_result_null(context);
108f9b596ebSdrh       break;
109f9b596ebSdrh     }
110f9b596ebSdrh   }
1110bce8354Sdrh }
1120bce8354Sdrh 
1130bce8354Sdrh /*
1140bce8354Sdrh ** Implementation of the abs() function
1150bce8354Sdrh */
1160ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1170bce8354Sdrh   assert( argc==1 );
118f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1199c054830Sdrh     case SQLITE_INTEGER: {
120f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
121f93bbbeaSdanielk1977       if( iVal<0 ) iVal = iVal * -1;
122f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
123f9b596ebSdrh       break;
124f9b596ebSdrh     }
1259c054830Sdrh     case SQLITE_NULL: {
126f9b596ebSdrh       sqlite3_result_null(context);
127f9b596ebSdrh       break;
128f9b596ebSdrh     }
129f9b596ebSdrh     default: {
130f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
131f93bbbeaSdanielk1977       if( rVal<0 ) rVal = rVal * -1.0;
132f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
133f9b596ebSdrh       break;
134f9b596ebSdrh     }
135f9b596ebSdrh   }
1360bce8354Sdrh }
1370bce8354Sdrh 
1380bce8354Sdrh /*
1390bce8354Sdrh ** Implementation of the substr() function
1400bce8354Sdrh */
141f9b596ebSdrh static void substrFunc(
142f9b596ebSdrh   sqlite3_context *context,
143f9b596ebSdrh   int argc,
144f9b596ebSdrh   sqlite3_value **argv
145f9b596ebSdrh ){
1460bce8354Sdrh   const char *z;
1470bce8354Sdrh   const char *z2;
1480bce8354Sdrh   int i;
1490bce8354Sdrh   int p1, p2, len;
150f9b596ebSdrh 
1510bce8354Sdrh   assert( argc==3 );
1524f26d6c4Sdrh   z = sqlite3_value_text(argv[0]);
1530bce8354Sdrh   if( z==0 ) return;
15451ad0ecdSdanielk1977   p1 = sqlite3_value_int(argv[1]);
15551ad0ecdSdanielk1977   p2 = sqlite3_value_int(argv[2]);
15647c8a679Sdrh   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
1570bce8354Sdrh   if( p1<0 ){
15889425d5eSdrh     p1 += len;
159653bc759Sdrh     if( p1<0 ){
160653bc759Sdrh       p2 += p1;
161653bc759Sdrh       p1 = 0;
162653bc759Sdrh     }
1630bce8354Sdrh   }else if( p1>0 ){
1640bce8354Sdrh     p1--;
1650bce8354Sdrh   }
1660bce8354Sdrh   if( p1+p2>len ){
1670bce8354Sdrh     p2 = len-p1;
1680bce8354Sdrh   }
16977396304Sdrh   for(i=0; i<p1 && z[i]; i++){
17047c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p1++;
1710bce8354Sdrh   }
17247c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
17377396304Sdrh   for(; i<p1+p2 && z[i]; i++){
17447c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p2++;
1750bce8354Sdrh   }
17647c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
177653bc759Sdrh   if( p2<0 ) p2 = 0;
178d8123366Sdanielk1977   sqlite3_result_text(context, &z[p1], p2, SQLITE_TRANSIENT);
1790bce8354Sdrh }
1800bce8354Sdrh 
1810bce8354Sdrh /*
1820bce8354Sdrh ** Implementation of the round() function
1830bce8354Sdrh */
1840ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
18551ad0ecdSdanielk1977   int n = 0;
1860bce8354Sdrh   double r;
187*592ac8cbSdrh   char zBuf[500];  /* larger than the %f representation of the largest double */
1880bce8354Sdrh   assert( argc==1 || argc==2 );
18951ad0ecdSdanielk1977   if( argc==2 ){
1909c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
19151ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
1920bce8354Sdrh     if( n>30 ) n = 30;
1930bce8354Sdrh     if( n<0 ) n = 0;
19451ad0ecdSdanielk1977   }
1959c054830Sdrh   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
1964f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
197e866fcb9Sdrh   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
198d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1990bce8354Sdrh }
200dc04c583Sdrh 
201dc04c583Sdrh /*
202dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
203dc04c583Sdrh */
2040ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2058cd9db00Sdrh   unsigned char *z;
206dc04c583Sdrh   int i;
2079c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
208c572ef7fSdanielk1977   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
209dc04c583Sdrh   if( z==0 ) return;
2104f26d6c4Sdrh   strcpy(z, sqlite3_value_text(argv[0]));
211dc04c583Sdrh   for(i=0; z[i]; i++){
2124c755c0fSdrh     z[i] = toupper(z[i]);
213dc04c583Sdrh   }
214d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2157e18c259Sdanielk1977   sqliteFree(z);
216dc04c583Sdrh }
2170ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2188cd9db00Sdrh   unsigned char *z;
219dc04c583Sdrh   int i;
2209c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
221c572ef7fSdanielk1977   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
222dc04c583Sdrh   if( z==0 ) return;
2234f26d6c4Sdrh   strcpy(z, sqlite3_value_text(argv[0]));
224dc04c583Sdrh   for(i=0; z[i]; i++){
2254c755c0fSdrh     z[i] = tolower(z[i]);
226dc04c583Sdrh   }
227d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2287e18c259Sdanielk1977   sqliteFree(z);
229dc04c583Sdrh }
230dc04c583Sdrh 
231dc04c583Sdrh /*
232fbc99082Sdrh ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
233b6c9e6e6Sjplyon ** All three do the same thing.  They return the first non-NULL
234b6c9e6e6Sjplyon ** argument.
2353212e182Sdrh */
236f9b596ebSdrh static void ifnullFunc(
237f9b596ebSdrh   sqlite3_context *context,
238f9b596ebSdrh   int argc,
239f9b596ebSdrh   sqlite3_value **argv
240f9b596ebSdrh ){
241fbc99082Sdrh   int i;
242fbc99082Sdrh   for(i=0; i<argc; i++){
2439c054830Sdrh     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
244f4479501Sdrh       sqlite3_result_value(context, argv[i]);
245fbc99082Sdrh       break;
246fbc99082Sdrh     }
247fbc99082Sdrh   }
2483212e182Sdrh }
2493212e182Sdrh 
2503212e182Sdrh /*
251f9ffac96Sdrh ** Implementation of random().  Return a random integer.
252f9ffac96Sdrh */
253f9b596ebSdrh static void randomFunc(
254f9b596ebSdrh   sqlite3_context *context,
255f9b596ebSdrh   int argc,
256f9b596ebSdrh   sqlite3_value **argv
257f9b596ebSdrh ){
258bbd82df6Sdrh   int r;
2594adee20fSdanielk1977   sqlite3Randomness(sizeof(r), &r);
260f4479501Sdrh   sqlite3_result_int(context, r);
261f9ffac96Sdrh }
262f9ffac96Sdrh 
263f9ffac96Sdrh /*
2646ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
26524b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
2666ed41ad7Sdrh */
26751ad0ecdSdanielk1977 static void last_insert_rowid(
2680ae8b831Sdanielk1977   sqlite3_context *context,
26951ad0ecdSdanielk1977   int arg,
27051ad0ecdSdanielk1977   sqlite3_value **argv
27151ad0ecdSdanielk1977 ){
2729bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
273f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
2746ed41ad7Sdrh }
2756ed41ad7Sdrh 
276f146a776Srdc /*
277b28af71aSdanielk1977 ** Implementation of the changes() SQL function.  The return value is the
278b28af71aSdanielk1977 ** same as the sqlite3_changes() API function.
279f146a776Srdc */
280b28af71aSdanielk1977 static void changes(
281f9b596ebSdrh   sqlite3_context *context,
282f9b596ebSdrh   int arg,
283f9b596ebSdrh   sqlite3_value **argv
284f9b596ebSdrh ){
2859bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
286f4479501Sdrh   sqlite3_result_int(context, sqlite3_changes(db));
287b0c374ffSrdc }
288f146a776Srdc 
289f146a776Srdc /*
290b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
291b28af71aSdanielk1977 ** the same as the sqlite3_total_changes() API function.
292f146a776Srdc */
293b28af71aSdanielk1977 static void total_changes(
2940ae8b831Sdanielk1977   sqlite3_context *context,
29551ad0ecdSdanielk1977   int arg,
29651ad0ecdSdanielk1977   sqlite3_value **argv
29751ad0ecdSdanielk1977 ){
2989bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
299b28af71aSdanielk1977   sqlite3_result_int(context, sqlite3_total_changes(db));
300b0c374ffSrdc }
301b0c374ffSrdc 
3026ed41ad7Sdrh /*
3034e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
304d02eb1fdSdanielk1977 */
3054e5ffc5fSdrh struct compareInfo {
3064e5ffc5fSdrh   u8 matchAll;
3074e5ffc5fSdrh   u8 matchOne;
3084e5ffc5fSdrh   u8 matchSet;
3094e5ffc5fSdrh   u8 noCase;
310d02eb1fdSdanielk1977 };
3114e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
31270031fa3Sdrh #ifndef SQLITE_CASE_SENSITIVE_LIKE
31370031fa3Sdrh   /* The correct SQL-92 behavior is for the LIKE operator to ignore
31470031fa3Sdrh   ** case.  Thus  'a' LIKE 'A' would be true. */
3154e5ffc5fSdrh   static const struct compareInfo likeInfo = { '%', '_',   0, 1 };
31670031fa3Sdrh #else
31770031fa3Sdrh   /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
31870031fa3Sdrh   ** is case sensitive causing 'a' LIKE 'A' to be false */
31970031fa3Sdrh   static const struct compareInfo likeInfo = { '%', '_',   0, 0 };
32070031fa3Sdrh #endif
321d02eb1fdSdanielk1977 
322d02eb1fdSdanielk1977 /*
3234e5ffc5fSdrh ** X is a pointer to the first byte of a UTF-8 character.  Increment
3244e5ffc5fSdrh ** X so that it points to the next character.  This only works right
3254e5ffc5fSdrh ** if X points to a well-formed UTF-8 string.
326d02eb1fdSdanielk1977 */
3274e5ffc5fSdrh #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
3284e5ffc5fSdrh #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
329d02eb1fdSdanielk1977 
330d02eb1fdSdanielk1977 
331d02eb1fdSdanielk1977 /*
3324e5ffc5fSdrh ** Compare two UTF-8 strings for equality where the first string can
3334e5ffc5fSdrh ** potentially be a "glob" expression.  Return true (1) if they
3344e5ffc5fSdrh ** are the same and false (0) if they are different.
3350ac65892Sdrh **
3364e5ffc5fSdrh ** Globbing rules:
3370ac65892Sdrh **
3384e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
339d02eb1fdSdanielk1977 **
3404e5ffc5fSdrh **      '?'       Matches exactly one character.
3414e5ffc5fSdrh **
3424e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
3434e5ffc5fSdrh **                characters.
3444e5ffc5fSdrh **
3454e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
3464e5ffc5fSdrh **
3474e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
3484e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
3494e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
3504e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
3514e5ffc5fSdrh ** it the last character in the list.
3524e5ffc5fSdrh **
3534e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
3544e5ffc5fSdrh **
3554e5ffc5fSdrh ** Hints: to match '*' or '?', put them in "[]".  Like this:
3564e5ffc5fSdrh **
3574e5ffc5fSdrh **         abc[*]xyz        Matches "abc*xyz" only
3580ac65892Sdrh */
3597c6303c0Sdanielk1977 static int patternCompare(
3604e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
3614e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
3627c6303c0Sdanielk1977   const struct compareInfo *pInfo, /* Information about how to do the compare */
3637c6303c0Sdanielk1977   const int esc                    /* The escape character */
36451ad0ecdSdanielk1977 ){
365ad7dd425Sdanielk1977   register int c;
3664e5ffc5fSdrh   int invert;
3674e5ffc5fSdrh   int seen;
3684e5ffc5fSdrh   int c2;
3694e5ffc5fSdrh   u8 matchOne = pInfo->matchOne;
3704e5ffc5fSdrh   u8 matchAll = pInfo->matchAll;
3714e5ffc5fSdrh   u8 matchSet = pInfo->matchSet;
3724e5ffc5fSdrh   u8 noCase = pInfo->noCase;
3737c6303c0Sdanielk1977   int prevEscape = 0;     /* True if the previous character was 'escape' */
374d02eb1fdSdanielk1977 
3754e5ffc5fSdrh   while( (c = *zPattern)!=0 ){
3767c6303c0Sdanielk1977     if( !prevEscape && c==matchAll ){
3774e5ffc5fSdrh       while( (c=zPattern[1]) == matchAll || c == matchOne ){
3784e5ffc5fSdrh         if( c==matchOne ){
3794e5ffc5fSdrh           if( *zString==0 ) return 0;
3804e5ffc5fSdrh           sqliteNextChar(zString);
381d02eb1fdSdanielk1977         }
3824e5ffc5fSdrh         zPattern++;
3834e5ffc5fSdrh       }
38420fc0887Sdrh       if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
3857c6303c0Sdanielk1977         u8 const *zTemp = &zPattern[1];
3867c6303c0Sdanielk1977         sqliteNextChar(zTemp);
3877c6303c0Sdanielk1977         c = *zTemp;
3887c6303c0Sdanielk1977       }
3894e5ffc5fSdrh       if( c==0 ) return 1;
3904e5ffc5fSdrh       if( c==matchSet ){
3917c6303c0Sdanielk1977         assert( esc==0 );   /* This is GLOB, not LIKE */
3927c6303c0Sdanielk1977         while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
3934e5ffc5fSdrh           sqliteNextChar(zString);
3944e5ffc5fSdrh         }
3954e5ffc5fSdrh         return *zString!=0;
396d02eb1fdSdanielk1977       }else{
3974e5ffc5fSdrh         while( (c2 = *zString)!=0 ){
3984e5ffc5fSdrh           if( noCase ){
3994e5ffc5fSdrh             c2 = sqlite3UpperToLower[c2];
4004e5ffc5fSdrh             c = sqlite3UpperToLower[c];
4014e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
402ad7dd425Sdanielk1977           }else{
4034e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
404ad7dd425Sdanielk1977           }
4054e5ffc5fSdrh           if( c2==0 ) return 0;
4067c6303c0Sdanielk1977           if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
4074e5ffc5fSdrh           sqliteNextChar(zString);
4084e5ffc5fSdrh         }
4094e5ffc5fSdrh         return 0;
4104e5ffc5fSdrh       }
4117c6303c0Sdanielk1977     }else if( !prevEscape && c==matchOne ){
4124e5ffc5fSdrh       if( *zString==0 ) return 0;
4134e5ffc5fSdrh       sqliteNextChar(zString);
4144e5ffc5fSdrh       zPattern++;
4154e5ffc5fSdrh     }else if( c==matchSet ){
4164e5ffc5fSdrh       int prior_c = 0;
4177c6303c0Sdanielk1977       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
4184e5ffc5fSdrh       seen = 0;
4194e5ffc5fSdrh       invert = 0;
4204e5ffc5fSdrh       c = sqliteCharVal(zString);
4214e5ffc5fSdrh       if( c==0 ) return 0;
4224e5ffc5fSdrh       c2 = *++zPattern;
4234e5ffc5fSdrh       if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
4244e5ffc5fSdrh       if( c2==']' ){
4254e5ffc5fSdrh         if( c==']' ) seen = 1;
4264e5ffc5fSdrh         c2 = *++zPattern;
4274e5ffc5fSdrh       }
4284e5ffc5fSdrh       while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
4294e5ffc5fSdrh         if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
4304e5ffc5fSdrh           zPattern++;
4314e5ffc5fSdrh           c2 = sqliteCharVal(zPattern);
4324e5ffc5fSdrh           if( c>=prior_c && c<=c2 ) seen = 1;
4334e5ffc5fSdrh           prior_c = 0;
4344e5ffc5fSdrh         }else if( c==c2 ){
4354e5ffc5fSdrh           seen = 1;
4364e5ffc5fSdrh           prior_c = c2;
437d02eb1fdSdanielk1977         }else{
4384e5ffc5fSdrh           prior_c = c2;
439d02eb1fdSdanielk1977         }
4404e5ffc5fSdrh         sqliteNextChar(zPattern);
441d02eb1fdSdanielk1977       }
4424e5ffc5fSdrh       if( c2==0 || (seen ^ invert)==0 ) return 0;
4434e5ffc5fSdrh       sqliteNextChar(zString);
4444e5ffc5fSdrh       zPattern++;
44520fc0887Sdrh     }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
4467c6303c0Sdanielk1977       prevEscape = 1;
4477c6303c0Sdanielk1977       sqliteNextChar(zPattern);
448d02eb1fdSdanielk1977     }else{
4494e5ffc5fSdrh       if( noCase ){
4504e5ffc5fSdrh         if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
4514e5ffc5fSdrh       }else{
4524e5ffc5fSdrh         if( c != *zString ) return 0;
4534e5ffc5fSdrh       }
4544e5ffc5fSdrh       zPattern++;
4554e5ffc5fSdrh       zString++;
4567c6303c0Sdanielk1977       prevEscape = 0;
45751ad0ecdSdanielk1977     }
4580ac65892Sdrh   }
4594e5ffc5fSdrh   return *zString==0;
4604e5ffc5fSdrh }
4614e5ffc5fSdrh 
4623f6b0874Sdanielk1977 
4633f6b0874Sdanielk1977 /*
4643f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
4653f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
4663f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
4673f6b0874Sdanielk1977 **
4683f6b0874Sdanielk1977 **       A LIKE B
4693f6b0874Sdanielk1977 **
4703f6b0874Sdanielk1977 ** is implemented as like(B,A).
4713f6b0874Sdanielk1977 **
4723f6b0874Sdanielk1977 ** If the pointer retrieved by via a call to sqlite3_user_data() is
4733f6b0874Sdanielk1977 ** not NULL, then this function uses UTF-16. Otherwise UTF-8.
4743f6b0874Sdanielk1977 */
4753f6b0874Sdanielk1977 static void likeFunc(
4763f6b0874Sdanielk1977   sqlite3_context *context,
4773f6b0874Sdanielk1977   int argc,
4783f6b0874Sdanielk1977   sqlite3_value **argv
4793f6b0874Sdanielk1977 ){
4803f6b0874Sdanielk1977   const unsigned char *zA = sqlite3_value_text(argv[0]);
4813f6b0874Sdanielk1977   const unsigned char *zB = sqlite3_value_text(argv[1]);
4827c6303c0Sdanielk1977   int escape = 0;
4837c6303c0Sdanielk1977   if( argc==3 ){
4847c6303c0Sdanielk1977     /* The escape character string must consist of a single UTF-8 character.
4857c6303c0Sdanielk1977     ** Otherwise, return an error.
4867c6303c0Sdanielk1977     */
4877c6303c0Sdanielk1977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
4887c6303c0Sdanielk1977     if( sqlite3utf8CharLen(zEsc, -1)!=1 ){
4897c6303c0Sdanielk1977       sqlite3_result_error(context,
4907c6303c0Sdanielk1977           "ESCAPE expression must be a single character", -1);
4917c6303c0Sdanielk1977       return;
4927c6303c0Sdanielk1977     }
4937c6303c0Sdanielk1977     escape = sqlite3ReadUtf8(zEsc);
4947c6303c0Sdanielk1977   }
4953f6b0874Sdanielk1977   if( zA && zB ){
4967c6303c0Sdanielk1977     sqlite3_result_int(context, patternCompare(zA, zB, &likeInfo, escape));
4973f6b0874Sdanielk1977   }
4983f6b0874Sdanielk1977 }
4990ac65892Sdrh 
5000ac65892Sdrh /*
5010ac65892Sdrh ** Implementation of the glob() SQL function.  This function implements
5020ac65892Sdrh ** the build-in GLOB operator.  The first argument to the function is the
5030ac65892Sdrh ** string and the second argument is the pattern.  So, the SQL statements:
5040ac65892Sdrh **
5050ac65892Sdrh **       A GLOB B
5060ac65892Sdrh **
5077c6303c0Sdanielk1977 ** is implemented as glob(B,A).
5080ac65892Sdrh */
5090ae8b831Sdanielk1977 static void globFunc(sqlite3_context *context, int arg, sqlite3_value **argv){
5104f26d6c4Sdrh   const unsigned char *zA = sqlite3_value_text(argv[0]);
5114f26d6c4Sdrh   const unsigned char *zB = sqlite3_value_text(argv[1]);
51251ad0ecdSdanielk1977   if( zA && zB ){
5137c6303c0Sdanielk1977     sqlite3_result_int(context, patternCompare(zA, zB, &globInfo, 0));
51451ad0ecdSdanielk1977   }
5158912d106Sdrh }
5168912d106Sdrh 
5178912d106Sdrh /*
5188912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
5198912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
5208912d106Sdrh ** arguments are equal to each other.
5218912d106Sdrh */
522f9b596ebSdrh static void nullifFunc(
523f9b596ebSdrh   sqlite3_context *context,
524f9b596ebSdrh   int argc,
525f9b596ebSdrh   sqlite3_value **argv
526f9b596ebSdrh ){
527dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
528dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
529f4479501Sdrh     sqlite3_result_value(context, argv[0]);
5308912d106Sdrh   }
5310ac65892Sdrh }
5320ac65892Sdrh 
533647cb0e1Sdrh /*
534647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
535647cb0e1Sdrh ** of the SQLite library that is running.
536647cb0e1Sdrh */
537f9b596ebSdrh static void versionFunc(
538f9b596ebSdrh   sqlite3_context *context,
539f9b596ebSdrh   int argc,
540f9b596ebSdrh   sqlite3_value **argv
541f9b596ebSdrh ){
542d8123366Sdanielk1977   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
543647cb0e1Sdrh }
544647cb0e1Sdrh 
545d641d646Sdanielk1977 
54647394703Sdrh /*
54747394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
54847394703Sdrh ** change.  This function may disappear.  Do not write code that depends
54947394703Sdrh ** on this function.
55047394703Sdrh **
55147394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
55247394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
55347394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
55447394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
55547394703Sdrh ** single-quote escapes.
55647394703Sdrh */
5570ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55847394703Sdrh   if( argc<1 ) return;
559f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
5609c054830Sdrh     case SQLITE_NULL: {
561d8123366Sdanielk1977       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
562f9b596ebSdrh       break;
563f9b596ebSdrh     }
5649c054830Sdrh     case SQLITE_INTEGER:
5659c054830Sdrh     case SQLITE_FLOAT: {
566f4479501Sdrh       sqlite3_result_value(context, argv[0]);
567f9b596ebSdrh       break;
568f9b596ebSdrh     }
5693f41e976Sdanielk1977     case SQLITE_BLOB: {
5703f41e976Sdanielk1977       static const char hexdigits[] = {
5713f41e976Sdanielk1977         '0', '1', '2', '3', '4', '5', '6', '7',
5723f41e976Sdanielk1977         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
5733f41e976Sdanielk1977       };
5743f41e976Sdanielk1977       char *zText = 0;
5753f41e976Sdanielk1977       int nBlob = sqlite3_value_bytes(argv[0]);
5763f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
5773f41e976Sdanielk1977 
5783f41e976Sdanielk1977       zText = (char *)sqliteMalloc((2*nBlob)+4);
5793f41e976Sdanielk1977       if( !zText ){
5803f41e976Sdanielk1977         sqlite3_result_error(context, "out of memory", -1);
5813f41e976Sdanielk1977       }else{
5823f41e976Sdanielk1977         int i;
5833f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
5843f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
5853f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
5863f41e976Sdanielk1977         }
5873f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
5883f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
5893f41e976Sdanielk1977         zText[0] = 'X';
5903f41e976Sdanielk1977         zText[1] = '\'';
591d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
5923f41e976Sdanielk1977         sqliteFree(zText);
5933f41e976Sdanielk1977       }
5943f41e976Sdanielk1977       break;
5953f41e976Sdanielk1977     }
5969c054830Sdrh     case SQLITE_TEXT: {
59747394703Sdrh       int i,j,n;
5984f26d6c4Sdrh       const char *zArg = sqlite3_value_text(argv[0]);
59947394703Sdrh       char *z;
600f9b596ebSdrh 
60151ad0ecdSdanielk1977       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
60247394703Sdrh       z = sqliteMalloc( i+n+3 );
60347394703Sdrh       if( z==0 ) return;
60447394703Sdrh       z[0] = '\'';
60551ad0ecdSdanielk1977       for(i=0, j=1; zArg[i]; i++){
60651ad0ecdSdanielk1977         z[j++] = zArg[i];
60751ad0ecdSdanielk1977         if( zArg[i]=='\'' ){
60847394703Sdrh           z[j++] = '\'';
60947394703Sdrh         }
61047394703Sdrh       }
61147394703Sdrh       z[j++] = '\'';
61247394703Sdrh       z[j] = 0;
613d8123366Sdanielk1977       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
61447394703Sdrh       sqliteFree(z);
61547394703Sdrh     }
61647394703Sdrh   }
617f9b596ebSdrh }
61847394703Sdrh 
619d24cc427Sdrh #ifdef SQLITE_SOUNDEX
620d24cc427Sdrh /*
621d24cc427Sdrh ** Compute the soundex encoding of a word.
622d24cc427Sdrh */
6230ae8b831Sdanielk1977 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
624d24cc427Sdrh   char zResult[8];
6254c755c0fSdrh   const u8 *zIn;
626d24cc427Sdrh   int i, j;
627d24cc427Sdrh   static const unsigned char iCode[] = {
628d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
629d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
630d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
631d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
632d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
633d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
634d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
635d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
636d24cc427Sdrh   };
637d24cc427Sdrh   assert( argc==1 );
6384c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
639d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
640d24cc427Sdrh   if( zIn[i] ){
641d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
642d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
643d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
644d24cc427Sdrh       if( code>0 ){
645d24cc427Sdrh         zResult[j++] = code + '0';
646d24cc427Sdrh       }
647d24cc427Sdrh     }
648d24cc427Sdrh     while( j<4 ){
649d24cc427Sdrh       zResult[j++] = '0';
650d24cc427Sdrh     }
651d24cc427Sdrh     zResult[j] = 0;
652d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
653d24cc427Sdrh   }else{
654d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
655d24cc427Sdrh   }
656d24cc427Sdrh }
657d24cc427Sdrh #endif
658d24cc427Sdrh 
659193a6b41Sdrh #ifdef SQLITE_TEST
660193a6b41Sdrh /*
661193a6b41Sdrh ** This function generates a string of random characters.  Used for
662193a6b41Sdrh ** generating test data.
663193a6b41Sdrh */
6640ae8b831Sdanielk1977 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
665bbd82df6Sdrh   static const unsigned char zSrc[] =
666193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
667193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
668193a6b41Sdrh      "0123456789"
669193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
670193a6b41Sdrh   int iMin, iMax, n, r, i;
671bbd82df6Sdrh   unsigned char zBuf[1000];
672193a6b41Sdrh   if( argc>=1 ){
673f9b596ebSdrh     iMin = sqlite3_value_int(argv[0]);
674193a6b41Sdrh     if( iMin<0 ) iMin = 0;
675193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
676193a6b41Sdrh   }else{
677193a6b41Sdrh     iMin = 1;
678193a6b41Sdrh   }
679193a6b41Sdrh   if( argc>=2 ){
680f9b596ebSdrh     iMax = sqlite3_value_int(argv[1]);
681193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
6821dba7279Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
683193a6b41Sdrh   }else{
684193a6b41Sdrh     iMax = 50;
685193a6b41Sdrh   }
686193a6b41Sdrh   n = iMin;
687193a6b41Sdrh   if( iMax>iMin ){
6884adee20fSdanielk1977     sqlite3Randomness(sizeof(r), &r);
689bbd82df6Sdrh     r &= 0x7fffffff;
690193a6b41Sdrh     n += r%(iMax + 1 - iMin);
691193a6b41Sdrh   }
6921dba7279Sdrh   assert( n<sizeof(zBuf) );
6934adee20fSdanielk1977   sqlite3Randomness(n, zBuf);
694193a6b41Sdrh   for(i=0; i<n; i++){
695bbd82df6Sdrh     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
696193a6b41Sdrh   }
697193a6b41Sdrh   zBuf[n] = 0;
698d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
699d8123366Sdanielk1977 }
7000e3d7476Sdrh #endif /* SQLITE_TEST */
701d8123366Sdanielk1977 
7020e3d7476Sdrh #ifdef SQLITE_TEST
703d8123366Sdanielk1977 /*
704d8123366Sdanielk1977 ** The following two SQL functions are used to test returning a text
705d8123366Sdanielk1977 ** result with a destructor. Function 'test_destructor' takes one argument
706d8123366Sdanielk1977 ** and returns the same argument interpreted as TEXT. A destructor is
707d8123366Sdanielk1977 ** passed with the sqlite3_result_text() call.
708d8123366Sdanielk1977 **
709d8123366Sdanielk1977 ** SQL function 'test_destructor_count' returns the number of outstanding
710d8123366Sdanielk1977 ** allocations made by 'test_destructor';
711d8123366Sdanielk1977 **
712d8123366Sdanielk1977 ** WARNING: Not threadsafe.
713d8123366Sdanielk1977 */
714d8123366Sdanielk1977 static int test_destructor_count_var = 0;
715d8123366Sdanielk1977 static void destructor(void *p){
716d8123366Sdanielk1977   char *zVal = (char *)p;
717d8123366Sdanielk1977   assert(zVal);
718d8123366Sdanielk1977   zVal--;
719d8123366Sdanielk1977   sqliteFree(zVal);
720d8123366Sdanielk1977   test_destructor_count_var--;
721d8123366Sdanielk1977 }
722d8123366Sdanielk1977 static void test_destructor(
723d8123366Sdanielk1977   sqlite3_context *pCtx,
724d8123366Sdanielk1977   int nArg,
725d8123366Sdanielk1977   sqlite3_value **argv
726d8123366Sdanielk1977 ){
727d8123366Sdanielk1977   char *zVal;
728f4618891Sdanielk1977   int len;
7299bb575fdSdrh   sqlite3 *db = sqlite3_user_data(pCtx);
730f4618891Sdanielk1977 
731d8123366Sdanielk1977   test_destructor_count_var++;
732d8123366Sdanielk1977   assert( nArg==1 );
733d8123366Sdanielk1977   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
734f4618891Sdanielk1977   len = sqlite3ValueBytes(argv[0], db->enc);
735f4618891Sdanielk1977   zVal = sqliteMalloc(len+3);
736f4618891Sdanielk1977   zVal[len] = 0;
737f4618891Sdanielk1977   zVal[len-1] = 0;
738d8123366Sdanielk1977   assert( zVal );
739d8123366Sdanielk1977   zVal++;
740f4618891Sdanielk1977   memcpy(zVal, sqlite3ValueText(argv[0], db->enc), len);
741f4618891Sdanielk1977   if( db->enc==SQLITE_UTF8 ){
742d8123366Sdanielk1977     sqlite3_result_text(pCtx, zVal, -1, destructor);
7436c62608fSdrh #ifndef SQLITE_OMIT_UTF16
744f4618891Sdanielk1977   }else if( db->enc==SQLITE_UTF16LE ){
745f4618891Sdanielk1977     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
746f4618891Sdanielk1977   }else{
747f4618891Sdanielk1977     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
7486c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
749f4618891Sdanielk1977   }
750d8123366Sdanielk1977 }
751d8123366Sdanielk1977 static void test_destructor_count(
752d8123366Sdanielk1977   sqlite3_context *pCtx,
753d8123366Sdanielk1977   int nArg,
754d8123366Sdanielk1977   sqlite3_value **argv
755d8123366Sdanielk1977 ){
756d8123366Sdanielk1977   sqlite3_result_int(pCtx, test_destructor_count_var);
757193a6b41Sdrh }
7580e3d7476Sdrh #endif /* SQLITE_TEST */
7593f6b0874Sdanielk1977 
7600e3d7476Sdrh #ifdef SQLITE_TEST
7610e3d7476Sdrh /*
7620e3d7476Sdrh ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
7630e3d7476Sdrh ** interface.
7640e3d7476Sdrh **
7650e3d7476Sdrh ** The test_auxdata() SQL function attempts to register each of its arguments
7660e3d7476Sdrh ** as auxiliary data.  If there are no prior registrations of aux data for
7670e3d7476Sdrh ** that argument (meaning the argument is not a constant or this is its first
7680e3d7476Sdrh ** call) then the result for that argument is 0.  If there is a prior
7690e3d7476Sdrh ** registration, the result for that argument is 1.  The overall result
7700e3d7476Sdrh ** is the individual argument results separated by spaces.
7710e3d7476Sdrh */
7723f6b0874Sdanielk1977 static void free_test_auxdata(void *p) {sqliteFree(p);}
7733f6b0874Sdanielk1977 static void test_auxdata(
7743f6b0874Sdanielk1977   sqlite3_context *pCtx,
7753f6b0874Sdanielk1977   int nArg,
7763f6b0874Sdanielk1977   sqlite3_value **argv
7773f6b0874Sdanielk1977 ){
7783f6b0874Sdanielk1977   int i;
7793f6b0874Sdanielk1977   char *zRet = sqliteMalloc(nArg*2);
7803f6b0874Sdanielk1977   if( !zRet ) return;
7813f6b0874Sdanielk1977   for(i=0; i<nArg; i++){
7823f6b0874Sdanielk1977     char const *z = sqlite3_value_text(argv[i]);
7833f6b0874Sdanielk1977     if( z ){
7843f6b0874Sdanielk1977       char *zAux = sqlite3_get_auxdata(pCtx, i);
7853f6b0874Sdanielk1977       if( zAux ){
7863f6b0874Sdanielk1977         zRet[i*2] = '1';
7873f6b0874Sdanielk1977         if( strcmp(zAux, z) ){
7883f6b0874Sdanielk1977           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
7893f6b0874Sdanielk1977           return;
7903f6b0874Sdanielk1977         }
7913f6b0874Sdanielk1977       }else{
7923f6b0874Sdanielk1977         zRet[i*2] = '0';
7933f6b0874Sdanielk1977         zAux = sqliteStrDup(z);
7943f6b0874Sdanielk1977         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
7953f6b0874Sdanielk1977       }
7963f6b0874Sdanielk1977       zRet[i*2+1] = ' ';
7973f6b0874Sdanielk1977     }
7983f6b0874Sdanielk1977   }
7993f6b0874Sdanielk1977   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
8003f6b0874Sdanielk1977 }
8010e3d7476Sdrh #endif /* SQLITE_TEST */
802193a6b41Sdrh 
80301427a62Sdanielk1977 #ifdef SQLITE_TEST
80401427a62Sdanielk1977 /*
80501427a62Sdanielk1977 ** A function to test error reporting from user functions. This function
80601427a62Sdanielk1977 ** returns a copy of it's first argument as an error.
80701427a62Sdanielk1977 */
80801427a62Sdanielk1977 static void test_error(
80901427a62Sdanielk1977   sqlite3_context *pCtx,
81001427a62Sdanielk1977   int nArg,
81101427a62Sdanielk1977   sqlite3_value **argv
81201427a62Sdanielk1977 ){
81324c8ab80Sdanielk1977   sqlite3_result_error(pCtx, sqlite3_value_text(argv[0]), 0);
81401427a62Sdanielk1977 }
81501427a62Sdanielk1977 #endif /* SQLITE_TEST */
81601427a62Sdanielk1977 
8170ac65892Sdrh /*
818d3a149efSdrh ** An instance of the following structure holds the context of a
819dd5baa95Sdrh ** sum() or avg() aggregate computation.
820dd5baa95Sdrh */
821dd5baa95Sdrh typedef struct SumCtx SumCtx;
822dd5baa95Sdrh struct SumCtx {
823dd5baa95Sdrh   double sum;     /* Sum of terms */
824739105c7Sdrh   int cnt;        /* Number of elements summed */
825dd5baa95Sdrh };
826dd5baa95Sdrh 
827dd5baa95Sdrh /*
828dd5baa95Sdrh ** Routines used to compute the sum or average.
829dd5baa95Sdrh */
8300ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
831dd5baa95Sdrh   SumCtx *p;
832dd5baa95Sdrh   if( argc<1 ) return;
8334f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8349c054830Sdrh   if( p && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
8354f26d6c4Sdrh     p->sum += sqlite3_value_double(argv[0]);
836739105c7Sdrh     p->cnt++;
837739105c7Sdrh   }
838dd5baa95Sdrh }
8390ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
840dd5baa95Sdrh   SumCtx *p;
8414f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8427e18c259Sdanielk1977   sqlite3_result_double(context, p ? p->sum : 0.0);
843dd5baa95Sdrh }
8440ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
845dd5baa95Sdrh   SumCtx *p;
8464f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
847739105c7Sdrh   if( p && p->cnt>0 ){
8487e18c259Sdanielk1977     sqlite3_result_double(context, p->sum/(double)p->cnt);
849dd5baa95Sdrh   }
850dd5baa95Sdrh }
851dd5baa95Sdrh 
852dd5baa95Sdrh /*
853dd5baa95Sdrh ** An instance of the following structure holds the context of a
854a2ed5601Sdrh ** variance or standard deviation computation.
855d3a149efSdrh */
856d3a149efSdrh typedef struct StdDevCtx StdDevCtx;
857d3a149efSdrh struct StdDevCtx {
858d3a149efSdrh   double sum;     /* Sum of terms */
859d3a149efSdrh   double sum2;    /* Sum of the squares of terms */
860739105c7Sdrh   int cnt;        /* Number of terms counted */
861d3a149efSdrh };
862d3a149efSdrh 
8630bce8354Sdrh /*
8640bce8354Sdrh ** The following structure keeps track of state information for the
8650bce8354Sdrh ** count() aggregate function.
8660bce8354Sdrh */
8670bce8354Sdrh typedef struct CountCtx CountCtx;
8680bce8354Sdrh struct CountCtx {
8690bce8354Sdrh   int n;
8700bce8354Sdrh };
871dd5baa95Sdrh 
8720bce8354Sdrh /*
8730bce8354Sdrh ** Routines to implement the count() aggregate function.
8740bce8354Sdrh */
8750ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
8760bce8354Sdrh   CountCtx *p;
8774f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8789c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
8790bce8354Sdrh     p->n++;
8800bce8354Sdrh   }
8810bce8354Sdrh }
8820ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
8830bce8354Sdrh   CountCtx *p;
8844f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
885f4479501Sdrh   sqlite3_result_int(context, p ? p->n : 0);
8860bce8354Sdrh }
8870bce8354Sdrh 
8880bce8354Sdrh /*
8890bce8354Sdrh ** This function tracks state information for the min() and max()
8900bce8354Sdrh ** aggregate functions.
8910bce8354Sdrh */
8920bce8354Sdrh typedef struct MinMaxCtx MinMaxCtx;
8930bce8354Sdrh struct MinMaxCtx {
8940bce8354Sdrh   char *z;         /* The best so far */
8950bce8354Sdrh   char zBuf[28];   /* Space that can be used for storage */
8960bce8354Sdrh };
8970bce8354Sdrh 
8980bce8354Sdrh /*
8990bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
9000bce8354Sdrh */
9010ae8b831Sdanielk1977 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
90288208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
9039eb516c0Sdrh   Mem *pBest;
9049eb516c0Sdrh 
9059eb516c0Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
9069eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
9073aeab9e4Sdanielk1977   if( !pBest ) return;
908268380caSdrh 
90988208050Sdanielk1977   if( pBest->flags ){
9109eb516c0Sdrh     int max;
9119eb516c0Sdrh     int cmp;
912dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
9137e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
9147e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
9157e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
9167e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
9177e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
9187e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
9197e18c259Sdanielk1977     ** aggregate, or 0 for min().
9207e18c259Sdanielk1977     */
92188208050Sdanielk1977     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
922dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
92388208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
9247e18c259Sdanielk1977       sqlite3VdbeMemCopy(pBest, pArg);
92588208050Sdanielk1977     }
9260bce8354Sdrh   }else{
9277e18c259Sdanielk1977     sqlite3VdbeMemCopy(pBest, pArg);
9280bce8354Sdrh   }
9290bce8354Sdrh }
9300ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
93188208050Sdanielk1977   sqlite3_value *pRes;
9324f26d6c4Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
93388208050Sdanielk1977   if( pRes->flags ){
934f4479501Sdrh     sqlite3_result_value(context, pRes);
9350bce8354Sdrh   }
936b20e56b4Sdanielk1977   sqlite3VdbeMemRelease(pRes);
9370bce8354Sdrh }
938dd5baa95Sdrh 
9394e5ffc5fSdrh 
940d3a149efSdrh /*
941a2ed5601Sdrh ** This function registered all of the above C functions as SQL
942a2ed5601Sdrh ** functions.  This should be the only routine in this file with
943a2ed5601Sdrh ** external linkage.
944dc04c583Sdrh */
9459bb575fdSdrh void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
9465719628aSdrh   static const struct {
9470bce8354Sdrh      char *zName;
948268380caSdrh      signed char nArg;
949268380caSdrh      u8 argType;           /* 0: none.  1: db  2: (-1) */
950d02eb1fdSdanielk1977      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
951dc1bdc4fSdanielk1977      u8 needCollSeq;
9520ae8b831Sdanielk1977      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
9530bce8354Sdrh   } aFuncs[] = {
954d8123366Sdanielk1977     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
955d8123366Sdanielk1977     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
956d8123366Sdanielk1977     { "max",               -1, 2, SQLITE_UTF8,    1, minmaxFunc },
957d8123366Sdanielk1977     { "max",                0, 2, SQLITE_UTF8,    1, 0          },
958d8123366Sdanielk1977     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
959d8123366Sdanielk1977     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
960d8123366Sdanielk1977     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
9616c62608fSdrh #ifndef SQLITE_OMIT_UTF16
962f4618891Sdanielk1977     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
9636c62608fSdrh #endif
964d8123366Sdanielk1977     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
965d8123366Sdanielk1977     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
966d8123366Sdanielk1977     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
967d8123366Sdanielk1977     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
968d8123366Sdanielk1977     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
969d8123366Sdanielk1977     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
970d8123366Sdanielk1977     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
971d8123366Sdanielk1977     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
972d8123366Sdanielk1977     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
973d8123366Sdanielk1977     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
974d8123366Sdanielk1977     { "like",               2, 0, SQLITE_UTF8,    0, likeFunc   },
9757c6303c0Sdanielk1977     { "like",               3, 0, SQLITE_UTF8,    0, likeFunc   },
976d8123366Sdanielk1977     { "glob",               2, 0, SQLITE_UTF8,    0, globFunc   },
97794a98365Sdrh     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
978d8123366Sdanielk1977     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
979d8123366Sdanielk1977     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
980d8123366Sdanielk1977     { "last_insert_rowid",  0, 1, SQLITE_UTF8,    0, last_insert_rowid },
981b28af71aSdanielk1977     { "changes",            0, 1, SQLITE_UTF8,    0, changes    },
982b28af71aSdanielk1977     { "total_changes",      0, 1, SQLITE_UTF8,    0, total_changes },
983d24cc427Sdrh #ifdef SQLITE_SOUNDEX
984d8123366Sdanielk1977     { "soundex",            1, 0, SQLITE_UTF8, 0, soundexFunc},
985d24cc427Sdrh #endif
986193a6b41Sdrh #ifdef SQLITE_TEST
987d8123366Sdanielk1977     { "randstr",               2, 0, SQLITE_UTF8, 0, randStr    },
988f4618891Sdanielk1977     { "test_destructor",       1, 1, SQLITE_UTF8, 0, test_destructor},
989d8123366Sdanielk1977     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
9903f6b0874Sdanielk1977     { "test_auxdata",         -1, 0, SQLITE_UTF8, 0, test_auxdata},
99101427a62Sdanielk1977     { "test_error",            1, 0, SQLITE_UTF8, 0, test_error},
992193a6b41Sdrh #endif
9930bce8354Sdrh   };
9945719628aSdrh   static const struct {
9950bce8354Sdrh     char *zName;
996268380caSdrh     signed char nArg;
997268380caSdrh     u8 argType;
998dc1bdc4fSdanielk1977     u8 needCollSeq;
9990ae8b831Sdanielk1977     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
10000ae8b831Sdanielk1977     void (*xFinalize)(sqlite3_context*);
10010bce8354Sdrh   } aAggs[] = {
1002dc1bdc4fSdanielk1977     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
1003dc1bdc4fSdanielk1977     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
1004dc1bdc4fSdanielk1977     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
1005dc1bdc4fSdanielk1977     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
1006dc1bdc4fSdanielk1977     { "count",  0, 0, 0, countStep,    countFinalize  },
1007dc1bdc4fSdanielk1977     { "count",  1, 0, 0, countStep,    countFinalize  },
10080bce8354Sdrh   };
10090bce8354Sdrh   int i;
10100bce8354Sdrh 
10110bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1012c572ef7fSdanielk1977     void *pArg = 0;
1013c572ef7fSdanielk1977     switch( aFuncs[i].argType ){
1014c572ef7fSdanielk1977       case 1: pArg = db; break;
1015c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1016c572ef7fSdanielk1977     }
1017ad7dd425Sdanielk1977     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
1018f9d64d2cSdanielk1977         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1019dc1bdc4fSdanielk1977     if( aFuncs[i].needCollSeq ){
1020dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1021dc1bdc4fSdanielk1977           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1022dc1bdc4fSdanielk1977       if( pFunc && aFuncs[i].needCollSeq ){
1023dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1024dc1bdc4fSdanielk1977       }
1025dc1bdc4fSdanielk1977     }
10260bce8354Sdrh   }
10271f01ec1bSdrh #ifndef SQLITE_OMIT_ALTERTABLE
10281f01ec1bSdrh   sqlite3AlterFunctions(db);
10291f01ec1bSdrh #endif
10300bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1031c572ef7fSdanielk1977     void *pArg = 0;
1032c572ef7fSdanielk1977     switch( aAggs[i].argType ){
1033c572ef7fSdanielk1977       case 1: pArg = db; break;
1034c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1035c572ef7fSdanielk1977     }
1036d8123366Sdanielk1977     sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1037f9d64d2cSdanielk1977         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1038dc1bdc4fSdanielk1977     if( aAggs[i].needCollSeq ){
1039dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1040d8123366Sdanielk1977           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1041dc1bdc4fSdanielk1977       if( pFunc && aAggs[i].needCollSeq ){
1042dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1043dc1bdc4fSdanielk1977       }
1044dc1bdc4fSdanielk1977     }
1045268380caSdrh   }
10464adee20fSdanielk1977   sqlite3RegisterDateTimeFunctions(db);
1047fd9e1f31Sdanielk1977 #ifdef SQLITE_SSE
1048fd9e1f31Sdanielk1977   {
1049fd9e1f31Sdanielk1977     sqlite3SseFunctions(db);
1050fd9e1f31Sdanielk1977   }
1051fd9e1f31Sdanielk1977 #endif
1052dc04c583Sdrh }
1053