xref: /sqlite-3.40.0/src/func.c (revision d64fe2f3)
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*d64fe2f3Sdrh ** $Id: func.c,v 1.106 2005/08/28 17:00:23 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 
2955ef4d97Sdrh /*
3055ef4d97Sdrh ** Return the collating function associated with a function.
3155ef4d97Sdrh */
32dc1bdc4fSdanielk1977 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
33dc1bdc4fSdanielk1977   return context->pColl;
34dc1bdc4fSdanielk1977 }
35dc1bdc4fSdanielk1977 
360bce8354Sdrh /*
370bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
380bce8354Sdrh */
39f9b596ebSdrh static void minmaxFunc(
40f9b596ebSdrh   sqlite3_context *context,
41f9b596ebSdrh   int argc,
42f9b596ebSdrh   sqlite3_value **argv
43f9b596ebSdrh ){
440bce8354Sdrh   int i;
45268380caSdrh   int mask;    /* 0 for min() or 0xffffffff for max() */
46f9b596ebSdrh   int iBest;
47dc1bdc4fSdanielk1977   CollSeq *pColl;
480bce8354Sdrh 
4989425d5eSdrh   if( argc==0 ) return;
50c44af71cSdrh   mask = sqlite3_user_data(context)==0 ? 0 : -1;
51dc1bdc4fSdanielk1977   pColl = sqlite3GetFuncCollSeq(context);
52dc1bdc4fSdanielk1977   assert( pColl );
53c572ef7fSdanielk1977   assert( mask==-1 || mask==0 );
54f9b596ebSdrh   iBest = 0;
559c054830Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56f9b596ebSdrh   for(i=1; i<argc; i++){
579c054830Sdrh     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
58dc1bdc4fSdanielk1977     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
59f9b596ebSdrh       iBest = i;
600bce8354Sdrh     }
610bce8354Sdrh   }
62f4479501Sdrh   sqlite3_result_value(context, argv[iBest]);
630bce8354Sdrh }
640bce8354Sdrh 
65268380caSdrh /*
66268380caSdrh ** Return the type of the argument.
67268380caSdrh */
68f9b596ebSdrh static void typeofFunc(
69f9b596ebSdrh   sqlite3_context *context,
70f9b596ebSdrh   int argc,
71f9b596ebSdrh   sqlite3_value **argv
72f9b596ebSdrh ){
7335bb9d02Sdanielk1977   const char *z = 0;
7435bb9d02Sdanielk1977   switch( sqlite3_value_type(argv[0]) ){
759c054830Sdrh     case SQLITE_NULL:    z = "null";    break;
769c054830Sdrh     case SQLITE_INTEGER: z = "integer"; break;
779c054830Sdrh     case SQLITE_TEXT:    z = "text";    break;
789c054830Sdrh     case SQLITE_FLOAT:   z = "real";    break;
799c054830Sdrh     case SQLITE_BLOB:    z = "blob";    break;
8035bb9d02Sdanielk1977   }
81d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
820bce8354Sdrh }
830bce8354Sdrh 
845708d2deSdrh 
855708d2deSdrh /*
860bce8354Sdrh ** Implementation of the length() function
870bce8354Sdrh */
88f9b596ebSdrh static void lengthFunc(
89f9b596ebSdrh   sqlite3_context *context,
90f9b596ebSdrh   int argc,
91f9b596ebSdrh   sqlite3_value **argv
92f9b596ebSdrh ){
930bce8354Sdrh   int len;
940bce8354Sdrh 
950bce8354Sdrh   assert( argc==1 );
96f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
979c054830Sdrh     case SQLITE_BLOB:
989c054830Sdrh     case SQLITE_INTEGER:
999c054830Sdrh     case SQLITE_FLOAT: {
100f4479501Sdrh       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
101f9b596ebSdrh       break;
102f9b596ebSdrh     }
1039c054830Sdrh     case SQLITE_TEXT: {
1044f26d6c4Sdrh       const char *z = sqlite3_value_text(argv[0]);
1050bce8354Sdrh       for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
106f4479501Sdrh       sqlite3_result_int(context, len);
107f9b596ebSdrh       break;
108f9b596ebSdrh     }
109f9b596ebSdrh     default: {
110f9b596ebSdrh       sqlite3_result_null(context);
111f9b596ebSdrh       break;
112f9b596ebSdrh     }
113f9b596ebSdrh   }
1140bce8354Sdrh }
1150bce8354Sdrh 
1160bce8354Sdrh /*
1170bce8354Sdrh ** Implementation of the abs() function
1180bce8354Sdrh */
1190ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1200bce8354Sdrh   assert( argc==1 );
121f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1229c054830Sdrh     case SQLITE_INTEGER: {
123f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
124f93bbbeaSdanielk1977       if( iVal<0 ) iVal = iVal * -1;
125f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
126f9b596ebSdrh       break;
127f9b596ebSdrh     }
1289c054830Sdrh     case SQLITE_NULL: {
129f9b596ebSdrh       sqlite3_result_null(context);
130f9b596ebSdrh       break;
131f9b596ebSdrh     }
132f9b596ebSdrh     default: {
133f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
134f93bbbeaSdanielk1977       if( rVal<0 ) rVal = rVal * -1.0;
135f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
136f9b596ebSdrh       break;
137f9b596ebSdrh     }
138f9b596ebSdrh   }
1390bce8354Sdrh }
1400bce8354Sdrh 
1410bce8354Sdrh /*
1420bce8354Sdrh ** Implementation of the substr() function
1430bce8354Sdrh */
144f9b596ebSdrh static void substrFunc(
145f9b596ebSdrh   sqlite3_context *context,
146f9b596ebSdrh   int argc,
147f9b596ebSdrh   sqlite3_value **argv
148f9b596ebSdrh ){
1490bce8354Sdrh   const char *z;
1500bce8354Sdrh   const char *z2;
1510bce8354Sdrh   int i;
1520bce8354Sdrh   int p1, p2, len;
153f9b596ebSdrh 
1540bce8354Sdrh   assert( argc==3 );
1554f26d6c4Sdrh   z = sqlite3_value_text(argv[0]);
1560bce8354Sdrh   if( z==0 ) return;
15751ad0ecdSdanielk1977   p1 = sqlite3_value_int(argv[1]);
15851ad0ecdSdanielk1977   p2 = sqlite3_value_int(argv[2]);
15947c8a679Sdrh   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
1600bce8354Sdrh   if( p1<0 ){
16189425d5eSdrh     p1 += len;
162653bc759Sdrh     if( p1<0 ){
163653bc759Sdrh       p2 += p1;
164653bc759Sdrh       p1 = 0;
165653bc759Sdrh     }
1660bce8354Sdrh   }else if( p1>0 ){
1670bce8354Sdrh     p1--;
1680bce8354Sdrh   }
1690bce8354Sdrh   if( p1+p2>len ){
1700bce8354Sdrh     p2 = len-p1;
1710bce8354Sdrh   }
17277396304Sdrh   for(i=0; i<p1 && z[i]; i++){
17347c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p1++;
1740bce8354Sdrh   }
17547c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
17677396304Sdrh   for(; i<p1+p2 && z[i]; i++){
17747c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p2++;
1780bce8354Sdrh   }
17947c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
180653bc759Sdrh   if( p2<0 ) p2 = 0;
181d8123366Sdanielk1977   sqlite3_result_text(context, &z[p1], p2, SQLITE_TRANSIENT);
1820bce8354Sdrh }
1830bce8354Sdrh 
1840bce8354Sdrh /*
1850bce8354Sdrh ** Implementation of the round() function
1860bce8354Sdrh */
1870ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
18851ad0ecdSdanielk1977   int n = 0;
1890bce8354Sdrh   double r;
190592ac8cbSdrh   char zBuf[500];  /* larger than the %f representation of the largest double */
1910bce8354Sdrh   assert( argc==1 || argc==2 );
19251ad0ecdSdanielk1977   if( argc==2 ){
1939c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
19451ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
1950bce8354Sdrh     if( n>30 ) n = 30;
1960bce8354Sdrh     if( n<0 ) n = 0;
19751ad0ecdSdanielk1977   }
1989c054830Sdrh   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
1994f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
200e866fcb9Sdrh   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
201d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
2020bce8354Sdrh }
203dc04c583Sdrh 
204dc04c583Sdrh /*
205dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
206dc04c583Sdrh */
2070ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2088cd9db00Sdrh   unsigned char *z;
209dc04c583Sdrh   int i;
2109c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
211c572ef7fSdanielk1977   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
212dc04c583Sdrh   if( z==0 ) return;
2134f26d6c4Sdrh   strcpy(z, sqlite3_value_text(argv[0]));
214dc04c583Sdrh   for(i=0; z[i]; i++){
2154c755c0fSdrh     z[i] = toupper(z[i]);
216dc04c583Sdrh   }
217d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2187e18c259Sdanielk1977   sqliteFree(z);
219dc04c583Sdrh }
2200ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2218cd9db00Sdrh   unsigned char *z;
222dc04c583Sdrh   int i;
2239c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
224c572ef7fSdanielk1977   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
225dc04c583Sdrh   if( z==0 ) return;
2264f26d6c4Sdrh   strcpy(z, sqlite3_value_text(argv[0]));
227dc04c583Sdrh   for(i=0; z[i]; i++){
2284c755c0fSdrh     z[i] = tolower(z[i]);
229dc04c583Sdrh   }
230d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2317e18c259Sdanielk1977   sqliteFree(z);
232dc04c583Sdrh }
233dc04c583Sdrh 
234dc04c583Sdrh /*
235fbc99082Sdrh ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
236b6c9e6e6Sjplyon ** All three do the same thing.  They return the first non-NULL
237b6c9e6e6Sjplyon ** argument.
2383212e182Sdrh */
239f9b596ebSdrh static void ifnullFunc(
240f9b596ebSdrh   sqlite3_context *context,
241f9b596ebSdrh   int argc,
242f9b596ebSdrh   sqlite3_value **argv
243f9b596ebSdrh ){
244fbc99082Sdrh   int i;
245fbc99082Sdrh   for(i=0; i<argc; i++){
2469c054830Sdrh     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
247f4479501Sdrh       sqlite3_result_value(context, argv[i]);
248fbc99082Sdrh       break;
249fbc99082Sdrh     }
250fbc99082Sdrh   }
2513212e182Sdrh }
2523212e182Sdrh 
2533212e182Sdrh /*
254f9ffac96Sdrh ** Implementation of random().  Return a random integer.
255f9ffac96Sdrh */
256f9b596ebSdrh static void randomFunc(
257f9b596ebSdrh   sqlite3_context *context,
258f9b596ebSdrh   int argc,
259f9b596ebSdrh   sqlite3_value **argv
260f9b596ebSdrh ){
261bbd82df6Sdrh   int r;
2624adee20fSdanielk1977   sqlite3Randomness(sizeof(r), &r);
263f4479501Sdrh   sqlite3_result_int(context, r);
264f9ffac96Sdrh }
265f9ffac96Sdrh 
266f9ffac96Sdrh /*
2676ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
26824b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
2696ed41ad7Sdrh */
27051ad0ecdSdanielk1977 static void last_insert_rowid(
2710ae8b831Sdanielk1977   sqlite3_context *context,
27251ad0ecdSdanielk1977   int arg,
27351ad0ecdSdanielk1977   sqlite3_value **argv
27451ad0ecdSdanielk1977 ){
2759bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
276f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
2776ed41ad7Sdrh }
2786ed41ad7Sdrh 
279f146a776Srdc /*
280b28af71aSdanielk1977 ** Implementation of the changes() SQL function.  The return value is the
281b28af71aSdanielk1977 ** same as the sqlite3_changes() API function.
282f146a776Srdc */
283b28af71aSdanielk1977 static void changes(
284f9b596ebSdrh   sqlite3_context *context,
285f9b596ebSdrh   int arg,
286f9b596ebSdrh   sqlite3_value **argv
287f9b596ebSdrh ){
2889bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
289f4479501Sdrh   sqlite3_result_int(context, sqlite3_changes(db));
290b0c374ffSrdc }
291f146a776Srdc 
292f146a776Srdc /*
293b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
294b28af71aSdanielk1977 ** the same as the sqlite3_total_changes() API function.
295f146a776Srdc */
296b28af71aSdanielk1977 static void total_changes(
2970ae8b831Sdanielk1977   sqlite3_context *context,
29851ad0ecdSdanielk1977   int arg,
29951ad0ecdSdanielk1977   sqlite3_value **argv
30051ad0ecdSdanielk1977 ){
3019bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
302b28af71aSdanielk1977   sqlite3_result_int(context, sqlite3_total_changes(db));
303b0c374ffSrdc }
304b0c374ffSrdc 
3056ed41ad7Sdrh /*
3064e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
307d02eb1fdSdanielk1977 */
3084e5ffc5fSdrh struct compareInfo {
3094e5ffc5fSdrh   u8 matchAll;
3104e5ffc5fSdrh   u8 matchOne;
3114e5ffc5fSdrh   u8 matchSet;
3124e5ffc5fSdrh   u8 noCase;
313d02eb1fdSdanielk1977 };
31455ef4d97Sdrh 
3154e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
31670031fa3Sdrh /* The correct SQL-92 behavior is for the LIKE operator to ignore
31770031fa3Sdrh ** case.  Thus  'a' LIKE 'A' would be true. */
31855ef4d97Sdrh static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
31970031fa3Sdrh /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
32070031fa3Sdrh ** is case sensitive causing 'a' LIKE 'A' to be false */
32155ef4d97Sdrh static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
322d02eb1fdSdanielk1977 
323d02eb1fdSdanielk1977 /*
3244e5ffc5fSdrh ** X is a pointer to the first byte of a UTF-8 character.  Increment
3254e5ffc5fSdrh ** X so that it points to the next character.  This only works right
3264e5ffc5fSdrh ** if X points to a well-formed UTF-8 string.
327d02eb1fdSdanielk1977 */
3284e5ffc5fSdrh #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
3294e5ffc5fSdrh #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
330d02eb1fdSdanielk1977 
331d02eb1fdSdanielk1977 
332d02eb1fdSdanielk1977 /*
3334e5ffc5fSdrh ** Compare two UTF-8 strings for equality where the first string can
3344e5ffc5fSdrh ** potentially be a "glob" expression.  Return true (1) if they
3354e5ffc5fSdrh ** are the same and false (0) if they are different.
3360ac65892Sdrh **
3374e5ffc5fSdrh ** Globbing rules:
3380ac65892Sdrh **
3394e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
340d02eb1fdSdanielk1977 **
3414e5ffc5fSdrh **      '?'       Matches exactly one character.
3424e5ffc5fSdrh **
3434e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
3444e5ffc5fSdrh **                characters.
3454e5ffc5fSdrh **
3464e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
3474e5ffc5fSdrh **
3484e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
3494e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
3504e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
3514e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
3524e5ffc5fSdrh ** it the last character in the list.
3534e5ffc5fSdrh **
3544e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
3554e5ffc5fSdrh **
3564e5ffc5fSdrh ** Hints: to match '*' or '?', put them in "[]".  Like this:
3574e5ffc5fSdrh **
3584e5ffc5fSdrh **         abc[*]xyz        Matches "abc*xyz" only
3590ac65892Sdrh */
3607c6303c0Sdanielk1977 static int patternCompare(
3614e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
3624e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
3637c6303c0Sdanielk1977   const struct compareInfo *pInfo, /* Information about how to do the compare */
3647c6303c0Sdanielk1977   const int esc                    /* The escape character */
36551ad0ecdSdanielk1977 ){
366ad7dd425Sdanielk1977   register int c;
3674e5ffc5fSdrh   int invert;
3684e5ffc5fSdrh   int seen;
3694e5ffc5fSdrh   int c2;
3704e5ffc5fSdrh   u8 matchOne = pInfo->matchOne;
3714e5ffc5fSdrh   u8 matchAll = pInfo->matchAll;
3724e5ffc5fSdrh   u8 matchSet = pInfo->matchSet;
3734e5ffc5fSdrh   u8 noCase = pInfo->noCase;
3747c6303c0Sdanielk1977   int prevEscape = 0;     /* True if the previous character was 'escape' */
375d02eb1fdSdanielk1977 
3764e5ffc5fSdrh   while( (c = *zPattern)!=0 ){
3777c6303c0Sdanielk1977     if( !prevEscape && c==matchAll ){
3784e5ffc5fSdrh       while( (c=zPattern[1]) == matchAll || c == matchOne ){
3794e5ffc5fSdrh         if( c==matchOne ){
3804e5ffc5fSdrh           if( *zString==0 ) return 0;
3814e5ffc5fSdrh           sqliteNextChar(zString);
382d02eb1fdSdanielk1977         }
3834e5ffc5fSdrh         zPattern++;
3844e5ffc5fSdrh       }
38520fc0887Sdrh       if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
3867c6303c0Sdanielk1977         u8 const *zTemp = &zPattern[1];
3877c6303c0Sdanielk1977         sqliteNextChar(zTemp);
3887c6303c0Sdanielk1977         c = *zTemp;
3897c6303c0Sdanielk1977       }
3904e5ffc5fSdrh       if( c==0 ) return 1;
3914e5ffc5fSdrh       if( c==matchSet ){
3927c6303c0Sdanielk1977         assert( esc==0 );   /* This is GLOB, not LIKE */
3937c6303c0Sdanielk1977         while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
3944e5ffc5fSdrh           sqliteNextChar(zString);
3954e5ffc5fSdrh         }
3964e5ffc5fSdrh         return *zString!=0;
397d02eb1fdSdanielk1977       }else{
3984e5ffc5fSdrh         while( (c2 = *zString)!=0 ){
3994e5ffc5fSdrh           if( noCase ){
4004e5ffc5fSdrh             c2 = sqlite3UpperToLower[c2];
4014e5ffc5fSdrh             c = sqlite3UpperToLower[c];
4024e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
403ad7dd425Sdanielk1977           }else{
4044e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
405ad7dd425Sdanielk1977           }
4064e5ffc5fSdrh           if( c2==0 ) return 0;
4077c6303c0Sdanielk1977           if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
4084e5ffc5fSdrh           sqliteNextChar(zString);
4094e5ffc5fSdrh         }
4104e5ffc5fSdrh         return 0;
4114e5ffc5fSdrh       }
4127c6303c0Sdanielk1977     }else if( !prevEscape && c==matchOne ){
4134e5ffc5fSdrh       if( *zString==0 ) return 0;
4144e5ffc5fSdrh       sqliteNextChar(zString);
4154e5ffc5fSdrh       zPattern++;
4164e5ffc5fSdrh     }else if( c==matchSet ){
4174e5ffc5fSdrh       int prior_c = 0;
4187c6303c0Sdanielk1977       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
4194e5ffc5fSdrh       seen = 0;
4204e5ffc5fSdrh       invert = 0;
4214e5ffc5fSdrh       c = sqliteCharVal(zString);
4224e5ffc5fSdrh       if( c==0 ) return 0;
4234e5ffc5fSdrh       c2 = *++zPattern;
4244e5ffc5fSdrh       if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
4254e5ffc5fSdrh       if( c2==']' ){
4264e5ffc5fSdrh         if( c==']' ) seen = 1;
4274e5ffc5fSdrh         c2 = *++zPattern;
4284e5ffc5fSdrh       }
4294e5ffc5fSdrh       while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
4304e5ffc5fSdrh         if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
4314e5ffc5fSdrh           zPattern++;
4324e5ffc5fSdrh           c2 = sqliteCharVal(zPattern);
4334e5ffc5fSdrh           if( c>=prior_c && c<=c2 ) seen = 1;
4344e5ffc5fSdrh           prior_c = 0;
4354e5ffc5fSdrh         }else if( c==c2 ){
4364e5ffc5fSdrh           seen = 1;
4374e5ffc5fSdrh           prior_c = c2;
438d02eb1fdSdanielk1977         }else{
4394e5ffc5fSdrh           prior_c = c2;
440d02eb1fdSdanielk1977         }
4414e5ffc5fSdrh         sqliteNextChar(zPattern);
442d02eb1fdSdanielk1977       }
4434e5ffc5fSdrh       if( c2==0 || (seen ^ invert)==0 ) return 0;
4444e5ffc5fSdrh       sqliteNextChar(zString);
4454e5ffc5fSdrh       zPattern++;
44620fc0887Sdrh     }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
4477c6303c0Sdanielk1977       prevEscape = 1;
4487c6303c0Sdanielk1977       sqliteNextChar(zPattern);
449d02eb1fdSdanielk1977     }else{
4504e5ffc5fSdrh       if( noCase ){
4514e5ffc5fSdrh         if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
4524e5ffc5fSdrh       }else{
4534e5ffc5fSdrh         if( c != *zString ) return 0;
4544e5ffc5fSdrh       }
4554e5ffc5fSdrh       zPattern++;
4564e5ffc5fSdrh       zString++;
4577c6303c0Sdanielk1977       prevEscape = 0;
45851ad0ecdSdanielk1977     }
4590ac65892Sdrh   }
4604e5ffc5fSdrh   return *zString==0;
4614e5ffc5fSdrh }
4624e5ffc5fSdrh 
46355ef4d97Sdrh /*
46455ef4d97Sdrh ** Count the number of times that the LIKE operator (or GLOB which is
46555ef4d97Sdrh ** just a variation of LIKE) gets called.  This is used for testing
46655ef4d97Sdrh ** only.
46755ef4d97Sdrh */
46855ef4d97Sdrh #ifdef SQLITE_TEST
46955ef4d97Sdrh int sqlite3_like_count = 0;
47055ef4d97Sdrh #endif
47155ef4d97Sdrh 
4723f6b0874Sdanielk1977 
4733f6b0874Sdanielk1977 /*
4743f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
4753f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
4763f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
4773f6b0874Sdanielk1977 **
4783f6b0874Sdanielk1977 **       A LIKE B
4793f6b0874Sdanielk1977 **
4803f6b0874Sdanielk1977 ** is implemented as like(B,A).
4813f6b0874Sdanielk1977 **
48255ef4d97Sdrh ** This same function (with a different compareInfo structure) computes
48355ef4d97Sdrh ** the GLOB operator.
4843f6b0874Sdanielk1977 */
4853f6b0874Sdanielk1977 static void likeFunc(
4863f6b0874Sdanielk1977   sqlite3_context *context,
4873f6b0874Sdanielk1977   int argc,
4883f6b0874Sdanielk1977   sqlite3_value **argv
4893f6b0874Sdanielk1977 ){
4903f6b0874Sdanielk1977   const unsigned char *zA = sqlite3_value_text(argv[0]);
4913f6b0874Sdanielk1977   const unsigned char *zB = sqlite3_value_text(argv[1]);
4927c6303c0Sdanielk1977   int escape = 0;
4937c6303c0Sdanielk1977   if( argc==3 ){
4947c6303c0Sdanielk1977     /* The escape character string must consist of a single UTF-8 character.
4957c6303c0Sdanielk1977     ** Otherwise, return an error.
4967c6303c0Sdanielk1977     */
4977c6303c0Sdanielk1977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
4987c6303c0Sdanielk1977     if( sqlite3utf8CharLen(zEsc, -1)!=1 ){
4997c6303c0Sdanielk1977       sqlite3_result_error(context,
5007c6303c0Sdanielk1977           "ESCAPE expression must be a single character", -1);
5017c6303c0Sdanielk1977       return;
5027c6303c0Sdanielk1977     }
5037c6303c0Sdanielk1977     escape = sqlite3ReadUtf8(zEsc);
5047c6303c0Sdanielk1977   }
5053f6b0874Sdanielk1977   if( zA && zB ){
50655ef4d97Sdrh     struct compareInfo *pInfo = sqlite3_user_data(context);
50755ef4d97Sdrh #ifdef SQLITE_TEST
50855ef4d97Sdrh     sqlite3_like_count++;
50955ef4d97Sdrh #endif
51055ef4d97Sdrh     sqlite3_result_int(context, patternCompare(zA, zB, pInfo, escape));
51151ad0ecdSdanielk1977   }
5128912d106Sdrh }
5138912d106Sdrh 
5148912d106Sdrh /*
5158912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
5168912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
5178912d106Sdrh ** arguments are equal to each other.
5188912d106Sdrh */
519f9b596ebSdrh static void nullifFunc(
520f9b596ebSdrh   sqlite3_context *context,
521f9b596ebSdrh   int argc,
522f9b596ebSdrh   sqlite3_value **argv
523f9b596ebSdrh ){
524dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
525dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
526f4479501Sdrh     sqlite3_result_value(context, argv[0]);
5278912d106Sdrh   }
5280ac65892Sdrh }
5290ac65892Sdrh 
530647cb0e1Sdrh /*
531647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
532647cb0e1Sdrh ** of the SQLite library that is running.
533647cb0e1Sdrh */
534f9b596ebSdrh static void versionFunc(
535f9b596ebSdrh   sqlite3_context *context,
536f9b596ebSdrh   int argc,
537f9b596ebSdrh   sqlite3_value **argv
538f9b596ebSdrh ){
539d8123366Sdanielk1977   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
540647cb0e1Sdrh }
541647cb0e1Sdrh 
542d641d646Sdanielk1977 
54347394703Sdrh /*
54447394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
54547394703Sdrh ** change.  This function may disappear.  Do not write code that depends
54647394703Sdrh ** on this function.
54747394703Sdrh **
54847394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
54947394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
55047394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
55147394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
55247394703Sdrh ** single-quote escapes.
55347394703Sdrh */
5540ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
55547394703Sdrh   if( argc<1 ) return;
556f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
5579c054830Sdrh     case SQLITE_NULL: {
558d8123366Sdanielk1977       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
559f9b596ebSdrh       break;
560f9b596ebSdrh     }
5619c054830Sdrh     case SQLITE_INTEGER:
5629c054830Sdrh     case SQLITE_FLOAT: {
563f4479501Sdrh       sqlite3_result_value(context, argv[0]);
564f9b596ebSdrh       break;
565f9b596ebSdrh     }
5663f41e976Sdanielk1977     case SQLITE_BLOB: {
5673f41e976Sdanielk1977       static const char hexdigits[] = {
5683f41e976Sdanielk1977         '0', '1', '2', '3', '4', '5', '6', '7',
5693f41e976Sdanielk1977         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
5703f41e976Sdanielk1977       };
5713f41e976Sdanielk1977       char *zText = 0;
5723f41e976Sdanielk1977       int nBlob = sqlite3_value_bytes(argv[0]);
5733f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
5743f41e976Sdanielk1977 
5753f41e976Sdanielk1977       zText = (char *)sqliteMalloc((2*nBlob)+4);
5763f41e976Sdanielk1977       if( !zText ){
5773f41e976Sdanielk1977         sqlite3_result_error(context, "out of memory", -1);
5783f41e976Sdanielk1977       }else{
5793f41e976Sdanielk1977         int i;
5803f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
5813f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
5823f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
5833f41e976Sdanielk1977         }
5843f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
5853f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
5863f41e976Sdanielk1977         zText[0] = 'X';
5873f41e976Sdanielk1977         zText[1] = '\'';
588d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
5893f41e976Sdanielk1977         sqliteFree(zText);
5903f41e976Sdanielk1977       }
5913f41e976Sdanielk1977       break;
5923f41e976Sdanielk1977     }
5939c054830Sdrh     case SQLITE_TEXT: {
59447394703Sdrh       int i,j,n;
5954f26d6c4Sdrh       const char *zArg = sqlite3_value_text(argv[0]);
59647394703Sdrh       char *z;
597f9b596ebSdrh 
59851ad0ecdSdanielk1977       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
59947394703Sdrh       z = sqliteMalloc( i+n+3 );
60047394703Sdrh       if( z==0 ) return;
60147394703Sdrh       z[0] = '\'';
60251ad0ecdSdanielk1977       for(i=0, j=1; zArg[i]; i++){
60351ad0ecdSdanielk1977         z[j++] = zArg[i];
60451ad0ecdSdanielk1977         if( zArg[i]=='\'' ){
60547394703Sdrh           z[j++] = '\'';
60647394703Sdrh         }
60747394703Sdrh       }
60847394703Sdrh       z[j++] = '\'';
60947394703Sdrh       z[j] = 0;
610d8123366Sdanielk1977       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
61147394703Sdrh       sqliteFree(z);
61247394703Sdrh     }
61347394703Sdrh   }
614f9b596ebSdrh }
61547394703Sdrh 
616d24cc427Sdrh #ifdef SQLITE_SOUNDEX
617d24cc427Sdrh /*
618d24cc427Sdrh ** Compute the soundex encoding of a word.
619d24cc427Sdrh */
6200ae8b831Sdanielk1977 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
621d24cc427Sdrh   char zResult[8];
6224c755c0fSdrh   const u8 *zIn;
623d24cc427Sdrh   int i, j;
624d24cc427Sdrh   static const unsigned char iCode[] = {
625d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
626d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
627d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
628d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
629d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
630d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
631d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
632d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
633d24cc427Sdrh   };
634d24cc427Sdrh   assert( argc==1 );
6354c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
636d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
637d24cc427Sdrh   if( zIn[i] ){
638d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
639d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
640d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
641d24cc427Sdrh       if( code>0 ){
642d24cc427Sdrh         zResult[j++] = code + '0';
643d24cc427Sdrh       }
644d24cc427Sdrh     }
645d24cc427Sdrh     while( j<4 ){
646d24cc427Sdrh       zResult[j++] = '0';
647d24cc427Sdrh     }
648d24cc427Sdrh     zResult[j] = 0;
649d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
650d24cc427Sdrh   }else{
651d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
652d24cc427Sdrh   }
653d24cc427Sdrh }
654d24cc427Sdrh #endif
655d24cc427Sdrh 
656193a6b41Sdrh #ifdef SQLITE_TEST
657193a6b41Sdrh /*
658193a6b41Sdrh ** This function generates a string of random characters.  Used for
659193a6b41Sdrh ** generating test data.
660193a6b41Sdrh */
6610ae8b831Sdanielk1977 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
662bbd82df6Sdrh   static const unsigned char zSrc[] =
663193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
664193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
665193a6b41Sdrh      "0123456789"
666193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
667193a6b41Sdrh   int iMin, iMax, n, r, i;
668bbd82df6Sdrh   unsigned char zBuf[1000];
669193a6b41Sdrh   if( argc>=1 ){
670f9b596ebSdrh     iMin = sqlite3_value_int(argv[0]);
671193a6b41Sdrh     if( iMin<0 ) iMin = 0;
672193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
673193a6b41Sdrh   }else{
674193a6b41Sdrh     iMin = 1;
675193a6b41Sdrh   }
676193a6b41Sdrh   if( argc>=2 ){
677f9b596ebSdrh     iMax = sqlite3_value_int(argv[1]);
678193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
6791dba7279Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
680193a6b41Sdrh   }else{
681193a6b41Sdrh     iMax = 50;
682193a6b41Sdrh   }
683193a6b41Sdrh   n = iMin;
684193a6b41Sdrh   if( iMax>iMin ){
6854adee20fSdanielk1977     sqlite3Randomness(sizeof(r), &r);
686bbd82df6Sdrh     r &= 0x7fffffff;
687193a6b41Sdrh     n += r%(iMax + 1 - iMin);
688193a6b41Sdrh   }
6891dba7279Sdrh   assert( n<sizeof(zBuf) );
6904adee20fSdanielk1977   sqlite3Randomness(n, zBuf);
691193a6b41Sdrh   for(i=0; i<n; i++){
692bbd82df6Sdrh     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
693193a6b41Sdrh   }
694193a6b41Sdrh   zBuf[n] = 0;
695d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
696d8123366Sdanielk1977 }
6970e3d7476Sdrh #endif /* SQLITE_TEST */
698d8123366Sdanielk1977 
6990e3d7476Sdrh #ifdef SQLITE_TEST
700d8123366Sdanielk1977 /*
701d8123366Sdanielk1977 ** The following two SQL functions are used to test returning a text
702d8123366Sdanielk1977 ** result with a destructor. Function 'test_destructor' takes one argument
703d8123366Sdanielk1977 ** and returns the same argument interpreted as TEXT. A destructor is
704d8123366Sdanielk1977 ** passed with the sqlite3_result_text() call.
705d8123366Sdanielk1977 **
706d8123366Sdanielk1977 ** SQL function 'test_destructor_count' returns the number of outstanding
707d8123366Sdanielk1977 ** allocations made by 'test_destructor';
708d8123366Sdanielk1977 **
709d8123366Sdanielk1977 ** WARNING: Not threadsafe.
710d8123366Sdanielk1977 */
711d8123366Sdanielk1977 static int test_destructor_count_var = 0;
712d8123366Sdanielk1977 static void destructor(void *p){
713d8123366Sdanielk1977   char *zVal = (char *)p;
714d8123366Sdanielk1977   assert(zVal);
715d8123366Sdanielk1977   zVal--;
716d8123366Sdanielk1977   sqliteFree(zVal);
717d8123366Sdanielk1977   test_destructor_count_var--;
718d8123366Sdanielk1977 }
719d8123366Sdanielk1977 static void test_destructor(
720d8123366Sdanielk1977   sqlite3_context *pCtx,
721d8123366Sdanielk1977   int nArg,
722d8123366Sdanielk1977   sqlite3_value **argv
723d8123366Sdanielk1977 ){
724d8123366Sdanielk1977   char *zVal;
725f4618891Sdanielk1977   int len;
7269bb575fdSdrh   sqlite3 *db = sqlite3_user_data(pCtx);
727f4618891Sdanielk1977 
728d8123366Sdanielk1977   test_destructor_count_var++;
729d8123366Sdanielk1977   assert( nArg==1 );
730d8123366Sdanielk1977   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
731f4618891Sdanielk1977   len = sqlite3ValueBytes(argv[0], db->enc);
732f4618891Sdanielk1977   zVal = sqliteMalloc(len+3);
733f4618891Sdanielk1977   zVal[len] = 0;
734f4618891Sdanielk1977   zVal[len-1] = 0;
735d8123366Sdanielk1977   assert( zVal );
736d8123366Sdanielk1977   zVal++;
737f4618891Sdanielk1977   memcpy(zVal, sqlite3ValueText(argv[0], db->enc), len);
738f4618891Sdanielk1977   if( db->enc==SQLITE_UTF8 ){
739d8123366Sdanielk1977     sqlite3_result_text(pCtx, zVal, -1, destructor);
7406c62608fSdrh #ifndef SQLITE_OMIT_UTF16
741f4618891Sdanielk1977   }else if( db->enc==SQLITE_UTF16LE ){
742f4618891Sdanielk1977     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
743f4618891Sdanielk1977   }else{
744f4618891Sdanielk1977     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
7456c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
746f4618891Sdanielk1977   }
747d8123366Sdanielk1977 }
748d8123366Sdanielk1977 static void test_destructor_count(
749d8123366Sdanielk1977   sqlite3_context *pCtx,
750d8123366Sdanielk1977   int nArg,
751d8123366Sdanielk1977   sqlite3_value **argv
752d8123366Sdanielk1977 ){
753d8123366Sdanielk1977   sqlite3_result_int(pCtx, test_destructor_count_var);
754193a6b41Sdrh }
7550e3d7476Sdrh #endif /* SQLITE_TEST */
7563f6b0874Sdanielk1977 
7570e3d7476Sdrh #ifdef SQLITE_TEST
7580e3d7476Sdrh /*
7590e3d7476Sdrh ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
7600e3d7476Sdrh ** interface.
7610e3d7476Sdrh **
7620e3d7476Sdrh ** The test_auxdata() SQL function attempts to register each of its arguments
7630e3d7476Sdrh ** as auxiliary data.  If there are no prior registrations of aux data for
7640e3d7476Sdrh ** that argument (meaning the argument is not a constant or this is its first
7650e3d7476Sdrh ** call) then the result for that argument is 0.  If there is a prior
7660e3d7476Sdrh ** registration, the result for that argument is 1.  The overall result
7670e3d7476Sdrh ** is the individual argument results separated by spaces.
7680e3d7476Sdrh */
7693f6b0874Sdanielk1977 static void free_test_auxdata(void *p) {sqliteFree(p);}
7703f6b0874Sdanielk1977 static void test_auxdata(
7713f6b0874Sdanielk1977   sqlite3_context *pCtx,
7723f6b0874Sdanielk1977   int nArg,
7733f6b0874Sdanielk1977   sqlite3_value **argv
7743f6b0874Sdanielk1977 ){
7753f6b0874Sdanielk1977   int i;
7763f6b0874Sdanielk1977   char *zRet = sqliteMalloc(nArg*2);
7773f6b0874Sdanielk1977   if( !zRet ) return;
7783f6b0874Sdanielk1977   for(i=0; i<nArg; i++){
7793f6b0874Sdanielk1977     char const *z = sqlite3_value_text(argv[i]);
7803f6b0874Sdanielk1977     if( z ){
7813f6b0874Sdanielk1977       char *zAux = sqlite3_get_auxdata(pCtx, i);
7823f6b0874Sdanielk1977       if( zAux ){
7833f6b0874Sdanielk1977         zRet[i*2] = '1';
7843f6b0874Sdanielk1977         if( strcmp(zAux, z) ){
7853f6b0874Sdanielk1977           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
7863f6b0874Sdanielk1977           return;
7873f6b0874Sdanielk1977         }
7883f6b0874Sdanielk1977       }else{
7893f6b0874Sdanielk1977         zRet[i*2] = '0';
7903f6b0874Sdanielk1977         zAux = sqliteStrDup(z);
7913f6b0874Sdanielk1977         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
7923f6b0874Sdanielk1977       }
7933f6b0874Sdanielk1977       zRet[i*2+1] = ' ';
7943f6b0874Sdanielk1977     }
7953f6b0874Sdanielk1977   }
7963f6b0874Sdanielk1977   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
7973f6b0874Sdanielk1977 }
7980e3d7476Sdrh #endif /* SQLITE_TEST */
799193a6b41Sdrh 
80001427a62Sdanielk1977 #ifdef SQLITE_TEST
80101427a62Sdanielk1977 /*
80201427a62Sdanielk1977 ** A function to test error reporting from user functions. This function
80301427a62Sdanielk1977 ** returns a copy of it's first argument as an error.
80401427a62Sdanielk1977 */
80501427a62Sdanielk1977 static void test_error(
80601427a62Sdanielk1977   sqlite3_context *pCtx,
80701427a62Sdanielk1977   int nArg,
80801427a62Sdanielk1977   sqlite3_value **argv
80901427a62Sdanielk1977 ){
81024c8ab80Sdanielk1977   sqlite3_result_error(pCtx, sqlite3_value_text(argv[0]), 0);
81101427a62Sdanielk1977 }
81201427a62Sdanielk1977 #endif /* SQLITE_TEST */
81301427a62Sdanielk1977 
8140ac65892Sdrh /*
815d3a149efSdrh ** An instance of the following structure holds the context of a
816dd5baa95Sdrh ** sum() or avg() aggregate computation.
817dd5baa95Sdrh */
818dd5baa95Sdrh typedef struct SumCtx SumCtx;
819dd5baa95Sdrh struct SumCtx {
820dd5baa95Sdrh   double sum;     /* Sum of terms */
821739105c7Sdrh   int cnt;        /* Number of elements summed */
822dd5baa95Sdrh };
823dd5baa95Sdrh 
824dd5baa95Sdrh /*
825dd5baa95Sdrh ** Routines used to compute the sum or average.
826dd5baa95Sdrh */
8270ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
828dd5baa95Sdrh   SumCtx *p;
829dd5baa95Sdrh   if( argc<1 ) return;
8304f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8319c054830Sdrh   if( p && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
8324f26d6c4Sdrh     p->sum += sqlite3_value_double(argv[0]);
833739105c7Sdrh     p->cnt++;
834739105c7Sdrh   }
835dd5baa95Sdrh }
8360ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
837dd5baa95Sdrh   SumCtx *p;
8384f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8397e18c259Sdanielk1977   sqlite3_result_double(context, p ? p->sum : 0.0);
840dd5baa95Sdrh }
8410ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
842dd5baa95Sdrh   SumCtx *p;
8434f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
844739105c7Sdrh   if( p && p->cnt>0 ){
8457e18c259Sdanielk1977     sqlite3_result_double(context, p->sum/(double)p->cnt);
846dd5baa95Sdrh   }
847dd5baa95Sdrh }
848dd5baa95Sdrh 
849dd5baa95Sdrh /*
850dd5baa95Sdrh ** An instance of the following structure holds the context of a
851a2ed5601Sdrh ** variance or standard deviation computation.
852d3a149efSdrh */
853d3a149efSdrh typedef struct StdDevCtx StdDevCtx;
854d3a149efSdrh struct StdDevCtx {
855d3a149efSdrh   double sum;     /* Sum of terms */
856d3a149efSdrh   double sum2;    /* Sum of the squares of terms */
857739105c7Sdrh   int cnt;        /* Number of terms counted */
858d3a149efSdrh };
859d3a149efSdrh 
8600bce8354Sdrh /*
8610bce8354Sdrh ** The following structure keeps track of state information for the
8620bce8354Sdrh ** count() aggregate function.
8630bce8354Sdrh */
8640bce8354Sdrh typedef struct CountCtx CountCtx;
8650bce8354Sdrh struct CountCtx {
8660bce8354Sdrh   int n;
8670bce8354Sdrh };
868dd5baa95Sdrh 
8690bce8354Sdrh /*
8700bce8354Sdrh ** Routines to implement the count() aggregate function.
8710bce8354Sdrh */
8720ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
8730bce8354Sdrh   CountCtx *p;
8744f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8759c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
8760bce8354Sdrh     p->n++;
8770bce8354Sdrh   }
8780bce8354Sdrh }
8790ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
8800bce8354Sdrh   CountCtx *p;
8814f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
882f4479501Sdrh   sqlite3_result_int(context, p ? p->n : 0);
8830bce8354Sdrh }
8840bce8354Sdrh 
8850bce8354Sdrh /*
8860bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
8870bce8354Sdrh */
8880ae8b831Sdanielk1977 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88988208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
8909eb516c0Sdrh   Mem *pBest;
8919eb516c0Sdrh 
8929eb516c0Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
8939eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
8943aeab9e4Sdanielk1977   if( !pBest ) return;
895268380caSdrh 
89688208050Sdanielk1977   if( pBest->flags ){
8979eb516c0Sdrh     int max;
8989eb516c0Sdrh     int cmp;
899dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
9007e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
9017e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
9027e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
9037e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
9047e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
9057e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
9067e18c259Sdanielk1977     ** aggregate, or 0 for min().
9077e18c259Sdanielk1977     */
90888208050Sdanielk1977     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
909dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
91088208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
9117e18c259Sdanielk1977       sqlite3VdbeMemCopy(pBest, pArg);
91288208050Sdanielk1977     }
9130bce8354Sdrh   }else{
9147e18c259Sdanielk1977     sqlite3VdbeMemCopy(pBest, pArg);
9150bce8354Sdrh   }
9160bce8354Sdrh }
9170ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
91888208050Sdanielk1977   sqlite3_value *pRes;
9194f26d6c4Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
92088208050Sdanielk1977   if( pRes->flags ){
921f4479501Sdrh     sqlite3_result_value(context, pRes);
9220bce8354Sdrh   }
923b20e56b4Sdanielk1977   sqlite3VdbeMemRelease(pRes);
9240bce8354Sdrh }
925dd5baa95Sdrh 
9264e5ffc5fSdrh 
927d3a149efSdrh /*
928a2ed5601Sdrh ** This function registered all of the above C functions as SQL
929a2ed5601Sdrh ** functions.  This should be the only routine in this file with
930a2ed5601Sdrh ** external linkage.
931dc04c583Sdrh */
9329bb575fdSdrh void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
9335719628aSdrh   static const struct {
9340bce8354Sdrh      char *zName;
935268380caSdrh      signed char nArg;
936268380caSdrh      u8 argType;           /* 0: none.  1: db  2: (-1) */
937d02eb1fdSdanielk1977      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
938dc1bdc4fSdanielk1977      u8 needCollSeq;
9390ae8b831Sdanielk1977      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
9400bce8354Sdrh   } aFuncs[] = {
941d8123366Sdanielk1977     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
942d8123366Sdanielk1977     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
943d8123366Sdanielk1977     { "max",               -1, 2, SQLITE_UTF8,    1, minmaxFunc },
944d8123366Sdanielk1977     { "max",                0, 2, SQLITE_UTF8,    1, 0          },
945d8123366Sdanielk1977     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
946d8123366Sdanielk1977     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
947d8123366Sdanielk1977     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
9486c62608fSdrh #ifndef SQLITE_OMIT_UTF16
949f4618891Sdanielk1977     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
9506c62608fSdrh #endif
951d8123366Sdanielk1977     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
952d8123366Sdanielk1977     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
953d8123366Sdanielk1977     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
954d8123366Sdanielk1977     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
955d8123366Sdanielk1977     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
956d8123366Sdanielk1977     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
957d8123366Sdanielk1977     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
958d8123366Sdanielk1977     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
959d8123366Sdanielk1977     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
960d8123366Sdanielk1977     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
96194a98365Sdrh     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
962d8123366Sdanielk1977     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
963d8123366Sdanielk1977     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
964d8123366Sdanielk1977     { "last_insert_rowid",  0, 1, SQLITE_UTF8,    0, last_insert_rowid },
965b28af71aSdanielk1977     { "changes",            0, 1, SQLITE_UTF8,    0, changes    },
966b28af71aSdanielk1977     { "total_changes",      0, 1, SQLITE_UTF8,    0, total_changes },
967d24cc427Sdrh #ifdef SQLITE_SOUNDEX
968d8123366Sdanielk1977     { "soundex",            1, 0, SQLITE_UTF8, 0, soundexFunc},
969d24cc427Sdrh #endif
970193a6b41Sdrh #ifdef SQLITE_TEST
971d8123366Sdanielk1977     { "randstr",               2, 0, SQLITE_UTF8, 0, randStr    },
972f4618891Sdanielk1977     { "test_destructor",       1, 1, SQLITE_UTF8, 0, test_destructor},
973d8123366Sdanielk1977     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
9743f6b0874Sdanielk1977     { "test_auxdata",         -1, 0, SQLITE_UTF8, 0, test_auxdata},
97501427a62Sdanielk1977     { "test_error",            1, 0, SQLITE_UTF8, 0, test_error},
976193a6b41Sdrh #endif
9770bce8354Sdrh   };
9785719628aSdrh   static const struct {
9790bce8354Sdrh     char *zName;
980268380caSdrh     signed char nArg;
981268380caSdrh     u8 argType;
982dc1bdc4fSdanielk1977     u8 needCollSeq;
9830ae8b831Sdanielk1977     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
9840ae8b831Sdanielk1977     void (*xFinalize)(sqlite3_context*);
9850bce8354Sdrh   } aAggs[] = {
986dc1bdc4fSdanielk1977     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
987dc1bdc4fSdanielk1977     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
988dc1bdc4fSdanielk1977     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
989dc1bdc4fSdanielk1977     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
990dc1bdc4fSdanielk1977     { "count",  0, 0, 0, countStep,    countFinalize  },
991dc1bdc4fSdanielk1977     { "count",  1, 0, 0, countStep,    countFinalize  },
9920bce8354Sdrh   };
9930bce8354Sdrh   int i;
9940bce8354Sdrh 
9950bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
996c572ef7fSdanielk1977     void *pArg = 0;
997c572ef7fSdanielk1977     switch( aFuncs[i].argType ){
998c572ef7fSdanielk1977       case 1: pArg = db; break;
999c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1000c572ef7fSdanielk1977     }
1001ad7dd425Sdanielk1977     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
1002f9d64d2cSdanielk1977         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1003dc1bdc4fSdanielk1977     if( aFuncs[i].needCollSeq ){
1004dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1005dc1bdc4fSdanielk1977           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1006dc1bdc4fSdanielk1977       if( pFunc && aFuncs[i].needCollSeq ){
1007dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1008dc1bdc4fSdanielk1977       }
1009dc1bdc4fSdanielk1977     }
10100bce8354Sdrh   }
10111f01ec1bSdrh #ifndef SQLITE_OMIT_ALTERTABLE
10121f01ec1bSdrh   sqlite3AlterFunctions(db);
10131f01ec1bSdrh #endif
10140bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1015c572ef7fSdanielk1977     void *pArg = 0;
1016c572ef7fSdanielk1977     switch( aAggs[i].argType ){
1017c572ef7fSdanielk1977       case 1: pArg = db; break;
1018c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1019c572ef7fSdanielk1977     }
1020d8123366Sdanielk1977     sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1021f9d64d2cSdanielk1977         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1022dc1bdc4fSdanielk1977     if( aAggs[i].needCollSeq ){
1023dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1024d8123366Sdanielk1977           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1025dc1bdc4fSdanielk1977       if( pFunc && aAggs[i].needCollSeq ){
1026dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1027dc1bdc4fSdanielk1977       }
1028dc1bdc4fSdanielk1977     }
1029268380caSdrh   }
10304adee20fSdanielk1977   sqlite3RegisterDateTimeFunctions(db);
1031fd9e1f31Sdanielk1977 #ifdef SQLITE_SSE
1032fd9e1f31Sdanielk1977   sqlite3SseFunctions(db);
1033fd9e1f31Sdanielk1977 #endif
103455ef4d97Sdrh #ifdef SQLITE_CASE_SENSITIVE_LIKE
103555ef4d97Sdrh   sqlite3RegisterLikeFunctions(db, 1);
103655ef4d97Sdrh #else
103755ef4d97Sdrh   sqlite3RegisterLikeFunctions(db, 0);
103855ef4d97Sdrh #endif
103955ef4d97Sdrh }
104055ef4d97Sdrh 
104155ef4d97Sdrh /*
104255ef4d97Sdrh ** Set the LIKEOPT flag on the 2-argument function with the given name.
104355ef4d97Sdrh */
1044*d64fe2f3Sdrh static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
104555ef4d97Sdrh   FuncDef *pDef;
104655ef4d97Sdrh   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
104755ef4d97Sdrh   if( pDef ){
1048*d64fe2f3Sdrh     pDef->flags = flagVal;
104955ef4d97Sdrh   }
105055ef4d97Sdrh }
105155ef4d97Sdrh 
105255ef4d97Sdrh /*
105355ef4d97Sdrh ** Register the built-in LIKE and GLOB functions.  The caseSensitive
105455ef4d97Sdrh ** parameter determines whether or not the LIKE operator is case
105555ef4d97Sdrh ** sensitive.  GLOB is always case sensitive.
105655ef4d97Sdrh */
105755ef4d97Sdrh void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
105855ef4d97Sdrh   struct compareInfo *pInfo;
105955ef4d97Sdrh   if( caseSensitive ){
106055ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoAlt;
106155ef4d97Sdrh   }else{
106255ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoNorm;
106355ef4d97Sdrh   }
106455ef4d97Sdrh   sqlite3_create_function(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
106555ef4d97Sdrh   sqlite3_create_function(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
106655ef4d97Sdrh   sqlite3_create_function(db, "glob", 2, SQLITE_UTF8,
106755ef4d97Sdrh       (struct compareInfo*)&globInfo, likeFunc, 0,0);
1068*d64fe2f3Sdrh   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1069*d64fe2f3Sdrh   setLikeOptFlag(db, "like",
1070*d64fe2f3Sdrh       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
107155ef4d97Sdrh }
107255ef4d97Sdrh 
107355ef4d97Sdrh /*
107455ef4d97Sdrh ** pExpr points to an expression which implements a function.  If
107555ef4d97Sdrh ** it is appropriate to apply the LIKE optimization to that function
107655ef4d97Sdrh ** then set aWc[0] through aWc[2] to the wildcard characters and
107755ef4d97Sdrh ** return TRUE.  If the function is not a LIKE-style function then
107855ef4d97Sdrh ** return FALSE.
107955ef4d97Sdrh */
1080*d64fe2f3Sdrh int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
108155ef4d97Sdrh   FuncDef *pDef;
108255ef4d97Sdrh   if( pExpr->op!=TK_FUNCTION ){
108355ef4d97Sdrh     return 0;
108455ef4d97Sdrh   }
108555ef4d97Sdrh   if( pExpr->pList->nExpr!=2 ){
108655ef4d97Sdrh     return 0;
108755ef4d97Sdrh   }
108855ef4d97Sdrh   pDef = sqlite3FindFunction(db, pExpr->token.z, pExpr->token.n, 2,
108955ef4d97Sdrh                              SQLITE_UTF8, 0);
1090*d64fe2f3Sdrh   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
109155ef4d97Sdrh     return 0;
109255ef4d97Sdrh   }
109355ef4d97Sdrh 
109455ef4d97Sdrh   /* The memcpy() statement assumes that the wildcard characters are
109555ef4d97Sdrh   ** the first three statements in the compareInfo structure.  The
109655ef4d97Sdrh   ** asserts() that follow verify that assumption
109755ef4d97Sdrh   */
109855ef4d97Sdrh   memcpy(aWc, pDef->pUserData, 3);
109955ef4d97Sdrh   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
110055ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
110155ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1102*d64fe2f3Sdrh   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
110355ef4d97Sdrh   return 1;
1104dc04c583Sdrh }
1105