xref: /sqlite-3.40.0/src/func.c (revision 4e5ffc5f)
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*4e5ffc5fSdrh ** $Id: func.c,v 1.81 2004/08/31 00:52:37 drh Exp $
20dc04c583Sdrh */
21dc04c583Sdrh #include <ctype.h>
22d3a149efSdrh #include <math.h>
23d3a149efSdrh #include <stdlib.h>
240bce8354Sdrh #include <assert.h>
250bce8354Sdrh #include "sqliteInt.h"
2688208050Sdanielk1977 #include "vdbeInt.h"
27771d8c3bSdrh #include "os.h"
280bce8354Sdrh 
29dc1bdc4fSdanielk1977 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
30dc1bdc4fSdanielk1977   return context->pColl;
31dc1bdc4fSdanielk1977 }
32dc1bdc4fSdanielk1977 
330bce8354Sdrh /*
340bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
350bce8354Sdrh */
36f9b596ebSdrh static void minmaxFunc(
37f9b596ebSdrh   sqlite3_context *context,
38f9b596ebSdrh   int argc,
39f9b596ebSdrh   sqlite3_value **argv
40f9b596ebSdrh ){
410bce8354Sdrh   int i;
42268380caSdrh   int mask;    /* 0 for min() or 0xffffffff for max() */
43f9b596ebSdrh   int iBest;
44dc1bdc4fSdanielk1977   CollSeq *pColl;
450bce8354Sdrh 
4689425d5eSdrh   if( argc==0 ) return;
4724b03fd0Sdanielk1977   mask = (int)sqlite3_user_data(context);
48dc1bdc4fSdanielk1977   pColl = sqlite3GetFuncCollSeq(context);
49dc1bdc4fSdanielk1977   assert( pColl );
50c572ef7fSdanielk1977   assert( mask==-1 || mask==0 );
51f9b596ebSdrh   iBest = 0;
529c054830Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
53f9b596ebSdrh   for(i=1; i<argc; i++){
549c054830Sdrh     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
55dc1bdc4fSdanielk1977     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
56f9b596ebSdrh       iBest = i;
570bce8354Sdrh     }
580bce8354Sdrh   }
59f4479501Sdrh   sqlite3_result_value(context, argv[iBest]);
600bce8354Sdrh }
610bce8354Sdrh 
62268380caSdrh /*
63268380caSdrh ** Return the type of the argument.
64268380caSdrh */
65f9b596ebSdrh static void typeofFunc(
66f9b596ebSdrh   sqlite3_context *context,
67f9b596ebSdrh   int argc,
68f9b596ebSdrh   sqlite3_value **argv
69f9b596ebSdrh ){
7035bb9d02Sdanielk1977   const char *z = 0;
7135bb9d02Sdanielk1977   switch( sqlite3_value_type(argv[0]) ){
729c054830Sdrh     case SQLITE_NULL:    z = "null";    break;
739c054830Sdrh     case SQLITE_INTEGER: z = "integer"; break;
749c054830Sdrh     case SQLITE_TEXT:    z = "text";    break;
759c054830Sdrh     case SQLITE_FLOAT:   z = "real";    break;
769c054830Sdrh     case SQLITE_BLOB:    z = "blob";    break;
7735bb9d02Sdanielk1977   }
78d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
790bce8354Sdrh }
800bce8354Sdrh 
810bce8354Sdrh /*
820bce8354Sdrh ** Implementation of the length() function
830bce8354Sdrh */
84f9b596ebSdrh static void lengthFunc(
85f9b596ebSdrh   sqlite3_context *context,
86f9b596ebSdrh   int argc,
87f9b596ebSdrh   sqlite3_value **argv
88f9b596ebSdrh ){
890bce8354Sdrh   int len;
900bce8354Sdrh 
910bce8354Sdrh   assert( argc==1 );
92f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
939c054830Sdrh     case SQLITE_BLOB:
949c054830Sdrh     case SQLITE_INTEGER:
959c054830Sdrh     case SQLITE_FLOAT: {
96f4479501Sdrh       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
97f9b596ebSdrh       break;
98f9b596ebSdrh     }
999c054830Sdrh     case SQLITE_TEXT: {
1004f26d6c4Sdrh       const char *z = sqlite3_value_text(argv[0]);
1010bce8354Sdrh       for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
102f4479501Sdrh       sqlite3_result_int(context, len);
103f9b596ebSdrh       break;
104f9b596ebSdrh     }
105f9b596ebSdrh     default: {
106f9b596ebSdrh       sqlite3_result_null(context);
107f9b596ebSdrh       break;
108f9b596ebSdrh     }
109f9b596ebSdrh   }
1100bce8354Sdrh }
1110bce8354Sdrh 
1120bce8354Sdrh /*
1130bce8354Sdrh ** Implementation of the abs() function
1140bce8354Sdrh */
1150ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1160bce8354Sdrh   assert( argc==1 );
117f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1189c054830Sdrh     case SQLITE_INTEGER: {
119f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
120f93bbbeaSdanielk1977       if( iVal<0 ) iVal = iVal * -1;
121f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
122f9b596ebSdrh       break;
123f9b596ebSdrh     }
1249c054830Sdrh     case SQLITE_NULL: {
125f9b596ebSdrh       sqlite3_result_null(context);
126f9b596ebSdrh       break;
127f9b596ebSdrh     }
128f9b596ebSdrh     default: {
129f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
130f93bbbeaSdanielk1977       if( rVal<0 ) rVal = rVal * -1.0;
131f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
132f9b596ebSdrh       break;
133f9b596ebSdrh     }
134f9b596ebSdrh   }
1350bce8354Sdrh }
1360bce8354Sdrh 
1370bce8354Sdrh /*
1380bce8354Sdrh ** Implementation of the substr() function
1390bce8354Sdrh */
140f9b596ebSdrh static void substrFunc(
141f9b596ebSdrh   sqlite3_context *context,
142f9b596ebSdrh   int argc,
143f9b596ebSdrh   sqlite3_value **argv
144f9b596ebSdrh ){
1450bce8354Sdrh   const char *z;
1460bce8354Sdrh   const char *z2;
1470bce8354Sdrh   int i;
1480bce8354Sdrh   int p1, p2, len;
149f9b596ebSdrh 
1500bce8354Sdrh   assert( argc==3 );
1514f26d6c4Sdrh   z = sqlite3_value_text(argv[0]);
1520bce8354Sdrh   if( z==0 ) return;
15351ad0ecdSdanielk1977   p1 = sqlite3_value_int(argv[1]);
15451ad0ecdSdanielk1977   p2 = sqlite3_value_int(argv[2]);
15547c8a679Sdrh   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
1560bce8354Sdrh   if( p1<0 ){
15789425d5eSdrh     p1 += len;
158653bc759Sdrh     if( p1<0 ){
159653bc759Sdrh       p2 += p1;
160653bc759Sdrh       p1 = 0;
161653bc759Sdrh     }
1620bce8354Sdrh   }else if( p1>0 ){
1630bce8354Sdrh     p1--;
1640bce8354Sdrh   }
1650bce8354Sdrh   if( p1+p2>len ){
1660bce8354Sdrh     p2 = len-p1;
1670bce8354Sdrh   }
16877396304Sdrh   for(i=0; i<p1 && z[i]; i++){
16947c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p1++;
1700bce8354Sdrh   }
17147c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
17277396304Sdrh   for(; i<p1+p2 && z[i]; i++){
17347c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p2++;
1740bce8354Sdrh   }
17547c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
176653bc759Sdrh   if( p2<0 ) p2 = 0;
177d8123366Sdanielk1977   sqlite3_result_text(context, &z[p1], p2, SQLITE_TRANSIENT);
1780bce8354Sdrh }
1790bce8354Sdrh 
1800bce8354Sdrh /*
1810bce8354Sdrh ** Implementation of the round() function
1820bce8354Sdrh */
1830ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
18451ad0ecdSdanielk1977   int n = 0;
1850bce8354Sdrh   double r;
1860bce8354Sdrh   char zBuf[100];
1870bce8354Sdrh   assert( argc==1 || argc==2 );
18851ad0ecdSdanielk1977   if( argc==2 ){
1899c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
19051ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
1910bce8354Sdrh     if( n>30 ) n = 30;
1920bce8354Sdrh     if( n<0 ) n = 0;
19351ad0ecdSdanielk1977   }
1949c054830Sdrh   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
1954f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
1960bce8354Sdrh   sprintf(zBuf,"%.*f",n,r);
197d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1980bce8354Sdrh }
199dc04c583Sdrh 
200dc04c583Sdrh /*
201dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
202dc04c583Sdrh */
2030ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2048cd9db00Sdrh   unsigned char *z;
205dc04c583Sdrh   int i;
2069c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
207c572ef7fSdanielk1977   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
208dc04c583Sdrh   if( z==0 ) return;
2094f26d6c4Sdrh   strcpy(z, sqlite3_value_text(argv[0]));
210dc04c583Sdrh   for(i=0; z[i]; i++){
2114c755c0fSdrh     z[i] = toupper(z[i]);
212dc04c583Sdrh   }
213d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2147e18c259Sdanielk1977   sqliteFree(z);
215dc04c583Sdrh }
2160ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
2178cd9db00Sdrh   unsigned char *z;
218dc04c583Sdrh   int i;
2199c054830Sdrh   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
220c572ef7fSdanielk1977   z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
221dc04c583Sdrh   if( z==0 ) return;
2224f26d6c4Sdrh   strcpy(z, sqlite3_value_text(argv[0]));
223dc04c583Sdrh   for(i=0; z[i]; i++){
2244c755c0fSdrh     z[i] = tolower(z[i]);
225dc04c583Sdrh   }
226d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2277e18c259Sdanielk1977   sqliteFree(z);
228dc04c583Sdrh }
229dc04c583Sdrh 
230dc04c583Sdrh /*
231fbc99082Sdrh ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
232b6c9e6e6Sjplyon ** All three do the same thing.  They return the first non-NULL
233b6c9e6e6Sjplyon ** argument.
2343212e182Sdrh */
235f9b596ebSdrh static void ifnullFunc(
236f9b596ebSdrh   sqlite3_context *context,
237f9b596ebSdrh   int argc,
238f9b596ebSdrh   sqlite3_value **argv
239f9b596ebSdrh ){
240fbc99082Sdrh   int i;
241fbc99082Sdrh   for(i=0; i<argc; i++){
2429c054830Sdrh     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
243f4479501Sdrh       sqlite3_result_value(context, argv[i]);
244fbc99082Sdrh       break;
245fbc99082Sdrh     }
246fbc99082Sdrh   }
2473212e182Sdrh }
2483212e182Sdrh 
2493212e182Sdrh /*
250f9ffac96Sdrh ** Implementation of random().  Return a random integer.
251f9ffac96Sdrh */
252f9b596ebSdrh static void randomFunc(
253f9b596ebSdrh   sqlite3_context *context,
254f9b596ebSdrh   int argc,
255f9b596ebSdrh   sqlite3_value **argv
256f9b596ebSdrh ){
257bbd82df6Sdrh   int r;
2584adee20fSdanielk1977   sqlite3Randomness(sizeof(r), &r);
259f4479501Sdrh   sqlite3_result_int(context, r);
260f9ffac96Sdrh }
261f9ffac96Sdrh 
262f9ffac96Sdrh /*
2636ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
26424b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
2656ed41ad7Sdrh */
26651ad0ecdSdanielk1977 static void last_insert_rowid(
2670ae8b831Sdanielk1977   sqlite3_context *context,
26851ad0ecdSdanielk1977   int arg,
26951ad0ecdSdanielk1977   sqlite3_value **argv
27051ad0ecdSdanielk1977 ){
27124b03fd0Sdanielk1977   sqlite *db = sqlite3_user_data(context);
272f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
2736ed41ad7Sdrh }
2746ed41ad7Sdrh 
275f146a776Srdc /*
276b28af71aSdanielk1977 ** Implementation of the changes() SQL function.  The return value is the
277b28af71aSdanielk1977 ** same as the sqlite3_changes() API function.
278f146a776Srdc */
279b28af71aSdanielk1977 static void changes(
280f9b596ebSdrh   sqlite3_context *context,
281f9b596ebSdrh   int arg,
282f9b596ebSdrh   sqlite3_value **argv
283f9b596ebSdrh ){
28424b03fd0Sdanielk1977   sqlite *db = sqlite3_user_data(context);
285f4479501Sdrh   sqlite3_result_int(context, sqlite3_changes(db));
286b0c374ffSrdc }
287f146a776Srdc 
288f146a776Srdc /*
289b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
290b28af71aSdanielk1977 ** the same as the sqlite3_total_changes() API function.
291f146a776Srdc */
292b28af71aSdanielk1977 static void total_changes(
2930ae8b831Sdanielk1977   sqlite3_context *context,
29451ad0ecdSdanielk1977   int arg,
29551ad0ecdSdanielk1977   sqlite3_value **argv
29651ad0ecdSdanielk1977 ){
29724b03fd0Sdanielk1977   sqlite *db = sqlite3_user_data(context);
298b28af71aSdanielk1977   sqlite3_result_int(context, sqlite3_total_changes(db));
299b0c374ffSrdc }
300b0c374ffSrdc 
3016ed41ad7Sdrh /*
302*4e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
303d02eb1fdSdanielk1977 */
304*4e5ffc5fSdrh struct compareInfo {
305*4e5ffc5fSdrh   u8 matchAll;
306*4e5ffc5fSdrh   u8 matchOne;
307*4e5ffc5fSdrh   u8 matchSet;
308*4e5ffc5fSdrh   u8 noCase;
309d02eb1fdSdanielk1977 };
310*4e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
311*4e5ffc5fSdrh static const struct compareInfo likeInfo = { '%', '_',   0, 1 };
312d02eb1fdSdanielk1977 
313d02eb1fdSdanielk1977 /*
314*4e5ffc5fSdrh ** X is a pointer to the first byte of a UTF-8 character.  Increment
315*4e5ffc5fSdrh ** X so that it points to the next character.  This only works right
316*4e5ffc5fSdrh ** if X points to a well-formed UTF-8 string.
317d02eb1fdSdanielk1977 */
318*4e5ffc5fSdrh #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
319*4e5ffc5fSdrh #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
320d02eb1fdSdanielk1977 
321d02eb1fdSdanielk1977 
322d02eb1fdSdanielk1977 /*
323*4e5ffc5fSdrh ** Compare two UTF-8 strings for equality where the first string can
324*4e5ffc5fSdrh ** potentially be a "glob" expression.  Return true (1) if they
325*4e5ffc5fSdrh ** are the same and false (0) if they are different.
3260ac65892Sdrh **
327*4e5ffc5fSdrh ** Globbing rules:
3280ac65892Sdrh **
329*4e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
330d02eb1fdSdanielk1977 **
331*4e5ffc5fSdrh **      '?'       Matches exactly one character.
332*4e5ffc5fSdrh **
333*4e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
334*4e5ffc5fSdrh **                characters.
335*4e5ffc5fSdrh **
336*4e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
337*4e5ffc5fSdrh **
338*4e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
339*4e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
340*4e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
341*4e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
342*4e5ffc5fSdrh ** it the last character in the list.
343*4e5ffc5fSdrh **
344*4e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
345*4e5ffc5fSdrh **
346*4e5ffc5fSdrh ** Hints: to match '*' or '?', put them in "[]".  Like this:
347*4e5ffc5fSdrh **
348*4e5ffc5fSdrh **         abc[*]xyz        Matches "abc*xyz" only
3490ac65892Sdrh */
350*4e5ffc5fSdrh int patternCompare(
351*4e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
352*4e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
353*4e5ffc5fSdrh   const struct compareInfo *pInfo  /* Information about how to do the compare */
35451ad0ecdSdanielk1977 ){
355ad7dd425Sdanielk1977   register int c;
356*4e5ffc5fSdrh   int invert;
357*4e5ffc5fSdrh   int seen;
358*4e5ffc5fSdrh   int c2;
359*4e5ffc5fSdrh   u8 matchOne = pInfo->matchOne;
360*4e5ffc5fSdrh   u8 matchAll = pInfo->matchAll;
361*4e5ffc5fSdrh   u8 matchSet = pInfo->matchSet;
362*4e5ffc5fSdrh   u8 noCase = pInfo->noCase;
363d02eb1fdSdanielk1977 
364*4e5ffc5fSdrh   while( (c = *zPattern)!=0 ){
365*4e5ffc5fSdrh     if( c==matchAll ){
366*4e5ffc5fSdrh       while( (c=zPattern[1]) == matchAll || c == matchOne ){
367*4e5ffc5fSdrh         if( c==matchOne ){
368*4e5ffc5fSdrh           if( *zString==0 ) return 0;
369*4e5ffc5fSdrh           sqliteNextChar(zString);
370d02eb1fdSdanielk1977         }
371*4e5ffc5fSdrh         zPattern++;
372*4e5ffc5fSdrh       }
373*4e5ffc5fSdrh       if( c==0 ) return 1;
374*4e5ffc5fSdrh       if( c==matchSet ){
375*4e5ffc5fSdrh         while( *zString && patternCompare(&zPattern[1],zString,pInfo)==0 ){
376*4e5ffc5fSdrh           sqliteNextChar(zString);
377*4e5ffc5fSdrh         }
378*4e5ffc5fSdrh         return *zString!=0;
379d02eb1fdSdanielk1977       }else{
380*4e5ffc5fSdrh         while( (c2 = *zString)!=0 ){
381*4e5ffc5fSdrh           if( noCase ){
382*4e5ffc5fSdrh             c2 = sqlite3UpperToLower[c2];
383*4e5ffc5fSdrh             c = sqlite3UpperToLower[c];
384*4e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
385ad7dd425Sdanielk1977           }else{
386*4e5ffc5fSdrh             while( c2 != 0 && c2 != c ){ c2 = *++zString; }
387ad7dd425Sdanielk1977           }
388*4e5ffc5fSdrh           if( c2==0 ) return 0;
389*4e5ffc5fSdrh           if( patternCompare(&zPattern[1],zString,pInfo) ) return 1;
390*4e5ffc5fSdrh           sqliteNextChar(zString);
391*4e5ffc5fSdrh         }
392*4e5ffc5fSdrh         return 0;
393*4e5ffc5fSdrh       }
394*4e5ffc5fSdrh     }else if( c==matchOne ){
395*4e5ffc5fSdrh       if( *zString==0 ) return 0;
396*4e5ffc5fSdrh       sqliteNextChar(zString);
397*4e5ffc5fSdrh       zPattern++;
398*4e5ffc5fSdrh     }else if( c==matchSet ){
399*4e5ffc5fSdrh       int prior_c = 0;
400*4e5ffc5fSdrh       seen = 0;
401*4e5ffc5fSdrh       invert = 0;
402*4e5ffc5fSdrh       c = sqliteCharVal(zString);
403*4e5ffc5fSdrh       if( c==0 ) return 0;
404*4e5ffc5fSdrh       c2 = *++zPattern;
405*4e5ffc5fSdrh       if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
406*4e5ffc5fSdrh       if( c2==']' ){
407*4e5ffc5fSdrh         if( c==']' ) seen = 1;
408*4e5ffc5fSdrh         c2 = *++zPattern;
409*4e5ffc5fSdrh       }
410*4e5ffc5fSdrh       while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
411*4e5ffc5fSdrh         if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
412*4e5ffc5fSdrh           zPattern++;
413*4e5ffc5fSdrh           c2 = sqliteCharVal(zPattern);
414*4e5ffc5fSdrh           if( c>=prior_c && c<=c2 ) seen = 1;
415*4e5ffc5fSdrh           prior_c = 0;
416*4e5ffc5fSdrh         }else if( c==c2 ){
417*4e5ffc5fSdrh           seen = 1;
418*4e5ffc5fSdrh           prior_c = c2;
419d02eb1fdSdanielk1977         }else{
420*4e5ffc5fSdrh           prior_c = c2;
421d02eb1fdSdanielk1977         }
422*4e5ffc5fSdrh         sqliteNextChar(zPattern);
423d02eb1fdSdanielk1977       }
424*4e5ffc5fSdrh       if( c2==0 || (seen ^ invert)==0 ) return 0;
425*4e5ffc5fSdrh       sqliteNextChar(zString);
426*4e5ffc5fSdrh       zPattern++;
427d02eb1fdSdanielk1977     }else{
428*4e5ffc5fSdrh       if( noCase ){
429*4e5ffc5fSdrh         if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
430*4e5ffc5fSdrh       }else{
431*4e5ffc5fSdrh         if( c != *zString ) return 0;
432*4e5ffc5fSdrh       }
433*4e5ffc5fSdrh       zPattern++;
434*4e5ffc5fSdrh       zString++;
43551ad0ecdSdanielk1977     }
4360ac65892Sdrh   }
437*4e5ffc5fSdrh   return *zString==0;
438*4e5ffc5fSdrh }
439*4e5ffc5fSdrh 
4403f6b0874Sdanielk1977 
4413f6b0874Sdanielk1977 /*
4423f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
4433f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
4443f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
4453f6b0874Sdanielk1977 **
4463f6b0874Sdanielk1977 **       A LIKE B
4473f6b0874Sdanielk1977 **
4483f6b0874Sdanielk1977 ** is implemented as like(B,A).
4493f6b0874Sdanielk1977 **
4503f6b0874Sdanielk1977 ** If the pointer retrieved by via a call to sqlite3_user_data() is
4513f6b0874Sdanielk1977 ** not NULL, then this function uses UTF-16. Otherwise UTF-8.
4523f6b0874Sdanielk1977 */
4533f6b0874Sdanielk1977 static void likeFunc(
4543f6b0874Sdanielk1977   sqlite3_context *context,
4553f6b0874Sdanielk1977   int argc,
4563f6b0874Sdanielk1977   sqlite3_value **argv
4573f6b0874Sdanielk1977 ){
4583f6b0874Sdanielk1977   const unsigned char *zA = sqlite3_value_text(argv[0]);
4593f6b0874Sdanielk1977   const unsigned char *zB = sqlite3_value_text(argv[1]);
4603f6b0874Sdanielk1977   if( zA && zB ){
461*4e5ffc5fSdrh     sqlite3_result_int(context, patternCompare(zA, zB, &likeInfo));
4623f6b0874Sdanielk1977   }
4633f6b0874Sdanielk1977 }
4640ac65892Sdrh 
4650ac65892Sdrh /*
4660ac65892Sdrh ** Implementation of the glob() SQL function.  This function implements
4670ac65892Sdrh ** the build-in GLOB operator.  The first argument to the function is the
4680ac65892Sdrh ** string and the second argument is the pattern.  So, the SQL statements:
4690ac65892Sdrh **
4700ac65892Sdrh **       A GLOB B
4710ac65892Sdrh **
4720ac65892Sdrh ** is implemented as glob(A,B).
4730ac65892Sdrh */
4740ae8b831Sdanielk1977 static void globFunc(sqlite3_context *context, int arg, sqlite3_value **argv){
4754f26d6c4Sdrh   const unsigned char *zA = sqlite3_value_text(argv[0]);
4764f26d6c4Sdrh   const unsigned char *zB = sqlite3_value_text(argv[1]);
47751ad0ecdSdanielk1977   if( zA && zB ){
478*4e5ffc5fSdrh     sqlite3_result_int(context, patternCompare(zA, zB, &globInfo));
47951ad0ecdSdanielk1977   }
4808912d106Sdrh }
4818912d106Sdrh 
4828912d106Sdrh /*
4838912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
4848912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
4858912d106Sdrh ** arguments are equal to each other.
4868912d106Sdrh */
487f9b596ebSdrh static void nullifFunc(
488f9b596ebSdrh   sqlite3_context *context,
489f9b596ebSdrh   int argc,
490f9b596ebSdrh   sqlite3_value **argv
491f9b596ebSdrh ){
492dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
493dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
494f4479501Sdrh     sqlite3_result_value(context, argv[0]);
4958912d106Sdrh   }
4960ac65892Sdrh }
4970ac65892Sdrh 
498647cb0e1Sdrh /*
499647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
500647cb0e1Sdrh ** of the SQLite library that is running.
501647cb0e1Sdrh */
502f9b596ebSdrh static void versionFunc(
503f9b596ebSdrh   sqlite3_context *context,
504f9b596ebSdrh   int argc,
505f9b596ebSdrh   sqlite3_value **argv
506f9b596ebSdrh ){
507d8123366Sdanielk1977   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
508647cb0e1Sdrh }
509647cb0e1Sdrh 
51047394703Sdrh /*
51147394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
51247394703Sdrh ** change.  This function may disappear.  Do not write code that depends
51347394703Sdrh ** on this function.
51447394703Sdrh **
51547394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
51647394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
51747394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
51847394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
51947394703Sdrh ** single-quote escapes.
52047394703Sdrh */
5210ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
52247394703Sdrh   if( argc<1 ) return;
523f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
5249c054830Sdrh     case SQLITE_NULL: {
525d8123366Sdanielk1977       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
526f9b596ebSdrh       break;
527f9b596ebSdrh     }
5289c054830Sdrh     case SQLITE_INTEGER:
5299c054830Sdrh     case SQLITE_FLOAT: {
530f4479501Sdrh       sqlite3_result_value(context, argv[0]);
531f9b596ebSdrh       break;
532f9b596ebSdrh     }
5333f41e976Sdanielk1977     case SQLITE_BLOB: {
5343f41e976Sdanielk1977       static const char hexdigits[] = {
5353f41e976Sdanielk1977         '0', '1', '2', '3', '4', '5', '6', '7',
5363f41e976Sdanielk1977         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
5373f41e976Sdanielk1977       };
5383f41e976Sdanielk1977       char *zText = 0;
5393f41e976Sdanielk1977       int nBlob = sqlite3_value_bytes(argv[0]);
5403f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
5413f41e976Sdanielk1977 
5423f41e976Sdanielk1977       zText = (char *)sqliteMalloc((2*nBlob)+4);
5433f41e976Sdanielk1977       if( !zText ){
5443f41e976Sdanielk1977         sqlite3_result_error(context, "out of memory", -1);
5453f41e976Sdanielk1977       }else{
5463f41e976Sdanielk1977         int i;
5473f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
5483f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
5493f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
5503f41e976Sdanielk1977         }
5513f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
5523f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
5533f41e976Sdanielk1977         zText[0] = 'X';
5543f41e976Sdanielk1977         zText[1] = '\'';
555d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
5563f41e976Sdanielk1977         sqliteFree(zText);
5573f41e976Sdanielk1977       }
5583f41e976Sdanielk1977       break;
5593f41e976Sdanielk1977     }
5609c054830Sdrh     case SQLITE_TEXT: {
56147394703Sdrh       int i,j,n;
5624f26d6c4Sdrh       const char *zArg = sqlite3_value_text(argv[0]);
56347394703Sdrh       char *z;
564f9b596ebSdrh 
56551ad0ecdSdanielk1977       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
56647394703Sdrh       z = sqliteMalloc( i+n+3 );
56747394703Sdrh       if( z==0 ) return;
56847394703Sdrh       z[0] = '\'';
56951ad0ecdSdanielk1977       for(i=0, j=1; zArg[i]; i++){
57051ad0ecdSdanielk1977         z[j++] = zArg[i];
57151ad0ecdSdanielk1977         if( zArg[i]=='\'' ){
57247394703Sdrh           z[j++] = '\'';
57347394703Sdrh         }
57447394703Sdrh       }
57547394703Sdrh       z[j++] = '\'';
57647394703Sdrh       z[j] = 0;
577d8123366Sdanielk1977       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
57847394703Sdrh       sqliteFree(z);
57947394703Sdrh     }
58047394703Sdrh   }
581f9b596ebSdrh }
58247394703Sdrh 
583d24cc427Sdrh #ifdef SQLITE_SOUNDEX
584d24cc427Sdrh /*
585d24cc427Sdrh ** Compute the soundex encoding of a word.
586d24cc427Sdrh */
5870ae8b831Sdanielk1977 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
588d24cc427Sdrh   char zResult[8];
5894c755c0fSdrh   const u8 *zIn;
590d24cc427Sdrh   int i, j;
591d24cc427Sdrh   static const unsigned char iCode[] = {
592d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
593d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
594d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
595d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
596d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
597d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
598d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
599d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
600d24cc427Sdrh   };
601d24cc427Sdrh   assert( argc==1 );
6024c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
603d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
604d24cc427Sdrh   if( zIn[i] ){
605d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
606d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
607d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
608d24cc427Sdrh       if( code>0 ){
609d24cc427Sdrh         zResult[j++] = code + '0';
610d24cc427Sdrh       }
611d24cc427Sdrh     }
612d24cc427Sdrh     while( j<4 ){
613d24cc427Sdrh       zResult[j++] = '0';
614d24cc427Sdrh     }
615d24cc427Sdrh     zResult[j] = 0;
616d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
617d24cc427Sdrh   }else{
618d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
619d24cc427Sdrh   }
620d24cc427Sdrh }
621d24cc427Sdrh #endif
622d24cc427Sdrh 
623193a6b41Sdrh #ifdef SQLITE_TEST
624193a6b41Sdrh /*
625193a6b41Sdrh ** This function generates a string of random characters.  Used for
626193a6b41Sdrh ** generating test data.
627193a6b41Sdrh */
6280ae8b831Sdanielk1977 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
629bbd82df6Sdrh   static const unsigned char zSrc[] =
630193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
631193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
632193a6b41Sdrh      "0123456789"
633193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
634193a6b41Sdrh   int iMin, iMax, n, r, i;
635bbd82df6Sdrh   unsigned char zBuf[1000];
636193a6b41Sdrh   if( argc>=1 ){
637f9b596ebSdrh     iMin = sqlite3_value_int(argv[0]);
638193a6b41Sdrh     if( iMin<0 ) iMin = 0;
639193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
640193a6b41Sdrh   }else{
641193a6b41Sdrh     iMin = 1;
642193a6b41Sdrh   }
643193a6b41Sdrh   if( argc>=2 ){
644f9b596ebSdrh     iMax = sqlite3_value_int(argv[1]);
645193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
6461dba7279Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
647193a6b41Sdrh   }else{
648193a6b41Sdrh     iMax = 50;
649193a6b41Sdrh   }
650193a6b41Sdrh   n = iMin;
651193a6b41Sdrh   if( iMax>iMin ){
6524adee20fSdanielk1977     sqlite3Randomness(sizeof(r), &r);
653bbd82df6Sdrh     r &= 0x7fffffff;
654193a6b41Sdrh     n += r%(iMax + 1 - iMin);
655193a6b41Sdrh   }
6561dba7279Sdrh   assert( n<sizeof(zBuf) );
6574adee20fSdanielk1977   sqlite3Randomness(n, zBuf);
658193a6b41Sdrh   for(i=0; i<n; i++){
659bbd82df6Sdrh     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
660193a6b41Sdrh   }
661193a6b41Sdrh   zBuf[n] = 0;
662d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
663d8123366Sdanielk1977 }
6640e3d7476Sdrh #endif /* SQLITE_TEST */
665d8123366Sdanielk1977 
6660e3d7476Sdrh #ifdef SQLITE_TEST
667d8123366Sdanielk1977 /*
668d8123366Sdanielk1977 ** The following two SQL functions are used to test returning a text
669d8123366Sdanielk1977 ** result with a destructor. Function 'test_destructor' takes one argument
670d8123366Sdanielk1977 ** and returns the same argument interpreted as TEXT. A destructor is
671d8123366Sdanielk1977 ** passed with the sqlite3_result_text() call.
672d8123366Sdanielk1977 **
673d8123366Sdanielk1977 ** SQL function 'test_destructor_count' returns the number of outstanding
674d8123366Sdanielk1977 ** allocations made by 'test_destructor';
675d8123366Sdanielk1977 **
676d8123366Sdanielk1977 ** WARNING: Not threadsafe.
677d8123366Sdanielk1977 */
678d8123366Sdanielk1977 static int test_destructor_count_var = 0;
679d8123366Sdanielk1977 static void destructor(void *p){
680d8123366Sdanielk1977   char *zVal = (char *)p;
681d8123366Sdanielk1977   assert(zVal);
682d8123366Sdanielk1977   zVal--;
683d8123366Sdanielk1977   sqliteFree(zVal);
684d8123366Sdanielk1977   test_destructor_count_var--;
685d8123366Sdanielk1977 }
686d8123366Sdanielk1977 static void test_destructor(
687d8123366Sdanielk1977   sqlite3_context *pCtx,
688d8123366Sdanielk1977   int nArg,
689d8123366Sdanielk1977   sqlite3_value **argv
690d8123366Sdanielk1977 ){
691d8123366Sdanielk1977   char *zVal;
692f4618891Sdanielk1977   int len;
693f4618891Sdanielk1977   sqlite *db = sqlite3_user_data(pCtx);
694f4618891Sdanielk1977 
695d8123366Sdanielk1977   test_destructor_count_var++;
696d8123366Sdanielk1977   assert( nArg==1 );
697d8123366Sdanielk1977   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
698f4618891Sdanielk1977   len = sqlite3ValueBytes(argv[0], db->enc);
699f4618891Sdanielk1977   zVal = sqliteMalloc(len+3);
700f4618891Sdanielk1977   zVal[len] = 0;
701f4618891Sdanielk1977   zVal[len-1] = 0;
702d8123366Sdanielk1977   assert( zVal );
703d8123366Sdanielk1977   zVal++;
704f4618891Sdanielk1977   memcpy(zVal, sqlite3ValueText(argv[0], db->enc), len);
705f4618891Sdanielk1977   if( db->enc==SQLITE_UTF8 ){
706d8123366Sdanielk1977     sqlite3_result_text(pCtx, zVal, -1, destructor);
707f4618891Sdanielk1977   }else if( db->enc==SQLITE_UTF16LE ){
708f4618891Sdanielk1977     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
709f4618891Sdanielk1977   }else{
710f4618891Sdanielk1977     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
711f4618891Sdanielk1977   }
712d8123366Sdanielk1977 }
713d8123366Sdanielk1977 static void test_destructor_count(
714d8123366Sdanielk1977   sqlite3_context *pCtx,
715d8123366Sdanielk1977   int nArg,
716d8123366Sdanielk1977   sqlite3_value **argv
717d8123366Sdanielk1977 ){
718d8123366Sdanielk1977   sqlite3_result_int(pCtx, test_destructor_count_var);
719193a6b41Sdrh }
7200e3d7476Sdrh #endif /* SQLITE_TEST */
7213f6b0874Sdanielk1977 
7220e3d7476Sdrh #ifdef SQLITE_TEST
7230e3d7476Sdrh /*
7240e3d7476Sdrh ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
7250e3d7476Sdrh ** interface.
7260e3d7476Sdrh **
7270e3d7476Sdrh ** The test_auxdata() SQL function attempts to register each of its arguments
7280e3d7476Sdrh ** as auxiliary data.  If there are no prior registrations of aux data for
7290e3d7476Sdrh ** that argument (meaning the argument is not a constant or this is its first
7300e3d7476Sdrh ** call) then the result for that argument is 0.  If there is a prior
7310e3d7476Sdrh ** registration, the result for that argument is 1.  The overall result
7320e3d7476Sdrh ** is the individual argument results separated by spaces.
7330e3d7476Sdrh */
7343f6b0874Sdanielk1977 static void free_test_auxdata(void *p) {sqliteFree(p);}
7353f6b0874Sdanielk1977 static void test_auxdata(
7363f6b0874Sdanielk1977   sqlite3_context *pCtx,
7373f6b0874Sdanielk1977   int nArg,
7383f6b0874Sdanielk1977   sqlite3_value **argv
7393f6b0874Sdanielk1977 ){
7403f6b0874Sdanielk1977   int i;
7413f6b0874Sdanielk1977   char *zRet = sqliteMalloc(nArg*2);
7423f6b0874Sdanielk1977   if( !zRet ) return;
7433f6b0874Sdanielk1977   for(i=0; i<nArg; i++){
7443f6b0874Sdanielk1977     char const *z = sqlite3_value_text(argv[i]);
7453f6b0874Sdanielk1977     if( z ){
7463f6b0874Sdanielk1977       char *zAux = sqlite3_get_auxdata(pCtx, i);
7473f6b0874Sdanielk1977       if( zAux ){
7483f6b0874Sdanielk1977         zRet[i*2] = '1';
7493f6b0874Sdanielk1977         if( strcmp(zAux, z) ){
7503f6b0874Sdanielk1977           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
7513f6b0874Sdanielk1977           return;
7523f6b0874Sdanielk1977         }
7533f6b0874Sdanielk1977       }else{
7543f6b0874Sdanielk1977         zRet[i*2] = '0';
7553f6b0874Sdanielk1977         zAux = sqliteStrDup(z);
7563f6b0874Sdanielk1977         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
7573f6b0874Sdanielk1977       }
7583f6b0874Sdanielk1977       zRet[i*2+1] = ' ';
7593f6b0874Sdanielk1977     }
7603f6b0874Sdanielk1977   }
7613f6b0874Sdanielk1977   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
7623f6b0874Sdanielk1977 }
7630e3d7476Sdrh #endif /* SQLITE_TEST */
764193a6b41Sdrh 
7650ac65892Sdrh /*
766d3a149efSdrh ** An instance of the following structure holds the context of a
767dd5baa95Sdrh ** sum() or avg() aggregate computation.
768dd5baa95Sdrh */
769dd5baa95Sdrh typedef struct SumCtx SumCtx;
770dd5baa95Sdrh struct SumCtx {
771dd5baa95Sdrh   double sum;     /* Sum of terms */
772739105c7Sdrh   int cnt;        /* Number of elements summed */
773dd5baa95Sdrh };
774dd5baa95Sdrh 
775dd5baa95Sdrh /*
776dd5baa95Sdrh ** Routines used to compute the sum or average.
777dd5baa95Sdrh */
7780ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
779dd5baa95Sdrh   SumCtx *p;
780dd5baa95Sdrh   if( argc<1 ) return;
7814f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
7829c054830Sdrh   if( p && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
7834f26d6c4Sdrh     p->sum += sqlite3_value_double(argv[0]);
784739105c7Sdrh     p->cnt++;
785739105c7Sdrh   }
786dd5baa95Sdrh }
7870ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
788dd5baa95Sdrh   SumCtx *p;
7894f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
7907e18c259Sdanielk1977   sqlite3_result_double(context, p ? p->sum : 0.0);
791dd5baa95Sdrh }
7920ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
793dd5baa95Sdrh   SumCtx *p;
7944f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
795739105c7Sdrh   if( p && p->cnt>0 ){
7967e18c259Sdanielk1977     sqlite3_result_double(context, p->sum/(double)p->cnt);
797dd5baa95Sdrh   }
798dd5baa95Sdrh }
799dd5baa95Sdrh 
800dd5baa95Sdrh /*
801dd5baa95Sdrh ** An instance of the following structure holds the context of a
802a2ed5601Sdrh ** variance or standard deviation computation.
803d3a149efSdrh */
804d3a149efSdrh typedef struct StdDevCtx StdDevCtx;
805d3a149efSdrh struct StdDevCtx {
806d3a149efSdrh   double sum;     /* Sum of terms */
807d3a149efSdrh   double sum2;    /* Sum of the squares of terms */
808739105c7Sdrh   int cnt;        /* Number of terms counted */
809d3a149efSdrh };
810d3a149efSdrh 
811ef2daf54Sdrh #if 0   /* Omit because math library is required */
812d3a149efSdrh /*
813d3a149efSdrh ** Routines used to compute the standard deviation as an aggregate.
814d3a149efSdrh */
8150ae8b831Sdanielk1977 static void stdDevStep(sqlite3_context *context, int argc, const char **argv){
816d3a149efSdrh   StdDevCtx *p;
817d3a149efSdrh   double x;
8181350b030Sdrh   if( argc<1 ) return;
81924b03fd0Sdanielk1977   p = sqlite3_aggregate_context(context, sizeof(*p));
820739105c7Sdrh   if( p && argv[0] ){
8214adee20fSdanielk1977     x = sqlite3AtoF(argv[0], 0);
822d3a149efSdrh     p->sum += x;
823d3a149efSdrh     p->sum2 += x*x;
824739105c7Sdrh     p->cnt++;
825739105c7Sdrh   }
826d3a149efSdrh }
8270ae8b831Sdanielk1977 static void stdDevFinalize(sqlite3_context *context){
82824b03fd0Sdanielk1977   double rN = sqlite3_aggregate_count(context);
82924b03fd0Sdanielk1977   StdDevCtx *p = sqlite3_aggregate_context(context, sizeof(*p));
830739105c7Sdrh   if( p && p->cnt>1 ){
831739105c7Sdrh     double rCnt = cnt;
83224b03fd0Sdanielk1977     sqlite3_set_result_double(context,
833739105c7Sdrh        sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
834d3a149efSdrh   }
835d3a149efSdrh }
836ef2daf54Sdrh #endif
837d3a149efSdrh 
8380bce8354Sdrh /*
8390bce8354Sdrh ** The following structure keeps track of state information for the
8400bce8354Sdrh ** count() aggregate function.
8410bce8354Sdrh */
8420bce8354Sdrh typedef struct CountCtx CountCtx;
8430bce8354Sdrh struct CountCtx {
8440bce8354Sdrh   int n;
8450bce8354Sdrh };
846dd5baa95Sdrh 
8470bce8354Sdrh /*
8480bce8354Sdrh ** Routines to implement the count() aggregate function.
8490bce8354Sdrh */
8500ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
8510bce8354Sdrh   CountCtx *p;
8524f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8539c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
8540bce8354Sdrh     p->n++;
8550bce8354Sdrh   }
8560bce8354Sdrh }
8570ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
8580bce8354Sdrh   CountCtx *p;
8594f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
860f4479501Sdrh   sqlite3_result_int(context, p ? p->n : 0);
8610bce8354Sdrh }
8620bce8354Sdrh 
8630bce8354Sdrh /*
8640bce8354Sdrh ** This function tracks state information for the min() and max()
8650bce8354Sdrh ** aggregate functions.
8660bce8354Sdrh */
8670bce8354Sdrh typedef struct MinMaxCtx MinMaxCtx;
8680bce8354Sdrh struct MinMaxCtx {
8690bce8354Sdrh   char *z;         /* The best so far */
8700bce8354Sdrh   char zBuf[28];   /* Space that can be used for storage */
8710bce8354Sdrh };
8720bce8354Sdrh 
8730bce8354Sdrh /*
8740bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
8750bce8354Sdrh */
8760ae8b831Sdanielk1977 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87788208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
8789eb516c0Sdrh   Mem *pBest;
8799eb516c0Sdrh 
8809eb516c0Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
8819eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
8823aeab9e4Sdanielk1977   if( !pBest ) return;
883268380caSdrh 
88488208050Sdanielk1977   if( pBest->flags ){
8859eb516c0Sdrh     int max;
8869eb516c0Sdrh     int cmp;
887dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
8887e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
8897e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
8907e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
8917e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
8927e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
8937e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
8947e18c259Sdanielk1977     ** aggregate, or 0 for min().
8957e18c259Sdanielk1977     */
89688208050Sdanielk1977     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
897dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
89888208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
8997e18c259Sdanielk1977       sqlite3VdbeMemCopy(pBest, pArg);
90088208050Sdanielk1977     }
9010bce8354Sdrh   }else{
9027e18c259Sdanielk1977     sqlite3VdbeMemCopy(pBest, pArg);
9030bce8354Sdrh   }
9040bce8354Sdrh }
9050ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
90688208050Sdanielk1977   sqlite3_value *pRes;
9074f26d6c4Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
90888208050Sdanielk1977   if( pRes->flags ){
909f4479501Sdrh     sqlite3_result_value(context, pRes);
9100bce8354Sdrh   }
911b20e56b4Sdanielk1977   sqlite3VdbeMemRelease(pRes);
9120bce8354Sdrh }
913dd5baa95Sdrh 
914*4e5ffc5fSdrh 
915d3a149efSdrh /*
916a2ed5601Sdrh ** This function registered all of the above C functions as SQL
917a2ed5601Sdrh ** functions.  This should be the only routine in this file with
918a2ed5601Sdrh ** external linkage.
919dc04c583Sdrh */
9204adee20fSdanielk1977 void sqlite3RegisterBuiltinFunctions(sqlite *db){
9210bce8354Sdrh   static struct {
9220bce8354Sdrh      char *zName;
923268380caSdrh      signed char nArg;
924268380caSdrh      u8 argType;           /* 0: none.  1: db  2: (-1) */
925d02eb1fdSdanielk1977      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
926dc1bdc4fSdanielk1977      u8 needCollSeq;
9270ae8b831Sdanielk1977      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
9280bce8354Sdrh   } aFuncs[] = {
929d8123366Sdanielk1977     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
930d8123366Sdanielk1977     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
931d8123366Sdanielk1977     { "max",               -1, 2, SQLITE_UTF8,    1, minmaxFunc },
932d8123366Sdanielk1977     { "max",                0, 2, SQLITE_UTF8,    1, 0          },
933d8123366Sdanielk1977     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
934d8123366Sdanielk1977     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
935d8123366Sdanielk1977     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
936f4618891Sdanielk1977     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
937d8123366Sdanielk1977     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
938d8123366Sdanielk1977     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
939d8123366Sdanielk1977     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
940d8123366Sdanielk1977     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
941d8123366Sdanielk1977     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
942d8123366Sdanielk1977     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
943d8123366Sdanielk1977     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
944d8123366Sdanielk1977     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
945d8123366Sdanielk1977     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
946d8123366Sdanielk1977     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
947d8123366Sdanielk1977     { "like",               2, 0, SQLITE_UTF8,    0, likeFunc   },
948d8123366Sdanielk1977     { "glob",               2, 0, SQLITE_UTF8,    0, globFunc   },
949d8123366Sdanielk1977     { "nullif",             2, 0, SQLITE_UTF8,    0, nullifFunc },
950d8123366Sdanielk1977     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
951d8123366Sdanielk1977     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
952d8123366Sdanielk1977     { "last_insert_rowid",  0, 1, SQLITE_UTF8,    0, last_insert_rowid },
953b28af71aSdanielk1977     { "changes",            0, 1, SQLITE_UTF8,    0, changes    },
954b28af71aSdanielk1977     { "total_changes",      0, 1, SQLITE_UTF8,    0, total_changes },
955d24cc427Sdrh #ifdef SQLITE_SOUNDEX
956d8123366Sdanielk1977     { "soundex",            1, 0, SQLITE_UTF8, 0, soundexFunc},
957d24cc427Sdrh #endif
958193a6b41Sdrh #ifdef SQLITE_TEST
959d8123366Sdanielk1977     { "randstr",               2, 0, SQLITE_UTF8, 0, randStr    },
960f4618891Sdanielk1977     { "test_destructor",       1, 1, SQLITE_UTF8, 0, test_destructor},
961d8123366Sdanielk1977     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
9623f6b0874Sdanielk1977     { "test_auxdata",         -1, 0, SQLITE_UTF8, 0, test_auxdata},
963193a6b41Sdrh #endif
9640bce8354Sdrh   };
9650bce8354Sdrh   static struct {
9660bce8354Sdrh     char *zName;
967268380caSdrh     signed char nArg;
968268380caSdrh     u8 argType;
969dc1bdc4fSdanielk1977     u8 needCollSeq;
9700ae8b831Sdanielk1977     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
9710ae8b831Sdanielk1977     void (*xFinalize)(sqlite3_context*);
9720bce8354Sdrh   } aAggs[] = {
973dc1bdc4fSdanielk1977     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
974dc1bdc4fSdanielk1977     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
975dc1bdc4fSdanielk1977     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
976dc1bdc4fSdanielk1977     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
977dc1bdc4fSdanielk1977     { "count",  0, 0, 0, countStep,    countFinalize  },
978dc1bdc4fSdanielk1977     { "count",  1, 0, 0, countStep,    countFinalize  },
979ef2daf54Sdrh #if 0
980f9b596ebSdrh     { "stddev", 1, 0, stdDevStep,   stdDevFinalize },
981ef2daf54Sdrh #endif
9820bce8354Sdrh   };
9830bce8354Sdrh   int i;
9840bce8354Sdrh 
9850bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
986c572ef7fSdanielk1977     void *pArg = 0;
987c572ef7fSdanielk1977     switch( aFuncs[i].argType ){
988c572ef7fSdanielk1977       case 1: pArg = db; break;
989c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
990c572ef7fSdanielk1977     }
991ad7dd425Sdanielk1977     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
992f9d64d2cSdanielk1977         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
993dc1bdc4fSdanielk1977     if( aFuncs[i].needCollSeq ){
994dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
995dc1bdc4fSdanielk1977           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
996dc1bdc4fSdanielk1977       if( pFunc && aFuncs[i].needCollSeq ){
997dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
998dc1bdc4fSdanielk1977       }
999dc1bdc4fSdanielk1977     }
10000bce8354Sdrh   }
10010bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1002c572ef7fSdanielk1977     void *pArg = 0;
1003c572ef7fSdanielk1977     switch( aAggs[i].argType ){
1004c572ef7fSdanielk1977       case 1: pArg = db; break;
1005c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1006c572ef7fSdanielk1977     }
1007d8123366Sdanielk1977     sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1008f9d64d2cSdanielk1977         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1009dc1bdc4fSdanielk1977     if( aAggs[i].needCollSeq ){
1010dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1011d8123366Sdanielk1977           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1012dc1bdc4fSdanielk1977       if( pFunc && aAggs[i].needCollSeq ){
1013dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1014dc1bdc4fSdanielk1977       }
1015dc1bdc4fSdanielk1977     }
1016268380caSdrh   }
10174adee20fSdanielk1977   sqlite3RegisterDateTimeFunctions(db);
1018dc04c583Sdrh }
1019