xref: /sqlite-3.40.0/src/func.c (revision 8cd9db00)
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*8cd9db00Sdrh ** $Id: func.c,v 1.79 2004/07/18 23:06:54 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){
204*8cd9db00Sdrh   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++){
211dc04c583Sdrh     if( islower(z[i]) ) 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){
217*8cd9db00Sdrh   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++){
224dc04c583Sdrh     if( isupper(z[i]) ) 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 
301b28af71aSdanielk1977 #if 0
302b28af71aSdanielk1977 
3036ed41ad7Sdrh /*
304d02eb1fdSdanielk1977 ** A LIKE pattern compiles to an instance of the following structure. Refer
305d02eb1fdSdanielk1977 ** to the comment for compileLike() function for details.
306d02eb1fdSdanielk1977 */
307d02eb1fdSdanielk1977 struct LikePattern {
308d02eb1fdSdanielk1977   int nState;
309d02eb1fdSdanielk1977   struct LikeState {
310d02eb1fdSdanielk1977     int val;           /* Unicode codepoint or -1 for any char i.e. '_' */
311d02eb1fdSdanielk1977     int failstate;     /* State to jump to if next char is not val */
312f92c7ff7Sdrh   } aState[1];
313d02eb1fdSdanielk1977 };
314d02eb1fdSdanielk1977 typedef struct LikePattern LikePattern;
315d02eb1fdSdanielk1977 
316d02eb1fdSdanielk1977 void deleteLike(void *pLike){
317d02eb1fdSdanielk1977   sqliteFree(pLike);
318d02eb1fdSdanielk1977 }
319d02eb1fdSdanielk1977 /* #define TRACE_LIKE */
320d02eb1fdSdanielk1977 #if defined(TRACE_LIKE) && !defined(NDEBUG)
321d02eb1fdSdanielk1977 char *dumpLike(LikePattern *pLike){
322d02eb1fdSdanielk1977   int i;
323d02eb1fdSdanielk1977   int k = 0;
324d02eb1fdSdanielk1977   char *zBuf = (char *)sqliteMalloc(pLike->nState*40);
325d02eb1fdSdanielk1977 
326d02eb1fdSdanielk1977   k += sprintf(&zBuf[k], "%d states - ", pLike->nState);
327d02eb1fdSdanielk1977   for(i=0; i<pLike->nState; i++){
328d02eb1fdSdanielk1977     k += sprintf(&zBuf[k], " %d:(%d, %d)", i, pLike->aState[i].val,
329d02eb1fdSdanielk1977         pLike->aState[i].failstate);
330d02eb1fdSdanielk1977   }
331d02eb1fdSdanielk1977   return zBuf;
332d02eb1fdSdanielk1977 }
333d02eb1fdSdanielk1977 #endif
334d02eb1fdSdanielk1977 
335d02eb1fdSdanielk1977 /*
336d02eb1fdSdanielk1977 ** This function compiles an SQL 'LIKE' pattern into a state machine,
337d02eb1fdSdanielk1977 ** represented by a LikePattern structure.
338d02eb1fdSdanielk1977 **
339d02eb1fdSdanielk1977 ** Each state of the state-machine has two attributes, 'val' and
340d02eb1fdSdanielk1977 ** 'failstate'. The val attribute is either the value of a unicode
341d02eb1fdSdanielk1977 ** codepoint, or -1, indicating a '_' wildcard (match any single
342d02eb1fdSdanielk1977 ** character). The failstate is either the number of another state
343d02eb1fdSdanielk1977 ** or -1, indicating jump to 'no match'.
344d02eb1fdSdanielk1977 **
345d02eb1fdSdanielk1977 ** To see if a string matches a pattern the pattern is
346d02eb1fdSdanielk1977 ** compiled to a state machine that is executed according to the algorithm
347d02eb1fdSdanielk1977 ** below. The string is assumed to be terminated by a 'NUL' character
348d02eb1fdSdanielk1977 ** (unicode codepoint 0).
349d02eb1fdSdanielk1977 **
350d02eb1fdSdanielk1977 ** 1   S = 0
351d02eb1fdSdanielk1977 ** 2   DO
352d02eb1fdSdanielk1977 ** 3       C = <Next character from input string>
353d02eb1fdSdanielk1977 ** 4       IF( C matches <State S val> )
354d02eb1fdSdanielk1977 ** 5           S = S+1
355d02eb1fdSdanielk1977 ** 6       ELSE IF( S != <State S failstate> )
356d02eb1fdSdanielk1977 ** 7           S = <State S failstate>
357d02eb1fdSdanielk1977 ** 8           <Rewind Input string 1 character>
358d02eb1fdSdanielk1977 ** 9   WHILE( (C != NUL) AND (S != FAILED) )
359d02eb1fdSdanielk1977 ** 10
360d02eb1fdSdanielk1977 ** 11  IF( S == <number of states> )
361d02eb1fdSdanielk1977 ** 12      RETURN MATCH
362d02eb1fdSdanielk1977 ** 13  ELSE
363d02eb1fdSdanielk1977 ** 14      RETURN NO-MATCH
364d02eb1fdSdanielk1977 **
365d02eb1fdSdanielk1977 ** In practice there is a small optimization to avoid the <Rewind>
366d02eb1fdSdanielk1977 ** operation in line 8 of the description above.
367d02eb1fdSdanielk1977 **
368d02eb1fdSdanielk1977 ** For example, the following pattern, 'X%ABabc%_Y' is compiled to
369d02eb1fdSdanielk1977 ** the state machine below.
370d02eb1fdSdanielk1977 **
371d02eb1fdSdanielk1977 ** State    Val          FailState
372d02eb1fdSdanielk1977 ** -------------------------------
373d02eb1fdSdanielk1977 ** 0        120 (x)      -1 (NO MATCH)
374d02eb1fdSdanielk1977 ** 1        97  (a)      1
375d02eb1fdSdanielk1977 ** 2        98  (b)      1
376d02eb1fdSdanielk1977 ** 3        97  (a)      1
377d02eb1fdSdanielk1977 ** 4        98  (b)      2
378d02eb1fdSdanielk1977 ** 5        99  (c)      3
379d02eb1fdSdanielk1977 ** 6        -1  (_)      6
380d02eb1fdSdanielk1977 ** 7        121 (y)      7
381d02eb1fdSdanielk1977 ** 8        0   (NUL)    7
382d02eb1fdSdanielk1977 **
383d02eb1fdSdanielk1977 ** The algorithms implemented to compile and execute the state machine were
384d02eb1fdSdanielk1977 ** first presented in "Fast pattern matching in strings", Knuth, Morris and
385d02eb1fdSdanielk1977 ** Pratt, 1977.
386d02eb1fdSdanielk1977 **
387d02eb1fdSdanielk1977 */
388d02eb1fdSdanielk1977 LikePattern *compileLike(sqlite3_value *pPattern, u8 enc){
389d02eb1fdSdanielk1977   LikePattern *pLike;
390d02eb1fdSdanielk1977   struct LikeState *aState;
391d02eb1fdSdanielk1977   int pc_state = -1;    /* State number of previous '%' wild card */
392d02eb1fdSdanielk1977   int n = 0;
393d02eb1fdSdanielk1977   int c;
394d02eb1fdSdanielk1977 
395d02eb1fdSdanielk1977   int offset = 0;
396d02eb1fdSdanielk1977   const char *zLike;
397d02eb1fdSdanielk1977 
398dc8453fdSdanielk1977   if( enc==SQLITE_UTF8 ){
399d02eb1fdSdanielk1977     zLike = sqlite3_value_text(pPattern);
400d02eb1fdSdanielk1977     n = sqlite3_value_bytes(pPattern) + 1;
401d02eb1fdSdanielk1977   }else{
402d02eb1fdSdanielk1977     zLike = sqlite3_value_text16(pPattern);
403d02eb1fdSdanielk1977     n = sqlite3_value_bytes16(pPattern)/2 + 1;
404d02eb1fdSdanielk1977   }
405d02eb1fdSdanielk1977 
406d02eb1fdSdanielk1977   pLike = (LikePattern *)
407d02eb1fdSdanielk1977       sqliteMalloc(sizeof(LikePattern)+n*sizeof(struct LikeState));
408d02eb1fdSdanielk1977   aState = pLike->aState;
409d02eb1fdSdanielk1977 
410d02eb1fdSdanielk1977   n = 0;
411d02eb1fdSdanielk1977   do {
412d02eb1fdSdanielk1977     c = sqlite3ReadUniChar(zLike, &offset, &enc, 1);
413d02eb1fdSdanielk1977     if( c==95 ){        /* A '_' wildcard */
414d02eb1fdSdanielk1977       aState[n].val = -1;
415d02eb1fdSdanielk1977       n++;
416d02eb1fdSdanielk1977     }else if( c==37 ){  /* A '%' wildcard */
417d02eb1fdSdanielk1977       aState[n].failstate = n;
418d02eb1fdSdanielk1977       pc_state = n;
419d02eb1fdSdanielk1977     }else{              /* A regular character */
420d02eb1fdSdanielk1977       aState[n].val = c;
421d02eb1fdSdanielk1977 
422d02eb1fdSdanielk1977       assert( pc_state<=n );
423d02eb1fdSdanielk1977       if( pc_state<0 ){
424d02eb1fdSdanielk1977         aState[n].failstate = -1;
425d02eb1fdSdanielk1977       }else if( pc_state==n ){
426ad7dd425Sdanielk1977         if( c ){
427d02eb1fdSdanielk1977           aState[n].failstate = pc_state;
428d02eb1fdSdanielk1977         }else{
429ad7dd425Sdanielk1977           aState[n].failstate = -2;
430ad7dd425Sdanielk1977         }
431ad7dd425Sdanielk1977       }else{
432d02eb1fdSdanielk1977         int k = pLike->aState[n-1].failstate;
433d02eb1fdSdanielk1977         while( k>pc_state && aState[k+1].val!=-1 && aState[k+1].val!=c ){
434d02eb1fdSdanielk1977           k = aState[k].failstate;
435d02eb1fdSdanielk1977         }
436d02eb1fdSdanielk1977         if( k!=pc_state && aState[k+1].val==c ){
437d02eb1fdSdanielk1977           assert( k==pc_state );
438d02eb1fdSdanielk1977           k++;
439d02eb1fdSdanielk1977         }
440d02eb1fdSdanielk1977         aState[n].failstate = k;
441d02eb1fdSdanielk1977       }
442d02eb1fdSdanielk1977       n++;
443d02eb1fdSdanielk1977     }
444d02eb1fdSdanielk1977   }while( c );
445d02eb1fdSdanielk1977   pLike->nState = n;
446d02eb1fdSdanielk1977 #if defined(TRACE_LIKE) && !defined(NDEBUG)
447d02eb1fdSdanielk1977   {
448d02eb1fdSdanielk1977     char *zCompiled = dumpLike(pLike);
449d02eb1fdSdanielk1977     printf("Pattern=\"%s\" Compiled=\"%s\"\n", zPattern, zCompiled);
450d02eb1fdSdanielk1977     sqliteFree(zCompiled);
451d02eb1fdSdanielk1977   }
452d02eb1fdSdanielk1977 #endif
453d02eb1fdSdanielk1977   return pLike;
454d02eb1fdSdanielk1977 }
455d02eb1fdSdanielk1977 
456d02eb1fdSdanielk1977 /*
4570ac65892Sdrh ** Implementation of the like() SQL function.  This function implements
4580ac65892Sdrh ** the build-in LIKE operator.  The first argument to the function is the
459d02eb1fdSdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
4600ac65892Sdrh **
4610ac65892Sdrh **       A LIKE B
4620ac65892Sdrh **
463d02eb1fdSdanielk1977 ** is implemented as like(B,A).
464d02eb1fdSdanielk1977 **
465d02eb1fdSdanielk1977 ** If the pointer retrieved by via a call to sqlite3_user_data() is
466d02eb1fdSdanielk1977 ** not NULL, then this function uses UTF-16. Otherwise UTF-8.
4670ac65892Sdrh */
46851ad0ecdSdanielk1977 static void likeFunc(
4690ae8b831Sdanielk1977   sqlite3_context *context,
47051ad0ecdSdanielk1977   int argc,
47151ad0ecdSdanielk1977   sqlite3_value **argv
47251ad0ecdSdanielk1977 ){
473ad7dd425Sdanielk1977   register int c;
474d02eb1fdSdanielk1977   u8 enc;
475d02eb1fdSdanielk1977   int offset = 0;
476d02eb1fdSdanielk1977   const unsigned char *zString;
477d02eb1fdSdanielk1977   LikePattern *pLike = sqlite3_get_auxdata(context, 0);
478ad7dd425Sdanielk1977   struct LikeState *aState;
479ad7dd425Sdanielk1977   register struct LikeState *pState;
480d02eb1fdSdanielk1977 
481d02eb1fdSdanielk1977   /* If either argument is NULL, the result is NULL */
482d02eb1fdSdanielk1977   if( sqlite3_value_type(argv[1])==SQLITE_NULL ||
483d02eb1fdSdanielk1977       sqlite3_value_type(argv[0])==SQLITE_NULL ){
484d02eb1fdSdanielk1977     return;
485d02eb1fdSdanielk1977   }
486d02eb1fdSdanielk1977 
487d02eb1fdSdanielk1977   /* If the user-data pointer is NULL, use UTF-8. Otherwise UTF-16. */
488d02eb1fdSdanielk1977   if( sqlite3_user_data(context) ){
489dc8453fdSdanielk1977     enc = SQLITE_UTF16NATIVE;
490d02eb1fdSdanielk1977     zString = (const unsigned char *)sqlite3_value_text16(argv[1]);
491ad7dd425Sdanielk1977     assert(0);
492d02eb1fdSdanielk1977   }else{
493dc8453fdSdanielk1977     enc = SQLITE_UTF8;
494d02eb1fdSdanielk1977     zString = sqlite3_value_text(argv[1]);
495d02eb1fdSdanielk1977   }
496d02eb1fdSdanielk1977 
497d02eb1fdSdanielk1977   /* If the LIKE pattern has not been compiled, compile it now. */
498d02eb1fdSdanielk1977   if( !pLike ){
499d02eb1fdSdanielk1977     pLike = compileLike(argv[0], enc);
500d02eb1fdSdanielk1977     if( !pLike ){
501d02eb1fdSdanielk1977       sqlite3_result_error(context, "out of memory", -1);
502d02eb1fdSdanielk1977       return;
503d02eb1fdSdanielk1977     }
504d02eb1fdSdanielk1977     sqlite3_set_auxdata(context, 0, pLike, deleteLike);
505d02eb1fdSdanielk1977   }
506ad7dd425Sdanielk1977   aState = pLike->aState;
507ad7dd425Sdanielk1977   pState = aState;
508d02eb1fdSdanielk1977 
509d02eb1fdSdanielk1977   do {
510dc8453fdSdanielk1977     if( enc==SQLITE_UTF8 ){
511ad7dd425Sdanielk1977       c = zString[offset++];
512ad7dd425Sdanielk1977       if( c&0x80 ){
513ad7dd425Sdanielk1977         offset--;
514ad7dd425Sdanielk1977         c = sqlite3ReadUniChar(zString, &offset, &enc, 1);
515ad7dd425Sdanielk1977       }
516ad7dd425Sdanielk1977     }else{
517ad7dd425Sdanielk1977       c = sqlite3ReadUniChar(zString, &offset, &enc, 1);
518ad7dd425Sdanielk1977     }
519ad7dd425Sdanielk1977 
520ad7dd425Sdanielk1977 skip_read:
521d02eb1fdSdanielk1977 
522d02eb1fdSdanielk1977 #if defined(TRACE_LIKE) && !defined(NDEBUG)
523d02eb1fdSdanielk1977     printf("State=%d:(%d, %d) Input=%d\n",
524ad7dd425Sdanielk1977         (aState - pState), pState->val, pState->failstate, c);
525d02eb1fdSdanielk1977 #endif
526d02eb1fdSdanielk1977 
527ad7dd425Sdanielk1977     if( pState->val==-1 || pState->val==c ){
528ad7dd425Sdanielk1977       pState++;
529d02eb1fdSdanielk1977     }else{
530ad7dd425Sdanielk1977       struct LikeState *pFailState = &aState[pState->failstate];
531ad7dd425Sdanielk1977       if( pState!=pFailState ){
532ad7dd425Sdanielk1977         pState = pFailState;
533ad7dd425Sdanielk1977         if( c && pState>=aState ) goto skip_read;
534d02eb1fdSdanielk1977       }
535d02eb1fdSdanielk1977     }
536ad7dd425Sdanielk1977   }while( c && pState>=aState );
537d02eb1fdSdanielk1977 
538ad7dd425Sdanielk1977   if( (pState-aState)==pLike->nState || (pState-aState)<-1 ){
539d02eb1fdSdanielk1977     sqlite3_result_int(context, 1);
540d02eb1fdSdanielk1977   }else{
541d02eb1fdSdanielk1977     sqlite3_result_int(context, 0);
54251ad0ecdSdanielk1977   }
5430ac65892Sdrh }
5443f6b0874Sdanielk1977 #endif
5453f6b0874Sdanielk1977 
5463f6b0874Sdanielk1977 /*
5473f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
5483f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
5493f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
5503f6b0874Sdanielk1977 **
5513f6b0874Sdanielk1977 **       A LIKE B
5523f6b0874Sdanielk1977 **
5533f6b0874Sdanielk1977 ** is implemented as like(B,A).
5543f6b0874Sdanielk1977 **
5553f6b0874Sdanielk1977 ** If the pointer retrieved by via a call to sqlite3_user_data() is
5563f6b0874Sdanielk1977 ** not NULL, then this function uses UTF-16. Otherwise UTF-8.
5573f6b0874Sdanielk1977 */
5583f6b0874Sdanielk1977 static void likeFunc(
5593f6b0874Sdanielk1977   sqlite3_context *context,
5603f6b0874Sdanielk1977   int argc,
5613f6b0874Sdanielk1977   sqlite3_value **argv
5623f6b0874Sdanielk1977 ){
5633f6b0874Sdanielk1977   const unsigned char *zA = sqlite3_value_text(argv[0]);
5643f6b0874Sdanielk1977   const unsigned char *zB = sqlite3_value_text(argv[1]);
5653f6b0874Sdanielk1977   if( zA && zB ){
5663f6b0874Sdanielk1977     sqlite3_result_int(context, sqlite3utf8LikeCompare(zA, zB));
5673f6b0874Sdanielk1977   }
5683f6b0874Sdanielk1977 }
5690ac65892Sdrh 
5700ac65892Sdrh /*
5710ac65892Sdrh ** Implementation of the glob() SQL function.  This function implements
5720ac65892Sdrh ** the build-in GLOB operator.  The first argument to the function is the
5730ac65892Sdrh ** string and the second argument is the pattern.  So, the SQL statements:
5740ac65892Sdrh **
5750ac65892Sdrh **       A GLOB B
5760ac65892Sdrh **
5770ac65892Sdrh ** is implemented as glob(A,B).
5780ac65892Sdrh */
5790ae8b831Sdanielk1977 static void globFunc(sqlite3_context *context, int arg, sqlite3_value **argv){
5804f26d6c4Sdrh   const unsigned char *zA = sqlite3_value_text(argv[0]);
5814f26d6c4Sdrh   const unsigned char *zB = sqlite3_value_text(argv[1]);
58251ad0ecdSdanielk1977   if( zA && zB ){
583f4479501Sdrh     sqlite3_result_int(context, sqlite3GlobCompare(zA, zB));
58451ad0ecdSdanielk1977   }
5858912d106Sdrh }
5868912d106Sdrh 
5878912d106Sdrh /*
5888912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
5898912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
5908912d106Sdrh ** arguments are equal to each other.
5918912d106Sdrh */
592f9b596ebSdrh static void nullifFunc(
593f9b596ebSdrh   sqlite3_context *context,
594f9b596ebSdrh   int argc,
595f9b596ebSdrh   sqlite3_value **argv
596f9b596ebSdrh ){
597dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
598dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
599f4479501Sdrh     sqlite3_result_value(context, argv[0]);
6008912d106Sdrh   }
6010ac65892Sdrh }
6020ac65892Sdrh 
603647cb0e1Sdrh /*
604647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
605647cb0e1Sdrh ** of the SQLite library that is running.
606647cb0e1Sdrh */
607f9b596ebSdrh static void versionFunc(
608f9b596ebSdrh   sqlite3_context *context,
609f9b596ebSdrh   int argc,
610f9b596ebSdrh   sqlite3_value **argv
611f9b596ebSdrh ){
612d8123366Sdanielk1977   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
613647cb0e1Sdrh }
614647cb0e1Sdrh 
61547394703Sdrh /*
61647394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
61747394703Sdrh ** change.  This function may disappear.  Do not write code that depends
61847394703Sdrh ** on this function.
61947394703Sdrh **
62047394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
62147394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
62247394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
62347394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
62447394703Sdrh ** single-quote escapes.
62547394703Sdrh */
6260ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62747394703Sdrh   if( argc<1 ) return;
628f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
6299c054830Sdrh     case SQLITE_NULL: {
630d8123366Sdanielk1977       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
631f9b596ebSdrh       break;
632f9b596ebSdrh     }
6339c054830Sdrh     case SQLITE_INTEGER:
6349c054830Sdrh     case SQLITE_FLOAT: {
635f4479501Sdrh       sqlite3_result_value(context, argv[0]);
636f9b596ebSdrh       break;
637f9b596ebSdrh     }
6383f41e976Sdanielk1977     case SQLITE_BLOB: {
6393f41e976Sdanielk1977       static const char hexdigits[] = {
6403f41e976Sdanielk1977         '0', '1', '2', '3', '4', '5', '6', '7',
6413f41e976Sdanielk1977         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
6423f41e976Sdanielk1977       };
6433f41e976Sdanielk1977       char *zText = 0;
6443f41e976Sdanielk1977       int nBlob = sqlite3_value_bytes(argv[0]);
6453f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
6463f41e976Sdanielk1977 
6473f41e976Sdanielk1977       zText = (char *)sqliteMalloc((2*nBlob)+4);
6483f41e976Sdanielk1977       if( !zText ){
6493f41e976Sdanielk1977         sqlite3_result_error(context, "out of memory", -1);
6503f41e976Sdanielk1977       }else{
6513f41e976Sdanielk1977         int i;
6523f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
6533f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
6543f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
6553f41e976Sdanielk1977         }
6563f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
6573f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
6583f41e976Sdanielk1977         zText[0] = 'X';
6593f41e976Sdanielk1977         zText[1] = '\'';
660d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
6613f41e976Sdanielk1977         sqliteFree(zText);
6623f41e976Sdanielk1977       }
6633f41e976Sdanielk1977       break;
6643f41e976Sdanielk1977     }
6659c054830Sdrh     case SQLITE_TEXT: {
66647394703Sdrh       int i,j,n;
6674f26d6c4Sdrh       const char *zArg = sqlite3_value_text(argv[0]);
66847394703Sdrh       char *z;
669f9b596ebSdrh 
67051ad0ecdSdanielk1977       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
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 
688d24cc427Sdrh #ifdef SQLITE_SOUNDEX
689d24cc427Sdrh /*
690d24cc427Sdrh ** Compute the soundex encoding of a word.
691d24cc427Sdrh */
6920ae8b831Sdanielk1977 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
693d24cc427Sdrh   char zResult[8];
694d24cc427Sdrh   const char *zIn;
695d24cc427Sdrh   int i, j;
696d24cc427Sdrh   static const unsigned char iCode[] = {
697d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
698d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
699d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
700d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
701d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
702d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
703d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
704d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
705d24cc427Sdrh   };
706d24cc427Sdrh   assert( argc==1 );
7074f26d6c4Sdrh   zIn = sqlite3_value_text(argv[0]);
708d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
709d24cc427Sdrh   if( zIn[i] ){
710d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
711d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
712d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
713d24cc427Sdrh       if( code>0 ){
714d24cc427Sdrh         zResult[j++] = code + '0';
715d24cc427Sdrh       }
716d24cc427Sdrh     }
717d24cc427Sdrh     while( j<4 ){
718d24cc427Sdrh       zResult[j++] = '0';
719d24cc427Sdrh     }
720d24cc427Sdrh     zResult[j] = 0;
721d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
722d24cc427Sdrh   }else{
723d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
724d24cc427Sdrh   }
725d24cc427Sdrh }
726d24cc427Sdrh #endif
727d24cc427Sdrh 
728193a6b41Sdrh #ifdef SQLITE_TEST
729193a6b41Sdrh /*
730193a6b41Sdrh ** This function generates a string of random characters.  Used for
731193a6b41Sdrh ** generating test data.
732193a6b41Sdrh */
7330ae8b831Sdanielk1977 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
734bbd82df6Sdrh   static const unsigned char zSrc[] =
735193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
736193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
737193a6b41Sdrh      "0123456789"
738193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
739193a6b41Sdrh   int iMin, iMax, n, r, i;
740bbd82df6Sdrh   unsigned char zBuf[1000];
741193a6b41Sdrh   if( argc>=1 ){
742f9b596ebSdrh     iMin = sqlite3_value_int(argv[0]);
743193a6b41Sdrh     if( iMin<0 ) iMin = 0;
744193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
745193a6b41Sdrh   }else{
746193a6b41Sdrh     iMin = 1;
747193a6b41Sdrh   }
748193a6b41Sdrh   if( argc>=2 ){
749f9b596ebSdrh     iMax = sqlite3_value_int(argv[1]);
750193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
7511dba7279Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
752193a6b41Sdrh   }else{
753193a6b41Sdrh     iMax = 50;
754193a6b41Sdrh   }
755193a6b41Sdrh   n = iMin;
756193a6b41Sdrh   if( iMax>iMin ){
7574adee20fSdanielk1977     sqlite3Randomness(sizeof(r), &r);
758bbd82df6Sdrh     r &= 0x7fffffff;
759193a6b41Sdrh     n += r%(iMax + 1 - iMin);
760193a6b41Sdrh   }
7611dba7279Sdrh   assert( n<sizeof(zBuf) );
7624adee20fSdanielk1977   sqlite3Randomness(n, zBuf);
763193a6b41Sdrh   for(i=0; i<n; i++){
764bbd82df6Sdrh     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
765193a6b41Sdrh   }
766193a6b41Sdrh   zBuf[n] = 0;
767d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
768d8123366Sdanielk1977 }
7690e3d7476Sdrh #endif /* SQLITE_TEST */
770d8123366Sdanielk1977 
7710e3d7476Sdrh #ifdef SQLITE_TEST
772d8123366Sdanielk1977 /*
773d8123366Sdanielk1977 ** The following two SQL functions are used to test returning a text
774d8123366Sdanielk1977 ** result with a destructor. Function 'test_destructor' takes one argument
775d8123366Sdanielk1977 ** and returns the same argument interpreted as TEXT. A destructor is
776d8123366Sdanielk1977 ** passed with the sqlite3_result_text() call.
777d8123366Sdanielk1977 **
778d8123366Sdanielk1977 ** SQL function 'test_destructor_count' returns the number of outstanding
779d8123366Sdanielk1977 ** allocations made by 'test_destructor';
780d8123366Sdanielk1977 **
781d8123366Sdanielk1977 ** WARNING: Not threadsafe.
782d8123366Sdanielk1977 */
783d8123366Sdanielk1977 static int test_destructor_count_var = 0;
784d8123366Sdanielk1977 static void destructor(void *p){
785d8123366Sdanielk1977   char *zVal = (char *)p;
786d8123366Sdanielk1977   assert(zVal);
787d8123366Sdanielk1977   zVal--;
788d8123366Sdanielk1977   sqliteFree(zVal);
789d8123366Sdanielk1977   test_destructor_count_var--;
790d8123366Sdanielk1977 }
791d8123366Sdanielk1977 static void test_destructor(
792d8123366Sdanielk1977   sqlite3_context *pCtx,
793d8123366Sdanielk1977   int nArg,
794d8123366Sdanielk1977   sqlite3_value **argv
795d8123366Sdanielk1977 ){
796d8123366Sdanielk1977   char *zVal;
797f4618891Sdanielk1977   int len;
798f4618891Sdanielk1977   sqlite *db = sqlite3_user_data(pCtx);
799f4618891Sdanielk1977 
800d8123366Sdanielk1977   test_destructor_count_var++;
801d8123366Sdanielk1977   assert( nArg==1 );
802d8123366Sdanielk1977   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
803f4618891Sdanielk1977   len = sqlite3ValueBytes(argv[0], db->enc);
804f4618891Sdanielk1977   zVal = sqliteMalloc(len+3);
805f4618891Sdanielk1977   zVal[len] = 0;
806f4618891Sdanielk1977   zVal[len-1] = 0;
807d8123366Sdanielk1977   assert( zVal );
808d8123366Sdanielk1977   zVal++;
809f4618891Sdanielk1977   memcpy(zVal, sqlite3ValueText(argv[0], db->enc), len);
810f4618891Sdanielk1977   if( db->enc==SQLITE_UTF8 ){
811d8123366Sdanielk1977     sqlite3_result_text(pCtx, zVal, -1, destructor);
812f4618891Sdanielk1977   }else if( db->enc==SQLITE_UTF16LE ){
813f4618891Sdanielk1977     sqlite3_result_text16le(pCtx, zVal, -1, destructor);
814f4618891Sdanielk1977   }else{
815f4618891Sdanielk1977     sqlite3_result_text16be(pCtx, zVal, -1, destructor);
816f4618891Sdanielk1977   }
817d8123366Sdanielk1977 }
818d8123366Sdanielk1977 static void test_destructor_count(
819d8123366Sdanielk1977   sqlite3_context *pCtx,
820d8123366Sdanielk1977   int nArg,
821d8123366Sdanielk1977   sqlite3_value **argv
822d8123366Sdanielk1977 ){
823d8123366Sdanielk1977   sqlite3_result_int(pCtx, test_destructor_count_var);
824193a6b41Sdrh }
8250e3d7476Sdrh #endif /* SQLITE_TEST */
8263f6b0874Sdanielk1977 
8270e3d7476Sdrh #ifdef SQLITE_TEST
8280e3d7476Sdrh /*
8290e3d7476Sdrh ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
8300e3d7476Sdrh ** interface.
8310e3d7476Sdrh **
8320e3d7476Sdrh ** The test_auxdata() SQL function attempts to register each of its arguments
8330e3d7476Sdrh ** as auxiliary data.  If there are no prior registrations of aux data for
8340e3d7476Sdrh ** that argument (meaning the argument is not a constant or this is its first
8350e3d7476Sdrh ** call) then the result for that argument is 0.  If there is a prior
8360e3d7476Sdrh ** registration, the result for that argument is 1.  The overall result
8370e3d7476Sdrh ** is the individual argument results separated by spaces.
8380e3d7476Sdrh */
8393f6b0874Sdanielk1977 static void free_test_auxdata(void *p) {sqliteFree(p);}
8403f6b0874Sdanielk1977 static void test_auxdata(
8413f6b0874Sdanielk1977   sqlite3_context *pCtx,
8423f6b0874Sdanielk1977   int nArg,
8433f6b0874Sdanielk1977   sqlite3_value **argv
8443f6b0874Sdanielk1977 ){
8453f6b0874Sdanielk1977   int i;
8463f6b0874Sdanielk1977   char *zRet = sqliteMalloc(nArg*2);
8473f6b0874Sdanielk1977   if( !zRet ) return;
8483f6b0874Sdanielk1977   for(i=0; i<nArg; i++){
8493f6b0874Sdanielk1977     char const *z = sqlite3_value_text(argv[i]);
8503f6b0874Sdanielk1977     if( z ){
8513f6b0874Sdanielk1977       char *zAux = sqlite3_get_auxdata(pCtx, i);
8523f6b0874Sdanielk1977       if( zAux ){
8533f6b0874Sdanielk1977         zRet[i*2] = '1';
8543f6b0874Sdanielk1977         if( strcmp(zAux, z) ){
8553f6b0874Sdanielk1977           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
8563f6b0874Sdanielk1977           return;
8573f6b0874Sdanielk1977         }
8583f6b0874Sdanielk1977       }else{
8593f6b0874Sdanielk1977         zRet[i*2] = '0';
8603f6b0874Sdanielk1977         zAux = sqliteStrDup(z);
8613f6b0874Sdanielk1977         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
8623f6b0874Sdanielk1977       }
8633f6b0874Sdanielk1977       zRet[i*2+1] = ' ';
8643f6b0874Sdanielk1977     }
8653f6b0874Sdanielk1977   }
8663f6b0874Sdanielk1977   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
8673f6b0874Sdanielk1977 }
8680e3d7476Sdrh #endif /* SQLITE_TEST */
869193a6b41Sdrh 
8700ac65892Sdrh /*
871d3a149efSdrh ** An instance of the following structure holds the context of a
872dd5baa95Sdrh ** sum() or avg() aggregate computation.
873dd5baa95Sdrh */
874dd5baa95Sdrh typedef struct SumCtx SumCtx;
875dd5baa95Sdrh struct SumCtx {
876dd5baa95Sdrh   double sum;     /* Sum of terms */
877739105c7Sdrh   int cnt;        /* Number of elements summed */
878dd5baa95Sdrh };
879dd5baa95Sdrh 
880dd5baa95Sdrh /*
881dd5baa95Sdrh ** Routines used to compute the sum or average.
882dd5baa95Sdrh */
8830ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
884dd5baa95Sdrh   SumCtx *p;
885dd5baa95Sdrh   if( argc<1 ) return;
8864f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8879c054830Sdrh   if( p && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
8884f26d6c4Sdrh     p->sum += sqlite3_value_double(argv[0]);
889739105c7Sdrh     p->cnt++;
890739105c7Sdrh   }
891dd5baa95Sdrh }
8920ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
893dd5baa95Sdrh   SumCtx *p;
8944f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8957e18c259Sdanielk1977   sqlite3_result_double(context, p ? p->sum : 0.0);
896dd5baa95Sdrh }
8970ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
898dd5baa95Sdrh   SumCtx *p;
8994f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
900739105c7Sdrh   if( p && p->cnt>0 ){
9017e18c259Sdanielk1977     sqlite3_result_double(context, p->sum/(double)p->cnt);
902dd5baa95Sdrh   }
903dd5baa95Sdrh }
904dd5baa95Sdrh 
905dd5baa95Sdrh /*
906dd5baa95Sdrh ** An instance of the following structure holds the context of a
907a2ed5601Sdrh ** variance or standard deviation computation.
908d3a149efSdrh */
909d3a149efSdrh typedef struct StdDevCtx StdDevCtx;
910d3a149efSdrh struct StdDevCtx {
911d3a149efSdrh   double sum;     /* Sum of terms */
912d3a149efSdrh   double sum2;    /* Sum of the squares of terms */
913739105c7Sdrh   int cnt;        /* Number of terms counted */
914d3a149efSdrh };
915d3a149efSdrh 
916ef2daf54Sdrh #if 0   /* Omit because math library is required */
917d3a149efSdrh /*
918d3a149efSdrh ** Routines used to compute the standard deviation as an aggregate.
919d3a149efSdrh */
9200ae8b831Sdanielk1977 static void stdDevStep(sqlite3_context *context, int argc, const char **argv){
921d3a149efSdrh   StdDevCtx *p;
922d3a149efSdrh   double x;
9231350b030Sdrh   if( argc<1 ) return;
92424b03fd0Sdanielk1977   p = sqlite3_aggregate_context(context, sizeof(*p));
925739105c7Sdrh   if( p && argv[0] ){
9264adee20fSdanielk1977     x = sqlite3AtoF(argv[0], 0);
927d3a149efSdrh     p->sum += x;
928d3a149efSdrh     p->sum2 += x*x;
929739105c7Sdrh     p->cnt++;
930739105c7Sdrh   }
931d3a149efSdrh }
9320ae8b831Sdanielk1977 static void stdDevFinalize(sqlite3_context *context){
93324b03fd0Sdanielk1977   double rN = sqlite3_aggregate_count(context);
93424b03fd0Sdanielk1977   StdDevCtx *p = sqlite3_aggregate_context(context, sizeof(*p));
935739105c7Sdrh   if( p && p->cnt>1 ){
936739105c7Sdrh     double rCnt = cnt;
93724b03fd0Sdanielk1977     sqlite3_set_result_double(context,
938739105c7Sdrh        sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
939d3a149efSdrh   }
940d3a149efSdrh }
941ef2daf54Sdrh #endif
942d3a149efSdrh 
9430bce8354Sdrh /*
9440bce8354Sdrh ** The following structure keeps track of state information for the
9450bce8354Sdrh ** count() aggregate function.
9460bce8354Sdrh */
9470bce8354Sdrh typedef struct CountCtx CountCtx;
9480bce8354Sdrh struct CountCtx {
9490bce8354Sdrh   int n;
9500bce8354Sdrh };
951dd5baa95Sdrh 
9520bce8354Sdrh /*
9530bce8354Sdrh ** Routines to implement the count() aggregate function.
9540bce8354Sdrh */
9550ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
9560bce8354Sdrh   CountCtx *p;
9574f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
9589c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
9590bce8354Sdrh     p->n++;
9600bce8354Sdrh   }
9610bce8354Sdrh }
9620ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
9630bce8354Sdrh   CountCtx *p;
9644f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
965f4479501Sdrh   sqlite3_result_int(context, p ? p->n : 0);
9660bce8354Sdrh }
9670bce8354Sdrh 
9680bce8354Sdrh /*
9690bce8354Sdrh ** This function tracks state information for the min() and max()
9700bce8354Sdrh ** aggregate functions.
9710bce8354Sdrh */
9720bce8354Sdrh typedef struct MinMaxCtx MinMaxCtx;
9730bce8354Sdrh struct MinMaxCtx {
9740bce8354Sdrh   char *z;         /* The best so far */
9750bce8354Sdrh   char zBuf[28];   /* Space that can be used for storage */
9760bce8354Sdrh };
9770bce8354Sdrh 
9780bce8354Sdrh /*
9790bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
9800bce8354Sdrh */
9810ae8b831Sdanielk1977 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
98288208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
9839eb516c0Sdrh   Mem *pBest;
9849eb516c0Sdrh 
9859eb516c0Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
9869eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
9873aeab9e4Sdanielk1977   if( !pBest ) return;
988268380caSdrh 
98988208050Sdanielk1977   if( pBest->flags ){
9909eb516c0Sdrh     int max;
9919eb516c0Sdrh     int cmp;
992dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
9937e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
9947e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
9957e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
9967e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
9977e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
9987e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
9997e18c259Sdanielk1977     ** aggregate, or 0 for min().
10007e18c259Sdanielk1977     */
100188208050Sdanielk1977     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
1002dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
100388208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
10047e18c259Sdanielk1977       sqlite3VdbeMemCopy(pBest, pArg);
100588208050Sdanielk1977     }
10060bce8354Sdrh   }else{
10077e18c259Sdanielk1977     sqlite3VdbeMemCopy(pBest, pArg);
10080bce8354Sdrh   }
10090bce8354Sdrh }
10100ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
101188208050Sdanielk1977   sqlite3_value *pRes;
10124f26d6c4Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
101388208050Sdanielk1977   if( pRes->flags ){
1014f4479501Sdrh     sqlite3_result_value(context, pRes);
10150bce8354Sdrh   }
1016b20e56b4Sdanielk1977   sqlite3VdbeMemRelease(pRes);
10170bce8354Sdrh }
1018dd5baa95Sdrh 
1019d3a149efSdrh /*
1020a2ed5601Sdrh ** This function registered all of the above C functions as SQL
1021a2ed5601Sdrh ** functions.  This should be the only routine in this file with
1022a2ed5601Sdrh ** external linkage.
1023dc04c583Sdrh */
10244adee20fSdanielk1977 void sqlite3RegisterBuiltinFunctions(sqlite *db){
10250bce8354Sdrh   static struct {
10260bce8354Sdrh      char *zName;
1027268380caSdrh      signed char nArg;
1028268380caSdrh      u8 argType;           /* 0: none.  1: db  2: (-1) */
1029d02eb1fdSdanielk1977      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
1030dc1bdc4fSdanielk1977      u8 needCollSeq;
10310ae8b831Sdanielk1977      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
10320bce8354Sdrh   } aFuncs[] = {
1033d8123366Sdanielk1977     { "min",               -1, 0, SQLITE_UTF8,    1, minmaxFunc },
1034d8123366Sdanielk1977     { "min",                0, 0, SQLITE_UTF8,    1, 0          },
1035d8123366Sdanielk1977     { "max",               -1, 2, SQLITE_UTF8,    1, minmaxFunc },
1036d8123366Sdanielk1977     { "max",                0, 2, SQLITE_UTF8,    1, 0          },
1037d8123366Sdanielk1977     { "typeof",             1, 0, SQLITE_UTF8,    0, typeofFunc },
1038d8123366Sdanielk1977     { "length",             1, 0, SQLITE_UTF8,    0, lengthFunc },
1039d8123366Sdanielk1977     { "substr",             3, 0, SQLITE_UTF8,    0, substrFunc },
1040f4618891Sdanielk1977     { "substr",             3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
1041d8123366Sdanielk1977     { "abs",                1, 0, SQLITE_UTF8,    0, absFunc    },
1042d8123366Sdanielk1977     { "round",              1, 0, SQLITE_UTF8,    0, roundFunc  },
1043d8123366Sdanielk1977     { "round",              2, 0, SQLITE_UTF8,    0, roundFunc  },
1044d8123366Sdanielk1977     { "upper",              1, 0, SQLITE_UTF8,    0, upperFunc  },
1045d8123366Sdanielk1977     { "lower",              1, 0, SQLITE_UTF8,    0, lowerFunc  },
1046d8123366Sdanielk1977     { "coalesce",          -1, 0, SQLITE_UTF8,    0, ifnullFunc },
1047d8123366Sdanielk1977     { "coalesce",           0, 0, SQLITE_UTF8,    0, 0          },
1048d8123366Sdanielk1977     { "coalesce",           1, 0, SQLITE_UTF8,    0, 0          },
1049d8123366Sdanielk1977     { "ifnull",             2, 0, SQLITE_UTF8,    1, ifnullFunc },
1050d8123366Sdanielk1977     { "random",            -1, 0, SQLITE_UTF8,    0, randomFunc },
1051d8123366Sdanielk1977     { "like",               2, 0, SQLITE_UTF8,    0, likeFunc   },
1052d8123366Sdanielk1977     { "glob",               2, 0, SQLITE_UTF8,    0, globFunc   },
1053d8123366Sdanielk1977     { "nullif",             2, 0, SQLITE_UTF8,    0, nullifFunc },
1054d8123366Sdanielk1977     { "sqlite_version",     0, 0, SQLITE_UTF8,    0, versionFunc},
1055d8123366Sdanielk1977     { "quote",              1, 0, SQLITE_UTF8,    0, quoteFunc  },
1056d8123366Sdanielk1977     { "last_insert_rowid",  0, 1, SQLITE_UTF8,    0, last_insert_rowid },
1057b28af71aSdanielk1977     { "changes",            0, 1, SQLITE_UTF8,    0, changes    },
1058b28af71aSdanielk1977     { "total_changes",      0, 1, SQLITE_UTF8,    0, total_changes },
1059d24cc427Sdrh #ifdef SQLITE_SOUNDEX
1060d8123366Sdanielk1977     { "soundex",            1, 0, SQLITE_UTF8, 0, soundexFunc},
1061d24cc427Sdrh #endif
1062193a6b41Sdrh #ifdef SQLITE_TEST
1063d8123366Sdanielk1977     { "randstr",               2, 0, SQLITE_UTF8, 0, randStr    },
1064f4618891Sdanielk1977     { "test_destructor",       1, 1, SQLITE_UTF8, 0, test_destructor},
1065d8123366Sdanielk1977     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
10663f6b0874Sdanielk1977     { "test_auxdata",         -1, 0, SQLITE_UTF8, 0, test_auxdata},
1067193a6b41Sdrh #endif
10680bce8354Sdrh   };
10690bce8354Sdrh   static struct {
10700bce8354Sdrh     char *zName;
1071268380caSdrh     signed char nArg;
1072268380caSdrh     u8 argType;
1073dc1bdc4fSdanielk1977     u8 needCollSeq;
10740ae8b831Sdanielk1977     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
10750ae8b831Sdanielk1977     void (*xFinalize)(sqlite3_context*);
10760bce8354Sdrh   } aAggs[] = {
1077dc1bdc4fSdanielk1977     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
1078dc1bdc4fSdanielk1977     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
1079dc1bdc4fSdanielk1977     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
1080dc1bdc4fSdanielk1977     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
1081dc1bdc4fSdanielk1977     { "count",  0, 0, 0, countStep,    countFinalize  },
1082dc1bdc4fSdanielk1977     { "count",  1, 0, 0, countStep,    countFinalize  },
1083ef2daf54Sdrh #if 0
1084f9b596ebSdrh     { "stddev", 1, 0, stdDevStep,   stdDevFinalize },
1085ef2daf54Sdrh #endif
10860bce8354Sdrh   };
10870bce8354Sdrh   int i;
10880bce8354Sdrh 
10890bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1090c572ef7fSdanielk1977     void *pArg = 0;
1091c572ef7fSdanielk1977     switch( aFuncs[i].argType ){
1092c572ef7fSdanielk1977       case 1: pArg = db; break;
1093c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1094c572ef7fSdanielk1977     }
1095ad7dd425Sdanielk1977     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
1096f9d64d2cSdanielk1977         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1097dc1bdc4fSdanielk1977     if( aFuncs[i].needCollSeq ){
1098dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1099dc1bdc4fSdanielk1977           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1100dc1bdc4fSdanielk1977       if( pFunc && aFuncs[i].needCollSeq ){
1101dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1102dc1bdc4fSdanielk1977       }
1103dc1bdc4fSdanielk1977     }
11040bce8354Sdrh   }
11050bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1106c572ef7fSdanielk1977     void *pArg = 0;
1107c572ef7fSdanielk1977     switch( aAggs[i].argType ){
1108c572ef7fSdanielk1977       case 1: pArg = db; break;
1109c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1110c572ef7fSdanielk1977     }
1111d8123366Sdanielk1977     sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1112f9d64d2cSdanielk1977         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1113dc1bdc4fSdanielk1977     if( aAggs[i].needCollSeq ){
1114dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1115d8123366Sdanielk1977           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1116dc1bdc4fSdanielk1977       if( pFunc && aAggs[i].needCollSeq ){
1117dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1118dc1bdc4fSdanielk1977       }
1119dc1bdc4fSdanielk1977     }
1120268380caSdrh   }
11214adee20fSdanielk1977   sqlite3RegisterDateTimeFunctions(db);
1122dc04c583Sdrh }
1123