xref: /sqlite-3.40.0/src/func.c (revision f9d64d2c)
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*f9d64d2cSdanielk1977 ** $Id: func.c,v 1.72 2004/06/19 08:18:09 danielk1977 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){
204dc04c583Sdrh   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){
217dc04c583Sdrh   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 /*
276f146a776Srdc ** Implementation of the change_count() SQL function.  The return
27724b03fd0Sdanielk1977 ** value is the same as the sqlite3_changes() API function.
278f146a776Srdc */
279f9b596ebSdrh static void change_count(
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 /*
289f146a776Srdc ** Implementation of the last_statement_change_count() SQL function.  The
29051ad0ecdSdanielk1977 ** return value is the same as the sqlite3_last_statement_changes() API
29151ad0ecdSdanielk1977 ** function.
292f146a776Srdc */
29351ad0ecdSdanielk1977 static void last_statement_change_count(
2940ae8b831Sdanielk1977   sqlite3_context *context,
29551ad0ecdSdanielk1977   int arg,
29651ad0ecdSdanielk1977   sqlite3_value **argv
29751ad0ecdSdanielk1977 ){
29824b03fd0Sdanielk1977   sqlite *db = sqlite3_user_data(context);
299f4479501Sdrh   sqlite3_result_int(context, sqlite3_last_statement_changes(db));
300b0c374ffSrdc }
301b0c374ffSrdc 
3026ed41ad7Sdrh /*
303d02eb1fdSdanielk1977 ** A LIKE pattern compiles to an instance of the following structure. Refer
304d02eb1fdSdanielk1977 ** to the comment for compileLike() function for details.
305d02eb1fdSdanielk1977 */
306d02eb1fdSdanielk1977 struct LikePattern {
307d02eb1fdSdanielk1977   int nState;
308d02eb1fdSdanielk1977   struct LikeState {
309d02eb1fdSdanielk1977     int val;           /* Unicode codepoint or -1 for any char i.e. '_' */
310d02eb1fdSdanielk1977     int failstate;     /* State to jump to if next char is not val */
311d02eb1fdSdanielk1977   } aState[0];
312d02eb1fdSdanielk1977 };
313d02eb1fdSdanielk1977 typedef struct LikePattern LikePattern;
314d02eb1fdSdanielk1977 
315d02eb1fdSdanielk1977 void deleteLike(void *pLike){
316d02eb1fdSdanielk1977   sqliteFree(pLike);
317d02eb1fdSdanielk1977 }
318d02eb1fdSdanielk1977 
319d02eb1fdSdanielk1977 
3203f6b0874Sdanielk1977 #if 0
321d02eb1fdSdanielk1977 /* #define TRACE_LIKE */
322d02eb1fdSdanielk1977 #if defined(TRACE_LIKE) && !defined(NDEBUG)
323d02eb1fdSdanielk1977 char *dumpLike(LikePattern *pLike){
324d02eb1fdSdanielk1977   int i;
325d02eb1fdSdanielk1977   int k = 0;
326d02eb1fdSdanielk1977   char *zBuf = (char *)sqliteMalloc(pLike->nState*40);
327d02eb1fdSdanielk1977 
328d02eb1fdSdanielk1977   k += sprintf(&zBuf[k], "%d states - ", pLike->nState);
329d02eb1fdSdanielk1977   for(i=0; i<pLike->nState; i++){
330d02eb1fdSdanielk1977     k += sprintf(&zBuf[k], " %d:(%d, %d)", i, pLike->aState[i].val,
331d02eb1fdSdanielk1977         pLike->aState[i].failstate);
332d02eb1fdSdanielk1977   }
333d02eb1fdSdanielk1977   return zBuf;
334d02eb1fdSdanielk1977 }
335d02eb1fdSdanielk1977 #endif
336d02eb1fdSdanielk1977 
337d02eb1fdSdanielk1977 /*
338d02eb1fdSdanielk1977 ** This function compiles an SQL 'LIKE' pattern into a state machine,
339d02eb1fdSdanielk1977 ** represented by a LikePattern structure.
340d02eb1fdSdanielk1977 **
341d02eb1fdSdanielk1977 ** Each state of the state-machine has two attributes, 'val' and
342d02eb1fdSdanielk1977 ** 'failstate'. The val attribute is either the value of a unicode
343d02eb1fdSdanielk1977 ** codepoint, or -1, indicating a '_' wildcard (match any single
344d02eb1fdSdanielk1977 ** character). The failstate is either the number of another state
345d02eb1fdSdanielk1977 ** or -1, indicating jump to 'no match'.
346d02eb1fdSdanielk1977 **
347d02eb1fdSdanielk1977 ** To see if a string matches a pattern the pattern is
348d02eb1fdSdanielk1977 ** compiled to a state machine that is executed according to the algorithm
349d02eb1fdSdanielk1977 ** below. The string is assumed to be terminated by a 'NUL' character
350d02eb1fdSdanielk1977 ** (unicode codepoint 0).
351d02eb1fdSdanielk1977 **
352d02eb1fdSdanielk1977 ** 1   S = 0
353d02eb1fdSdanielk1977 ** 2   DO
354d02eb1fdSdanielk1977 ** 3       C = <Next character from input string>
355d02eb1fdSdanielk1977 ** 4       IF( C matches <State S val> )
356d02eb1fdSdanielk1977 ** 5           S = S+1
357d02eb1fdSdanielk1977 ** 6       ELSE IF( S != <State S failstate> )
358d02eb1fdSdanielk1977 ** 7           S = <State S failstate>
359d02eb1fdSdanielk1977 ** 8           <Rewind Input string 1 character>
360d02eb1fdSdanielk1977 ** 9   WHILE( (C != NUL) AND (S != FAILED) )
361d02eb1fdSdanielk1977 ** 10
362d02eb1fdSdanielk1977 ** 11  IF( S == <number of states> )
363d02eb1fdSdanielk1977 ** 12      RETURN MATCH
364d02eb1fdSdanielk1977 ** 13  ELSE
365d02eb1fdSdanielk1977 ** 14      RETURN NO-MATCH
366d02eb1fdSdanielk1977 **
367d02eb1fdSdanielk1977 ** In practice there is a small optimization to avoid the <Rewind>
368d02eb1fdSdanielk1977 ** operation in line 8 of the description above.
369d02eb1fdSdanielk1977 **
370d02eb1fdSdanielk1977 ** For example, the following pattern, 'X%ABabc%_Y' is compiled to
371d02eb1fdSdanielk1977 ** the state machine below.
372d02eb1fdSdanielk1977 **
373d02eb1fdSdanielk1977 ** State    Val          FailState
374d02eb1fdSdanielk1977 ** -------------------------------
375d02eb1fdSdanielk1977 ** 0        120 (x)      -1 (NO MATCH)
376d02eb1fdSdanielk1977 ** 1        97  (a)      1
377d02eb1fdSdanielk1977 ** 2        98  (b)      1
378d02eb1fdSdanielk1977 ** 3        97  (a)      1
379d02eb1fdSdanielk1977 ** 4        98  (b)      2
380d02eb1fdSdanielk1977 ** 5        99  (c)      3
381d02eb1fdSdanielk1977 ** 6        -1  (_)      6
382d02eb1fdSdanielk1977 ** 7        121 (y)      7
383d02eb1fdSdanielk1977 ** 8        0   (NUL)    7
384d02eb1fdSdanielk1977 **
385d02eb1fdSdanielk1977 ** The algorithms implemented to compile and execute the state machine were
386d02eb1fdSdanielk1977 ** first presented in "Fast pattern matching in strings", Knuth, Morris and
387d02eb1fdSdanielk1977 ** Pratt, 1977.
388d02eb1fdSdanielk1977 **
389d02eb1fdSdanielk1977 */
390d02eb1fdSdanielk1977 LikePattern *compileLike(sqlite3_value *pPattern, u8 enc){
391d02eb1fdSdanielk1977   LikePattern *pLike;
392d02eb1fdSdanielk1977   struct LikeState *aState;
393d02eb1fdSdanielk1977   int pc_state = -1;    /* State number of previous '%' wild card */
394d02eb1fdSdanielk1977   int n = 0;
395d02eb1fdSdanielk1977   int c;
396d02eb1fdSdanielk1977 
397d02eb1fdSdanielk1977   int offset = 0;
398d02eb1fdSdanielk1977   const char *zLike;
399d02eb1fdSdanielk1977 
400dc8453fdSdanielk1977   if( enc==SQLITE_UTF8 ){
401d02eb1fdSdanielk1977     zLike = sqlite3_value_text(pPattern);
402d02eb1fdSdanielk1977     n = sqlite3_value_bytes(pPattern) + 1;
403d02eb1fdSdanielk1977   }else{
404d02eb1fdSdanielk1977     zLike = sqlite3_value_text16(pPattern);
405d02eb1fdSdanielk1977     n = sqlite3_value_bytes16(pPattern)/2 + 1;
406d02eb1fdSdanielk1977   }
407d02eb1fdSdanielk1977 
408d02eb1fdSdanielk1977   pLike = (LikePattern *)
409d02eb1fdSdanielk1977       sqliteMalloc(sizeof(LikePattern)+n*sizeof(struct LikeState));
410d02eb1fdSdanielk1977   aState = pLike->aState;
411d02eb1fdSdanielk1977 
412d02eb1fdSdanielk1977   n = 0;
413d02eb1fdSdanielk1977   do {
414d02eb1fdSdanielk1977     c = sqlite3ReadUniChar(zLike, &offset, &enc, 1);
415d02eb1fdSdanielk1977     if( c==95 ){        /* A '_' wildcard */
416d02eb1fdSdanielk1977       aState[n].val = -1;
417d02eb1fdSdanielk1977       n++;
418d02eb1fdSdanielk1977     }else if( c==37 ){  /* A '%' wildcard */
419d02eb1fdSdanielk1977       aState[n].failstate = n;
420d02eb1fdSdanielk1977       pc_state = n;
421d02eb1fdSdanielk1977     }else{              /* A regular character */
422d02eb1fdSdanielk1977       aState[n].val = c;
423d02eb1fdSdanielk1977 
424d02eb1fdSdanielk1977       assert( pc_state<=n );
425d02eb1fdSdanielk1977       if( pc_state<0 ){
426d02eb1fdSdanielk1977         aState[n].failstate = -1;
427d02eb1fdSdanielk1977       }else if( pc_state==n ){
428ad7dd425Sdanielk1977         if( c ){
429d02eb1fdSdanielk1977           aState[n].failstate = pc_state;
430d02eb1fdSdanielk1977         }else{
431ad7dd425Sdanielk1977           aState[n].failstate = -2;
432ad7dd425Sdanielk1977         }
433ad7dd425Sdanielk1977       }else{
434d02eb1fdSdanielk1977         int k = pLike->aState[n-1].failstate;
435d02eb1fdSdanielk1977         while( k>pc_state && aState[k+1].val!=-1 && aState[k+1].val!=c ){
436d02eb1fdSdanielk1977           k = aState[k].failstate;
437d02eb1fdSdanielk1977         }
438d02eb1fdSdanielk1977         if( k!=pc_state && aState[k+1].val==c ){
439d02eb1fdSdanielk1977           assert( k==pc_state );
440d02eb1fdSdanielk1977           k++;
441d02eb1fdSdanielk1977         }
442d02eb1fdSdanielk1977         aState[n].failstate = k;
443d02eb1fdSdanielk1977       }
444d02eb1fdSdanielk1977       n++;
445d02eb1fdSdanielk1977     }
446d02eb1fdSdanielk1977   }while( c );
447d02eb1fdSdanielk1977   pLike->nState = n;
448d02eb1fdSdanielk1977 #if defined(TRACE_LIKE) && !defined(NDEBUG)
449d02eb1fdSdanielk1977   {
450d02eb1fdSdanielk1977     char *zCompiled = dumpLike(pLike);
451d02eb1fdSdanielk1977     printf("Pattern=\"%s\" Compiled=\"%s\"\n", zPattern, zCompiled);
452d02eb1fdSdanielk1977     sqliteFree(zCompiled);
453d02eb1fdSdanielk1977   }
454d02eb1fdSdanielk1977 #endif
455d02eb1fdSdanielk1977   return pLike;
456d02eb1fdSdanielk1977 }
457d02eb1fdSdanielk1977 
458d02eb1fdSdanielk1977 /*
4590ac65892Sdrh ** Implementation of the like() SQL function.  This function implements
4600ac65892Sdrh ** the build-in LIKE operator.  The first argument to the function is the
461d02eb1fdSdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
4620ac65892Sdrh **
4630ac65892Sdrh **       A LIKE B
4640ac65892Sdrh **
465d02eb1fdSdanielk1977 ** is implemented as like(B,A).
466d02eb1fdSdanielk1977 **
467d02eb1fdSdanielk1977 ** If the pointer retrieved by via a call to sqlite3_user_data() is
468d02eb1fdSdanielk1977 ** not NULL, then this function uses UTF-16. Otherwise UTF-8.
4690ac65892Sdrh */
47051ad0ecdSdanielk1977 static void likeFunc(
4710ae8b831Sdanielk1977   sqlite3_context *context,
47251ad0ecdSdanielk1977   int argc,
47351ad0ecdSdanielk1977   sqlite3_value **argv
47451ad0ecdSdanielk1977 ){
475ad7dd425Sdanielk1977   register int c;
476d02eb1fdSdanielk1977   u8 enc;
477d02eb1fdSdanielk1977   int offset = 0;
478d02eb1fdSdanielk1977   const unsigned char *zString;
479d02eb1fdSdanielk1977   LikePattern *pLike = sqlite3_get_auxdata(context, 0);
480ad7dd425Sdanielk1977   struct LikeState *aState;
481ad7dd425Sdanielk1977   register struct LikeState *pState;
482d02eb1fdSdanielk1977 
483d02eb1fdSdanielk1977   /* If either argument is NULL, the result is NULL */
484d02eb1fdSdanielk1977   if( sqlite3_value_type(argv[1])==SQLITE_NULL ||
485d02eb1fdSdanielk1977       sqlite3_value_type(argv[0])==SQLITE_NULL ){
486d02eb1fdSdanielk1977     return;
487d02eb1fdSdanielk1977   }
488d02eb1fdSdanielk1977 
489d02eb1fdSdanielk1977   /* If the user-data pointer is NULL, use UTF-8. Otherwise UTF-16. */
490d02eb1fdSdanielk1977   if( sqlite3_user_data(context) ){
491dc8453fdSdanielk1977     enc = SQLITE_UTF16NATIVE;
492d02eb1fdSdanielk1977     zString = (const unsigned char *)sqlite3_value_text16(argv[1]);
493ad7dd425Sdanielk1977     assert(0);
494d02eb1fdSdanielk1977   }else{
495dc8453fdSdanielk1977     enc = SQLITE_UTF8;
496d02eb1fdSdanielk1977     zString = sqlite3_value_text(argv[1]);
497d02eb1fdSdanielk1977   }
498d02eb1fdSdanielk1977 
499d02eb1fdSdanielk1977   /* If the LIKE pattern has not been compiled, compile it now. */
500d02eb1fdSdanielk1977   if( !pLike ){
501d02eb1fdSdanielk1977     pLike = compileLike(argv[0], enc);
502d02eb1fdSdanielk1977     if( !pLike ){
503d02eb1fdSdanielk1977       sqlite3_result_error(context, "out of memory", -1);
504d02eb1fdSdanielk1977       return;
505d02eb1fdSdanielk1977     }
506d02eb1fdSdanielk1977     sqlite3_set_auxdata(context, 0, pLike, deleteLike);
507d02eb1fdSdanielk1977   }
508ad7dd425Sdanielk1977   aState = pLike->aState;
509ad7dd425Sdanielk1977   pState = aState;
510d02eb1fdSdanielk1977 
511d02eb1fdSdanielk1977   do {
512dc8453fdSdanielk1977     if( enc==SQLITE_UTF8 ){
513ad7dd425Sdanielk1977       c = zString[offset++];
514ad7dd425Sdanielk1977       if( c&0x80 ){
515ad7dd425Sdanielk1977         offset--;
516ad7dd425Sdanielk1977         c = sqlite3ReadUniChar(zString, &offset, &enc, 1);
517ad7dd425Sdanielk1977       }
518ad7dd425Sdanielk1977     }else{
519ad7dd425Sdanielk1977       c = sqlite3ReadUniChar(zString, &offset, &enc, 1);
520ad7dd425Sdanielk1977     }
521ad7dd425Sdanielk1977 
522ad7dd425Sdanielk1977 skip_read:
523d02eb1fdSdanielk1977 
524d02eb1fdSdanielk1977 #if defined(TRACE_LIKE) && !defined(NDEBUG)
525d02eb1fdSdanielk1977     printf("State=%d:(%d, %d) Input=%d\n",
526ad7dd425Sdanielk1977         (aState - pState), pState->val, pState->failstate, c);
527d02eb1fdSdanielk1977 #endif
528d02eb1fdSdanielk1977 
529ad7dd425Sdanielk1977     if( pState->val==-1 || pState->val==c ){
530ad7dd425Sdanielk1977       pState++;
531d02eb1fdSdanielk1977     }else{
532ad7dd425Sdanielk1977       struct LikeState *pFailState = &aState[pState->failstate];
533ad7dd425Sdanielk1977       if( pState!=pFailState ){
534ad7dd425Sdanielk1977         pState = pFailState;
535ad7dd425Sdanielk1977         if( c && pState>=aState ) goto skip_read;
536d02eb1fdSdanielk1977       }
537d02eb1fdSdanielk1977     }
538ad7dd425Sdanielk1977   }while( c && pState>=aState );
539d02eb1fdSdanielk1977 
540ad7dd425Sdanielk1977   if( (pState-aState)==pLike->nState || (pState-aState)<-1 ){
541d02eb1fdSdanielk1977     sqlite3_result_int(context, 1);
542d02eb1fdSdanielk1977   }else{
543d02eb1fdSdanielk1977     sqlite3_result_int(context, 0);
54451ad0ecdSdanielk1977   }
5450ac65892Sdrh }
5463f6b0874Sdanielk1977 #endif
5473f6b0874Sdanielk1977 
5483f6b0874Sdanielk1977 /*
5493f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
5503f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
5513f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
5523f6b0874Sdanielk1977 **
5533f6b0874Sdanielk1977 **       A LIKE B
5543f6b0874Sdanielk1977 **
5553f6b0874Sdanielk1977 ** is implemented as like(B,A).
5563f6b0874Sdanielk1977 **
5573f6b0874Sdanielk1977 ** If the pointer retrieved by via a call to sqlite3_user_data() is
5583f6b0874Sdanielk1977 ** not NULL, then this function uses UTF-16. Otherwise UTF-8.
5593f6b0874Sdanielk1977 */
5603f6b0874Sdanielk1977 static void likeFunc(
5613f6b0874Sdanielk1977   sqlite3_context *context,
5623f6b0874Sdanielk1977   int argc,
5633f6b0874Sdanielk1977   sqlite3_value **argv
5643f6b0874Sdanielk1977 ){
5653f6b0874Sdanielk1977   const unsigned char *zA = sqlite3_value_text(argv[0]);
5663f6b0874Sdanielk1977   const unsigned char *zB = sqlite3_value_text(argv[1]);
5673f6b0874Sdanielk1977   if( zA && zB ){
5683f6b0874Sdanielk1977     sqlite3_result_int(context, sqlite3utf8LikeCompare(zA, zB));
5693f6b0874Sdanielk1977   }
5703f6b0874Sdanielk1977 }
5710ac65892Sdrh 
5720ac65892Sdrh /*
5730ac65892Sdrh ** Implementation of the glob() SQL function.  This function implements
5740ac65892Sdrh ** the build-in GLOB operator.  The first argument to the function is the
5750ac65892Sdrh ** string and the second argument is the pattern.  So, the SQL statements:
5760ac65892Sdrh **
5770ac65892Sdrh **       A GLOB B
5780ac65892Sdrh **
5790ac65892Sdrh ** is implemented as glob(A,B).
5800ac65892Sdrh */
5810ae8b831Sdanielk1977 static void globFunc(sqlite3_context *context, int arg, sqlite3_value **argv){
5824f26d6c4Sdrh   const unsigned char *zA = sqlite3_value_text(argv[0]);
5834f26d6c4Sdrh   const unsigned char *zB = sqlite3_value_text(argv[1]);
58451ad0ecdSdanielk1977   if( zA && zB ){
585f4479501Sdrh     sqlite3_result_int(context, sqlite3GlobCompare(zA, zB));
58651ad0ecdSdanielk1977   }
5878912d106Sdrh }
5888912d106Sdrh 
5898912d106Sdrh /*
5908912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
5918912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
5928912d106Sdrh ** arguments are equal to each other.
5938912d106Sdrh */
594f9b596ebSdrh static void nullifFunc(
595f9b596ebSdrh   sqlite3_context *context,
596f9b596ebSdrh   int argc,
597f9b596ebSdrh   sqlite3_value **argv
598f9b596ebSdrh ){
599dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
600dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
601f4479501Sdrh     sqlite3_result_value(context, argv[0]);
6028912d106Sdrh   }
6030ac65892Sdrh }
6040ac65892Sdrh 
605647cb0e1Sdrh /*
606647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
607647cb0e1Sdrh ** of the SQLite library that is running.
608647cb0e1Sdrh */
609f9b596ebSdrh static void versionFunc(
610f9b596ebSdrh   sqlite3_context *context,
611f9b596ebSdrh   int argc,
612f9b596ebSdrh   sqlite3_value **argv
613f9b596ebSdrh ){
614d8123366Sdanielk1977   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
615647cb0e1Sdrh }
616647cb0e1Sdrh 
61747394703Sdrh /*
61847394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
61947394703Sdrh ** change.  This function may disappear.  Do not write code that depends
62047394703Sdrh ** on this function.
62147394703Sdrh **
62247394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
62347394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
62447394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
62547394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
62647394703Sdrh ** single-quote escapes.
62747394703Sdrh */
6280ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62947394703Sdrh   if( argc<1 ) return;
630f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
6319c054830Sdrh     case SQLITE_NULL: {
632d8123366Sdanielk1977       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
633f9b596ebSdrh       break;
634f9b596ebSdrh     }
6359c054830Sdrh     case SQLITE_INTEGER:
6369c054830Sdrh     case SQLITE_FLOAT: {
637f4479501Sdrh       sqlite3_result_value(context, argv[0]);
638f9b596ebSdrh       break;
639f9b596ebSdrh     }
6403f41e976Sdanielk1977     case SQLITE_BLOB: {
6413f41e976Sdanielk1977       static const char hexdigits[] = {
6423f41e976Sdanielk1977         '0', '1', '2', '3', '4', '5', '6', '7',
6433f41e976Sdanielk1977         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
6443f41e976Sdanielk1977       };
6453f41e976Sdanielk1977       char *zText = 0;
6463f41e976Sdanielk1977       int nBlob = sqlite3_value_bytes(argv[0]);
6473f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
6483f41e976Sdanielk1977 
6493f41e976Sdanielk1977       zText = (char *)sqliteMalloc((2*nBlob)+4);
6503f41e976Sdanielk1977       if( !zText ){
6513f41e976Sdanielk1977         sqlite3_result_error(context, "out of memory", -1);
6523f41e976Sdanielk1977       }else{
6533f41e976Sdanielk1977         int i;
6543f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
6553f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
6563f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
6573f41e976Sdanielk1977         }
6583f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
6593f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
6603f41e976Sdanielk1977         zText[0] = 'X';
6613f41e976Sdanielk1977         zText[1] = '\'';
662d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
6633f41e976Sdanielk1977         sqliteFree(zText);
6643f41e976Sdanielk1977       }
6653f41e976Sdanielk1977       break;
6663f41e976Sdanielk1977     }
6679c054830Sdrh     case SQLITE_TEXT: {
66847394703Sdrh       int i,j,n;
6694f26d6c4Sdrh       const char *zArg = sqlite3_value_text(argv[0]);
67047394703Sdrh       char *z;
671f9b596ebSdrh 
67251ad0ecdSdanielk1977       for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
67347394703Sdrh       z = sqliteMalloc( i+n+3 );
67447394703Sdrh       if( z==0 ) return;
67547394703Sdrh       z[0] = '\'';
67651ad0ecdSdanielk1977       for(i=0, j=1; zArg[i]; i++){
67751ad0ecdSdanielk1977         z[j++] = zArg[i];
67851ad0ecdSdanielk1977         if( zArg[i]=='\'' ){
67947394703Sdrh           z[j++] = '\'';
68047394703Sdrh         }
68147394703Sdrh       }
68247394703Sdrh       z[j++] = '\'';
68347394703Sdrh       z[j] = 0;
684d8123366Sdanielk1977       sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
68547394703Sdrh       sqliteFree(z);
68647394703Sdrh     }
68747394703Sdrh   }
688f9b596ebSdrh }
68947394703Sdrh 
690d24cc427Sdrh #ifdef SQLITE_SOUNDEX
691d24cc427Sdrh /*
692d24cc427Sdrh ** Compute the soundex encoding of a word.
693d24cc427Sdrh */
6940ae8b831Sdanielk1977 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
695d24cc427Sdrh   char zResult[8];
696d24cc427Sdrh   const char *zIn;
697d24cc427Sdrh   int i, j;
698d24cc427Sdrh   static const unsigned char iCode[] = {
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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
702d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
706d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
707d24cc427Sdrh   };
708d24cc427Sdrh   assert( argc==1 );
7094f26d6c4Sdrh   zIn = sqlite3_value_text(argv[0]);
710d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
711d24cc427Sdrh   if( zIn[i] ){
712d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
713d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
714d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
715d24cc427Sdrh       if( code>0 ){
716d24cc427Sdrh         zResult[j++] = code + '0';
717d24cc427Sdrh       }
718d24cc427Sdrh     }
719d24cc427Sdrh     while( j<4 ){
720d24cc427Sdrh       zResult[j++] = '0';
721d24cc427Sdrh     }
722d24cc427Sdrh     zResult[j] = 0;
723d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
724d24cc427Sdrh   }else{
725d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
726d24cc427Sdrh   }
727d24cc427Sdrh }
728d24cc427Sdrh #endif
729d24cc427Sdrh 
730193a6b41Sdrh #ifdef SQLITE_TEST
731193a6b41Sdrh /*
732193a6b41Sdrh ** This function generates a string of random characters.  Used for
733193a6b41Sdrh ** generating test data.
734193a6b41Sdrh */
7350ae8b831Sdanielk1977 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
736bbd82df6Sdrh   static const unsigned char zSrc[] =
737193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
738193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
739193a6b41Sdrh      "0123456789"
740193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
741193a6b41Sdrh   int iMin, iMax, n, r, i;
742bbd82df6Sdrh   unsigned char zBuf[1000];
743193a6b41Sdrh   if( argc>=1 ){
744f9b596ebSdrh     iMin = sqlite3_value_int(argv[0]);
745193a6b41Sdrh     if( iMin<0 ) iMin = 0;
746193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
747193a6b41Sdrh   }else{
748193a6b41Sdrh     iMin = 1;
749193a6b41Sdrh   }
750193a6b41Sdrh   if( argc>=2 ){
751f9b596ebSdrh     iMax = sqlite3_value_int(argv[1]);
752193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
7531dba7279Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
754193a6b41Sdrh   }else{
755193a6b41Sdrh     iMax = 50;
756193a6b41Sdrh   }
757193a6b41Sdrh   n = iMin;
758193a6b41Sdrh   if( iMax>iMin ){
7594adee20fSdanielk1977     sqlite3Randomness(sizeof(r), &r);
760bbd82df6Sdrh     r &= 0x7fffffff;
761193a6b41Sdrh     n += r%(iMax + 1 - iMin);
762193a6b41Sdrh   }
7631dba7279Sdrh   assert( n<sizeof(zBuf) );
7644adee20fSdanielk1977   sqlite3Randomness(n, zBuf);
765193a6b41Sdrh   for(i=0; i<n; i++){
766bbd82df6Sdrh     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
767193a6b41Sdrh   }
768193a6b41Sdrh   zBuf[n] = 0;
769d8123366Sdanielk1977   sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
770d8123366Sdanielk1977 }
771d8123366Sdanielk1977 
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;
797d8123366Sdanielk1977   test_destructor_count_var++;
798d8123366Sdanielk1977   assert( nArg==1 );
799d8123366Sdanielk1977   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
800d8123366Sdanielk1977   zVal = sqliteMalloc(sqlite3_value_bytes(argv[0]) + 2);
801d8123366Sdanielk1977   assert( zVal );
802d8123366Sdanielk1977   zVal++;
803d8123366Sdanielk1977   strcpy(zVal, sqlite3_value_text(argv[0]));
804d8123366Sdanielk1977   sqlite3_result_text(pCtx, zVal, -1, destructor);
805d8123366Sdanielk1977 }
806d8123366Sdanielk1977 static void test_destructor_count(
807d8123366Sdanielk1977   sqlite3_context *pCtx,
808d8123366Sdanielk1977   int nArg,
809d8123366Sdanielk1977   sqlite3_value **argv
810d8123366Sdanielk1977 ){
811d8123366Sdanielk1977   sqlite3_result_int(pCtx, test_destructor_count_var);
812193a6b41Sdrh }
8133f6b0874Sdanielk1977 
8143f6b0874Sdanielk1977 static void free_test_auxdata(void *p) {sqliteFree(p);}
8153f6b0874Sdanielk1977 static void test_auxdata(
8163f6b0874Sdanielk1977   sqlite3_context *pCtx,
8173f6b0874Sdanielk1977   int nArg,
8183f6b0874Sdanielk1977   sqlite3_value **argv
8193f6b0874Sdanielk1977 ){
8203f6b0874Sdanielk1977   int i;
8213f6b0874Sdanielk1977   char *zRet = sqliteMalloc(nArg*2);
8223f6b0874Sdanielk1977   if( !zRet ) return;
8233f6b0874Sdanielk1977   for(i=0; i<nArg; i++){
8243f6b0874Sdanielk1977     char const *z = sqlite3_value_text(argv[i]);
8253f6b0874Sdanielk1977     if( z ){
8263f6b0874Sdanielk1977       char *zAux = sqlite3_get_auxdata(pCtx, i);
8273f6b0874Sdanielk1977       if( zAux ){
8283f6b0874Sdanielk1977         zRet[i*2] = '1';
8293f6b0874Sdanielk1977         if( strcmp(zAux, z) ){
8303f6b0874Sdanielk1977           sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
8313f6b0874Sdanielk1977           return;
8323f6b0874Sdanielk1977         }
8333f6b0874Sdanielk1977       }else{
8343f6b0874Sdanielk1977         zRet[i*2] = '0';
8353f6b0874Sdanielk1977         zAux = sqliteStrDup(z);
8363f6b0874Sdanielk1977         sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
8373f6b0874Sdanielk1977       }
8383f6b0874Sdanielk1977       zRet[i*2+1] = ' ';
8393f6b0874Sdanielk1977     }
8403f6b0874Sdanielk1977   }
8413f6b0874Sdanielk1977   sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
8423f6b0874Sdanielk1977 }
843193a6b41Sdrh #endif
844193a6b41Sdrh 
8450ac65892Sdrh /*
846d3a149efSdrh ** An instance of the following structure holds the context of a
847dd5baa95Sdrh ** sum() or avg() aggregate computation.
848dd5baa95Sdrh */
849dd5baa95Sdrh typedef struct SumCtx SumCtx;
850dd5baa95Sdrh struct SumCtx {
851dd5baa95Sdrh   double sum;     /* Sum of terms */
852739105c7Sdrh   int cnt;        /* Number of elements summed */
853dd5baa95Sdrh };
854dd5baa95Sdrh 
855dd5baa95Sdrh /*
856dd5baa95Sdrh ** Routines used to compute the sum or average.
857dd5baa95Sdrh */
8580ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
859dd5baa95Sdrh   SumCtx *p;
860dd5baa95Sdrh   if( argc<1 ) return;
8614f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8629c054830Sdrh   if( p && SQLITE_NULL!=sqlite3_value_type(argv[0]) ){
8634f26d6c4Sdrh     p->sum += sqlite3_value_double(argv[0]);
864739105c7Sdrh     p->cnt++;
865739105c7Sdrh   }
866dd5baa95Sdrh }
8670ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
868dd5baa95Sdrh   SumCtx *p;
8694f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
8707e18c259Sdanielk1977   sqlite3_result_double(context, p ? p->sum : 0.0);
871dd5baa95Sdrh }
8720ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
873dd5baa95Sdrh   SumCtx *p;
8744f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
875739105c7Sdrh   if( p && p->cnt>0 ){
8767e18c259Sdanielk1977     sqlite3_result_double(context, p->sum/(double)p->cnt);
877dd5baa95Sdrh   }
878dd5baa95Sdrh }
879dd5baa95Sdrh 
880dd5baa95Sdrh /*
881dd5baa95Sdrh ** An instance of the following structure holds the context of a
882a2ed5601Sdrh ** variance or standard deviation computation.
883d3a149efSdrh */
884d3a149efSdrh typedef struct StdDevCtx StdDevCtx;
885d3a149efSdrh struct StdDevCtx {
886d3a149efSdrh   double sum;     /* Sum of terms */
887d3a149efSdrh   double sum2;    /* Sum of the squares of terms */
888739105c7Sdrh   int cnt;        /* Number of terms counted */
889d3a149efSdrh };
890d3a149efSdrh 
891ef2daf54Sdrh #if 0   /* Omit because math library is required */
892d3a149efSdrh /*
893d3a149efSdrh ** Routines used to compute the standard deviation as an aggregate.
894d3a149efSdrh */
8950ae8b831Sdanielk1977 static void stdDevStep(sqlite3_context *context, int argc, const char **argv){
896d3a149efSdrh   StdDevCtx *p;
897d3a149efSdrh   double x;
8981350b030Sdrh   if( argc<1 ) return;
89924b03fd0Sdanielk1977   p = sqlite3_aggregate_context(context, sizeof(*p));
900739105c7Sdrh   if( p && argv[0] ){
9014adee20fSdanielk1977     x = sqlite3AtoF(argv[0], 0);
902d3a149efSdrh     p->sum += x;
903d3a149efSdrh     p->sum2 += x*x;
904739105c7Sdrh     p->cnt++;
905739105c7Sdrh   }
906d3a149efSdrh }
9070ae8b831Sdanielk1977 static void stdDevFinalize(sqlite3_context *context){
90824b03fd0Sdanielk1977   double rN = sqlite3_aggregate_count(context);
90924b03fd0Sdanielk1977   StdDevCtx *p = sqlite3_aggregate_context(context, sizeof(*p));
910739105c7Sdrh   if( p && p->cnt>1 ){
911739105c7Sdrh     double rCnt = cnt;
91224b03fd0Sdanielk1977     sqlite3_set_result_double(context,
913739105c7Sdrh        sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
914d3a149efSdrh   }
915d3a149efSdrh }
916ef2daf54Sdrh #endif
917d3a149efSdrh 
9180bce8354Sdrh /*
9190bce8354Sdrh ** The following structure keeps track of state information for the
9200bce8354Sdrh ** count() aggregate function.
9210bce8354Sdrh */
9220bce8354Sdrh typedef struct CountCtx CountCtx;
9230bce8354Sdrh struct CountCtx {
9240bce8354Sdrh   int n;
9250bce8354Sdrh };
926dd5baa95Sdrh 
9270bce8354Sdrh /*
9280bce8354Sdrh ** Routines to implement the count() aggregate function.
9290bce8354Sdrh */
9300ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
9310bce8354Sdrh   CountCtx *p;
9324f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
9339c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
9340bce8354Sdrh     p->n++;
9350bce8354Sdrh   }
9360bce8354Sdrh }
9370ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
9380bce8354Sdrh   CountCtx *p;
9394f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
940f4479501Sdrh   sqlite3_result_int(context, p ? p->n : 0);
9410bce8354Sdrh }
9420bce8354Sdrh 
9430bce8354Sdrh /*
9440bce8354Sdrh ** This function tracks state information for the min() and max()
9450bce8354Sdrh ** aggregate functions.
9460bce8354Sdrh */
9470bce8354Sdrh typedef struct MinMaxCtx MinMaxCtx;
9480bce8354Sdrh struct MinMaxCtx {
9490bce8354Sdrh   char *z;         /* The best so far */
9500bce8354Sdrh   char zBuf[28];   /* Space that can be used for storage */
9510bce8354Sdrh };
9520bce8354Sdrh 
9530bce8354Sdrh /*
9540bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
9550bce8354Sdrh */
9560ae8b831Sdanielk1977 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95788208050Sdanielk1977   int max = 0;
95888208050Sdanielk1977   int cmp = 0;
95988208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
9604f26d6c4Sdrh   Mem *pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
961268380caSdrh 
9625c4c7787Sdanielk1977   if( !pBest || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
96388208050Sdanielk1977   if( pBest->flags ){
964dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
9657e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
9667e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
9677e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
9687e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
9697e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
9707e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
9717e18c259Sdanielk1977     ** aggregate, or 0 for min().
9727e18c259Sdanielk1977     */
97388208050Sdanielk1977     max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
974dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
97588208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
9767e18c259Sdanielk1977       sqlite3VdbeMemCopy(pBest, pArg);
97788208050Sdanielk1977     }
9780bce8354Sdrh   }else{
9797e18c259Sdanielk1977     sqlite3VdbeMemCopy(pBest, pArg);
9800bce8354Sdrh   }
9810bce8354Sdrh }
9820ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
98388208050Sdanielk1977   sqlite3_value *pRes;
9844f26d6c4Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, sizeof(Mem));
98588208050Sdanielk1977   if( pRes->flags ){
986f4479501Sdrh     sqlite3_result_value(context, pRes);
9870bce8354Sdrh   }
988b20e56b4Sdanielk1977   sqlite3VdbeMemRelease(pRes);
9890bce8354Sdrh }
990dd5baa95Sdrh 
991d3a149efSdrh /*
992a2ed5601Sdrh ** This function registered all of the above C functions as SQL
993a2ed5601Sdrh ** functions.  This should be the only routine in this file with
994a2ed5601Sdrh ** external linkage.
995dc04c583Sdrh */
9964adee20fSdanielk1977 void sqlite3RegisterBuiltinFunctions(sqlite *db){
9970bce8354Sdrh   static struct {
9980bce8354Sdrh      char *zName;
999268380caSdrh      signed char nArg;
1000268380caSdrh      u8 argType;               /* 0: none.  1: db  2: (-1) */
1001d02eb1fdSdanielk1977      u8 eTextRep;              /* 1: UTF-16.  0: UTF-8 */
1002dc1bdc4fSdanielk1977      u8 needCollSeq;
10030ae8b831Sdanielk1977      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
10040bce8354Sdrh   } aFuncs[] = {
1005d8123366Sdanielk1977     { "min",                        -1, 0, SQLITE_UTF8, 1, minmaxFunc },
1006d8123366Sdanielk1977     { "min",                         0, 0, SQLITE_UTF8, 1, 0          },
1007d8123366Sdanielk1977     { "max",                        -1, 2, SQLITE_UTF8, 1, minmaxFunc },
1008d8123366Sdanielk1977     { "max",                         0, 2, SQLITE_UTF8, 1, 0          },
1009d8123366Sdanielk1977     { "typeof",                      1, 0, SQLITE_UTF8, 0, typeofFunc },
1010d8123366Sdanielk1977     { "length",                      1, 0, SQLITE_UTF8, 0, lengthFunc },
1011d8123366Sdanielk1977     { "substr",                      3, 0, SQLITE_UTF8, 0, substrFunc },
1012d8123366Sdanielk1977     { "abs",                         1, 0, SQLITE_UTF8, 0, absFunc    },
1013d8123366Sdanielk1977     { "round",                       1, 0, SQLITE_UTF8, 0, roundFunc  },
1014d8123366Sdanielk1977     { "round",                       2, 0, SQLITE_UTF8, 0, roundFunc  },
1015d8123366Sdanielk1977     { "upper",                       1, 0, SQLITE_UTF8, 0, upperFunc  },
1016d8123366Sdanielk1977     { "lower",                       1, 0, SQLITE_UTF8, 0, lowerFunc  },
1017d8123366Sdanielk1977     { "coalesce",                   -1, 0, SQLITE_UTF8, 0, ifnullFunc },
1018d8123366Sdanielk1977     { "coalesce",                    0, 0, SQLITE_UTF8, 0, 0          },
1019d8123366Sdanielk1977     { "coalesce",                    1, 0, SQLITE_UTF8, 0, 0          },
1020d8123366Sdanielk1977     { "ifnull",                      2, 0, SQLITE_UTF8, 1, ifnullFunc },
1021d8123366Sdanielk1977     { "random",                     -1, 0, SQLITE_UTF8, 0, randomFunc },
1022d8123366Sdanielk1977     { "like",                        2, 0, SQLITE_UTF8, 0, likeFunc   },
10233f6b0874Sdanielk1977 /* { "like",                        2, 2, SQLITE_UTF16,0, likeFunc   }, */
1024d8123366Sdanielk1977     { "glob",                        2, 0, SQLITE_UTF8, 0, globFunc   },
1025d8123366Sdanielk1977     { "nullif",                      2, 0, SQLITE_UTF8, 0, nullifFunc },
1026d8123366Sdanielk1977     { "sqlite_version",              0, 0, SQLITE_UTF8, 0, versionFunc},
1027d8123366Sdanielk1977     { "quote",                       1, 0, SQLITE_UTF8, 0, quoteFunc  },
1028d8123366Sdanielk1977     { "last_insert_rowid",           0, 1, SQLITE_UTF8, 0, last_insert_rowid },
1029d8123366Sdanielk1977     { "change_count",                0, 1, SQLITE_UTF8, 0, change_count      },
1030d8123366Sdanielk1977     { "last_statement_change_count", 0, 1, SQLITE_UTF8, 0,
1031d8123366Sdanielk1977        last_statement_change_count },
1032d24cc427Sdrh #ifdef SQLITE_SOUNDEX
1033d8123366Sdanielk1977     { "soundex",                     1, 0, SQLITE_UTF8, 0, soundexFunc},
1034d24cc427Sdrh #endif
1035193a6b41Sdrh #ifdef SQLITE_TEST
1036d8123366Sdanielk1977     { "randstr",                     2, 0, SQLITE_UTF8, 0, randStr    },
1037d8123366Sdanielk1977     { "test_destructor",             1, 0, SQLITE_UTF8, 0, test_destructor},
1038d8123366Sdanielk1977     { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
10393f6b0874Sdanielk1977     { "test_auxdata",               -1, 0, SQLITE_UTF8, 0, test_auxdata},
1040193a6b41Sdrh #endif
10410bce8354Sdrh   };
10420bce8354Sdrh   static struct {
10430bce8354Sdrh     char *zName;
1044268380caSdrh     signed char nArg;
1045268380caSdrh     u8 argType;
1046dc1bdc4fSdanielk1977     u8 needCollSeq;
10470ae8b831Sdanielk1977     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
10480ae8b831Sdanielk1977     void (*xFinalize)(sqlite3_context*);
10490bce8354Sdrh   } aAggs[] = {
1050dc1bdc4fSdanielk1977     { "min",    1, 0, 1, minmaxStep,   minMaxFinalize },
1051dc1bdc4fSdanielk1977     { "max",    1, 2, 1, minmaxStep,   minMaxFinalize },
1052dc1bdc4fSdanielk1977     { "sum",    1, 0, 0, sumStep,      sumFinalize    },
1053dc1bdc4fSdanielk1977     { "avg",    1, 0, 0, sumStep,      avgFinalize    },
1054dc1bdc4fSdanielk1977     { "count",  0, 0, 0, countStep,    countFinalize  },
1055dc1bdc4fSdanielk1977     { "count",  1, 0, 0, countStep,    countFinalize  },
1056ef2daf54Sdrh #if 0
1057f9b596ebSdrh     { "stddev", 1, 0, stdDevStep,   stdDevFinalize },
1058ef2daf54Sdrh #endif
10590bce8354Sdrh   };
10600bce8354Sdrh   int i;
10610bce8354Sdrh 
10620bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1063c572ef7fSdanielk1977     void *pArg = 0;
1064c572ef7fSdanielk1977     switch( aFuncs[i].argType ){
1065c572ef7fSdanielk1977       case 1: pArg = db; break;
1066c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1067c572ef7fSdanielk1977     }
1068ad7dd425Sdanielk1977     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
1069*f9d64d2cSdanielk1977         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1070dc1bdc4fSdanielk1977     if( aFuncs[i].needCollSeq ){
1071dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1072dc1bdc4fSdanielk1977           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1073dc1bdc4fSdanielk1977       if( pFunc && aFuncs[i].needCollSeq ){
1074dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1075dc1bdc4fSdanielk1977       }
1076dc1bdc4fSdanielk1977     }
10770bce8354Sdrh   }
10780bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1079c572ef7fSdanielk1977     void *pArg = 0;
1080c572ef7fSdanielk1977     switch( aAggs[i].argType ){
1081c572ef7fSdanielk1977       case 1: pArg = db; break;
1082c572ef7fSdanielk1977       case 2: pArg = (void *)(-1); break;
1083c572ef7fSdanielk1977     }
1084d8123366Sdanielk1977     sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1085*f9d64d2cSdanielk1977         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1086dc1bdc4fSdanielk1977     if( aAggs[i].needCollSeq ){
1087dc1bdc4fSdanielk1977       FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1088d8123366Sdanielk1977           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1089dc1bdc4fSdanielk1977       if( pFunc && aAggs[i].needCollSeq ){
1090dc1bdc4fSdanielk1977         pFunc->needCollSeq = 1;
1091dc1bdc4fSdanielk1977       }
1092dc1bdc4fSdanielk1977     }
1093268380caSdrh   }
10944adee20fSdanielk1977   sqlite3RegisterDateTimeFunctions(db);
1095dc04c583Sdrh }
1096dc1bdc4fSdanielk1977 
1097