xref: /sqlite-3.40.0/src/func.c (revision b56fe1ff)
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*b56fe1ffSdanielk1977 ** $Id: func.c,v 1.153 2007/05/09 08:24:44 danielk1977 Exp $
20dc04c583Sdrh */
21b659e9bfSdrh #include "sqliteInt.h"
22dc04c583Sdrh #include <ctype.h>
23b37df7b9Sdrh /* #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: {
1042646da7eSdrh       const unsigned char *z = sqlite3_value_text(argv[0]);
1057a521cfbSdrh       if( z==0 ) return;
1060bce8354Sdrh       for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
107f4479501Sdrh       sqlite3_result_int(context, len);
108f9b596ebSdrh       break;
109f9b596ebSdrh     }
110f9b596ebSdrh     default: {
111f9b596ebSdrh       sqlite3_result_null(context);
112f9b596ebSdrh       break;
113f9b596ebSdrh     }
114f9b596ebSdrh   }
1150bce8354Sdrh }
1160bce8354Sdrh 
1170bce8354Sdrh /*
1180bce8354Sdrh ** Implementation of the abs() function
1190bce8354Sdrh */
1200ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1210bce8354Sdrh   assert( argc==1 );
122f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1239c054830Sdrh     case SQLITE_INTEGER: {
124f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
12552fc849aSdrh       if( iVal<0 ){
12652fc849aSdrh         if( (iVal<<1)==0 ){
12752fc849aSdrh           sqlite3_result_error(context, "integer overflow", -1);
12852fc849aSdrh           return;
12952fc849aSdrh         }
13052fc849aSdrh         iVal = -iVal;
13152fc849aSdrh       }
132f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
133f9b596ebSdrh       break;
134f9b596ebSdrh     }
1359c054830Sdrh     case SQLITE_NULL: {
136f9b596ebSdrh       sqlite3_result_null(context);
137f9b596ebSdrh       break;
138f9b596ebSdrh     }
139f9b596ebSdrh     default: {
140f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
14152fc849aSdrh       if( rVal<0 ) rVal = -rVal;
142f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
143f9b596ebSdrh       break;
144f9b596ebSdrh     }
145f9b596ebSdrh   }
1460bce8354Sdrh }
1470bce8354Sdrh 
1480bce8354Sdrh /*
1490bce8354Sdrh ** Implementation of the substr() function
1500bce8354Sdrh */
151f9b596ebSdrh static void substrFunc(
152f9b596ebSdrh   sqlite3_context *context,
153f9b596ebSdrh   int argc,
154f9b596ebSdrh   sqlite3_value **argv
155f9b596ebSdrh ){
1562646da7eSdrh   const unsigned char *z;
1572646da7eSdrh   const unsigned char *z2;
1580bce8354Sdrh   int i;
159023ae03aSdrh   int len;
160023ae03aSdrh   i64 p1, p2;
161f9b596ebSdrh 
1620bce8354Sdrh   assert( argc==3 );
1634f26d6c4Sdrh   z = sqlite3_value_text(argv[0]);
1640bce8354Sdrh   if( z==0 ) return;
16551ad0ecdSdanielk1977   p1 = sqlite3_value_int(argv[1]);
16651ad0ecdSdanielk1977   p2 = sqlite3_value_int(argv[2]);
16747c8a679Sdrh   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
1680bce8354Sdrh   if( p1<0 ){
16989425d5eSdrh     p1 += len;
170653bc759Sdrh     if( p1<0 ){
171653bc759Sdrh       p2 += p1;
172653bc759Sdrh       p1 = 0;
173653bc759Sdrh     }
1740bce8354Sdrh   }else if( p1>0 ){
1750bce8354Sdrh     p1--;
1760bce8354Sdrh   }
1770bce8354Sdrh   if( p1+p2>len ){
1780bce8354Sdrh     p2 = len-p1;
1790bce8354Sdrh   }
18077396304Sdrh   for(i=0; i<p1 && z[i]; i++){
18147c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p1++;
1820bce8354Sdrh   }
18347c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
18477396304Sdrh   for(; i<p1+p2 && z[i]; i++){
18547c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p2++;
1860bce8354Sdrh   }
18747c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
188653bc759Sdrh   if( p2<0 ) p2 = 0;
1892646da7eSdrh   sqlite3_result_text(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
1900bce8354Sdrh }
1910bce8354Sdrh 
1920bce8354Sdrh /*
1930bce8354Sdrh ** Implementation of the round() function
1940bce8354Sdrh */
1950ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
19651ad0ecdSdanielk1977   int n = 0;
1970bce8354Sdrh   double r;
198592ac8cbSdrh   char zBuf[500];  /* larger than the %f representation of the largest double */
1990bce8354Sdrh   assert( argc==1 || argc==2 );
20051ad0ecdSdanielk1977   if( argc==2 ){
2019c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
20251ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
2030bce8354Sdrh     if( n>30 ) n = 30;
2040bce8354Sdrh     if( n<0 ) n = 0;
20551ad0ecdSdanielk1977   }
206d589a92aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
2074f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
208e866fcb9Sdrh   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
209502b962bSdrh   sqlite3AtoF(zBuf, &r);
210502b962bSdrh   sqlite3_result_double(context, r);
2110bce8354Sdrh }
212dc04c583Sdrh 
213dc04c583Sdrh /*
214dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
215dc04c583Sdrh */
2160ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2177a521cfbSdrh   char *z1;
2187a521cfbSdrh   const char *z2;
2199310ef23Sdrh   int i, n;
2209c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
2219310ef23Sdrh   n = sqlite3_value_bytes(argv[0]);
2227a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
2237a521cfbSdrh   if( z2 ){
2249310ef23Sdrh     z1 = sqlite3_malloc(n+1);
2257a521cfbSdrh     if( z1 ){
2265bb3eb9bSdrh       memcpy(z1, z2, n+1);
2277a521cfbSdrh       for(i=0; z1[i]; i++){
2287a521cfbSdrh         z1[i] = toupper(z1[i]);
229dc04c583Sdrh       }
2307a521cfbSdrh       sqlite3_result_text(context, z1, -1, sqlite3_free);
2317a521cfbSdrh     }
2327a521cfbSdrh   }
233dc04c583Sdrh }
2340ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2357a521cfbSdrh   char *z1;
2367a521cfbSdrh   const char *z2;
2379310ef23Sdrh   int i, n;
2389c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
2399310ef23Sdrh   n = sqlite3_value_bytes(argv[0]);
2407a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
2417a521cfbSdrh   if( z2 ){
2429310ef23Sdrh     z1 = sqlite3_malloc(n+1);
2437a521cfbSdrh     if( z1 ){
2445bb3eb9bSdrh       memcpy(z1, z2, n+1);
2457a521cfbSdrh       for(i=0; z1[i]; i++){
2467a521cfbSdrh         z1[i] = tolower(z1[i]);
247dc04c583Sdrh       }
2487a521cfbSdrh       sqlite3_result_text(context, z1, -1, sqlite3_free);
2497a521cfbSdrh     }
2507a521cfbSdrh   }
251dc04c583Sdrh }
252dc04c583Sdrh 
253dc04c583Sdrh /*
254fbc99082Sdrh ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
255b6c9e6e6Sjplyon ** All three do the same thing.  They return the first non-NULL
256b6c9e6e6Sjplyon ** argument.
2573212e182Sdrh */
258f9b596ebSdrh static void ifnullFunc(
259f9b596ebSdrh   sqlite3_context *context,
260f9b596ebSdrh   int argc,
261f9b596ebSdrh   sqlite3_value **argv
262f9b596ebSdrh ){
263fbc99082Sdrh   int i;
264fbc99082Sdrh   for(i=0; i<argc; i++){
2659c054830Sdrh     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
266f4479501Sdrh       sqlite3_result_value(context, argv[i]);
267fbc99082Sdrh       break;
268fbc99082Sdrh     }
269fbc99082Sdrh   }
2703212e182Sdrh }
2713212e182Sdrh 
2723212e182Sdrh /*
273f9ffac96Sdrh ** Implementation of random().  Return a random integer.
274f9ffac96Sdrh */
275f9b596ebSdrh static void randomFunc(
276f9b596ebSdrh   sqlite3_context *context,
277f9b596ebSdrh   int argc,
278f9b596ebSdrh   sqlite3_value **argv
279f9b596ebSdrh ){
28052fc849aSdrh   sqlite_int64 r;
2814adee20fSdanielk1977   sqlite3Randomness(sizeof(r), &r);
282874abbedSdrh   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
283874abbedSdrh                           /* can always do abs() of the result */
28452fc849aSdrh   sqlite3_result_int64(context, r);
285f9ffac96Sdrh }
286f9ffac96Sdrh 
287f9ffac96Sdrh /*
288137c728fSdrh ** Implementation of randomblob(N).  Return a random blob
289137c728fSdrh ** that is N bytes long.
29063cf66f0Sdrh */
291137c728fSdrh static void randomBlob(
29263cf66f0Sdrh   sqlite3_context *context,
29363cf66f0Sdrh   int argc,
29463cf66f0Sdrh   sqlite3_value **argv
29563cf66f0Sdrh ){
296137c728fSdrh   int n;
297137c728fSdrh   unsigned char *p;
29863cf66f0Sdrh   assert( argc==1 );
29963cf66f0Sdrh   n = sqlite3_value_int(argv[0]);
300023ae03aSdrh   if( n<1 ){
301023ae03aSdrh     n = 1;
302023ae03aSdrh   }
303023ae03aSdrh   if( n>SQLITE_MAX_LENGTH ){
304a0206bc8Sdrh     sqlite3_result_error_toobig(context);
305023ae03aSdrh     return;
306023ae03aSdrh   }
30702d85836Sdrh   p = sqliteMalloc(n);
30802d85836Sdrh   if( p ){
309137c728fSdrh     sqlite3Randomness(n, p);
31002d85836Sdrh     sqlite3_result_blob(context, (char*)p, n, sqlite3FreeX);
31102d85836Sdrh   }
31263cf66f0Sdrh }
31363cf66f0Sdrh 
31463cf66f0Sdrh /*
3156ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
31624b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
3176ed41ad7Sdrh */
31851ad0ecdSdanielk1977 static void last_insert_rowid(
3190ae8b831Sdanielk1977   sqlite3_context *context,
32051ad0ecdSdanielk1977   int arg,
32151ad0ecdSdanielk1977   sqlite3_value **argv
32251ad0ecdSdanielk1977 ){
3239bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
324f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
3256ed41ad7Sdrh }
3266ed41ad7Sdrh 
327f146a776Srdc /*
328b28af71aSdanielk1977 ** Implementation of the changes() SQL function.  The return value is the
329b28af71aSdanielk1977 ** same as the sqlite3_changes() API function.
330f146a776Srdc */
331b28af71aSdanielk1977 static void changes(
332f9b596ebSdrh   sqlite3_context *context,
333f9b596ebSdrh   int arg,
334f9b596ebSdrh   sqlite3_value **argv
335f9b596ebSdrh ){
3369bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
337f4479501Sdrh   sqlite3_result_int(context, sqlite3_changes(db));
338b0c374ffSrdc }
339f146a776Srdc 
340f146a776Srdc /*
341b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
342b28af71aSdanielk1977 ** the same as the sqlite3_total_changes() API function.
343f146a776Srdc */
344b28af71aSdanielk1977 static void total_changes(
3450ae8b831Sdanielk1977   sqlite3_context *context,
34651ad0ecdSdanielk1977   int arg,
34751ad0ecdSdanielk1977   sqlite3_value **argv
34851ad0ecdSdanielk1977 ){
3499bb575fdSdrh   sqlite3 *db = sqlite3_user_data(context);
350b28af71aSdanielk1977   sqlite3_result_int(context, sqlite3_total_changes(db));
351b0c374ffSrdc }
352b0c374ffSrdc 
3536ed41ad7Sdrh /*
3544e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
355d02eb1fdSdanielk1977 */
3564e5ffc5fSdrh struct compareInfo {
3574e5ffc5fSdrh   u8 matchAll;
3584e5ffc5fSdrh   u8 matchOne;
3594e5ffc5fSdrh   u8 matchSet;
3604e5ffc5fSdrh   u8 noCase;
361d02eb1fdSdanielk1977 };
36255ef4d97Sdrh 
3634e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
36470031fa3Sdrh /* The correct SQL-92 behavior is for the LIKE operator to ignore
36570031fa3Sdrh ** case.  Thus  'a' LIKE 'A' would be true. */
36655ef4d97Sdrh static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
36770031fa3Sdrh /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
36870031fa3Sdrh ** is case sensitive causing 'a' LIKE 'A' to be false */
36955ef4d97Sdrh static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
370d02eb1fdSdanielk1977 
371d02eb1fdSdanielk1977 /*
3724e5ffc5fSdrh ** X is a pointer to the first byte of a UTF-8 character.  Increment
3734e5ffc5fSdrh ** X so that it points to the next character.  This only works right
3744e5ffc5fSdrh ** if X points to a well-formed UTF-8 string.
375d02eb1fdSdanielk1977 */
3764e5ffc5fSdrh #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
3774e5ffc5fSdrh #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
378d02eb1fdSdanielk1977 
379d02eb1fdSdanielk1977 
380d02eb1fdSdanielk1977 /*
3814e5ffc5fSdrh ** Compare two UTF-8 strings for equality where the first string can
3824e5ffc5fSdrh ** potentially be a "glob" expression.  Return true (1) if they
3834e5ffc5fSdrh ** are the same and false (0) if they are different.
3840ac65892Sdrh **
3854e5ffc5fSdrh ** Globbing rules:
3860ac65892Sdrh **
3874e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
388d02eb1fdSdanielk1977 **
3894e5ffc5fSdrh **      '?'       Matches exactly one character.
3904e5ffc5fSdrh **
3914e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
3924e5ffc5fSdrh **                characters.
3934e5ffc5fSdrh **
3944e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
3954e5ffc5fSdrh **
3964e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
3974e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
3984e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
3994e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
4004e5ffc5fSdrh ** it the last character in the list.
4014e5ffc5fSdrh **
4024e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
4034e5ffc5fSdrh **
4044e5ffc5fSdrh ** Hints: to match '*' or '?', put them in "[]".  Like this:
4054e5ffc5fSdrh **
4064e5ffc5fSdrh **         abc[*]xyz        Matches "abc*xyz" only
4070ac65892Sdrh */
4087c6303c0Sdanielk1977 static int patternCompare(
4094e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
4104e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
4117c6303c0Sdanielk1977   const struct compareInfo *pInfo, /* Information about how to do the compare */
4127c6303c0Sdanielk1977   const int esc                    /* The escape character */
41351ad0ecdSdanielk1977 ){
414ad7dd425Sdanielk1977   register int c;
4154e5ffc5fSdrh   int invert;
4164e5ffc5fSdrh   int seen;
4174e5ffc5fSdrh   int c2;
4184e5ffc5fSdrh   u8 matchOne = pInfo->matchOne;
4194e5ffc5fSdrh   u8 matchAll = pInfo->matchAll;
4204e5ffc5fSdrh   u8 matchSet = pInfo->matchSet;
4214e5ffc5fSdrh   u8 noCase = pInfo->noCase;
4227c6303c0Sdanielk1977   int prevEscape = 0;     /* True if the previous character was 'escape' */
423d02eb1fdSdanielk1977 
4244e5ffc5fSdrh   while( (c = *zPattern)!=0 ){
4257c6303c0Sdanielk1977     if( !prevEscape && c==matchAll ){
4264e5ffc5fSdrh       while( (c=zPattern[1]) == matchAll || c == matchOne ){
4274e5ffc5fSdrh         if( c==matchOne ){
4284e5ffc5fSdrh           if( *zString==0 ) return 0;
4294e5ffc5fSdrh           sqliteNextChar(zString);
430d02eb1fdSdanielk1977         }
4314e5ffc5fSdrh         zPattern++;
4324e5ffc5fSdrh       }
43320fc0887Sdrh       if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
4347c6303c0Sdanielk1977         u8 const *zTemp = &zPattern[1];
4357c6303c0Sdanielk1977         sqliteNextChar(zTemp);
4367c6303c0Sdanielk1977         c = *zTemp;
4377c6303c0Sdanielk1977       }
4384e5ffc5fSdrh       if( c==0 ) return 1;
4394e5ffc5fSdrh       if( c==matchSet ){
4407c6303c0Sdanielk1977         assert( esc==0 );   /* This is GLOB, not LIKE */
4417c6303c0Sdanielk1977         while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
4424e5ffc5fSdrh           sqliteNextChar(zString);
4434e5ffc5fSdrh         }
4444e5ffc5fSdrh         return *zString!=0;
445d02eb1fdSdanielk1977       }else{
4464e5ffc5fSdrh         while( (c2 = *zString)!=0 ){
4474e5ffc5fSdrh           if( noCase ){
4484e5ffc5fSdrh             c2 = sqlite3UpperToLower[c2];
4494e5ffc5fSdrh             c = sqlite3UpperToLower[c];
4504e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
451ad7dd425Sdanielk1977           }else{
4524e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
453ad7dd425Sdanielk1977           }
4544e5ffc5fSdrh           if( c2==0 ) return 0;
4557c6303c0Sdanielk1977           if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
4564e5ffc5fSdrh           sqliteNextChar(zString);
4574e5ffc5fSdrh         }
4584e5ffc5fSdrh         return 0;
4594e5ffc5fSdrh       }
4607c6303c0Sdanielk1977     }else if( !prevEscape && c==matchOne ){
4614e5ffc5fSdrh       if( *zString==0 ) return 0;
4624e5ffc5fSdrh       sqliteNextChar(zString);
4634e5ffc5fSdrh       zPattern++;
4644e5ffc5fSdrh     }else if( c==matchSet ){
4654e5ffc5fSdrh       int prior_c = 0;
4667c6303c0Sdanielk1977       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
4674e5ffc5fSdrh       seen = 0;
4684e5ffc5fSdrh       invert = 0;
4694e5ffc5fSdrh       c = sqliteCharVal(zString);
4704e5ffc5fSdrh       if( c==0 ) return 0;
4714e5ffc5fSdrh       c2 = *++zPattern;
4724e5ffc5fSdrh       if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
4734e5ffc5fSdrh       if( c2==']' ){
4744e5ffc5fSdrh         if( c==']' ) seen = 1;
4754e5ffc5fSdrh         c2 = *++zPattern;
4764e5ffc5fSdrh       }
4774e5ffc5fSdrh       while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
4784e5ffc5fSdrh         if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
4794e5ffc5fSdrh           zPattern++;
4804e5ffc5fSdrh           c2 = sqliteCharVal(zPattern);
4814e5ffc5fSdrh           if( c>=prior_c && c<=c2 ) seen = 1;
4824e5ffc5fSdrh           prior_c = 0;
4834e5ffc5fSdrh         }else if( c==c2 ){
4844e5ffc5fSdrh           seen = 1;
4854e5ffc5fSdrh           prior_c = c2;
486d02eb1fdSdanielk1977         }else{
4874e5ffc5fSdrh           prior_c = c2;
488d02eb1fdSdanielk1977         }
4894e5ffc5fSdrh         sqliteNextChar(zPattern);
490d02eb1fdSdanielk1977       }
4914e5ffc5fSdrh       if( c2==0 || (seen ^ invert)==0 ) return 0;
4924e5ffc5fSdrh       sqliteNextChar(zString);
4934e5ffc5fSdrh       zPattern++;
49420fc0887Sdrh     }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
4957c6303c0Sdanielk1977       prevEscape = 1;
4967c6303c0Sdanielk1977       sqliteNextChar(zPattern);
497d02eb1fdSdanielk1977     }else{
4984e5ffc5fSdrh       if( noCase ){
4994e5ffc5fSdrh         if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
5004e5ffc5fSdrh       }else{
5014e5ffc5fSdrh         if( c != *zString ) return 0;
5024e5ffc5fSdrh       }
5034e5ffc5fSdrh       zPattern++;
5044e5ffc5fSdrh       zString++;
5057c6303c0Sdanielk1977       prevEscape = 0;
50651ad0ecdSdanielk1977     }
5070ac65892Sdrh   }
5084e5ffc5fSdrh   return *zString==0;
5094e5ffc5fSdrh }
5104e5ffc5fSdrh 
51155ef4d97Sdrh /*
51255ef4d97Sdrh ** Count the number of times that the LIKE operator (or GLOB which is
51355ef4d97Sdrh ** just a variation of LIKE) gets called.  This is used for testing
51455ef4d97Sdrh ** only.
51555ef4d97Sdrh */
51655ef4d97Sdrh #ifdef SQLITE_TEST
51755ef4d97Sdrh int sqlite3_like_count = 0;
51855ef4d97Sdrh #endif
51955ef4d97Sdrh 
5203f6b0874Sdanielk1977 
5213f6b0874Sdanielk1977 /*
5223f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
5233f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
5243f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
5253f6b0874Sdanielk1977 **
5263f6b0874Sdanielk1977 **       A LIKE B
5273f6b0874Sdanielk1977 **
5283f6b0874Sdanielk1977 ** is implemented as like(B,A).
5293f6b0874Sdanielk1977 **
53055ef4d97Sdrh ** This same function (with a different compareInfo structure) computes
53155ef4d97Sdrh ** the GLOB operator.
5323f6b0874Sdanielk1977 */
5333f6b0874Sdanielk1977 static void likeFunc(
5343f6b0874Sdanielk1977   sqlite3_context *context,
5353f6b0874Sdanielk1977   int argc,
5363f6b0874Sdanielk1977   sqlite3_value **argv
5373f6b0874Sdanielk1977 ){
538beb818d1Sdrh   const unsigned char *zA, *zB;
539beb818d1Sdrh 
540beb818d1Sdrh   /* Limit the length of the LIKE or GLOB pattern to avoid problems
541beb818d1Sdrh   ** of deep recursion and N*N behavior in patternCompare().
542beb818d1Sdrh   */
543*b56fe1ffSdanielk1977   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
544beb818d1Sdrh     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
545beb818d1Sdrh     return;
546beb818d1Sdrh   }
547beb818d1Sdrh 
548*b56fe1ffSdanielk1977   zB = sqlite3_value_text(argv[0]);
549*b56fe1ffSdanielk1977   zA = sqlite3_value_text(argv[1]);
5507c6303c0Sdanielk1977   int escape = 0;
5517c6303c0Sdanielk1977   if( argc==3 ){
5527c6303c0Sdanielk1977     /* The escape character string must consist of a single UTF-8 character.
5537c6303c0Sdanielk1977     ** Otherwise, return an error.
5547c6303c0Sdanielk1977     */
5557c6303c0Sdanielk1977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
5567a521cfbSdrh     if( zEsc==0 ) return;
557ee85813cSdrh     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
5587c6303c0Sdanielk1977       sqlite3_result_error(context,
5597c6303c0Sdanielk1977           "ESCAPE expression must be a single character", -1);
5607c6303c0Sdanielk1977       return;
5617c6303c0Sdanielk1977     }
5627c6303c0Sdanielk1977     escape = sqlite3ReadUtf8(zEsc);
5637c6303c0Sdanielk1977   }
5643f6b0874Sdanielk1977   if( zA && zB ){
56555ef4d97Sdrh     struct compareInfo *pInfo = sqlite3_user_data(context);
56655ef4d97Sdrh #ifdef SQLITE_TEST
56755ef4d97Sdrh     sqlite3_like_count++;
56855ef4d97Sdrh #endif
569beb818d1Sdrh 
570*b56fe1ffSdanielk1977     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
57151ad0ecdSdanielk1977   }
5728912d106Sdrh }
5738912d106Sdrh 
5748912d106Sdrh /*
5758912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
5768912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
5778912d106Sdrh ** arguments are equal to each other.
5788912d106Sdrh */
579f9b596ebSdrh static void nullifFunc(
580f9b596ebSdrh   sqlite3_context *context,
581f9b596ebSdrh   int argc,
582f9b596ebSdrh   sqlite3_value **argv
583f9b596ebSdrh ){
584dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
585dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
586f4479501Sdrh     sqlite3_result_value(context, argv[0]);
5878912d106Sdrh   }
5880ac65892Sdrh }
5890ac65892Sdrh 
590647cb0e1Sdrh /*
591647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
592647cb0e1Sdrh ** of the SQLite library that is running.
593647cb0e1Sdrh */
594f9b596ebSdrh static void versionFunc(
595f9b596ebSdrh   sqlite3_context *context,
596f9b596ebSdrh   int argc,
597f9b596ebSdrh   sqlite3_value **argv
598f9b596ebSdrh ){
599d8123366Sdanielk1977   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
600647cb0e1Sdrh }
601647cb0e1Sdrh 
602137c728fSdrh /* Array for converting from half-bytes (nybbles) into ASCII hex
603137c728fSdrh ** digits. */
604137c728fSdrh static const char hexdigits[] = {
605137c728fSdrh   '0', '1', '2', '3', '4', '5', '6', '7',
606137c728fSdrh   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
607137c728fSdrh };
608d641d646Sdanielk1977 
60947394703Sdrh /*
61047394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
61147394703Sdrh ** change.  This function may disappear.  Do not write code that depends
61247394703Sdrh ** on this function.
61347394703Sdrh **
61447394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
61547394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
61647394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
61747394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
61847394703Sdrh ** single-quote escapes.
61947394703Sdrh */
6200ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62147394703Sdrh   if( argc<1 ) return;
622f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
6239c054830Sdrh     case SQLITE_NULL: {
624d8123366Sdanielk1977       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
625f9b596ebSdrh       break;
626f9b596ebSdrh     }
6279c054830Sdrh     case SQLITE_INTEGER:
6289c054830Sdrh     case SQLITE_FLOAT: {
629f4479501Sdrh       sqlite3_result_value(context, argv[0]);
630f9b596ebSdrh       break;
631f9b596ebSdrh     }
6323f41e976Sdanielk1977     case SQLITE_BLOB: {
6333f41e976Sdanielk1977       char *zText = 0;
6343f41e976Sdanielk1977       int nBlob = sqlite3_value_bytes(argv[0]);
6353f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
6363f41e976Sdanielk1977 
637023ae03aSdrh       if( 2*nBlob+4>SQLITE_MAX_LENGTH ){
638a0206bc8Sdrh         sqlite3_result_error_toobig(context);
639023ae03aSdrh         return;
640023ae03aSdrh       }
6413f41e976Sdanielk1977       zText = (char *)sqliteMalloc((2*nBlob)+4);
6423f41e976Sdanielk1977       if( !zText ){
6433f41e976Sdanielk1977         sqlite3_result_error(context, "out of memory", -1);
6443f41e976Sdanielk1977       }else{
6453f41e976Sdanielk1977         int i;
6463f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
6473f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
6483f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
6493f41e976Sdanielk1977         }
6503f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
6513f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
6523f41e976Sdanielk1977         zText[0] = 'X';
6533f41e976Sdanielk1977         zText[1] = '\'';
654d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
6553f41e976Sdanielk1977         sqliteFree(zText);
6563f41e976Sdanielk1977       }
6573f41e976Sdanielk1977       break;
6583f41e976Sdanielk1977     }
6599c054830Sdrh     case SQLITE_TEXT: {
660023ae03aSdrh       int i,j;
661023ae03aSdrh       u64 n;
6622646da7eSdrh       const unsigned char *zArg = sqlite3_value_text(argv[0]);
66347394703Sdrh       char *z;
664f9b596ebSdrh 
6657a521cfbSdrh       if( zArg==0 ) return;
666023ae03aSdrh       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
667023ae03aSdrh       if( i+n+3>SQLITE_MAX_LENGTH ){
668a0206bc8Sdrh         sqlite3_result_error_toobig(context);
669023ae03aSdrh         return;
670023ae03aSdrh       }
67147394703Sdrh       z = sqliteMalloc( i+n+3 );
67247394703Sdrh       if( z==0 ) return;
67347394703Sdrh       z[0] = '\'';
67451ad0ecdSdanielk1977       for(i=0, j=1; zArg[i]; i++){
67551ad0ecdSdanielk1977         z[j++] = zArg[i];
67651ad0ecdSdanielk1977         if( zArg[i]=='\'' ){
67747394703Sdrh           z[j++] = '\'';
67847394703Sdrh         }
67947394703Sdrh       }
68047394703Sdrh       z[j++] = '\'';
68147394703Sdrh       z[j] = 0;
682d8123366Sdanielk1977       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
68347394703Sdrh       sqliteFree(z);
68447394703Sdrh     }
68547394703Sdrh   }
686f9b596ebSdrh }
68747394703Sdrh 
688137c728fSdrh /*
689137c728fSdrh ** The hex() function.  Interpret the argument as a blob.  Return
690137c728fSdrh ** a hexadecimal rendering as text.
691137c728fSdrh */
692137c728fSdrh static void hexFunc(
693137c728fSdrh   sqlite3_context *context,
694137c728fSdrh   int argc,
695137c728fSdrh   sqlite3_value **argv
696137c728fSdrh ){
697137c728fSdrh   int i, n;
698137c728fSdrh   const unsigned char *pBlob;
699137c728fSdrh   char *zHex, *z;
700137c728fSdrh   assert( argc==1 );
701137c728fSdrh   n = sqlite3_value_bytes(argv[0]);
702023ae03aSdrh   if( n*2+1>SQLITE_MAX_LENGTH ){
703a0206bc8Sdrh     sqlite3_result_error_toobig(context);
704023ae03aSdrh     return;
705023ae03aSdrh   }
7061eb2538aSdrh   pBlob = sqlite3_value_blob(argv[0]);
707137c728fSdrh   z = zHex = sqlite3_malloc(n*2 + 1);
708137c728fSdrh   if( zHex==0 ) return;
709137c728fSdrh   for(i=0; i<n; i++, pBlob++){
710137c728fSdrh     unsigned char c = *pBlob;
711137c728fSdrh     *(z++) = hexdigits[(c>>4)&0xf];
712137c728fSdrh     *(z++) = hexdigits[c&0xf];
713137c728fSdrh   }
714137c728fSdrh   *z = 0;
715137c728fSdrh   sqlite3_result_text(context, zHex, n*2, sqlite3_free);
716137c728fSdrh }
717137c728fSdrh 
71826b6d90dSdrh /*
7198cff382eSdrh ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
7208cff382eSdrh */
7218cff382eSdrh static void zeroblobFunc(
7228cff382eSdrh   sqlite3_context *context,
7238cff382eSdrh   int argc,
7248cff382eSdrh   sqlite3_value **argv
7258cff382eSdrh ){
7268cff382eSdrh   int n;
7278cff382eSdrh   assert( argc==1 );
7288cff382eSdrh   n = sqlite3_value_int(argv[0]);
7298cff382eSdrh   sqlite3_result_zeroblob(context, n);
7308cff382eSdrh }
7318cff382eSdrh 
7328cff382eSdrh /*
73326b6d90dSdrh ** The replace() function.  Three arguments are all strings: call
73426b6d90dSdrh ** them A, B, and C. The result is also a string which is derived
73526b6d90dSdrh ** from A by replacing every occurance of B with C.  The match
73626b6d90dSdrh ** must be exact.  Collating sequences are not used.
73726b6d90dSdrh */
73826b6d90dSdrh static void replaceFunc(
73926b6d90dSdrh   sqlite3_context *context,
74026b6d90dSdrh   int argc,
74126b6d90dSdrh   sqlite3_value **argv
74226b6d90dSdrh ){
74326b6d90dSdrh   const unsigned char *zStr;        /* The input string A */
74426b6d90dSdrh   const unsigned char *zPattern;    /* The pattern string B */
74526b6d90dSdrh   const unsigned char *zRep;        /* The replacement string C */
74626b6d90dSdrh   unsigned char *zOut;              /* The output */
74726b6d90dSdrh   int nStr;                /* Size of zStr */
74826b6d90dSdrh   int nPattern;            /* Size of zPattern */
74926b6d90dSdrh   int nRep;                /* Size of zRep */
7502e6400baSdrh   i64 nOut;                /* Maximum size of zOut */
75126b6d90dSdrh   int loopLimit;           /* Last zStr[] that might match zPattern[] */
75226b6d90dSdrh   int i, j;                /* Loop counters */
75326b6d90dSdrh 
75426b6d90dSdrh   assert( argc==3 );
7559310ef23Sdrh   nStr = sqlite3_value_bytes(argv[0]);
75626b6d90dSdrh   zStr = sqlite3_value_text(argv[0]);
7577a521cfbSdrh   if( zStr==0 ) return;
7589310ef23Sdrh   nPattern = sqlite3_value_bytes(argv[1]);
75926b6d90dSdrh   zPattern = sqlite3_value_text(argv[1]);
760709cff33Sdrh   if( zPattern==0 || zPattern[0]==0 ) return;
7619310ef23Sdrh   nRep = sqlite3_value_bytes(argv[2]);
76226b6d90dSdrh   zRep = sqlite3_value_text(argv[2]);
7637a521cfbSdrh   if( zRep==0 ) return;
7642e6400baSdrh   nOut = nStr + 1;
7652e6400baSdrh   assert( nOut<SQLITE_MAX_LENGTH );
7662e6400baSdrh   zOut = sqlite3_malloc((int)nOut);
7672e6400baSdrh   if( zOut==0 ){
7682e6400baSdrh     return;
76926b6d90dSdrh   }
77026b6d90dSdrh   loopLimit = nStr - nPattern;
77126b6d90dSdrh   for(i=j=0; i<=loopLimit; i++){
77226b6d90dSdrh     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
77326b6d90dSdrh       zOut[j++] = zStr[i];
77426b6d90dSdrh     }else{
7752e6400baSdrh       nOut += nRep - nPattern;
7762e6400baSdrh       if( nOut>=SQLITE_MAX_LENGTH ){
777a0206bc8Sdrh         sqlite3_result_error_toobig(context);
77817374e8fSdanielk1977         sqlite3_free(zOut);
77917374e8fSdanielk1977         return;
78017374e8fSdanielk1977       }
7812e6400baSdrh       zOut = sqlite3_realloc(zOut, (int)nOut);
7822e6400baSdrh       if( zOut==0 ){
7832e6400baSdrh         return;
7842e6400baSdrh       }
78526b6d90dSdrh       memcpy(&zOut[j], zRep, nRep);
78626b6d90dSdrh       j += nRep;
78726b6d90dSdrh       i += nPattern-1;
78826b6d90dSdrh     }
78926b6d90dSdrh   }
7902e6400baSdrh   assert( j+nStr-i+1==nOut );
79126b6d90dSdrh   memcpy(&zOut[j], &zStr[i], nStr-i);
79226b6d90dSdrh   j += nStr - i;
79326b6d90dSdrh   assert( j<=nOut );
79426b6d90dSdrh   zOut[j] = 0;
79526b6d90dSdrh   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
79626b6d90dSdrh }
79726b6d90dSdrh 
798309b3386Sdrh /*
799309b3386Sdrh ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
800309b3386Sdrh ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
801309b3386Sdrh */
802309b3386Sdrh static void trimFunc(
803309b3386Sdrh   sqlite3_context *context,
804309b3386Sdrh   int argc,
805309b3386Sdrh   sqlite3_value **argv
806309b3386Sdrh ){
807309b3386Sdrh   const unsigned char *zIn;         /* Input string */
808309b3386Sdrh   const unsigned char *zCharSet;    /* Set of characters to trim */
809309b3386Sdrh   int nIn;                          /* Number of bytes in input */
810d1e3a616Sdrh   int flags;                        /* 1: trimleft  2: trimright  3: trim */
811d1e3a616Sdrh   int i;                            /* Loop counter */
812d1e3a616Sdrh   unsigned char *aLen;              /* Length of each character in zCharSet */
813d1e3a616Sdrh   const unsigned char **azChar;     /* Individual characters in zCharSet */
814d1e3a616Sdrh   int nChar;                        /* Number of characters in zCharSet */
815d1e3a616Sdrh 
816309b3386Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
817309b3386Sdrh     return;
818309b3386Sdrh   }
8199310ef23Sdrh   nIn = sqlite3_value_bytes(argv[0]);
820309b3386Sdrh   zIn = sqlite3_value_text(argv[0]);
8217a521cfbSdrh   if( zIn==0 ) return;
822309b3386Sdrh   if( argc==1 ){
823d1e3a616Sdrh     static const unsigned char lenOne[] = { 1 };
8248cff382eSdrh     static const unsigned char *azOne[] = { (u8*)" " };
825d1e3a616Sdrh     nChar = 1;
8268cff382eSdrh     aLen = (u8*)lenOne;
8278cff382eSdrh     azChar = azOne;
828d1e3a616Sdrh     zCharSet = 0;
8297a521cfbSdrh   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
830309b3386Sdrh     return;
831d1e3a616Sdrh   }else{
832d1e3a616Sdrh     const unsigned char *z;
833d1e3a616Sdrh     for(z=zCharSet, nChar=0; *z; nChar++){
834d1e3a616Sdrh       sqliteNextChar(z);
835309b3386Sdrh     }
836d1e3a616Sdrh     if( nChar>0 ){
837d1e3a616Sdrh       azChar = sqlite3_malloc( nChar*(sizeof(char*)+1) );
838d1e3a616Sdrh       if( azChar==0 ){
839d1e3a616Sdrh         return;
840d1e3a616Sdrh       }
841d1e3a616Sdrh       aLen = (unsigned char*)&azChar[nChar];
842d1e3a616Sdrh       for(z=zCharSet, nChar=0; *z; nChar++){
843d1e3a616Sdrh         azChar[nChar] = z;
844d1e3a616Sdrh         sqliteNextChar(z);
845d1e3a616Sdrh         aLen[nChar] = z - azChar[nChar];
846d1e3a616Sdrh       }
847d1e3a616Sdrh     }
848d1e3a616Sdrh   }
849d1e3a616Sdrh   if( nChar>0 ){
850309b3386Sdrh     flags = (int)sqlite3_user_data(context);
851309b3386Sdrh     if( flags & 1 ){
852d1e3a616Sdrh       while( nIn>0 ){
853d1e3a616Sdrh         int len;
854d1e3a616Sdrh         for(i=0; i<nChar; i++){
855d1e3a616Sdrh           len = aLen[i];
856d1e3a616Sdrh           if( memcmp(zIn, azChar[i], len)==0 ) break;
857d1e3a616Sdrh         }
858d1e3a616Sdrh         if( i>=nChar ) break;
859d1e3a616Sdrh         zIn += len;
860d1e3a616Sdrh         nIn -= len;
861309b3386Sdrh       }
862309b3386Sdrh     }
863309b3386Sdrh     if( flags & 2 ){
864d1e3a616Sdrh       while( nIn>0 ){
865d1e3a616Sdrh         int len;
866d1e3a616Sdrh         for(i=0; i<nChar; i++){
867d1e3a616Sdrh           len = aLen[i];
868d1e3a616Sdrh           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
869309b3386Sdrh         }
870d1e3a616Sdrh         if( i>=nChar ) break;
871d1e3a616Sdrh         nIn -= len;
872d1e3a616Sdrh       }
873d1e3a616Sdrh     }
874d1e3a616Sdrh     if( zCharSet ){
875d1e3a616Sdrh       sqlite3_free(azChar);
876309b3386Sdrh     }
877309b3386Sdrh   }
878309b3386Sdrh   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
879309b3386Sdrh }
88026b6d90dSdrh 
881d24cc427Sdrh #ifdef SQLITE_SOUNDEX
882d24cc427Sdrh /*
883d24cc427Sdrh ** Compute the soundex encoding of a word.
884d24cc427Sdrh */
885137c728fSdrh static void soundexFunc(
886137c728fSdrh   sqlite3_context *context,
887137c728fSdrh   int argc,
888137c728fSdrh   sqlite3_value **argv
889137c728fSdrh ){
890d24cc427Sdrh   char zResult[8];
8914c755c0fSdrh   const u8 *zIn;
892d24cc427Sdrh   int i, j;
893d24cc427Sdrh   static const unsigned char iCode[] = {
894d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
895d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
896d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
897d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
898d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
899d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
900d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
901d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
902d24cc427Sdrh   };
903d24cc427Sdrh   assert( argc==1 );
9044c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
905bdf67e0eSdrh   if( zIn==0 ) zIn = (u8*)"";
906d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
907d24cc427Sdrh   if( zIn[i] ){
908bdf67e0eSdrh     u8 prevcode = iCode[zIn[i]&0x7f];
909d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
910d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
911d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
912d24cc427Sdrh       if( code>0 ){
913bdf67e0eSdrh         if( code!=prevcode ){
914bdf67e0eSdrh           prevcode = code;
915d24cc427Sdrh           zResult[j++] = code + '0';
916d24cc427Sdrh         }
917bdf67e0eSdrh       }else{
918bdf67e0eSdrh         prevcode = 0;
919bdf67e0eSdrh       }
920d24cc427Sdrh     }
921d24cc427Sdrh     while( j<4 ){
922d24cc427Sdrh       zResult[j++] = '0';
923d24cc427Sdrh     }
924d24cc427Sdrh     zResult[j] = 0;
925d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
926d24cc427Sdrh   }else{
927d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
928d24cc427Sdrh   }
929d24cc427Sdrh }
930d24cc427Sdrh #endif
931d24cc427Sdrh 
932fdb83b2fSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
933fdb83b2fSdrh /*
934fdb83b2fSdrh ** A function that loads a shared-library extension then returns NULL.
935fdb83b2fSdrh */
936fdb83b2fSdrh static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
93765fd59f7Sdanielk1977   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
9387a521cfbSdrh   const char *zProc;
939fdb83b2fSdrh   sqlite3 *db = sqlite3_user_data(context);
940fdb83b2fSdrh   char *zErrMsg = 0;
941fdb83b2fSdrh 
942fdb83b2fSdrh   if( argc==2 ){
94365fd59f7Sdanielk1977     zProc = (const char *)sqlite3_value_text(argv[1]);
9447a521cfbSdrh   }else{
9457a521cfbSdrh     zProc = 0;
946fdb83b2fSdrh   }
9477a521cfbSdrh   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
948fdb83b2fSdrh     sqlite3_result_error(context, zErrMsg, -1);
949fdb83b2fSdrh     sqlite3_free(zErrMsg);
950fdb83b2fSdrh   }
951fdb83b2fSdrh }
952fdb83b2fSdrh #endif
953fdb83b2fSdrh 
954193a6b41Sdrh #ifdef SQLITE_TEST
955193a6b41Sdrh /*
956193a6b41Sdrh ** This function generates a string of random characters.  Used for
957193a6b41Sdrh ** generating test data.
958193a6b41Sdrh */
9590ae8b831Sdanielk1977 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
960bbd82df6Sdrh   static const unsigned char zSrc[] =
961193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
962193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
963193a6b41Sdrh      "0123456789"
964193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
965193a6b41Sdrh   int iMin, iMax, n, r, i;
966bbd82df6Sdrh   unsigned char zBuf[1000];
967193a6b41Sdrh   if( argc>=1 ){
968f9b596ebSdrh     iMin = sqlite3_value_int(argv[0]);
969193a6b41Sdrh     if( iMin<0 ) iMin = 0;
970193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
971193a6b41Sdrh   }else{
972193a6b41Sdrh     iMin = 1;
973193a6b41Sdrh   }
974193a6b41Sdrh   if( argc>=2 ){
975f9b596ebSdrh     iMax = sqlite3_value_int(argv[1]);
976193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
9771dba7279Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
978193a6b41Sdrh   }else{
979193a6b41Sdrh     iMax = 50;
980193a6b41Sdrh   }
981193a6b41Sdrh   n = iMin;
982193a6b41Sdrh   if( iMax>iMin ){
9834adee20fSdanielk1977     sqlite3Randomness(sizeof(r), &r);
984bbd82df6Sdrh     r &= 0x7fffffff;
985193a6b41Sdrh     n += r%(iMax + 1 - iMin);
986193a6b41Sdrh   }
9871dba7279Sdrh   assert( n<sizeof(zBuf) );
9884adee20fSdanielk1977   sqlite3Randomness(n, zBuf);
989193a6b41Sdrh   for(i=0; i<n; i++){
990bbd82df6Sdrh     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
991193a6b41Sdrh   }
992193a6b41Sdrh   zBuf[n] = 0;
9932646da7eSdrh   sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
994d8123366Sdanielk1977 }
9950e3d7476Sdrh #endif /* SQLITE_TEST */
996d8123366Sdanielk1977 
9970e3d7476Sdrh #ifdef SQLITE_TEST
998d8123366Sdanielk1977 /*
999d8123366Sdanielk1977 ** The following two SQL functions are used to test returning a text
1000d8123366Sdanielk1977 ** result with a destructor. Function 'test_destructor' takes one argument
1001d8123366Sdanielk1977 ** and returns the same argument interpreted as TEXT. A destructor is
1002d8123366Sdanielk1977 ** passed with the sqlite3_result_text() call.
1003d8123366Sdanielk1977 **
1004d8123366Sdanielk1977 ** SQL function 'test_destructor_count' returns the number of outstanding
1005d8123366Sdanielk1977 ** allocations made by 'test_destructor';
1006d8123366Sdanielk1977 **
1007d8123366Sdanielk1977 ** WARNING: Not threadsafe.
1008d8123366Sdanielk1977 */
1009d8123366Sdanielk1977 static int test_destructor_count_var = 0;
1010d8123366Sdanielk1977 static void destructor(void *p){
1011d8123366Sdanielk1977   char *zVal = (char *)p;
1012d8123366Sdanielk1977   assert(zVal);
1013d8123366Sdanielk1977   zVal--;
1014d8123366Sdanielk1977   sqliteFree(zVal);
1015d8123366Sdanielk1977   test_destructor_count_var--;
1016d8123366Sdanielk1977 }
1017d8123366Sdanielk1977 static void test_destructor(
1018d8123366Sdanielk1977   sqlite3_context *pCtx,
1019d8123366Sdanielk1977   int nArg,
1020d8123366Sdanielk1977   sqlite3_value **argv
1021d8123366Sdanielk1977 ){
1022d8123366Sdanielk1977   char *zVal;
1023f4618891Sdanielk1977   int len;
10249bb575fdSdrh   sqlite3 *db = sqlite3_user_data(pCtx);
1025f4618891Sdanielk1977 
1026d8123366Sdanielk1977   test_destructor_count_var++;
1027d8123366Sdanielk1977   assert( nArg==1 );
1028d8123366Sdanielk1977   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
102914db2665Sdanielk1977   len = sqlite3ValueBytes(argv[0], ENC(db));
1030f4618891Sdanielk1977   zVal = sqliteMalloc(len+3);
1031f4618891Sdanielk1977   zVal[len] = 0;
1032f4618891Sdanielk1977   zVal[len-1] = 0;
1033d8123366Sdanielk1977   assert( zVal );
1034d8123366Sdanielk1977   zVal++;
103514db2665Sdanielk1977   memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
103614db2665Sdanielk1977   if( ENC(db)==SQLITE_UTF8 ){
1037d8123366Sdanielk1977     sqlite3_result_text(pCtx, zVal, -1, destructor);
10386c62608fSdrh #ifndef SQLITE_OMIT_UTF16
103914db2665Sdanielk1977   }else if( ENC(db)==SQLITE_UTF16LE ){
1040f4618891Sdanielk1977     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
1041f4618891Sdanielk1977   }else{
1042f4618891Sdanielk1977     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
10436c62608fSdrh #endif /* SQLITE_OMIT_UTF16 */
1044f4618891Sdanielk1977   }
1045d8123366Sdanielk1977 }
1046d8123366Sdanielk1977 static void test_destructor_count(
1047d8123366Sdanielk1977   sqlite3_context *pCtx,
1048d8123366Sdanielk1977   int nArg,
1049d8123366Sdanielk1977   sqlite3_value **argv
1050d8123366Sdanielk1977 ){
1051d8123366Sdanielk1977   sqlite3_result_int(pCtx, test_destructor_count_var);
1052193a6b41Sdrh }
10530e3d7476Sdrh #endif /* SQLITE_TEST */
10543f6b0874Sdanielk1977 
10550e3d7476Sdrh #ifdef SQLITE_TEST
10560e3d7476Sdrh /*
10570e3d7476Sdrh ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
10580e3d7476Sdrh ** interface.
10590e3d7476Sdrh **
10600e3d7476Sdrh ** The test_auxdata() SQL function attempts to register each of its arguments
10610e3d7476Sdrh ** as auxiliary data.  If there are no prior registrations of aux data for
10620e3d7476Sdrh ** that argument (meaning the argument is not a constant or this is its first
10630e3d7476Sdrh ** call) then the result for that argument is 0.  If there is a prior
10640e3d7476Sdrh ** registration, the result for that argument is 1.  The overall result
10650e3d7476Sdrh ** is the individual argument results separated by spaces.
10660e3d7476Sdrh */
10673f6b0874Sdanielk1977 static void free_test_auxdata(void *p) {sqliteFree(p);}
10683f6b0874Sdanielk1977 static void test_auxdata(
10693f6b0874Sdanielk1977   sqlite3_context *pCtx,
10703f6b0874Sdanielk1977   int nArg,
10713f6b0874Sdanielk1977   sqlite3_value **argv
10723f6b0874Sdanielk1977 ){
10733f6b0874Sdanielk1977   int i;
10743f6b0874Sdanielk1977   char *zRet = sqliteMalloc(nArg*2);
10753f6b0874Sdanielk1977   if( !zRet ) return;
10763f6b0874Sdanielk1977   for(i=0; i<nArg; i++){
10772646da7eSdrh     char const *z = (char*)sqlite3_value_text(argv[i]);
10783f6b0874Sdanielk1977     if( z ){
10793f6b0874Sdanielk1977       char *zAux = sqlite3_get_auxdata(pCtx, i);
10803f6b0874Sdanielk1977       if( zAux ){
10813f6b0874Sdanielk1977         zRet[i*2] = '1';
10823f6b0874Sdanielk1977         if( strcmp(zAux, z) ){
10833f6b0874Sdanielk1977           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
10843f6b0874Sdanielk1977           return;
10853f6b0874Sdanielk1977         }
10863f6b0874Sdanielk1977       }else{
10873f6b0874Sdanielk1977         zRet[i*2] = '0';
10883f6b0874Sdanielk1977         zAux = sqliteStrDup(z);
10893f6b0874Sdanielk1977         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
10903f6b0874Sdanielk1977       }
10913f6b0874Sdanielk1977       zRet[i*2+1] = ' ';
10923f6b0874Sdanielk1977     }
10933f6b0874Sdanielk1977   }
10943f6b0874Sdanielk1977   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
10953f6b0874Sdanielk1977 }
10960e3d7476Sdrh #endif /* SQLITE_TEST */
1097193a6b41Sdrh 
109801427a62Sdanielk1977 #ifdef SQLITE_TEST
109901427a62Sdanielk1977 /*
110001427a62Sdanielk1977 ** A function to test error reporting from user functions. This function
110101427a62Sdanielk1977 ** returns a copy of it's first argument as an error.
110201427a62Sdanielk1977 */
110301427a62Sdanielk1977 static void test_error(
110401427a62Sdanielk1977   sqlite3_context *pCtx,
110501427a62Sdanielk1977   int nArg,
110601427a62Sdanielk1977   sqlite3_value **argv
110701427a62Sdanielk1977 ){
11082646da7eSdrh   sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
110901427a62Sdanielk1977 }
111001427a62Sdanielk1977 #endif /* SQLITE_TEST */
111101427a62Sdanielk1977 
11120ac65892Sdrh /*
1113d3a149efSdrh ** An instance of the following structure holds the context of a
1114dd5baa95Sdrh ** sum() or avg() aggregate computation.
1115dd5baa95Sdrh */
1116dd5baa95Sdrh typedef struct SumCtx SumCtx;
1117dd5baa95Sdrh struct SumCtx {
11188c08e861Sdrh   double rSum;      /* Floating point sum */
11198c08e861Sdrh   i64 iSum;         /* Integer sum */
1120cf85a51cSdrh   i64 cnt;          /* Number of elements summed */
11218c08e861Sdrh   u8 overflow;      /* True if integer overflow seen */
11228c08e861Sdrh   u8 approx;        /* True if non-integer value was input to the sum */
1123dd5baa95Sdrh };
1124dd5baa95Sdrh 
1125dd5baa95Sdrh /*
1126a97fdd3bSdrh ** Routines used to compute the sum, average, and total.
1127a97fdd3bSdrh **
1128a97fdd3bSdrh ** The SUM() function follows the (broken) SQL standard which means
1129a97fdd3bSdrh ** that it returns NULL if it sums over no inputs.  TOTAL returns
1130a97fdd3bSdrh ** 0.0 in that case.  In addition, TOTAL always returns a float where
1131a97fdd3bSdrh ** SUM might return an integer if it never encounters a floating point
1132c806d857Sdrh ** value.  TOTAL never fails, but SUM might through an exception if
1133c806d857Sdrh ** it overflows an integer.
1134dd5baa95Sdrh */
11350ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1136dd5baa95Sdrh   SumCtx *p;
11373d1d95e6Sdrh   int type;
11383f219f46Sdrh   assert( argc==1 );
11394f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
114029d72108Sdrh   type = sqlite3_value_numeric_type(argv[0]);
11413d1d95e6Sdrh   if( p && type!=SQLITE_NULL ){
1142739105c7Sdrh     p->cnt++;
114329d72108Sdrh     if( type==SQLITE_INTEGER ){
11448c08e861Sdrh       i64 v = sqlite3_value_int64(argv[0]);
11458c08e861Sdrh       p->rSum += v;
11468c08e861Sdrh       if( (p->approx|p->overflow)==0 ){
11478c08e861Sdrh         i64 iNewSum = p->iSum + v;
11488c08e861Sdrh         int s1 = p->iSum >> (sizeof(i64)*8-1);
11498c08e861Sdrh         int s2 = v       >> (sizeof(i64)*8-1);
11508c08e861Sdrh         int s3 = iNewSum >> (sizeof(i64)*8-1);
11518c08e861Sdrh         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
11528c08e861Sdrh         p->iSum = iNewSum;
115329d72108Sdrh       }
115429d72108Sdrh     }else{
11558c08e861Sdrh       p->rSum += sqlite3_value_double(argv[0]);
115629d72108Sdrh       p->approx = 1;
11573f219f46Sdrh     }
1158739105c7Sdrh   }
1159dd5baa95Sdrh }
11600ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
1161dd5baa95Sdrh   SumCtx *p;
1162abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1163c2bd913aSdrh   if( p && p->cnt>0 ){
11648c08e861Sdrh     if( p->overflow ){
11658c08e861Sdrh       sqlite3_result_error(context,"integer overflow",-1);
11668c08e861Sdrh     }else if( p->approx ){
11678c08e861Sdrh       sqlite3_result_double(context, p->rSum);
1168c2bd913aSdrh     }else{
11698c08e861Sdrh       sqlite3_result_int64(context, p->iSum);
11703d1d95e6Sdrh     }
1171dd5baa95Sdrh   }
1172c2bd913aSdrh }
11730ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
1174dd5baa95Sdrh   SumCtx *p;
1175abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1176739105c7Sdrh   if( p && p->cnt>0 ){
11778c08e861Sdrh     sqlite3_result_double(context, p->rSum/(double)p->cnt);
1178dd5baa95Sdrh   }
1179dd5baa95Sdrh }
1180a97fdd3bSdrh static void totalFinalize(sqlite3_context *context){
1181a97fdd3bSdrh   SumCtx *p;
1182a97fdd3bSdrh   p = sqlite3_aggregate_context(context, 0);
11838c08e861Sdrh   sqlite3_result_double(context, p ? p->rSum : 0.0);
1184a97fdd3bSdrh }
1185dd5baa95Sdrh 
1186dd5baa95Sdrh /*
11870bce8354Sdrh ** The following structure keeps track of state information for the
11880bce8354Sdrh ** count() aggregate function.
11890bce8354Sdrh */
11900bce8354Sdrh typedef struct CountCtx CountCtx;
11910bce8354Sdrh struct CountCtx {
1192fc6ad39cSdrh   i64 n;
11930bce8354Sdrh };
1194dd5baa95Sdrh 
11950bce8354Sdrh /*
11960bce8354Sdrh ** Routines to implement the count() aggregate function.
11970bce8354Sdrh */
11980ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
11990bce8354Sdrh   CountCtx *p;
12004f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
12019c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
12020bce8354Sdrh     p->n++;
12030bce8354Sdrh   }
12040bce8354Sdrh }
12050ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
12060bce8354Sdrh   CountCtx *p;
1207abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1208fc6ad39cSdrh   sqlite3_result_int64(context, p ? p->n : 0);
12090bce8354Sdrh }
12100bce8354Sdrh 
12110bce8354Sdrh /*
12120bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
12130bce8354Sdrh */
12140ae8b831Sdanielk1977 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
121588208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
12169eb516c0Sdrh   Mem *pBest;
12179eb516c0Sdrh 
12189eb516c0Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
12199eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
12203aeab9e4Sdanielk1977   if( !pBest ) return;
1221268380caSdrh 
122288208050Sdanielk1977   if( pBest->flags ){
12239eb516c0Sdrh     int max;
12249eb516c0Sdrh     int cmp;
1225dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
12267e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
12277e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
12287e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
12297e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
12307e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
12317e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
12327e18c259Sdanielk1977     ** aggregate, or 0 for min().
12337e18c259Sdanielk1977     */
1234309b3386Sdrh     max = sqlite3_user_data(context)!=0;
1235dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
123688208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
12377e18c259Sdanielk1977       sqlite3VdbeMemCopy(pBest, pArg);
123888208050Sdanielk1977     }
12390bce8354Sdrh   }else{
12407e18c259Sdanielk1977     sqlite3VdbeMemCopy(pBest, pArg);
12410bce8354Sdrh   }
12420bce8354Sdrh }
12430ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
124488208050Sdanielk1977   sqlite3_value *pRes;
1245abfcea25Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
1246abfcea25Sdrh   if( pRes ){
124788208050Sdanielk1977     if( pRes->flags ){
1248f4479501Sdrh       sqlite3_result_value(context, pRes);
12490bce8354Sdrh     }
1250b20e56b4Sdanielk1977     sqlite3VdbeMemRelease(pRes);
12510bce8354Sdrh   }
1252abfcea25Sdrh }
1253dd5baa95Sdrh 
12544e5ffc5fSdrh 
1255d3a149efSdrh /*
1256a2ed5601Sdrh ** This function registered all of the above C functions as SQL
1257a2ed5601Sdrh ** functions.  This should be the only routine in this file with
1258a2ed5601Sdrh ** external linkage.
1259dc04c583Sdrh */
12609bb575fdSdrh void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
12615719628aSdrh   static const struct {
12620bce8354Sdrh      char *zName;
1263268380caSdrh      signed char nArg;
1264309b3386Sdrh      u8 argType;           /* ff: db   1: 0, 2: 1, 3: 2,...  N:  N-1. */
1265d02eb1fdSdanielk1977      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
1266dc1bdc4fSdanielk1977      u8 needCollSeq;
12670ae8b831Sdanielk1977      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
12680bce8354Sdrh   } aFuncs[] = {
1269d8123366Sdanielk1977     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
1270d8123366Sdanielk1977     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
1271309b3386Sdrh     { "max",               -1, 1, SQLITE_UTF8,    1, minmaxFunc },
1272309b3386Sdrh     { "max",                0, 1, SQLITE_UTF8,    1, 0          },
1273d8123366Sdanielk1977     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
1274d8123366Sdanielk1977     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
1275d8123366Sdanielk1977     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
12766c62608fSdrh #ifndef SQLITE_OMIT_UTF16
1277ee85813cSdrh     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3Utf16Substr },
12786c62608fSdrh #endif
1279d8123366Sdanielk1977     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
1280d8123366Sdanielk1977     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
1281d8123366Sdanielk1977     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
1282d8123366Sdanielk1977     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
1283d8123366Sdanielk1977     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
1284d8123366Sdanielk1977     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
1285d8123366Sdanielk1977     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
1286d8123366Sdanielk1977     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
1287137c728fSdrh     { "hex",                1, 0, SQLITE_UTF8,    0, hexFunc    },
1288d8123366Sdanielk1977     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
1289d8123366Sdanielk1977     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
1290137c728fSdrh     { "randomblob",         1, 0, SQLITE_UTF8,    0, randomBlob },
129194a98365Sdrh     { "nullif",             2, 0, SQLITE_UTF8,    1, nullifFunc },
1292d8123366Sdanielk1977     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
1293d8123366Sdanielk1977     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
1294309b3386Sdrh     { "last_insert_rowid",  0, 0xff, SQLITE_UTF8, 0, last_insert_rowid },
1295309b3386Sdrh     { "changes",            0, 0xff, SQLITE_UTF8, 0, changes           },
1296309b3386Sdrh     { "total_changes",      0, 0xff, SQLITE_UTF8, 0, total_changes     },
129726b6d90dSdrh     { "replace",            3, 0, SQLITE_UTF8,    0, replaceFunc       },
1298309b3386Sdrh     { "ltrim",              1, 1, SQLITE_UTF8,    0, trimFunc          },
1299309b3386Sdrh     { "ltrim",              2, 1, SQLITE_UTF8,    0, trimFunc          },
1300309b3386Sdrh     { "rtrim",              1, 2, SQLITE_UTF8,    0, trimFunc          },
1301309b3386Sdrh     { "rtrim",              2, 2, SQLITE_UTF8,    0, trimFunc          },
1302309b3386Sdrh     { "trim",               1, 3, SQLITE_UTF8,    0, trimFunc          },
1303309b3386Sdrh     { "trim",               2, 3, SQLITE_UTF8,    0, trimFunc          },
13048cff382eSdrh     { "zeroblob",           1, 0, SQLITE_UTF8,    0, zeroblobFunc      },
1305d24cc427Sdrh #ifdef SQLITE_SOUNDEX
1306d8123366Sdanielk1977     { "soundex",            1, 0, SQLITE_UTF8,    0, soundexFunc},
1307d24cc427Sdrh #endif
1308fdb83b2fSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
1309309b3386Sdrh     { "load_extension",     1, 0xff, SQLITE_UTF8, 0, loadExt },
1310309b3386Sdrh     { "load_extension",     2, 0xff, SQLITE_UTF8, 0, loadExt },
1311fdb83b2fSdrh #endif
1312193a6b41Sdrh #ifdef SQLITE_TEST
1313d8123366Sdanielk1977     { "randstr",               2, 0,    SQLITE_UTF8, 0, randStr    },
1314309b3386Sdrh     { "test_destructor",       1, 0xff, SQLITE_UTF8, 0, test_destructor},
1315d8123366Sdanielk1977     { "test_destructor_count", 0, 0,    SQLITE_UTF8, 0, test_destructor_count},
13163f6b0874Sdanielk1977     { "test_auxdata",         -1, 0,    SQLITE_UTF8, 0, test_auxdata},
131701427a62Sdanielk1977     { "test_error",            1, 0,    SQLITE_UTF8, 0, test_error},
1318193a6b41Sdrh #endif
13190bce8354Sdrh   };
13205719628aSdrh   static const struct {
13210bce8354Sdrh     char *zName;
1322268380caSdrh     signed char nArg;
1323268380caSdrh     u8 argType;
1324dc1bdc4fSdanielk1977     u8 needCollSeq;
13250ae8b831Sdanielk1977     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
13260ae8b831Sdanielk1977     void (*xFinalize)(sqlite3_context*);
13270bce8354Sdrh   } aAggs[] = {
1328dc1bdc4fSdanielk1977     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
1329309b3386Sdrh     { "max",    1, 1, 1, minmaxStep,   minMaxFinalize },
1330dc1bdc4fSdanielk1977     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
1331a97fdd3bSdrh     { "total",  1, 0, 0, sumStep,      totalFinalize    },
1332dc1bdc4fSdanielk1977     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
1333dc1bdc4fSdanielk1977     { "count",  0, 0, 0, countStep,    countFinalize  },
1334dc1bdc4fSdanielk1977     { "count",  1, 0, 0, countStep,    countFinalize  },
13350bce8354Sdrh   };
13360bce8354Sdrh   int i;
13370bce8354Sdrh 
13380bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1339309b3386Sdrh     void *pArg;
1340309b3386Sdrh     u8 argType = aFuncs[i].argType;
1341309b3386Sdrh     if( argType==0xff ){
1342309b3386Sdrh       pArg = db;
1343309b3386Sdrh     }else{
1344309b3386Sdrh       pArg = (void*)(int)argType;
1345c572ef7fSdanielk1977     }
1346771151b6Sdanielk1977     sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
1347f9d64d2cSdanielk1977         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1348dc1bdc4fSdanielk1977     if( aFuncs[i].needCollSeq ){
1349dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1350dc1bdc4fSdanielk1977           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1351dc1bdc4fSdanielk1977       if( pFunc && aFuncs[i].needCollSeq ){
1352dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1353dc1bdc4fSdanielk1977       }
1354dc1bdc4fSdanielk1977     }
13550bce8354Sdrh   }
13561f01ec1bSdrh #ifndef SQLITE_OMIT_ALTERTABLE
13571f01ec1bSdrh   sqlite3AlterFunctions(db);
13581f01ec1bSdrh #endif
1359198bf391Sdrh #ifndef SQLITE_OMIT_PARSER
1360f744bb56Sdanielk1977   sqlite3AttachFunctions(db);
1361198bf391Sdrh #endif
13620bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1363309b3386Sdrh     void *pArg = (void*)(int)aAggs[i].argType;
1364771151b6Sdanielk1977     sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1365f9d64d2cSdanielk1977         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1366dc1bdc4fSdanielk1977     if( aAggs[i].needCollSeq ){
1367dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1368d8123366Sdanielk1977           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1369dc1bdc4fSdanielk1977       if( pFunc && aAggs[i].needCollSeq ){
1370dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1371dc1bdc4fSdanielk1977       }
1372dc1bdc4fSdanielk1977     }
1373268380caSdrh   }
13744adee20fSdanielk1977   sqlite3RegisterDateTimeFunctions(db);
1375b7481e70Sdrh   sqlite3_overload_function(db, "MATCH", 2);
1376fd9e1f31Sdanielk1977 #ifdef SQLITE_SSE
13773752785fSdrh   (void)sqlite3SseFunctions(db);
1378fd9e1f31Sdanielk1977 #endif
137955ef4d97Sdrh #ifdef SQLITE_CASE_SENSITIVE_LIKE
138055ef4d97Sdrh   sqlite3RegisterLikeFunctions(db, 1);
138155ef4d97Sdrh #else
138255ef4d97Sdrh   sqlite3RegisterLikeFunctions(db, 0);
138355ef4d97Sdrh #endif
138455ef4d97Sdrh }
138555ef4d97Sdrh 
138655ef4d97Sdrh /*
138755ef4d97Sdrh ** Set the LIKEOPT flag on the 2-argument function with the given name.
138855ef4d97Sdrh */
1389d64fe2f3Sdrh static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
139055ef4d97Sdrh   FuncDef *pDef;
139155ef4d97Sdrh   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
139255ef4d97Sdrh   if( pDef ){
1393d64fe2f3Sdrh     pDef->flags = flagVal;
139455ef4d97Sdrh   }
139555ef4d97Sdrh }
139655ef4d97Sdrh 
139755ef4d97Sdrh /*
139855ef4d97Sdrh ** Register the built-in LIKE and GLOB functions.  The caseSensitive
139955ef4d97Sdrh ** parameter determines whether or not the LIKE operator is case
140055ef4d97Sdrh ** sensitive.  GLOB is always case sensitive.
140155ef4d97Sdrh */
140255ef4d97Sdrh void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
140355ef4d97Sdrh   struct compareInfo *pInfo;
140455ef4d97Sdrh   if( caseSensitive ){
140555ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoAlt;
140655ef4d97Sdrh   }else{
140755ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoNorm;
140855ef4d97Sdrh   }
1409771151b6Sdanielk1977   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
1410771151b6Sdanielk1977   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
1411771151b6Sdanielk1977   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
141255ef4d97Sdrh       (struct compareInfo*)&globInfo, likeFunc, 0,0);
1413d64fe2f3Sdrh   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1414d64fe2f3Sdrh   setLikeOptFlag(db, "like",
1415d64fe2f3Sdrh       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
141655ef4d97Sdrh }
141755ef4d97Sdrh 
141855ef4d97Sdrh /*
141955ef4d97Sdrh ** pExpr points to an expression which implements a function.  If
142055ef4d97Sdrh ** it is appropriate to apply the LIKE optimization to that function
142155ef4d97Sdrh ** then set aWc[0] through aWc[2] to the wildcard characters and
142255ef4d97Sdrh ** return TRUE.  If the function is not a LIKE-style function then
142355ef4d97Sdrh ** return FALSE.
142455ef4d97Sdrh */
1425d64fe2f3Sdrh int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
142655ef4d97Sdrh   FuncDef *pDef;
142755ef4d97Sdrh   if( pExpr->op!=TK_FUNCTION ){
142855ef4d97Sdrh     return 0;
142955ef4d97Sdrh   }
143055ef4d97Sdrh   if( pExpr->pList->nExpr!=2 ){
143155ef4d97Sdrh     return 0;
143255ef4d97Sdrh   }
14332646da7eSdrh   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
143455ef4d97Sdrh                              SQLITE_UTF8, 0);
1435d64fe2f3Sdrh   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
143655ef4d97Sdrh     return 0;
143755ef4d97Sdrh   }
143855ef4d97Sdrh 
143955ef4d97Sdrh   /* The memcpy() statement assumes that the wildcard characters are
144055ef4d97Sdrh   ** the first three statements in the compareInfo structure.  The
144155ef4d97Sdrh   ** asserts() that follow verify that assumption
144255ef4d97Sdrh   */
144355ef4d97Sdrh   memcpy(aWc, pDef->pUserData, 3);
144455ef4d97Sdrh   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
144555ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
144655ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1447d64fe2f3Sdrh   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
144855ef4d97Sdrh   return 1;
1449dc04c583Sdrh }
1450