xref: /sqlite-3.40.0/src/func.c (revision 683b0fff)
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){
25a9e03b1bSdrh   VdbeOp *pOp;
26a9e03b1bSdrh   assert( context->pVdbe!=0 );
27a9e03b1bSdrh   pOp = &context->pVdbe->aOp[context->iOp-1];
28a15cc47fSdrh   assert( pOp->opcode==OP_CollSeq );
29a15cc47fSdrh   assert( pOp->p4type==P4_COLLSEQ );
30a15cc47fSdrh   return pOp->p4.pColl;
31dc1bdc4fSdanielk1977 }
32dc1bdc4fSdanielk1977 
330bce8354Sdrh /*
347a95789cSdrh ** Indicate that the accumulator load should be skipped on this
357a95789cSdrh ** iteration of the aggregate loop.
367a95789cSdrh */
377a95789cSdrh static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
3821d59784Sdrh   assert( context->isError<=0 );
3921d59784Sdrh   context->isError = -1;
407a95789cSdrh   context->skipFlag = 1;
417a95789cSdrh }
427a95789cSdrh 
437a95789cSdrh /*
440bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
450bce8354Sdrh */
46f9b596ebSdrh static void minmaxFunc(
47f9b596ebSdrh   sqlite3_context *context,
48f9b596ebSdrh   int argc,
49f9b596ebSdrh   sqlite3_value **argv
50f9b596ebSdrh ){
510bce8354Sdrh   int i;
52268380caSdrh   int mask;    /* 0 for min() or 0xffffffff for max() */
53f9b596ebSdrh   int iBest;
54dc1bdc4fSdanielk1977   CollSeq *pColl;
550bce8354Sdrh 
5665595cd6Sdrh   assert( argc>1 );
57c44af71cSdrh   mask = sqlite3_user_data(context)==0 ? 0 : -1;
58dc1bdc4fSdanielk1977   pColl = sqlite3GetFuncCollSeq(context);
59dc1bdc4fSdanielk1977   assert( pColl );
60c572ef7fSdanielk1977   assert( mask==-1 || mask==0 );
61f9b596ebSdrh   iBest = 0;
629c054830Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63f9b596ebSdrh   for(i=1; i<argc; i++){
649c054830Sdrh     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
65dc1bdc4fSdanielk1977     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
6665595cd6Sdrh       testcase( mask==0 );
67f9b596ebSdrh       iBest = i;
680bce8354Sdrh     }
690bce8354Sdrh   }
70f4479501Sdrh   sqlite3_result_value(context, argv[iBest]);
710bce8354Sdrh }
720bce8354Sdrh 
73268380caSdrh /*
74268380caSdrh ** Return the type of the argument.
75268380caSdrh */
76f9b596ebSdrh static void typeofFunc(
77f9b596ebSdrh   sqlite3_context *context,
7862c14b34Sdanielk1977   int NotUsed,
79f9b596ebSdrh   sqlite3_value **argv
80f9b596ebSdrh ){
819d8e401cSdrh   static const char *azType[] = { "integer", "real", "text", "blob", "null" };
829d8e401cSdrh   int i = sqlite3_value_type(argv[0]) - 1;
8362c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
849d8e401cSdrh   assert( i>=0 && i<ArraySize(azType) );
859d8e401cSdrh   assert( SQLITE_INTEGER==1 );
869d8e401cSdrh   assert( SQLITE_FLOAT==2 );
879d8e401cSdrh   assert( SQLITE_TEXT==3 );
889d8e401cSdrh   assert( SQLITE_BLOB==4 );
899d8e401cSdrh   assert( SQLITE_NULL==5 );
903cef3649Sdrh   /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
913cef3649Sdrh   ** the datatype code for the initial datatype of the sqlite3_value object
923cef3649Sdrh   ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
933cef3649Sdrh   ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
949d8e401cSdrh   sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
950bce8354Sdrh }
960bce8354Sdrh 
975708d2deSdrh 
985708d2deSdrh /*
990bce8354Sdrh ** Implementation of the length() function
1000bce8354Sdrh */
101f9b596ebSdrh static void lengthFunc(
102f9b596ebSdrh   sqlite3_context *context,
103f9b596ebSdrh   int argc,
104f9b596ebSdrh   sqlite3_value **argv
105f9b596ebSdrh ){
1060bce8354Sdrh   assert( argc==1 );
107f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
108f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1099c054830Sdrh     case SQLITE_BLOB:
1109c054830Sdrh     case SQLITE_INTEGER:
1119c054830Sdrh     case SQLITE_FLOAT: {
112f4479501Sdrh       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
113f9b596ebSdrh       break;
114f9b596ebSdrh     }
1159c054830Sdrh     case SQLITE_TEXT: {
1162646da7eSdrh       const unsigned char *z = sqlite3_value_text(argv[0]);
1177ea3469eSdrh       const unsigned char *z0;
1187ea3469eSdrh       unsigned char c;
1197a521cfbSdrh       if( z==0 ) return;
1207ea3469eSdrh       z0 = z;
1217ea3469eSdrh       while( (c = *z)!=0 ){
1227ea3469eSdrh         z++;
1237ea3469eSdrh         if( c>=0xc0 ){
1247ea3469eSdrh           while( (*z & 0xc0)==0x80 ){ z++; z0++; }
1254a919118Sdrh         }
1267ea3469eSdrh       }
1277ea3469eSdrh       sqlite3_result_int(context, (int)(z-z0));
128f9b596ebSdrh       break;
129f9b596ebSdrh     }
130f9b596ebSdrh     default: {
131f9b596ebSdrh       sqlite3_result_null(context);
132f9b596ebSdrh       break;
133f9b596ebSdrh     }
134f9b596ebSdrh   }
1350bce8354Sdrh }
1360bce8354Sdrh 
1370bce8354Sdrh /*
1382ba3cccfSdrh ** Implementation of the abs() function.
1392ba3cccfSdrh **
1402ba3cccfSdrh ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
1412ba3cccfSdrh ** the numeric argument X.
1420bce8354Sdrh */
1430ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1440bce8354Sdrh   assert( argc==1 );
145f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
146f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1479c054830Sdrh     case SQLITE_INTEGER: {
148f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
14952fc849aSdrh       if( iVal<0 ){
150693e6719Sdrh         if( iVal==SMALLEST_INT64 ){
151eb091cdfSdrh           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
152eb091cdfSdrh           ** then abs(X) throws an integer overflow error since there is no
1532ba3cccfSdrh           ** equivalent positive 64-bit two complement value. */
15452fc849aSdrh           sqlite3_result_error(context, "integer overflow", -1);
15552fc849aSdrh           return;
15652fc849aSdrh         }
15752fc849aSdrh         iVal = -iVal;
15852fc849aSdrh       }
159f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
160f9b596ebSdrh       break;
161f9b596ebSdrh     }
1629c054830Sdrh     case SQLITE_NULL: {
1632ba3cccfSdrh       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
164f9b596ebSdrh       sqlite3_result_null(context);
165f9b596ebSdrh       break;
166f9b596ebSdrh     }
167f9b596ebSdrh     default: {
1682ba3cccfSdrh       /* Because sqlite3_value_double() returns 0.0 if the argument is not
1692ba3cccfSdrh       ** something that can be converted into a number, we have:
170643091f0Sdrh       ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
171643091f0Sdrh       ** that cannot be converted to a numeric value.
1722ba3cccfSdrh       */
173f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
17452fc849aSdrh       if( rVal<0 ) rVal = -rVal;
175f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
176f9b596ebSdrh       break;
177f9b596ebSdrh     }
178f9b596ebSdrh   }
1790bce8354Sdrh }
1800bce8354Sdrh 
1810bce8354Sdrh /*
182d55e0729Sdrh ** Implementation of the instr() function.
183d55e0729Sdrh **
184d55e0729Sdrh ** instr(haystack,needle) finds the first occurrence of needle
185d55e0729Sdrh ** in haystack and returns the number of previous characters plus 1,
186d55e0729Sdrh ** or 0 if needle does not occur within haystack.
187d55e0729Sdrh **
188d55e0729Sdrh ** If both haystack and needle are BLOBs, then the result is one more than
189d55e0729Sdrh ** the number of bytes in haystack prior to the first occurrence of needle,
190d55e0729Sdrh ** or 0 if needle never occurs in haystack.
191d55e0729Sdrh */
192d55e0729Sdrh static void instrFunc(
193d55e0729Sdrh   sqlite3_context *context,
194d55e0729Sdrh   int argc,
195d55e0729Sdrh   sqlite3_value **argv
196d55e0729Sdrh ){
197d55e0729Sdrh   const unsigned char *zHaystack;
198d55e0729Sdrh   const unsigned char *zNeedle;
199d55e0729Sdrh   int nHaystack;
200d55e0729Sdrh   int nNeedle;
201d55e0729Sdrh   int typeHaystack, typeNeedle;
202d55e0729Sdrh   int N = 1;
203d55e0729Sdrh   int isText;
204d55e0729Sdrh 
20568c804b9Sdrh   UNUSED_PARAMETER(argc);
206d55e0729Sdrh   typeHaystack = sqlite3_value_type(argv[0]);
207d55e0729Sdrh   typeNeedle = sqlite3_value_type(argv[1]);
208d55e0729Sdrh   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
209d55e0729Sdrh   nHaystack = sqlite3_value_bytes(argv[0]);
210d55e0729Sdrh   nNeedle = sqlite3_value_bytes(argv[1]);
211895decf6Sdan   if( nNeedle>0 ){
212d55e0729Sdrh     if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
213d55e0729Sdrh       zHaystack = sqlite3_value_blob(argv[0]);
214d55e0729Sdrh       zNeedle = sqlite3_value_blob(argv[1]);
215d55e0729Sdrh       isText = 0;
216d55e0729Sdrh     }else{
217d55e0729Sdrh       zHaystack = sqlite3_value_text(argv[0]);
218d55e0729Sdrh       zNeedle = sqlite3_value_text(argv[1]);
219d55e0729Sdrh       isText = 1;
220d55e0729Sdrh     }
221b30574bcSdrh     if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
222d55e0729Sdrh     while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
223d55e0729Sdrh       N++;
224d55e0729Sdrh       do{
225d55e0729Sdrh         nHaystack--;
226d55e0729Sdrh         zHaystack++;
227d55e0729Sdrh       }while( isText && (zHaystack[0]&0xc0)==0x80 );
228d55e0729Sdrh     }
229d55e0729Sdrh     if( nNeedle>nHaystack ) N = 0;
230895decf6Sdan   }
231d55e0729Sdrh   sqlite3_result_int(context, N);
232d55e0729Sdrh }
233d55e0729Sdrh 
234d55e0729Sdrh /*
235a5c1416dSdrh ** Implementation of the printf() function.
236a5c1416dSdrh */
237a5c1416dSdrh static void printfFunc(
238a5c1416dSdrh   sqlite3_context *context,
239a5c1416dSdrh   int argc,
240a5c1416dSdrh   sqlite3_value **argv
241a5c1416dSdrh ){
242a5c1416dSdrh   PrintfArguments x;
243a5c1416dSdrh   StrAccum str;
244a5c1416dSdrh   const char *zFormat;
245a5c1416dSdrh   int n;
246c0490572Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
247a5c1416dSdrh 
248a5c1416dSdrh   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
249a5c1416dSdrh     x.nArg = argc-1;
250a5c1416dSdrh     x.nUsed = 0;
251a5c1416dSdrh     x.apArg = argv+1;
252c0490572Sdrh     sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
2535f4a686fSdrh     str.printfFlags = SQLITE_PRINTF_SQLFUNC;
2540cdbe1aeSdrh     sqlite3_str_appendf(&str, zFormat, &x);
255a5c1416dSdrh     n = str.nChar;
256a5c1416dSdrh     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
257a5c1416dSdrh                         SQLITE_DYNAMIC);
258a5c1416dSdrh   }
259a5c1416dSdrh }
260a5c1416dSdrh 
261a5c1416dSdrh /*
262f764e6fcSdrh ** Implementation of the substr() function.
263f764e6fcSdrh **
264f764e6fcSdrh ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
265f764e6fcSdrh ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
266f764e6fcSdrh ** of x.  If x is text, then we actually count UTF-8 characters.
267f764e6fcSdrh ** If x is a blob, then we count bytes.
268f764e6fcSdrh **
269f764e6fcSdrh ** If p1 is negative, then we begin abs(p1) from the end of x[].
270779b8f12Sshaneh **
271f7b5496eSdrh ** If p2 is negative, return the p2 characters preceding p1.
2720bce8354Sdrh */
273f9b596ebSdrh static void substrFunc(
274f9b596ebSdrh   sqlite3_context *context,
275f9b596ebSdrh   int argc,
276f9b596ebSdrh   sqlite3_value **argv
277f9b596ebSdrh ){
2782646da7eSdrh   const unsigned char *z;
2792646da7eSdrh   const unsigned char *z2;
280023ae03aSdrh   int len;
281f764e6fcSdrh   int p0type;
282023ae03aSdrh   i64 p1, p2;
28365595cd6Sdrh   int negP2 = 0;
284f9b596ebSdrh 
28564f31519Sdrh   assert( argc==3 || argc==2 );
2868198d254Sdrh   if( sqlite3_value_type(argv[1])==SQLITE_NULL
2878198d254Sdrh    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
2888198d254Sdrh   ){
2898198d254Sdrh     return;
2908198d254Sdrh   }
291f764e6fcSdrh   p0type = sqlite3_value_type(argv[0]);
2924adc4cb9Sdrh   p1 = sqlite3_value_int(argv[1]);
293f764e6fcSdrh   if( p0type==SQLITE_BLOB ){
294f764e6fcSdrh     len = sqlite3_value_bytes(argv[0]);
295f764e6fcSdrh     z = sqlite3_value_blob(argv[0]);
296f764e6fcSdrh     if( z==0 ) return;
2971f0feef8Sdrh     assert( len==sqlite3_value_bytes(argv[0]) );
298f764e6fcSdrh   }else{
2994f26d6c4Sdrh     z = sqlite3_value_text(argv[0]);
3000bce8354Sdrh     if( z==0 ) return;
3014a919118Sdrh     len = 0;
3024adc4cb9Sdrh     if( p1<0 ){
3034a919118Sdrh       for(z2=z; *z2; len++){
3044a919118Sdrh         SQLITE_SKIP_UTF8(z2);
3054a919118Sdrh       }
306f764e6fcSdrh     }
3074adc4cb9Sdrh   }
308883ad049Sdrh #ifdef SQLITE_SUBSTR_COMPATIBILITY
309883ad049Sdrh   /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
310883ad049Sdrh   ** as substr(X,1,N) - it returns the first N characters of X.  This
311883ad049Sdrh   ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
312883ad049Sdrh   ** from 2009-02-02 for compatibility of applications that exploited the
313883ad049Sdrh   ** old buggy behavior. */
314883ad049Sdrh   if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
315883ad049Sdrh #endif
31664f31519Sdrh   if( argc==3 ){
31751ad0ecdSdanielk1977     p2 = sqlite3_value_int(argv[2]);
31865595cd6Sdrh     if( p2<0 ){
31965595cd6Sdrh       p2 = -p2;
32065595cd6Sdrh       negP2 = 1;
32165595cd6Sdrh     }
32264f31519Sdrh   }else{
323bb4957f8Sdrh     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
32464f31519Sdrh   }
3250bce8354Sdrh   if( p1<0 ){
32689425d5eSdrh     p1 += len;
327653bc759Sdrh     if( p1<0 ){
328653bc759Sdrh       p2 += p1;
32965595cd6Sdrh       if( p2<0 ) p2 = 0;
330653bc759Sdrh       p1 = 0;
331653bc759Sdrh     }
3320bce8354Sdrh   }else if( p1>0 ){
3330bce8354Sdrh     p1--;
33465595cd6Sdrh   }else if( p2>0 ){
33565595cd6Sdrh     p2--;
3360bce8354Sdrh   }
33765595cd6Sdrh   if( negP2 ){
33865595cd6Sdrh     p1 -= p2;
3394e79c594Sdrh     if( p1<0 ){
3404e79c594Sdrh       p2 += p1;
3414e79c594Sdrh       p1 = 0;
3424e79c594Sdrh     }
3434e79c594Sdrh   }
34465595cd6Sdrh   assert( p1>=0 && p2>=0 );
345f764e6fcSdrh   if( p0type!=SQLITE_BLOB ){
3464a919118Sdrh     while( *z && p1 ){
3474a919118Sdrh       SQLITE_SKIP_UTF8(z);
3484a919118Sdrh       p1--;
3490bce8354Sdrh     }
3504a919118Sdrh     for(z2=z; *z2 && p2; p2--){
3514a919118Sdrh       SQLITE_SKIP_UTF8(z2);
3520bce8354Sdrh     }
353bbf483f8Sdrh     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
354bbf483f8Sdrh                           SQLITE_UTF8);
355f764e6fcSdrh   }else{
3564adc4cb9Sdrh     if( p1+p2>len ){
3574adc4cb9Sdrh       p2 = len-p1;
3584adc4cb9Sdrh       if( p2<0 ) p2 = 0;
3594adc4cb9Sdrh     }
360bbf483f8Sdrh     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
361f764e6fcSdrh   }
3620bce8354Sdrh }
3630bce8354Sdrh 
3640bce8354Sdrh /*
3650bce8354Sdrh ** Implementation of the round() function
3660bce8354Sdrh */
367fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
3680ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
36951ad0ecdSdanielk1977   int n = 0;
3700bce8354Sdrh   double r;
37150d654daSdrh   char *zBuf;
3720bce8354Sdrh   assert( argc==1 || argc==2 );
37351ad0ecdSdanielk1977   if( argc==2 ){
3749c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
37551ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
3760bce8354Sdrh     if( n>30 ) n = 30;
3770bce8354Sdrh     if( n<0 ) n = 0;
37851ad0ecdSdanielk1977   }
379d589a92aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
3804f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
381147e176aSshaneh   /* If Y==0 and X will fit in a 64-bit int,
382147e176aSshaneh   ** handle the rounding directly,
383147e176aSshaneh   ** otherwise use printf.
384147e176aSshaneh   */
385147e176aSshaneh   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
386147e176aSshaneh     r = (double)((sqlite_int64)(r+0.5));
387147e176aSshaneh   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
388147e176aSshaneh     r = -(double)((sqlite_int64)((-r)+0.5));
389147e176aSshaneh   }else{
39050d654daSdrh     zBuf = sqlite3_mprintf("%.*f",n,r);
39150d654daSdrh     if( zBuf==0 ){
39250d654daSdrh       sqlite3_result_error_nomem(context);
393147e176aSshaneh       return;
394147e176aSshaneh     }
3959339da1fSdrh     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
39650d654daSdrh     sqlite3_free(zBuf);
3970bce8354Sdrh   }
398147e176aSshaneh   sqlite3_result_double(context, r);
39950d654daSdrh }
400fbd60f82Sshane #endif
401dc04c583Sdrh 
40226783a58Sdanielk1977 /*
403f3cdcdccSdrh ** Allocate nByte bytes of space using sqlite3Malloc(). If the
40426783a58Sdanielk1977 ** allocation fails, call sqlite3_result_error_nomem() to notify
40527e62dbeSdrh ** the database handle that malloc() has failed and return NULL.
40627e62dbeSdrh ** If nByte is larger than the maximum string or blob length, then
40727e62dbeSdrh ** raise an SQLITE_TOOBIG exception and return NULL.
40826783a58Sdanielk1977 */
409b1a6c3c1Sdrh static void *contextMalloc(sqlite3_context *context, i64 nByte){
410bb4957f8Sdrh   char *z;
41127e62dbeSdrh   sqlite3 *db = sqlite3_context_db_handle(context);
412ef31c6aaSdrh   assert( nByte>0 );
41327e62dbeSdrh   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
41427e62dbeSdrh   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
41527e62dbeSdrh   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
416bb4957f8Sdrh     sqlite3_result_error_toobig(context);
417bb4957f8Sdrh     z = 0;
418bb4957f8Sdrh   }else{
419da4ca9d1Sdrh     z = sqlite3Malloc(nByte);
420ef31c6aaSdrh     if( !z ){
421a1644fd8Sdanielk1977       sqlite3_result_error_nomem(context);
422a1644fd8Sdanielk1977     }
423bb4957f8Sdrh   }
424a1644fd8Sdanielk1977   return z;
425a1644fd8Sdanielk1977 }
426a1644fd8Sdanielk1977 
427dc04c583Sdrh /*
428dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
429dc04c583Sdrh */
4300ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
4317a521cfbSdrh   char *z1;
4327a521cfbSdrh   const char *z2;
4339310ef23Sdrh   int i, n;
4341d34fdecSdrh   UNUSED_PARAMETER(argc);
4357a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
4361f0feef8Sdrh   n = sqlite3_value_bytes(argv[0]);
4371f0feef8Sdrh   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
4381f0feef8Sdrh   assert( z2==(char*)sqlite3_value_text(argv[0]) );
4397a521cfbSdrh   if( z2 ){
440b1a6c3c1Sdrh     z1 = contextMalloc(context, ((i64)n)+1);
4417a521cfbSdrh     if( z1 ){
442df901d34Sdrh       for(i=0; i<n; i++){
443df901d34Sdrh         z1[i] = (char)sqlite3Toupper(z2[i]);
444dc04c583Sdrh       }
445df901d34Sdrh       sqlite3_result_text(context, z1, n, sqlite3_free);
4467a521cfbSdrh     }
4477a521cfbSdrh   }
448dc04c583Sdrh }
4490ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
450df901d34Sdrh   char *z1;
4517a521cfbSdrh   const char *z2;
4529310ef23Sdrh   int i, n;
4531d34fdecSdrh   UNUSED_PARAMETER(argc);
4547a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
4551f0feef8Sdrh   n = sqlite3_value_bytes(argv[0]);
4561f0feef8Sdrh   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
4571f0feef8Sdrh   assert( z2==(char*)sqlite3_value_text(argv[0]) );
4587a521cfbSdrh   if( z2 ){
459b1a6c3c1Sdrh     z1 = contextMalloc(context, ((i64)n)+1);
4607a521cfbSdrh     if( z1 ){
461df901d34Sdrh       for(i=0; i<n; i++){
462df901d34Sdrh         z1[i] = sqlite3Tolower(z2[i]);
463dc04c583Sdrh       }
464df901d34Sdrh       sqlite3_result_text(context, z1, n, sqlite3_free);
4657a521cfbSdrh     }
4667a521cfbSdrh   }
467dc04c583Sdrh }
468dc04c583Sdrh 
469ae6bb957Sdrh /*
470cca9f3d2Sdrh ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
471cca9f3d2Sdrh ** as VDBE code so that unused argument values do not have to be computed.
472cca9f3d2Sdrh ** However, we still need some kind of function implementation for this
473cca9f3d2Sdrh ** routines in the function table.  The noopFunc macro provides this.
474cca9f3d2Sdrh ** noopFunc will never be called so it doesn't matter what the implementation
475cca9f3d2Sdrh ** is.  We might as well use the "version()" function as a substitute.
476ae6bb957Sdrh */
477cca9f3d2Sdrh #define noopFunc versionFunc   /* Substitute function - never called */
4783212e182Sdrh 
4793212e182Sdrh /*
480f9ffac96Sdrh ** Implementation of random().  Return a random integer.
481f9ffac96Sdrh */
482f9b596ebSdrh static void randomFunc(
483f9b596ebSdrh   sqlite3_context *context,
48462c14b34Sdanielk1977   int NotUsed,
48562c14b34Sdanielk1977   sqlite3_value **NotUsed2
486f9b596ebSdrh ){
48752fc849aSdrh   sqlite_int64 r;
48862c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
4892fa1868fSdrh   sqlite3_randomness(sizeof(r), &r);
4903034e3d3Sdrh   if( r<0 ){
4913034e3d3Sdrh     /* We need to prevent a random number of 0x8000000000000000
4923034e3d3Sdrh     ** (or -9223372036854775808) since when you do abs() of that
4933034e3d3Sdrh     ** number of you get the same value back again.  To do this
4943034e3d3Sdrh     ** in a way that is testable, mask the sign bit off of negative
4953034e3d3Sdrh     ** values, resulting in a positive value.  Then take the
4963034e3d3Sdrh     ** 2s complement of that positive value.  The end result can
4973034e3d3Sdrh     ** therefore be no less than -9223372036854775807.
4983034e3d3Sdrh     */
499af8001bfSdrh     r = -(r & LARGEST_INT64);
5003034e3d3Sdrh   }
50152fc849aSdrh   sqlite3_result_int64(context, r);
502f9ffac96Sdrh }
503f9ffac96Sdrh 
504f9ffac96Sdrh /*
505137c728fSdrh ** Implementation of randomblob(N).  Return a random blob
506137c728fSdrh ** that is N bytes long.
50763cf66f0Sdrh */
508137c728fSdrh static void randomBlob(
50963cf66f0Sdrh   sqlite3_context *context,
51063cf66f0Sdrh   int argc,
51163cf66f0Sdrh   sqlite3_value **argv
51263cf66f0Sdrh ){
513137c728fSdrh   int n;
514137c728fSdrh   unsigned char *p;
51563cf66f0Sdrh   assert( argc==1 );
516f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
51763cf66f0Sdrh   n = sqlite3_value_int(argv[0]);
518023ae03aSdrh   if( n<1 ){
519023ae03aSdrh     n = 1;
520023ae03aSdrh   }
521a1644fd8Sdanielk1977   p = contextMalloc(context, n);
52202d85836Sdrh   if( p ){
5232fa1868fSdrh     sqlite3_randomness(n, p);
52417435752Sdrh     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
52502d85836Sdrh   }
52663cf66f0Sdrh }
52763cf66f0Sdrh 
52863cf66f0Sdrh /*
5296ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
53024b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
5316ed41ad7Sdrh */
53251ad0ecdSdanielk1977 static void last_insert_rowid(
5330ae8b831Sdanielk1977   sqlite3_context *context,
53462c14b34Sdanielk1977   int NotUsed,
53562c14b34Sdanielk1977   sqlite3_value **NotUsed2
53651ad0ecdSdanielk1977 ){
537fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
53862c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
539ab2f1f95Sdrh   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
540ab2f1f95Sdrh   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
541ab2f1f95Sdrh   ** function. */
542f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
5436ed41ad7Sdrh }
5446ed41ad7Sdrh 
545f146a776Srdc /*
546ab2f1f95Sdrh ** Implementation of the changes() SQL function.
547ab2f1f95Sdrh **
548ab2f1f95Sdrh ** IMP: R-62073-11209 The changes() SQL function is a wrapper
549ab2f1f95Sdrh ** around the sqlite3_changes() C/C++ function and hence follows the same
550ab2f1f95Sdrh ** rules for counting changes.
551f146a776Srdc */
552b28af71aSdanielk1977 static void changes(
553f9b596ebSdrh   sqlite3_context *context,
55462c14b34Sdanielk1977   int NotUsed,
55562c14b34Sdanielk1977   sqlite3_value **NotUsed2
556f9b596ebSdrh ){
557fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
55862c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
559f4479501Sdrh   sqlite3_result_int(context, sqlite3_changes(db));
560b0c374ffSrdc }
561f146a776Srdc 
562f146a776Srdc /*
563b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
564b28af71aSdanielk1977 ** the same as the sqlite3_total_changes() API function.
565f146a776Srdc */
566b28af71aSdanielk1977 static void total_changes(
5670ae8b831Sdanielk1977   sqlite3_context *context,
56862c14b34Sdanielk1977   int NotUsed,
56962c14b34Sdanielk1977   sqlite3_value **NotUsed2
57051ad0ecdSdanielk1977 ){
571fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
57262c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
573ab2f1f95Sdrh   /* IMP: R-52756-41993 This function is a wrapper around the
574ab2f1f95Sdrh   ** sqlite3_total_changes() C/C++ interface. */
575b28af71aSdanielk1977   sqlite3_result_int(context, sqlite3_total_changes(db));
576b0c374ffSrdc }
577b0c374ffSrdc 
5786ed41ad7Sdrh /*
5794e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
580d02eb1fdSdanielk1977 */
5814e5ffc5fSdrh struct compareInfo {
58207e83472Sdrh   u8 matchAll;          /* "*" or "%" */
58307e83472Sdrh   u8 matchOne;          /* "?" or "_" */
58407e83472Sdrh   u8 matchSet;          /* "[" or 0 */
58507e83472Sdrh   u8 noCase;            /* true to ignore case differences */
586d02eb1fdSdanielk1977 };
58755ef4d97Sdrh 
588b9175aedSdrh /*
589b9175aedSdrh ** For LIKE and GLOB matching on EBCDIC machines, assume that every
590b0870486Sdrh ** character is exactly one byte in size.  Also, provde the Utf8Read()
591b0870486Sdrh ** macro for fast reading of the next character in the common case where
592b0870486Sdrh ** the next character is ASCII.
593b9175aedSdrh */
594b9175aedSdrh #if defined(SQLITE_EBCDIC)
59542610961Sdrh # define sqlite3Utf8Read(A)        (*((*A)++))
596b0870486Sdrh # define Utf8Read(A)               (*(A++))
597b9175aedSdrh #else
598b0870486Sdrh # define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
599b9175aedSdrh #endif
600b9175aedSdrh 
6014e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
60270031fa3Sdrh /* The correct SQL-92 behavior is for the LIKE operator to ignore
60370031fa3Sdrh ** case.  Thus  'a' LIKE 'A' would be true. */
60455ef4d97Sdrh static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
60570031fa3Sdrh /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
60670031fa3Sdrh ** is case sensitive causing 'a' LIKE 'A' to be false */
60755ef4d97Sdrh static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
608d02eb1fdSdanielk1977 
609d02eb1fdSdanielk1977 /*
610698a01caSdrh ** Possible error returns from patternMatch()
611698a01caSdrh */
612698a01caSdrh #define SQLITE_MATCH             0
613698a01caSdrh #define SQLITE_NOMATCH           1
614698a01caSdrh #define SQLITE_NOWILDCARDMATCH   2
615698a01caSdrh 
616698a01caSdrh /*
617698a01caSdrh ** Compare two UTF-8 strings for equality where the first string is
618698a01caSdrh ** a GLOB or LIKE expression.  Return values:
619698a01caSdrh **
620698a01caSdrh **    SQLITE_MATCH:            Match
621698a01caSdrh **    SQLITE_NOMATCH:          No match
622698a01caSdrh **    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
6230ac65892Sdrh **
6244e5ffc5fSdrh ** Globbing rules:
6250ac65892Sdrh **
6264e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
627d02eb1fdSdanielk1977 **
6284e5ffc5fSdrh **      '?'       Matches exactly one character.
6294e5ffc5fSdrh **
6304e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
6314e5ffc5fSdrh **                characters.
6324e5ffc5fSdrh **
6334e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
6344e5ffc5fSdrh **
6354e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
6364e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
6374e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
6384e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
6394e5ffc5fSdrh ** it the last character in the list.
6404e5ffc5fSdrh **
6419fdfdc89Sdrh ** Like matching rules:
6429fdfdc89Sdrh **
6439fdfdc89Sdrh **      '%'       Matches any sequence of zero or more characters
6449fdfdc89Sdrh **
6459fdfdc89Sdrh ***     '_'       Matches any one character
6469fdfdc89Sdrh **
6479fdfdc89Sdrh **      Ec        Where E is the "esc" character and c is any other
6489fdfdc89Sdrh **                character, including '%', '_', and esc, match exactly c.
6499fdfdc89Sdrh **
650b0870486Sdrh ** The comments within this routine usually assume glob matching.
6519fdfdc89Sdrh **
6524e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
6530ac65892Sdrh */
6547c6303c0Sdanielk1977 static int patternCompare(
6554e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
6564e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
6577c6303c0Sdanielk1977   const struct compareInfo *pInfo, /* Information about how to do the compare */
658698a01caSdrh   u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
65951ad0ecdSdanielk1977 ){
6609fdfdc89Sdrh   u32 c, c2;                       /* Next pattern and input string chars */
6619fdfdc89Sdrh   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
6629fdfdc89Sdrh   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
6639fdfdc89Sdrh   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
6649fdfdc89Sdrh   const u8 *zEscaped = 0;          /* One past the last escaped input char */
665d02eb1fdSdanielk1977 
666b0870486Sdrh   while( (c = Utf8Read(zPattern))!=0 ){
6679fdfdc89Sdrh     if( c==matchAll ){  /* Match "*" */
6689fdfdc89Sdrh       /* Skip over multiple "*" characters in the pattern.  If there
6699fdfdc89Sdrh       ** are also "?" characters, skip those as well, but consume a
6709fdfdc89Sdrh       ** single character of the input string for each "?" skipped */
671b0870486Sdrh       while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
67242610961Sdrh         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
673698a01caSdrh           return SQLITE_NOWILDCARDMATCH;
674d02eb1fdSdanielk1977         }
6754e5ffc5fSdrh       }
67666150956Sdrh       if( c==0 ){
677698a01caSdrh         return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
67888b3322fSdrh       }else if( c==matchOther ){
67907e83472Sdrh         if( pInfo->matchSet==0 ){
68042610961Sdrh           c = sqlite3Utf8Read(&zPattern);
681698a01caSdrh           if( c==0 ) return SQLITE_NOWILDCARDMATCH;
68288b3322fSdrh         }else{
6839fdfdc89Sdrh           /* "[...]" immediately follows the "*".  We have to do a slow
6849fdfdc89Sdrh           ** recursive search in this case, but it is an unusual case. */
68588b3322fSdrh           assert( matchOther<0x80 );  /* '[' is a single-byte character */
686698a01caSdrh           while( *zString ){
687698a01caSdrh             int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
688698a01caSdrh             if( bMatch!=SQLITE_NOMATCH ) return bMatch;
6894a919118Sdrh             SQLITE_SKIP_UTF8(zString);
6904e5ffc5fSdrh           }
691698a01caSdrh           return SQLITE_NOWILDCARDMATCH;
69266150956Sdrh         }
69388b3322fSdrh       }
6949fdfdc89Sdrh 
6959fdfdc89Sdrh       /* At this point variable c contains the first character of the
6969fdfdc89Sdrh       ** pattern string past the "*".  Search in the input string for the
6971a4a7376Sdan       ** first matching character and recursively continue the match from
6989fdfdc89Sdrh       ** that point.
6999fdfdc89Sdrh       **
7009fdfdc89Sdrh       ** For a case-insensitive search, set variable cx to be the same as
7019fdfdc89Sdrh       ** c but in the other case and search the input string for either
7029fdfdc89Sdrh       ** c or cx.
7039fdfdc89Sdrh       */
7049fdfdc89Sdrh       if( c<=0x80 ){
705eba21f9eSdrh         char zStop[3];
706698a01caSdrh         int bMatch;
7079fdfdc89Sdrh         if( noCase ){
708eba21f9eSdrh           zStop[0] = sqlite3Toupper(c);
709eba21f9eSdrh           zStop[1] = sqlite3Tolower(c);
710eba21f9eSdrh           zStop[2] = 0;
711ad7dd425Sdanielk1977         }else{
712eba21f9eSdrh           zStop[0] = c;
713eba21f9eSdrh           zStop[1] = 0;
71466150956Sdrh         }
715eba21f9eSdrh         while(1){
716eba21f9eSdrh           zString += strcspn((const char*)zString, zStop);
717eba21f9eSdrh           if( zString[0]==0 ) break;
718eba21f9eSdrh           zString++;
719698a01caSdrh           bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
720698a01caSdrh           if( bMatch!=SQLITE_NOMATCH ) return bMatch;
7214e5ffc5fSdrh         }
72288b3322fSdrh       }else{
723698a01caSdrh         int bMatch;
724b0870486Sdrh         while( (c2 = Utf8Read(zString))!=0 ){
7259fdfdc89Sdrh           if( c2!=c ) continue;
726698a01caSdrh           bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
727698a01caSdrh           if( bMatch!=SQLITE_NOMATCH ) return bMatch;
72866150956Sdrh         }
72988b3322fSdrh       }
730698a01caSdrh       return SQLITE_NOWILDCARDMATCH;
7319fdfdc89Sdrh     }
73288b3322fSdrh     if( c==matchOther ){
73307e83472Sdrh       if( pInfo->matchSet==0 ){
73488b3322fSdrh         c = sqlite3Utf8Read(&zPattern);
735698a01caSdrh         if( c==0 ) return SQLITE_NOMATCH;
7369fdfdc89Sdrh         zEscaped = zPattern;
73788b3322fSdrh       }else{
7381aa4f3e5Sdrh         u32 prior_c = 0;
7399fdfdc89Sdrh         int seen = 0;
7409fdfdc89Sdrh         int invert = 0;
74142610961Sdrh         c = sqlite3Utf8Read(&zString);
742698a01caSdrh         if( c==0 ) return SQLITE_NOMATCH;
74342610961Sdrh         c2 = sqlite3Utf8Read(&zPattern);
74466150956Sdrh         if( c2=='^' ){
74566150956Sdrh           invert = 1;
74642610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
74766150956Sdrh         }
7484e5ffc5fSdrh         if( c2==']' ){
7494e5ffc5fSdrh           if( c==']' ) seen = 1;
75042610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
7514e5ffc5fSdrh         }
75266150956Sdrh         while( c2 && c2!=']' ){
75366150956Sdrh           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
75442610961Sdrh             c2 = sqlite3Utf8Read(&zPattern);
7554e5ffc5fSdrh             if( c>=prior_c && c<=c2 ) seen = 1;
7564e5ffc5fSdrh             prior_c = 0;
75766150956Sdrh           }else{
75866150956Sdrh             if( c==c2 ){
7594e5ffc5fSdrh               seen = 1;
76066150956Sdrh             }
7614e5ffc5fSdrh             prior_c = c2;
762d02eb1fdSdanielk1977           }
76342610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
764d02eb1fdSdanielk1977         }
76566150956Sdrh         if( c2==0 || (seen ^ invert)==0 ){
766698a01caSdrh           return SQLITE_NOMATCH;
76766150956Sdrh         }
76888b3322fSdrh         continue;
769328d913cSdrh       }
77088b3322fSdrh     }
771b0870486Sdrh     c2 = Utf8Read(zString);
77288b3322fSdrh     if( c==c2 ) continue;
773c80937a5Sdrh     if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
7749fdfdc89Sdrh       continue;
7759fdfdc89Sdrh     }
7769fdfdc89Sdrh     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
777698a01caSdrh     return SQLITE_NOMATCH;
7780ac65892Sdrh   }
779698a01caSdrh   return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
7804e5ffc5fSdrh }
7814e5ffc5fSdrh 
78255ef4d97Sdrh /*
783698a01caSdrh ** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
784698a01caSdrh ** non-zero if there is no match.
78556282a5bSdrh */
78656282a5bSdrh int sqlite3_strglob(const char *zGlobPattern, const char *zString){
787698a01caSdrh   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
78856282a5bSdrh }
78956282a5bSdrh 
79056282a5bSdrh /*
791698a01caSdrh ** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
792698a01caSdrh ** a miss - like strcmp().
7938b4a94adSdrh */
7948b4a94adSdrh int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
795698a01caSdrh   return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
7968b4a94adSdrh }
7978b4a94adSdrh 
7988b4a94adSdrh /*
79955ef4d97Sdrh ** Count the number of times that the LIKE operator (or GLOB which is
80055ef4d97Sdrh ** just a variation of LIKE) gets called.  This is used for testing
80155ef4d97Sdrh ** only.
80255ef4d97Sdrh */
80355ef4d97Sdrh #ifdef SQLITE_TEST
80455ef4d97Sdrh int sqlite3_like_count = 0;
80555ef4d97Sdrh #endif
80655ef4d97Sdrh 
8073f6b0874Sdanielk1977 
8083f6b0874Sdanielk1977 /*
8093f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
8103f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
8113f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
8123f6b0874Sdanielk1977 **
8133f6b0874Sdanielk1977 **       A LIKE B
8143f6b0874Sdanielk1977 **
8153f6b0874Sdanielk1977 ** is implemented as like(B,A).
8163f6b0874Sdanielk1977 **
81755ef4d97Sdrh ** This same function (with a different compareInfo structure) computes
81855ef4d97Sdrh ** the GLOB operator.
8193f6b0874Sdanielk1977 */
8203f6b0874Sdanielk1977 static void likeFunc(
8213f6b0874Sdanielk1977   sqlite3_context *context,
8223f6b0874Sdanielk1977   int argc,
8233f6b0874Sdanielk1977   sqlite3_value **argv
8243f6b0874Sdanielk1977 ){
825beb818d1Sdrh   const unsigned char *zA, *zB;
82607e83472Sdrh   u32 escape;
82727e62dbeSdrh   int nPat;
828bb4957f8Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
82907e83472Sdrh   struct compareInfo *pInfo = sqlite3_user_data(context);
830beb818d1Sdrh 
83141d2e66eSdrh #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
83241d2e66eSdrh   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
83341d2e66eSdrh    || sqlite3_value_type(argv[1])==SQLITE_BLOB
83441d2e66eSdrh   ){
83541d2e66eSdrh #ifdef SQLITE_TEST
83641d2e66eSdrh     sqlite3_like_count++;
83741d2e66eSdrh #endif
83841d2e66eSdrh     sqlite3_result_int(context, 0);
83941d2e66eSdrh     return;
84041d2e66eSdrh   }
84141d2e66eSdrh #endif
8421f0feef8Sdrh   zB = sqlite3_value_text(argv[0]);
8431f0feef8Sdrh   zA = sqlite3_value_text(argv[1]);
8441f0feef8Sdrh 
845beb818d1Sdrh   /* Limit the length of the LIKE or GLOB pattern to avoid problems
846beb818d1Sdrh   ** of deep recursion and N*N behavior in patternCompare().
847beb818d1Sdrh   */
84827e62dbeSdrh   nPat = sqlite3_value_bytes(argv[0]);
84927e62dbeSdrh   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
85027e62dbeSdrh   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
85127e62dbeSdrh   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
852beb818d1Sdrh     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
853beb818d1Sdrh     return;
854beb818d1Sdrh   }
8551f0feef8Sdrh   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
856beb818d1Sdrh 
8577c6303c0Sdanielk1977   if( argc==3 ){
8587c6303c0Sdanielk1977     /* The escape character string must consist of a single UTF-8 character.
8597c6303c0Sdanielk1977     ** Otherwise, return an error.
8607c6303c0Sdanielk1977     */
8617c6303c0Sdanielk1977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
8627a521cfbSdrh     if( zEsc==0 ) return;
863ee85813cSdrh     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
8647c6303c0Sdanielk1977       sqlite3_result_error(context,
8657c6303c0Sdanielk1977           "ESCAPE expression must be a single character", -1);
8667c6303c0Sdanielk1977       return;
8677c6303c0Sdanielk1977     }
86842610961Sdrh     escape = sqlite3Utf8Read(&zEsc);
86907e83472Sdrh   }else{
87007e83472Sdrh     escape = pInfo->matchSet;
8717c6303c0Sdanielk1977   }
8723f6b0874Sdanielk1977   if( zA && zB ){
87355ef4d97Sdrh #ifdef SQLITE_TEST
87455ef4d97Sdrh     sqlite3_like_count++;
87555ef4d97Sdrh #endif
876f49759bfSdrh     sqlite3_result_int(context,
877f49759bfSdrh                       patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
87851ad0ecdSdanielk1977   }
8798912d106Sdrh }
8808912d106Sdrh 
8818912d106Sdrh /*
8828912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
8838912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
8848912d106Sdrh ** arguments are equal to each other.
8858912d106Sdrh */
886f9b596ebSdrh static void nullifFunc(
887f9b596ebSdrh   sqlite3_context *context,
88862c14b34Sdanielk1977   int NotUsed,
889f9b596ebSdrh   sqlite3_value **argv
890f9b596ebSdrh ){
891dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
89262c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
893dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
894f4479501Sdrh     sqlite3_result_value(context, argv[0]);
8958912d106Sdrh   }
8960ac65892Sdrh }
8970ac65892Sdrh 
898647cb0e1Sdrh /*
89947baebc2Sdrh ** Implementation of the sqlite_version() function.  The result is the version
900647cb0e1Sdrh ** of the SQLite library that is running.
901647cb0e1Sdrh */
902f9b596ebSdrh static void versionFunc(
903f9b596ebSdrh   sqlite3_context *context,
90462c14b34Sdanielk1977   int NotUsed,
90562c14b34Sdanielk1977   sqlite3_value **NotUsed2
906f9b596ebSdrh ){
90762c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
908ab2f1f95Sdrh   /* IMP: R-48699-48617 This function is an SQL wrapper around the
909ab2f1f95Sdrh   ** sqlite3_libversion() C-interface. */
910ab2f1f95Sdrh   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
911647cb0e1Sdrh }
912647cb0e1Sdrh 
91347baebc2Sdrh /*
91447baebc2Sdrh ** Implementation of the sqlite_source_id() function. The result is a string
91547baebc2Sdrh ** that identifies the particular version of the source code used to build
91647baebc2Sdrh ** SQLite.
91747baebc2Sdrh */
91847baebc2Sdrh static void sourceidFunc(
91947baebc2Sdrh   sqlite3_context *context,
92047baebc2Sdrh   int NotUsed,
92147baebc2Sdrh   sqlite3_value **NotUsed2
92247baebc2Sdrh ){
92347baebc2Sdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
924ab2f1f95Sdrh   /* IMP: R-24470-31136 This function is an SQL wrapper around the
925ab2f1f95Sdrh   ** sqlite3_sourceid() C interface. */
926ab2f1f95Sdrh   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
92747baebc2Sdrh }
92847baebc2Sdrh 
929bdea6d13Sshaneh /*
9303ca84ef6Sdrh ** Implementation of the sqlite_log() function.  This is a wrapper around
9313ca84ef6Sdrh ** sqlite3_log().  The return value is NULL.  The function exists purely for
9323ca84ef6Sdrh ** its side-effects.
9333ca84ef6Sdrh */
934840561f2Sdrh static void errlogFunc(
9353ca84ef6Sdrh   sqlite3_context *context,
9363ca84ef6Sdrh   int argc,
9373ca84ef6Sdrh   sqlite3_value **argv
9383ca84ef6Sdrh ){
9393ca84ef6Sdrh   UNUSED_PARAMETER(argc);
9403ca84ef6Sdrh   UNUSED_PARAMETER(context);
9413ca84ef6Sdrh   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
9423ca84ef6Sdrh }
9433ca84ef6Sdrh 
9443ca84ef6Sdrh /*
945dc97a8cdSshaneh ** Implementation of the sqlite_compileoption_used() function.
946dc97a8cdSshaneh ** The result is an integer that identifies if the compiler option
947dc97a8cdSshaneh ** was used to build SQLite.
948bdea6d13Sshaneh */
949dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
950dc97a8cdSshaneh static void compileoptionusedFunc(
951bdea6d13Sshaneh   sqlite3_context *context,
952dc97a8cdSshaneh   int argc,
953dc97a8cdSshaneh   sqlite3_value **argv
954bdea6d13Sshaneh ){
955dc97a8cdSshaneh   const char *zOptName;
956dc97a8cdSshaneh   assert( argc==1 );
957dc97a8cdSshaneh   UNUSED_PARAMETER(argc);
958a3e414cdSdrh   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
959a3e414cdSdrh   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
960a3e414cdSdrh   ** function.
961a3e414cdSdrh   */
962264a2d4dSdrh   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
963dc97a8cdSshaneh     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
964bdea6d13Sshaneh   }
965dc97a8cdSshaneh }
966dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
967dc97a8cdSshaneh 
968dc97a8cdSshaneh /*
969dc97a8cdSshaneh ** Implementation of the sqlite_compileoption_get() function.
970dc97a8cdSshaneh ** The result is a string that identifies the compiler options
971dc97a8cdSshaneh ** used to build SQLite.
972dc97a8cdSshaneh */
973dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
974dc97a8cdSshaneh static void compileoptiongetFunc(
975dc97a8cdSshaneh   sqlite3_context *context,
976dc97a8cdSshaneh   int argc,
977dc97a8cdSshaneh   sqlite3_value **argv
978dc97a8cdSshaneh ){
979dc97a8cdSshaneh   int n;
980dc97a8cdSshaneh   assert( argc==1 );
981dc97a8cdSshaneh   UNUSED_PARAMETER(argc);
982a3e414cdSdrh   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
983a3e414cdSdrh   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
984a3e414cdSdrh   */
985dc97a8cdSshaneh   n = sqlite3_value_int(argv[0]);
986dc97a8cdSshaneh   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
987dc97a8cdSshaneh }
988dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
989bdea6d13Sshaneh 
990137c728fSdrh /* Array for converting from half-bytes (nybbles) into ASCII hex
991137c728fSdrh ** digits. */
992137c728fSdrh static const char hexdigits[] = {
993137c728fSdrh   '0', '1', '2', '3', '4', '5', '6', '7',
994137c728fSdrh   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
995137c728fSdrh };
996d641d646Sdanielk1977 
99747394703Sdrh /*
99847394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
99947394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
100047394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
100147394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
100247394703Sdrh ** single-quote escapes.
100347394703Sdrh */
10040ae8b831Sdanielk1977 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1005a0df4ccfSdrh   assert( argc==1 );
10061d34fdecSdrh   UNUSED_PARAMETER(argc);
1007f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
10089c054830Sdrh     case SQLITE_FLOAT: {
100972b3fbc7Sdrh       double r1, r2;
101072b3fbc7Sdrh       char zBuf[50];
10112b434a7eSmistachkin       r1 = sqlite3_value_double(argv[0]);
101272b3fbc7Sdrh       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
101372b3fbc7Sdrh       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
101472b3fbc7Sdrh       if( r1!=r2 ){
101572b3fbc7Sdrh         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
101672b3fbc7Sdrh       }
101772b3fbc7Sdrh       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
101872b3fbc7Sdrh       break;
101972b3fbc7Sdrh     }
102072b3fbc7Sdrh     case SQLITE_INTEGER: {
1021f4479501Sdrh       sqlite3_result_value(context, argv[0]);
1022f9b596ebSdrh       break;
1023f9b596ebSdrh     }
10243f41e976Sdanielk1977     case SQLITE_BLOB: {
10253f41e976Sdanielk1977       char *zText = 0;
10263f41e976Sdanielk1977       char const *zBlob = sqlite3_value_blob(argv[0]);
10271f0feef8Sdrh       int nBlob = sqlite3_value_bytes(argv[0]);
10281f0feef8Sdrh       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
1029b1a6c3c1Sdrh       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
1030a1644fd8Sdanielk1977       if( zText ){
10313f41e976Sdanielk1977         int i;
10323f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
10333f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
10343f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
10353f41e976Sdanielk1977         }
10363f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
10373f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
10383f41e976Sdanielk1977         zText[0] = 'X';
10393f41e976Sdanielk1977         zText[1] = '\'';
1040d8123366Sdanielk1977         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
104117435752Sdrh         sqlite3_free(zText);
10423f41e976Sdanielk1977       }
10433f41e976Sdanielk1977       break;
10443f41e976Sdanielk1977     }
10459c054830Sdrh     case SQLITE_TEXT: {
1046023ae03aSdrh       int i,j;
1047023ae03aSdrh       u64 n;
10482646da7eSdrh       const unsigned char *zArg = sqlite3_value_text(argv[0]);
104947394703Sdrh       char *z;
1050f9b596ebSdrh 
10517a521cfbSdrh       if( zArg==0 ) return;
1052023ae03aSdrh       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
1053b1a6c3c1Sdrh       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
1054a1644fd8Sdanielk1977       if( z ){
105547394703Sdrh         z[0] = '\'';
105651ad0ecdSdanielk1977         for(i=0, j=1; zArg[i]; i++){
105751ad0ecdSdanielk1977           z[j++] = zArg[i];
105851ad0ecdSdanielk1977           if( zArg[i]=='\'' ){
105947394703Sdrh             z[j++] = '\'';
106047394703Sdrh           }
106147394703Sdrh         }
106247394703Sdrh         z[j++] = '\'';
106347394703Sdrh         z[j] = 0;
1064a1644fd8Sdanielk1977         sqlite3_result_text(context, z, j, sqlite3_free);
1065a1644fd8Sdanielk1977       }
1066a0df4ccfSdrh       break;
1067a0df4ccfSdrh     }
1068a0df4ccfSdrh     default: {
1069a0df4ccfSdrh       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
1070a0df4ccfSdrh       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
1071a0df4ccfSdrh       break;
107247394703Sdrh     }
107347394703Sdrh   }
1074f9b596ebSdrh }
107547394703Sdrh 
1076137c728fSdrh /*
1077d495d8c9Sdrh ** The unicode() function.  Return the integer unicode code-point value
1078d495d8c9Sdrh ** for the first character of the input string.
1079d495d8c9Sdrh */
1080d495d8c9Sdrh static void unicodeFunc(
1081d495d8c9Sdrh   sqlite3_context *context,
1082d495d8c9Sdrh   int argc,
1083d495d8c9Sdrh   sqlite3_value **argv
1084d495d8c9Sdrh ){
1085d495d8c9Sdrh   const unsigned char *z = sqlite3_value_text(argv[0]);
10861d59d036Sdrh   (void)argc;
1087d495d8c9Sdrh   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
1088d495d8c9Sdrh }
1089d495d8c9Sdrh 
1090d495d8c9Sdrh /*
1091d495d8c9Sdrh ** The char() function takes zero or more arguments, each of which is
1092d495d8c9Sdrh ** an integer.  It constructs a string where each character of the string
1093d495d8c9Sdrh ** is the unicode character for the corresponding integer argument.
1094d495d8c9Sdrh */
1095d495d8c9Sdrh static void charFunc(
1096d495d8c9Sdrh   sqlite3_context *context,
1097d495d8c9Sdrh   int argc,
1098d495d8c9Sdrh   sqlite3_value **argv
1099d495d8c9Sdrh ){
1100d495d8c9Sdrh   unsigned char *z, *zOut;
1101d495d8c9Sdrh   int i;
1102f3cdcdccSdrh   zOut = z = sqlite3_malloc64( argc*4+1 );
1103d495d8c9Sdrh   if( z==0 ){
1104d495d8c9Sdrh     sqlite3_result_error_nomem(context);
1105d495d8c9Sdrh     return;
1106d495d8c9Sdrh   }
1107d495d8c9Sdrh   for(i=0; i<argc; i++){
1108c9545442Smistachkin     sqlite3_int64 x;
1109d495d8c9Sdrh     unsigned c;
1110d495d8c9Sdrh     x = sqlite3_value_int64(argv[i]);
1111d495d8c9Sdrh     if( x<0 || x>0x10ffff ) x = 0xfffd;
1112d495d8c9Sdrh     c = (unsigned)(x & 0x1fffff);
1113fe7a5d11Sdrh     if( c<0x00080 ){
1114fe7a5d11Sdrh       *zOut++ = (u8)(c&0xFF);
1115fe7a5d11Sdrh     }else if( c<0x00800 ){
1116fe7a5d11Sdrh       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
1117fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1118fe7a5d11Sdrh     }else if( c<0x10000 ){
1119fe7a5d11Sdrh       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
1120fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1121fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1122d495d8c9Sdrh     }else{
1123fe7a5d11Sdrh       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
1124fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
1125fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1126fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1127fe7a5d11Sdrh     }                                                    \
1128d495d8c9Sdrh   }
1129bbf483f8Sdrh   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
1130d495d8c9Sdrh }
1131d495d8c9Sdrh 
1132d495d8c9Sdrh /*
1133137c728fSdrh ** The hex() function.  Interpret the argument as a blob.  Return
1134137c728fSdrh ** a hexadecimal rendering as text.
1135137c728fSdrh */
1136137c728fSdrh static void hexFunc(
1137137c728fSdrh   sqlite3_context *context,
1138137c728fSdrh   int argc,
1139137c728fSdrh   sqlite3_value **argv
1140137c728fSdrh ){
1141137c728fSdrh   int i, n;
1142137c728fSdrh   const unsigned char *pBlob;
1143137c728fSdrh   char *zHex, *z;
1144137c728fSdrh   assert( argc==1 );
1145f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
11461f0feef8Sdrh   pBlob = sqlite3_value_blob(argv[0]);
1147137c728fSdrh   n = sqlite3_value_bytes(argv[0]);
11481f0feef8Sdrh   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
1149b1a6c3c1Sdrh   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
1150a1644fd8Sdanielk1977   if( zHex ){
1151137c728fSdrh     for(i=0; i<n; i++, pBlob++){
1152137c728fSdrh       unsigned char c = *pBlob;
1153137c728fSdrh       *(z++) = hexdigits[(c>>4)&0xf];
1154137c728fSdrh       *(z++) = hexdigits[c&0xf];
1155137c728fSdrh     }
1156137c728fSdrh     *z = 0;
1157137c728fSdrh     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
1158137c728fSdrh   }
1159a1644fd8Sdanielk1977 }
1160137c728fSdrh 
116126b6d90dSdrh /*
11628cff382eSdrh ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
11638cff382eSdrh */
11648cff382eSdrh static void zeroblobFunc(
11658cff382eSdrh   sqlite3_context *context,
11668cff382eSdrh   int argc,
11678cff382eSdrh   sqlite3_value **argv
11688cff382eSdrh ){
116998640a3fSdrh   i64 n;
1170a4d5ae8fSdan   int rc;
11718cff382eSdrh   assert( argc==1 );
1172f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
117398640a3fSdrh   n = sqlite3_value_int64(argv[0]);
117453e66c3cSdrh   if( n<0 ) n = 0;
1175a4d5ae8fSdan   rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
1176a4d5ae8fSdan   if( rc ){
1177a4d5ae8fSdan     sqlite3_result_error_code(context, rc);
11788cff382eSdrh   }
117998640a3fSdrh }
11808cff382eSdrh 
11818cff382eSdrh /*
118226b6d90dSdrh ** The replace() function.  Three arguments are all strings: call
118326b6d90dSdrh ** them A, B, and C. The result is also a string which is derived
1184f7b5496eSdrh ** from A by replacing every occurrence of B with C.  The match
118526b6d90dSdrh ** must be exact.  Collating sequences are not used.
118626b6d90dSdrh */
118726b6d90dSdrh static void replaceFunc(
118826b6d90dSdrh   sqlite3_context *context,
118926b6d90dSdrh   int argc,
119026b6d90dSdrh   sqlite3_value **argv
119126b6d90dSdrh ){
119226b6d90dSdrh   const unsigned char *zStr;        /* The input string A */
119326b6d90dSdrh   const unsigned char *zPattern;    /* The pattern string B */
119426b6d90dSdrh   const unsigned char *zRep;        /* The replacement string C */
119526b6d90dSdrh   unsigned char *zOut;              /* The output */
119626b6d90dSdrh   int nStr;                /* Size of zStr */
119726b6d90dSdrh   int nPattern;            /* Size of zPattern */
119826b6d90dSdrh   int nRep;                /* Size of zRep */
11992e6400baSdrh   i64 nOut;                /* Maximum size of zOut */
120026b6d90dSdrh   int loopLimit;           /* Last zStr[] that might match zPattern[] */
120126b6d90dSdrh   int i, j;                /* Loop counters */
1202f3139520Sdrh   unsigned cntExpand;      /* Number zOut expansions */
1203f3139520Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
120426b6d90dSdrh 
120526b6d90dSdrh   assert( argc==3 );
1206f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
120726b6d90dSdrh   zStr = sqlite3_value_text(argv[0]);
12087a521cfbSdrh   if( zStr==0 ) return;
12091f0feef8Sdrh   nStr = sqlite3_value_bytes(argv[0]);
12101f0feef8Sdrh   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
121126b6d90dSdrh   zPattern = sqlite3_value_text(argv[1]);
1212a605fe8dSdrh   if( zPattern==0 ){
12132333606eSdrh     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
12142333606eSdrh             || sqlite3_context_db_handle(context)->mallocFailed );
1215a605fe8dSdrh     return;
1216a605fe8dSdrh   }
1217a605fe8dSdrh   if( zPattern[0]==0 ){
1218a605fe8dSdrh     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
1219a605fe8dSdrh     sqlite3_result_value(context, argv[0]);
1220a605fe8dSdrh     return;
1221a605fe8dSdrh   }
12221f0feef8Sdrh   nPattern = sqlite3_value_bytes(argv[1]);
12231f0feef8Sdrh   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
122426b6d90dSdrh   zRep = sqlite3_value_text(argv[2]);
12257a521cfbSdrh   if( zRep==0 ) return;
12261f0feef8Sdrh   nRep = sqlite3_value_bytes(argv[2]);
12271f0feef8Sdrh   assert( zRep==sqlite3_value_text(argv[2]) );
12282e6400baSdrh   nOut = nStr + 1;
12292e6400baSdrh   assert( nOut<SQLITE_MAX_LENGTH );
1230b1a6c3c1Sdrh   zOut = contextMalloc(context, (i64)nOut);
12312e6400baSdrh   if( zOut==0 ){
12322e6400baSdrh     return;
123326b6d90dSdrh   }
123426b6d90dSdrh   loopLimit = nStr - nPattern;
1235f3139520Sdrh   cntExpand = 0;
123626b6d90dSdrh   for(i=j=0; i<=loopLimit; i++){
123726b6d90dSdrh     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
123826b6d90dSdrh       zOut[j++] = zStr[i];
123926b6d90dSdrh     }else{
1240f3139520Sdrh       if( nRep>nPattern ){
12412e6400baSdrh         nOut += nRep - nPattern;
1242c86d82f2Sdrh         testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
1243c86d82f2Sdrh         testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
124427e62dbeSdrh         if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1245a0206bc8Sdrh           sqlite3_result_error_toobig(context);
1246b975598eSdrh           sqlite3_free(zOut);
124717374e8fSdanielk1977           return;
124817374e8fSdanielk1977         }
1249f3139520Sdrh         cntExpand++;
1250f3139520Sdrh         if( (cntExpand&(cntExpand-1))==0 ){
1251f3139520Sdrh           /* Grow the size of the output buffer only on substitutions
1252f3139520Sdrh           ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
1253f3139520Sdrh           u8 *zOld;
12544a50aac5Sdrh           zOld = zOut;
1255f3139520Sdrh           zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
12562e6400baSdrh           if( zOut==0 ){
1257a1644fd8Sdanielk1977             sqlite3_result_error_nomem(context);
1258b975598eSdrh             sqlite3_free(zOld);
12592e6400baSdrh             return;
12602e6400baSdrh           }
1261f3139520Sdrh         }
1262f3139520Sdrh       }
126326b6d90dSdrh       memcpy(&zOut[j], zRep, nRep);
126426b6d90dSdrh       j += nRep;
126526b6d90dSdrh       i += nPattern-1;
126626b6d90dSdrh     }
126726b6d90dSdrh   }
1268f3139520Sdrh   assert( j+nStr-i+1<=nOut );
126926b6d90dSdrh   memcpy(&zOut[j], &zStr[i], nStr-i);
127026b6d90dSdrh   j += nStr - i;
127126b6d90dSdrh   assert( j<=nOut );
127226b6d90dSdrh   zOut[j] = 0;
127326b6d90dSdrh   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
127426b6d90dSdrh }
127526b6d90dSdrh 
1276309b3386Sdrh /*
1277309b3386Sdrh ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
1278309b3386Sdrh ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
1279309b3386Sdrh */
1280309b3386Sdrh static void trimFunc(
1281309b3386Sdrh   sqlite3_context *context,
1282309b3386Sdrh   int argc,
1283309b3386Sdrh   sqlite3_value **argv
1284309b3386Sdrh ){
1285309b3386Sdrh   const unsigned char *zIn;         /* Input string */
1286309b3386Sdrh   const unsigned char *zCharSet;    /* Set of characters to trim */
1287309b3386Sdrh   int nIn;                          /* Number of bytes in input */
12887209c697Sdrh   int flags;                        /* 1: trimleft  2: trimright  3: trim */
1289d1e3a616Sdrh   int i;                            /* Loop counter */
12901bd10f8aSdrh   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
12911bd10f8aSdrh   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
1292d1e3a616Sdrh   int nChar;                        /* Number of characters in zCharSet */
1293d1e3a616Sdrh 
1294309b3386Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1295309b3386Sdrh     return;
1296309b3386Sdrh   }
1297309b3386Sdrh   zIn = sqlite3_value_text(argv[0]);
12987a521cfbSdrh   if( zIn==0 ) return;
12991f0feef8Sdrh   nIn = sqlite3_value_bytes(argv[0]);
13001f0feef8Sdrh   assert( zIn==sqlite3_value_text(argv[0]) );
1301309b3386Sdrh   if( argc==1 ){
1302d1e3a616Sdrh     static const unsigned char lenOne[] = { 1 };
1303a4de4532Sdanielk1977     static unsigned char * const azOne[] = { (u8*)" " };
1304d1e3a616Sdrh     nChar = 1;
13058cff382eSdrh     aLen = (u8*)lenOne;
1306bc67da48Sdanielk1977     azChar = (unsigned char **)azOne;
1307d1e3a616Sdrh     zCharSet = 0;
13087a521cfbSdrh   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
1309309b3386Sdrh     return;
1310d1e3a616Sdrh   }else{
1311d1e3a616Sdrh     const unsigned char *z;
1312d1e3a616Sdrh     for(z=zCharSet, nChar=0; *z; nChar++){
13134a919118Sdrh       SQLITE_SKIP_UTF8(z);
1314309b3386Sdrh     }
1315d1e3a616Sdrh     if( nChar>0 ){
1316b1a6c3c1Sdrh       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
1317d1e3a616Sdrh       if( azChar==0 ){
1318d1e3a616Sdrh         return;
1319d1e3a616Sdrh       }
1320d1e3a616Sdrh       aLen = (unsigned char*)&azChar[nChar];
1321d1e3a616Sdrh       for(z=zCharSet, nChar=0; *z; nChar++){
1322bc67da48Sdanielk1977         azChar[nChar] = (unsigned char *)z;
13234a919118Sdrh         SQLITE_SKIP_UTF8(z);
13243abbd39aSdrh         aLen[nChar] = (u8)(z - azChar[nChar]);
1325d1e3a616Sdrh       }
1326d1e3a616Sdrh     }
1327d1e3a616Sdrh   }
1328d1e3a616Sdrh   if( nChar>0 ){
13291fc4129dSshane     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
1330309b3386Sdrh     if( flags & 1 ){
1331d1e3a616Sdrh       while( nIn>0 ){
13321bd10f8aSdrh         int len = 0;
1333d1e3a616Sdrh         for(i=0; i<nChar; i++){
1334d1e3a616Sdrh           len = aLen[i];
133527e62dbeSdrh           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
1336d1e3a616Sdrh         }
1337d1e3a616Sdrh         if( i>=nChar ) break;
1338d1e3a616Sdrh         zIn += len;
1339d1e3a616Sdrh         nIn -= len;
1340309b3386Sdrh       }
1341309b3386Sdrh     }
1342309b3386Sdrh     if( flags & 2 ){
1343d1e3a616Sdrh       while( nIn>0 ){
13441bd10f8aSdrh         int len = 0;
1345d1e3a616Sdrh         for(i=0; i<nChar; i++){
1346d1e3a616Sdrh           len = aLen[i];
1347d1e3a616Sdrh           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
1348309b3386Sdrh         }
1349d1e3a616Sdrh         if( i>=nChar ) break;
1350d1e3a616Sdrh         nIn -= len;
1351d1e3a616Sdrh       }
1352d1e3a616Sdrh     }
1353d1e3a616Sdrh     if( zCharSet ){
1354d1e3a616Sdrh       sqlite3_free(azChar);
1355309b3386Sdrh     }
1356309b3386Sdrh   }
1357309b3386Sdrh   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
1358309b3386Sdrh }
135926b6d90dSdrh 
1360a4de4532Sdanielk1977 
1361cc15313cSdrh #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1362cc15313cSdrh /*
1363cc15313cSdrh ** The "unknown" function is automatically substituted in place of
1364cc15313cSdrh ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
1365cc15313cSdrh ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
1366cc15313cSdrh ** When the "sqlite3" command-line shell is built using this functionality,
1367cc15313cSdrh ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
1368cc15313cSdrh ** involving application-defined functions to be examined in a generic
1369cc15313cSdrh ** sqlite3 shell.
1370cc15313cSdrh */
1371cc15313cSdrh static void unknownFunc(
1372cc15313cSdrh   sqlite3_context *context,
1373cc15313cSdrh   int argc,
1374cc15313cSdrh   sqlite3_value **argv
1375cc15313cSdrh ){
1376cc15313cSdrh   /* no-op */
1377cc15313cSdrh }
1378cc15313cSdrh #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
1379cc15313cSdrh 
1380cc15313cSdrh 
13812ba3cccfSdrh /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
13822ba3cccfSdrh ** is only available if the SQLITE_SOUNDEX compile-time option is used
13832ba3cccfSdrh ** when SQLite is built.
13842ba3cccfSdrh */
1385d24cc427Sdrh #ifdef SQLITE_SOUNDEX
1386d24cc427Sdrh /*
1387d24cc427Sdrh ** Compute the soundex encoding of a word.
13882ba3cccfSdrh **
13892ba3cccfSdrh ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
13902ba3cccfSdrh ** soundex encoding of the string X.
1391d24cc427Sdrh */
1392137c728fSdrh static void soundexFunc(
1393137c728fSdrh   sqlite3_context *context,
1394137c728fSdrh   int argc,
1395137c728fSdrh   sqlite3_value **argv
1396137c728fSdrh ){
1397d24cc427Sdrh   char zResult[8];
13984c755c0fSdrh   const u8 *zIn;
1399d24cc427Sdrh   int i, j;
1400d24cc427Sdrh   static const unsigned char iCode[] = {
1401d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1402d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1403d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1404d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1405d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1406d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1407d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1408d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1409d24cc427Sdrh   };
1410d24cc427Sdrh   assert( argc==1 );
14114c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
1412bdf67e0eSdrh   if( zIn==0 ) zIn = (u8*)"";
1413dc86e2b2Sdrh   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
1414d24cc427Sdrh   if( zIn[i] ){
1415bdf67e0eSdrh     u8 prevcode = iCode[zIn[i]&0x7f];
141678ca0e7eSdanielk1977     zResult[0] = sqlite3Toupper(zIn[i]);
1417d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
1418d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
1419d24cc427Sdrh       if( code>0 ){
1420bdf67e0eSdrh         if( code!=prevcode ){
1421bdf67e0eSdrh           prevcode = code;
1422d24cc427Sdrh           zResult[j++] = code + '0';
1423d24cc427Sdrh         }
1424bdf67e0eSdrh       }else{
1425bdf67e0eSdrh         prevcode = 0;
1426bdf67e0eSdrh       }
1427d24cc427Sdrh     }
1428d24cc427Sdrh     while( j<4 ){
1429d24cc427Sdrh       zResult[j++] = '0';
1430d24cc427Sdrh     }
1431d24cc427Sdrh     zResult[j] = 0;
1432d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
1433d24cc427Sdrh   }else{
14342ba3cccfSdrh     /* IMP: R-64894-50321 The string "?000" is returned if the argument
14352ba3cccfSdrh     ** is NULL or contains no ASCII alphabetic characters. */
1436d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
1437d24cc427Sdrh   }
1438d24cc427Sdrh }
14392ba3cccfSdrh #endif /* SQLITE_SOUNDEX */
1440d24cc427Sdrh 
1441fdb83b2fSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
1442fdb83b2fSdrh /*
1443fdb83b2fSdrh ** A function that loads a shared-library extension then returns NULL.
1444fdb83b2fSdrh */
1445fdb83b2fSdrh static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
144665fd59f7Sdanielk1977   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
14477a521cfbSdrh   const char *zProc;
1448fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
1449fdb83b2fSdrh   char *zErrMsg = 0;
1450fdb83b2fSdrh 
1451191dd061Sdrh   /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
14521a55dedfSdrh   ** flag is set.  See the sqlite3_enable_load_extension() API.
14531a55dedfSdrh   */
1454f602a161Sdrh   if( (db->flags & SQLITE_LoadExtFunc)==0 ){
1455f602a161Sdrh     sqlite3_result_error(context, "not authorized", -1);
1456f602a161Sdrh     return;
1457f602a161Sdrh   }
14581a55dedfSdrh 
1459fdb83b2fSdrh   if( argc==2 ){
146065fd59f7Sdanielk1977     zProc = (const char *)sqlite3_value_text(argv[1]);
14617a521cfbSdrh   }else{
14627a521cfbSdrh     zProc = 0;
1463fdb83b2fSdrh   }
14647a521cfbSdrh   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
1465fdb83b2fSdrh     sqlite3_result_error(context, zErrMsg, -1);
1466fdb83b2fSdrh     sqlite3_free(zErrMsg);
1467fdb83b2fSdrh   }
1468fdb83b2fSdrh }
1469fdb83b2fSdrh #endif
1470fdb83b2fSdrh 
147101427a62Sdanielk1977 
14720ac65892Sdrh /*
1473d3a149efSdrh ** An instance of the following structure holds the context of a
1474dd5baa95Sdrh ** sum() or avg() aggregate computation.
1475dd5baa95Sdrh */
1476dd5baa95Sdrh typedef struct SumCtx SumCtx;
1477dd5baa95Sdrh struct SumCtx {
14788c08e861Sdrh   double rSum;      /* Floating point sum */
14798c08e861Sdrh   i64 iSum;         /* Integer sum */
1480cf85a51cSdrh   i64 cnt;          /* Number of elements summed */
14818c08e861Sdrh   u8 overflow;      /* True if integer overflow seen */
14828c08e861Sdrh   u8 approx;        /* True if non-integer value was input to the sum */
1483dd5baa95Sdrh };
1484dd5baa95Sdrh 
1485dd5baa95Sdrh /*
1486a97fdd3bSdrh ** Routines used to compute the sum, average, and total.
1487a97fdd3bSdrh **
1488a97fdd3bSdrh ** The SUM() function follows the (broken) SQL standard which means
1489a97fdd3bSdrh ** that it returns NULL if it sums over no inputs.  TOTAL returns
1490a97fdd3bSdrh ** 0.0 in that case.  In addition, TOTAL always returns a float where
1491a97fdd3bSdrh ** SUM might return an integer if it never encounters a floating point
1492c806d857Sdrh ** value.  TOTAL never fails, but SUM might through an exception if
1493c806d857Sdrh ** it overflows an integer.
1494dd5baa95Sdrh */
14950ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1496dd5baa95Sdrh   SumCtx *p;
14973d1d95e6Sdrh   int type;
14983f219f46Sdrh   assert( argc==1 );
1499f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
15004f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
150129d72108Sdrh   type = sqlite3_value_numeric_type(argv[0]);
15023d1d95e6Sdrh   if( p && type!=SQLITE_NULL ){
1503739105c7Sdrh     p->cnt++;
150429d72108Sdrh     if( type==SQLITE_INTEGER ){
15058c08e861Sdrh       i64 v = sqlite3_value_int64(argv[0]);
15068c08e861Sdrh       p->rSum += v;
1507158b9cb9Sdrh       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
1508158b9cb9Sdrh         p->overflow = 1;
150929d72108Sdrh       }
151029d72108Sdrh     }else{
15118c08e861Sdrh       p->rSum += sqlite3_value_double(argv[0]);
151229d72108Sdrh       p->approx = 1;
15133f219f46Sdrh     }
1514739105c7Sdrh   }
1515dd5baa95Sdrh }
151667a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
1517c3a20c19Sdan static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
1518c3a20c19Sdan   SumCtx *p;
1519c3a20c19Sdan   int type;
1520c3a20c19Sdan   assert( argc==1 );
1521c3a20c19Sdan   UNUSED_PARAMETER(argc);
1522c3a20c19Sdan   p = sqlite3_aggregate_context(context, sizeof(*p));
1523c3a20c19Sdan   type = sqlite3_value_numeric_type(argv[0]);
1524c3a20c19Sdan   if( p && type!=SQLITE_NULL ){
1525c3a20c19Sdan     p->cnt--;
1526c3a20c19Sdan     if( type==SQLITE_INTEGER ){
1527c3a20c19Sdan       i64 v = sqlite3_value_int64(argv[0]);
1528c3a20c19Sdan       p->rSum -= v;
1529c3a20c19Sdan       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, -1*v) ){
1530c3a20c19Sdan         p->overflow = 1;
1531c3a20c19Sdan       }
1532c3a20c19Sdan     }else{
1533d736829eSdan       p->rSum -= sqlite3_value_double(argv[0]);
1534c3a20c19Sdan       p->approx = 1;
1535c3a20c19Sdan     }
1536c3a20c19Sdan   }
1537c3a20c19Sdan }
153867a9b8edSdan #else
153967a9b8edSdan # define sumInverse 0
154067a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
15410ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
1542dd5baa95Sdrh   SumCtx *p;
1543abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1544c2bd913aSdrh   if( p && p->cnt>0 ){
15458c08e861Sdrh     if( p->overflow ){
15468c08e861Sdrh       sqlite3_result_error(context,"integer overflow",-1);
15478c08e861Sdrh     }else if( p->approx ){
15488c08e861Sdrh       sqlite3_result_double(context, p->rSum);
1549c2bd913aSdrh     }else{
15508c08e861Sdrh       sqlite3_result_int64(context, p->iSum);
15513d1d95e6Sdrh     }
1552dd5baa95Sdrh   }
1553c2bd913aSdrh }
15540ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
1555dd5baa95Sdrh   SumCtx *p;
1556abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1557739105c7Sdrh   if( p && p->cnt>0 ){
15588c08e861Sdrh     sqlite3_result_double(context, p->rSum/(double)p->cnt);
1559dd5baa95Sdrh   }
1560dd5baa95Sdrh }
1561a97fdd3bSdrh static void totalFinalize(sqlite3_context *context){
1562a97fdd3bSdrh   SumCtx *p;
1563a97fdd3bSdrh   p = sqlite3_aggregate_context(context, 0);
1564fbd60f82Sshane   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1565fbd60f82Sshane   sqlite3_result_double(context, p ? p->rSum : (double)0);
1566a97fdd3bSdrh }
1567dd5baa95Sdrh 
1568dd5baa95Sdrh /*
15690bce8354Sdrh ** The following structure keeps track of state information for the
15700bce8354Sdrh ** count() aggregate function.
15710bce8354Sdrh */
15720bce8354Sdrh typedef struct CountCtx CountCtx;
15730bce8354Sdrh struct CountCtx {
1574fc6ad39cSdrh   i64 n;
15757262ca94Sdan #ifdef SQLITE_DEBUG
15767262ca94Sdan   int bInverse;                   /* True if xInverse() ever called */
15777262ca94Sdan #endif
15780bce8354Sdrh };
1579dd5baa95Sdrh 
15800bce8354Sdrh /*
15810bce8354Sdrh ** Routines to implement the count() aggregate function.
15820bce8354Sdrh */
15830ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
15840bce8354Sdrh   CountCtx *p;
15854f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
15869c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
15870bce8354Sdrh     p->n++;
15880bce8354Sdrh   }
15892e79c3d5Sdrh 
1590d3264c7cSdrh #ifndef SQLITE_OMIT_DEPRECATED
15912e79c3d5Sdrh   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
15922e79c3d5Sdrh   ** sure it still operates correctly, verify that its count agrees with our
15932e79c3d5Sdrh   ** internal count when using count(*) and when the total count can be
15942e79c3d5Sdrh   ** expressed as a 32-bit integer. */
15957262ca94Sdan   assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
15962e79c3d5Sdrh           || p->n==sqlite3_aggregate_count(context) );
1597d3264c7cSdrh #endif
15980bce8354Sdrh }
15990ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
16000bce8354Sdrh   CountCtx *p;
1601abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1602fc6ad39cSdrh   sqlite3_result_int64(context, p ? p->n : 0);
16030bce8354Sdrh }
16047262ca94Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
16057262ca94Sdan static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
16067262ca94Sdan   CountCtx *p;
16077262ca94Sdan   p = sqlite3_aggregate_context(ctx, sizeof(*p));
16087262ca94Sdan   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
16097262ca94Sdan     p->n--;
16107262ca94Sdan #ifdef SQLITE_DEBUG
16117262ca94Sdan     p->bInverse = 1;
16127262ca94Sdan #endif
16137262ca94Sdan   }
16147262ca94Sdan }
16156b4b8820Sdan #else
16166b4b8820Sdan # define countInverse 0
16176b4b8820Sdan #endif /* SQLITE_OMIT_WINDOWFUNC */
16180bce8354Sdrh 
16190bce8354Sdrh /*
16200bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
16210bce8354Sdrh */
162262c14b34Sdanielk1977 static void minmaxStep(
162362c14b34Sdanielk1977   sqlite3_context *context,
162462c14b34Sdanielk1977   int NotUsed,
162562c14b34Sdanielk1977   sqlite3_value **argv
162662c14b34Sdanielk1977 ){
162788208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
16289eb516c0Sdrh   Mem *pBest;
162962c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
16309eb516c0Sdrh 
16319eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
16323aeab9e4Sdanielk1977   if( !pBest ) return;
1633268380caSdrh 
16346fb2b54cSdan   if( sqlite3_value_type(pArg)==SQLITE_NULL ){
163594a6d998Sdrh     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
163694a6d998Sdrh   }else if( pBest->flags ){
16379eb516c0Sdrh     int max;
16389eb516c0Sdrh     int cmp;
1639dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
16407e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
16417e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
16427e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
16437e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
16447e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
16457e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
16467e18c259Sdanielk1977     ** aggregate, or 0 for min().
16477e18c259Sdanielk1977     */
1648309b3386Sdrh     max = sqlite3_user_data(context)!=0;
1649dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
165088208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
1651b21c8cd4Sdrh       sqlite3VdbeMemCopy(pBest, pArg);
16527a95789cSdrh     }else{
16537a95789cSdrh       sqlite3SkipAccumulatorLoad(context);
165488208050Sdanielk1977     }
16550bce8354Sdrh   }else{
1656035e563bSdrh     pBest->db = sqlite3_context_db_handle(context);
1657b21c8cd4Sdrh     sqlite3VdbeMemCopy(pBest, pArg);
16580bce8354Sdrh   }
16590bce8354Sdrh }
16606fb2b54cSdan static void minMaxValueFinalize(sqlite3_context *context, int bValue){
166188208050Sdanielk1977   sqlite3_value *pRes;
1662abfcea25Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
1663abfcea25Sdrh   if( pRes ){
166494a6d998Sdrh     if( pRes->flags ){
1665f4479501Sdrh       sqlite3_result_value(context, pRes);
16660bce8354Sdrh     }
16676fb2b54cSdan     if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
16680bce8354Sdrh   }
1669abfcea25Sdrh }
167067a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
16716fb2b54cSdan static void minMaxValue(sqlite3_context *context){
16726fb2b54cSdan   return minMaxValueFinalize(context, 1);
16736fb2b54cSdan }
167467a9b8edSdan #else
167567a9b8edSdan # define minMaxValue 0
167667a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
16776fb2b54cSdan static void minMaxFinalize(sqlite3_context *context){
16786fb2b54cSdan   return minMaxValueFinalize(context, 0);
16796fb2b54cSdan }
1680dd5baa95Sdrh 
1681b0689696Sdrh /*
1682b0689696Sdrh ** group_concat(EXPR, ?SEPARATOR?)
1683b0689696Sdrh */
1684b0689696Sdrh static void groupConcatStep(
1685b0689696Sdrh   sqlite3_context *context,
1686b0689696Sdrh   int argc,
1687b0689696Sdrh   sqlite3_value **argv
1688b0689696Sdrh ){
1689b0689696Sdrh   const char *zVal;
1690ade86483Sdrh   StrAccum *pAccum;
1691b0689696Sdrh   const char *zSep;
169207d3117aSdrh   int nVal, nSep;
169307d3117aSdrh   assert( argc==1 || argc==2 );
169407d3117aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
1695ade86483Sdrh   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
1696ade86483Sdrh 
1697ade86483Sdrh   if( pAccum ){
1698bb4957f8Sdrh     sqlite3 *db = sqlite3_context_db_handle(context);
1699e3bf632cSdan     int firstTerm = pAccum->mxAlloc==0;
1700bb4957f8Sdrh     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
17018bfd7190Sdrh     if( !firstTerm ){
170207d3117aSdrh       if( argc==2 ){
170307d3117aSdrh         zSep = (char*)sqlite3_value_text(argv[1]);
170407d3117aSdrh         nSep = sqlite3_value_bytes(argv[1]);
1705b0689696Sdrh       }else{
1706b0689696Sdrh         zSep = ",";
1707ade86483Sdrh         nSep = 1;
1708b0689696Sdrh       }
17090cdbe1aeSdrh       if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
1710b0689696Sdrh     }
171107d3117aSdrh     zVal = (char*)sqlite3_value_text(argv[0]);
171207d3117aSdrh     nVal = sqlite3_value_bytes(argv[0]);
17130cdbe1aeSdrh     if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
1714b0689696Sdrh   }
1715b0689696Sdrh }
171667a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
171703854d2eSdan static void groupConcatInverse(
171803854d2eSdan   sqlite3_context *context,
171903854d2eSdan   int argc,
172003854d2eSdan   sqlite3_value **argv
172103854d2eSdan ){
172203854d2eSdan   int n;
172303854d2eSdan   assert( argc==1 || argc==2 );
172403854d2eSdan   StrAccum *pAccum;
172503854d2eSdan   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
172603854d2eSdan   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
172703854d2eSdan   if( pAccum ){
172803854d2eSdan     n = sqlite3_value_bytes(argv[0]);
172903854d2eSdan     if( argc==2 ){
173003854d2eSdan       n += sqlite3_value_bytes(argv[1]);
1731*683b0fffSdan     }else{
1732*683b0fffSdan       n++;
173303854d2eSdan     }
173403854d2eSdan     if( n>=pAccum->nChar ){
173503854d2eSdan       pAccum->nChar = 0;
173603854d2eSdan     }else{
173703854d2eSdan       pAccum->nChar -= n;
173803854d2eSdan       memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
173903854d2eSdan     }
1740e3bf632cSdan     if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
174103854d2eSdan   }
174203854d2eSdan }
174367a9b8edSdan #else
174467a9b8edSdan # define groupConcatInverse 0
174567a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
1746b0689696Sdrh static void groupConcatFinalize(sqlite3_context *context){
1747ade86483Sdrh   StrAccum *pAccum;
1748ade86483Sdrh   pAccum = sqlite3_aggregate_context(context, 0);
1749ade86483Sdrh   if( pAccum ){
17500cdbe1aeSdrh     if( pAccum->accError==SQLITE_TOOBIG ){
1751ade86483Sdrh       sqlite3_result_error_toobig(context);
17520cdbe1aeSdrh     }else if( pAccum->accError==SQLITE_NOMEM ){
1753ade86483Sdrh       sqlite3_result_error_nomem(context);
1754ade86483Sdrh     }else{
1755ade86483Sdrh       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
1756ade86483Sdrh                           sqlite3_free);
1757b0689696Sdrh     }
1758b0689696Sdrh   }
1759ade86483Sdrh }
176067a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
1761e2f781b9Sdan static void groupConcatValue(sqlite3_context *context){
1762e2f781b9Sdan   sqlite3_str *pAccum;
1763e2f781b9Sdan   pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
1764e2f781b9Sdan   if( pAccum ){
1765e2f781b9Sdan     if( pAccum->accError==SQLITE_TOOBIG ){
1766e2f781b9Sdan       sqlite3_result_error_toobig(context);
1767e2f781b9Sdan     }else if( pAccum->accError==SQLITE_NOMEM ){
1768e2f781b9Sdan       sqlite3_result_error_nomem(context);
1769e2f781b9Sdan     }else{
1770e2f781b9Sdan       const char *zText = sqlite3_str_value(pAccum);
1771e2f781b9Sdan       sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
1772e2f781b9Sdan     }
1773e2f781b9Sdan   }
1774e2f781b9Sdan }
177567a9b8edSdan #else
177667a9b8edSdan # define groupConcatValue 0
177767a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
17784e5ffc5fSdrh 
1779d3a149efSdrh /*
1780a4741840Sdrh ** This routine does per-connection function registration.  Most
1781a4741840Sdrh ** of the built-in functions above are part of the global function set.
1782a4741840Sdrh ** This routine only deals with those that are not global.
1783dc04c583Sdrh */
178480738d9cSdrh void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
1785832a58a6Sdanielk1977   int rc = sqlite3_overload_function(db, "MATCH", 2);
1786832a58a6Sdanielk1977   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
1787832a58a6Sdanielk1977   if( rc==SQLITE_NOMEM ){
17884a642b60Sdrh     sqlite3OomFault(db);
1789832a58a6Sdanielk1977   }
1790832a58a6Sdanielk1977 }
179155ef4d97Sdrh 
179255ef4d97Sdrh /*
179355ef4d97Sdrh ** Set the LIKEOPT flag on the 2-argument function with the given name.
179455ef4d97Sdrh */
17951bd10f8aSdrh static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
179655ef4d97Sdrh   FuncDef *pDef;
179780738d9cSdrh   pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
1798d27135adSdrh   if( ALWAYS(pDef) ){
1799d36e1041Sdrh     pDef->funcFlags |= flagVal;
180055ef4d97Sdrh   }
180155ef4d97Sdrh }
180255ef4d97Sdrh 
180355ef4d97Sdrh /*
180455ef4d97Sdrh ** Register the built-in LIKE and GLOB functions.  The caseSensitive
180555ef4d97Sdrh ** parameter determines whether or not the LIKE operator is case
180655ef4d97Sdrh ** sensitive.  GLOB is always case sensitive.
180755ef4d97Sdrh */
180855ef4d97Sdrh void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
180955ef4d97Sdrh   struct compareInfo *pInfo;
181055ef4d97Sdrh   if( caseSensitive ){
181155ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoAlt;
181255ef4d97Sdrh   }else{
181355ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoNorm;
181455ef4d97Sdrh   }
1815660af939Sdan   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
1816660af939Sdan   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
1817901e994bSdrh   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
1818660af939Sdan       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0, 0, 0);
1819d64fe2f3Sdrh   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1820d64fe2f3Sdrh   setLikeOptFlag(db, "like",
1821d64fe2f3Sdrh       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
182255ef4d97Sdrh }
182355ef4d97Sdrh 
182455ef4d97Sdrh /*
182555ef4d97Sdrh ** pExpr points to an expression which implements a function.  If
182655ef4d97Sdrh ** it is appropriate to apply the LIKE optimization to that function
18271d42ea71Sdrh ** then set aWc[0] through aWc[2] to the wildcard characters and the
18281d42ea71Sdrh ** escape character and then return TRUE.  If the function is not a
18291d42ea71Sdrh ** LIKE-style function then return FALSE.
18301d42ea71Sdrh **
18311d42ea71Sdrh ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
18321d42ea71Sdrh ** operator if c is a string literal that is exactly one byte in length.
18331d42ea71Sdrh ** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is
18341d42ea71Sdrh ** no ESCAPE clause.
183516897072Sdrh **
183616897072Sdrh ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
183716897072Sdrh ** the function (default for LIKE).  If the function makes the distinction
183816897072Sdrh ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
183916897072Sdrh ** false.
184055ef4d97Sdrh */
1841d64fe2f3Sdrh int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
184255ef4d97Sdrh   FuncDef *pDef;
18431d42ea71Sdrh   int nExpr;
18441d42ea71Sdrh   if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
184555ef4d97Sdrh     return 0;
184655ef4d97Sdrh   }
18476ab3a2ecSdanielk1977   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
18481d42ea71Sdrh   nExpr = pExpr->x.pList->nExpr;
18491d42ea71Sdrh   pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
1850d36e1041Sdrh   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
185155ef4d97Sdrh     return 0;
185255ef4d97Sdrh   }
18531d42ea71Sdrh   if( nExpr<3 ){
18541d42ea71Sdrh     aWc[3] = 0;
18551d42ea71Sdrh   }else{
18561d42ea71Sdrh     Expr *pEscape = pExpr->x.pList->a[2].pExpr;
18571d42ea71Sdrh     char *zEscape;
18581d42ea71Sdrh     if( pEscape->op!=TK_STRING ) return 0;
18591d42ea71Sdrh     zEscape = pEscape->u.zToken;
18601d42ea71Sdrh     if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
18611d42ea71Sdrh     aWc[3] = zEscape[0];
18621d42ea71Sdrh   }
186355ef4d97Sdrh 
186455ef4d97Sdrh   /* The memcpy() statement assumes that the wildcard characters are
186555ef4d97Sdrh   ** the first three statements in the compareInfo structure.  The
186655ef4d97Sdrh   ** asserts() that follow verify that assumption
186755ef4d97Sdrh   */
186855ef4d97Sdrh   memcpy(aWc, pDef->pUserData, 3);
186955ef4d97Sdrh   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
187055ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
187155ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1872d36e1041Sdrh   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
187355ef4d97Sdrh   return 1;
1874dc04c583Sdrh }
18758c0a791aSdanielk1977 
187693ce741bSdanielk1977 /*
187760ec914cSpeter.d.reid ** All of the FuncDef structures in the aBuiltinFunc[] array above
187893ce741bSdanielk1977 ** to the global function hash table.  This occurs at start-time (as
187993ce741bSdanielk1977 ** a consequence of calling sqlite3_initialize()).
188093ce741bSdanielk1977 **
188193ce741bSdanielk1977 ** After this routine runs
188293ce741bSdanielk1977 */
188380738d9cSdrh void sqlite3RegisterBuiltinFunctions(void){
18848c0a791aSdanielk1977   /*
1885777c5386Sdrh   ** The following array holds FuncDef structures for all of the functions
1886777c5386Sdrh   ** defined in this file.
18878c0a791aSdanielk1977   **
1888777c5386Sdrh   ** The array cannot be constant since changes are made to the
1889777c5386Sdrh   ** FuncDef.pHash elements at start-time.  The elements of this array
1890777c5386Sdrh   ** are read-only after initialization is complete.
189180738d9cSdrh   **
189280738d9cSdrh   ** For peak efficiency, put the most frequently used function last.
18938c0a791aSdanielk1977   */
189480738d9cSdrh   static FuncDef aBuiltinFunc[] = {
189580738d9cSdrh #ifdef SQLITE_SOUNDEX
189680738d9cSdrh     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
189780738d9cSdrh #endif
189880738d9cSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
189980738d9cSdrh     VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
190080738d9cSdrh     VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
190180738d9cSdrh #endif
190280738d9cSdrh #if SQLITE_USER_AUTHENTICATION
190380738d9cSdrh     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
190480738d9cSdrh #endif
190580738d9cSdrh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
190680738d9cSdrh     DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
190780738d9cSdrh     DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
190880738d9cSdrh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
190980738d9cSdrh     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
191080738d9cSdrh     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
191180738d9cSdrh     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
191254240751Sdrh #ifdef SQLITE_DEBUG
1913a1a523a5Sdrh     FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
191454240751Sdrh #endif
1915092457b1Sdrh #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
191635100fb1Sdrh     FUNCTION2(sqlite_offset,     1, 0, 0, noopFunc,  SQLITE_FUNC_OFFSET|
19172fc865c1Sdrh                                                      SQLITE_FUNC_TYPEOF),
1918092457b1Sdrh #endif
19198c0a791aSdanielk1977     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
19208c0a791aSdanielk1977     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
19218c0a791aSdanielk1977     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
19228c0a791aSdanielk1977     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
19238c0a791aSdanielk1977     FUNCTION(trim,               1, 3, 0, trimFunc         ),
19248c0a791aSdanielk1977     FUNCTION(trim,               2, 3, 0, trimFunc         ),
19258c0a791aSdanielk1977     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
19268c0a791aSdanielk1977     FUNCTION(min,                0, 0, 1, 0                ),
19276fb2b54cSdan     WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
19289588ad95Sdrh                                           SQLITE_FUNC_MINMAX ),
19298c0a791aSdanielk1977     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
19308c0a791aSdanielk1977     FUNCTION(max,                0, 1, 1, 0                ),
19316fb2b54cSdan     WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
19329588ad95Sdrh                                           SQLITE_FUNC_MINMAX ),
1933a748fdccSdrh     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
1934a748fdccSdrh     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
1935d55e0729Sdrh     FUNCTION(instr,              2, 0, 0, instrFunc        ),
1936a5c1416dSdrh     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
1937d495d8c9Sdrh     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
1938d495d8c9Sdrh     FUNCTION(char,              -1, 0, 0, charFunc         ),
19398c0a791aSdanielk1977     FUNCTION(abs,                1, 0, 0, absFunc          ),
1940fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
19418c0a791aSdanielk1977     FUNCTION(round,              1, 0, 0, roundFunc        ),
19428c0a791aSdanielk1977     FUNCTION(round,              2, 0, 0, roundFunc        ),
1943fbd60f82Sshane #endif
19448c0a791aSdanielk1977     FUNCTION(upper,              1, 0, 0, upperFunc        ),
19458c0a791aSdanielk1977     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
19468c0a791aSdanielk1977     FUNCTION(hex,                1, 0, 0, hexFunc          ),
1947cca9f3d2Sdrh     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
1948b1fba286Sdrh     VFUNCTION(random,            0, 0, 0, randomFunc       ),
1949b1fba286Sdrh     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
19508c0a791aSdanielk1977     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
195103bf26d9Sdrh     DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
195203bf26d9Sdrh     DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
1953840561f2Sdrh     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
19548c0a791aSdanielk1977     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
1955b1fba286Sdrh     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
1956b1fba286Sdrh     VFUNCTION(changes,           0, 0, 0, changes          ),
1957b1fba286Sdrh     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
19588c0a791aSdanielk1977     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
19598c0a791aSdanielk1977     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
196080738d9cSdrh     FUNCTION(substr,             2, 0, 0, substrFunc       ),
196180738d9cSdrh     FUNCTION(substr,             3, 0, 0, substrFunc       ),
19626fb2b54cSdan     WAGGREGATE(sum,   1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
19636fb2b54cSdan     WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
19646fb2b54cSdan     WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
19657262ca94Sdan     WAGGREGATE(count, 0,0,0, countStep,
19667262ca94Sdan         countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT  ),
19677262ca94Sdan     WAGGREGATE(count, 1,0,0, countStep,
19687262ca94Sdan         countFinalize, countFinalize, countInverse, 0  ),
196903854d2eSdan     WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
19706fb2b54cSdan         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
197103854d2eSdan     WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
19726fb2b54cSdan         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
19738c0a791aSdanielk1977 
19748c0a791aSdanielk1977     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
19758c0a791aSdanielk1977 #ifdef SQLITE_CASE_SENSITIVE_LIKE
19768c0a791aSdanielk1977     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
19778c0a791aSdanielk1977     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
19788c0a791aSdanielk1977 #else
19798c0a791aSdanielk1977     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
19808c0a791aSdanielk1977     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
19818c0a791aSdanielk1977 #endif
1982cc15313cSdrh #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1983cc15313cSdrh     FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
1984cc15313cSdrh #endif
198580738d9cSdrh     FUNCTION(coalesce,           1, 0, 0, 0                ),
198680738d9cSdrh     FUNCTION(coalesce,           0, 0, 0, 0                ),
198780738d9cSdrh     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
19888c0a791aSdanielk1977   };
1989545f587fSdrh #ifndef SQLITE_OMIT_ALTERTABLE
1990545f587fSdrh   sqlite3AlterFunctions();
1991545f587fSdrh #endif
1992dfa552f4Sdan   sqlite3WindowFunctions();
19930106e378Sdan #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
19940106e378Sdan   sqlite3AnalyzeFunctions();
19950106e378Sdan #endif
199680738d9cSdrh   sqlite3RegisterDateTimeFunctions();
199780738d9cSdrh   sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
199880738d9cSdrh 
199980738d9cSdrh #if 0  /* Enable to print out how the built-in functions are hashed */
200080738d9cSdrh   {
200180738d9cSdrh     int i;
200280738d9cSdrh     FuncDef *p;
200380738d9cSdrh     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
200480738d9cSdrh       printf("FUNC-HASH %02d:", i);
200580738d9cSdrh       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
200680738d9cSdrh         int n = sqlite3Strlen30(p->zName);
200780738d9cSdrh         int h = p->zName[0] + n;
200880738d9cSdrh         printf(" %s(%d)", p->zName, h);
200980738d9cSdrh       }
201080738d9cSdrh       printf("\n");
201180738d9cSdrh     }
201280738d9cSdrh   }
201380738d9cSdrh #endif
201470a8ca3cSdrh }
2015