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