xref: /sqlite-3.40.0/src/func.c (revision 7014aff3)
1dc04c583Sdrh /*
2dc04c583Sdrh ** 2002 February 23
3dc04c583Sdrh **
4dc04c583Sdrh ** The author disclaims copyright to this source code.  In place of
5dc04c583Sdrh ** a legal notice, here is a blessing:
6dc04c583Sdrh **
7dc04c583Sdrh **    May you do good and not evil.
8dc04c583Sdrh **    May you find forgiveness for yourself and forgive others.
9dc04c583Sdrh **    May you share freely, never taking more than you give.
10dc04c583Sdrh **
11dc04c583Sdrh *************************************************************************
12dc04c583Sdrh ** This file contains the C functions that implement various SQL
13dc04c583Sdrh ** functions of SQLite.
14dc04c583Sdrh **
15dc04c583Sdrh ** There is only one exported symbol in this file - the function
16dc04c583Sdrh ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
17dc04c583Sdrh ** All other code has file scope.
18dc04c583Sdrh **
19*7014aff3Sdrh ** $Id: func.c,v 1.33 2003/11/01 01:53:54 drh Exp $
20dc04c583Sdrh */
21dc04c583Sdrh #include <ctype.h>
22d3a149efSdrh #include <math.h>
23d3a149efSdrh #include <stdlib.h>
240bce8354Sdrh #include <assert.h>
250bce8354Sdrh #include "sqliteInt.h"
26771d8c3bSdrh #include "os.h"
270bce8354Sdrh 
280bce8354Sdrh /*
290bce8354Sdrh ** Implementation of the non-aggregate min() and max() functions
300bce8354Sdrh */
310bce8354Sdrh static void minFunc(sqlite_func *context, int argc, const char **argv){
320bce8354Sdrh   const char *zBest;
330bce8354Sdrh   int i;
340bce8354Sdrh 
3589425d5eSdrh   if( argc==0 ) return;
360bce8354Sdrh   zBest = argv[0];
378912d106Sdrh   if( zBest==0 ) return;
380bce8354Sdrh   for(i=1; i<argc; i++){
398912d106Sdrh     if( argv[i]==0 ) return;
400bce8354Sdrh     if( sqliteCompare(argv[i], zBest)<0 ){
410bce8354Sdrh       zBest = argv[i];
420bce8354Sdrh     }
430bce8354Sdrh   }
440bce8354Sdrh   sqlite_set_result_string(context, zBest, -1);
450bce8354Sdrh }
460bce8354Sdrh static void maxFunc(sqlite_func *context, int argc, const char **argv){
470bce8354Sdrh   const char *zBest;
480bce8354Sdrh   int i;
490bce8354Sdrh 
5089425d5eSdrh   if( argc==0 ) return;
510bce8354Sdrh   zBest = argv[0];
528912d106Sdrh   if( zBest==0 ) return;
530bce8354Sdrh   for(i=1; i<argc; i++){
548912d106Sdrh     if( argv[i]==0 ) return;
550bce8354Sdrh     if( sqliteCompare(argv[i], zBest)>0 ){
560bce8354Sdrh       zBest = argv[i];
570bce8354Sdrh     }
580bce8354Sdrh   }
590bce8354Sdrh   sqlite_set_result_string(context, zBest, -1);
600bce8354Sdrh }
610bce8354Sdrh 
620bce8354Sdrh /*
630bce8354Sdrh ** Implementation of the length() function
640bce8354Sdrh */
650bce8354Sdrh static void lengthFunc(sqlite_func *context, int argc, const char **argv){
660bce8354Sdrh   const char *z;
670bce8354Sdrh   int len;
680bce8354Sdrh 
690bce8354Sdrh   assert( argc==1 );
700bce8354Sdrh   z = argv[0];
718912d106Sdrh   if( z==0 ) return;
720bce8354Sdrh #ifdef SQLITE_UTF8
730bce8354Sdrh   for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
740bce8354Sdrh #else
750bce8354Sdrh   len = strlen(z);
760bce8354Sdrh #endif
770bce8354Sdrh   sqlite_set_result_int(context, len);
780bce8354Sdrh }
790bce8354Sdrh 
800bce8354Sdrh /*
810bce8354Sdrh ** Implementation of the abs() function
820bce8354Sdrh */
830bce8354Sdrh static void absFunc(sqlite_func *context, int argc, const char **argv){
840bce8354Sdrh   const char *z;
850bce8354Sdrh   assert( argc==1 );
860bce8354Sdrh   z = argv[0];
878912d106Sdrh   if( z==0 ) return;
888912d106Sdrh   if( z[0]=='-' && isdigit(z[1]) ) z++;
890bce8354Sdrh   sqlite_set_result_string(context, z, -1);
900bce8354Sdrh }
910bce8354Sdrh 
920bce8354Sdrh /*
930bce8354Sdrh ** Implementation of the substr() function
940bce8354Sdrh */
950bce8354Sdrh static void substrFunc(sqlite_func *context, int argc, const char **argv){
960bce8354Sdrh   const char *z;
970bce8354Sdrh #ifdef SQLITE_UTF8
980bce8354Sdrh   const char *z2;
990bce8354Sdrh   int i;
1000bce8354Sdrh #endif
1010bce8354Sdrh   int p1, p2, len;
1020bce8354Sdrh   assert( argc==3 );
1030bce8354Sdrh   z = argv[0];
1040bce8354Sdrh   if( z==0 ) return;
1050bce8354Sdrh   p1 = atoi(argv[1]?argv[1]:0);
1060bce8354Sdrh   p2 = atoi(argv[2]?argv[2]:0);
1070bce8354Sdrh #ifdef SQLITE_UTF8
10847c8a679Sdrh   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
1090bce8354Sdrh #else
1100bce8354Sdrh   len = strlen(z);
1110bce8354Sdrh #endif
1120bce8354Sdrh   if( p1<0 ){
11389425d5eSdrh     p1 += len;
114653bc759Sdrh     if( p1<0 ){
115653bc759Sdrh       p2 += p1;
116653bc759Sdrh       p1 = 0;
117653bc759Sdrh     }
1180bce8354Sdrh   }else if( p1>0 ){
1190bce8354Sdrh     p1--;
1200bce8354Sdrh   }
1210bce8354Sdrh   if( p1+p2>len ){
1220bce8354Sdrh     p2 = len-p1;
1230bce8354Sdrh   }
1240bce8354Sdrh #ifdef SQLITE_UTF8
1250bce8354Sdrh   for(i=0; i<p1; i++){
1260bce8354Sdrh     assert( z[i] );
12747c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p1++;
1280bce8354Sdrh   }
12947c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
1300bce8354Sdrh   for(; i<p1+p2; i++){
1310bce8354Sdrh     assert( z[i] );
13247c8a679Sdrh     if( (z[i]&0xc0)==0x80 ) p2++;
1330bce8354Sdrh   }
13447c8a679Sdrh   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
1350bce8354Sdrh #endif
136653bc759Sdrh   if( p2<0 ) p2 = 0;
1370bce8354Sdrh   sqlite_set_result_string(context, &z[p1], p2);
1380bce8354Sdrh }
1390bce8354Sdrh 
1400bce8354Sdrh /*
1410bce8354Sdrh ** Implementation of the round() function
1420bce8354Sdrh */
1430bce8354Sdrh static void roundFunc(sqlite_func *context, int argc, const char **argv){
1440bce8354Sdrh   int n;
1450bce8354Sdrh   double r;
1460bce8354Sdrh   char zBuf[100];
1470bce8354Sdrh   assert( argc==1 || argc==2 );
1488912d106Sdrh   if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
1498912d106Sdrh   n = argc==2 ? atoi(argv[1]) : 0;
1500bce8354Sdrh   if( n>30 ) n = 30;
1510bce8354Sdrh   if( n<0 ) n = 0;
1528912d106Sdrh   r = atof(argv[0]);
1530bce8354Sdrh   sprintf(zBuf,"%.*f",n,r);
1540bce8354Sdrh   sqlite_set_result_string(context, zBuf, -1);
1550bce8354Sdrh }
156dc04c583Sdrh 
157dc04c583Sdrh /*
158dc04c583Sdrh ** Implementation of the upper() and lower() SQL functions.
159dc04c583Sdrh */
1601350b030Sdrh static void upperFunc(sqlite_func *context, int argc, const char **argv){
161dc04c583Sdrh   char *z;
162dc04c583Sdrh   int i;
163dc04c583Sdrh   if( argc<1 || argv[0]==0 ) return;
164dc04c583Sdrh   z = sqlite_set_result_string(context, argv[0], -1);
165dc04c583Sdrh   if( z==0 ) return;
166dc04c583Sdrh   for(i=0; z[i]; i++){
167dc04c583Sdrh     if( islower(z[i]) ) z[i] = toupper(z[i]);
168dc04c583Sdrh   }
169dc04c583Sdrh }
1701350b030Sdrh static void lowerFunc(sqlite_func *context, int argc, const char **argv){
171dc04c583Sdrh   char *z;
172dc04c583Sdrh   int i;
173dc04c583Sdrh   if( argc<1 || argv[0]==0 ) return;
174dc04c583Sdrh   z = sqlite_set_result_string(context, argv[0], -1);
175dc04c583Sdrh   if( z==0 ) return;
176dc04c583Sdrh   for(i=0; z[i]; i++){
177dc04c583Sdrh     if( isupper(z[i]) ) z[i] = tolower(z[i]);
178dc04c583Sdrh   }
179dc04c583Sdrh }
180dc04c583Sdrh 
181dc04c583Sdrh /*
182fbc99082Sdrh ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
183fbc99082Sdrh ** All three do the same thing.  They return the first argument
184fbc99082Sdrh ** non-NULL argument.
1853212e182Sdrh */
1863212e182Sdrh static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
187fbc99082Sdrh   int i;
188fbc99082Sdrh   for(i=0; i<argc; i++){
189fbc99082Sdrh     if( argv[i] ){
190fbc99082Sdrh       sqlite_set_result_string(context, argv[i], -1);
191fbc99082Sdrh       break;
192fbc99082Sdrh     }
193fbc99082Sdrh   }
1943212e182Sdrh }
1953212e182Sdrh 
1963212e182Sdrh /*
197f9ffac96Sdrh ** Implementation of random().  Return a random integer.
198f9ffac96Sdrh */
199f9ffac96Sdrh static void randomFunc(sqlite_func *context, int argc, const char **argv){
200f9ffac96Sdrh   sqlite_set_result_int(context, sqliteRandomInteger());
201f9ffac96Sdrh }
202f9ffac96Sdrh 
203f9ffac96Sdrh /*
2046ed41ad7Sdrh ** Implementation of the last_insert_rowid() SQL function.  The return
2056ed41ad7Sdrh ** value is the same as the sqlite_last_insert_rowid() API function.
2066ed41ad7Sdrh */
2070ac65892Sdrh static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
2086ed41ad7Sdrh   sqlite *db = sqlite_user_data(context);
2096ed41ad7Sdrh   sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
2106ed41ad7Sdrh }
2116ed41ad7Sdrh 
2126ed41ad7Sdrh /*
2130ac65892Sdrh ** Implementation of the like() SQL function.  This function implements
2140ac65892Sdrh ** the build-in LIKE operator.  The first argument to the function is the
2150ac65892Sdrh ** string and the second argument is the pattern.  So, the SQL statements:
2160ac65892Sdrh **
2170ac65892Sdrh **       A LIKE B
2180ac65892Sdrh **
2190ac65892Sdrh ** is implemented as like(A,B).
2200ac65892Sdrh */
2210ac65892Sdrh static void likeFunc(sqlite_func *context, int arg, const char **argv){
2228912d106Sdrh   if( argv[0]==0 || argv[1]==0 ) return;
223ec1bd0bdSdrh   sqlite_set_result_int(context,
224ec1bd0bdSdrh     sqliteLikeCompare((const unsigned char*)argv[0],
225ec1bd0bdSdrh                       (const unsigned char*)argv[1]));
2260ac65892Sdrh }
2270ac65892Sdrh 
2280ac65892Sdrh /*
2290ac65892Sdrh ** Implementation of the glob() SQL function.  This function implements
2300ac65892Sdrh ** the build-in GLOB operator.  The first argument to the function is the
2310ac65892Sdrh ** string and the second argument is the pattern.  So, the SQL statements:
2320ac65892Sdrh **
2330ac65892Sdrh **       A GLOB B
2340ac65892Sdrh **
2350ac65892Sdrh ** is implemented as glob(A,B).
2360ac65892Sdrh */
2370ac65892Sdrh static void globFunc(sqlite_func *context, int arg, const char **argv){
2388912d106Sdrh   if( argv[0]==0 || argv[1]==0 ) return;
239ec1bd0bdSdrh   sqlite_set_result_int(context,
240ec1bd0bdSdrh     sqliteGlobCompare((const unsigned char*)argv[0],
241ec1bd0bdSdrh                       (const unsigned char*)argv[1]));
2428912d106Sdrh }
2438912d106Sdrh 
2448912d106Sdrh /*
2458912d106Sdrh ** Implementation of the NULLIF(x,y) function.  The result is the first
2468912d106Sdrh ** argument if the arguments are different.  The result is NULL if the
2478912d106Sdrh ** arguments are equal to each other.
2488912d106Sdrh */
2498912d106Sdrh static void nullifFunc(sqlite_func *context, int argc, const char **argv){
2508912d106Sdrh   if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
2518912d106Sdrh     sqlite_set_result_string(context, argv[0], -1);
2528912d106Sdrh   }
2530ac65892Sdrh }
2540ac65892Sdrh 
255647cb0e1Sdrh /*
256647cb0e1Sdrh ** Implementation of the VERSION(*) function.  The result is the version
257647cb0e1Sdrh ** of the SQLite library that is running.
258647cb0e1Sdrh */
259647cb0e1Sdrh static void versionFunc(sqlite_func *context, int argc, const char **argv){
260647cb0e1Sdrh   sqlite_set_result_string(context, sqlite_version, -1);
261647cb0e1Sdrh }
262647cb0e1Sdrh 
26347394703Sdrh /*
26447394703Sdrh ** EXPERIMENTAL - This is not an official function.  The interface may
26547394703Sdrh ** change.  This function may disappear.  Do not write code that depends
26647394703Sdrh ** on this function.
26747394703Sdrh **
26847394703Sdrh ** Implementation of the QUOTE() function.  This function takes a single
26947394703Sdrh ** argument.  If the argument is numeric, the return value is the same as
27047394703Sdrh ** the argument.  If the argument is NULL, the return value is the string
27147394703Sdrh ** "NULL".  Otherwise, the argument is enclosed in single quotes with
27247394703Sdrh ** single-quote escapes.
27347394703Sdrh */
27447394703Sdrh static void quoteFunc(sqlite_func *context, int argc, const char **argv){
27547394703Sdrh   if( argc<1 ) return;
27647394703Sdrh   if( argv[0]==0 ){
27747394703Sdrh     sqlite_set_result_string(context, "NULL", 4);
27847394703Sdrh   }else if( sqliteIsNumber(argv[0]) ){
27947394703Sdrh     sqlite_set_result_string(context, argv[0], -1);
28047394703Sdrh   }else{
28147394703Sdrh     int i,j,n;
28247394703Sdrh     char *z;
28347394703Sdrh     for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
28447394703Sdrh     z = sqliteMalloc( i+n+3 );
28547394703Sdrh     if( z==0 ) return;
28647394703Sdrh     z[0] = '\'';
28747394703Sdrh     for(i=0, j=1; argv[0][i]; i++){
28847394703Sdrh       z[j++] = argv[0][i];
28947394703Sdrh       if( argv[0][i]=='\'' ){
29047394703Sdrh         z[j++] = '\'';
29147394703Sdrh       }
29247394703Sdrh     }
29347394703Sdrh     z[j++] = '\'';
29447394703Sdrh     z[j] = 0;
29547394703Sdrh     sqlite_set_result_string(context, z, j);
29647394703Sdrh     sqliteFree(z);
29747394703Sdrh   }
29847394703Sdrh }
29947394703Sdrh 
300d24cc427Sdrh #ifdef SQLITE_SOUNDEX
301d24cc427Sdrh /*
302d24cc427Sdrh ** Compute the soundex encoding of a word.
303d24cc427Sdrh */
304d24cc427Sdrh static void soundexFunc(sqlite_func *context, int argc, const char **argv){
305d24cc427Sdrh   char zResult[8];
306d24cc427Sdrh   const char *zIn;
307d24cc427Sdrh   int i, j;
308d24cc427Sdrh   static const unsigned char iCode[] = {
309d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
310d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
311d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
312d24cc427Sdrh     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
313d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
314d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
315d24cc427Sdrh     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
316d24cc427Sdrh     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
317d24cc427Sdrh   };
318d24cc427Sdrh   assert( argc==1 );
319d24cc427Sdrh   zIn = argv[0];
320d24cc427Sdrh   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
321d24cc427Sdrh   if( zIn[i] ){
322d24cc427Sdrh     zResult[0] = toupper(zIn[i]);
323d24cc427Sdrh     for(j=1; j<4 && zIn[i]; i++){
324d24cc427Sdrh       int code = iCode[zIn[i]&0x7f];
325d24cc427Sdrh       if( code>0 ){
326d24cc427Sdrh         zResult[j++] = code + '0';
327d24cc427Sdrh       }
328d24cc427Sdrh     }
329d24cc427Sdrh     while( j<4 ){
330d24cc427Sdrh       zResult[j++] = '0';
331d24cc427Sdrh     }
332d24cc427Sdrh     zResult[j] = 0;
333d24cc427Sdrh     sqlite_set_result_string(context, zResult, 4);
334d24cc427Sdrh   }else{
335937dd84dSdrh     sqlite_set_result_string(context, "?000", 4);
336d24cc427Sdrh   }
337d24cc427Sdrh }
338d24cc427Sdrh #endif
339d24cc427Sdrh 
340193a6b41Sdrh #ifdef SQLITE_TEST
341193a6b41Sdrh /*
342193a6b41Sdrh ** This function generates a string of random characters.  Used for
343193a6b41Sdrh ** generating test data.
344193a6b41Sdrh */
345193a6b41Sdrh static void randStr(sqlite_func *context, int argc, const char **argv){
346193a6b41Sdrh   static const char zSrc[] =
347193a6b41Sdrh      "abcdefghijklmnopqrstuvwxyz"
348193a6b41Sdrh      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
349193a6b41Sdrh      "0123456789"
350193a6b41Sdrh      ".-!,:*^+=_|?/<> ";
351193a6b41Sdrh   int iMin, iMax, n, r, i;
352193a6b41Sdrh   char zBuf[1000];
353193a6b41Sdrh   if( argc>=1 ){
354193a6b41Sdrh     iMin = atoi(argv[0]);
355193a6b41Sdrh     if( iMin<0 ) iMin = 0;
356193a6b41Sdrh     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
357193a6b41Sdrh   }else{
358193a6b41Sdrh     iMin = 1;
359193a6b41Sdrh   }
360193a6b41Sdrh   if( argc>=2 ){
361193a6b41Sdrh     iMax = atoi(argv[1]);
362193a6b41Sdrh     if( iMax<iMin ) iMax = iMin;
363193a6b41Sdrh     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf);
364193a6b41Sdrh   }else{
365193a6b41Sdrh     iMax = 50;
366193a6b41Sdrh   }
367193a6b41Sdrh   n = iMin;
368193a6b41Sdrh   if( iMax>iMin ){
36939581966Sdrh     r = sqliteRandomInteger() & 0x7fffffff;
370193a6b41Sdrh     n += r%(iMax + 1 - iMin);
371193a6b41Sdrh   }
372193a6b41Sdrh   r = 0;
373193a6b41Sdrh   for(i=0; i<n; i++){
374193a6b41Sdrh     r = (r + sqliteRandomByte())% (sizeof(zSrc)-1);
375193a6b41Sdrh     zBuf[i] = zSrc[r];
376193a6b41Sdrh   }
377193a6b41Sdrh   zBuf[n] = 0;
378193a6b41Sdrh   sqlite_set_result_string(context, zBuf, n);
379193a6b41Sdrh }
380193a6b41Sdrh #endif
381193a6b41Sdrh 
3820ac65892Sdrh /*
383d3a149efSdrh ** An instance of the following structure holds the context of a
384dd5baa95Sdrh ** sum() or avg() aggregate computation.
385dd5baa95Sdrh */
386dd5baa95Sdrh typedef struct SumCtx SumCtx;
387dd5baa95Sdrh struct SumCtx {
388dd5baa95Sdrh   double sum;     /* Sum of terms */
389739105c7Sdrh   int cnt;        /* Number of elements summed */
390dd5baa95Sdrh };
391dd5baa95Sdrh 
392dd5baa95Sdrh /*
393dd5baa95Sdrh ** Routines used to compute the sum or average.
394dd5baa95Sdrh */
395dd5baa95Sdrh static void sumStep(sqlite_func *context, int argc, const char **argv){
396dd5baa95Sdrh   SumCtx *p;
397dd5baa95Sdrh   if( argc<1 ) return;
398dd5baa95Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
399739105c7Sdrh   if( p && argv[0] ){
400739105c7Sdrh     p->sum += atof(argv[0]);
401739105c7Sdrh     p->cnt++;
402739105c7Sdrh   }
403dd5baa95Sdrh }
404dd5baa95Sdrh static void sumFinalize(sqlite_func *context){
405dd5baa95Sdrh   SumCtx *p;
406dd5baa95Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
40789425d5eSdrh   sqlite_set_result_double(context, p ? p->sum : 0.0);
408dd5baa95Sdrh }
409dd5baa95Sdrh static void avgFinalize(sqlite_func *context){
410dd5baa95Sdrh   SumCtx *p;
411dd5baa95Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
412739105c7Sdrh   if( p && p->cnt>0 ){
413739105c7Sdrh     sqlite_set_result_double(context, p->sum/(double)p->cnt);
414dd5baa95Sdrh   }
415dd5baa95Sdrh }
416dd5baa95Sdrh 
417dd5baa95Sdrh /*
418dd5baa95Sdrh ** An instance of the following structure holds the context of a
419a2ed5601Sdrh ** variance or standard deviation computation.
420d3a149efSdrh */
421d3a149efSdrh typedef struct StdDevCtx StdDevCtx;
422d3a149efSdrh struct StdDevCtx {
423d3a149efSdrh   double sum;     /* Sum of terms */
424d3a149efSdrh   double sum2;    /* Sum of the squares of terms */
425739105c7Sdrh   int cnt;        /* Number of terms counted */
426d3a149efSdrh };
427d3a149efSdrh 
428ef2daf54Sdrh #if 0   /* Omit because math library is required */
429d3a149efSdrh /*
430d3a149efSdrh ** Routines used to compute the standard deviation as an aggregate.
431d3a149efSdrh */
4321350b030Sdrh static void stdDevStep(sqlite_func *context, int argc, const char **argv){
433d3a149efSdrh   StdDevCtx *p;
434d3a149efSdrh   double x;
4351350b030Sdrh   if( argc<1 ) return;
4361350b030Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
437739105c7Sdrh   if( p && argv[0] ){
438739105c7Sdrh     x = atof(argv[0]);
439d3a149efSdrh     p->sum += x;
440d3a149efSdrh     p->sum2 += x*x;
441739105c7Sdrh     p->cnt++;
442739105c7Sdrh   }
443d3a149efSdrh }
4441350b030Sdrh static void stdDevFinalize(sqlite_func *context){
445dd5baa95Sdrh   double rN = sqlite_aggregate_count(context);
4461350b030Sdrh   StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
447739105c7Sdrh   if( p && p->cnt>1 ){
448739105c7Sdrh     double rCnt = cnt;
449d3a149efSdrh     sqlite_set_result_double(context,
450739105c7Sdrh        sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
451d3a149efSdrh   }
452d3a149efSdrh }
453ef2daf54Sdrh #endif
454d3a149efSdrh 
4550bce8354Sdrh /*
4560bce8354Sdrh ** The following structure keeps track of state information for the
4570bce8354Sdrh ** count() aggregate function.
4580bce8354Sdrh */
4590bce8354Sdrh typedef struct CountCtx CountCtx;
4600bce8354Sdrh struct CountCtx {
4610bce8354Sdrh   int n;
4620bce8354Sdrh };
463dd5baa95Sdrh 
4640bce8354Sdrh /*
4650bce8354Sdrh ** Routines to implement the count() aggregate function.
4660bce8354Sdrh */
4670bce8354Sdrh static void countStep(sqlite_func *context, int argc, const char **argv){
4680bce8354Sdrh   CountCtx *p;
4690bce8354Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
4700bce8354Sdrh   if( (argc==0 || argv[0]) && p ){
4710bce8354Sdrh     p->n++;
4720bce8354Sdrh   }
4730bce8354Sdrh }
4740bce8354Sdrh static void countFinalize(sqlite_func *context){
4750bce8354Sdrh   CountCtx *p;
4760bce8354Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
477f55f25f0Sdrh   sqlite_set_result_int(context, p ? p->n : 0);
4780bce8354Sdrh }
4790bce8354Sdrh 
4800bce8354Sdrh /*
4810bce8354Sdrh ** This function tracks state information for the min() and max()
4820bce8354Sdrh ** aggregate functions.
4830bce8354Sdrh */
4840bce8354Sdrh typedef struct MinMaxCtx MinMaxCtx;
4850bce8354Sdrh struct MinMaxCtx {
4860bce8354Sdrh   char *z;         /* The best so far */
4870bce8354Sdrh   char zBuf[28];   /* Space that can be used for storage */
4880bce8354Sdrh };
4890bce8354Sdrh 
4900bce8354Sdrh /*
4910bce8354Sdrh ** Routines to implement min() and max() aggregate functions.
4920bce8354Sdrh */
4930bce8354Sdrh static void minStep(sqlite_func *context, int argc, const char **argv){
4940bce8354Sdrh   MinMaxCtx *p;
4950bce8354Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
496739105c7Sdrh   if( p==0 || argc<1 || argv[0]==0 ) return;
497f570f011Sdrh   if( p->z==0 || sqliteCompare(argv[0],p->z)<0 ){
4988912d106Sdrh     int len;
4990bce8354Sdrh     if( p->z && p->z!=p->zBuf ){
5000bce8354Sdrh       sqliteFree(p->z);
5010bce8354Sdrh     }
5028912d106Sdrh     len = strlen(argv[0]);
5030bce8354Sdrh     if( len < sizeof(p->zBuf) ){
5040bce8354Sdrh       p->z = p->zBuf;
5050bce8354Sdrh     }else{
5060bce8354Sdrh       p->z = sqliteMalloc( len+1 );
5070bce8354Sdrh       if( p->z==0 ) return;
5080bce8354Sdrh     }
5090bce8354Sdrh     strcpy(p->z, argv[0]);
5100bce8354Sdrh   }
5110bce8354Sdrh }
5120bce8354Sdrh static void maxStep(sqlite_func *context, int argc, const char **argv){
5130bce8354Sdrh   MinMaxCtx *p;
5140bce8354Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
515739105c7Sdrh   if( p==0 || argc<1 || argv[0]==0 ) return;
516f570f011Sdrh   if( p->z==0 || sqliteCompare(argv[0],p->z)>0 ){
5178912d106Sdrh     int len;
5180bce8354Sdrh     if( p->z && p->z!=p->zBuf ){
5190bce8354Sdrh       sqliteFree(p->z);
5200bce8354Sdrh     }
5218912d106Sdrh     len = strlen(argv[0]);
5220bce8354Sdrh     if( len < sizeof(p->zBuf) ){
5230bce8354Sdrh       p->z = p->zBuf;
5240bce8354Sdrh     }else{
5250bce8354Sdrh       p->z = sqliteMalloc( len+1 );
5260bce8354Sdrh       if( p->z==0 ) return;
5270bce8354Sdrh     }
5280bce8354Sdrh     strcpy(p->z, argv[0]);
5290bce8354Sdrh   }
5300bce8354Sdrh }
5310bce8354Sdrh static void minMaxFinalize(sqlite_func *context){
5320bce8354Sdrh   MinMaxCtx *p;
5330bce8354Sdrh   p = sqlite_aggregate_context(context, sizeof(*p));
534739105c7Sdrh   if( p && p->z ){
5350bce8354Sdrh     sqlite_set_result_string(context, p->z, strlen(p->z));
5360bce8354Sdrh   }
5370bce8354Sdrh   if( p && p->z && p->z!=p->zBuf ){
5380bce8354Sdrh     sqliteFree(p->z);
5390bce8354Sdrh   }
5400bce8354Sdrh }
541dd5baa95Sdrh 
542d3a149efSdrh /*
543a2ed5601Sdrh ** This function registered all of the above C functions as SQL
544a2ed5601Sdrh ** functions.  This should be the only routine in this file with
545a2ed5601Sdrh ** external linkage.
546dc04c583Sdrh */
54728f4b688Sdrh void sqliteRegisterBuiltinFunctions(sqlite *db){
5480bce8354Sdrh   static struct {
5490bce8354Sdrh      char *zName;
5500bce8354Sdrh      int nArg;
551c9b84a1fSdrh      int dataType;
5520bce8354Sdrh      void (*xFunc)(sqlite_func*,int,const char**);
5530bce8354Sdrh   } aFuncs[] = {
554c9b84a1fSdrh     { "min",       -1, SQLITE_ARGS,    minFunc    },
555c9b84a1fSdrh     { "min",        0, 0,              0          },
556c9b84a1fSdrh     { "max",       -1, SQLITE_ARGS,    maxFunc    },
557c9b84a1fSdrh     { "max",        0, 0,              0          },
558c9b84a1fSdrh     { "length",     1, SQLITE_NUMERIC, lengthFunc },
559c9b84a1fSdrh     { "substr",     3, SQLITE_TEXT,    substrFunc },
560c9b84a1fSdrh     { "abs",        1, SQLITE_NUMERIC, absFunc    },
561c9b84a1fSdrh     { "round",      1, SQLITE_NUMERIC, roundFunc  },
562c9b84a1fSdrh     { "round",      2, SQLITE_NUMERIC, roundFunc  },
563c9b84a1fSdrh     { "upper",      1, SQLITE_TEXT,    upperFunc  },
564c9b84a1fSdrh     { "lower",      1, SQLITE_TEXT,    lowerFunc  },
565c9b84a1fSdrh     { "coalesce",  -1, SQLITE_ARGS,    ifnullFunc },
566c9b84a1fSdrh     { "coalesce",   0, 0,              0          },
567c9b84a1fSdrh     { "coalesce",   1, 0,              0          },
568c9b84a1fSdrh     { "ifnull",     2, SQLITE_ARGS,    ifnullFunc },
569c9b84a1fSdrh     { "random",    -1, SQLITE_NUMERIC, randomFunc },
570c9b84a1fSdrh     { "like",       2, SQLITE_NUMERIC, likeFunc   },
571c9b84a1fSdrh     { "glob",       2, SQLITE_NUMERIC, globFunc   },
572c9b84a1fSdrh     { "nullif",     2, SQLITE_ARGS,    nullifFunc },
573647cb0e1Sdrh     { "sqlite_version",0,SQLITE_TEXT,  versionFunc},
57447394703Sdrh     { "quote",      1, SQLITE_ARGS,    quoteFunc  },
575d24cc427Sdrh #ifdef SQLITE_SOUNDEX
576d24cc427Sdrh     { "soundex",    1, SQLITE_TEXT,    soundexFunc},
577d24cc427Sdrh #endif
578193a6b41Sdrh #ifdef SQLITE_TEST
579193a6b41Sdrh     { "randstr",    2, SQLITE_TEXT,    randStr    },
580193a6b41Sdrh #endif
5810bce8354Sdrh   };
5820bce8354Sdrh   static struct {
5830bce8354Sdrh     char *zName;
5840bce8354Sdrh     int nArg;
585c9b84a1fSdrh     int dataType;
5860bce8354Sdrh     void (*xStep)(sqlite_func*,int,const char**);
5870bce8354Sdrh     void (*xFinalize)(sqlite_func*);
5880bce8354Sdrh   } aAggs[] = {
589c9b84a1fSdrh     { "min",    1, 0,              minStep,      minMaxFinalize },
590c9b84a1fSdrh     { "max",    1, 0,              maxStep,      minMaxFinalize },
591c9b84a1fSdrh     { "sum",    1, SQLITE_NUMERIC, sumStep,      sumFinalize    },
592c9b84a1fSdrh     { "avg",    1, SQLITE_NUMERIC, sumStep,      avgFinalize    },
593c9b84a1fSdrh     { "count",  0, SQLITE_NUMERIC, countStep,    countFinalize  },
594c9b84a1fSdrh     { "count",  1, SQLITE_NUMERIC, countStep,    countFinalize  },
595ef2daf54Sdrh #if 0
596c9b84a1fSdrh     { "stddev", 1, SQLITE_NUMERIC, stdDevStep,   stdDevFinalize },
597ef2daf54Sdrh #endif
5980bce8354Sdrh   };
5990bce8354Sdrh   int i;
6000bce8354Sdrh 
6010bce8354Sdrh   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
6020bce8354Sdrh     sqlite_create_function(db, aFuncs[i].zName,
6030bce8354Sdrh            aFuncs[i].nArg, aFuncs[i].xFunc, 0);
604c9b84a1fSdrh     if( aFuncs[i].xFunc ){
605c9b84a1fSdrh       sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
606c9b84a1fSdrh     }
6070bce8354Sdrh   }
6086ed41ad7Sdrh   sqlite_create_function(db, "last_insert_rowid", 0,
6096ed41ad7Sdrh            last_insert_rowid, db);
610c9b84a1fSdrh   sqlite_function_type(db, "last_insert_rowid", SQLITE_NUMERIC);
6110bce8354Sdrh   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
6120bce8354Sdrh     sqlite_create_aggregate(db, aAggs[i].zName,
6130bce8354Sdrh            aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, 0);
614c9b84a1fSdrh     sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
6150bce8354Sdrh   }
616*7014aff3Sdrh   sqliteRegisterDateTimeFunctions(db);
617dc04c583Sdrh }
618