xref: /illumos-gate/usr/src/lib/libsqlite/src/func.c (revision 33efde4275d24731ef87927237b0ffb0630b6b2d)
1 /*
2 ** 2002 February 23
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains the C functions that implement various SQL
13 ** functions of SQLite.
14 **
15 ** There is only one exported symbol in this file - the function
16 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
17 ** All other code has file scope.
18 **
19 ** $Id: func.c,v 1.43.2.3 2004/07/18 23:03:11 drh Exp $
20 */
21 #include <ctype.h>
22 #include <math.h>
23 #include <stdlib.h>
24 #include <sys/u8_textprep.h>
25 #include <assert.h>
26 #include "sqliteInt.h"
27 #include "os.h"
28 
29 /*
30 ** Implementation of the non-aggregate min() and max() functions
31 */
minmaxFunc(sqlite_func * context,int argc,const char ** argv)32 static void minmaxFunc(sqlite_func *context, int argc, const char **argv){
33   const char *zBest;
34   int i;
35   int (*xCompare)(const char*, const char*);
36   int mask;    /* 0 for min() or 0xffffffff for max() */
37 
38   if( argc==0 ) return;
39   mask = (int)sqlite_user_data(context);
40   zBest = argv[0];
41   if( zBest==0 ) return;
42   if( argv[1][0]=='n' ){
43     xCompare = sqliteCompare;
44   }else{
45     xCompare = strcmp;
46   }
47   for(i=2; i<argc; i+=2){
48     if( argv[i]==0 ) return;
49     if( (xCompare(argv[i], zBest)^mask)<0 ){
50       zBest = argv[i];
51     }
52   }
53   sqlite_set_result_string(context, zBest, -1);
54 }
55 
56 /*
57 ** Return the type of the argument.
58 */
typeofFunc(sqlite_func * context,int argc,const char ** argv)59 static void typeofFunc(sqlite_func *context, int argc, const char **argv){
60   assert( argc==2 );
61   sqlite_set_result_string(context, argv[1], -1);
62 }
63 
64 /*
65 ** Implementation of the length() function
66 */
lengthFunc(sqlite_func * context,int argc,const char ** argv)67 static void lengthFunc(sqlite_func *context, int argc, const char **argv){
68   const char *z;
69   int len;
70 
71   assert( argc==1 );
72   z = argv[0];
73   if( z==0 ) return;
74 #ifdef SQLITE_UTF8
75   for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
76 #else
77   len = strlen(z);
78 #endif
79   sqlite_set_result_int(context, len);
80 }
81 
82 /*
83 ** Implementation of the abs() function
84 */
absFunc(sqlite_func * context,int argc,const char ** argv)85 static void absFunc(sqlite_func *context, int argc, const char **argv){
86   const char *z;
87   assert( argc==1 );
88   z = argv[0];
89   if( z==0 ) return;
90   if( z[0]=='-' && isdigit(z[1]) ) z++;
91   sqlite_set_result_string(context, z, -1);
92 }
93 
94 /*
95 ** Implementation of the substr() function
96 */
substrFunc(sqlite_func * context,int argc,const char ** argv)97 static void substrFunc(sqlite_func *context, int argc, const char **argv){
98   const char *z;
99 #ifdef SQLITE_UTF8
100   const char *z2;
101   int i;
102 #endif
103   int p1, p2, len;
104   assert( argc==3 );
105   z = argv[0];
106   if( z==0 ) return;
107   p1 = atoi(argv[1]?argv[1]:0);
108   p2 = atoi(argv[2]?argv[2]:0);
109 #ifdef SQLITE_UTF8
110   for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
111 #else
112   len = strlen(z);
113 #endif
114   if( p1<0 ){
115     p1 += len;
116     if( p1<0 ){
117       p2 += p1;
118       p1 = 0;
119     }
120   }else if( p1>0 ){
121     p1--;
122   }
123   if( p1+p2>len ){
124     p2 = len-p1;
125   }
126 #ifdef SQLITE_UTF8
127   for(i=0; i<p1 && z[i]; i++){
128     if( (z[i]&0xc0)==0x80 ) p1++;
129   }
130   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
131   for(; i<p1+p2 && z[i]; i++){
132     if( (z[i]&0xc0)==0x80 ) p2++;
133   }
134   while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
135 #endif
136   if( p2<0 ) p2 = 0;
137   sqlite_set_result_string(context, &z[p1], p2);
138 }
139 
140 /*
141 ** Implementation of the round() function
142 */
roundFunc(sqlite_func * context,int argc,const char ** argv)143 static void roundFunc(sqlite_func *context, int argc, const char **argv){
144   int n;
145   double r;
146   char zBuf[100];
147   assert( argc==1 || argc==2 );
148   if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
149   n = argc==2 ? atoi(argv[1]) : 0;
150   if( n>30 ) n = 30;
151   if( n<0 ) n = 0;
152   r = sqliteAtoF(argv[0], 0);
153   sprintf(zBuf,"%.*f",n,r);
154   sqlite_set_result_string(context, zBuf, -1);
155 }
156 
157 /*
158 ** Implementation of the upper() and lower() SQL functions.
159 */
upperFunc(sqlite_func * context,int argc,const char ** argv)160 static void upperFunc(sqlite_func *context, int argc, const char **argv){
161   unsigned char *z;
162   int i;
163   if( argc<1 || argv[0]==0 ) return;
164   z = (unsigned char*)sqlite_set_result_string(context, argv[0], -1);
165   if( z==0 ) return;
166   for(i=0; z[i]; i++){
167     if( islower(z[i]) ) z[i] = toupper(z[i]);
168   }
169 }
lowerFunc(sqlite_func * context,int argc,const char ** argv)170 static void lowerFunc(sqlite_func *context, int argc, const char **argv){
171   unsigned char *z;
172   int i;
173   if( argc<1 || argv[0]==0 ) return;
174   z = (unsigned char*)sqlite_set_result_string(context, argv[0], -1);
175   if( z==0 ) return;
176   for(i=0; z[i]; i++){
177     if( isupper(z[i]) ) z[i] = tolower(z[i]);
178   }
179 }
180 
181 /*
182  * A utility wrapper around u8_textprep_str() that returns an allocated
183  * string.  The result must be freed or passed to
184  * sqlite_set_result_string().
185  *
186  * This is a Solaris-specific function, though it could be made
187  * portable.  u8_textprep_str() and friends are CDDL'ed.  This code was
188  * added to this file without changing the public domain notice, and
189  * therefore is in the public domain as well.
190  */
191 static
192 char *
utf8textprep(const char * s,int flag)193 utf8textprep(const char *s, int flag)
194 {
195 	char *res = NULL;
196 	char *outs;
197 	size_t inlen, outlen, inbytesleft, outbytesleft;
198 	int rc, err;
199 
200 	/*
201 	 * u8_textprep_str() does not allocate memory.  The input and
202 	 * output buffers may differ in size (though that would be more
203 	 * likely when normalization is done).  We have to loop over it...
204 	 *
205 	 * To improve the chances that we can avoid looping we add 10
206 	 * bytes of output buffer room the first go around.
207 	 */
208 	inlen = inbytesleft = strlen(s);
209 	outlen = outbytesleft = inlen + 10;
210 	if ((res = sqliteMalloc(outlen)) == NULL)
211 		return (NULL);
212 	outs = res;
213 
214 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
215 	    &outbytesleft, flag, U8_UNICODE_LATEST, &err)) < 0 &&
216 	    err == E2BIG) {
217 		if ((res = sqliteRealloc(res, outlen + inbytesleft)) == NULL)
218 			return (NULL);
219 		/* adjust input/output buffer pointers */
220 		s += (inlen - inbytesleft);
221 		outs = res + outlen - outbytesleft;
222 		/* adjust outbytesleft and outlen */
223 		outlen += inbytesleft;
224 		outbytesleft += inbytesleft;
225 	}
226 
227 	if (rc < 0) {
228 		free(res);
229 		res = NULL;
230 		return (NULL);
231 	}
232 
233 	res[outlen - outbytesleft] = '\0';
234 
235 	return (res);
236 }
237 /*
238  * A Unicode-capable case-folding (to lower) function
239  *
240  * See block comment for case_fold_utf8().
241  */
242 static
243 void
lower_utf8Func(sqlite_func * context,int argc,const char ** argv)244 lower_utf8Func(sqlite_func *context, int argc, const char **argv)
245 {
246 	char *lower = NULL;
247 
248 	/*
249 	 * SQLite functions can take many arguments, but this function
250 	 * uses only one, and we call sqlite_create_function() with
251 	 * nArg == 1.
252 	 */
253 	assert(argc <= 1);
254 
255 	if (argv[0] != NULL)
256 		lower = utf8textprep(argv[0], U8_TEXTPREP_TOLOWER);
257 
258 	(void) sqlite_set_result_string(context, lower, -1);
259 	free(lower);
260 }
261 static
262 void
upper_utf8Func(sqlite_func * context,int argc,const char ** argv)263 upper_utf8Func(sqlite_func *context, int argc, const char **argv)
264 {
265 	char *upper = NULL;
266 
267 	/*
268 	 * SQLite functions can take many arguments, but this function
269 	 * uses only one, and we call sqlite_create_function() with
270 	 * nArg == 1.
271 	 */
272 	assert(argc <= 1);
273 
274 	if (argv[0] != NULL)
275 		upper = utf8textprep(argv[0], U8_TEXTPREP_TOUPPER);
276 
277 	(void) sqlite_set_result_string(context, upper, -1);
278 	free(upper);
279 }
280 
281 /*
282 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
283 ** All three do the same thing.  They return the first non-NULL
284 ** argument.
285 */
ifnullFunc(sqlite_func * context,int argc,const char ** argv)286 static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
287   int i;
288   for(i=0; i<argc; i++){
289     if( argv[i] ){
290       sqlite_set_result_string(context, argv[i], -1);
291       break;
292     }
293   }
294 }
295 
296 /*
297 ** Implementation of random().  Return a random integer.
298 */
randomFunc(sqlite_func * context,int argc,const char ** argv)299 static void randomFunc(sqlite_func *context, int argc, const char **argv){
300   int r;
301   sqliteRandomness(sizeof(r), &r);
302   sqlite_set_result_int(context, r);
303 }
304 
305 /*
306 ** Implementation of the last_insert_rowid() SQL function.  The return
307 ** value is the same as the sqlite_last_insert_rowid() API function.
308 */
last_insert_rowid(sqlite_func * context,int arg,const char ** argv)309 static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
310   sqlite *db = sqlite_user_data(context);
311   sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
312 }
313 
314 /*
315 ** Implementation of the change_count() SQL function.  The return
316 ** value is the same as the sqlite_changes() API function.
317 */
change_count(sqlite_func * context,int arg,const char ** argv)318 static void change_count(sqlite_func *context, int arg, const char **argv){
319   sqlite *db = sqlite_user_data(context);
320   sqlite_set_result_int(context, sqlite_changes(db));
321 }
322 
323 /*
324 ** Implementation of the last_statement_change_count() SQL function.  The
325 ** return value is the same as the sqlite_last_statement_changes() API function.
326 */
last_statement_change_count(sqlite_func * context,int arg,const char ** argv)327 static void last_statement_change_count(sqlite_func *context, int arg,
328                                         const char **argv){
329   sqlite *db = sqlite_user_data(context);
330   sqlite_set_result_int(context, sqlite_last_statement_changes(db));
331 }
332 
333 /*
334 ** Implementation of the like() SQL function.  This function implements
335 ** the build-in LIKE operator.  The first argument to the function is the
336 ** string and the second argument is the pattern.  So, the SQL statements:
337 **
338 **       A LIKE B
339 **
340 ** is implemented as like(A,B).
341 */
likeFunc(sqlite_func * context,int arg,const char ** argv)342 static void likeFunc(sqlite_func *context, int arg, const char **argv){
343   if( argv[0]==0 || argv[1]==0 ) return;
344   sqlite_set_result_int(context,
345     sqliteLikeCompare((const unsigned char*)argv[0],
346                       (const unsigned char*)argv[1]));
347 }
348 
349 /*
350 ** Implementation of the glob() SQL function.  This function implements
351 ** the build-in GLOB operator.  The first argument to the function is the
352 ** string and the second argument is the pattern.  So, the SQL statements:
353 **
354 **       A GLOB B
355 **
356 ** is implemented as glob(A,B).
357 */
globFunc(sqlite_func * context,int arg,const char ** argv)358 static void globFunc(sqlite_func *context, int arg, const char **argv){
359   if( argv[0]==0 || argv[1]==0 ) return;
360   sqlite_set_result_int(context,
361     sqliteGlobCompare((const unsigned char*)argv[0],
362                       (const unsigned char*)argv[1]));
363 }
364 
365 /*
366 ** Implementation of the NULLIF(x,y) function.  The result is the first
367 ** argument if the arguments are different.  The result is NULL if the
368 ** arguments are equal to each other.
369 */
nullifFunc(sqlite_func * context,int argc,const char ** argv)370 static void nullifFunc(sqlite_func *context, int argc, const char **argv){
371   if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
372     sqlite_set_result_string(context, argv[0], -1);
373   }
374 }
375 
376 /*
377 ** Implementation of the VERSION(*) function.  The result is the version
378 ** of the SQLite library that is running.
379 */
versionFunc(sqlite_func * context,int argc,const char ** argv)380 static void versionFunc(sqlite_func *context, int argc, const char **argv){
381   sqlite_set_result_string(context, sqlite_version, -1);
382 }
383 
384 /*
385 ** EXPERIMENTAL - This is not an official function.  The interface may
386 ** change.  This function may disappear.  Do not write code that depends
387 ** on this function.
388 **
389 ** Implementation of the QUOTE() function.  This function takes a single
390 ** argument.  If the argument is numeric, the return value is the same as
391 ** the argument.  If the argument is NULL, the return value is the string
392 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
393 ** single-quote escapes.
394 */
quoteFunc(sqlite_func * context,int argc,const char ** argv)395 static void quoteFunc(sqlite_func *context, int argc, const char **argv){
396   if( argc<1 ) return;
397   if( argv[0]==0 ){
398     sqlite_set_result_string(context, "NULL", 4);
399   }else if( sqliteIsNumber(argv[0]) ){
400     sqlite_set_result_string(context, argv[0], -1);
401   }else{
402     int i,j,n;
403     char *z;
404     for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
405     z = sqliteMalloc( i+n+3 );
406     if( z==0 ) return;
407     z[0] = '\'';
408     for(i=0, j=1; argv[0][i]; i++){
409       z[j++] = argv[0][i];
410       if( argv[0][i]=='\'' ){
411         z[j++] = '\'';
412       }
413     }
414     z[j++] = '\'';
415     z[j] = 0;
416     sqlite_set_result_string(context, z, j);
417     sqliteFree(z);
418   }
419 }
420 
421 #ifdef SQLITE_SOUNDEX
422 /*
423 ** Compute the soundex encoding of a word.
424 */
soundexFunc(sqlite_func * context,int argc,const char ** argv)425 static void soundexFunc(sqlite_func *context, int argc, const char **argv){
426   char zResult[8];
427   const char *zIn;
428   int i, j;
429   static const unsigned char iCode[] = {
430     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
431     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
432     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
433     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
434     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
435     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
436     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
437     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
438   };
439   assert( argc==1 );
440   zIn = argv[0];
441   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
442   if( zIn[i] ){
443     zResult[0] = toupper(zIn[i]);
444     for(j=1; j<4 && zIn[i]; i++){
445       int code = iCode[zIn[i]&0x7f];
446       if( code>0 ){
447         zResult[j++] = code + '0';
448       }
449     }
450     while( j<4 ){
451       zResult[j++] = '0';
452     }
453     zResult[j] = 0;
454     sqlite_set_result_string(context, zResult, 4);
455   }else{
456     sqlite_set_result_string(context, "?000", 4);
457   }
458 }
459 #endif
460 
461 #ifdef SQLITE_TEST
462 /*
463 ** This function generates a string of random characters.  Used for
464 ** generating test data.
465 */
randStr(sqlite_func * context,int argc,const char ** argv)466 static void randStr(sqlite_func *context, int argc, const char **argv){
467   static const unsigned char zSrc[] =
468      "abcdefghijklmnopqrstuvwxyz"
469      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
470      "0123456789"
471      ".-!,:*^+=_|?/<> ";
472   int iMin, iMax, n, r, i;
473   unsigned char zBuf[1000];
474   if( argc>=1 ){
475     iMin = atoi(argv[0]);
476     if( iMin<0 ) iMin = 0;
477     if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
478   }else{
479     iMin = 1;
480   }
481   if( argc>=2 ){
482     iMax = atoi(argv[1]);
483     if( iMax<iMin ) iMax = iMin;
484     if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
485   }else{
486     iMax = 50;
487   }
488   n = iMin;
489   if( iMax>iMin ){
490     sqliteRandomness(sizeof(r), &r);
491     r &= 0x7fffffff;
492     n += r%(iMax + 1 - iMin);
493   }
494   assert( n<sizeof(zBuf) );
495   sqliteRandomness(n, zBuf);
496   for(i=0; i<n; i++){
497     zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
498   }
499   zBuf[n] = 0;
500   sqlite_set_result_string(context, zBuf, n);
501 }
502 #endif
503 
504 /*
505 ** An instance of the following structure holds the context of a
506 ** sum() or avg() aggregate computation.
507 */
508 typedef struct SumCtx SumCtx;
509 struct SumCtx {
510   double sum;     /* Sum of terms */
511   int cnt;        /* Number of elements summed */
512 };
513 
514 /*
515 ** Routines used to compute the sum or average.
516 */
sumStep(sqlite_func * context,int argc,const char ** argv)517 static void sumStep(sqlite_func *context, int argc, const char **argv){
518   SumCtx *p;
519   if( argc<1 ) return;
520   p = sqlite_aggregate_context(context, sizeof(*p));
521   if( p && argv[0] ){
522     p->sum += sqliteAtoF(argv[0], 0);
523     p->cnt++;
524   }
525 }
sumFinalize(sqlite_func * context)526 static void sumFinalize(sqlite_func *context){
527   SumCtx *p;
528   p = sqlite_aggregate_context(context, sizeof(*p));
529   sqlite_set_result_double(context, p ? p->sum : 0.0);
530 }
avgFinalize(sqlite_func * context)531 static void avgFinalize(sqlite_func *context){
532   SumCtx *p;
533   p = sqlite_aggregate_context(context, sizeof(*p));
534   if( p && p->cnt>0 ){
535     sqlite_set_result_double(context, p->sum/(double)p->cnt);
536   }
537 }
538 
539 /*
540 ** An instance of the following structure holds the context of a
541 ** variance or standard deviation computation.
542 */
543 typedef struct StdDevCtx StdDevCtx;
544 struct StdDevCtx {
545   double sum;     /* Sum of terms */
546   double sum2;    /* Sum of the squares of terms */
547   int cnt;        /* Number of terms counted */
548 };
549 
550 #if 0   /* Omit because math library is required */
551 /*
552 ** Routines used to compute the standard deviation as an aggregate.
553 */
554 static void stdDevStep(sqlite_func *context, int argc, const char **argv){
555   StdDevCtx *p;
556   double x;
557   if( argc<1 ) return;
558   p = sqlite_aggregate_context(context, sizeof(*p));
559   if( p && argv[0] ){
560     x = sqliteAtoF(argv[0], 0);
561     p->sum += x;
562     p->sum2 += x*x;
563     p->cnt++;
564   }
565 }
566 static void stdDevFinalize(sqlite_func *context){
567   double rN = sqlite_aggregate_count(context);
568   StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
569   if( p && p->cnt>1 ){
570     double rCnt = cnt;
571     sqlite_set_result_double(context,
572        sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
573   }
574 }
575 #endif
576 
577 /*
578 ** The following structure keeps track of state information for the
579 ** count() aggregate function.
580 */
581 typedef struct CountCtx CountCtx;
582 struct CountCtx {
583   int n;
584 };
585 
586 /*
587 ** Routines to implement the count() aggregate function.
588 */
countStep(sqlite_func * context,int argc,const char ** argv)589 static void countStep(sqlite_func *context, int argc, const char **argv){
590   CountCtx *p;
591   p = sqlite_aggregate_context(context, sizeof(*p));
592   if( (argc==0 || argv[0]) && p ){
593     p->n++;
594   }
595 }
countFinalize(sqlite_func * context)596 static void countFinalize(sqlite_func *context){
597   CountCtx *p;
598   p = sqlite_aggregate_context(context, sizeof(*p));
599   sqlite_set_result_int(context, p ? p->n : 0);
600 }
601 
602 /*
603 ** This function tracks state information for the min() and max()
604 ** aggregate functions.
605 */
606 typedef struct MinMaxCtx MinMaxCtx;
607 struct MinMaxCtx {
608   char *z;         /* The best so far */
609   char zBuf[28];   /* Space that can be used for storage */
610 };
611 
612 /*
613 ** Routines to implement min() and max() aggregate functions.
614 */
minmaxStep(sqlite_func * context,int argc,const char ** argv)615 static void minmaxStep(sqlite_func *context, int argc, const char **argv){
616   MinMaxCtx *p;
617   int (*xCompare)(const char*, const char*);
618   int mask;    /* 0 for min() or 0xffffffff for max() */
619 
620   assert( argc==2 );
621   if( argv[0]==0 ) return;  /* Ignore NULL values */
622   if( argv[1][0]=='n' ){
623     xCompare = sqliteCompare;
624   }else{
625     xCompare = strcmp;
626   }
627   mask = (int)sqlite_user_data(context);
628   assert( mask==0 || mask==-1 );
629   p = sqlite_aggregate_context(context, sizeof(*p));
630   if( p==0 || argc<1 ) return;
631   if( p->z==0 || (xCompare(argv[0],p->z)^mask)<0 ){
632     int len;
633     if( p->zBuf[0] ){
634       sqliteFree(p->z);
635     }
636     len = strlen(argv[0]);
637     if( len < sizeof(p->zBuf)-1 ){
638       p->z = &p->zBuf[1];
639       p->zBuf[0] = 0;
640     }else{
641       p->z = sqliteMalloc( len+1 );
642       p->zBuf[0] = 1;
643       if( p->z==0 ) return;
644     }
645     strcpy(p->z, argv[0]);
646   }
647 }
minMaxFinalize(sqlite_func * context)648 static void minMaxFinalize(sqlite_func *context){
649   MinMaxCtx *p;
650   p = sqlite_aggregate_context(context, sizeof(*p));
651   if( p && p->z && p->zBuf[0]<2 ){
652     sqlite_set_result_string(context, p->z, strlen(p->z));
653   }
654   if( p && p->zBuf[0] ){
655     sqliteFree(p->z);
656   }
657 }
658 
659 /*
660 ** This function registered all of the above C functions as SQL
661 ** functions.  This should be the only routine in this file with
662 ** external linkage.
663 */
sqliteRegisterBuiltinFunctions(sqlite * db)664 void sqliteRegisterBuiltinFunctions(sqlite *db){
665   static struct {
666      char *zName;
667      signed char nArg;
668      signed char dataType;
669      u8 argType;               /* 0: none.  1: db  2: (-1) */
670      void (*xFunc)(sqlite_func*,int,const char**);
671   } aFuncs[] = {
672     { "min",       -1, SQLITE_ARGS,    0, minmaxFunc      },
673     { "min",        0, 0,              0, 0               },
674     { "max",       -1, SQLITE_ARGS,    2, minmaxFunc      },
675     { "max",        0, 0,              2, 0               },
676     { "typeof",     1, SQLITE_TEXT,    0, typeofFunc      },
677     { "length",     1, SQLITE_NUMERIC, 0, lengthFunc      },
678     { "substr",     3, SQLITE_TEXT,    0, substrFunc      },
679     { "abs",        1, SQLITE_NUMERIC, 0, absFunc         },
680     { "round",      1, SQLITE_NUMERIC, 0, roundFunc       },
681     { "round",      2, SQLITE_NUMERIC, 0, roundFunc       },
682     { "upper",      1, SQLITE_TEXT,    0, upperFunc       },
683     { "lower",      1, SQLITE_TEXT,    0, lowerFunc       },
684     { "lower_utf8", 1, SQLITE_TEXT,    0, lower_utf8Func  },
685     { "upper_utf8", 1, SQLITE_TEXT,    0, upper_utf8Func  },
686     { "coalesce",  -1, SQLITE_ARGS,    0, ifnullFunc      },
687     { "coalesce",   0, 0,              0, 0               },
688     { "coalesce",   1, 0,              0, 0               },
689     { "ifnull",     2, SQLITE_ARGS,    0, ifnullFunc      },
690     { "random",    -1, SQLITE_NUMERIC, 0, randomFunc      },
691     { "like",       2, SQLITE_NUMERIC, 0, likeFunc        },
692     { "glob",       2, SQLITE_NUMERIC, 0, globFunc        },
693     { "nullif",     2, SQLITE_ARGS,    0, nullifFunc      },
694     { "sqlite_version",0,SQLITE_TEXT,  0, versionFunc     },
695     { "quote",      1, SQLITE_ARGS,    0, quoteFunc       },
696     { "last_insert_rowid", 0, SQLITE_NUMERIC, 1, last_insert_rowid },
697     { "change_count",      0, SQLITE_NUMERIC, 1, change_count      },
698     { "last_statement_change_count",
699                            0, SQLITE_NUMERIC, 1, last_statement_change_count },
700 #ifdef SQLITE_SOUNDEX
701     { "soundex",    1, SQLITE_TEXT,    0, soundexFunc},
702 #endif
703 #ifdef SQLITE_TEST
704     { "randstr",    2, SQLITE_TEXT,    0, randStr    },
705 #endif
706   };
707   static struct {
708     char *zName;
709     signed char nArg;
710     signed char dataType;
711     u8 argType;
712     void (*xStep)(sqlite_func*,int,const char**);
713     void (*xFinalize)(sqlite_func*);
714   } aAggs[] = {
715     { "min",    1, 0,              0, minmaxStep,   minMaxFinalize },
716     { "max",    1, 0,              2, minmaxStep,   minMaxFinalize },
717     { "sum",    1, SQLITE_NUMERIC, 0, sumStep,      sumFinalize    },
718     { "avg",    1, SQLITE_NUMERIC, 0, sumStep,      avgFinalize    },
719     { "count",  0, SQLITE_NUMERIC, 0, countStep,    countFinalize  },
720     { "count",  1, SQLITE_NUMERIC, 0, countStep,    countFinalize  },
721 #if 0
722     { "stddev", 1, SQLITE_NUMERIC, 0, stdDevStep,   stdDevFinalize },
723 #endif
724   };
725   static const char *azTypeFuncs[] = { "min", "max", "typeof" };
726   int i;
727 
728   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
729     void *pArg;
730     switch( aFuncs[i].argType ){
731       case 0:  pArg = 0;           break;
732       case 1:  pArg = db;          break;
733       case 2:  pArg = (void*)(-1); break;
734     }
735     sqlite_create_function(db, aFuncs[i].zName,
736            aFuncs[i].nArg, aFuncs[i].xFunc, pArg);
737     if( aFuncs[i].xFunc ){
738       sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
739     }
740   }
741   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
742     void *pArg;
743     switch( aAggs[i].argType ){
744       case 0:  pArg = 0;           break;
745       case 1:  pArg = db;          break;
746       case 2:  pArg = (void*)(-1); break;
747     }
748     sqlite_create_aggregate(db, aAggs[i].zName,
749            aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, pArg);
750     sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
751   }
752   for(i=0; i<sizeof(azTypeFuncs)/sizeof(azTypeFuncs[0]); i++){
753     int n = strlen(azTypeFuncs[i]);
754     FuncDef *p = sqliteHashFind(&db->aFunc, azTypeFuncs[i], n);
755     while( p ){
756       p->includeTypes = 1;
757       p = p->pNext;
758     }
759   }
760   sqliteRegisterDateTimeFunctions(db);
761 }
762