comparison sqlite/func.c @ 1434:b6b61becdf4e trunk

[svn] - add sqlite/ directory
author nenolod
date Thu, 27 Jul 2006 22:41:31 -0700
parents
children
comparison
equal deleted inserted replaced
1433:3cbe3d14ea68 1434:b6b61becdf4e
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.128 2006/05/11 13:25:39 drh Exp $
20 */
21 #include "sqliteInt.h"
22 #include <ctype.h>
23 /* #include <math.h> */
24 #include <stdlib.h>
25 #include <assert.h>
26 #include "vdbeInt.h"
27 #include "os.h"
28
29 /*
30 ** Return the collating function associated with a function.
31 */
32 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
33 return context->pColl;
34 }
35
36 /*
37 ** Implementation of the non-aggregate min() and max() functions
38 */
39 static void minmaxFunc(
40 sqlite3_context *context,
41 int argc,
42 sqlite3_value **argv
43 ){
44 int i;
45 int mask; /* 0 for min() or 0xffffffff for max() */
46 int iBest;
47 CollSeq *pColl;
48
49 if( argc==0 ) return;
50 mask = sqlite3_user_data(context)==0 ? 0 : -1;
51 pColl = sqlite3GetFuncCollSeq(context);
52 assert( pColl );
53 assert( mask==-1 || mask==0 );
54 iBest = 0;
55 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
56 for(i=1; i<argc; i++){
57 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
58 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
59 iBest = i;
60 }
61 }
62 sqlite3_result_value(context, argv[iBest]);
63 }
64
65 /*
66 ** Return the type of the argument.
67 */
68 static void typeofFunc(
69 sqlite3_context *context,
70 int argc,
71 sqlite3_value **argv
72 ){
73 const char *z = 0;
74 switch( sqlite3_value_type(argv[0]) ){
75 case SQLITE_NULL: z = "null"; break;
76 case SQLITE_INTEGER: z = "integer"; break;
77 case SQLITE_TEXT: z = "text"; break;
78 case SQLITE_FLOAT: z = "real"; break;
79 case SQLITE_BLOB: z = "blob"; break;
80 }
81 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
82 }
83
84
85 /*
86 ** Implementation of the length() function
87 */
88 static void lengthFunc(
89 sqlite3_context *context,
90 int argc,
91 sqlite3_value **argv
92 ){
93 int len;
94
95 assert( argc==1 );
96 switch( sqlite3_value_type(argv[0]) ){
97 case SQLITE_BLOB:
98 case SQLITE_INTEGER:
99 case SQLITE_FLOAT: {
100 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
101 break;
102 }
103 case SQLITE_TEXT: {
104 const unsigned char *z = sqlite3_value_text(argv[0]);
105 for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
106 sqlite3_result_int(context, len);
107 break;
108 }
109 default: {
110 sqlite3_result_null(context);
111 break;
112 }
113 }
114 }
115
116 /*
117 ** Implementation of the abs() function
118 */
119 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
120 assert( argc==1 );
121 switch( sqlite3_value_type(argv[0]) ){
122 case SQLITE_INTEGER: {
123 i64 iVal = sqlite3_value_int64(argv[0]);
124 if( iVal<0 ){
125 if( (iVal<<1)==0 ){
126 sqlite3_result_error(context, "integer overflow", -1);
127 return;
128 }
129 iVal = -iVal;
130 }
131 sqlite3_result_int64(context, iVal);
132 break;
133 }
134 case SQLITE_NULL: {
135 sqlite3_result_null(context);
136 break;
137 }
138 default: {
139 double rVal = sqlite3_value_double(argv[0]);
140 if( rVal<0 ) rVal = -rVal;
141 sqlite3_result_double(context, rVal);
142 break;
143 }
144 }
145 }
146
147 /*
148 ** Implementation of the substr() function
149 */
150 static void substrFunc(
151 sqlite3_context *context,
152 int argc,
153 sqlite3_value **argv
154 ){
155 const unsigned char *z;
156 const unsigned char *z2;
157 int i;
158 int p1, p2, len;
159
160 assert( argc==3 );
161 z = sqlite3_value_text(argv[0]);
162 if( z==0 ) return;
163 p1 = sqlite3_value_int(argv[1]);
164 p2 = sqlite3_value_int(argv[2]);
165 for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
166 if( p1<0 ){
167 p1 += len;
168 if( p1<0 ){
169 p2 += p1;
170 p1 = 0;
171 }
172 }else if( p1>0 ){
173 p1--;
174 }
175 if( p1+p2>len ){
176 p2 = len-p1;
177 }
178 for(i=0; i<p1 && z[i]; i++){
179 if( (z[i]&0xc0)==0x80 ) p1++;
180 }
181 while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
182 for(; i<p1+p2 && z[i]; i++){
183 if( (z[i]&0xc0)==0x80 ) p2++;
184 }
185 while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
186 if( p2<0 ) p2 = 0;
187 sqlite3_result_text(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
188 }
189
190 /*
191 ** Implementation of the round() function
192 */
193 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
194 int n = 0;
195 double r;
196 char zBuf[500]; /* larger than the %f representation of the largest double */
197 assert( argc==1 || argc==2 );
198 if( argc==2 ){
199 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
200 n = sqlite3_value_int(argv[1]);
201 if( n>30 ) n = 30;
202 if( n<0 ) n = 0;
203 }
204 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
205 r = sqlite3_value_double(argv[0]);
206 sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
207 sqlite3AtoF(zBuf, &r);
208 sqlite3_result_double(context, r);
209 }
210
211 /*
212 ** Implementation of the upper() and lower() SQL functions.
213 */
214 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
215 unsigned char *z;
216 int i;
217 if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
218 z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
219 if( z==0 ) return;
220 strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
221 for(i=0; z[i]; i++){
222 z[i] = toupper(z[i]);
223 }
224 sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
225 sqliteFree(z);
226 }
227 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
228 unsigned char *z;
229 int i;
230 if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
231 z = sqliteMalloc(sqlite3_value_bytes(argv[0])+1);
232 if( z==0 ) return;
233 strcpy((char*)z, (char*)sqlite3_value_text(argv[0]));
234 for(i=0; z[i]; i++){
235 z[i] = tolower(z[i]);
236 }
237 sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
238 sqliteFree(z);
239 }
240
241 /*
242 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
243 ** All three do the same thing. They return the first non-NULL
244 ** argument.
245 */
246 static void ifnullFunc(
247 sqlite3_context *context,
248 int argc,
249 sqlite3_value **argv
250 ){
251 int i;
252 for(i=0; i<argc; i++){
253 if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
254 sqlite3_result_value(context, argv[i]);
255 break;
256 }
257 }
258 }
259
260 /*
261 ** Implementation of random(). Return a random integer.
262 */
263 static void randomFunc(
264 sqlite3_context *context,
265 int argc,
266 sqlite3_value **argv
267 ){
268 sqlite_int64 r;
269 sqlite3Randomness(sizeof(r), &r);
270 if( (r<<1)==0 ) r = 0; /* Prevent 0x8000.... as the result so that we */
271 /* can always do abs() of the result */
272 sqlite3_result_int64(context, r);
273 }
274
275 /*
276 ** Implementation of the last_insert_rowid() SQL function. The return
277 ** value is the same as the sqlite3_last_insert_rowid() API function.
278 */
279 static void last_insert_rowid(
280 sqlite3_context *context,
281 int arg,
282 sqlite3_value **argv
283 ){
284 sqlite3 *db = sqlite3_user_data(context);
285 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
286 }
287
288 /*
289 ** Implementation of the changes() SQL function. The return value is the
290 ** same as the sqlite3_changes() API function.
291 */
292 static void changes(
293 sqlite3_context *context,
294 int arg,
295 sqlite3_value **argv
296 ){
297 sqlite3 *db = sqlite3_user_data(context);
298 sqlite3_result_int(context, sqlite3_changes(db));
299 }
300
301 /*
302 ** Implementation of the total_changes() SQL function. The return value is
303 ** the same as the sqlite3_total_changes() API function.
304 */
305 static void total_changes(
306 sqlite3_context *context,
307 int arg,
308 sqlite3_value **argv
309 ){
310 sqlite3 *db = sqlite3_user_data(context);
311 sqlite3_result_int(context, sqlite3_total_changes(db));
312 }
313
314 /*
315 ** A structure defining how to do GLOB-style comparisons.
316 */
317 struct compareInfo {
318 u8 matchAll;
319 u8 matchOne;
320 u8 matchSet;
321 u8 noCase;
322 };
323
324 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
325 /* The correct SQL-92 behavior is for the LIKE operator to ignore
326 ** case. Thus 'a' LIKE 'A' would be true. */
327 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
328 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
329 ** is case sensitive causing 'a' LIKE 'A' to be false */
330 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
331
332 /*
333 ** X is a pointer to the first byte of a UTF-8 character. Increment
334 ** X so that it points to the next character. This only works right
335 ** if X points to a well-formed UTF-8 string.
336 */
337 #define sqliteNextChar(X) while( (0xc0&*++(X))==0x80 ){}
338 #define sqliteCharVal(X) sqlite3ReadUtf8(X)
339
340
341 /*
342 ** Compare two UTF-8 strings for equality where the first string can
343 ** potentially be a "glob" expression. Return true (1) if they
344 ** are the same and false (0) if they are different.
345 **
346 ** Globbing rules:
347 **
348 ** '*' Matches any sequence of zero or more characters.
349 **
350 ** '?' Matches exactly one character.
351 **
352 ** [...] Matches one character from the enclosed list of
353 ** characters.
354 **
355 ** [^...] Matches one character not in the enclosed list.
356 **
357 ** With the [...] and [^...] matching, a ']' character can be included
358 ** in the list by making it the first character after '[' or '^'. A
359 ** range of characters can be specified using '-'. Example:
360 ** "[a-z]" matches any single lower-case letter. To match a '-', make
361 ** it the last character in the list.
362 **
363 ** This routine is usually quick, but can be N**2 in the worst case.
364 **
365 ** Hints: to match '*' or '?', put them in "[]". Like this:
366 **
367 ** abc[*]xyz Matches "abc*xyz" only
368 */
369 static int patternCompare(
370 const u8 *zPattern, /* The glob pattern */
371 const u8 *zString, /* The string to compare against the glob */
372 const struct compareInfo *pInfo, /* Information about how to do the compare */
373 const int esc /* The escape character */
374 ){
375 register int c;
376 int invert;
377 int seen;
378 int c2;
379 u8 matchOne = pInfo->matchOne;
380 u8 matchAll = pInfo->matchAll;
381 u8 matchSet = pInfo->matchSet;
382 u8 noCase = pInfo->noCase;
383 int prevEscape = 0; /* True if the previous character was 'escape' */
384
385 while( (c = *zPattern)!=0 ){
386 if( !prevEscape && c==matchAll ){
387 while( (c=zPattern[1]) == matchAll || c == matchOne ){
388 if( c==matchOne ){
389 if( *zString==0 ) return 0;
390 sqliteNextChar(zString);
391 }
392 zPattern++;
393 }
394 if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
395 u8 const *zTemp = &zPattern[1];
396 sqliteNextChar(zTemp);
397 c = *zTemp;
398 }
399 if( c==0 ) return 1;
400 if( c==matchSet ){
401 assert( esc==0 ); /* This is GLOB, not LIKE */
402 while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
403 sqliteNextChar(zString);
404 }
405 return *zString!=0;
406 }else{
407 while( (c2 = *zString)!=0 ){
408 if( noCase ){
409 c2 = sqlite3UpperToLower[c2];
410 c = sqlite3UpperToLower[c];
411 while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
412 }else{
413 while( c2 != 0 && c2 != c ){ c2 = *++zString; }
414 }
415 if( c2==0 ) return 0;
416 if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
417 sqliteNextChar(zString);
418 }
419 return 0;
420 }
421 }else if( !prevEscape && c==matchOne ){
422 if( *zString==0 ) return 0;
423 sqliteNextChar(zString);
424 zPattern++;
425 }else if( c==matchSet ){
426 int prior_c = 0;
427 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
428 seen = 0;
429 invert = 0;
430 c = sqliteCharVal(zString);
431 if( c==0 ) return 0;
432 c2 = *++zPattern;
433 if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
434 if( c2==']' ){
435 if( c==']' ) seen = 1;
436 c2 = *++zPattern;
437 }
438 while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
439 if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
440 zPattern++;
441 c2 = sqliteCharVal(zPattern);
442 if( c>=prior_c && c<=c2 ) seen = 1;
443 prior_c = 0;
444 }else if( c==c2 ){
445 seen = 1;
446 prior_c = c2;
447 }else{
448 prior_c = c2;
449 }
450 sqliteNextChar(zPattern);
451 }
452 if( c2==0 || (seen ^ invert)==0 ) return 0;
453 sqliteNextChar(zString);
454 zPattern++;
455 }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
456 prevEscape = 1;
457 sqliteNextChar(zPattern);
458 }else{
459 if( noCase ){
460 if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
461 }else{
462 if( c != *zString ) return 0;
463 }
464 zPattern++;
465 zString++;
466 prevEscape = 0;
467 }
468 }
469 return *zString==0;
470 }
471
472 /*
473 ** Count the number of times that the LIKE operator (or GLOB which is
474 ** just a variation of LIKE) gets called. This is used for testing
475 ** only.
476 */
477 #ifdef SQLITE_TEST
478 int sqlite3_like_count = 0;
479 #endif
480
481
482 /*
483 ** Implementation of the like() SQL function. This function implements
484 ** the build-in LIKE operator. The first argument to the function is the
485 ** pattern and the second argument is the string. So, the SQL statements:
486 **
487 ** A LIKE B
488 **
489 ** is implemented as like(B,A).
490 **
491 ** This same function (with a different compareInfo structure) computes
492 ** the GLOB operator.
493 */
494 static void likeFunc(
495 sqlite3_context *context,
496 int argc,
497 sqlite3_value **argv
498 ){
499 const unsigned char *zA = sqlite3_value_text(argv[0]);
500 const unsigned char *zB = sqlite3_value_text(argv[1]);
501 int escape = 0;
502 if( argc==3 ){
503 /* The escape character string must consist of a single UTF-8 character.
504 ** Otherwise, return an error.
505 */
506 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
507 if( sqlite3utf8CharLen((char*)zEsc, -1)!=1 ){
508 sqlite3_result_error(context,
509 "ESCAPE expression must be a single character", -1);
510 return;
511 }
512 escape = sqlite3ReadUtf8(zEsc);
513 }
514 if( zA && zB ){
515 struct compareInfo *pInfo = sqlite3_user_data(context);
516 #ifdef SQLITE_TEST
517 sqlite3_like_count++;
518 #endif
519 sqlite3_result_int(context, patternCompare(zA, zB, pInfo, escape));
520 }
521 }
522
523 /*
524 ** Implementation of the NULLIF(x,y) function. The result is the first
525 ** argument if the arguments are different. The result is NULL if the
526 ** arguments are equal to each other.
527 */
528 static void nullifFunc(
529 sqlite3_context *context,
530 int argc,
531 sqlite3_value **argv
532 ){
533 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
534 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
535 sqlite3_result_value(context, argv[0]);
536 }
537 }
538
539 /*
540 ** Implementation of the VERSION(*) function. The result is the version
541 ** of the SQLite library that is running.
542 */
543 static void versionFunc(
544 sqlite3_context *context,
545 int argc,
546 sqlite3_value **argv
547 ){
548 sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
549 }
550
551
552 /*
553 ** EXPERIMENTAL - This is not an official function. The interface may
554 ** change. This function may disappear. Do not write code that depends
555 ** on this function.
556 **
557 ** Implementation of the QUOTE() function. This function takes a single
558 ** argument. If the argument is numeric, the return value is the same as
559 ** the argument. If the argument is NULL, the return value is the string
560 ** "NULL". Otherwise, the argument is enclosed in single quotes with
561 ** single-quote escapes.
562 */
563 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
564 if( argc<1 ) return;
565 switch( sqlite3_value_type(argv[0]) ){
566 case SQLITE_NULL: {
567 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
568 break;
569 }
570 case SQLITE_INTEGER:
571 case SQLITE_FLOAT: {
572 sqlite3_result_value(context, argv[0]);
573 break;
574 }
575 case SQLITE_BLOB: {
576 static const char hexdigits[] = {
577 '0', '1', '2', '3', '4', '5', '6', '7',
578 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
579 };
580 char *zText = 0;
581 int nBlob = sqlite3_value_bytes(argv[0]);
582 char const *zBlob = sqlite3_value_blob(argv[0]);
583
584 zText = (char *)sqliteMalloc((2*nBlob)+4);
585 if( !zText ){
586 sqlite3_result_error(context, "out of memory", -1);
587 }else{
588 int i;
589 for(i=0; i<nBlob; i++){
590 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
591 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
592 }
593 zText[(nBlob*2)+2] = '\'';
594 zText[(nBlob*2)+3] = '\0';
595 zText[0] = 'X';
596 zText[1] = '\'';
597 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
598 sqliteFree(zText);
599 }
600 break;
601 }
602 case SQLITE_TEXT: {
603 int i,j,n;
604 const unsigned char *zArg = sqlite3_value_text(argv[0]);
605 char *z;
606
607 for(i=n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
608 z = sqliteMalloc( i+n+3 );
609 if( z==0 ) return;
610 z[0] = '\'';
611 for(i=0, j=1; zArg[i]; i++){
612 z[j++] = zArg[i];
613 if( zArg[i]=='\'' ){
614 z[j++] = '\'';
615 }
616 }
617 z[j++] = '\'';
618 z[j] = 0;
619 sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
620 sqliteFree(z);
621 }
622 }
623 }
624
625 #ifdef SQLITE_SOUNDEX
626 /*
627 ** Compute the soundex encoding of a word.
628 */
629 static void soundexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
630 char zResult[8];
631 const u8 *zIn;
632 int i, j;
633 static const unsigned char iCode[] = {
634 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
635 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
636 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
637 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
638 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
639 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
640 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
641 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
642 };
643 assert( argc==1 );
644 zIn = (u8*)sqlite3_value_text(argv[0]);
645 for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
646 if( zIn[i] ){
647 zResult[0] = toupper(zIn[i]);
648 for(j=1; j<4 && zIn[i]; i++){
649 int code = iCode[zIn[i]&0x7f];
650 if( code>0 ){
651 zResult[j++] = code + '0';
652 }
653 }
654 while( j<4 ){
655 zResult[j++] = '0';
656 }
657 zResult[j] = 0;
658 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
659 }else{
660 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
661 }
662 }
663 #endif
664
665 #ifdef SQLITE_TEST
666 /*
667 ** This function generates a string of random characters. Used for
668 ** generating test data.
669 */
670 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
671 static const unsigned char zSrc[] =
672 "abcdefghijklmnopqrstuvwxyz"
673 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
674 "0123456789"
675 ".-!,:*^+=_|?/<> ";
676 int iMin, iMax, n, r, i;
677 unsigned char zBuf[1000];
678 if( argc>=1 ){
679 iMin = sqlite3_value_int(argv[0]);
680 if( iMin<0 ) iMin = 0;
681 if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
682 }else{
683 iMin = 1;
684 }
685 if( argc>=2 ){
686 iMax = sqlite3_value_int(argv[1]);
687 if( iMax<iMin ) iMax = iMin;
688 if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
689 }else{
690 iMax = 50;
691 }
692 n = iMin;
693 if( iMax>iMin ){
694 sqlite3Randomness(sizeof(r), &r);
695 r &= 0x7fffffff;
696 n += r%(iMax + 1 - iMin);
697 }
698 assert( n<sizeof(zBuf) );
699 sqlite3Randomness(n, zBuf);
700 for(i=0; i<n; i++){
701 zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
702 }
703 zBuf[n] = 0;
704 sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
705 }
706 #endif /* SQLITE_TEST */
707
708 #ifdef SQLITE_TEST
709 /*
710 ** The following two SQL functions are used to test returning a text
711 ** result with a destructor. Function 'test_destructor' takes one argument
712 ** and returns the same argument interpreted as TEXT. A destructor is
713 ** passed with the sqlite3_result_text() call.
714 **
715 ** SQL function 'test_destructor_count' returns the number of outstanding
716 ** allocations made by 'test_destructor';
717 **
718 ** WARNING: Not threadsafe.
719 */
720 static int test_destructor_count_var = 0;
721 static void destructor(void *p){
722 char *zVal = (char *)p;
723 assert(zVal);
724 zVal--;
725 sqliteFree(zVal);
726 test_destructor_count_var--;
727 }
728 static void test_destructor(
729 sqlite3_context *pCtx,
730 int nArg,
731 sqlite3_value **argv
732 ){
733 char *zVal;
734 int len;
735 sqlite3 *db = sqlite3_user_data(pCtx);
736
737 test_destructor_count_var++;
738 assert( nArg==1 );
739 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
740 len = sqlite3ValueBytes(argv[0], ENC(db));
741 zVal = sqliteMalloc(len+3);
742 zVal[len] = 0;
743 zVal[len-1] = 0;
744 assert( zVal );
745 zVal++;
746 memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
747 if( ENC(db)==SQLITE_UTF8 ){
748 sqlite3_result_text(pCtx, zVal, -1, destructor);
749 #ifndef SQLITE_OMIT_UTF16
750 }else if( ENC(db)==SQLITE_UTF16LE ){
751 sqlite3_result_text16le(pCtx, zVal, -1, destructor);
752 }else{
753 sqlite3_result_text16be(pCtx, zVal, -1, destructor);
754 #endif /* SQLITE_OMIT_UTF16 */
755 }
756 }
757 static void test_destructor_count(
758 sqlite3_context *pCtx,
759 int nArg,
760 sqlite3_value **argv
761 ){
762 sqlite3_result_int(pCtx, test_destructor_count_var);
763 }
764 #endif /* SQLITE_TEST */
765
766 #ifdef SQLITE_TEST
767 /*
768 ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
769 ** interface.
770 **
771 ** The test_auxdata() SQL function attempts to register each of its arguments
772 ** as auxiliary data. If there are no prior registrations of aux data for
773 ** that argument (meaning the argument is not a constant or this is its first
774 ** call) then the result for that argument is 0. If there is a prior
775 ** registration, the result for that argument is 1. The overall result
776 ** is the individual argument results separated by spaces.
777 */
778 static void free_test_auxdata(void *p) {sqliteFree(p);}
779 static void test_auxdata(
780 sqlite3_context *pCtx,
781 int nArg,
782 sqlite3_value **argv
783 ){
784 int i;
785 char *zRet = sqliteMalloc(nArg*2);
786 if( !zRet ) return;
787 for(i=0; i<nArg; i++){
788 char const *z = (char*)sqlite3_value_text(argv[i]);
789 if( z ){
790 char *zAux = sqlite3_get_auxdata(pCtx, i);
791 if( zAux ){
792 zRet[i*2] = '1';
793 if( strcmp(zAux, z) ){
794 sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
795 return;
796 }
797 }else{
798 zRet[i*2] = '0';
799 zAux = sqliteStrDup(z);
800 sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
801 }
802 zRet[i*2+1] = ' ';
803 }
804 }
805 sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
806 }
807 #endif /* SQLITE_TEST */
808
809 #ifdef SQLITE_TEST
810 /*
811 ** A function to test error reporting from user functions. This function
812 ** returns a copy of it's first argument as an error.
813 */
814 static void test_error(
815 sqlite3_context *pCtx,
816 int nArg,
817 sqlite3_value **argv
818 ){
819 sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
820 }
821 #endif /* SQLITE_TEST */
822
823 /*
824 ** An instance of the following structure holds the context of a
825 ** sum() or avg() aggregate computation.
826 */
827 typedef struct SumCtx SumCtx;
828 struct SumCtx {
829 double rSum; /* Floating point sum */
830 i64 iSum; /* Integer sum */
831 i64 cnt; /* Number of elements summed */
832 u8 overflow; /* True if integer overflow seen */
833 u8 approx; /* True if non-integer value was input to the sum */
834 };
835
836 /*
837 ** Routines used to compute the sum, average, and total.
838 **
839 ** The SUM() function follows the (broken) SQL standard which means
840 ** that it returns NULL if it sums over no inputs. TOTAL returns
841 ** 0.0 in that case. In addition, TOTAL always returns a float where
842 ** SUM might return an integer if it never encounters a floating point
843 ** value. TOTAL never fails, but SUM might through an exception if
844 ** it overflows an integer.
845 */
846 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
847 SumCtx *p;
848 int type;
849 assert( argc==1 );
850 p = sqlite3_aggregate_context(context, sizeof(*p));
851 type = sqlite3_value_numeric_type(argv[0]);
852 if( p && type!=SQLITE_NULL ){
853 p->cnt++;
854 if( type==SQLITE_INTEGER ){
855 i64 v = sqlite3_value_int64(argv[0]);
856 p->rSum += v;
857 if( (p->approx|p->overflow)==0 ){
858 i64 iNewSum = p->iSum + v;
859 int s1 = p->iSum >> (sizeof(i64)*8-1);
860 int s2 = v >> (sizeof(i64)*8-1);
861 int s3 = iNewSum >> (sizeof(i64)*8-1);
862 p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
863 p->iSum = iNewSum;
864 }
865 }else{
866 p->rSum += sqlite3_value_double(argv[0]);
867 p->approx = 1;
868 }
869 }
870 }
871 static void sumFinalize(sqlite3_context *context){
872 SumCtx *p;
873 p = sqlite3_aggregate_context(context, 0);
874 if( p && p->cnt>0 ){
875 if( p->overflow ){
876 sqlite3_result_error(context,"integer overflow",-1);
877 }else if( p->approx ){
878 sqlite3_result_double(context, p->rSum);
879 }else{
880 sqlite3_result_int64(context, p->iSum);
881 }
882 }
883 }
884 static void avgFinalize(sqlite3_context *context){
885 SumCtx *p;
886 p = sqlite3_aggregate_context(context, 0);
887 if( p && p->cnt>0 ){
888 sqlite3_result_double(context, p->rSum/(double)p->cnt);
889 }
890 }
891 static void totalFinalize(sqlite3_context *context){
892 SumCtx *p;
893 p = sqlite3_aggregate_context(context, 0);
894 sqlite3_result_double(context, p ? p->rSum : 0.0);
895 }
896
897 /*
898 ** The following structure keeps track of state information for the
899 ** count() aggregate function.
900 */
901 typedef struct CountCtx CountCtx;
902 struct CountCtx {
903 i64 n;
904 };
905
906 /*
907 ** Routines to implement the count() aggregate function.
908 */
909 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
910 CountCtx *p;
911 p = sqlite3_aggregate_context(context, sizeof(*p));
912 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
913 p->n++;
914 }
915 }
916 static void countFinalize(sqlite3_context *context){
917 CountCtx *p;
918 p = sqlite3_aggregate_context(context, 0);
919 sqlite3_result_int64(context, p ? p->n : 0);
920 }
921
922 /*
923 ** Routines to implement min() and max() aggregate functions.
924 */
925 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
926 Mem *pArg = (Mem *)argv[0];
927 Mem *pBest;
928
929 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
930 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
931 if( !pBest ) return;
932
933 if( pBest->flags ){
934 int max;
935 int cmp;
936 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
937 /* This step function is used for both the min() and max() aggregates,
938 ** the only difference between the two being that the sense of the
939 ** comparison is inverted. For the max() aggregate, the
940 ** sqlite3_user_data() function returns (void *)-1. For min() it
941 ** returns (void *)db, where db is the sqlite3* database pointer.
942 ** Therefore the next statement sets variable 'max' to 1 for the max()
943 ** aggregate, or 0 for min().
944 */
945 max = ((sqlite3_user_data(context)==(void *)-1)?1:0);
946 cmp = sqlite3MemCompare(pBest, pArg, pColl);
947 if( (max && cmp<0) || (!max && cmp>0) ){
948 sqlite3VdbeMemCopy(pBest, pArg);
949 }
950 }else{
951 sqlite3VdbeMemCopy(pBest, pArg);
952 }
953 }
954 static void minMaxFinalize(sqlite3_context *context){
955 sqlite3_value *pRes;
956 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
957 if( pRes ){
958 if( pRes->flags ){
959 sqlite3_result_value(context, pRes);
960 }
961 sqlite3VdbeMemRelease(pRes);
962 }
963 }
964
965
966 /*
967 ** This function registered all of the above C functions as SQL
968 ** functions. This should be the only routine in this file with
969 ** external linkage.
970 */
971 void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
972 static const struct {
973 char *zName;
974 signed char nArg;
975 u8 argType; /* 0: none. 1: db 2: (-1) */
976 u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */
977 u8 needCollSeq;
978 void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
979 } aFuncs[] = {
980 { "min", -1, 0, SQLITE_UTF8, 1, minmaxFunc },
981 { "min", 0, 0, SQLITE_UTF8, 1, 0 },
982 { "max", -1, 2, SQLITE_UTF8, 1, minmaxFunc },
983 { "max", 0, 2, SQLITE_UTF8, 1, 0 },
984 { "typeof", 1, 0, SQLITE_UTF8, 0, typeofFunc },
985 { "length", 1, 0, SQLITE_UTF8, 0, lengthFunc },
986 { "substr", 3, 0, SQLITE_UTF8, 0, substrFunc },
987 #ifndef SQLITE_OMIT_UTF16
988 { "substr", 3, 0, SQLITE_UTF16LE, 0, sqlite3utf16Substr },
989 #endif
990 { "abs", 1, 0, SQLITE_UTF8, 0, absFunc },
991 { "round", 1, 0, SQLITE_UTF8, 0, roundFunc },
992 { "round", 2, 0, SQLITE_UTF8, 0, roundFunc },
993 { "upper", 1, 0, SQLITE_UTF8, 0, upperFunc },
994 { "lower", 1, 0, SQLITE_UTF8, 0, lowerFunc },
995 { "coalesce", -1, 0, SQLITE_UTF8, 0, ifnullFunc },
996 { "coalesce", 0, 0, SQLITE_UTF8, 0, 0 },
997 { "coalesce", 1, 0, SQLITE_UTF8, 0, 0 },
998 { "ifnull", 2, 0, SQLITE_UTF8, 1, ifnullFunc },
999 { "random", -1, 0, SQLITE_UTF8, 0, randomFunc },
1000 { "nullif", 2, 0, SQLITE_UTF8, 1, nullifFunc },
1001 { "sqlite_version", 0, 0, SQLITE_UTF8, 0, versionFunc},
1002 { "quote", 1, 0, SQLITE_UTF8, 0, quoteFunc },
1003 { "last_insert_rowid", 0, 1, SQLITE_UTF8, 0, last_insert_rowid },
1004 { "changes", 0, 1, SQLITE_UTF8, 0, changes },
1005 { "total_changes", 0, 1, SQLITE_UTF8, 0, total_changes },
1006 #ifdef SQLITE_SOUNDEX
1007 { "soundex", 1, 0, SQLITE_UTF8, 0, soundexFunc},
1008 #endif
1009 #ifdef SQLITE_TEST
1010 { "randstr", 2, 0, SQLITE_UTF8, 0, randStr },
1011 { "test_destructor", 1, 1, SQLITE_UTF8, 0, test_destructor},
1012 { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
1013 { "test_auxdata", -1, 0, SQLITE_UTF8, 0, test_auxdata},
1014 { "test_error", 1, 0, SQLITE_UTF8, 0, test_error},
1015 #endif
1016 };
1017 static const struct {
1018 char *zName;
1019 signed char nArg;
1020 u8 argType;
1021 u8 needCollSeq;
1022 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
1023 void (*xFinalize)(sqlite3_context*);
1024 } aAggs[] = {
1025 { "min", 1, 0, 1, minmaxStep, minMaxFinalize },
1026 { "max", 1, 2, 1, minmaxStep, minMaxFinalize },
1027 { "sum", 1, 0, 0, sumStep, sumFinalize },
1028 { "total", 1, 0, 0, sumStep, totalFinalize },
1029 { "avg", 1, 0, 0, sumStep, avgFinalize },
1030 { "count", 0, 0, 0, countStep, countFinalize },
1031 { "count", 1, 0, 0, countStep, countFinalize },
1032 };
1033 int i;
1034
1035 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1036 void *pArg = 0;
1037 switch( aFuncs[i].argType ){
1038 case 1: pArg = db; break;
1039 case 2: pArg = (void *)(-1); break;
1040 }
1041 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
1042 aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1043 if( aFuncs[i].needCollSeq ){
1044 FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1045 strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1046 if( pFunc && aFuncs[i].needCollSeq ){
1047 pFunc->needCollSeq = 1;
1048 }
1049 }
1050 }
1051 #ifndef SQLITE_OMIT_ALTERTABLE
1052 sqlite3AlterFunctions(db);
1053 #endif
1054 #ifndef SQLITE_OMIT_PARSER
1055 sqlite3AttachFunctions(db);
1056 #endif
1057 for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1058 void *pArg = 0;
1059 switch( aAggs[i].argType ){
1060 case 1: pArg = db; break;
1061 case 2: pArg = (void *)(-1); break;
1062 }
1063 sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1064 pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1065 if( aAggs[i].needCollSeq ){
1066 FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1067 strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1068 if( pFunc && aAggs[i].needCollSeq ){
1069 pFunc->needCollSeq = 1;
1070 }
1071 }
1072 }
1073 sqlite3RegisterDateTimeFunctions(db);
1074 #ifdef SQLITE_SSE
1075 (void)sqlite3SseFunctions(db);
1076 #endif
1077 #ifdef SQLITE_CASE_SENSITIVE_LIKE
1078 sqlite3RegisterLikeFunctions(db, 1);
1079 #else
1080 sqlite3RegisterLikeFunctions(db, 0);
1081 #endif
1082 }
1083
1084 /*
1085 ** Set the LIKEOPT flag on the 2-argument function with the given name.
1086 */
1087 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
1088 FuncDef *pDef;
1089 pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
1090 if( pDef ){
1091 pDef->flags = flagVal;
1092 }
1093 }
1094
1095 /*
1096 ** Register the built-in LIKE and GLOB functions. The caseSensitive
1097 ** parameter determines whether or not the LIKE operator is case
1098 ** sensitive. GLOB is always case sensitive.
1099 */
1100 void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
1101 struct compareInfo *pInfo;
1102 if( caseSensitive ){
1103 pInfo = (struct compareInfo*)&likeInfoAlt;
1104 }else{
1105 pInfo = (struct compareInfo*)&likeInfoNorm;
1106 }
1107 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
1108 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
1109 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
1110 (struct compareInfo*)&globInfo, likeFunc, 0,0);
1111 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
1112 setLikeOptFlag(db, "like",
1113 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
1114 }
1115
1116 /*
1117 ** pExpr points to an expression which implements a function. If
1118 ** it is appropriate to apply the LIKE optimization to that function
1119 ** then set aWc[0] through aWc[2] to the wildcard characters and
1120 ** return TRUE. If the function is not a LIKE-style function then
1121 ** return FALSE.
1122 */
1123 int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
1124 FuncDef *pDef;
1125 if( pExpr->op!=TK_FUNCTION ){
1126 return 0;
1127 }
1128 if( pExpr->pList->nExpr!=2 ){
1129 return 0;
1130 }
1131 pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
1132 SQLITE_UTF8, 0);
1133 if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
1134 return 0;
1135 }
1136
1137 /* The memcpy() statement assumes that the wildcard characters are
1138 ** the first three statements in the compareInfo structure. The
1139 ** asserts() that follow verify that assumption
1140 */
1141 memcpy(aWc, pDef->pUserData, 3);
1142 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
1143 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
1144 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
1145 *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
1146 return 1;
1147 }