xref: /sqlite-3.40.0/src/func.c (revision bbf483f8)
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 *************************************************************************
1260ec914cSpeter.d.reid ** This file contains the C-language implementations for many of the SQL
13ede7ae31Sdrh ** functions of SQLite.  (Some function, and in particular the date and
14ede7ae31Sdrh ** time functions, are implemented separately.)
15dc04c583Sdrh */
16b659e9bfSdrh #include "sqliteInt.h"
17d3a149efSdrh #include <stdlib.h>
180bce8354Sdrh #include <assert.h>
1988208050Sdanielk1977 #include "vdbeInt.h"
200bce8354Sdrh 
2155ef4d97Sdrh /*
2255ef4d97Sdrh ** Return the collating function associated with a function.
2355ef4d97Sdrh */
24dc1bdc4fSdanielk1977 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
25dc1bdc4fSdanielk1977   return context->pColl;
26dc1bdc4fSdanielk1977 }
27dc1bdc4fSdanielk1977 
280bce8354Sdrh /*
297a95789cSdrh ** Indicate that the accumulator load should be skipped on this
307a95789cSdrh ** iteration of the aggregate loop.
317a95789cSdrh */
327a95789cSdrh static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
337a95789cSdrh   context->skipFlag = 1;
347a95789cSdrh }
357a95789cSdrh 
367a95789cSdrh /*
370bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
380bce8354Sdrh */
39f9b596ebSdrh static void minmaxFunc(
40f9b596ebSdrh   sqlite3_context *context,
41f9b596ebSdrh   int argc,
42f9b596ebSdrh   sqlite3_value **argv
43f9b596ebSdrh ){
440bce8354Sdrh   int i;
45268380caSdrh   int mask;    /* 0 for min() or 0xffffffff for max() */
46f9b596ebSdrh   int iBest;
47dc1bdc4fSdanielk1977   CollSeq *pColl;
480bce8354Sdrh 
4965595cd6Sdrh   assert( argc>1 );
50c44af71cSdrh   mask = sqlite3_user_data(context)==0 ? 0 : -1;
51dc1bdc4fSdanielk1977   pColl = sqlite3GetFuncCollSeq(context);
52dc1bdc4fSdanielk1977   assert( pColl );
53c572ef7fSdanielk1977   assert( mask==-1 || mask==0 );
54f9b596ebSdrh   iBest = 0;
559c054830Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56f9b596ebSdrh   for(i=1; i<argc; i++){
579c054830Sdrh     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
58dc1bdc4fSdanielk1977     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
5965595cd6Sdrh       testcase( mask==0 );
60f9b596ebSdrh       iBest = i;
610bce8354Sdrh     }
620bce8354Sdrh   }
63f4479501Sdrh   sqlite3_result_value(context, argv[iBest]);
640bce8354Sdrh }
650bce8354Sdrh 
66268380caSdrh /*
67268380caSdrh ** Return the type of the argument.
68268380caSdrh */
69f9b596ebSdrh static void typeofFunc(
70f9b596ebSdrh   sqlite3_context *context,
7162c14b34Sdanielk1977   int NotUsed,
72f9b596ebSdrh   sqlite3_value **argv
73f9b596ebSdrh ){
7435bb9d02Sdanielk1977   const char *z = 0;
7562c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
7635bb9d02Sdanielk1977   switch( sqlite3_value_type(argv[0]) ){
779c054830Sdrh     case SQLITE_INTEGER: z = "integer"; break;
789c054830Sdrh     case SQLITE_TEXT:    z = "text";    break;
799c054830Sdrh     case SQLITE_FLOAT:   z = "real";    break;
809c054830Sdrh     case SQLITE_BLOB:    z = "blob";    break;
8165595cd6Sdrh     default:             z = "null";    break;
8235bb9d02Sdanielk1977   }
83d8123366Sdanielk1977   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
840bce8354Sdrh }
850bce8354Sdrh 
865708d2deSdrh 
875708d2deSdrh /*
880bce8354Sdrh ** Implementation of the length() function
890bce8354Sdrh */
90f9b596ebSdrh static void lengthFunc(
91f9b596ebSdrh   sqlite3_context *context,
92f9b596ebSdrh   int argc,
93f9b596ebSdrh   sqlite3_value **argv
94f9b596ebSdrh ){
950bce8354Sdrh   int len;
960bce8354Sdrh 
970bce8354Sdrh   assert( argc==1 );
98f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
99f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1009c054830Sdrh     case SQLITE_BLOB:
1019c054830Sdrh     case SQLITE_INTEGER:
1029c054830Sdrh     case SQLITE_FLOAT: {
103f4479501Sdrh       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
104f9b596ebSdrh       break;
105f9b596ebSdrh     }
1069c054830Sdrh     case SQLITE_TEXT: {
1072646da7eSdrh       const unsigned char *z = sqlite3_value_text(argv[0]);
1087a521cfbSdrh       if( z==0 ) return;
1094a919118Sdrh       len = 0;
1104a919118Sdrh       while( *z ){
1114a919118Sdrh         len++;
1124a919118Sdrh         SQLITE_SKIP_UTF8(z);
1134a919118Sdrh       }
114f4479501Sdrh       sqlite3_result_int(context, len);
115f9b596ebSdrh       break;
116f9b596ebSdrh     }
117f9b596ebSdrh     default: {
118f9b596ebSdrh       sqlite3_result_null(context);
119f9b596ebSdrh       break;
120f9b596ebSdrh     }
121f9b596ebSdrh   }
1220bce8354Sdrh }
1230bce8354Sdrh 
1240bce8354Sdrh /*
1252ba3cccfSdrh ** Implementation of the abs() function.
1262ba3cccfSdrh **
1272ba3cccfSdrh ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
1282ba3cccfSdrh ** the numeric argument X.
1290bce8354Sdrh */
1300ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1310bce8354Sdrh   assert( argc==1 );
132f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
133f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1349c054830Sdrh     case SQLITE_INTEGER: {
135f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
13652fc849aSdrh       if( iVal<0 ){
137693e6719Sdrh         if( iVal==SMALLEST_INT64 ){
138eb091cdfSdrh           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
139eb091cdfSdrh           ** then abs(X) throws an integer overflow error since there is no
1402ba3cccfSdrh           ** equivalent positive 64-bit two complement value. */
14152fc849aSdrh           sqlite3_result_error(context, "integer overflow", -1);
14252fc849aSdrh           return;
14352fc849aSdrh         }
14452fc849aSdrh         iVal = -iVal;
14552fc849aSdrh       }
146f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
147f9b596ebSdrh       break;
148f9b596ebSdrh     }
1499c054830Sdrh     case SQLITE_NULL: {
1502ba3cccfSdrh       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
151f9b596ebSdrh       sqlite3_result_null(context);
152f9b596ebSdrh       break;
153f9b596ebSdrh     }
154f9b596ebSdrh     default: {
1552ba3cccfSdrh       /* Because sqlite3_value_double() returns 0.0 if the argument is not
1562ba3cccfSdrh       ** something that can be converted into a number, we have:
1572ba3cccfSdrh       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
1582ba3cccfSdrh       ** cannot be converted to a numeric value.
1592ba3cccfSdrh       */
160f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
16152fc849aSdrh       if( rVal<0 ) rVal = -rVal;
162f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
163f9b596ebSdrh       break;
164f9b596ebSdrh     }
165f9b596ebSdrh   }
1660bce8354Sdrh }
1670bce8354Sdrh 
1680bce8354Sdrh /*
169d55e0729Sdrh ** Implementation of the instr() function.
170d55e0729Sdrh **
171d55e0729Sdrh ** instr(haystack,needle) finds the first occurrence of needle
172d55e0729Sdrh ** in haystack and returns the number of previous characters plus 1,
173d55e0729Sdrh ** or 0 if needle does not occur within haystack.
174d55e0729Sdrh **
175d55e0729Sdrh ** If both haystack and needle are BLOBs, then the result is one more than
176d55e0729Sdrh ** the number of bytes in haystack prior to the first occurrence of needle,
177d55e0729Sdrh ** or 0 if needle never occurs in haystack.
178d55e0729Sdrh */
179d55e0729Sdrh static void instrFunc(
180d55e0729Sdrh   sqlite3_context *context,
181d55e0729Sdrh   int argc,
182d55e0729Sdrh   sqlite3_value **argv
183d55e0729Sdrh ){
184d55e0729Sdrh   const unsigned char *zHaystack;
185d55e0729Sdrh   const unsigned char *zNeedle;
186d55e0729Sdrh   int nHaystack;
187d55e0729Sdrh   int nNeedle;
188d55e0729Sdrh   int typeHaystack, typeNeedle;
189d55e0729Sdrh   int N = 1;
190d55e0729Sdrh   int isText;
191d55e0729Sdrh 
19268c804b9Sdrh   UNUSED_PARAMETER(argc);
193d55e0729Sdrh   typeHaystack = sqlite3_value_type(argv[0]);
194d55e0729Sdrh   typeNeedle = sqlite3_value_type(argv[1]);
195d55e0729Sdrh   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
196d55e0729Sdrh   nHaystack = sqlite3_value_bytes(argv[0]);
197d55e0729Sdrh   nNeedle = sqlite3_value_bytes(argv[1]);
198d55e0729Sdrh   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
199d55e0729Sdrh     zHaystack = sqlite3_value_blob(argv[0]);
200d55e0729Sdrh     zNeedle = sqlite3_value_blob(argv[1]);
201d55e0729Sdrh     isText = 0;
202d55e0729Sdrh   }else{
203d55e0729Sdrh     zHaystack = sqlite3_value_text(argv[0]);
204d55e0729Sdrh     zNeedle = sqlite3_value_text(argv[1]);
205d55e0729Sdrh     isText = 1;
206d55e0729Sdrh   }
207d55e0729Sdrh   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
208d55e0729Sdrh     N++;
209d55e0729Sdrh     do{
210d55e0729Sdrh       nHaystack--;
211d55e0729Sdrh       zHaystack++;
212d55e0729Sdrh     }while( isText && (zHaystack[0]&0xc0)==0x80 );
213d55e0729Sdrh   }
214d55e0729Sdrh   if( nNeedle>nHaystack ) N = 0;
215d55e0729Sdrh   sqlite3_result_int(context, N);
216d55e0729Sdrh }
217d55e0729Sdrh 
218d55e0729Sdrh /*
219a5c1416dSdrh ** Implementation of the printf() function.
220a5c1416dSdrh */
221a5c1416dSdrh static void printfFunc(
222a5c1416dSdrh   sqlite3_context *context,
223a5c1416dSdrh   int argc,
224a5c1416dSdrh   sqlite3_value **argv
225a5c1416dSdrh ){
226a5c1416dSdrh   PrintfArguments x;
227a5c1416dSdrh   StrAccum str;
228a5c1416dSdrh   const char *zFormat;
229a5c1416dSdrh   int n;
230a5c1416dSdrh 
231a5c1416dSdrh   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
232a5c1416dSdrh     x.nArg = argc-1;
233a5c1416dSdrh     x.nUsed = 0;
234a5c1416dSdrh     x.apArg = argv+1;
235a5c1416dSdrh     sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
236a5c1416dSdrh     str.db = sqlite3_context_db_handle(context);
237a5c1416dSdrh     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
238a5c1416dSdrh     n = str.nChar;
239a5c1416dSdrh     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
240a5c1416dSdrh                         SQLITE_DYNAMIC);
241a5c1416dSdrh   }
242a5c1416dSdrh }
243a5c1416dSdrh 
244a5c1416dSdrh /*
245f764e6fcSdrh ** Implementation of the substr() function.
246f764e6fcSdrh **
247f764e6fcSdrh ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
248f764e6fcSdrh ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
249f764e6fcSdrh ** of x.  If x is text, then we actually count UTF-8 characters.
250f764e6fcSdrh ** If x is a blob, then we count bytes.
251f764e6fcSdrh **
252f764e6fcSdrh ** If p1 is negative, then we begin abs(p1) from the end of x[].
253779b8f12Sshaneh **
254f7b5496eSdrh ** If p2 is negative, return the p2 characters preceding p1.
2550bce8354Sdrh */
256f9b596ebSdrh static void substrFunc(
257f9b596ebSdrh   sqlite3_context *context,
258f9b596ebSdrh   int argc,
259f9b596ebSdrh   sqlite3_value **argv
260f9b596ebSdrh ){
2612646da7eSdrh   const unsigned char *z;
2622646da7eSdrh   const unsigned char *z2;
263023ae03aSdrh   int len;
264f764e6fcSdrh   int p0type;
265023ae03aSdrh   i64 p1, p2;
26665595cd6Sdrh   int negP2 = 0;
267f9b596ebSdrh 
26864f31519Sdrh   assert( argc==3 || argc==2 );
2698198d254Sdrh   if( sqlite3_value_type(argv[1])==SQLITE_NULL
2708198d254Sdrh    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
2718198d254Sdrh   ){
2728198d254Sdrh     return;
2738198d254Sdrh   }
274f764e6fcSdrh   p0type = sqlite3_value_type(argv[0]);
2754adc4cb9Sdrh   p1 = sqlite3_value_int(argv[1]);
276f764e6fcSdrh   if( p0type==SQLITE_BLOB ){
277f764e6fcSdrh     len = sqlite3_value_bytes(argv[0]);
278f764e6fcSdrh     z = sqlite3_value_blob(argv[0]);
279f764e6fcSdrh     if( z==0 ) return;
2801f0feef8Sdrh     assert( len==sqlite3_value_bytes(argv[0]) );
281f764e6fcSdrh   }else{
2824f26d6c4Sdrh     z = sqlite3_value_text(argv[0]);
2830bce8354Sdrh     if( z==0 ) return;
2844a919118Sdrh     len = 0;
2854adc4cb9Sdrh     if( p1<0 ){
2864a919118Sdrh       for(z2=z; *z2; len++){
2874a919118Sdrh         SQLITE_SKIP_UTF8(z2);
2884a919118Sdrh       }
289f764e6fcSdrh     }
2904adc4cb9Sdrh   }
29164f31519Sdrh   if( argc==3 ){
29251ad0ecdSdanielk1977     p2 = sqlite3_value_int(argv[2]);
29365595cd6Sdrh     if( p2<0 ){
29465595cd6Sdrh       p2 = -p2;
29565595cd6Sdrh       negP2 = 1;
29665595cd6Sdrh     }
29764f31519Sdrh   }else{
298bb4957f8Sdrh     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
29964f31519Sdrh   }
3000bce8354Sdrh   if( p1<0 ){
30189425d5eSdrh     p1 += len;
302653bc759Sdrh     if( p1<0 ){
303653bc759Sdrh       p2 += p1;
30465595cd6Sdrh       if( p2<0 ) p2 = 0;
305653bc759Sdrh       p1 = 0;
306653bc759Sdrh     }
3070bce8354Sdrh   }else if( p1>0 ){
3080bce8354Sdrh     p1--;
30965595cd6Sdrh   }else if( p2>0 ){
31065595cd6Sdrh     p2--;
3110bce8354Sdrh   }
31265595cd6Sdrh   if( negP2 ){
31365595cd6Sdrh     p1 -= p2;
3144e79c594Sdrh     if( p1<0 ){
3154e79c594Sdrh       p2 += p1;
3164e79c594Sdrh       p1 = 0;
3174e79c594Sdrh     }
3184e79c594Sdrh   }
31965595cd6Sdrh   assert( p1>=0 && p2>=0 );
320f764e6fcSdrh   if( p0type!=SQLITE_BLOB ){
3214a919118Sdrh     while( *z && p1 ){
3224a919118Sdrh       SQLITE_SKIP_UTF8(z);
3234a919118Sdrh       p1--;
3240bce8354Sdrh     }
3254a919118Sdrh     for(z2=z; *z2 && p2; p2--){
3264a919118Sdrh       SQLITE_SKIP_UTF8(z2);
3270bce8354Sdrh     }
328*bbf483f8Sdrh     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
329*bbf483f8Sdrh                           SQLITE_UTF8);
330f764e6fcSdrh   }else{
3314adc4cb9Sdrh     if( p1+p2>len ){
3324adc4cb9Sdrh       p2 = len-p1;
3334adc4cb9Sdrh       if( p2<0 ) p2 = 0;
3344adc4cb9Sdrh     }
335*bbf483f8Sdrh     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
336f764e6fcSdrh   }
3370bce8354Sdrh }
3380bce8354Sdrh 
3390bce8354Sdrh /*
3400bce8354Sdrh ** Implementation of the round() function
3410bce8354Sdrh */
342fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
3430ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
34451ad0ecdSdanielk1977   int n = 0;
3450bce8354Sdrh   double r;
34650d654daSdrh   char *zBuf;
3470bce8354Sdrh   assert( argc==1 || argc==2 );
34851ad0ecdSdanielk1977   if( argc==2 ){
3499c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
35051ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
3510bce8354Sdrh     if( n>30 ) n = 30;
3520bce8354Sdrh     if( n<0 ) n = 0;
35351ad0ecdSdanielk1977   }
354d589a92aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
3554f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
356147e176aSshaneh   /* If Y==0 and X will fit in a 64-bit int,
357147e176aSshaneh   ** handle the rounding directly,
358147e176aSshaneh   ** otherwise use printf.
359147e176aSshaneh   */
360147e176aSshaneh   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
361147e176aSshaneh     r = (double)((sqlite_int64)(r+0.5));
362147e176aSshaneh   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
363147e176aSshaneh     r = -(double)((sqlite_int64)((-r)+0.5));
364147e176aSshaneh   }else{
36550d654daSdrh     zBuf = sqlite3_mprintf("%.*f",n,r);
36650d654daSdrh     if( zBuf==0 ){
36750d654daSdrh       sqlite3_result_error_nomem(context);
368147e176aSshaneh       return;
369147e176aSshaneh     }
3709339da1fSdrh     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
37150d654daSdrh     sqlite3_free(zBuf);
3720bce8354Sdrh   }
373147e176aSshaneh   sqlite3_result_double(context, r);
37450d654daSdrh }
375fbd60f82Sshane #endif
376dc04c583Sdrh 
37726783a58Sdanielk1977 /*
37826783a58Sdanielk1977 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
37926783a58Sdanielk1977 ** allocation fails, call sqlite3_result_error_nomem() to notify
38027e62dbeSdrh ** the database handle that malloc() has failed and return NULL.
38127e62dbeSdrh ** If nByte is larger than the maximum string or blob length, then
38227e62dbeSdrh ** raise an SQLITE_TOOBIG exception and return NULL.
38326783a58Sdanielk1977 */
384b1a6c3c1Sdrh static void *contextMalloc(sqlite3_context *context, i64 nByte){
385bb4957f8Sdrh   char *z;
38627e62dbeSdrh   sqlite3 *db = sqlite3_context_db_handle(context);
387ef31c6aaSdrh   assert( nByte>0 );
38827e62dbeSdrh   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
38927e62dbeSdrh   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
39027e62dbeSdrh   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
391bb4957f8Sdrh     sqlite3_result_error_toobig(context);
392bb4957f8Sdrh     z = 0;
393bb4957f8Sdrh   }else{
394da4ca9d1Sdrh     z = sqlite3Malloc(nByte);
395ef31c6aaSdrh     if( !z ){
396a1644fd8Sdanielk1977       sqlite3_result_error_nomem(context);
397a1644fd8Sdanielk1977     }
398bb4957f8Sdrh   }
399a1644fd8Sdanielk1977   return z;
400a1644fd8Sdanielk1977 }
401a1644fd8Sdanielk1977 
402dc04c583Sdrh /*
403dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
404dc04c583Sdrh */
4050ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
4067a521cfbSdrh   char *z1;
4077a521cfbSdrh   const char *z2;
4089310ef23Sdrh   int i, n;
4091d34fdecSdrh   UNUSED_PARAMETER(argc);
4107a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
4111f0feef8Sdrh   n = sqlite3_value_bytes(argv[0]);
4121f0feef8Sdrh   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
4131f0feef8Sdrh   assert( z2==(char*)sqlite3_value_text(argv[0]) );
4147a521cfbSdrh   if( z2 ){
415b1a6c3c1Sdrh     z1 = contextMalloc(context, ((i64)n)+1);
4167a521cfbSdrh     if( z1 ){
417df901d34Sdrh       for(i=0; i<n; i++){
418df901d34Sdrh         z1[i] = (char)sqlite3Toupper(z2[i]);
419dc04c583Sdrh       }
420df901d34Sdrh       sqlite3_result_text(context, z1, n, sqlite3_free);
4217a521cfbSdrh     }
4227a521cfbSdrh   }
423dc04c583Sdrh }
4240ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
425df901d34Sdrh   char *z1;
4267a521cfbSdrh   const char *z2;
4279310ef23Sdrh   int i, n;
4281d34fdecSdrh   UNUSED_PARAMETER(argc);
4297a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
4301f0feef8Sdrh   n = sqlite3_value_bytes(argv[0]);
4311f0feef8Sdrh   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
4321f0feef8Sdrh   assert( z2==(char*)sqlite3_value_text(argv[0]) );
4337a521cfbSdrh   if( z2 ){
434b1a6c3c1Sdrh     z1 = contextMalloc(context, ((i64)n)+1);
4357a521cfbSdrh     if( z1 ){
436df901d34Sdrh       for(i=0; i<n; i++){
437df901d34Sdrh         z1[i] = sqlite3Tolower(z2[i]);
438dc04c583Sdrh       }
439df901d34Sdrh       sqlite3_result_text(context, z1, n, sqlite3_free);
4407a521cfbSdrh     }
4417a521cfbSdrh   }
442dc04c583Sdrh }
443dc04c583Sdrh 
444ae6bb957Sdrh /*
445cca9f3d2Sdrh ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
446cca9f3d2Sdrh ** as VDBE code so that unused argument values do not have to be computed.
447cca9f3d2Sdrh ** However, we still need some kind of function implementation for this
448cca9f3d2Sdrh ** routines in the function table.  The noopFunc macro provides this.
449cca9f3d2Sdrh ** noopFunc will never be called so it doesn't matter what the implementation
450cca9f3d2Sdrh ** is.  We might as well use the "version()" function as a substitute.
451ae6bb957Sdrh */
452cca9f3d2Sdrh #define noopFunc versionFunc   /* Substitute function - never called */
4533212e182Sdrh 
4543212e182Sdrh /*
455f9ffac96Sdrh ** Implementation of random().  Return a random integer.
456f9ffac96Sdrh */
457f9b596ebSdrh static void randomFunc(
458f9b596ebSdrh   sqlite3_context *context,
45962c14b34Sdanielk1977   int NotUsed,
46062c14b34Sdanielk1977   sqlite3_value **NotUsed2
461f9b596ebSdrh ){
46252fc849aSdrh   sqlite_int64 r;
46362c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
4642fa1868fSdrh   sqlite3_randomness(sizeof(r), &r);
4653034e3d3Sdrh   if( r<0 ){
4663034e3d3Sdrh     /* We need to prevent a random number of 0x8000000000000000
4673034e3d3Sdrh     ** (or -9223372036854775808) since when you do abs() of that
4683034e3d3Sdrh     ** number of you get the same value back again.  To do this
4693034e3d3Sdrh     ** in a way that is testable, mask the sign bit off of negative
4703034e3d3Sdrh     ** values, resulting in a positive value.  Then take the
4713034e3d3Sdrh     ** 2s complement of that positive value.  The end result can
4723034e3d3Sdrh     ** therefore be no less than -9223372036854775807.
4733034e3d3Sdrh     */
474af8001bfSdrh     r = -(r & LARGEST_INT64);
4753034e3d3Sdrh   }
47652fc849aSdrh   sqlite3_result_int64(context, r);
477f9ffac96Sdrh }
478f9ffac96Sdrh 
479f9ffac96Sdrh /*
480137c728fSdrh ** Implementation of randomblob(N).  Return a random blob
481137c728fSdrh ** that is N bytes long.
48263cf66f0Sdrh */
483137c728fSdrh static void randomBlob(
48463cf66f0Sdrh   sqlite3_context *context,
48563cf66f0Sdrh   int argc,
48663cf66f0Sdrh   sqlite3_value **argv
48763cf66f0Sdrh ){
488137c728fSdrh   int n;
489137c728fSdrh   unsigned char *p;
49063cf66f0Sdrh   assert( argc==1 );
491f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
49263cf66f0Sdrh   n = sqlite3_value_int(argv[0]);
493023ae03aSdrh   if( n<1 ){
494023ae03aSdrh     n = 1;
495023ae03aSdrh   }
496a1644fd8Sdanielk1977   p = contextMalloc(context, n);
49702d85836Sdrh   if( p ){
4982fa1868fSdrh     sqlite3_randomness(n, p);
49917435752Sdrh     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
50002d85836Sdrh   }
50163cf66f0Sdrh }
50263cf66f0Sdrh 
50363cf66f0Sdrh /*
5046ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
50524b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
5066ed41ad7Sdrh */
50751ad0ecdSdanielk1977 static void last_insert_rowid(
5080ae8b831Sdanielk1977   sqlite3_context *context,
50962c14b34Sdanielk1977   int NotUsed,
51062c14b34Sdanielk1977   sqlite3_value **NotUsed2
51151ad0ecdSdanielk1977 ){
512fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
51362c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
514ab2f1f95Sdrh   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
515ab2f1f95Sdrh   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
516ab2f1f95Sdrh   ** function. */
517f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
5186ed41ad7Sdrh }
5196ed41ad7Sdrh 
520f146a776Srdc /*
521ab2f1f95Sdrh ** Implementation of the changes() SQL function.
522ab2f1f95Sdrh **
523ab2f1f95Sdrh ** IMP: R-62073-11209 The changes() SQL function is a wrapper
524ab2f1f95Sdrh ** around the sqlite3_changes() C/C++ function and hence follows the same
525ab2f1f95Sdrh ** rules for counting changes.
526f146a776Srdc */
527b28af71aSdanielk1977 static void changes(
528f9b596ebSdrh   sqlite3_context *context,
52962c14b34Sdanielk1977   int NotUsed,
53062c14b34Sdanielk1977   sqlite3_value **NotUsed2
531f9b596ebSdrh ){
532fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
53362c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
534f4479501Sdrh   sqlite3_result_int(context, sqlite3_changes(db));
535b0c374ffSrdc }
536f146a776Srdc 
537f146a776Srdc /*
538b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
539b28af71aSdanielk1977 ** the same as the sqlite3_total_changes() API function.
540f146a776Srdc */
541b28af71aSdanielk1977 static void total_changes(
5420ae8b831Sdanielk1977   sqlite3_context *context,
54362c14b34Sdanielk1977   int NotUsed,
54462c14b34Sdanielk1977   sqlite3_value **NotUsed2
54551ad0ecdSdanielk1977 ){
546fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
54762c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
548ab2f1f95Sdrh   /* IMP: R-52756-41993 This function is a wrapper around the
549ab2f1f95Sdrh   ** sqlite3_total_changes() C/C++ interface. */
550b28af71aSdanielk1977   sqlite3_result_int(context, sqlite3_total_changes(db));
551b0c374ffSrdc }
552b0c374ffSrdc 
5536ed41ad7Sdrh /*
5544e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
555d02eb1fdSdanielk1977 */
5564e5ffc5fSdrh struct compareInfo {
5574e5ffc5fSdrh   u8 matchAll;
5584e5ffc5fSdrh   u8 matchOne;
5594e5ffc5fSdrh   u8 matchSet;
5604e5ffc5fSdrh   u8 noCase;
561d02eb1fdSdanielk1977 };
56255ef4d97Sdrh 
563b9175aedSdrh /*
564b9175aedSdrh ** For LIKE and GLOB matching on EBCDIC machines, assume that every
565b9175aedSdrh ** character is exactly one byte in size.  Also, all characters are
566b9175aedSdrh ** able to participate in upper-case-to-lower-case mappings in EBCDIC
567b9175aedSdrh ** whereas only characters less than 0x80 do in ASCII.
568b9175aedSdrh */
569b9175aedSdrh #if defined(SQLITE_EBCDIC)
57042610961Sdrh # define sqlite3Utf8Read(A)    (*((*A)++))
5716e1b1674Sdrh # define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
572b9175aedSdrh #else
5736e1b1674Sdrh # define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
574b9175aedSdrh #endif
575b9175aedSdrh 
5764e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
57770031fa3Sdrh /* The correct SQL-92 behavior is for the LIKE operator to ignore
57870031fa3Sdrh ** case.  Thus  'a' LIKE 'A' would be true. */
57955ef4d97Sdrh static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
58070031fa3Sdrh /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
58170031fa3Sdrh ** is case sensitive causing 'a' LIKE 'A' to be false */
58255ef4d97Sdrh static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
583d02eb1fdSdanielk1977 
584d02eb1fdSdanielk1977 /*
5854e5ffc5fSdrh ** Compare two UTF-8 strings for equality where the first string can
5864e5ffc5fSdrh ** potentially be a "glob" expression.  Return true (1) if they
5874e5ffc5fSdrh ** are the same and false (0) if they are different.
5880ac65892Sdrh **
5894e5ffc5fSdrh ** Globbing rules:
5900ac65892Sdrh **
5914e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
592d02eb1fdSdanielk1977 **
5934e5ffc5fSdrh **      '?'       Matches exactly one character.
5944e5ffc5fSdrh **
5954e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
5964e5ffc5fSdrh **                characters.
5974e5ffc5fSdrh **
5984e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
5994e5ffc5fSdrh **
6004e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
6014e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
6024e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
6034e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
6044e5ffc5fSdrh ** it the last character in the list.
6054e5ffc5fSdrh **
6064e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
6074e5ffc5fSdrh **
6084e5ffc5fSdrh ** Hints: to match '*' or '?', put them in "[]".  Like this:
6094e5ffc5fSdrh **
6104e5ffc5fSdrh **         abc[*]xyz        Matches "abc*xyz" only
6110ac65892Sdrh */
6127c6303c0Sdanielk1977 static int patternCompare(
6134e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
6144e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
6157c6303c0Sdanielk1977   const struct compareInfo *pInfo, /* Information about how to do the compare */
6160a32fa6dSdrh   u32 esc                          /* The escape character */
61751ad0ecdSdanielk1977 ){
6180a32fa6dSdrh   u32 c, c2;
6194e5ffc5fSdrh   int invert;
6204e5ffc5fSdrh   int seen;
6214e5ffc5fSdrh   u8 matchOne = pInfo->matchOne;
6224e5ffc5fSdrh   u8 matchAll = pInfo->matchAll;
6234e5ffc5fSdrh   u8 matchSet = pInfo->matchSet;
6244e5ffc5fSdrh   u8 noCase = pInfo->noCase;
6257c6303c0Sdanielk1977   int prevEscape = 0;     /* True if the previous character was 'escape' */
626d02eb1fdSdanielk1977 
62742610961Sdrh   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
62842610961Sdrh     if( c==matchAll && !prevEscape ){
62942610961Sdrh       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
63066150956Sdrh                || c == matchOne ){
63142610961Sdrh         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
63266150956Sdrh           return 0;
633d02eb1fdSdanielk1977         }
6344e5ffc5fSdrh       }
63566150956Sdrh       if( c==0 ){
63666150956Sdrh         return 1;
63766150956Sdrh       }else if( c==esc ){
63842610961Sdrh         c = sqlite3Utf8Read(&zPattern);
63966150956Sdrh         if( c==0 ){
64066150956Sdrh           return 0;
6417c6303c0Sdanielk1977         }
64266150956Sdrh       }else if( c==matchSet ){
6437c6303c0Sdanielk1977         assert( esc==0 );         /* This is GLOB, not LIKE */
64466150956Sdrh         assert( matchSet<0x80 );  /* '[' is a single-byte character */
64566150956Sdrh         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
6464a919118Sdrh           SQLITE_SKIP_UTF8(zString);
6474e5ffc5fSdrh         }
6484e5ffc5fSdrh         return *zString!=0;
64966150956Sdrh       }
65042610961Sdrh       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
6514e5ffc5fSdrh         if( noCase ){
6526e1b1674Sdrh           GlobUpperToLower(c2);
6536e1b1674Sdrh           GlobUpperToLower(c);
65466150956Sdrh           while( c2 != 0 && c2 != c ){
65542610961Sdrh             c2 = sqlite3Utf8Read(&zString);
6566e1b1674Sdrh             GlobUpperToLower(c2);
65766150956Sdrh           }
658ad7dd425Sdanielk1977         }else{
65966150956Sdrh           while( c2 != 0 && c2 != c ){
66042610961Sdrh             c2 = sqlite3Utf8Read(&zString);
66166150956Sdrh           }
662ad7dd425Sdanielk1977         }
6634e5ffc5fSdrh         if( c2==0 ) return 0;
66466150956Sdrh         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
6654e5ffc5fSdrh       }
6664e5ffc5fSdrh       return 0;
66742610961Sdrh     }else if( c==matchOne && !prevEscape ){
66842610961Sdrh       if( sqlite3Utf8Read(&zString)==0 ){
66966150956Sdrh         return 0;
67066150956Sdrh       }
6714e5ffc5fSdrh     }else if( c==matchSet ){
6721aa4f3e5Sdrh       u32 prior_c = 0;
6737c6303c0Sdanielk1977       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
6744e5ffc5fSdrh       seen = 0;
6754e5ffc5fSdrh       invert = 0;
67642610961Sdrh       c = sqlite3Utf8Read(&zString);
6774e5ffc5fSdrh       if( c==0 ) return 0;
67842610961Sdrh       c2 = sqlite3Utf8Read(&zPattern);
67966150956Sdrh       if( c2=='^' ){
68066150956Sdrh         invert = 1;
68142610961Sdrh         c2 = sqlite3Utf8Read(&zPattern);
68266150956Sdrh       }
6834e5ffc5fSdrh       if( c2==']' ){
6844e5ffc5fSdrh         if( c==']' ) seen = 1;
68542610961Sdrh         c2 = sqlite3Utf8Read(&zPattern);
6864e5ffc5fSdrh       }
68766150956Sdrh       while( c2 && c2!=']' ){
68866150956Sdrh         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
68942610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
6904e5ffc5fSdrh           if( c>=prior_c && c<=c2 ) seen = 1;
6914e5ffc5fSdrh           prior_c = 0;
69266150956Sdrh         }else{
69366150956Sdrh           if( c==c2 ){
6944e5ffc5fSdrh             seen = 1;
69566150956Sdrh           }
6964e5ffc5fSdrh           prior_c = c2;
697d02eb1fdSdanielk1977         }
69842610961Sdrh         c2 = sqlite3Utf8Read(&zPattern);
699d02eb1fdSdanielk1977       }
70066150956Sdrh       if( c2==0 || (seen ^ invert)==0 ){
70166150956Sdrh         return 0;
70266150956Sdrh       }
70366150956Sdrh     }else if( esc==c && !prevEscape ){
7047c6303c0Sdanielk1977       prevEscape = 1;
705d02eb1fdSdanielk1977     }else{
70642610961Sdrh       c2 = sqlite3Utf8Read(&zString);
7074e5ffc5fSdrh       if( noCase ){
7086e1b1674Sdrh         GlobUpperToLower(c);
7096e1b1674Sdrh         GlobUpperToLower(c2);
7104e5ffc5fSdrh       }
71166150956Sdrh       if( c!=c2 ){
71266150956Sdrh         return 0;
71366150956Sdrh       }
7147c6303c0Sdanielk1977       prevEscape = 0;
71551ad0ecdSdanielk1977     }
7160ac65892Sdrh   }
7174e5ffc5fSdrh   return *zString==0;
7184e5ffc5fSdrh }
7194e5ffc5fSdrh 
72055ef4d97Sdrh /*
72156282a5bSdrh ** The sqlite3_strglob() interface.
72256282a5bSdrh */
72356282a5bSdrh int sqlite3_strglob(const char *zGlobPattern, const char *zString){
72456282a5bSdrh   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
72556282a5bSdrh }
72656282a5bSdrh 
72756282a5bSdrh /*
72855ef4d97Sdrh ** Count the number of times that the LIKE operator (or GLOB which is
72955ef4d97Sdrh ** just a variation of LIKE) gets called.  This is used for testing
73055ef4d97Sdrh ** only.
73155ef4d97Sdrh */
73255ef4d97Sdrh #ifdef SQLITE_TEST
73355ef4d97Sdrh int sqlite3_like_count = 0;
73455ef4d97Sdrh #endif
73555ef4d97Sdrh 
7363f6b0874Sdanielk1977 
7373f6b0874Sdanielk1977 /*
7383f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
7393f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
7403f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
7413f6b0874Sdanielk1977 **
7423f6b0874Sdanielk1977 **       A LIKE B
7433f6b0874Sdanielk1977 **
7443f6b0874Sdanielk1977 ** is implemented as like(B,A).
7453f6b0874Sdanielk1977 **
74655ef4d97Sdrh ** This same function (with a different compareInfo structure) computes
74755ef4d97Sdrh ** the GLOB operator.
7483f6b0874Sdanielk1977 */
7493f6b0874Sdanielk1977 static void likeFunc(
7503f6b0874Sdanielk1977   sqlite3_context *context,
7513f6b0874Sdanielk1977   int argc,
7523f6b0874Sdanielk1977   sqlite3_value **argv
7533f6b0874Sdanielk1977 ){
754beb818d1Sdrh   const unsigned char *zA, *zB;
7550a32fa6dSdrh   u32 escape = 0;
75627e62dbeSdrh   int nPat;
757bb4957f8Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
758beb818d1Sdrh 
7591f0feef8Sdrh   zB = sqlite3_value_text(argv[0]);
7601f0feef8Sdrh   zA = sqlite3_value_text(argv[1]);
7611f0feef8Sdrh 
762beb818d1Sdrh   /* Limit the length of the LIKE or GLOB pattern to avoid problems
763beb818d1Sdrh   ** of deep recursion and N*N behavior in patternCompare().
764beb818d1Sdrh   */
76527e62dbeSdrh   nPat = sqlite3_value_bytes(argv[0]);
76627e62dbeSdrh   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
76727e62dbeSdrh   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
76827e62dbeSdrh   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
769beb818d1Sdrh     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
770beb818d1Sdrh     return;
771beb818d1Sdrh   }
7721f0feef8Sdrh   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
773beb818d1Sdrh 
7747c6303c0Sdanielk1977   if( argc==3 ){
7757c6303c0Sdanielk1977     /* The escape character string must consist of a single UTF-8 character.
7767c6303c0Sdanielk1977     ** Otherwise, return an error.
7777c6303c0Sdanielk1977     */
7787c6303c0Sdanielk1977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
7797a521cfbSdrh     if( zEsc==0 ) return;
780ee85813cSdrh     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
7817c6303c0Sdanielk1977       sqlite3_result_error(context,
7827c6303c0Sdanielk1977           "ESCAPE expression must be a single character", -1);
7837c6303c0Sdanielk1977       return;
7847c6303c0Sdanielk1977     }
78542610961Sdrh     escape = sqlite3Utf8Read(&zEsc);
7867c6303c0Sdanielk1977   }
7873f6b0874Sdanielk1977   if( zA && zB ){
78855ef4d97Sdrh     struct compareInfo *pInfo = sqlite3_user_data(context);
78955ef4d97Sdrh #ifdef SQLITE_TEST
79055ef4d97Sdrh     sqlite3_like_count++;
79155ef4d97Sdrh #endif
792beb818d1Sdrh 
793b56fe1ffSdanielk1977     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
79451ad0ecdSdanielk1977   }
7958912d106Sdrh }
7968912d106Sdrh 
7978912d106Sdrh /*
7988912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
7998912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
8008912d106Sdrh ** arguments are equal to each other.
8018912d106Sdrh */
802f9b596ebSdrh static void nullifFunc(
803f9b596ebSdrh   sqlite3_context *context,
80462c14b34Sdanielk1977   int NotUsed,
805f9b596ebSdrh   sqlite3_value **argv
806f9b596ebSdrh ){
807dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
80862c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
809dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
810f4479501Sdrh     sqlite3_result_value(context, argv[0]);
8118912d106Sdrh   }
8120ac65892Sdrh }
8130ac65892Sdrh 
814647cb0e1Sdrh /*
81547baebc2Sdrh ** Implementation of the sqlite_version() function.  The result is the version
816647cb0e1Sdrh ** of the SQLite library that is running.
817647cb0e1Sdrh */
818f9b596ebSdrh static void versionFunc(
819f9b596ebSdrh   sqlite3_context *context,
82062c14b34Sdanielk1977   int NotUsed,
82162c14b34Sdanielk1977   sqlite3_value **NotUsed2
822f9b596ebSdrh ){
82362c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
824ab2f1f95Sdrh   /* IMP: R-48699-48617 This function is an SQL wrapper around the
825ab2f1f95Sdrh   ** sqlite3_libversion() C-interface. */
826ab2f1f95Sdrh   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
827647cb0e1Sdrh }
828647cb0e1Sdrh 
82947baebc2Sdrh /*
83047baebc2Sdrh ** Implementation of the sqlite_source_id() function. The result is a string
83147baebc2Sdrh ** that identifies the particular version of the source code used to build
83247baebc2Sdrh ** SQLite.
83347baebc2Sdrh */
83447baebc2Sdrh static void sourceidFunc(
83547baebc2Sdrh   sqlite3_context *context,
83647baebc2Sdrh   int NotUsed,
83747baebc2Sdrh   sqlite3_value **NotUsed2
83847baebc2Sdrh ){
83947baebc2Sdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
840ab2f1f95Sdrh   /* IMP: R-24470-31136 This function is an SQL wrapper around the
841ab2f1f95Sdrh   ** sqlite3_sourceid() C interface. */
842ab2f1f95Sdrh   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
84347baebc2Sdrh }
84447baebc2Sdrh 
845bdea6d13Sshaneh /*
8463ca84ef6Sdrh ** Implementation of the sqlite_log() function.  This is a wrapper around
8473ca84ef6Sdrh ** sqlite3_log().  The return value is NULL.  The function exists purely for
8483ca84ef6Sdrh ** its side-effects.
8493ca84ef6Sdrh */
850840561f2Sdrh static void errlogFunc(
8513ca84ef6Sdrh   sqlite3_context *context,
8523ca84ef6Sdrh   int argc,
8533ca84ef6Sdrh   sqlite3_value **argv
8543ca84ef6Sdrh ){
8553ca84ef6Sdrh   UNUSED_PARAMETER(argc);
8563ca84ef6Sdrh   UNUSED_PARAMETER(context);
8573ca84ef6Sdrh   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
8583ca84ef6Sdrh }
8593ca84ef6Sdrh 
8603ca84ef6Sdrh /*
861dc97a8cdSshaneh ** Implementation of the sqlite_compileoption_used() function.
862dc97a8cdSshaneh ** The result is an integer that identifies if the compiler option
863dc97a8cdSshaneh ** was used to build SQLite.
864bdea6d13Sshaneh */
865dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
866dc97a8cdSshaneh static void compileoptionusedFunc(
867bdea6d13Sshaneh   sqlite3_context *context,
868dc97a8cdSshaneh   int argc,
869dc97a8cdSshaneh   sqlite3_value **argv
870bdea6d13Sshaneh ){
871dc97a8cdSshaneh   const char *zOptName;
872dc97a8cdSshaneh   assert( argc==1 );
873dc97a8cdSshaneh   UNUSED_PARAMETER(argc);
874a3e414cdSdrh   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
875a3e414cdSdrh   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
876a3e414cdSdrh   ** function.
877a3e414cdSdrh   */
878264a2d4dSdrh   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
879dc97a8cdSshaneh     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
880bdea6d13Sshaneh   }
881dc97a8cdSshaneh }
882dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
883dc97a8cdSshaneh 
884dc97a8cdSshaneh /*
885dc97a8cdSshaneh ** Implementation of the sqlite_compileoption_get() function.
886dc97a8cdSshaneh ** The result is a string that identifies the compiler options
887dc97a8cdSshaneh ** used to build SQLite.
888dc97a8cdSshaneh */
889dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
890dc97a8cdSshaneh static void compileoptiongetFunc(
891dc97a8cdSshaneh   sqlite3_context *context,
892dc97a8cdSshaneh   int argc,
893dc97a8cdSshaneh   sqlite3_value **argv
894dc97a8cdSshaneh ){
895dc97a8cdSshaneh   int n;
896dc97a8cdSshaneh   assert( argc==1 );
897dc97a8cdSshaneh   UNUSED_PARAMETER(argc);
898a3e414cdSdrh   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
899a3e414cdSdrh   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
900a3e414cdSdrh   */
901dc97a8cdSshaneh   n = sqlite3_value_int(argv[0]);
902dc97a8cdSshaneh   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
903dc97a8cdSshaneh }
904dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
905bdea6d13Sshaneh 
906137c728fSdrh /* Array for converting from half-bytes (nybbles) into ASCII hex
907137c728fSdrh ** digits. */
908137c728fSdrh static const char hexdigits[] = {
909137c728fSdrh   '0', '1', '2', '3', '4', '5', '6', '7',
910137c728fSdrh   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
911137c728fSdrh };
912d641d646Sdanielk1977 
91347394703Sdrh /*
91447394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
91547394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
91647394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
91747394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
91847394703Sdrh ** single-quote escapes.
91947394703Sdrh */
9200ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
921a0df4ccfSdrh   assert( argc==1 );
9221d34fdecSdrh   UNUSED_PARAMETER(argc);
923f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
9249c054830Sdrh     case SQLITE_FLOAT: {
92572b3fbc7Sdrh       double r1, r2;
92672b3fbc7Sdrh       char zBuf[50];
9272b434a7eSmistachkin       r1 = sqlite3_value_double(argv[0]);
92872b3fbc7Sdrh       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
92972b3fbc7Sdrh       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
93072b3fbc7Sdrh       if( r1!=r2 ){
93172b3fbc7Sdrh         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
93272b3fbc7Sdrh       }
93372b3fbc7Sdrh       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
93472b3fbc7Sdrh       break;
93572b3fbc7Sdrh     }
93672b3fbc7Sdrh     case SQLITE_INTEGER: {
937f4479501Sdrh       sqlite3_result_value(context, argv[0]);
938f9b596ebSdrh       break;
939f9b596ebSdrh     }
9403f41e976Sdanielk1977     case SQLITE_BLOB: {
9413f41e976Sdanielk1977       char *zText = 0;
9423f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
9431f0feef8Sdrh       int nBlob = sqlite3_value_bytes(argv[0]);
9441f0feef8Sdrh       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
945b1a6c3c1Sdrh       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
946a1644fd8Sdanielk1977       if( zText ){
9473f41e976Sdanielk1977         int i;
9483f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
9493f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
9503f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
9513f41e976Sdanielk1977         }
9523f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
9533f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
9543f41e976Sdanielk1977         zText[0] = 'X';
9553f41e976Sdanielk1977         zText[1] = '\'';
956d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
95717435752Sdrh         sqlite3_free(zText);
9583f41e976Sdanielk1977       }
9593f41e976Sdanielk1977       break;
9603f41e976Sdanielk1977     }
9619c054830Sdrh     case SQLITE_TEXT: {
962023ae03aSdrh       int i,j;
963023ae03aSdrh       u64 n;
9642646da7eSdrh       const unsigned char *zArg = sqlite3_value_text(argv[0]);
96547394703Sdrh       char *z;
966f9b596ebSdrh 
9677a521cfbSdrh       if( zArg==0 ) return;
968023ae03aSdrh       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
969b1a6c3c1Sdrh       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
970a1644fd8Sdanielk1977       if( z ){
97147394703Sdrh         z[0] = '\'';
97251ad0ecdSdanielk1977         for(i=0, j=1; zArg[i]; i++){
97351ad0ecdSdanielk1977           z[j++] = zArg[i];
97451ad0ecdSdanielk1977           if( zArg[i]=='\'' ){
97547394703Sdrh             z[j++] = '\'';
97647394703Sdrh           }
97747394703Sdrh         }
97847394703Sdrh         z[j++] = '\'';
97947394703Sdrh         z[j] = 0;
980a1644fd8Sdanielk1977         sqlite3_result_text(context, z, j, sqlite3_free);
981a1644fd8Sdanielk1977       }
982a0df4ccfSdrh       break;
983a0df4ccfSdrh     }
984a0df4ccfSdrh     default: {
985a0df4ccfSdrh       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
986a0df4ccfSdrh       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
987a0df4ccfSdrh       break;
98847394703Sdrh     }
98947394703Sdrh   }
990f9b596ebSdrh }
99147394703Sdrh 
992137c728fSdrh /*
993d495d8c9Sdrh ** The unicode() function.  Return the integer unicode code-point value
994d495d8c9Sdrh ** for the first character of the input string.
995d495d8c9Sdrh */
996d495d8c9Sdrh static void unicodeFunc(
997d495d8c9Sdrh   sqlite3_context *context,
998d495d8c9Sdrh   int argc,
999d495d8c9Sdrh   sqlite3_value **argv
1000d495d8c9Sdrh ){
1001d495d8c9Sdrh   const unsigned char *z = sqlite3_value_text(argv[0]);
10021d59d036Sdrh   (void)argc;
1003d495d8c9Sdrh   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
1004d495d8c9Sdrh }
1005d495d8c9Sdrh 
1006d495d8c9Sdrh /*
1007d495d8c9Sdrh ** The char() function takes zero or more arguments, each of which is
1008d495d8c9Sdrh ** an integer.  It constructs a string where each character of the string
1009d495d8c9Sdrh ** is the unicode character for the corresponding integer argument.
1010d495d8c9Sdrh */
1011d495d8c9Sdrh static void charFunc(
1012d495d8c9Sdrh   sqlite3_context *context,
1013d495d8c9Sdrh   int argc,
1014d495d8c9Sdrh   sqlite3_value **argv
1015d495d8c9Sdrh ){
1016d495d8c9Sdrh   unsigned char *z, *zOut;
1017d495d8c9Sdrh   int i;
1018b72cad14Sdan   zOut = z = sqlite3_malloc( argc*4+1 );
1019d495d8c9Sdrh   if( z==0 ){
1020d495d8c9Sdrh     sqlite3_result_error_nomem(context);
1021d495d8c9Sdrh     return;
1022d495d8c9Sdrh   }
1023d495d8c9Sdrh   for(i=0; i<argc; i++){
1024c9545442Smistachkin     sqlite3_int64 x;
1025d495d8c9Sdrh     unsigned c;
1026d495d8c9Sdrh     x = sqlite3_value_int64(argv[i]);
1027d495d8c9Sdrh     if( x<0 || x>0x10ffff ) x = 0xfffd;
1028d495d8c9Sdrh     c = (unsigned)(x & 0x1fffff);
1029fe7a5d11Sdrh     if( c<0x00080 ){
1030fe7a5d11Sdrh       *zOut++ = (u8)(c&0xFF);
1031fe7a5d11Sdrh     }else if( c<0x00800 ){
1032fe7a5d11Sdrh       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
1033fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1034fe7a5d11Sdrh     }else if( c<0x10000 ){
1035fe7a5d11Sdrh       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
1036fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1037fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1038d495d8c9Sdrh     }else{
1039fe7a5d11Sdrh       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
1040fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
1041fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1042fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1043fe7a5d11Sdrh     }                                                    \
1044d495d8c9Sdrh   }
1045*bbf483f8Sdrh   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
1046d495d8c9Sdrh }
1047d495d8c9Sdrh 
1048d495d8c9Sdrh /*
1049137c728fSdrh ** The hex() function.  Interpret the argument as a blob.  Return
1050137c728fSdrh ** a hexadecimal rendering as text.
1051137c728fSdrh */
1052137c728fSdrh static void hexFunc(
1053137c728fSdrh   sqlite3_context *context,
1054137c728fSdrh   int argc,
1055137c728fSdrh   sqlite3_value **argv
1056137c728fSdrh ){
1057137c728fSdrh   int i, n;
1058137c728fSdrh   const unsigned char *pBlob;
1059137c728fSdrh   char *zHex, *z;
1060137c728fSdrh   assert( argc==1 );
1061f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
10621f0feef8Sdrh   pBlob = sqlite3_value_blob(argv[0]);
1063137c728fSdrh   n = sqlite3_value_bytes(argv[0]);
10641f0feef8Sdrh   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
1065b1a6c3c1Sdrh   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
1066a1644fd8Sdanielk1977   if( zHex ){
1067137c728fSdrh     for(i=0; i<n; i++, pBlob++){
1068137c728fSdrh       unsigned char c = *pBlob;
1069137c728fSdrh       *(z++) = hexdigits[(c>>4)&0xf];
1070137c728fSdrh       *(z++) = hexdigits[c&0xf];
1071137c728fSdrh     }
1072137c728fSdrh     *z = 0;
1073137c728fSdrh     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
1074137c728fSdrh   }
1075a1644fd8Sdanielk1977 }
1076137c728fSdrh 
107726b6d90dSdrh /*
10788cff382eSdrh ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
10798cff382eSdrh */
10808cff382eSdrh static void zeroblobFunc(
10818cff382eSdrh   sqlite3_context *context,
10828cff382eSdrh   int argc,
10838cff382eSdrh   sqlite3_value **argv
10848cff382eSdrh ){
108598640a3fSdrh   i64 n;
108627e62dbeSdrh   sqlite3 *db = sqlite3_context_db_handle(context);
10878cff382eSdrh   assert( argc==1 );
1088f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
108998640a3fSdrh   n = sqlite3_value_int64(argv[0]);
109027e62dbeSdrh   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
109127e62dbeSdrh   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
109227e62dbeSdrh   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
109398640a3fSdrh     sqlite3_result_error_toobig(context);
109498640a3fSdrh   }else{
1095ab2f1f95Sdrh     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
10968cff382eSdrh   }
109798640a3fSdrh }
10988cff382eSdrh 
10998cff382eSdrh /*
110026b6d90dSdrh ** The replace() function.  Three arguments are all strings: call
110126b6d90dSdrh ** them A, B, and C. The result is also a string which is derived
1102f7b5496eSdrh ** from A by replacing every occurrence of B with C.  The match
110326b6d90dSdrh ** must be exact.  Collating sequences are not used.
110426b6d90dSdrh */
110526b6d90dSdrh static void replaceFunc(
110626b6d90dSdrh   sqlite3_context *context,
110726b6d90dSdrh   int argc,
110826b6d90dSdrh   sqlite3_value **argv
110926b6d90dSdrh ){
111026b6d90dSdrh   const unsigned char *zStr;        /* The input string A */
111126b6d90dSdrh   const unsigned char *zPattern;    /* The pattern string B */
111226b6d90dSdrh   const unsigned char *zRep;        /* The replacement string C */
111326b6d90dSdrh   unsigned char *zOut;              /* The output */
111426b6d90dSdrh   int nStr;                /* Size of zStr */
111526b6d90dSdrh   int nPattern;            /* Size of zPattern */
111626b6d90dSdrh   int nRep;                /* Size of zRep */
11172e6400baSdrh   i64 nOut;                /* Maximum size of zOut */
111826b6d90dSdrh   int loopLimit;           /* Last zStr[] that might match zPattern[] */
111926b6d90dSdrh   int i, j;                /* Loop counters */
112026b6d90dSdrh 
112126b6d90dSdrh   assert( argc==3 );
1122f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
112326b6d90dSdrh   zStr = sqlite3_value_text(argv[0]);
11247a521cfbSdrh   if( zStr==0 ) return;
11251f0feef8Sdrh   nStr = sqlite3_value_bytes(argv[0]);
11261f0feef8Sdrh   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
112726b6d90dSdrh   zPattern = sqlite3_value_text(argv[1]);
1128a605fe8dSdrh   if( zPattern==0 ){
11292333606eSdrh     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
11302333606eSdrh             || sqlite3_context_db_handle(context)->mallocFailed );
1131a605fe8dSdrh     return;
1132a605fe8dSdrh   }
1133a605fe8dSdrh   if( zPattern[0]==0 ){
1134a605fe8dSdrh     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
1135a605fe8dSdrh     sqlite3_result_value(context, argv[0]);
1136a605fe8dSdrh     return;
1137a605fe8dSdrh   }
11381f0feef8Sdrh   nPattern = sqlite3_value_bytes(argv[1]);
11391f0feef8Sdrh   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
114026b6d90dSdrh   zRep = sqlite3_value_text(argv[2]);
11417a521cfbSdrh   if( zRep==0 ) return;
11421f0feef8Sdrh   nRep = sqlite3_value_bytes(argv[2]);
11431f0feef8Sdrh   assert( zRep==sqlite3_value_text(argv[2]) );
11442e6400baSdrh   nOut = nStr + 1;
11452e6400baSdrh   assert( nOut<SQLITE_MAX_LENGTH );
1146b1a6c3c1Sdrh   zOut = contextMalloc(context, (i64)nOut);
11472e6400baSdrh   if( zOut==0 ){
11482e6400baSdrh     return;
114926b6d90dSdrh   }
115026b6d90dSdrh   loopLimit = nStr - nPattern;
115126b6d90dSdrh   for(i=j=0; i<=loopLimit; i++){
115226b6d90dSdrh     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
115326b6d90dSdrh       zOut[j++] = zStr[i];
115426b6d90dSdrh     }else{
11554a50aac5Sdrh       u8 *zOld;
1156bb4957f8Sdrh       sqlite3 *db = sqlite3_context_db_handle(context);
11572e6400baSdrh       nOut += nRep - nPattern;
115827e62dbeSdrh       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
115927e62dbeSdrh       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
116027e62dbeSdrh       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1161a0206bc8Sdrh         sqlite3_result_error_toobig(context);
1162b975598eSdrh         sqlite3_free(zOut);
116317374e8fSdanielk1977         return;
116417374e8fSdanielk1977       }
11654a50aac5Sdrh       zOld = zOut;
11662e6400baSdrh       zOut = sqlite3_realloc(zOut, (int)nOut);
11672e6400baSdrh       if( zOut==0 ){
1168a1644fd8Sdanielk1977         sqlite3_result_error_nomem(context);
1169b975598eSdrh         sqlite3_free(zOld);
11702e6400baSdrh         return;
11712e6400baSdrh       }
117226b6d90dSdrh       memcpy(&zOut[j], zRep, nRep);
117326b6d90dSdrh       j += nRep;
117426b6d90dSdrh       i += nPattern-1;
117526b6d90dSdrh     }
117626b6d90dSdrh   }
11772e6400baSdrh   assert( j+nStr-i+1==nOut );
117826b6d90dSdrh   memcpy(&zOut[j], &zStr[i], nStr-i);
117926b6d90dSdrh   j += nStr - i;
118026b6d90dSdrh   assert( j<=nOut );
118126b6d90dSdrh   zOut[j] = 0;
118226b6d90dSdrh   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
118326b6d90dSdrh }
118426b6d90dSdrh 
1185309b3386Sdrh /*
1186309b3386Sdrh ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
1187309b3386Sdrh ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
1188309b3386Sdrh */
1189309b3386Sdrh static void trimFunc(
1190309b3386Sdrh   sqlite3_context *context,
1191309b3386Sdrh   int argc,
1192309b3386Sdrh   sqlite3_value **argv
1193309b3386Sdrh ){
1194309b3386Sdrh   const unsigned char *zIn;         /* Input string */
1195309b3386Sdrh   const unsigned char *zCharSet;    /* Set of characters to trim */
1196309b3386Sdrh   int nIn;                          /* Number of bytes in input */
11977209c697Sdrh   int flags;                        /* 1: trimleft  2: trimright  3: trim */
1198d1e3a616Sdrh   int i;                            /* Loop counter */
11991bd10f8aSdrh   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
12001bd10f8aSdrh   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
1201d1e3a616Sdrh   int nChar;                        /* Number of characters in zCharSet */
1202d1e3a616Sdrh 
1203309b3386Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1204309b3386Sdrh     return;
1205309b3386Sdrh   }
1206309b3386Sdrh   zIn = sqlite3_value_text(argv[0]);
12077a521cfbSdrh   if( zIn==0 ) return;
12081f0feef8Sdrh   nIn = sqlite3_value_bytes(argv[0]);
12091f0feef8Sdrh   assert( zIn==sqlite3_value_text(argv[0]) );
1210309b3386Sdrh   if( argc==1 ){
1211d1e3a616Sdrh     static const unsigned char lenOne[] = { 1 };
1212a4de4532Sdanielk1977     static unsigned char * const azOne[] = { (u8*)" " };
1213d1e3a616Sdrh     nChar = 1;
12148cff382eSdrh     aLen = (u8*)lenOne;
1215bc67da48Sdanielk1977     azChar = (unsigned char **)azOne;
1216d1e3a616Sdrh     zCharSet = 0;
12177a521cfbSdrh   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
1218309b3386Sdrh     return;
1219d1e3a616Sdrh   }else{
1220d1e3a616Sdrh     const unsigned char *z;
1221d1e3a616Sdrh     for(z=zCharSet, nChar=0; *z; nChar++){
12224a919118Sdrh       SQLITE_SKIP_UTF8(z);
1223309b3386Sdrh     }
1224d1e3a616Sdrh     if( nChar>0 ){
1225b1a6c3c1Sdrh       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
1226d1e3a616Sdrh       if( azChar==0 ){
1227d1e3a616Sdrh         return;
1228d1e3a616Sdrh       }
1229d1e3a616Sdrh       aLen = (unsigned char*)&azChar[nChar];
1230d1e3a616Sdrh       for(z=zCharSet, nChar=0; *z; nChar++){
1231bc67da48Sdanielk1977         azChar[nChar] = (unsigned char *)z;
12324a919118Sdrh         SQLITE_SKIP_UTF8(z);
12333abbd39aSdrh         aLen[nChar] = (u8)(z - azChar[nChar]);
1234d1e3a616Sdrh       }
1235d1e3a616Sdrh     }
1236d1e3a616Sdrh   }
1237d1e3a616Sdrh   if( nChar>0 ){
12381fc4129dSshane     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
1239309b3386Sdrh     if( flags & 1 ){
1240d1e3a616Sdrh       while( nIn>0 ){
12411bd10f8aSdrh         int len = 0;
1242d1e3a616Sdrh         for(i=0; i<nChar; i++){
1243d1e3a616Sdrh           len = aLen[i];
124427e62dbeSdrh           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
1245d1e3a616Sdrh         }
1246d1e3a616Sdrh         if( i>=nChar ) break;
1247d1e3a616Sdrh         zIn += len;
1248d1e3a616Sdrh         nIn -= len;
1249309b3386Sdrh       }
1250309b3386Sdrh     }
1251309b3386Sdrh     if( flags & 2 ){
1252d1e3a616Sdrh       while( nIn>0 ){
12531bd10f8aSdrh         int len = 0;
1254d1e3a616Sdrh         for(i=0; i<nChar; i++){
1255d1e3a616Sdrh           len = aLen[i];
1256d1e3a616Sdrh           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
1257309b3386Sdrh         }
1258d1e3a616Sdrh         if( i>=nChar ) break;
1259d1e3a616Sdrh         nIn -= len;
1260d1e3a616Sdrh       }
1261d1e3a616Sdrh     }
1262d1e3a616Sdrh     if( zCharSet ){
1263d1e3a616Sdrh       sqlite3_free(azChar);
1264309b3386Sdrh     }
1265309b3386Sdrh   }
1266309b3386Sdrh   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
1267309b3386Sdrh }
126826b6d90dSdrh 
1269a4de4532Sdanielk1977 
12702ba3cccfSdrh /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
12712ba3cccfSdrh ** is only available if the SQLITE_SOUNDEX compile-time option is used
12722ba3cccfSdrh ** when SQLite is built.
12732ba3cccfSdrh */
1274d24cc427Sdrh #ifdef SQLITE_SOUNDEX
1275d24cc427Sdrh /*
1276d24cc427Sdrh ** Compute the soundex encoding of a word.
12772ba3cccfSdrh **
12782ba3cccfSdrh ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
12792ba3cccfSdrh ** soundex encoding of the string X.
1280d24cc427Sdrh */
1281137c728fSdrh static void soundexFunc(
1282137c728fSdrh   sqlite3_context *context,
1283137c728fSdrh   int argc,
1284137c728fSdrh   sqlite3_value **argv
1285137c728fSdrh ){
1286d24cc427Sdrh   char zResult[8];
12874c755c0fSdrh   const u8 *zIn;
1288d24cc427Sdrh   int i, j;
1289d24cc427Sdrh   static const unsigned char iCode[] = {
1290d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1291d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1292d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1293d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1294d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1295d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1296d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1297d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1298d24cc427Sdrh   };
1299d24cc427Sdrh   assert( argc==1 );
13004c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
1301bdf67e0eSdrh   if( zIn==0 ) zIn = (u8*)"";
1302dc86e2b2Sdrh   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
1303d24cc427Sdrh   if( zIn[i] ){
1304bdf67e0eSdrh     u8 prevcode = iCode[zIn[i]&0x7f];
130578ca0e7eSdanielk1977     zResult[0] = sqlite3Toupper(zIn[i]);
1306d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
1307d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
1308d24cc427Sdrh       if( code>0 ){
1309bdf67e0eSdrh         if( code!=prevcode ){
1310bdf67e0eSdrh           prevcode = code;
1311d24cc427Sdrh           zResult[j++] = code + '0';
1312d24cc427Sdrh         }
1313bdf67e0eSdrh       }else{
1314bdf67e0eSdrh         prevcode = 0;
1315bdf67e0eSdrh       }
1316d24cc427Sdrh     }
1317d24cc427Sdrh     while( j<4 ){
1318d24cc427Sdrh       zResult[j++] = '0';
1319d24cc427Sdrh     }
1320d24cc427Sdrh     zResult[j] = 0;
1321d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
1322d24cc427Sdrh   }else{
13232ba3cccfSdrh     /* IMP: R-64894-50321 The string "?000" is returned if the argument
13242ba3cccfSdrh     ** is NULL or contains no ASCII alphabetic characters. */
1325d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
1326d24cc427Sdrh   }
1327d24cc427Sdrh }
13282ba3cccfSdrh #endif /* SQLITE_SOUNDEX */
1329d24cc427Sdrh 
1330fdb83b2fSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
1331fdb83b2fSdrh /*
1332fdb83b2fSdrh ** A function that loads a shared-library extension then returns NULL.
1333fdb83b2fSdrh */
1334fdb83b2fSdrh static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
133565fd59f7Sdanielk1977   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
13367a521cfbSdrh   const char *zProc;
1337fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
1338fdb83b2fSdrh   char *zErrMsg = 0;
1339fdb83b2fSdrh 
1340fdb83b2fSdrh   if( argc==2 ){
134165fd59f7Sdanielk1977     zProc = (const char *)sqlite3_value_text(argv[1]);
13427a521cfbSdrh   }else{
13437a521cfbSdrh     zProc = 0;
1344fdb83b2fSdrh   }
13457a521cfbSdrh   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
1346fdb83b2fSdrh     sqlite3_result_error(context, zErrMsg, -1);
1347fdb83b2fSdrh     sqlite3_free(zErrMsg);
1348fdb83b2fSdrh   }
1349fdb83b2fSdrh }
1350fdb83b2fSdrh #endif
1351fdb83b2fSdrh 
135201427a62Sdanielk1977 
13530ac65892Sdrh /*
1354d3a149efSdrh ** An instance of the following structure holds the context of a
1355dd5baa95Sdrh ** sum() or avg() aggregate computation.
1356dd5baa95Sdrh */
1357dd5baa95Sdrh typedef struct SumCtx SumCtx;
1358dd5baa95Sdrh struct SumCtx {
13598c08e861Sdrh   double rSum;      /* Floating point sum */
13608c08e861Sdrh   i64 iSum;         /* Integer sum */
1361cf85a51cSdrh   i64 cnt;          /* Number of elements summed */
13628c08e861Sdrh   u8 overflow;      /* True if integer overflow seen */
13638c08e861Sdrh   u8 approx;        /* True if non-integer value was input to the sum */
1364dd5baa95Sdrh };
1365dd5baa95Sdrh 
1366dd5baa95Sdrh /*
1367a97fdd3bSdrh ** Routines used to compute the sum, average, and total.
1368a97fdd3bSdrh **
1369a97fdd3bSdrh ** The SUM() function follows the (broken) SQL standard which means
1370a97fdd3bSdrh ** that it returns NULL if it sums over no inputs.  TOTAL returns
1371a97fdd3bSdrh ** 0.0 in that case.  In addition, TOTAL always returns a float where
1372a97fdd3bSdrh ** SUM might return an integer if it never encounters a floating point
1373c806d857Sdrh ** value.  TOTAL never fails, but SUM might through an exception if
1374c806d857Sdrh ** it overflows an integer.
1375dd5baa95Sdrh */
13760ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1377dd5baa95Sdrh   SumCtx *p;
13783d1d95e6Sdrh   int type;
13793f219f46Sdrh   assert( argc==1 );
1380f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
13814f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
138229d72108Sdrh   type = sqlite3_value_numeric_type(argv[0]);
13833d1d95e6Sdrh   if( p && type!=SQLITE_NULL ){
1384739105c7Sdrh     p->cnt++;
138529d72108Sdrh     if( type==SQLITE_INTEGER ){
13868c08e861Sdrh       i64 v = sqlite3_value_int64(argv[0]);
13878c08e861Sdrh       p->rSum += v;
1388158b9cb9Sdrh       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
1389158b9cb9Sdrh         p->overflow = 1;
139029d72108Sdrh       }
139129d72108Sdrh     }else{
13928c08e861Sdrh       p->rSum += sqlite3_value_double(argv[0]);
139329d72108Sdrh       p->approx = 1;
13943f219f46Sdrh     }
1395739105c7Sdrh   }
1396dd5baa95Sdrh }
13970ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
1398dd5baa95Sdrh   SumCtx *p;
1399abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1400c2bd913aSdrh   if( p && p->cnt>0 ){
14018c08e861Sdrh     if( p->overflow ){
14028c08e861Sdrh       sqlite3_result_error(context,"integer overflow",-1);
14038c08e861Sdrh     }else if( p->approx ){
14048c08e861Sdrh       sqlite3_result_double(context, p->rSum);
1405c2bd913aSdrh     }else{
14068c08e861Sdrh       sqlite3_result_int64(context, p->iSum);
14073d1d95e6Sdrh     }
1408dd5baa95Sdrh   }
1409c2bd913aSdrh }
14100ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
1411dd5baa95Sdrh   SumCtx *p;
1412abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1413739105c7Sdrh   if( p && p->cnt>0 ){
14148c08e861Sdrh     sqlite3_result_double(context, p->rSum/(double)p->cnt);
1415dd5baa95Sdrh   }
1416dd5baa95Sdrh }
1417a97fdd3bSdrh static void totalFinalize(sqlite3_context *context){
1418a97fdd3bSdrh   SumCtx *p;
1419a97fdd3bSdrh   p = sqlite3_aggregate_context(context, 0);
1420fbd60f82Sshane   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1421fbd60f82Sshane   sqlite3_result_double(context, p ? p->rSum : (double)0);
1422a97fdd3bSdrh }
1423dd5baa95Sdrh 
1424dd5baa95Sdrh /*
14250bce8354Sdrh ** The following structure keeps track of state information for the
14260bce8354Sdrh ** count() aggregate function.
14270bce8354Sdrh */
14280bce8354Sdrh typedef struct CountCtx CountCtx;
14290bce8354Sdrh struct CountCtx {
1430fc6ad39cSdrh   i64 n;
14310bce8354Sdrh };
1432dd5baa95Sdrh 
14330bce8354Sdrh /*
14340bce8354Sdrh ** Routines to implement the count() aggregate function.
14350bce8354Sdrh */
14360ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
14370bce8354Sdrh   CountCtx *p;
14384f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
14399c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
14400bce8354Sdrh     p->n++;
14410bce8354Sdrh   }
14422e79c3d5Sdrh 
1443d3264c7cSdrh #ifndef SQLITE_OMIT_DEPRECATED
14442e79c3d5Sdrh   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
14452e79c3d5Sdrh   ** sure it still operates correctly, verify that its count agrees with our
14462e79c3d5Sdrh   ** internal count when using count(*) and when the total count can be
14472e79c3d5Sdrh   ** expressed as a 32-bit integer. */
14482e79c3d5Sdrh   assert( argc==1 || p==0 || p->n>0x7fffffff
14492e79c3d5Sdrh           || p->n==sqlite3_aggregate_count(context) );
1450d3264c7cSdrh #endif
14510bce8354Sdrh }
14520ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
14530bce8354Sdrh   CountCtx *p;
1454abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1455fc6ad39cSdrh   sqlite3_result_int64(context, p ? p->n : 0);
14560bce8354Sdrh }
14570bce8354Sdrh 
14580bce8354Sdrh /*
14590bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
14600bce8354Sdrh */
146162c14b34Sdanielk1977 static void minmaxStep(
146262c14b34Sdanielk1977   sqlite3_context *context,
146362c14b34Sdanielk1977   int NotUsed,
146462c14b34Sdanielk1977   sqlite3_value **argv
146562c14b34Sdanielk1977 ){
146688208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
14679eb516c0Sdrh   Mem *pBest;
146862c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
14699eb516c0Sdrh 
14709eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
14713aeab9e4Sdanielk1977   if( !pBest ) return;
1472268380caSdrh 
147394a6d998Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
147494a6d998Sdrh     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
147594a6d998Sdrh   }else if( pBest->flags ){
14769eb516c0Sdrh     int max;
14779eb516c0Sdrh     int cmp;
1478dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
14797e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
14807e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
14817e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
14827e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
14837e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
14847e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
14857e18c259Sdanielk1977     ** aggregate, or 0 for min().
14867e18c259Sdanielk1977     */
1487309b3386Sdrh     max = sqlite3_user_data(context)!=0;
1488dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
148988208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
1490b21c8cd4Sdrh       sqlite3VdbeMemCopy(pBest, pArg);
14917a95789cSdrh     }else{
14927a95789cSdrh       sqlite3SkipAccumulatorLoad(context);
149388208050Sdanielk1977     }
14940bce8354Sdrh   }else{
1495b21c8cd4Sdrh     sqlite3VdbeMemCopy(pBest, pArg);
14960bce8354Sdrh   }
14970bce8354Sdrh }
14980ae8b831Sdanielk1977 static void minMaxFinalize(sqlite3_context *context){
149988208050Sdanielk1977   sqlite3_value *pRes;
1500abfcea25Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
1501abfcea25Sdrh   if( pRes ){
150294a6d998Sdrh     if( pRes->flags ){
1503f4479501Sdrh       sqlite3_result_value(context, pRes);
15040bce8354Sdrh     }
1505b20e56b4Sdanielk1977     sqlite3VdbeMemRelease(pRes);
15060bce8354Sdrh   }
1507abfcea25Sdrh }
1508dd5baa95Sdrh 
1509b0689696Sdrh /*
1510b0689696Sdrh ** group_concat(EXPR, ?SEPARATOR?)
1511b0689696Sdrh */
1512b0689696Sdrh static void groupConcatStep(
1513b0689696Sdrh   sqlite3_context *context,
1514b0689696Sdrh   int argc,
1515b0689696Sdrh   sqlite3_value **argv
1516b0689696Sdrh ){
1517b0689696Sdrh   const char *zVal;
1518ade86483Sdrh   StrAccum *pAccum;
1519b0689696Sdrh   const char *zSep;
152007d3117aSdrh   int nVal, nSep;
152107d3117aSdrh   assert( argc==1 || argc==2 );
152207d3117aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
1523ade86483Sdrh   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
1524ade86483Sdrh 
1525ade86483Sdrh   if( pAccum ){
1526bb4957f8Sdrh     sqlite3 *db = sqlite3_context_db_handle(context);
15278bfd7190Sdrh     int firstTerm = pAccum->useMalloc==0;
1528b975598eSdrh     pAccum->useMalloc = 2;
1529bb4957f8Sdrh     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
15308bfd7190Sdrh     if( !firstTerm ){
153107d3117aSdrh       if( argc==2 ){
153207d3117aSdrh         zSep = (char*)sqlite3_value_text(argv[1]);
153307d3117aSdrh         nSep = sqlite3_value_bytes(argv[1]);
1534b0689696Sdrh       }else{
1535b0689696Sdrh         zSep = ",";
1536ade86483Sdrh         nSep = 1;
1537b0689696Sdrh       }
1538a9ab481fSdrh       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
1539b0689696Sdrh     }
154007d3117aSdrh     zVal = (char*)sqlite3_value_text(argv[0]);
154107d3117aSdrh     nVal = sqlite3_value_bytes(argv[0]);
15428009c9b4Sdrh     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
1543b0689696Sdrh   }
1544b0689696Sdrh }
1545b0689696Sdrh static void groupConcatFinalize(sqlite3_context *context){
1546ade86483Sdrh   StrAccum *pAccum;
1547ade86483Sdrh   pAccum = sqlite3_aggregate_context(context, 0);
1548ade86483Sdrh   if( pAccum ){
1549b49bc86aSdrh     if( pAccum->accError==STRACCUM_TOOBIG ){
1550ade86483Sdrh       sqlite3_result_error_toobig(context);
1551b49bc86aSdrh     }else if( pAccum->accError==STRACCUM_NOMEM ){
1552ade86483Sdrh       sqlite3_result_error_nomem(context);
1553ade86483Sdrh     }else{
1554ade86483Sdrh       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
1555ade86483Sdrh                           sqlite3_free);
1556b0689696Sdrh     }
1557b0689696Sdrh   }
1558ade86483Sdrh }
15594e5ffc5fSdrh 
1560d3a149efSdrh /*
1561a4741840Sdrh ** This routine does per-connection function registration.  Most
1562a4741840Sdrh ** of the built-in functions above are part of the global function set.
1563a4741840Sdrh ** This routine only deals with those that are not global.
1564dc04c583Sdrh */
15659bb575fdSdrh void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
1566832a58a6Sdanielk1977   int rc = sqlite3_overload_function(db, "MATCH", 2);
1567832a58a6Sdanielk1977   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
1568832a58a6Sdanielk1977   if( rc==SQLITE_NOMEM ){
15691e536953Sdanielk1977     db->mallocFailed = 1;
1570832a58a6Sdanielk1977   }
1571832a58a6Sdanielk1977 }
157255ef4d97Sdrh 
157355ef4d97Sdrh /*
157455ef4d97Sdrh ** Set the LIKEOPT flag on the 2-argument function with the given name.
157555ef4d97Sdrh */
15761bd10f8aSdrh static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
157755ef4d97Sdrh   FuncDef *pDef;
1578ea678832Sdrh   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
1579ea678832Sdrh                              2, SQLITE_UTF8, 0);
1580d27135adSdrh   if( ALWAYS(pDef) ){
1581d36e1041Sdrh     pDef->funcFlags |= flagVal;
158255ef4d97Sdrh   }
158355ef4d97Sdrh }
158455ef4d97Sdrh 
158555ef4d97Sdrh /*
158655ef4d97Sdrh ** Register the built-in LIKE and GLOB functions.  The caseSensitive
158755ef4d97Sdrh ** parameter determines whether or not the LIKE operator is case
158855ef4d97Sdrh ** sensitive.  GLOB is always case sensitive.
158955ef4d97Sdrh */
159055ef4d97Sdrh void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
159155ef4d97Sdrh   struct compareInfo *pInfo;
159255ef4d97Sdrh   if( caseSensitive ){
159355ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoAlt;
159455ef4d97Sdrh   }else{
159555ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoNorm;
159655ef4d97Sdrh   }
1597901e994bSdrh   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
1598901e994bSdrh   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
1599901e994bSdrh   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
1600d2199f0fSdan       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
1601d64fe2f3Sdrh   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1602d64fe2f3Sdrh   setLikeOptFlag(db, "like",
1603d64fe2f3Sdrh       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
160455ef4d97Sdrh }
160555ef4d97Sdrh 
160655ef4d97Sdrh /*
160755ef4d97Sdrh ** pExpr points to an expression which implements a function.  If
160855ef4d97Sdrh ** it is appropriate to apply the LIKE optimization to that function
160955ef4d97Sdrh ** then set aWc[0] through aWc[2] to the wildcard characters and
161055ef4d97Sdrh ** return TRUE.  If the function is not a LIKE-style function then
161155ef4d97Sdrh ** return FALSE.
161255ef4d97Sdrh */
1613d64fe2f3Sdrh int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
161455ef4d97Sdrh   FuncDef *pDef;
16156ab3a2ecSdanielk1977   if( pExpr->op!=TK_FUNCTION
16166ab3a2ecSdanielk1977    || !pExpr->x.pList
16176ab3a2ecSdanielk1977    || pExpr->x.pList->nExpr!=2
16186ab3a2ecSdanielk1977   ){
161955ef4d97Sdrh     return 0;
162055ef4d97Sdrh   }
16216ab3a2ecSdanielk1977   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
162233e619fcSdrh   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
162333e619fcSdrh                              sqlite3Strlen30(pExpr->u.zToken),
1624b7916a78Sdrh                              2, SQLITE_UTF8, 0);
1625d36e1041Sdrh   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
162655ef4d97Sdrh     return 0;
162755ef4d97Sdrh   }
162855ef4d97Sdrh 
162955ef4d97Sdrh   /* The memcpy() statement assumes that the wildcard characters are
163055ef4d97Sdrh   ** the first three statements in the compareInfo structure.  The
163155ef4d97Sdrh   ** asserts() that follow verify that assumption
163255ef4d97Sdrh   */
163355ef4d97Sdrh   memcpy(aWc, pDef->pUserData, 3);
163455ef4d97Sdrh   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
163555ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
163655ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1637d36e1041Sdrh   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
163855ef4d97Sdrh   return 1;
1639dc04c583Sdrh }
16408c0a791aSdanielk1977 
164193ce741bSdanielk1977 /*
164260ec914cSpeter.d.reid ** All of the FuncDef structures in the aBuiltinFunc[] array above
164393ce741bSdanielk1977 ** to the global function hash table.  This occurs at start-time (as
164493ce741bSdanielk1977 ** a consequence of calling sqlite3_initialize()).
164593ce741bSdanielk1977 **
164693ce741bSdanielk1977 ** After this routine runs
164793ce741bSdanielk1977 */
164893ce741bSdanielk1977 void sqlite3RegisterGlobalFunctions(void){
16498c0a791aSdanielk1977   /*
1650777c5386Sdrh   ** The following array holds FuncDef structures for all of the functions
1651777c5386Sdrh   ** defined in this file.
16528c0a791aSdanielk1977   **
1653777c5386Sdrh   ** The array cannot be constant since changes are made to the
1654777c5386Sdrh   ** FuncDef.pHash elements at start-time.  The elements of this array
1655777c5386Sdrh   ** are read-only after initialization is complete.
16568c0a791aSdanielk1977   */
165793ce741bSdanielk1977   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
16588c0a791aSdanielk1977     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
16598c0a791aSdanielk1977     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
16608c0a791aSdanielk1977     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
16618c0a791aSdanielk1977     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
16628c0a791aSdanielk1977     FUNCTION(trim,               1, 3, 0, trimFunc         ),
16638c0a791aSdanielk1977     FUNCTION(trim,               2, 3, 0, trimFunc         ),
16648c0a791aSdanielk1977     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
16658c0a791aSdanielk1977     FUNCTION(min,                0, 0, 1, 0                ),
16668c0a791aSdanielk1977     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
16678c0a791aSdanielk1977     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
16688c0a791aSdanielk1977     FUNCTION(max,                0, 1, 1, 0                ),
16698c0a791aSdanielk1977     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
1670a748fdccSdrh     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
1671a748fdccSdrh     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
1672d55e0729Sdrh     FUNCTION(instr,              2, 0, 0, instrFunc        ),
16738c0a791aSdanielk1977     FUNCTION(substr,             2, 0, 0, substrFunc       ),
16748c0a791aSdanielk1977     FUNCTION(substr,             3, 0, 0, substrFunc       ),
1675a5c1416dSdrh     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
1676d495d8c9Sdrh     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
1677d495d8c9Sdrh     FUNCTION(char,              -1, 0, 0, charFunc         ),
16788c0a791aSdanielk1977     FUNCTION(abs,                1, 0, 0, absFunc          ),
1679fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
16808c0a791aSdanielk1977     FUNCTION(round,              1, 0, 0, roundFunc        ),
16818c0a791aSdanielk1977     FUNCTION(round,              2, 0, 0, roundFunc        ),
1682fbd60f82Sshane #endif
16838c0a791aSdanielk1977     FUNCTION(upper,              1, 0, 0, upperFunc        ),
16848c0a791aSdanielk1977     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
16858c0a791aSdanielk1977     FUNCTION(coalesce,           1, 0, 0, 0                ),
16868c0a791aSdanielk1977     FUNCTION(coalesce,           0, 0, 0, 0                ),
1687cca9f3d2Sdrh     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
16888c0a791aSdanielk1977     FUNCTION(hex,                1, 0, 0, hexFunc          ),
1689cca9f3d2Sdrh     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
1690cca9f3d2Sdrh     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
1691aae0f9e4Sdrh     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
169203202a97Sdrh     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
1693b1fba286Sdrh     VFUNCTION(random,            0, 0, 0, randomFunc       ),
1694b1fba286Sdrh     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
16958c0a791aSdanielk1977     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
16968c0a791aSdanielk1977     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
169747baebc2Sdrh     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
1698840561f2Sdrh     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
1699dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17008bb76d39Sdrh     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
17018bb76d39Sdrh     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
1702dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17038c0a791aSdanielk1977     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
1704b1fba286Sdrh     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
1705b1fba286Sdrh     VFUNCTION(changes,           0, 0, 0, changes          ),
1706b1fba286Sdrh     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
17078c0a791aSdanielk1977     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
17088c0a791aSdanielk1977     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
17098c0a791aSdanielk1977   #ifdef SQLITE_SOUNDEX
17108c0a791aSdanielk1977     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
17118c0a791aSdanielk1977   #endif
17128c0a791aSdanielk1977   #ifndef SQLITE_OMIT_LOAD_EXTENSION
17138c0a791aSdanielk1977     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
17148c0a791aSdanielk1977     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
17158c0a791aSdanielk1977   #endif
17168c0a791aSdanielk1977     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
17178c0a791aSdanielk1977     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
17188c0a791aSdanielk1977     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
1719a5533162Sdanielk1977  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
1720d36e1041Sdrh     {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
17218c0a791aSdanielk1977     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
172207d3117aSdrh     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
172307d3117aSdrh     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
17248c0a791aSdanielk1977 
17258c0a791aSdanielk1977     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
17268c0a791aSdanielk1977   #ifdef SQLITE_CASE_SENSITIVE_LIKE
17278c0a791aSdanielk1977     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
17288c0a791aSdanielk1977     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
17298c0a791aSdanielk1977   #else
17308c0a791aSdanielk1977     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
17318c0a791aSdanielk1977     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
17328c0a791aSdanielk1977   #endif
17338c0a791aSdanielk1977   };
17348c0a791aSdanielk1977 
173570a8ca3cSdrh   int i;
1736075c23afSdanielk1977   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
1737106cee54Sdrh   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
173893ce741bSdanielk1977 
173993ce741bSdanielk1977   for(i=0; i<ArraySize(aBuiltinFunc); i++){
174093ce741bSdanielk1977     sqlite3FuncDefInsert(pHash, &aFunc[i]);
174170a8ca3cSdrh   }
1742777c5386Sdrh   sqlite3RegisterDateTimeFunctions();
1743545f587fSdrh #ifndef SQLITE_OMIT_ALTERTABLE
1744545f587fSdrh   sqlite3AlterFunctions();
1745545f587fSdrh #endif
17460106e378Sdan #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
17470106e378Sdan   sqlite3AnalyzeFunctions();
17480106e378Sdan #endif
174970a8ca3cSdrh }
1750