xref: /sqlite-3.40.0/src/func.c (revision 42dddb97)
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>
19ef9f719dSdrh #ifndef SQLITE_OMIT_FLOATING_POINT
2005d7bfd0Sdrh #include <math.h>
21ef9f719dSdrh #endif
2288208050Sdanielk1977 #include "vdbeInt.h"
230bce8354Sdrh 
2455ef4d97Sdrh /*
2555ef4d97Sdrh ** Return the collating function associated with a function.
2655ef4d97Sdrh */
sqlite3GetFuncCollSeq(sqlite3_context * context)27dc1bdc4fSdanielk1977 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
28a9e03b1bSdrh   VdbeOp *pOp;
29a9e03b1bSdrh   assert( context->pVdbe!=0 );
30a9e03b1bSdrh   pOp = &context->pVdbe->aOp[context->iOp-1];
31a15cc47fSdrh   assert( pOp->opcode==OP_CollSeq );
32a15cc47fSdrh   assert( pOp->p4type==P4_COLLSEQ );
33a15cc47fSdrh   return pOp->p4.pColl;
34dc1bdc4fSdanielk1977 }
35dc1bdc4fSdanielk1977 
360bce8354Sdrh /*
377a95789cSdrh ** Indicate that the accumulator load should be skipped on this
387a95789cSdrh ** iteration of the aggregate loop.
397a95789cSdrh */
sqlite3SkipAccumulatorLoad(sqlite3_context * context)407a95789cSdrh static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
4121d59784Sdrh   assert( context->isError<=0 );
4221d59784Sdrh   context->isError = -1;
437a95789cSdrh   context->skipFlag = 1;
447a95789cSdrh }
457a95789cSdrh 
467a95789cSdrh /*
470bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
480bce8354Sdrh */
minmaxFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)49f9b596ebSdrh static void minmaxFunc(
50f9b596ebSdrh   sqlite3_context *context,
51f9b596ebSdrh   int argc,
52f9b596ebSdrh   sqlite3_value **argv
53f9b596ebSdrh ){
540bce8354Sdrh   int i;
55268380caSdrh   int mask;    /* 0 for min() or 0xffffffff for max() */
56f9b596ebSdrh   int iBest;
57dc1bdc4fSdanielk1977   CollSeq *pColl;
580bce8354Sdrh 
5965595cd6Sdrh   assert( argc>1 );
60c44af71cSdrh   mask = sqlite3_user_data(context)==0 ? 0 : -1;
61dc1bdc4fSdanielk1977   pColl = sqlite3GetFuncCollSeq(context);
62dc1bdc4fSdanielk1977   assert( pColl );
63c572ef7fSdanielk1977   assert( mask==-1 || mask==0 );
64f9b596ebSdrh   iBest = 0;
659c054830Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
66f9b596ebSdrh   for(i=1; i<argc; i++){
679c054830Sdrh     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
68dc1bdc4fSdanielk1977     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
6965595cd6Sdrh       testcase( mask==0 );
70f9b596ebSdrh       iBest = i;
710bce8354Sdrh     }
720bce8354Sdrh   }
73f4479501Sdrh   sqlite3_result_value(context, argv[iBest]);
740bce8354Sdrh }
750bce8354Sdrh 
76268380caSdrh /*
77268380caSdrh ** Return the type of the argument.
78268380caSdrh */
typeofFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** argv)79f9b596ebSdrh static void typeofFunc(
80f9b596ebSdrh   sqlite3_context *context,
8162c14b34Sdanielk1977   int NotUsed,
82f9b596ebSdrh   sqlite3_value **argv
83f9b596ebSdrh ){
849d8e401cSdrh   static const char *azType[] = { "integer", "real", "text", "blob", "null" };
859d8e401cSdrh   int i = sqlite3_value_type(argv[0]) - 1;
8662c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
879d8e401cSdrh   assert( i>=0 && i<ArraySize(azType) );
889d8e401cSdrh   assert( SQLITE_INTEGER==1 );
899d8e401cSdrh   assert( SQLITE_FLOAT==2 );
909d8e401cSdrh   assert( SQLITE_TEXT==3 );
919d8e401cSdrh   assert( SQLITE_BLOB==4 );
929d8e401cSdrh   assert( SQLITE_NULL==5 );
933cef3649Sdrh   /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
943cef3649Sdrh   ** the datatype code for the initial datatype of the sqlite3_value object
953cef3649Sdrh   ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
963cef3649Sdrh   ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
979d8e401cSdrh   sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
980bce8354Sdrh }
990bce8354Sdrh 
1009d44f18bSdrh /* subtype(X)
1019d44f18bSdrh **
1029d44f18bSdrh ** Return the subtype of X
1039d44f18bSdrh */
subtypeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1049d44f18bSdrh static void subtypeFunc(
1059d44f18bSdrh   sqlite3_context *context,
1069d44f18bSdrh   int argc,
1079d44f18bSdrh   sqlite3_value **argv
1089d44f18bSdrh ){
10969b0ce33Sdrh   UNUSED_PARAMETER(argc);
1109d44f18bSdrh   sqlite3_result_int(context, sqlite3_value_subtype(argv[0]));
1119d44f18bSdrh }
1125708d2deSdrh 
1135708d2deSdrh /*
1140bce8354Sdrh ** Implementation of the length() function
1150bce8354Sdrh */
lengthFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)116f9b596ebSdrh static void lengthFunc(
117f9b596ebSdrh   sqlite3_context *context,
118f9b596ebSdrh   int argc,
119f9b596ebSdrh   sqlite3_value **argv
120f9b596ebSdrh ){
1210bce8354Sdrh   assert( argc==1 );
122f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
123f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1249c054830Sdrh     case SQLITE_BLOB:
1259c054830Sdrh     case SQLITE_INTEGER:
1269c054830Sdrh     case SQLITE_FLOAT: {
127f4479501Sdrh       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
128f9b596ebSdrh       break;
129f9b596ebSdrh     }
1309c054830Sdrh     case SQLITE_TEXT: {
1312646da7eSdrh       const unsigned char *z = sqlite3_value_text(argv[0]);
1327ea3469eSdrh       const unsigned char *z0;
1337ea3469eSdrh       unsigned char c;
1347a521cfbSdrh       if( z==0 ) return;
1357ea3469eSdrh       z0 = z;
1367ea3469eSdrh       while( (c = *z)!=0 ){
1377ea3469eSdrh         z++;
1387ea3469eSdrh         if( c>=0xc0 ){
1397ea3469eSdrh           while( (*z & 0xc0)==0x80 ){ z++; z0++; }
1404a919118Sdrh         }
1417ea3469eSdrh       }
1427ea3469eSdrh       sqlite3_result_int(context, (int)(z-z0));
143f9b596ebSdrh       break;
144f9b596ebSdrh     }
145f9b596ebSdrh     default: {
146f9b596ebSdrh       sqlite3_result_null(context);
147f9b596ebSdrh       break;
148f9b596ebSdrh     }
149f9b596ebSdrh   }
1500bce8354Sdrh }
1510bce8354Sdrh 
1520bce8354Sdrh /*
1532ba3cccfSdrh ** Implementation of the abs() function.
1542ba3cccfSdrh **
1552ba3cccfSdrh ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
1562ba3cccfSdrh ** the numeric argument X.
1570bce8354Sdrh */
absFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1580ae8b831Sdanielk1977 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1590bce8354Sdrh   assert( argc==1 );
160f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
161f9b596ebSdrh   switch( sqlite3_value_type(argv[0]) ){
1629c054830Sdrh     case SQLITE_INTEGER: {
163f93bbbeaSdanielk1977       i64 iVal = sqlite3_value_int64(argv[0]);
16452fc849aSdrh       if( iVal<0 ){
165693e6719Sdrh         if( iVal==SMALLEST_INT64 ){
166eb091cdfSdrh           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
167eb091cdfSdrh           ** then abs(X) throws an integer overflow error since there is no
1682ba3cccfSdrh           ** equivalent positive 64-bit two complement value. */
16952fc849aSdrh           sqlite3_result_error(context, "integer overflow", -1);
17052fc849aSdrh           return;
17152fc849aSdrh         }
17252fc849aSdrh         iVal = -iVal;
17352fc849aSdrh       }
174f93bbbeaSdanielk1977       sqlite3_result_int64(context, iVal);
175f9b596ebSdrh       break;
176f9b596ebSdrh     }
1779c054830Sdrh     case SQLITE_NULL: {
1782ba3cccfSdrh       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
179f9b596ebSdrh       sqlite3_result_null(context);
180f9b596ebSdrh       break;
181f9b596ebSdrh     }
182f9b596ebSdrh     default: {
1832ba3cccfSdrh       /* Because sqlite3_value_double() returns 0.0 if the argument is not
1842ba3cccfSdrh       ** something that can be converted into a number, we have:
185643091f0Sdrh       ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
186643091f0Sdrh       ** that cannot be converted to a numeric value.
1872ba3cccfSdrh       */
188f93bbbeaSdanielk1977       double rVal = sqlite3_value_double(argv[0]);
18952fc849aSdrh       if( rVal<0 ) rVal = -rVal;
190f93bbbeaSdanielk1977       sqlite3_result_double(context, rVal);
191f9b596ebSdrh       break;
192f9b596ebSdrh     }
193f9b596ebSdrh   }
1940bce8354Sdrh }
1950bce8354Sdrh 
1960bce8354Sdrh /*
197d55e0729Sdrh ** Implementation of the instr() function.
198d55e0729Sdrh **
199d55e0729Sdrh ** instr(haystack,needle) finds the first occurrence of needle
200d55e0729Sdrh ** in haystack and returns the number of previous characters plus 1,
201d55e0729Sdrh ** or 0 if needle does not occur within haystack.
202d55e0729Sdrh **
203d55e0729Sdrh ** If both haystack and needle are BLOBs, then the result is one more than
204d55e0729Sdrh ** the number of bytes in haystack prior to the first occurrence of needle,
205d55e0729Sdrh ** or 0 if needle never occurs in haystack.
206d55e0729Sdrh */
instrFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)207d55e0729Sdrh static void instrFunc(
208d55e0729Sdrh   sqlite3_context *context,
209d55e0729Sdrh   int argc,
210d55e0729Sdrh   sqlite3_value **argv
211d55e0729Sdrh ){
212d55e0729Sdrh   const unsigned char *zHaystack;
213d55e0729Sdrh   const unsigned char *zNeedle;
214d55e0729Sdrh   int nHaystack;
215d55e0729Sdrh   int nNeedle;
216d55e0729Sdrh   int typeHaystack, typeNeedle;
217d55e0729Sdrh   int N = 1;
218d55e0729Sdrh   int isText;
219c930b405Sdrh   unsigned char firstChar;
22097b02505Sdrh   sqlite3_value *pC1 = 0;
22197b02505Sdrh   sqlite3_value *pC2 = 0;
222d55e0729Sdrh 
22368c804b9Sdrh   UNUSED_PARAMETER(argc);
224d55e0729Sdrh   typeHaystack = sqlite3_value_type(argv[0]);
225d55e0729Sdrh   typeNeedle = sqlite3_value_type(argv[1]);
226d55e0729Sdrh   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
227d55e0729Sdrh   nHaystack = sqlite3_value_bytes(argv[0]);
228d55e0729Sdrh   nNeedle = sqlite3_value_bytes(argv[1]);
229895decf6Sdan   if( nNeedle>0 ){
230d55e0729Sdrh     if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
231d55e0729Sdrh       zHaystack = sqlite3_value_blob(argv[0]);
232d55e0729Sdrh       zNeedle = sqlite3_value_blob(argv[1]);
233d55e0729Sdrh       isText = 0;
23497b02505Sdrh     }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){
235d55e0729Sdrh       zHaystack = sqlite3_value_text(argv[0]);
236d55e0729Sdrh       zNeedle = sqlite3_value_text(argv[1]);
237d55e0729Sdrh       isText = 1;
23897b02505Sdrh     }else{
23997b02505Sdrh       pC1 = sqlite3_value_dup(argv[0]);
24097b02505Sdrh       zHaystack = sqlite3_value_text(pC1);
2419d702840Sdrh       if( zHaystack==0 ) goto endInstrOOM;
2429d702840Sdrh       nHaystack = sqlite3_value_bytes(pC1);
24397b02505Sdrh       pC2 = sqlite3_value_dup(argv[1]);
24497b02505Sdrh       zNeedle = sqlite3_value_text(pC2);
2459d702840Sdrh       if( zNeedle==0 ) goto endInstrOOM;
2469d702840Sdrh       nNeedle = sqlite3_value_bytes(pC2);
24797b02505Sdrh       isText = 1;
248d55e0729Sdrh     }
2499d702840Sdrh     if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;
250c930b405Sdrh     firstChar = zNeedle[0];
251c930b405Sdrh     while( nNeedle<=nHaystack
252c930b405Sdrh        && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
253c930b405Sdrh     ){
254d55e0729Sdrh       N++;
255d55e0729Sdrh       do{
256d55e0729Sdrh         nHaystack--;
257d55e0729Sdrh         zHaystack++;
258d55e0729Sdrh       }while( isText && (zHaystack[0]&0xc0)==0x80 );
259d55e0729Sdrh     }
260d55e0729Sdrh     if( nNeedle>nHaystack ) N = 0;
261895decf6Sdan   }
262d55e0729Sdrh   sqlite3_result_int(context, N);
26397b02505Sdrh endInstr:
26497b02505Sdrh   sqlite3_value_free(pC1);
26597b02505Sdrh   sqlite3_value_free(pC2);
2669d702840Sdrh   return;
2679d702840Sdrh endInstrOOM:
2689d702840Sdrh   sqlite3_result_error_nomem(context);
2699d702840Sdrh   goto endInstr;
270d55e0729Sdrh }
271d55e0729Sdrh 
272d55e0729Sdrh /*
2736bcd5857Sdrh ** Implementation of the printf() (a.k.a. format()) SQL function.
274a5c1416dSdrh */
printfFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)275a5c1416dSdrh static void printfFunc(
276a5c1416dSdrh   sqlite3_context *context,
277a5c1416dSdrh   int argc,
278a5c1416dSdrh   sqlite3_value **argv
279a5c1416dSdrh ){
280a5c1416dSdrh   PrintfArguments x;
281a5c1416dSdrh   StrAccum str;
282a5c1416dSdrh   const char *zFormat;
283a5c1416dSdrh   int n;
284c0490572Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
285a5c1416dSdrh 
286a5c1416dSdrh   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
287a5c1416dSdrh     x.nArg = argc-1;
288a5c1416dSdrh     x.nUsed = 0;
289a5c1416dSdrh     x.apArg = argv+1;
290c0490572Sdrh     sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
2915f4a686fSdrh     str.printfFlags = SQLITE_PRINTF_SQLFUNC;
2920cdbe1aeSdrh     sqlite3_str_appendf(&str, zFormat, &x);
293a5c1416dSdrh     n = str.nChar;
294a5c1416dSdrh     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
295a5c1416dSdrh                         SQLITE_DYNAMIC);
296a5c1416dSdrh   }
297a5c1416dSdrh }
298a5c1416dSdrh 
299a5c1416dSdrh /*
300f764e6fcSdrh ** Implementation of the substr() function.
301f764e6fcSdrh **
302f764e6fcSdrh ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
303f764e6fcSdrh ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
304f764e6fcSdrh ** of x.  If x is text, then we actually count UTF-8 characters.
305f764e6fcSdrh ** If x is a blob, then we count bytes.
306f764e6fcSdrh **
307f764e6fcSdrh ** If p1 is negative, then we begin abs(p1) from the end of x[].
308779b8f12Sshaneh **
309f7b5496eSdrh ** If p2 is negative, return the p2 characters preceding p1.
3100bce8354Sdrh */
substrFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)311f9b596ebSdrh static void substrFunc(
312f9b596ebSdrh   sqlite3_context *context,
313f9b596ebSdrh   int argc,
314f9b596ebSdrh   sqlite3_value **argv
315f9b596ebSdrh ){
3162646da7eSdrh   const unsigned char *z;
3172646da7eSdrh   const unsigned char *z2;
318023ae03aSdrh   int len;
319f764e6fcSdrh   int p0type;
320023ae03aSdrh   i64 p1, p2;
32165595cd6Sdrh   int negP2 = 0;
322f9b596ebSdrh 
32364f31519Sdrh   assert( argc==3 || argc==2 );
3248198d254Sdrh   if( sqlite3_value_type(argv[1])==SQLITE_NULL
3258198d254Sdrh    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
3268198d254Sdrh   ){
3278198d254Sdrh     return;
3288198d254Sdrh   }
329f764e6fcSdrh   p0type = sqlite3_value_type(argv[0]);
3304adc4cb9Sdrh   p1 = sqlite3_value_int(argv[1]);
331f764e6fcSdrh   if( p0type==SQLITE_BLOB ){
332f764e6fcSdrh     len = sqlite3_value_bytes(argv[0]);
333f764e6fcSdrh     z = sqlite3_value_blob(argv[0]);
334f764e6fcSdrh     if( z==0 ) return;
3351f0feef8Sdrh     assert( len==sqlite3_value_bytes(argv[0]) );
336f764e6fcSdrh   }else{
3374f26d6c4Sdrh     z = sqlite3_value_text(argv[0]);
3380bce8354Sdrh     if( z==0 ) return;
3394a919118Sdrh     len = 0;
3404adc4cb9Sdrh     if( p1<0 ){
3414a919118Sdrh       for(z2=z; *z2; len++){
3424a919118Sdrh         SQLITE_SKIP_UTF8(z2);
3434a919118Sdrh       }
344f764e6fcSdrh     }
3454adc4cb9Sdrh   }
346883ad049Sdrh #ifdef SQLITE_SUBSTR_COMPATIBILITY
347883ad049Sdrh   /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
348883ad049Sdrh   ** as substr(X,1,N) - it returns the first N characters of X.  This
349883ad049Sdrh   ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
350883ad049Sdrh   ** from 2009-02-02 for compatibility of applications that exploited the
351883ad049Sdrh   ** old buggy behavior. */
352883ad049Sdrh   if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
353883ad049Sdrh #endif
35464f31519Sdrh   if( argc==3 ){
35551ad0ecdSdanielk1977     p2 = sqlite3_value_int(argv[2]);
35665595cd6Sdrh     if( p2<0 ){
35765595cd6Sdrh       p2 = -p2;
35865595cd6Sdrh       negP2 = 1;
35965595cd6Sdrh     }
36064f31519Sdrh   }else{
361bb4957f8Sdrh     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
36264f31519Sdrh   }
3630bce8354Sdrh   if( p1<0 ){
36489425d5eSdrh     p1 += len;
365653bc759Sdrh     if( p1<0 ){
366653bc759Sdrh       p2 += p1;
36765595cd6Sdrh       if( p2<0 ) p2 = 0;
368653bc759Sdrh       p1 = 0;
369653bc759Sdrh     }
3700bce8354Sdrh   }else if( p1>0 ){
3710bce8354Sdrh     p1--;
37265595cd6Sdrh   }else if( p2>0 ){
37365595cd6Sdrh     p2--;
3740bce8354Sdrh   }
37565595cd6Sdrh   if( negP2 ){
37665595cd6Sdrh     p1 -= p2;
3774e79c594Sdrh     if( p1<0 ){
3784e79c594Sdrh       p2 += p1;
3794e79c594Sdrh       p1 = 0;
3804e79c594Sdrh     }
3814e79c594Sdrh   }
38265595cd6Sdrh   assert( p1>=0 && p2>=0 );
383f764e6fcSdrh   if( p0type!=SQLITE_BLOB ){
3844a919118Sdrh     while( *z && p1 ){
3854a919118Sdrh       SQLITE_SKIP_UTF8(z);
3864a919118Sdrh       p1--;
3870bce8354Sdrh     }
3884a919118Sdrh     for(z2=z; *z2 && p2; p2--){
3894a919118Sdrh       SQLITE_SKIP_UTF8(z2);
3900bce8354Sdrh     }
391bbf483f8Sdrh     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
392bbf483f8Sdrh                           SQLITE_UTF8);
393f764e6fcSdrh   }else{
3944adc4cb9Sdrh     if( p1+p2>len ){
3954adc4cb9Sdrh       p2 = len-p1;
3964adc4cb9Sdrh       if( p2<0 ) p2 = 0;
3974adc4cb9Sdrh     }
398bbf483f8Sdrh     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
399f764e6fcSdrh   }
4000bce8354Sdrh }
4010bce8354Sdrh 
4020bce8354Sdrh /*
4030bce8354Sdrh ** Implementation of the round() function
4040bce8354Sdrh */
405fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
roundFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4060ae8b831Sdanielk1977 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
40751ad0ecdSdanielk1977   int n = 0;
4080bce8354Sdrh   double r;
40950d654daSdrh   char *zBuf;
4100bce8354Sdrh   assert( argc==1 || argc==2 );
41151ad0ecdSdanielk1977   if( argc==2 ){
4129c054830Sdrh     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
41351ad0ecdSdanielk1977     n = sqlite3_value_int(argv[1]);
4140bce8354Sdrh     if( n>30 ) n = 30;
4150bce8354Sdrh     if( n<0 ) n = 0;
41651ad0ecdSdanielk1977   }
417d589a92aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
4184f26d6c4Sdrh   r = sqlite3_value_double(argv[0]);
419147e176aSshaneh   /* If Y==0 and X will fit in a 64-bit int,
420147e176aSshaneh   ** handle the rounding directly,
421147e176aSshaneh   ** otherwise use printf.
422147e176aSshaneh   */
42384422db9Sdrh   if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
42484422db9Sdrh     /* The value has no fractional part so there is nothing to round */
42584422db9Sdrh   }else if( n==0 ){
42684422db9Sdrh     r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
427147e176aSshaneh   }else{
42850d654daSdrh     zBuf = sqlite3_mprintf("%.*f",n,r);
42950d654daSdrh     if( zBuf==0 ){
43050d654daSdrh       sqlite3_result_error_nomem(context);
431147e176aSshaneh       return;
432147e176aSshaneh     }
43355700bcdSdrh     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
43450d654daSdrh     sqlite3_free(zBuf);
4350bce8354Sdrh   }
436147e176aSshaneh   sqlite3_result_double(context, r);
43750d654daSdrh }
438fbd60f82Sshane #endif
439dc04c583Sdrh 
44026783a58Sdanielk1977 /*
441f3cdcdccSdrh ** Allocate nByte bytes of space using sqlite3Malloc(). If the
44226783a58Sdanielk1977 ** allocation fails, call sqlite3_result_error_nomem() to notify
44327e62dbeSdrh ** the database handle that malloc() has failed and return NULL.
44427e62dbeSdrh ** If nByte is larger than the maximum string or blob length, then
44527e62dbeSdrh ** raise an SQLITE_TOOBIG exception and return NULL.
44626783a58Sdanielk1977 */
contextMalloc(sqlite3_context * context,i64 nByte)447b1a6c3c1Sdrh static void *contextMalloc(sqlite3_context *context, i64 nByte){
448bb4957f8Sdrh   char *z;
44927e62dbeSdrh   sqlite3 *db = sqlite3_context_db_handle(context);
450ef31c6aaSdrh   assert( nByte>0 );
45127e62dbeSdrh   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
45227e62dbeSdrh   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
45327e62dbeSdrh   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
454bb4957f8Sdrh     sqlite3_result_error_toobig(context);
455bb4957f8Sdrh     z = 0;
456bb4957f8Sdrh   }else{
457da4ca9d1Sdrh     z = sqlite3Malloc(nByte);
458ef31c6aaSdrh     if( !z ){
459a1644fd8Sdanielk1977       sqlite3_result_error_nomem(context);
460a1644fd8Sdanielk1977     }
461bb4957f8Sdrh   }
462a1644fd8Sdanielk1977   return z;
463a1644fd8Sdanielk1977 }
464a1644fd8Sdanielk1977 
465dc04c583Sdrh /*
466dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
467dc04c583Sdrh */
upperFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4680ae8b831Sdanielk1977 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
4697a521cfbSdrh   char *z1;
4707a521cfbSdrh   const char *z2;
4719310ef23Sdrh   int i, n;
4721d34fdecSdrh   UNUSED_PARAMETER(argc);
4737a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
4741f0feef8Sdrh   n = sqlite3_value_bytes(argv[0]);
4751f0feef8Sdrh   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
4761f0feef8Sdrh   assert( z2==(char*)sqlite3_value_text(argv[0]) );
4777a521cfbSdrh   if( z2 ){
478b1a6c3c1Sdrh     z1 = contextMalloc(context, ((i64)n)+1);
4797a521cfbSdrh     if( z1 ){
480df901d34Sdrh       for(i=0; i<n; i++){
481df901d34Sdrh         z1[i] = (char)sqlite3Toupper(z2[i]);
482dc04c583Sdrh       }
483df901d34Sdrh       sqlite3_result_text(context, z1, n, sqlite3_free);
4847a521cfbSdrh     }
4857a521cfbSdrh   }
486dc04c583Sdrh }
lowerFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)4870ae8b831Sdanielk1977 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
488df901d34Sdrh   char *z1;
4897a521cfbSdrh   const char *z2;
4909310ef23Sdrh   int i, n;
4911d34fdecSdrh   UNUSED_PARAMETER(argc);
4927a521cfbSdrh   z2 = (char*)sqlite3_value_text(argv[0]);
4931f0feef8Sdrh   n = sqlite3_value_bytes(argv[0]);
4941f0feef8Sdrh   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
4951f0feef8Sdrh   assert( z2==(char*)sqlite3_value_text(argv[0]) );
4967a521cfbSdrh   if( z2 ){
497b1a6c3c1Sdrh     z1 = contextMalloc(context, ((i64)n)+1);
4987a521cfbSdrh     if( z1 ){
499df901d34Sdrh       for(i=0; i<n; i++){
500df901d34Sdrh         z1[i] = sqlite3Tolower(z2[i]);
501dc04c583Sdrh       }
502df901d34Sdrh       sqlite3_result_text(context, z1, n, sqlite3_free);
5037a521cfbSdrh     }
5047a521cfbSdrh   }
505dc04c583Sdrh }
506dc04c583Sdrh 
507ae6bb957Sdrh /*
508cca9f3d2Sdrh ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
509cca9f3d2Sdrh ** as VDBE code so that unused argument values do not have to be computed.
510cca9f3d2Sdrh ** However, we still need some kind of function implementation for this
511cca9f3d2Sdrh ** routines in the function table.  The noopFunc macro provides this.
512cca9f3d2Sdrh ** noopFunc will never be called so it doesn't matter what the implementation
513cca9f3d2Sdrh ** is.  We might as well use the "version()" function as a substitute.
514ae6bb957Sdrh */
515cca9f3d2Sdrh #define noopFunc versionFunc   /* Substitute function - never called */
5163212e182Sdrh 
5173212e182Sdrh /*
518f9ffac96Sdrh ** Implementation of random().  Return a random integer.
519f9ffac96Sdrh */
randomFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)520f9b596ebSdrh static void randomFunc(
521f9b596ebSdrh   sqlite3_context *context,
52262c14b34Sdanielk1977   int NotUsed,
52362c14b34Sdanielk1977   sqlite3_value **NotUsed2
524f9b596ebSdrh ){
52552fc849aSdrh   sqlite_int64 r;
52662c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
5272fa1868fSdrh   sqlite3_randomness(sizeof(r), &r);
5283034e3d3Sdrh   if( r<0 ){
5293034e3d3Sdrh     /* We need to prevent a random number of 0x8000000000000000
5303034e3d3Sdrh     ** (or -9223372036854775808) since when you do abs() of that
5313034e3d3Sdrh     ** number of you get the same value back again.  To do this
5323034e3d3Sdrh     ** in a way that is testable, mask the sign bit off of negative
5333034e3d3Sdrh     ** values, resulting in a positive value.  Then take the
5343034e3d3Sdrh     ** 2s complement of that positive value.  The end result can
5353034e3d3Sdrh     ** therefore be no less than -9223372036854775807.
5363034e3d3Sdrh     */
537af8001bfSdrh     r = -(r & LARGEST_INT64);
5383034e3d3Sdrh   }
53952fc849aSdrh   sqlite3_result_int64(context, r);
540f9ffac96Sdrh }
541f9ffac96Sdrh 
542f9ffac96Sdrh /*
543137c728fSdrh ** Implementation of randomblob(N).  Return a random blob
544137c728fSdrh ** that is N bytes long.
54563cf66f0Sdrh */
randomBlob(sqlite3_context * context,int argc,sqlite3_value ** argv)546137c728fSdrh static void randomBlob(
54763cf66f0Sdrh   sqlite3_context *context,
54863cf66f0Sdrh   int argc,
54963cf66f0Sdrh   sqlite3_value **argv
55063cf66f0Sdrh ){
5513cb79202Sdrh   sqlite3_int64 n;
552137c728fSdrh   unsigned char *p;
55363cf66f0Sdrh   assert( argc==1 );
554f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
5553cb79202Sdrh   n = sqlite3_value_int64(argv[0]);
556023ae03aSdrh   if( n<1 ){
557023ae03aSdrh     n = 1;
558023ae03aSdrh   }
559a1644fd8Sdanielk1977   p = contextMalloc(context, n);
56002d85836Sdrh   if( p ){
5612fa1868fSdrh     sqlite3_randomness(n, p);
56217435752Sdrh     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
56302d85836Sdrh   }
56463cf66f0Sdrh }
56563cf66f0Sdrh 
56663cf66f0Sdrh /*
5676ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
56824b03fd0Sdanielk1977 ** value is the same as the sqlite3_last_insert_rowid() API function.
5696ed41ad7Sdrh */
last_insert_rowid(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)57051ad0ecdSdanielk1977 static void last_insert_rowid(
5710ae8b831Sdanielk1977   sqlite3_context *context,
57262c14b34Sdanielk1977   int NotUsed,
57362c14b34Sdanielk1977   sqlite3_value **NotUsed2
57451ad0ecdSdanielk1977 ){
575fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
57662c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
577ab2f1f95Sdrh   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
578ab2f1f95Sdrh   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
579ab2f1f95Sdrh   ** function. */
580f9b596ebSdrh   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
5816ed41ad7Sdrh }
5826ed41ad7Sdrh 
583f146a776Srdc /*
584ab2f1f95Sdrh ** Implementation of the changes() SQL function.
585ab2f1f95Sdrh **
586c0bd26a2Sdrh ** IMP: R-32760-32347 The changes() SQL function is a wrapper
587c0bd26a2Sdrh ** around the sqlite3_changes64() C/C++ function and hence follows the
588c0bd26a2Sdrh ** same rules for counting changes.
589f146a776Srdc */
changes(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)590b28af71aSdanielk1977 static void changes(
591f9b596ebSdrh   sqlite3_context *context,
59262c14b34Sdanielk1977   int NotUsed,
59362c14b34Sdanielk1977   sqlite3_value **NotUsed2
594f9b596ebSdrh ){
595fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
59662c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
5972c718873Sdan   sqlite3_result_int64(context, sqlite3_changes64(db));
598b0c374ffSrdc }
599f146a776Srdc 
600f146a776Srdc /*
601b28af71aSdanielk1977 ** Implementation of the total_changes() SQL function.  The return value is
60210496f76Slarrybr ** the same as the sqlite3_total_changes64() API function.
603f146a776Srdc */
total_changes(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)604b28af71aSdanielk1977 static void total_changes(
6050ae8b831Sdanielk1977   sqlite3_context *context,
60662c14b34Sdanielk1977   int NotUsed,
60762c14b34Sdanielk1977   sqlite3_value **NotUsed2
60851ad0ecdSdanielk1977 ){
609fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
61062c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
611c0bd26a2Sdrh   /* IMP: R-11217-42568 This function is a wrapper around the
612c0bd26a2Sdrh   ** sqlite3_total_changes64() C/C++ interface. */
61310496f76Slarrybr   sqlite3_result_int64(context, sqlite3_total_changes64(db));
614b0c374ffSrdc }
615b0c374ffSrdc 
6166ed41ad7Sdrh /*
6174e5ffc5fSdrh ** A structure defining how to do GLOB-style comparisons.
618d02eb1fdSdanielk1977 */
6194e5ffc5fSdrh struct compareInfo {
62007e83472Sdrh   u8 matchAll;          /* "*" or "%" */
62107e83472Sdrh   u8 matchOne;          /* "?" or "_" */
62207e83472Sdrh   u8 matchSet;          /* "[" or 0 */
62307e83472Sdrh   u8 noCase;            /* true to ignore case differences */
624d02eb1fdSdanielk1977 };
62555ef4d97Sdrh 
626b9175aedSdrh /*
627b9175aedSdrh ** For LIKE and GLOB matching on EBCDIC machines, assume that every
628b0870486Sdrh ** character is exactly one byte in size.  Also, provde the Utf8Read()
629b0870486Sdrh ** macro for fast reading of the next character in the common case where
630b0870486Sdrh ** the next character is ASCII.
631b9175aedSdrh */
632b9175aedSdrh #if defined(SQLITE_EBCDIC)
63342610961Sdrh # define sqlite3Utf8Read(A)        (*((*A)++))
634b0870486Sdrh # define Utf8Read(A)               (*(A++))
635b9175aedSdrh #else
636b0870486Sdrh # define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
637b9175aedSdrh #endif
638b9175aedSdrh 
6394e5ffc5fSdrh static const struct compareInfo globInfo = { '*', '?', '[', 0 };
64070031fa3Sdrh /* The correct SQL-92 behavior is for the LIKE operator to ignore
64170031fa3Sdrh ** case.  Thus  'a' LIKE 'A' would be true. */
64255ef4d97Sdrh static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
64370031fa3Sdrh /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
64470031fa3Sdrh ** is case sensitive causing 'a' LIKE 'A' to be false */
64555ef4d97Sdrh static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
646d02eb1fdSdanielk1977 
647d02eb1fdSdanielk1977 /*
648698a01caSdrh ** Possible error returns from patternMatch()
649698a01caSdrh */
650698a01caSdrh #define SQLITE_MATCH             0
651698a01caSdrh #define SQLITE_NOMATCH           1
652698a01caSdrh #define SQLITE_NOWILDCARDMATCH   2
653698a01caSdrh 
654698a01caSdrh /*
655698a01caSdrh ** Compare two UTF-8 strings for equality where the first string is
656698a01caSdrh ** a GLOB or LIKE expression.  Return values:
657698a01caSdrh **
658698a01caSdrh **    SQLITE_MATCH:            Match
659698a01caSdrh **    SQLITE_NOMATCH:          No match
660698a01caSdrh **    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
6610ac65892Sdrh **
6624e5ffc5fSdrh ** Globbing rules:
6630ac65892Sdrh **
6644e5ffc5fSdrh **      '*'       Matches any sequence of zero or more characters.
665d02eb1fdSdanielk1977 **
6664e5ffc5fSdrh **      '?'       Matches exactly one character.
6674e5ffc5fSdrh **
6684e5ffc5fSdrh **     [...]      Matches one character from the enclosed list of
6694e5ffc5fSdrh **                characters.
6704e5ffc5fSdrh **
6714e5ffc5fSdrh **     [^...]     Matches one character not in the enclosed list.
6724e5ffc5fSdrh **
6734e5ffc5fSdrh ** With the [...] and [^...] matching, a ']' character can be included
6744e5ffc5fSdrh ** in the list by making it the first character after '[' or '^'.  A
6754e5ffc5fSdrh ** range of characters can be specified using '-'.  Example:
6764e5ffc5fSdrh ** "[a-z]" matches any single lower-case letter.  To match a '-', make
6774e5ffc5fSdrh ** it the last character in the list.
6784e5ffc5fSdrh **
6799fdfdc89Sdrh ** Like matching rules:
6809fdfdc89Sdrh **
6819fdfdc89Sdrh **      '%'       Matches any sequence of zero or more characters
6829fdfdc89Sdrh **
6839fdfdc89Sdrh ***     '_'       Matches any one character
6849fdfdc89Sdrh **
6859fdfdc89Sdrh **      Ec        Where E is the "esc" character and c is any other
6869fdfdc89Sdrh **                character, including '%', '_', and esc, match exactly c.
6879fdfdc89Sdrh **
688b0870486Sdrh ** The comments within this routine usually assume glob matching.
6899fdfdc89Sdrh **
6904e5ffc5fSdrh ** This routine is usually quick, but can be N**2 in the worst case.
6910ac65892Sdrh */
patternCompare(const u8 * zPattern,const u8 * zString,const struct compareInfo * pInfo,u32 matchOther)6927c6303c0Sdanielk1977 static int patternCompare(
6934e5ffc5fSdrh   const u8 *zPattern,              /* The glob pattern */
6944e5ffc5fSdrh   const u8 *zString,               /* The string to compare against the glob */
6957c6303c0Sdanielk1977   const struct compareInfo *pInfo, /* Information about how to do the compare */
696698a01caSdrh   u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
69751ad0ecdSdanielk1977 ){
6989fdfdc89Sdrh   u32 c, c2;                       /* Next pattern and input string chars */
6999fdfdc89Sdrh   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
7009fdfdc89Sdrh   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
7019fdfdc89Sdrh   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
7029fdfdc89Sdrh   const u8 *zEscaped = 0;          /* One past the last escaped input char */
703d02eb1fdSdanielk1977 
704b0870486Sdrh   while( (c = Utf8Read(zPattern))!=0 ){
7059fdfdc89Sdrh     if( c==matchAll ){  /* Match "*" */
7069fdfdc89Sdrh       /* Skip over multiple "*" characters in the pattern.  If there
7079fdfdc89Sdrh       ** are also "?" characters, skip those as well, but consume a
7089fdfdc89Sdrh       ** single character of the input string for each "?" skipped */
70933941691Sdrh       while( (c=Utf8Read(zPattern)) == matchAll
71033941691Sdrh              || (c == matchOne && matchOne!=0) ){
71142610961Sdrh         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
712698a01caSdrh           return SQLITE_NOWILDCARDMATCH;
713d02eb1fdSdanielk1977         }
7144e5ffc5fSdrh       }
71566150956Sdrh       if( c==0 ){
716698a01caSdrh         return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
71788b3322fSdrh       }else if( c==matchOther ){
71807e83472Sdrh         if( pInfo->matchSet==0 ){
71942610961Sdrh           c = sqlite3Utf8Read(&zPattern);
720698a01caSdrh           if( c==0 ) return SQLITE_NOWILDCARDMATCH;
72188b3322fSdrh         }else{
7229fdfdc89Sdrh           /* "[...]" immediately follows the "*".  We have to do a slow
7239fdfdc89Sdrh           ** recursive search in this case, but it is an unusual case. */
72488b3322fSdrh           assert( matchOther<0x80 );  /* '[' is a single-byte character */
725698a01caSdrh           while( *zString ){
726698a01caSdrh             int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
727698a01caSdrh             if( bMatch!=SQLITE_NOMATCH ) return bMatch;
7284a919118Sdrh             SQLITE_SKIP_UTF8(zString);
7294e5ffc5fSdrh           }
730698a01caSdrh           return SQLITE_NOWILDCARDMATCH;
73166150956Sdrh         }
73288b3322fSdrh       }
7339fdfdc89Sdrh 
7349fdfdc89Sdrh       /* At this point variable c contains the first character of the
7359fdfdc89Sdrh       ** pattern string past the "*".  Search in the input string for the
7361a4a7376Sdan       ** first matching character and recursively continue the match from
7379fdfdc89Sdrh       ** that point.
7389fdfdc89Sdrh       **
7399fdfdc89Sdrh       ** For a case-insensitive search, set variable cx to be the same as
7409fdfdc89Sdrh       ** c but in the other case and search the input string for either
7419fdfdc89Sdrh       ** c or cx.
7429fdfdc89Sdrh       */
7432bc4a6caSdan       if( c<0x80 ){
744eba21f9eSdrh         char zStop[3];
745698a01caSdrh         int bMatch;
7469fdfdc89Sdrh         if( noCase ){
747eba21f9eSdrh           zStop[0] = sqlite3Toupper(c);
748eba21f9eSdrh           zStop[1] = sqlite3Tolower(c);
749eba21f9eSdrh           zStop[2] = 0;
750ad7dd425Sdanielk1977         }else{
751eba21f9eSdrh           zStop[0] = c;
752eba21f9eSdrh           zStop[1] = 0;
75366150956Sdrh         }
754eba21f9eSdrh         while(1){
755eba21f9eSdrh           zString += strcspn((const char*)zString, zStop);
756eba21f9eSdrh           if( zString[0]==0 ) break;
757eba21f9eSdrh           zString++;
758698a01caSdrh           bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
759698a01caSdrh           if( bMatch!=SQLITE_NOMATCH ) return bMatch;
7604e5ffc5fSdrh         }
76188b3322fSdrh       }else{
762698a01caSdrh         int bMatch;
763b0870486Sdrh         while( (c2 = Utf8Read(zString))!=0 ){
7649fdfdc89Sdrh           if( c2!=c ) continue;
765698a01caSdrh           bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
766698a01caSdrh           if( bMatch!=SQLITE_NOMATCH ) return bMatch;
76766150956Sdrh         }
76888b3322fSdrh       }
769698a01caSdrh       return SQLITE_NOWILDCARDMATCH;
7709fdfdc89Sdrh     }
77188b3322fSdrh     if( c==matchOther ){
77207e83472Sdrh       if( pInfo->matchSet==0 ){
77388b3322fSdrh         c = sqlite3Utf8Read(&zPattern);
774698a01caSdrh         if( c==0 ) return SQLITE_NOMATCH;
7759fdfdc89Sdrh         zEscaped = zPattern;
77688b3322fSdrh       }else{
7771aa4f3e5Sdrh         u32 prior_c = 0;
7789fdfdc89Sdrh         int seen = 0;
7799fdfdc89Sdrh         int invert = 0;
78042610961Sdrh         c = sqlite3Utf8Read(&zString);
781698a01caSdrh         if( c==0 ) return SQLITE_NOMATCH;
78242610961Sdrh         c2 = sqlite3Utf8Read(&zPattern);
78366150956Sdrh         if( c2=='^' ){
78466150956Sdrh           invert = 1;
78542610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
78666150956Sdrh         }
7874e5ffc5fSdrh         if( c2==']' ){
7884e5ffc5fSdrh           if( c==']' ) seen = 1;
78942610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
7904e5ffc5fSdrh         }
79166150956Sdrh         while( c2 && c2!=']' ){
79266150956Sdrh           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
79342610961Sdrh             c2 = sqlite3Utf8Read(&zPattern);
7944e5ffc5fSdrh             if( c>=prior_c && c<=c2 ) seen = 1;
7954e5ffc5fSdrh             prior_c = 0;
79666150956Sdrh           }else{
79766150956Sdrh             if( c==c2 ){
7984e5ffc5fSdrh               seen = 1;
79966150956Sdrh             }
8004e5ffc5fSdrh             prior_c = c2;
801d02eb1fdSdanielk1977           }
80242610961Sdrh           c2 = sqlite3Utf8Read(&zPattern);
803d02eb1fdSdanielk1977         }
80466150956Sdrh         if( c2==0 || (seen ^ invert)==0 ){
805698a01caSdrh           return SQLITE_NOMATCH;
80666150956Sdrh         }
80788b3322fSdrh         continue;
808328d913cSdrh       }
80988b3322fSdrh     }
810b0870486Sdrh     c2 = Utf8Read(zString);
81188b3322fSdrh     if( c==c2 ) continue;
812c80937a5Sdrh     if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
8139fdfdc89Sdrh       continue;
8149fdfdc89Sdrh     }
8159fdfdc89Sdrh     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
816698a01caSdrh     return SQLITE_NOMATCH;
8170ac65892Sdrh   }
818698a01caSdrh   return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
8194e5ffc5fSdrh }
8204e5ffc5fSdrh 
82155ef4d97Sdrh /*
822698a01caSdrh ** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
823698a01caSdrh ** non-zero if there is no match.
82456282a5bSdrh */
sqlite3_strglob(const char * zGlobPattern,const char * zString)82556282a5bSdrh int sqlite3_strglob(const char *zGlobPattern, const char *zString){
826*42dddb97Sdrh   if( zString==0 ){
827*42dddb97Sdrh     return zGlobPattern!=0;
828*42dddb97Sdrh   }else if( zGlobPattern==0 ){
829*42dddb97Sdrh     return 1;
830*42dddb97Sdrh   }else {
831698a01caSdrh     return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
83256282a5bSdrh   }
833*42dddb97Sdrh }
83456282a5bSdrh 
83556282a5bSdrh /*
836698a01caSdrh ** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
837698a01caSdrh ** a miss - like strcmp().
8388b4a94adSdrh */
sqlite3_strlike(const char * zPattern,const char * zStr,unsigned int esc)8398b4a94adSdrh int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
840*42dddb97Sdrh   if( zStr==0 ){
841*42dddb97Sdrh     return zPattern!=0;
842*42dddb97Sdrh   }else if( zPattern==0 ){
843*42dddb97Sdrh     return 1;
844*42dddb97Sdrh   }else{
845698a01caSdrh     return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
8468b4a94adSdrh   }
847*42dddb97Sdrh }
8488b4a94adSdrh 
8498b4a94adSdrh /*
85055ef4d97Sdrh ** Count the number of times that the LIKE operator (or GLOB which is
85155ef4d97Sdrh ** just a variation of LIKE) gets called.  This is used for testing
85255ef4d97Sdrh ** only.
85355ef4d97Sdrh */
85455ef4d97Sdrh #ifdef SQLITE_TEST
85555ef4d97Sdrh int sqlite3_like_count = 0;
85655ef4d97Sdrh #endif
85755ef4d97Sdrh 
8583f6b0874Sdanielk1977 
8593f6b0874Sdanielk1977 /*
8603f6b0874Sdanielk1977 ** Implementation of the like() SQL function.  This function implements
8613f6b0874Sdanielk1977 ** the build-in LIKE operator.  The first argument to the function is the
8623f6b0874Sdanielk1977 ** pattern and the second argument is the string.  So, the SQL statements:
8633f6b0874Sdanielk1977 **
8643f6b0874Sdanielk1977 **       A LIKE B
8653f6b0874Sdanielk1977 **
8663f6b0874Sdanielk1977 ** is implemented as like(B,A).
8673f6b0874Sdanielk1977 **
86855ef4d97Sdrh ** This same function (with a different compareInfo structure) computes
86955ef4d97Sdrh ** the GLOB operator.
8703f6b0874Sdanielk1977 */
likeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)8713f6b0874Sdanielk1977 static void likeFunc(
8723f6b0874Sdanielk1977   sqlite3_context *context,
8733f6b0874Sdanielk1977   int argc,
8743f6b0874Sdanielk1977   sqlite3_value **argv
8753f6b0874Sdanielk1977 ){
876beb818d1Sdrh   const unsigned char *zA, *zB;
87707e83472Sdrh   u32 escape;
87827e62dbeSdrh   int nPat;
879bb4957f8Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
88007e83472Sdrh   struct compareInfo *pInfo = sqlite3_user_data(context);
881589c7876Sdrh   struct compareInfo backupInfo;
882beb818d1Sdrh 
88341d2e66eSdrh #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
88441d2e66eSdrh   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
88541d2e66eSdrh    || sqlite3_value_type(argv[1])==SQLITE_BLOB
88641d2e66eSdrh   ){
88741d2e66eSdrh #ifdef SQLITE_TEST
88841d2e66eSdrh     sqlite3_like_count++;
88941d2e66eSdrh #endif
89041d2e66eSdrh     sqlite3_result_int(context, 0);
89141d2e66eSdrh     return;
89241d2e66eSdrh   }
89341d2e66eSdrh #endif
8941f0feef8Sdrh 
895beb818d1Sdrh   /* Limit the length of the LIKE or GLOB pattern to avoid problems
896beb818d1Sdrh   ** of deep recursion and N*N behavior in patternCompare().
897beb818d1Sdrh   */
89827e62dbeSdrh   nPat = sqlite3_value_bytes(argv[0]);
89927e62dbeSdrh   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
90027e62dbeSdrh   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
90127e62dbeSdrh   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
902beb818d1Sdrh     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
903beb818d1Sdrh     return;
904beb818d1Sdrh   }
9057c6303c0Sdanielk1977   if( argc==3 ){
9067c6303c0Sdanielk1977     /* The escape character string must consist of a single UTF-8 character.
9077c6303c0Sdanielk1977     ** Otherwise, return an error.
9087c6303c0Sdanielk1977     */
9097c6303c0Sdanielk1977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
9107a521cfbSdrh     if( zEsc==0 ) return;
911ee85813cSdrh     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
9127c6303c0Sdanielk1977       sqlite3_result_error(context,
9137c6303c0Sdanielk1977           "ESCAPE expression must be a single character", -1);
9147c6303c0Sdanielk1977       return;
9157c6303c0Sdanielk1977     }
91642610961Sdrh     escape = sqlite3Utf8Read(&zEsc);
917589c7876Sdrh     if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
918589c7876Sdrh       memcpy(&backupInfo, pInfo, sizeof(backupInfo));
919589c7876Sdrh       pInfo = &backupInfo;
920589c7876Sdrh       if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
921589c7876Sdrh       if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
922589c7876Sdrh     }
92307e83472Sdrh   }else{
92407e83472Sdrh     escape = pInfo->matchSet;
9257c6303c0Sdanielk1977   }
926cf833239Sdrh   zB = sqlite3_value_text(argv[0]);
927cf833239Sdrh   zA = sqlite3_value_text(argv[1]);
9283f6b0874Sdanielk1977   if( zA && zB ){
92955ef4d97Sdrh #ifdef SQLITE_TEST
93055ef4d97Sdrh     sqlite3_like_count++;
93155ef4d97Sdrh #endif
932f49759bfSdrh     sqlite3_result_int(context,
933f49759bfSdrh                       patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
93451ad0ecdSdanielk1977   }
9358912d106Sdrh }
9368912d106Sdrh 
9378912d106Sdrh /*
9388912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
9398912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
9408912d106Sdrh ** arguments are equal to each other.
9418912d106Sdrh */
nullifFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** argv)942f9b596ebSdrh static void nullifFunc(
943f9b596ebSdrh   sqlite3_context *context,
94462c14b34Sdanielk1977   int NotUsed,
945f9b596ebSdrh   sqlite3_value **argv
946f9b596ebSdrh ){
947dc1bdc4fSdanielk1977   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
94862c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
949dc1bdc4fSdanielk1977   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
950f4479501Sdrh     sqlite3_result_value(context, argv[0]);
9518912d106Sdrh   }
9520ac65892Sdrh }
9530ac65892Sdrh 
954647cb0e1Sdrh /*
95547baebc2Sdrh ** Implementation of the sqlite_version() function.  The result is the version
956647cb0e1Sdrh ** of the SQLite library that is running.
957647cb0e1Sdrh */
versionFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)958f9b596ebSdrh static void versionFunc(
959f9b596ebSdrh   sqlite3_context *context,
96062c14b34Sdanielk1977   int NotUsed,
96162c14b34Sdanielk1977   sqlite3_value **NotUsed2
962f9b596ebSdrh ){
96362c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
964ab2f1f95Sdrh   /* IMP: R-48699-48617 This function is an SQL wrapper around the
965ab2f1f95Sdrh   ** sqlite3_libversion() C-interface. */
966ab2f1f95Sdrh   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
967647cb0e1Sdrh }
968647cb0e1Sdrh 
96947baebc2Sdrh /*
97047baebc2Sdrh ** Implementation of the sqlite_source_id() function. The result is a string
97147baebc2Sdrh ** that identifies the particular version of the source code used to build
97247baebc2Sdrh ** SQLite.
97347baebc2Sdrh */
sourceidFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)97447baebc2Sdrh static void sourceidFunc(
97547baebc2Sdrh   sqlite3_context *context,
97647baebc2Sdrh   int NotUsed,
97747baebc2Sdrh   sqlite3_value **NotUsed2
97847baebc2Sdrh ){
97947baebc2Sdrh   UNUSED_PARAMETER2(NotUsed, NotUsed2);
980ab2f1f95Sdrh   /* IMP: R-24470-31136 This function is an SQL wrapper around the
981ab2f1f95Sdrh   ** sqlite3_sourceid() C interface. */
982ab2f1f95Sdrh   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
98347baebc2Sdrh }
98447baebc2Sdrh 
985bdea6d13Sshaneh /*
9863ca84ef6Sdrh ** Implementation of the sqlite_log() function.  This is a wrapper around
9873ca84ef6Sdrh ** sqlite3_log().  The return value is NULL.  The function exists purely for
9883ca84ef6Sdrh ** its side-effects.
9893ca84ef6Sdrh */
errlogFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)990840561f2Sdrh static void errlogFunc(
9913ca84ef6Sdrh   sqlite3_context *context,
9923ca84ef6Sdrh   int argc,
9933ca84ef6Sdrh   sqlite3_value **argv
9943ca84ef6Sdrh ){
9953ca84ef6Sdrh   UNUSED_PARAMETER(argc);
9963ca84ef6Sdrh   UNUSED_PARAMETER(context);
9973ca84ef6Sdrh   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
9983ca84ef6Sdrh }
9993ca84ef6Sdrh 
10003ca84ef6Sdrh /*
1001dc97a8cdSshaneh ** Implementation of the sqlite_compileoption_used() function.
1002dc97a8cdSshaneh ** The result is an integer that identifies if the compiler option
1003dc97a8cdSshaneh ** was used to build SQLite.
1004bdea6d13Sshaneh */
1005dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
compileoptionusedFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1006dc97a8cdSshaneh static void compileoptionusedFunc(
1007bdea6d13Sshaneh   sqlite3_context *context,
1008dc97a8cdSshaneh   int argc,
1009dc97a8cdSshaneh   sqlite3_value **argv
1010bdea6d13Sshaneh ){
1011dc97a8cdSshaneh   const char *zOptName;
1012dc97a8cdSshaneh   assert( argc==1 );
1013dc97a8cdSshaneh   UNUSED_PARAMETER(argc);
1014a3e414cdSdrh   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
1015a3e414cdSdrh   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
1016a3e414cdSdrh   ** function.
1017a3e414cdSdrh   */
1018264a2d4dSdrh   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
1019dc97a8cdSshaneh     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
1020bdea6d13Sshaneh   }
1021dc97a8cdSshaneh }
1022dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1023dc97a8cdSshaneh 
1024dc97a8cdSshaneh /*
1025dc97a8cdSshaneh ** Implementation of the sqlite_compileoption_get() function.
1026dc97a8cdSshaneh ** The result is a string that identifies the compiler options
1027dc97a8cdSshaneh ** used to build SQLite.
1028dc97a8cdSshaneh */
1029dc97a8cdSshaneh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
compileoptiongetFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1030dc97a8cdSshaneh static void compileoptiongetFunc(
1031dc97a8cdSshaneh   sqlite3_context *context,
1032dc97a8cdSshaneh   int argc,
1033dc97a8cdSshaneh   sqlite3_value **argv
1034dc97a8cdSshaneh ){
1035dc97a8cdSshaneh   int n;
1036dc97a8cdSshaneh   assert( argc==1 );
1037dc97a8cdSshaneh   UNUSED_PARAMETER(argc);
1038a3e414cdSdrh   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
1039a3e414cdSdrh   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
1040a3e414cdSdrh   */
1041dc97a8cdSshaneh   n = sqlite3_value_int(argv[0]);
1042dc97a8cdSshaneh   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
1043dc97a8cdSshaneh }
1044dc97a8cdSshaneh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1045bdea6d13Sshaneh 
1046137c728fSdrh /* Array for converting from half-bytes (nybbles) into ASCII hex
1047137c728fSdrh ** digits. */
1048137c728fSdrh static const char hexdigits[] = {
1049137c728fSdrh   '0', '1', '2', '3', '4', '5', '6', '7',
1050137c728fSdrh   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
1051137c728fSdrh };
1052d641d646Sdanielk1977 
105347394703Sdrh /*
1054ef95d558Sdrh ** Append to pStr text that is the SQL literal representation of the
1055ef95d558Sdrh ** value contained in pValue.
105647394703Sdrh */
sqlite3QuoteValue(StrAccum * pStr,sqlite3_value * pValue)1057ef95d558Sdrh void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){
1058ef95d558Sdrh   /* As currently implemented, the string must be initially empty.
1059ef95d558Sdrh   ** we might relax this requirement in the future, but that will
1060ef95d558Sdrh   ** require enhancements to the implementation. */
1061ef95d558Sdrh   assert( pStr!=0 && pStr->nChar==0 );
1062ef95d558Sdrh 
1063ef95d558Sdrh   switch( sqlite3_value_type(pValue) ){
10649c054830Sdrh     case SQLITE_FLOAT: {
106572b3fbc7Sdrh       double r1, r2;
1066ef95d558Sdrh       const char *zVal;
1067ef95d558Sdrh       r1 = sqlite3_value_double(pValue);
1068ef95d558Sdrh       sqlite3_str_appendf(pStr, "%!.15g", r1);
1069ef95d558Sdrh       zVal = sqlite3_str_value(pStr);
1070ef95d558Sdrh       if( zVal ){
1071ef95d558Sdrh         sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);
107272b3fbc7Sdrh         if( r1!=r2 ){
1073ef95d558Sdrh           sqlite3_str_reset(pStr);
1074ef95d558Sdrh           sqlite3_str_appendf(pStr, "%!.20e", r1);
107572b3fbc7Sdrh         }
1076ef95d558Sdrh       }
107772b3fbc7Sdrh       break;
107872b3fbc7Sdrh     }
107972b3fbc7Sdrh     case SQLITE_INTEGER: {
1080ef95d558Sdrh       sqlite3_str_appendf(pStr, "%lld", sqlite3_value_int64(pValue));
1081f9b596ebSdrh       break;
1082f9b596ebSdrh     }
10833f41e976Sdanielk1977     case SQLITE_BLOB: {
1084ef95d558Sdrh       char const *zBlob = sqlite3_value_blob(pValue);
1085ef95d558Sdrh       int nBlob = sqlite3_value_bytes(pValue);
1086ef95d558Sdrh       assert( zBlob==sqlite3_value_blob(pValue) ); /* No encoding change */
1087ef95d558Sdrh       sqlite3StrAccumEnlarge(pStr, nBlob*2 + 4);
1088ef95d558Sdrh       if( pStr->accError==0 ){
1089ef95d558Sdrh         char *zText = pStr->zText;
10903f41e976Sdanielk1977         int i;
10913f41e976Sdanielk1977         for(i=0; i<nBlob; i++){
10923f41e976Sdanielk1977           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
10933f41e976Sdanielk1977           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
10943f41e976Sdanielk1977         }
10953f41e976Sdanielk1977         zText[(nBlob*2)+2] = '\'';
10963f41e976Sdanielk1977         zText[(nBlob*2)+3] = '\0';
10973f41e976Sdanielk1977         zText[0] = 'X';
10983f41e976Sdanielk1977         zText[1] = '\'';
1099ef95d558Sdrh         pStr->nChar = nBlob*2 + 3;
11003f41e976Sdanielk1977       }
11013f41e976Sdanielk1977       break;
11023f41e976Sdanielk1977     }
11039c054830Sdrh     case SQLITE_TEXT: {
1104ef95d558Sdrh       const unsigned char *zArg = sqlite3_value_text(pValue);
1105ef95d558Sdrh       sqlite3_str_appendf(pStr, "%Q", zArg);
1106a0df4ccfSdrh       break;
1107a0df4ccfSdrh     }
1108a0df4ccfSdrh     default: {
1109ef95d558Sdrh       assert( sqlite3_value_type(pValue)==SQLITE_NULL );
1110ef95d558Sdrh       sqlite3_str_append(pStr, "NULL", 4);
1111a0df4ccfSdrh       break;
111247394703Sdrh     }
111347394703Sdrh   }
1114f9b596ebSdrh }
111547394703Sdrh 
1116137c728fSdrh /*
1117ef95d558Sdrh ** Implementation of the QUOTE() function.
1118ef95d558Sdrh **
1119ef95d558Sdrh ** The quote(X) function returns the text of an SQL literal which is the
1120ef95d558Sdrh ** value of its argument suitable for inclusion into an SQL statement.
1121ef95d558Sdrh ** Strings are surrounded by single-quotes with escapes on interior quotes
1122ef95d558Sdrh ** as needed. BLOBs are encoded as hexadecimal literals. Strings with
1123ef95d558Sdrh ** embedded NUL characters cannot be represented as string literals in SQL
1124ef95d558Sdrh ** and hence the returned string literal is truncated prior to the first NUL.
1125ef95d558Sdrh */
quoteFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1126ef95d558Sdrh static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1127ef95d558Sdrh   sqlite3_str str;
1128ef95d558Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
1129ef95d558Sdrh   assert( argc==1 );
1130ef95d558Sdrh   UNUSED_PARAMETER(argc);
1131ef95d558Sdrh   sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
1132ef95d558Sdrh   sqlite3QuoteValue(&str,argv[0]);
1133ef95d558Sdrh   sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,
1134ef95d558Sdrh                       SQLITE_DYNAMIC);
1135af7b8dcbSdan   if( str.accError!=SQLITE_OK ){
1136af7b8dcbSdan     sqlite3_result_null(context);
1137af7b8dcbSdan     sqlite3_result_error_code(context, str.accError);
1138ef95d558Sdrh   }
1139ef95d558Sdrh }
1140ef95d558Sdrh 
1141ef95d558Sdrh /*
1142d495d8c9Sdrh ** The unicode() function.  Return the integer unicode code-point value
1143d495d8c9Sdrh ** for the first character of the input string.
1144d495d8c9Sdrh */
unicodeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1145d495d8c9Sdrh static void unicodeFunc(
1146d495d8c9Sdrh   sqlite3_context *context,
1147d495d8c9Sdrh   int argc,
1148d495d8c9Sdrh   sqlite3_value **argv
1149d495d8c9Sdrh ){
1150d495d8c9Sdrh   const unsigned char *z = sqlite3_value_text(argv[0]);
11511d59d036Sdrh   (void)argc;
1152d495d8c9Sdrh   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
1153d495d8c9Sdrh }
1154d495d8c9Sdrh 
1155d495d8c9Sdrh /*
1156d495d8c9Sdrh ** The char() function takes zero or more arguments, each of which is
1157d495d8c9Sdrh ** an integer.  It constructs a string where each character of the string
1158d495d8c9Sdrh ** is the unicode character for the corresponding integer argument.
1159d495d8c9Sdrh */
charFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1160d495d8c9Sdrh static void charFunc(
1161d495d8c9Sdrh   sqlite3_context *context,
1162d495d8c9Sdrh   int argc,
1163d495d8c9Sdrh   sqlite3_value **argv
1164d495d8c9Sdrh ){
1165d495d8c9Sdrh   unsigned char *z, *zOut;
1166d495d8c9Sdrh   int i;
1167f3cdcdccSdrh   zOut = z = sqlite3_malloc64( argc*4+1 );
1168d495d8c9Sdrh   if( z==0 ){
1169d495d8c9Sdrh     sqlite3_result_error_nomem(context);
1170d495d8c9Sdrh     return;
1171d495d8c9Sdrh   }
1172d495d8c9Sdrh   for(i=0; i<argc; i++){
1173c9545442Smistachkin     sqlite3_int64 x;
1174d495d8c9Sdrh     unsigned c;
1175d495d8c9Sdrh     x = sqlite3_value_int64(argv[i]);
1176d495d8c9Sdrh     if( x<0 || x>0x10ffff ) x = 0xfffd;
1177d495d8c9Sdrh     c = (unsigned)(x & 0x1fffff);
1178fe7a5d11Sdrh     if( c<0x00080 ){
1179fe7a5d11Sdrh       *zOut++ = (u8)(c&0xFF);
1180fe7a5d11Sdrh     }else if( c<0x00800 ){
1181fe7a5d11Sdrh       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
1182fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1183fe7a5d11Sdrh     }else if( c<0x10000 ){
1184fe7a5d11Sdrh       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
1185fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1186fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1187d495d8c9Sdrh     }else{
1188fe7a5d11Sdrh       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
1189fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
1190fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
1191fe7a5d11Sdrh       *zOut++ = 0x80 + (u8)(c & 0x3F);
1192fe7a5d11Sdrh     }                                                    \
1193d495d8c9Sdrh   }
1194bbf483f8Sdrh   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
1195d495d8c9Sdrh }
1196d495d8c9Sdrh 
1197d495d8c9Sdrh /*
1198137c728fSdrh ** The hex() function.  Interpret the argument as a blob.  Return
1199137c728fSdrh ** a hexadecimal rendering as text.
1200137c728fSdrh */
hexFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1201137c728fSdrh static void hexFunc(
1202137c728fSdrh   sqlite3_context *context,
1203137c728fSdrh   int argc,
1204137c728fSdrh   sqlite3_value **argv
1205137c728fSdrh ){
1206137c728fSdrh   int i, n;
1207137c728fSdrh   const unsigned char *pBlob;
1208137c728fSdrh   char *zHex, *z;
1209137c728fSdrh   assert( argc==1 );
1210f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
12111f0feef8Sdrh   pBlob = sqlite3_value_blob(argv[0]);
1212137c728fSdrh   n = sqlite3_value_bytes(argv[0]);
12131f0feef8Sdrh   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
1214b1a6c3c1Sdrh   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
1215a1644fd8Sdanielk1977   if( zHex ){
1216137c728fSdrh     for(i=0; i<n; i++, pBlob++){
1217137c728fSdrh       unsigned char c = *pBlob;
1218137c728fSdrh       *(z++) = hexdigits[(c>>4)&0xf];
1219137c728fSdrh       *(z++) = hexdigits[c&0xf];
1220137c728fSdrh     }
1221137c728fSdrh     *z = 0;
1222137c728fSdrh     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
1223137c728fSdrh   }
1224a1644fd8Sdanielk1977 }
1225137c728fSdrh 
122626b6d90dSdrh /*
12278cff382eSdrh ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
12288cff382eSdrh */
zeroblobFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)12298cff382eSdrh static void zeroblobFunc(
12308cff382eSdrh   sqlite3_context *context,
12318cff382eSdrh   int argc,
12328cff382eSdrh   sqlite3_value **argv
12338cff382eSdrh ){
123498640a3fSdrh   i64 n;
1235a4d5ae8fSdan   int rc;
12368cff382eSdrh   assert( argc==1 );
1237f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
123898640a3fSdrh   n = sqlite3_value_int64(argv[0]);
123953e66c3cSdrh   if( n<0 ) n = 0;
1240a4d5ae8fSdan   rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
1241a4d5ae8fSdan   if( rc ){
1242a4d5ae8fSdan     sqlite3_result_error_code(context, rc);
12438cff382eSdrh   }
124498640a3fSdrh }
12458cff382eSdrh 
12468cff382eSdrh /*
124726b6d90dSdrh ** The replace() function.  Three arguments are all strings: call
124826b6d90dSdrh ** them A, B, and C. The result is also a string which is derived
1249f7b5496eSdrh ** from A by replacing every occurrence of B with C.  The match
125026b6d90dSdrh ** must be exact.  Collating sequences are not used.
125126b6d90dSdrh */
replaceFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)125226b6d90dSdrh static void replaceFunc(
125326b6d90dSdrh   sqlite3_context *context,
125426b6d90dSdrh   int argc,
125526b6d90dSdrh   sqlite3_value **argv
125626b6d90dSdrh ){
125726b6d90dSdrh   const unsigned char *zStr;        /* The input string A */
125826b6d90dSdrh   const unsigned char *zPattern;    /* The pattern string B */
125926b6d90dSdrh   const unsigned char *zRep;        /* The replacement string C */
126026b6d90dSdrh   unsigned char *zOut;              /* The output */
126126b6d90dSdrh   int nStr;                /* Size of zStr */
126226b6d90dSdrh   int nPattern;            /* Size of zPattern */
126326b6d90dSdrh   int nRep;                /* Size of zRep */
12642e6400baSdrh   i64 nOut;                /* Maximum size of zOut */
126526b6d90dSdrh   int loopLimit;           /* Last zStr[] that might match zPattern[] */
126626b6d90dSdrh   int i, j;                /* Loop counters */
1267f3139520Sdrh   unsigned cntExpand;      /* Number zOut expansions */
1268f3139520Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
126926b6d90dSdrh 
127026b6d90dSdrh   assert( argc==3 );
1271f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
127226b6d90dSdrh   zStr = sqlite3_value_text(argv[0]);
12737a521cfbSdrh   if( zStr==0 ) return;
12741f0feef8Sdrh   nStr = sqlite3_value_bytes(argv[0]);
12751f0feef8Sdrh   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
127626b6d90dSdrh   zPattern = sqlite3_value_text(argv[1]);
1277a605fe8dSdrh   if( zPattern==0 ){
12782333606eSdrh     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
12792333606eSdrh             || sqlite3_context_db_handle(context)->mallocFailed );
1280a605fe8dSdrh     return;
1281a605fe8dSdrh   }
1282a605fe8dSdrh   if( zPattern[0]==0 ){
1283a605fe8dSdrh     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
1284a605fe8dSdrh     sqlite3_result_value(context, argv[0]);
1285a605fe8dSdrh     return;
1286a605fe8dSdrh   }
12871f0feef8Sdrh   nPattern = sqlite3_value_bytes(argv[1]);
12881f0feef8Sdrh   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
128926b6d90dSdrh   zRep = sqlite3_value_text(argv[2]);
12907a521cfbSdrh   if( zRep==0 ) return;
12911f0feef8Sdrh   nRep = sqlite3_value_bytes(argv[2]);
12921f0feef8Sdrh   assert( zRep==sqlite3_value_text(argv[2]) );
12932e6400baSdrh   nOut = nStr + 1;
12942e6400baSdrh   assert( nOut<SQLITE_MAX_LENGTH );
1295b1a6c3c1Sdrh   zOut = contextMalloc(context, (i64)nOut);
12962e6400baSdrh   if( zOut==0 ){
12972e6400baSdrh     return;
129826b6d90dSdrh   }
129926b6d90dSdrh   loopLimit = nStr - nPattern;
1300f3139520Sdrh   cntExpand = 0;
130126b6d90dSdrh   for(i=j=0; i<=loopLimit; i++){
130226b6d90dSdrh     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
130326b6d90dSdrh       zOut[j++] = zStr[i];
130426b6d90dSdrh     }else{
1305f3139520Sdrh       if( nRep>nPattern ){
13062e6400baSdrh         nOut += nRep - nPattern;
1307c86d82f2Sdrh         testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
1308c86d82f2Sdrh         testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
130927e62dbeSdrh         if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
1310a0206bc8Sdrh           sqlite3_result_error_toobig(context);
1311b975598eSdrh           sqlite3_free(zOut);
131217374e8fSdanielk1977           return;
131317374e8fSdanielk1977         }
1314f3139520Sdrh         cntExpand++;
1315f3139520Sdrh         if( (cntExpand&(cntExpand-1))==0 ){
1316f3139520Sdrh           /* Grow the size of the output buffer only on substitutions
1317f3139520Sdrh           ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
1318f3139520Sdrh           u8 *zOld;
13194a50aac5Sdrh           zOld = zOut;
1320d924e7bcSdrh           zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
13212e6400baSdrh           if( zOut==0 ){
1322a1644fd8Sdanielk1977             sqlite3_result_error_nomem(context);
1323b975598eSdrh             sqlite3_free(zOld);
13242e6400baSdrh             return;
13252e6400baSdrh           }
1326f3139520Sdrh         }
1327f3139520Sdrh       }
132826b6d90dSdrh       memcpy(&zOut[j], zRep, nRep);
132926b6d90dSdrh       j += nRep;
133026b6d90dSdrh       i += nPattern-1;
133126b6d90dSdrh     }
133226b6d90dSdrh   }
1333f3139520Sdrh   assert( j+nStr-i+1<=nOut );
133426b6d90dSdrh   memcpy(&zOut[j], &zStr[i], nStr-i);
133526b6d90dSdrh   j += nStr - i;
133626b6d90dSdrh   assert( j<=nOut );
133726b6d90dSdrh   zOut[j] = 0;
133826b6d90dSdrh   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
133926b6d90dSdrh }
134026b6d90dSdrh 
1341309b3386Sdrh /*
1342309b3386Sdrh ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
1343309b3386Sdrh ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
1344309b3386Sdrh */
trimFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1345309b3386Sdrh static void trimFunc(
1346309b3386Sdrh   sqlite3_context *context,
1347309b3386Sdrh   int argc,
1348309b3386Sdrh   sqlite3_value **argv
1349309b3386Sdrh ){
1350309b3386Sdrh   const unsigned char *zIn;         /* Input string */
1351309b3386Sdrh   const unsigned char *zCharSet;    /* Set of characters to trim */
1352972da427Sdrh   unsigned int nIn;                 /* Number of bytes in input */
13537209c697Sdrh   int flags;                        /* 1: trimleft  2: trimright  3: trim */
1354d1e3a616Sdrh   int i;                            /* Loop counter */
1355972da427Sdrh   unsigned int *aLen = 0;           /* Length of each character in zCharSet */
13561bd10f8aSdrh   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
1357d1e3a616Sdrh   int nChar;                        /* Number of characters in zCharSet */
1358d1e3a616Sdrh 
1359309b3386Sdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1360309b3386Sdrh     return;
1361309b3386Sdrh   }
1362309b3386Sdrh   zIn = sqlite3_value_text(argv[0]);
13637a521cfbSdrh   if( zIn==0 ) return;
1364972da427Sdrh   nIn = (unsigned)sqlite3_value_bytes(argv[0]);
13651f0feef8Sdrh   assert( zIn==sqlite3_value_text(argv[0]) );
1366309b3386Sdrh   if( argc==1 ){
1367972da427Sdrh     static const unsigned lenOne[] = { 1 };
1368a4de4532Sdanielk1977     static unsigned char * const azOne[] = { (u8*)" " };
1369d1e3a616Sdrh     nChar = 1;
1370972da427Sdrh     aLen = (unsigned*)lenOne;
1371bc67da48Sdanielk1977     azChar = (unsigned char **)azOne;
1372d1e3a616Sdrh     zCharSet = 0;
13737a521cfbSdrh   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
1374309b3386Sdrh     return;
1375d1e3a616Sdrh   }else{
1376d1e3a616Sdrh     const unsigned char *z;
1377d1e3a616Sdrh     for(z=zCharSet, nChar=0; *z; nChar++){
13784a919118Sdrh       SQLITE_SKIP_UTF8(z);
1379309b3386Sdrh     }
1380d1e3a616Sdrh     if( nChar>0 ){
1381972da427Sdrh       azChar = contextMalloc(context,
1382972da427Sdrh                      ((i64)nChar)*(sizeof(char*)+sizeof(unsigned)));
1383d1e3a616Sdrh       if( azChar==0 ){
1384d1e3a616Sdrh         return;
1385d1e3a616Sdrh       }
1386972da427Sdrh       aLen = (unsigned*)&azChar[nChar];
1387d1e3a616Sdrh       for(z=zCharSet, nChar=0; *z; nChar++){
1388bc67da48Sdanielk1977         azChar[nChar] = (unsigned char *)z;
13894a919118Sdrh         SQLITE_SKIP_UTF8(z);
1390972da427Sdrh         aLen[nChar] = (unsigned)(z - azChar[nChar]);
1391d1e3a616Sdrh       }
1392d1e3a616Sdrh     }
1393d1e3a616Sdrh   }
1394d1e3a616Sdrh   if( nChar>0 ){
13951fc4129dSshane     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
1396309b3386Sdrh     if( flags & 1 ){
1397d1e3a616Sdrh       while( nIn>0 ){
1398972da427Sdrh         unsigned int len = 0;
1399d1e3a616Sdrh         for(i=0; i<nChar; i++){
1400d1e3a616Sdrh           len = aLen[i];
140127e62dbeSdrh           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
1402d1e3a616Sdrh         }
1403d1e3a616Sdrh         if( i>=nChar ) break;
1404d1e3a616Sdrh         zIn += len;
1405d1e3a616Sdrh         nIn -= len;
1406309b3386Sdrh       }
1407309b3386Sdrh     }
1408309b3386Sdrh     if( flags & 2 ){
1409d1e3a616Sdrh       while( nIn>0 ){
1410972da427Sdrh         unsigned int len = 0;
1411d1e3a616Sdrh         for(i=0; i<nChar; i++){
1412d1e3a616Sdrh           len = aLen[i];
1413d1e3a616Sdrh           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
1414309b3386Sdrh         }
1415d1e3a616Sdrh         if( i>=nChar ) break;
1416d1e3a616Sdrh         nIn -= len;
1417d1e3a616Sdrh       }
1418d1e3a616Sdrh     }
1419d1e3a616Sdrh     if( zCharSet ){
1420d1e3a616Sdrh       sqlite3_free(azChar);
1421309b3386Sdrh     }
1422309b3386Sdrh   }
1423309b3386Sdrh   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
1424309b3386Sdrh }
142526b6d90dSdrh 
1426a4de4532Sdanielk1977 
1427cc15313cSdrh #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1428cc15313cSdrh /*
1429cc15313cSdrh ** The "unknown" function is automatically substituted in place of
1430cc15313cSdrh ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
1431cc15313cSdrh ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
1432cc15313cSdrh ** When the "sqlite3" command-line shell is built using this functionality,
1433cc15313cSdrh ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
1434cc15313cSdrh ** involving application-defined functions to be examined in a generic
1435cc15313cSdrh ** sqlite3 shell.
1436cc15313cSdrh */
unknownFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1437cc15313cSdrh static void unknownFunc(
1438cc15313cSdrh   sqlite3_context *context,
1439cc15313cSdrh   int argc,
1440cc15313cSdrh   sqlite3_value **argv
1441cc15313cSdrh ){
1442cc15313cSdrh   /* no-op */
1443cc15313cSdrh }
1444cc15313cSdrh #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
1445cc15313cSdrh 
1446cc15313cSdrh 
14472ba3cccfSdrh /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
14482ba3cccfSdrh ** is only available if the SQLITE_SOUNDEX compile-time option is used
14492ba3cccfSdrh ** when SQLite is built.
14502ba3cccfSdrh */
1451d24cc427Sdrh #ifdef SQLITE_SOUNDEX
1452d24cc427Sdrh /*
1453d24cc427Sdrh ** Compute the soundex encoding of a word.
14542ba3cccfSdrh **
14552ba3cccfSdrh ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
14562ba3cccfSdrh ** soundex encoding of the string X.
1457d24cc427Sdrh */
soundexFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1458137c728fSdrh static void soundexFunc(
1459137c728fSdrh   sqlite3_context *context,
1460137c728fSdrh   int argc,
1461137c728fSdrh   sqlite3_value **argv
1462137c728fSdrh ){
1463d24cc427Sdrh   char zResult[8];
14644c755c0fSdrh   const u8 *zIn;
1465d24cc427Sdrh   int i, j;
1466d24cc427Sdrh   static const unsigned char iCode[] = {
1467d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1468d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1469d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1470d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1471d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1472d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1473d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1474d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1475d24cc427Sdrh   };
1476d24cc427Sdrh   assert( argc==1 );
14774c755c0fSdrh   zIn = (u8*)sqlite3_value_text(argv[0]);
1478bdf67e0eSdrh   if( zIn==0 ) zIn = (u8*)"";
1479dc86e2b2Sdrh   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
1480d24cc427Sdrh   if( zIn[i] ){
1481bdf67e0eSdrh     u8 prevcode = iCode[zIn[i]&0x7f];
148278ca0e7eSdanielk1977     zResult[0] = sqlite3Toupper(zIn[i]);
1483d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
1484d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
1485d24cc427Sdrh       if( code>0 ){
1486bdf67e0eSdrh         if( code!=prevcode ){
1487bdf67e0eSdrh           prevcode = code;
1488d24cc427Sdrh           zResult[j++] = code + '0';
1489d24cc427Sdrh         }
1490bdf67e0eSdrh       }else{
1491bdf67e0eSdrh         prevcode = 0;
1492bdf67e0eSdrh       }
1493d24cc427Sdrh     }
1494d24cc427Sdrh     while( j<4 ){
1495d24cc427Sdrh       zResult[j++] = '0';
1496d24cc427Sdrh     }
1497d24cc427Sdrh     zResult[j] = 0;
1498d8123366Sdanielk1977     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
1499d24cc427Sdrh   }else{
15002ba3cccfSdrh     /* IMP: R-64894-50321 The string "?000" is returned if the argument
15012ba3cccfSdrh     ** is NULL or contains no ASCII alphabetic characters. */
1502d8123366Sdanielk1977     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
1503d24cc427Sdrh   }
1504d24cc427Sdrh }
15052ba3cccfSdrh #endif /* SQLITE_SOUNDEX */
1506d24cc427Sdrh 
1507fdb83b2fSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
1508fdb83b2fSdrh /*
1509fdb83b2fSdrh ** A function that loads a shared-library extension then returns NULL.
1510fdb83b2fSdrh */
loadExt(sqlite3_context * context,int argc,sqlite3_value ** argv)1511fdb83b2fSdrh static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
151265fd59f7Sdanielk1977   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
15137a521cfbSdrh   const char *zProc;
1514fa4a4b91Sdrh   sqlite3 *db = sqlite3_context_db_handle(context);
1515fdb83b2fSdrh   char *zErrMsg = 0;
1516fdb83b2fSdrh 
1517191dd061Sdrh   /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
15181a55dedfSdrh   ** flag is set.  See the sqlite3_enable_load_extension() API.
15191a55dedfSdrh   */
1520f602a161Sdrh   if( (db->flags & SQLITE_LoadExtFunc)==0 ){
1521f602a161Sdrh     sqlite3_result_error(context, "not authorized", -1);
1522f602a161Sdrh     return;
1523f602a161Sdrh   }
15241a55dedfSdrh 
1525fdb83b2fSdrh   if( argc==2 ){
152665fd59f7Sdanielk1977     zProc = (const char *)sqlite3_value_text(argv[1]);
15277a521cfbSdrh   }else{
15287a521cfbSdrh     zProc = 0;
1529fdb83b2fSdrh   }
15307a521cfbSdrh   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
1531fdb83b2fSdrh     sqlite3_result_error(context, zErrMsg, -1);
1532fdb83b2fSdrh     sqlite3_free(zErrMsg);
1533fdb83b2fSdrh   }
1534fdb83b2fSdrh }
1535fdb83b2fSdrh #endif
1536fdb83b2fSdrh 
153701427a62Sdanielk1977 
15380ac65892Sdrh /*
1539d3a149efSdrh ** An instance of the following structure holds the context of a
1540dd5baa95Sdrh ** sum() or avg() aggregate computation.
1541dd5baa95Sdrh */
1542dd5baa95Sdrh typedef struct SumCtx SumCtx;
1543dd5baa95Sdrh struct SumCtx {
15448c08e861Sdrh   double rSum;      /* Floating point sum */
15458c08e861Sdrh   i64 iSum;         /* Integer sum */
1546cf85a51cSdrh   i64 cnt;          /* Number of elements summed */
15478c08e861Sdrh   u8 overflow;      /* True if integer overflow seen */
15488c08e861Sdrh   u8 approx;        /* True if non-integer value was input to the sum */
1549dd5baa95Sdrh };
1550dd5baa95Sdrh 
1551dd5baa95Sdrh /*
1552a97fdd3bSdrh ** Routines used to compute the sum, average, and total.
1553a97fdd3bSdrh **
1554a97fdd3bSdrh ** The SUM() function follows the (broken) SQL standard which means
1555a97fdd3bSdrh ** that it returns NULL if it sums over no inputs.  TOTAL returns
1556a97fdd3bSdrh ** 0.0 in that case.  In addition, TOTAL always returns a float where
1557a97fdd3bSdrh ** SUM might return an integer if it never encounters a floating point
1558c806d857Sdrh ** value.  TOTAL never fails, but SUM might through an exception if
1559c806d857Sdrh ** it overflows an integer.
1560dd5baa95Sdrh */
sumStep(sqlite3_context * context,int argc,sqlite3_value ** argv)15610ae8b831Sdanielk1977 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1562dd5baa95Sdrh   SumCtx *p;
15633d1d95e6Sdrh   int type;
15643f219f46Sdrh   assert( argc==1 );
1565f3d3c27aSdanielk1977   UNUSED_PARAMETER(argc);
15664f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
156729d72108Sdrh   type = sqlite3_value_numeric_type(argv[0]);
15683d1d95e6Sdrh   if( p && type!=SQLITE_NULL ){
1569739105c7Sdrh     p->cnt++;
157029d72108Sdrh     if( type==SQLITE_INTEGER ){
15718c08e861Sdrh       i64 v = sqlite3_value_int64(argv[0]);
15728c08e861Sdrh       p->rSum += v;
1573158b9cb9Sdrh       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
1574a546ef21Sdrh         p->approx = p->overflow = 1;
157529d72108Sdrh       }
157629d72108Sdrh     }else{
15778c08e861Sdrh       p->rSum += sqlite3_value_double(argv[0]);
157829d72108Sdrh       p->approx = 1;
15793f219f46Sdrh     }
1580739105c7Sdrh   }
1581dd5baa95Sdrh }
158267a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
sumInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)1583c3a20c19Sdan static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
1584c3a20c19Sdan   SumCtx *p;
1585c3a20c19Sdan   int type;
1586c3a20c19Sdan   assert( argc==1 );
1587c3a20c19Sdan   UNUSED_PARAMETER(argc);
1588c3a20c19Sdan   p = sqlite3_aggregate_context(context, sizeof(*p));
1589c3a20c19Sdan   type = sqlite3_value_numeric_type(argv[0]);
1590fd4b7285Sdrh   /* p is always non-NULL because sumStep() will have been called first
1591fd4b7285Sdrh   ** to initialize it */
1592fd4b7285Sdrh   if( ALWAYS(p) && type!=SQLITE_NULL ){
1593a546ef21Sdrh     assert( p->cnt>0 );
1594c3a20c19Sdan     p->cnt--;
1595a546ef21Sdrh     assert( type==SQLITE_INTEGER || p->approx );
1596a546ef21Sdrh     if( type==SQLITE_INTEGER && p->approx==0 ){
1597c3a20c19Sdan       i64 v = sqlite3_value_int64(argv[0]);
1598c3a20c19Sdan       p->rSum -= v;
1599a546ef21Sdrh       p->iSum -= v;
1600c3a20c19Sdan     }else{
1601d736829eSdan       p->rSum -= sqlite3_value_double(argv[0]);
1602c3a20c19Sdan     }
1603c3a20c19Sdan   }
1604c3a20c19Sdan }
160567a9b8edSdan #else
160667a9b8edSdan # define sumInverse 0
160767a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
sumFinalize(sqlite3_context * context)16080ae8b831Sdanielk1977 static void sumFinalize(sqlite3_context *context){
1609dd5baa95Sdrh   SumCtx *p;
1610abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1611c2bd913aSdrh   if( p && p->cnt>0 ){
16128c08e861Sdrh     if( p->overflow ){
16138c08e861Sdrh       sqlite3_result_error(context,"integer overflow",-1);
16148c08e861Sdrh     }else if( p->approx ){
16158c08e861Sdrh       sqlite3_result_double(context, p->rSum);
1616c2bd913aSdrh     }else{
16178c08e861Sdrh       sqlite3_result_int64(context, p->iSum);
16183d1d95e6Sdrh     }
1619dd5baa95Sdrh   }
1620c2bd913aSdrh }
avgFinalize(sqlite3_context * context)16210ae8b831Sdanielk1977 static void avgFinalize(sqlite3_context *context){
1622dd5baa95Sdrh   SumCtx *p;
1623abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1624739105c7Sdrh   if( p && p->cnt>0 ){
16258c08e861Sdrh     sqlite3_result_double(context, p->rSum/(double)p->cnt);
1626dd5baa95Sdrh   }
1627dd5baa95Sdrh }
totalFinalize(sqlite3_context * context)1628a97fdd3bSdrh static void totalFinalize(sqlite3_context *context){
1629a97fdd3bSdrh   SumCtx *p;
1630a97fdd3bSdrh   p = sqlite3_aggregate_context(context, 0);
1631fbd60f82Sshane   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1632fbd60f82Sshane   sqlite3_result_double(context, p ? p->rSum : (double)0);
1633a97fdd3bSdrh }
1634dd5baa95Sdrh 
1635dd5baa95Sdrh /*
16360bce8354Sdrh ** The following structure keeps track of state information for the
16370bce8354Sdrh ** count() aggregate function.
16380bce8354Sdrh */
16390bce8354Sdrh typedef struct CountCtx CountCtx;
16400bce8354Sdrh struct CountCtx {
1641fc6ad39cSdrh   i64 n;
16427262ca94Sdan #ifdef SQLITE_DEBUG
16437262ca94Sdan   int bInverse;                   /* True if xInverse() ever called */
16447262ca94Sdan #endif
16450bce8354Sdrh };
1646dd5baa95Sdrh 
16470bce8354Sdrh /*
16480bce8354Sdrh ** Routines to implement the count() aggregate function.
16490bce8354Sdrh */
countStep(sqlite3_context * context,int argc,sqlite3_value ** argv)16500ae8b831Sdanielk1977 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
16510bce8354Sdrh   CountCtx *p;
16524f26d6c4Sdrh   p = sqlite3_aggregate_context(context, sizeof(*p));
16539c054830Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
16540bce8354Sdrh     p->n++;
16550bce8354Sdrh   }
16562e79c3d5Sdrh 
1657d3264c7cSdrh #ifndef SQLITE_OMIT_DEPRECATED
16582e79c3d5Sdrh   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
16592e79c3d5Sdrh   ** sure it still operates correctly, verify that its count agrees with our
16602e79c3d5Sdrh   ** internal count when using count(*) and when the total count can be
16612e79c3d5Sdrh   ** expressed as a 32-bit integer. */
16627262ca94Sdan   assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
16632e79c3d5Sdrh           || p->n==sqlite3_aggregate_count(context) );
1664d3264c7cSdrh #endif
16650bce8354Sdrh }
countFinalize(sqlite3_context * context)16660ae8b831Sdanielk1977 static void countFinalize(sqlite3_context *context){
16670bce8354Sdrh   CountCtx *p;
1668abfcea25Sdrh   p = sqlite3_aggregate_context(context, 0);
1669fc6ad39cSdrh   sqlite3_result_int64(context, p ? p->n : 0);
16700bce8354Sdrh }
16717262ca94Sdan #ifndef SQLITE_OMIT_WINDOWFUNC
countInverse(sqlite3_context * ctx,int argc,sqlite3_value ** argv)16727262ca94Sdan static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
16737262ca94Sdan   CountCtx *p;
16747262ca94Sdan   p = sqlite3_aggregate_context(ctx, sizeof(*p));
1675fd4b7285Sdrh   /* p is always non-NULL since countStep() will have been called first */
1676fd4b7285Sdrh   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
16777262ca94Sdan     p->n--;
16787262ca94Sdan #ifdef SQLITE_DEBUG
16797262ca94Sdan     p->bInverse = 1;
16807262ca94Sdan #endif
16817262ca94Sdan   }
16827262ca94Sdan }
16836b4b8820Sdan #else
16846b4b8820Sdan # define countInverse 0
16856b4b8820Sdan #endif /* SQLITE_OMIT_WINDOWFUNC */
16860bce8354Sdrh 
16870bce8354Sdrh /*
16880bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
16890bce8354Sdrh */
minmaxStep(sqlite3_context * context,int NotUsed,sqlite3_value ** argv)169062c14b34Sdanielk1977 static void minmaxStep(
169162c14b34Sdanielk1977   sqlite3_context *context,
169262c14b34Sdanielk1977   int NotUsed,
169362c14b34Sdanielk1977   sqlite3_value **argv
169462c14b34Sdanielk1977 ){
169588208050Sdanielk1977   Mem *pArg  = (Mem *)argv[0];
16969eb516c0Sdrh   Mem *pBest;
169762c14b34Sdanielk1977   UNUSED_PARAMETER(NotUsed);
16989eb516c0Sdrh 
16999eb516c0Sdrh   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
17003aeab9e4Sdanielk1977   if( !pBest ) return;
1701268380caSdrh 
17026fb2b54cSdan   if( sqlite3_value_type(pArg)==SQLITE_NULL ){
170394a6d998Sdrh     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
170494a6d998Sdrh   }else if( pBest->flags ){
17059eb516c0Sdrh     int max;
17069eb516c0Sdrh     int cmp;
1707dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
17087e18c259Sdanielk1977     /* This step function is used for both the min() and max() aggregates,
17097e18c259Sdanielk1977     ** the only difference between the two being that the sense of the
17107e18c259Sdanielk1977     ** comparison is inverted. For the max() aggregate, the
17117e18c259Sdanielk1977     ** sqlite3_user_data() function returns (void *)-1. For min() it
17127e18c259Sdanielk1977     ** returns (void *)db, where db is the sqlite3* database pointer.
17137e18c259Sdanielk1977     ** Therefore the next statement sets variable 'max' to 1 for the max()
17147e18c259Sdanielk1977     ** aggregate, or 0 for min().
17157e18c259Sdanielk1977     */
1716309b3386Sdrh     max = sqlite3_user_data(context)!=0;
1717dc1bdc4fSdanielk1977     cmp = sqlite3MemCompare(pBest, pArg, pColl);
171888208050Sdanielk1977     if( (max && cmp<0) || (!max && cmp>0) ){
1719b21c8cd4Sdrh       sqlite3VdbeMemCopy(pBest, pArg);
17207a95789cSdrh     }else{
17217a95789cSdrh       sqlite3SkipAccumulatorLoad(context);
172288208050Sdanielk1977     }
17230bce8354Sdrh   }else{
1724035e563bSdrh     pBest->db = sqlite3_context_db_handle(context);
1725b21c8cd4Sdrh     sqlite3VdbeMemCopy(pBest, pArg);
17260bce8354Sdrh   }
17270bce8354Sdrh }
minMaxValueFinalize(sqlite3_context * context,int bValue)17286fb2b54cSdan static void minMaxValueFinalize(sqlite3_context *context, int bValue){
172988208050Sdanielk1977   sqlite3_value *pRes;
1730abfcea25Sdrh   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
1731abfcea25Sdrh   if( pRes ){
173294a6d998Sdrh     if( pRes->flags ){
1733f4479501Sdrh       sqlite3_result_value(context, pRes);
17340bce8354Sdrh     }
17356fb2b54cSdan     if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
17360bce8354Sdrh   }
1737abfcea25Sdrh }
173867a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
minMaxValue(sqlite3_context * context)17396fb2b54cSdan static void minMaxValue(sqlite3_context *context){
1740c7bf5716Sdrh   minMaxValueFinalize(context, 1);
17416fb2b54cSdan }
174267a9b8edSdan #else
174367a9b8edSdan # define minMaxValue 0
174467a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
minMaxFinalize(sqlite3_context * context)17456fb2b54cSdan static void minMaxFinalize(sqlite3_context *context){
1746c7bf5716Sdrh   minMaxValueFinalize(context, 0);
17476fb2b54cSdan }
1748dd5baa95Sdrh 
1749b0689696Sdrh /*
1750b0689696Sdrh ** group_concat(EXPR, ?SEPARATOR?)
1751f06db3e8Sdrh **
1752f06db3e8Sdrh ** The SEPARATOR goes before the EXPR string.  This is tragic.  The
1753f06db3e8Sdrh ** groupConcatInverse() implementation would have been easier if the
1754f06db3e8Sdrh ** SEPARATOR were appended after EXPR.  And the order is undocumented,
1755f06db3e8Sdrh ** so we could change it, in theory.  But the old behavior has been
1756f06db3e8Sdrh ** around for so long that we dare not, for fear of breaking something.
1757b0689696Sdrh */
1758dde13e6fSlarrybr typedef struct {
1759dde13e6fSlarrybr   StrAccum str;          /* The accumulated concatenation */
1760dde13e6fSlarrybr #ifndef SQLITE_OMIT_WINDOWFUNC
1761dde13e6fSlarrybr   int nAccum;            /* Number of strings presently concatenated */
1762dde13e6fSlarrybr   int nFirstSepLength;   /* Used to detect separator length change */
1763dde13e6fSlarrybr   /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
1764f06db3e8Sdrh   ** stored as actually incorporated into presently accumulated result.
1765f06db3e8Sdrh   ** (Hence, its slots in use number nAccum-1 between method calls.)
1766f06db3e8Sdrh   ** If pnSepLengths==0, nFirstSepLength is the length used throughout.
1767dde13e6fSlarrybr   */
1768dde13e6fSlarrybr   int *pnSepLengths;
1769dde13e6fSlarrybr #endif
1770dde13e6fSlarrybr } GroupConcatCtx;
1771dde13e6fSlarrybr 
groupConcatStep(sqlite3_context * context,int argc,sqlite3_value ** argv)1772b0689696Sdrh static void groupConcatStep(
1773b0689696Sdrh   sqlite3_context *context,
1774b0689696Sdrh   int argc,
1775b0689696Sdrh   sqlite3_value **argv
1776b0689696Sdrh ){
1777b0689696Sdrh   const char *zVal;
1778dde13e6fSlarrybr   GroupConcatCtx *pGCC;
1779b0689696Sdrh   const char *zSep;
178007d3117aSdrh   int nVal, nSep;
178107d3117aSdrh   assert( argc==1 || argc==2 );
178207d3117aSdrh   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
1783dde13e6fSlarrybr   pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
1784dde13e6fSlarrybr   if( pGCC ){
1785bb4957f8Sdrh     sqlite3 *db = sqlite3_context_db_handle(context);
1786dde13e6fSlarrybr     int firstTerm = pGCC->str.mxAlloc==0;
1787dde13e6fSlarrybr     pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
1788f06db3e8Sdrh     if( argc==1 ){
17898bfd7190Sdrh       if( !firstTerm ){
1790f06db3e8Sdrh         sqlite3_str_appendchar(&pGCC->str, 1, ',');
1791f06db3e8Sdrh       }
1792f06db3e8Sdrh #ifndef SQLITE_OMIT_WINDOWFUNC
1793f06db3e8Sdrh       else{
1794f06db3e8Sdrh         pGCC->nFirstSepLength = 1;
1795f06db3e8Sdrh       }
1796f06db3e8Sdrh #endif
1797f06db3e8Sdrh     }else if( !firstTerm ){
179807d3117aSdrh       zSep = (char*)sqlite3_value_text(argv[1]);
179907d3117aSdrh       nSep = sqlite3_value_bytes(argv[1]);
1800f06db3e8Sdrh       if( zSep ){
1801dde13e6fSlarrybr         sqlite3_str_append(&pGCC->str, zSep, nSep);
1802f06db3e8Sdrh       }
1803dde13e6fSlarrybr #ifndef SQLITE_OMIT_WINDOWFUNC
1804f06db3e8Sdrh       else{
1805dde13e6fSlarrybr         nSep = 0;
1806f06db3e8Sdrh       }
1807dde13e6fSlarrybr       if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){
1808dde13e6fSlarrybr         int *pnsl = pGCC->pnSepLengths;
1809dde13e6fSlarrybr         if( pnsl == 0 ){
1810dde13e6fSlarrybr           /* First separator length variation seen, start tracking them. */
1811dde13e6fSlarrybr           pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int));
1812dde13e6fSlarrybr           if( pnsl!=0 ){
1813dde13e6fSlarrybr             int i = 0, nA = pGCC->nAccum-1;
1814dde13e6fSlarrybr             while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength;
1815b0689696Sdrh           }
1816b0689696Sdrh         }else{
1817dde13e6fSlarrybr           pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int));
181807d3117aSdrh         }
1819dde13e6fSlarrybr         if( pnsl!=0 ){
18203dd01111Sdrh           if( ALWAYS(pGCC->nAccum>0) ){
1821dde13e6fSlarrybr             pnsl[pGCC->nAccum-1] = nSep;
1822b0689696Sdrh           }
1823dde13e6fSlarrybr           pGCC->pnSepLengths = pnsl;
1824dde13e6fSlarrybr         }else{
1825f06db3e8Sdrh           sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM);
1826dde13e6fSlarrybr         }
1827dde13e6fSlarrybr       }
1828dde13e6fSlarrybr #endif
1829dde13e6fSlarrybr     }
1830dde13e6fSlarrybr #ifndef SQLITE_OMIT_WINDOWFUNC
1831dde13e6fSlarrybr     else{
18323dd01111Sdrh       pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]);
1833dde13e6fSlarrybr     }
1834dde13e6fSlarrybr     pGCC->nAccum += 1;
1835dde13e6fSlarrybr #endif
183607d3117aSdrh     zVal = (char*)sqlite3_value_text(argv[0]);
183707d3117aSdrh     nVal = sqlite3_value_bytes(argv[0]);
1838dde13e6fSlarrybr     if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal);
1839b0689696Sdrh   }
1840b0689696Sdrh }
1841dde13e6fSlarrybr 
184267a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
groupConcatInverse(sqlite3_context * context,int argc,sqlite3_value ** argv)184303854d2eSdan static void groupConcatInverse(
184403854d2eSdan   sqlite3_context *context,
184503854d2eSdan   int argc,
184603854d2eSdan   sqlite3_value **argv
184703854d2eSdan ){
1848dde13e6fSlarrybr   GroupConcatCtx *pGCC;
1849c7bf5716Sdrh   assert( argc==1 || argc==2 );
1850260ff081Sdrh   (void)argc;  /* Suppress unused parameter warning */
185103854d2eSdan   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
1852dde13e6fSlarrybr   pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, sizeof(*pGCC));
1853dde13e6fSlarrybr   /* pGCC is always non-NULL since groupConcatStep() will have always
1854fd4b7285Sdrh   ** run frist to initialize it */
1855dde13e6fSlarrybr   if( ALWAYS(pGCC) ){
18564fc80671Sdrh     int nVS;
18574fc80671Sdrh     /* Must call sqlite3_value_text() to convert the argument into text prior
18584fc80671Sdrh     ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */
18594fc80671Sdrh     (void)sqlite3_value_text(argv[0]);
18604fc80671Sdrh     nVS = sqlite3_value_bytes(argv[0]);
1861dde13e6fSlarrybr     pGCC->nAccum -= 1;
1862dde13e6fSlarrybr     if( pGCC->pnSepLengths!=0 ){
1863dde13e6fSlarrybr       assert(pGCC->nAccum >= 0);
1864dde13e6fSlarrybr       if( pGCC->nAccum>0 ){
1865dde13e6fSlarrybr         nVS += *pGCC->pnSepLengths;
1866dde13e6fSlarrybr         memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1,
1867dde13e6fSlarrybr                (pGCC->nAccum-1)*sizeof(int));
186803854d2eSdan       }
186903854d2eSdan     }else{
1870dde13e6fSlarrybr       /* If removing single accumulated string, harmlessly over-do. */
1871dde13e6fSlarrybr       nVS += pGCC->nFirstSepLength;
187203854d2eSdan     }
1873dde13e6fSlarrybr     if( nVS>=(int)pGCC->str.nChar ){
1874dde13e6fSlarrybr       pGCC->str.nChar = 0;
1875dde13e6fSlarrybr     }else{
1876dde13e6fSlarrybr       pGCC->str.nChar -= nVS;
1877dde13e6fSlarrybr       memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar);
1878dde13e6fSlarrybr     }
1879dde13e6fSlarrybr     if( pGCC->str.nChar==0 ){
1880dde13e6fSlarrybr       pGCC->str.mxAlloc = 0;
1881dde13e6fSlarrybr       sqlite3_free(pGCC->pnSepLengths);
1882dde13e6fSlarrybr       pGCC->pnSepLengths = 0;
1883dde13e6fSlarrybr     }
188403854d2eSdan   }
188503854d2eSdan }
188667a9b8edSdan #else
188767a9b8edSdan # define groupConcatInverse 0
188867a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
groupConcatFinalize(sqlite3_context * context)1889b0689696Sdrh static void groupConcatFinalize(sqlite3_context *context){
1890dde13e6fSlarrybr   GroupConcatCtx *pGCC
1891dde13e6fSlarrybr     = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
1892dde13e6fSlarrybr   if( pGCC ){
18935bf4715eSdrh     sqlite3ResultStrAccum(context, &pGCC->str);
1894dde13e6fSlarrybr #ifndef SQLITE_OMIT_WINDOWFUNC
1895dde13e6fSlarrybr     sqlite3_free(pGCC->pnSepLengths);
1896dde13e6fSlarrybr #endif
1897b0689696Sdrh   }
1898ade86483Sdrh }
189967a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC
groupConcatValue(sqlite3_context * context)1900e2f781b9Sdan static void groupConcatValue(sqlite3_context *context){
1901dde13e6fSlarrybr   GroupConcatCtx *pGCC
1902dde13e6fSlarrybr     = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0);
1903dde13e6fSlarrybr   if( pGCC ){
1904dde13e6fSlarrybr     StrAccum *pAccum = &pGCC->str;
1905e2f781b9Sdan     if( pAccum->accError==SQLITE_TOOBIG ){
1906e2f781b9Sdan       sqlite3_result_error_toobig(context);
1907e2f781b9Sdan     }else if( pAccum->accError==SQLITE_NOMEM ){
1908e2f781b9Sdan       sqlite3_result_error_nomem(context);
1909e2f781b9Sdan     }else{
1910e2f781b9Sdan       const char *zText = sqlite3_str_value(pAccum);
1911f06db3e8Sdrh       sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
1912e2f781b9Sdan     }
1913e2f781b9Sdan   }
1914e2f781b9Sdan }
191567a9b8edSdan #else
191667a9b8edSdan # define groupConcatValue 0
191767a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */
19184e5ffc5fSdrh 
1919d3a149efSdrh /*
1920a4741840Sdrh ** This routine does per-connection function registration.  Most
1921a4741840Sdrh ** of the built-in functions above are part of the global function set.
1922a4741840Sdrh ** This routine only deals with those that are not global.
1923dc04c583Sdrh */
sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 * db)192480738d9cSdrh void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
1925832a58a6Sdanielk1977   int rc = sqlite3_overload_function(db, "MATCH", 2);
1926832a58a6Sdanielk1977   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
1927832a58a6Sdanielk1977   if( rc==SQLITE_NOMEM ){
19284a642b60Sdrh     sqlite3OomFault(db);
1929832a58a6Sdanielk1977   }
1930832a58a6Sdanielk1977 }
193155ef4d97Sdrh 
193255ef4d97Sdrh /*
193308652b5eSdrh ** Re-register the built-in LIKE functions.  The caseSensitive
193455ef4d97Sdrh ** parameter determines whether or not the LIKE operator is case
193508652b5eSdrh ** sensitive.
193655ef4d97Sdrh */
sqlite3RegisterLikeFunctions(sqlite3 * db,int caseSensitive)193755ef4d97Sdrh void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
193855ef4d97Sdrh   struct compareInfo *pInfo;
1939ea5c040fSdrh   int flags;
194055ef4d97Sdrh   if( caseSensitive ){
194155ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoAlt;
1942ea5c040fSdrh     flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;
194355ef4d97Sdrh   }else{
194455ef4d97Sdrh     pInfo = (struct compareInfo*)&likeInfoNorm;
1945ea5c040fSdrh     flags = SQLITE_FUNC_LIKE;
194655ef4d97Sdrh   }
1947660af939Sdan   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
1948660af939Sdan   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
1949ea5c040fSdrh   sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags;
1950ea5c040fSdrh   sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags;
195155ef4d97Sdrh }
195255ef4d97Sdrh 
195355ef4d97Sdrh /*
195455ef4d97Sdrh ** pExpr points to an expression which implements a function.  If
195555ef4d97Sdrh ** it is appropriate to apply the LIKE optimization to that function
19561d42ea71Sdrh ** then set aWc[0] through aWc[2] to the wildcard characters and the
19571d42ea71Sdrh ** escape character and then return TRUE.  If the function is not a
19581d42ea71Sdrh ** LIKE-style function then return FALSE.
19591d42ea71Sdrh **
19601d42ea71Sdrh ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
19611d42ea71Sdrh ** operator if c is a string literal that is exactly one byte in length.
19621d42ea71Sdrh ** That one byte is stored in aWc[3].  aWc[3] is set to zero if there is
19631d42ea71Sdrh ** no ESCAPE clause.
196416897072Sdrh **
196516897072Sdrh ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
196616897072Sdrh ** the function (default for LIKE).  If the function makes the distinction
196716897072Sdrh ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
196816897072Sdrh ** false.
196955ef4d97Sdrh */
sqlite3IsLikeFunction(sqlite3 * db,Expr * pExpr,int * pIsNocase,char * aWc)1970d64fe2f3Sdrh int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
197155ef4d97Sdrh   FuncDef *pDef;
19721d42ea71Sdrh   int nExpr;
197317988aaeSdrh   assert( pExpr!=0 );
197417988aaeSdrh   assert( pExpr->op==TK_FUNCTION );
1975a4eeccdfSdrh   assert( ExprUseXList(pExpr) );
197617988aaeSdrh   if( !pExpr->x.pList ){
197755ef4d97Sdrh     return 0;
197855ef4d97Sdrh   }
19791d42ea71Sdrh   nExpr = pExpr->x.pList->nExpr;
1980f9751074Sdrh   assert( !ExprHasProperty(pExpr, EP_IntValue) );
19811d42ea71Sdrh   pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
198278b52203Sdrh #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
198378b52203Sdrh   if( pDef==0 ) return 0;
198478b52203Sdrh #endif
1985d36e1041Sdrh   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
198655ef4d97Sdrh     return 0;
198755ef4d97Sdrh   }
198855ef4d97Sdrh 
198955ef4d97Sdrh   /* The memcpy() statement assumes that the wildcard characters are
199055ef4d97Sdrh   ** the first three statements in the compareInfo structure.  The
199155ef4d97Sdrh   ** asserts() that follow verify that assumption
199255ef4d97Sdrh   */
199355ef4d97Sdrh   memcpy(aWc, pDef->pUserData, 3);
199455ef4d97Sdrh   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
199555ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
199655ef4d97Sdrh   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1997589c7876Sdrh 
1998589c7876Sdrh   if( nExpr<3 ){
1999589c7876Sdrh     aWc[3] = 0;
2000589c7876Sdrh   }else{
2001589c7876Sdrh     Expr *pEscape = pExpr->x.pList->a[2].pExpr;
2002589c7876Sdrh     char *zEscape;
2003589c7876Sdrh     if( pEscape->op!=TK_STRING ) return 0;
2004f9751074Sdrh     assert( !ExprHasProperty(pEscape, EP_IntValue) );
2005589c7876Sdrh     zEscape = pEscape->u.zToken;
2006589c7876Sdrh     if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
2007589c7876Sdrh     if( zEscape[0]==aWc[0] ) return 0;
2008589c7876Sdrh     if( zEscape[0]==aWc[1] ) return 0;
2009589c7876Sdrh     aWc[3] = zEscape[0];
2010589c7876Sdrh   }
2011589c7876Sdrh 
2012d36e1041Sdrh   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
201355ef4d97Sdrh   return 1;
2014dc04c583Sdrh }
20158c0a791aSdanielk1977 
201663f8f98aSdrh /* Mathematical Constants */
201763f8f98aSdrh #ifndef M_PI
201863f8f98aSdrh # define M_PI   3.141592653589793238462643383279502884
201963f8f98aSdrh #endif
202063f8f98aSdrh #ifndef M_LN10
202163f8f98aSdrh # define M_LN10 2.302585092994045684017991454684364208
202263f8f98aSdrh #endif
202363f8f98aSdrh #ifndef M_LN2
202463f8f98aSdrh # define M_LN2  0.693147180559945309417232121458176568
202563f8f98aSdrh #endif
202663f8f98aSdrh 
202763f8f98aSdrh 
2028f6e904bdSdrh /* Extra math functions that require linking with -lm
2029f6e904bdSdrh */
2030f6e904bdSdrh #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2031f6e904bdSdrh /*
2032f6e904bdSdrh ** Implementation SQL functions:
2033f6e904bdSdrh **
2034f6e904bdSdrh **   ceil(X)
2035f6e904bdSdrh **   ceiling(X)
2036f6e904bdSdrh **   floor(X)
2037f6e904bdSdrh **
2038f6e904bdSdrh ** The sqlite3_user_data() pointer is a pointer to the libm implementation
2039f6e904bdSdrh ** of the underlying C function.
2040f6e904bdSdrh */
ceilingFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)2041f6e904bdSdrh static void ceilingFunc(
2042f6e904bdSdrh   sqlite3_context *context,
2043f6e904bdSdrh   int argc,
2044f6e904bdSdrh   sqlite3_value **argv
2045f6e904bdSdrh ){
2046f6e904bdSdrh   assert( argc==1 );
204763f8f98aSdrh   switch( sqlite3_value_numeric_type(argv[0]) ){
204863f8f98aSdrh     case SQLITE_INTEGER: {
2049f6e904bdSdrh        sqlite3_result_int64(context, sqlite3_value_int64(argv[0]));
2050f6e904bdSdrh        break;
205163f8f98aSdrh     }
205263f8f98aSdrh     case SQLITE_FLOAT: {
2053f6e904bdSdrh        double (*x)(double) = (double(*)(double))sqlite3_user_data(context);
2054f6e904bdSdrh        sqlite3_result_double(context, x(sqlite3_value_double(argv[0])));
2055f6e904bdSdrh        break;
2056f6e904bdSdrh     }
205763f8f98aSdrh     default: {
205863f8f98aSdrh        break;
205963f8f98aSdrh     }
2060f6e904bdSdrh   }
2061f6e904bdSdrh }
2062f6e904bdSdrh 
2063f6e904bdSdrh /*
20644fd4a7a1Sdrh ** On some systems, ceil() and floor() are intrinsic function.  You are
2065c2dbf35fSdrh ** unable to take a pointer to these functions.  Hence, we here wrap them
20664fd4a7a1Sdrh ** in our own actual functions.
20674fd4a7a1Sdrh */
xCeil(double x)20684fd4a7a1Sdrh static double xCeil(double x){ return ceil(x); }
xFloor(double x)20694fd4a7a1Sdrh static double xFloor(double x){ return floor(x); }
20704fd4a7a1Sdrh 
20714fd4a7a1Sdrh /*
2072f6e904bdSdrh ** Implementation of SQL functions:
2073f6e904bdSdrh **
2074f6e904bdSdrh **   ln(X)       - natural logarithm
207563f8f98aSdrh **   log(X)      - log X base 10
207663f8f98aSdrh **   log10(X)    - log X base 10
207763f8f98aSdrh **   log(B,X)    - log X base B
2078f6e904bdSdrh */
logFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)2079f6e904bdSdrh static void logFunc(
2080f6e904bdSdrh   sqlite3_context *context,
2081f6e904bdSdrh   int argc,
2082f6e904bdSdrh   sqlite3_value **argv
2083f6e904bdSdrh ){
208463f8f98aSdrh   double x, b, ans;
2085f6e904bdSdrh   assert( argc==1 || argc==2 );
208663f8f98aSdrh   switch( sqlite3_value_numeric_type(argv[0]) ){
208763f8f98aSdrh     case SQLITE_INTEGER:
208863f8f98aSdrh     case SQLITE_FLOAT:
208963f8f98aSdrh       x = sqlite3_value_double(argv[0]);
209002d6f9b2Sdrh       if( x<=0.0 ) return;
209163f8f98aSdrh       break;
209263f8f98aSdrh     default:
209363f8f98aSdrh       return;
2094f6e904bdSdrh   }
2095f6e904bdSdrh   if( argc==2 ){
209663f8f98aSdrh     switch( sqlite3_value_numeric_type(argv[0]) ){
209763f8f98aSdrh       case SQLITE_INTEGER:
209863f8f98aSdrh       case SQLITE_FLOAT:
209902d6f9b2Sdrh         b = log(x);
210002d6f9b2Sdrh         if( b<=0.0 ) return;
210163f8f98aSdrh         x = sqlite3_value_double(argv[1]);
210202d6f9b2Sdrh         if( x<=0.0 ) return;
210363f8f98aSdrh         break;
210463f8f98aSdrh      default:
210563f8f98aSdrh         return;
2106f6e904bdSdrh     }
210702d6f9b2Sdrh     ans = log(x)/b;
210863f8f98aSdrh   }else{
210963f8f98aSdrh     ans = log(x);
211063f8f98aSdrh     switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context)) ){
211163f8f98aSdrh       case 1:
2112f6e904bdSdrh         /* Convert from natural logarithm to log base 10 */
2113724e298eSdrh         ans /= M_LN10;
211463f8f98aSdrh         break;
211563f8f98aSdrh       case 2:
211663f8f98aSdrh         /* Convert from natural logarithm to log base 2 */
2117724e298eSdrh         ans /= M_LN2;
211863f8f98aSdrh         break;
211963f8f98aSdrh       default:
212063f8f98aSdrh         break;
212163f8f98aSdrh     }
2122f6e904bdSdrh   }
2123f6e904bdSdrh   sqlite3_result_double(context, ans);
2124f6e904bdSdrh }
212563f8f98aSdrh 
212663f8f98aSdrh /*
212763f8f98aSdrh ** Functions to converts degrees to radians and radians to degrees.
212863f8f98aSdrh */
degToRad(double x)212963f8f98aSdrh static double degToRad(double x){ return x*(M_PI/180.0); }
radToDeg(double x)213063f8f98aSdrh static double radToDeg(double x){ return x*(180.0/M_PI); }
213163f8f98aSdrh 
213263f8f98aSdrh /*
213363f8f98aSdrh ** Implementation of 1-argument SQL math functions:
213463f8f98aSdrh **
213563f8f98aSdrh **   exp(X)  - Compute e to the X-th power
213663f8f98aSdrh */
math1Func(sqlite3_context * context,int argc,sqlite3_value ** argv)213763f8f98aSdrh static void math1Func(
213863f8f98aSdrh   sqlite3_context *context,
213963f8f98aSdrh   int argc,
214063f8f98aSdrh   sqlite3_value **argv
214163f8f98aSdrh ){
214263f8f98aSdrh   int type0;
214363f8f98aSdrh   double v0, ans;
214463f8f98aSdrh   double (*x)(double);
2145d97a4c00Smistachkin   assert( argc==1 );
214663f8f98aSdrh   type0 = sqlite3_value_numeric_type(argv[0]);
214763f8f98aSdrh   if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
214863f8f98aSdrh   v0 = sqlite3_value_double(argv[0]);
214963f8f98aSdrh   x = (double(*)(double))sqlite3_user_data(context);
215063f8f98aSdrh   ans = x(v0);
215163f8f98aSdrh   sqlite3_result_double(context, ans);
215263f8f98aSdrh }
215363f8f98aSdrh 
215463f8f98aSdrh /*
215563f8f98aSdrh ** Implementation of 2-argument SQL math functions:
215663f8f98aSdrh **
215763f8f98aSdrh **   power(X,Y)  - Compute X to the Y-th power
215863f8f98aSdrh */
math2Func(sqlite3_context * context,int argc,sqlite3_value ** argv)215963f8f98aSdrh static void math2Func(
216063f8f98aSdrh   sqlite3_context *context,
216163f8f98aSdrh   int argc,
216263f8f98aSdrh   sqlite3_value **argv
216363f8f98aSdrh ){
216463f8f98aSdrh   int type0, type1;
216563f8f98aSdrh   double v0, v1, ans;
216663f8f98aSdrh   double (*x)(double,double);
2167d97a4c00Smistachkin   assert( argc==2 );
216863f8f98aSdrh   type0 = sqlite3_value_numeric_type(argv[0]);
216963f8f98aSdrh   if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
217063f8f98aSdrh   type1 = sqlite3_value_numeric_type(argv[1]);
217163f8f98aSdrh   if( type1!=SQLITE_INTEGER && type1!=SQLITE_FLOAT ) return;
217263f8f98aSdrh   v0 = sqlite3_value_double(argv[0]);
217363f8f98aSdrh   v1 = sqlite3_value_double(argv[1]);
217463f8f98aSdrh   x = (double(*)(double,double))sqlite3_user_data(context);
217563f8f98aSdrh   ans = x(v0, v1);
217663f8f98aSdrh   sqlite3_result_double(context, ans);
217763f8f98aSdrh }
217863f8f98aSdrh 
217963f8f98aSdrh /*
218081e5a9a6Sdrh ** Implementation of 0-argument pi() function.
218163f8f98aSdrh */
piFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)218263f8f98aSdrh static void piFunc(
218363f8f98aSdrh   sqlite3_context *context,
218463f8f98aSdrh   int argc,
218563f8f98aSdrh   sqlite3_value **argv
218663f8f98aSdrh ){
218763f8f98aSdrh   assert( argc==0 );
218863f8f98aSdrh   sqlite3_result_double(context, M_PI);
218963f8f98aSdrh }
219063f8f98aSdrh 
2191f6e904bdSdrh #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2192f6e904bdSdrh 
219393ce741bSdanielk1977 /*
219463f8f98aSdrh ** Implementation of sign(X) function.
219563f8f98aSdrh */
signFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)219663f8f98aSdrh static void signFunc(
219763f8f98aSdrh   sqlite3_context *context,
219863f8f98aSdrh   int argc,
219963f8f98aSdrh   sqlite3_value **argv
220063f8f98aSdrh ){
220163f8f98aSdrh   int type0;
220263f8f98aSdrh   double x;
2203e5baf5c2Sdrh   UNUSED_PARAMETER(argc);
2204d97a4c00Smistachkin   assert( argc==1 );
220563f8f98aSdrh   type0 = sqlite3_value_numeric_type(argv[0]);
220663f8f98aSdrh   if( type0!=SQLITE_INTEGER && type0!=SQLITE_FLOAT ) return;
220763f8f98aSdrh   x = sqlite3_value_double(argv[0]);
220863f8f98aSdrh   sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);
220963f8f98aSdrh }
221063f8f98aSdrh 
221163f8f98aSdrh /*
221260ec914cSpeter.d.reid ** All of the FuncDef structures in the aBuiltinFunc[] array above
221393ce741bSdanielk1977 ** to the global function hash table.  This occurs at start-time (as
221493ce741bSdanielk1977 ** a consequence of calling sqlite3_initialize()).
221593ce741bSdanielk1977 **
221693ce741bSdanielk1977 ** After this routine runs
221793ce741bSdanielk1977 */
sqlite3RegisterBuiltinFunctions(void)221880738d9cSdrh void sqlite3RegisterBuiltinFunctions(void){
22198c0a791aSdanielk1977   /*
2220777c5386Sdrh   ** The following array holds FuncDef structures for all of the functions
2221777c5386Sdrh   ** defined in this file.
22228c0a791aSdanielk1977   **
2223777c5386Sdrh   ** The array cannot be constant since changes are made to the
2224777c5386Sdrh   ** FuncDef.pHash elements at start-time.  The elements of this array
2225777c5386Sdrh   ** are read-only after initialization is complete.
222680738d9cSdrh   **
222780738d9cSdrh   ** For peak efficiency, put the most frequently used function last.
22288c0a791aSdanielk1977   */
222980738d9cSdrh   static FuncDef aBuiltinFunc[] = {
2230171c50ecSdrh /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
22313780f9a4Sdrh #if !defined(SQLITE_UNTESTABLE)
2232171c50ecSdrh     TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
2233171c50ecSdrh     TEST_FUNC(expr_compare,        2, INLINEFUNC_expr_compare,        0),
2234171c50ecSdrh     TEST_FUNC(expr_implies_expr,   2, INLINEFUNC_expr_implies_expr,   0),
2235171c50ecSdrh     TEST_FUNC(affinity,            1, INLINEFUNC_affinity,            0),
22363780f9a4Sdrh #endif /* !defined(SQLITE_UNTESTABLE) */
2237171c50ecSdrh /***** Regular functions *****/
223880738d9cSdrh #ifdef SQLITE_SOUNDEX
223980738d9cSdrh     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
224080738d9cSdrh #endif
224180738d9cSdrh #ifndef SQLITE_OMIT_LOAD_EXTENSION
224264de2a5fSdrh     SFUNCTION(load_extension,    1, 0, 0, loadExt          ),
224364de2a5fSdrh     SFUNCTION(load_extension,    2, 0, 0, loadExt          ),
224480738d9cSdrh #endif
224580738d9cSdrh #if SQLITE_USER_AUTHENTICATION
224680738d9cSdrh     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
224780738d9cSdrh #endif
224880738d9cSdrh #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
224980738d9cSdrh     DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
225080738d9cSdrh     DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
225180738d9cSdrh #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
225225c4296bSdrh     INLINE_FUNC(unlikely,        1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
225325c4296bSdrh     INLINE_FUNC(likelihood,      2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
225425c4296bSdrh     INLINE_FUNC(likely,          1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
2255092457b1Sdrh #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2256645682a7Sdrh     INLINE_FUNC(sqlite_offset,   1, INLINEFUNC_sqlite_offset, 0 ),
2257092457b1Sdrh #endif
22588c0a791aSdanielk1977     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
22598c0a791aSdanielk1977     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
22608c0a791aSdanielk1977     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
22618c0a791aSdanielk1977     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
22628c0a791aSdanielk1977     FUNCTION(trim,               1, 3, 0, trimFunc         ),
22638c0a791aSdanielk1977     FUNCTION(trim,               2, 3, 0, trimFunc         ),
22648c0a791aSdanielk1977     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
22658c0a791aSdanielk1977     FUNCTION(min,                0, 0, 1, 0                ),
22666fb2b54cSdan     WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
2267bb301231Sdrh                                  SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
22688c0a791aSdanielk1977     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
22698c0a791aSdanielk1977     FUNCTION(max,                0, 1, 1, 0                ),
22706fb2b54cSdan     WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
2271bb301231Sdrh                                  SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ),
2272a748fdccSdrh     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
22739d44f18bSdrh     FUNCTION2(subtype,           1, 0, 0, subtypeFunc, SQLITE_FUNC_TYPEOF),
2274a748fdccSdrh     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
2275d55e0729Sdrh     FUNCTION(instr,              2, 0, 0, instrFunc        ),
2276a5c1416dSdrh     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
22776bcd5857Sdrh     FUNCTION(format,            -1, 0, 0, printfFunc       ),
2278d495d8c9Sdrh     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
2279d495d8c9Sdrh     FUNCTION(char,              -1, 0, 0, charFunc         ),
22808c0a791aSdanielk1977     FUNCTION(abs,                1, 0, 0, absFunc          ),
2281fbd60f82Sshane #ifndef SQLITE_OMIT_FLOATING_POINT
22828c0a791aSdanielk1977     FUNCTION(round,              1, 0, 0, roundFunc        ),
22838c0a791aSdanielk1977     FUNCTION(round,              2, 0, 0, roundFunc        ),
2284fbd60f82Sshane #endif
22858c0a791aSdanielk1977     FUNCTION(upper,              1, 0, 0, upperFunc        ),
22868c0a791aSdanielk1977     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
22878c0a791aSdanielk1977     FUNCTION(hex,                1, 0, 0, hexFunc          ),
2288ffe421c7Sdrh     INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),
2289b1fba286Sdrh     VFUNCTION(random,            0, 0, 0, randomFunc       ),
2290b1fba286Sdrh     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
22918c0a791aSdanielk1977     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
229203bf26d9Sdrh     DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
229303bf26d9Sdrh     DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
2294840561f2Sdrh     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
22958c0a791aSdanielk1977     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
2296b1fba286Sdrh     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
2297b1fba286Sdrh     VFUNCTION(changes,           0, 0, 0, changes          ),
2298b1fba286Sdrh     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
22998c0a791aSdanielk1977     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
23008c0a791aSdanielk1977     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
230180738d9cSdrh     FUNCTION(substr,             2, 0, 0, substrFunc       ),
230280738d9cSdrh     FUNCTION(substr,             3, 0, 0, substrFunc       ),
23031335ec7dSdrh     FUNCTION(substring,          2, 0, 0, substrFunc       ),
23041335ec7dSdrh     FUNCTION(substring,          3, 0, 0, substrFunc       ),
23056fb2b54cSdan     WAGGREGATE(sum,   1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
23066fb2b54cSdan     WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
23076fb2b54cSdan     WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
23087262ca94Sdan     WAGGREGATE(count, 0,0,0, countStep,
2309bb301231Sdrh         countFinalize, countFinalize, countInverse,
2310bb301231Sdrh         SQLITE_FUNC_COUNT|SQLITE_FUNC_ANYORDER  ),
23117262ca94Sdan     WAGGREGATE(count, 1,0,0, countStep,
2312bb301231Sdrh         countFinalize, countFinalize, countInverse, SQLITE_FUNC_ANYORDER ),
231303854d2eSdan     WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
23146fb2b54cSdan         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
231503854d2eSdan     WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
23166fb2b54cSdan         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
23178c0a791aSdanielk1977 
23188c0a791aSdanielk1977     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
23198c0a791aSdanielk1977 #ifdef SQLITE_CASE_SENSITIVE_LIKE
23208c0a791aSdanielk1977     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
23218c0a791aSdanielk1977     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
23228c0a791aSdanielk1977 #else
23238c0a791aSdanielk1977     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
23248c0a791aSdanielk1977     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
23258c0a791aSdanielk1977 #endif
2326cc15313cSdrh #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2327cc15313cSdrh     FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
2328cc15313cSdrh #endif
232980738d9cSdrh     FUNCTION(coalesce,           1, 0, 0, 0                ),
233080738d9cSdrh     FUNCTION(coalesce,           0, 0, 0, 0                ),
2331f6e904bdSdrh #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
23324fd4a7a1Sdrh     MFUNCTION(ceil,              1, xCeil,     ceilingFunc ),
23334fd4a7a1Sdrh     MFUNCTION(ceiling,           1, xCeil,     ceilingFunc ),
23344fd4a7a1Sdrh     MFUNCTION(floor,             1, xFloor,    ceilingFunc ),
2335d97a4c00Smistachkin #if SQLITE_HAVE_C99_MATH_FUNCS
233663f8f98aSdrh     MFUNCTION(trunc,             1, trunc,     ceilingFunc ),
2337d97a4c00Smistachkin #endif
2338f6e904bdSdrh     FUNCTION(ln,                 1, 0, 0,      logFunc     ),
2339f6e904bdSdrh     FUNCTION(log,                1, 1, 0,      logFunc     ),
2340f6e904bdSdrh     FUNCTION(log10,              1, 1, 0,      logFunc     ),
234163f8f98aSdrh     FUNCTION(log2,               1, 2, 0,      logFunc     ),
2342f6e904bdSdrh     FUNCTION(log,                2, 0, 0,      logFunc     ),
234363f8f98aSdrh     MFUNCTION(exp,               1, exp,       math1Func   ),
234463f8f98aSdrh     MFUNCTION(pow,               2, pow,       math2Func   ),
234563f8f98aSdrh     MFUNCTION(power,             2, pow,       math2Func   ),
234663f8f98aSdrh     MFUNCTION(mod,               2, fmod,      math2Func   ),
234763f8f98aSdrh     MFUNCTION(acos,              1, acos,      math1Func   ),
234863f8f98aSdrh     MFUNCTION(asin,              1, asin,      math1Func   ),
234963f8f98aSdrh     MFUNCTION(atan,              1, atan,      math1Func   ),
235063f8f98aSdrh     MFUNCTION(atan2,             2, atan2,     math2Func   ),
235163f8f98aSdrh     MFUNCTION(cos,               1, cos,       math1Func   ),
235263f8f98aSdrh     MFUNCTION(sin,               1, sin,       math1Func   ),
235363f8f98aSdrh     MFUNCTION(tan,               1, tan,       math1Func   ),
235463f8f98aSdrh     MFUNCTION(cosh,              1, cosh,      math1Func   ),
235563f8f98aSdrh     MFUNCTION(sinh,              1, sinh,      math1Func   ),
235663f8f98aSdrh     MFUNCTION(tanh,              1, tanh,      math1Func   ),
2357d97a4c00Smistachkin #if SQLITE_HAVE_C99_MATH_FUNCS
235863f8f98aSdrh     MFUNCTION(acosh,             1, acosh,     math1Func   ),
235963f8f98aSdrh     MFUNCTION(asinh,             1, asinh,     math1Func   ),
236063f8f98aSdrh     MFUNCTION(atanh,             1, atanh,     math1Func   ),
2361d97a4c00Smistachkin #endif
236263f8f98aSdrh     MFUNCTION(sqrt,              1, sqrt,      math1Func   ),
236363f8f98aSdrh     MFUNCTION(radians,           1, degToRad,  math1Func   ),
236463f8f98aSdrh     MFUNCTION(degrees,           1, radToDeg,  math1Func   ),
236563f8f98aSdrh     FUNCTION(pi,                 0, 0, 0,      piFunc      ),
2366f6e904bdSdrh #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
236763f8f98aSdrh     FUNCTION(sign,               1, 0, 0,      signFunc    ),
236863f8f98aSdrh     INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),
236963f8f98aSdrh     INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),
23708c0a791aSdanielk1977   };
2371545f587fSdrh #ifndef SQLITE_OMIT_ALTERTABLE
2372545f587fSdrh   sqlite3AlterFunctions();
2373545f587fSdrh #endif
2374dfa552f4Sdan   sqlite3WindowFunctions();
237580738d9cSdrh   sqlite3RegisterDateTimeFunctions();
23769dbf96bdSdrh   sqlite3RegisterJsonFunctions();
237780738d9cSdrh   sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
237880738d9cSdrh 
237980738d9cSdrh #if 0  /* Enable to print out how the built-in functions are hashed */
238080738d9cSdrh   {
238180738d9cSdrh     int i;
238280738d9cSdrh     FuncDef *p;
238380738d9cSdrh     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
238480738d9cSdrh       printf("FUNC-HASH %02d:", i);
238580738d9cSdrh       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
238680738d9cSdrh         int n = sqlite3Strlen30(p->zName);
238780738d9cSdrh         int h = p->zName[0] + n;
2388f9751074Sdrh         assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
238980738d9cSdrh         printf(" %s(%d)", p->zName, h);
239080738d9cSdrh       }
239180738d9cSdrh       printf("\n");
239280738d9cSdrh     }
239380738d9cSdrh   }
239480738d9cSdrh #endif
239570a8ca3cSdrh }
2396