4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** This file contains the C-language implementations for many of the SQL
13 ** functions of SQLite. (Some function, and in particular the date and
14 ** time functions, are implemented separately.)
16 #include "sqliteInt.h"
19 #ifndef SQLITE_OMIT_FLOATING_POINT
25 ** Return the collating function associated with a function.
27 static CollSeq
*sqlite3GetFuncCollSeq(sqlite3_context
*context
){
29 assert( context
->pVdbe
!=0 );
30 pOp
= &context
->pVdbe
->aOp
[context
->iOp
-1];
31 assert( pOp
->opcode
==OP_CollSeq
);
32 assert( pOp
->p4type
==P4_COLLSEQ
);
37 ** Indicate that the accumulator load should be skipped on this
38 ** iteration of the aggregate loop.
40 static void sqlite3SkipAccumulatorLoad(sqlite3_context
*context
){
41 assert( context
->isError
<=0 );
42 context
->isError
= -1;
43 context
->skipFlag
= 1;
47 ** Implementation of the non-aggregate min() and max() functions
49 static void minmaxFunc(
50 sqlite3_context
*context
,
55 int mask
; /* 0 for min() or 0xffffffff for max() */
60 mask
= sqlite3_user_data(context
)==0 ? 0 : -1;
61 pColl
= sqlite3GetFuncCollSeq(context
);
63 assert( mask
==-1 || mask
==0 );
65 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
) return;
66 for(i
=1; i
<argc
; i
++){
67 if( sqlite3_value_type(argv
[i
])==SQLITE_NULL
) return;
68 if( (sqlite3MemCompare(argv
[iBest
], argv
[i
], pColl
)^mask
)>=0 ){
73 sqlite3_result_value(context
, argv
[iBest
]);
77 ** Return the type of the argument.
79 static void typeofFunc(
80 sqlite3_context
*context
,
84 static const char *azType
[] = { "integer", "real", "text", "blob", "null" };
85 int i
= sqlite3_value_type(argv
[0]) - 1;
86 UNUSED_PARAMETER(NotUsed
);
87 assert( i
>=0 && i
<ArraySize(azType
) );
88 assert( SQLITE_INTEGER
==1 );
89 assert( SQLITE_FLOAT
==2 );
90 assert( SQLITE_TEXT
==3 );
91 assert( SQLITE_BLOB
==4 );
92 assert( SQLITE_NULL
==5 );
93 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
94 ** the datatype code for the initial datatype of the sqlite3_value object
95 ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
96 ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
97 sqlite3_result_text(context
, azType
[i
], -1, SQLITE_STATIC
);
102 ** Return the subtype of X
104 static void subtypeFunc(
105 sqlite3_context
*context
,
109 UNUSED_PARAMETER(argc
);
110 sqlite3_result_int(context
, sqlite3_value_subtype(argv
[0]));
114 ** Implementation of the length() function
116 static void lengthFunc(
117 sqlite3_context
*context
,
122 UNUSED_PARAMETER(argc
);
123 switch( sqlite3_value_type(argv
[0]) ){
127 sqlite3_result_int(context
, sqlite3_value_bytes(argv
[0]));
131 const unsigned char *z
= sqlite3_value_text(argv
[0]);
132 const unsigned char *z0
;
136 while( (c
= *z
)!=0 ){
139 while( (*z
& 0xc0)==0x80 ){ z
++; z0
++; }
142 sqlite3_result_int(context
, (int)(z
-z0
));
146 sqlite3_result_null(context
);
153 ** Implementation of the octet_length() function
155 static void bytelengthFunc(
156 sqlite3_context
*context
,
161 UNUSED_PARAMETER(argc
);
162 switch( sqlite3_value_type(argv
[0]) ){
164 sqlite3_result_int(context
, sqlite3_value_bytes(argv
[0]));
169 i64 m
= sqlite3_context_db_handle(context
)->enc
<=SQLITE_UTF8
? 1 : 2;
170 sqlite3_result_int64(context
, sqlite3_value_bytes(argv
[0])*m
);
174 if( sqlite3_value_encoding(argv
[0])<=SQLITE_UTF8
){
175 sqlite3_result_int(context
, sqlite3_value_bytes(argv
[0]));
177 sqlite3_result_int(context
, sqlite3_value_bytes16(argv
[0]));
182 sqlite3_result_null(context
);
189 ** Implementation of the abs() function.
191 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
192 ** the numeric argument X.
194 static void absFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
196 UNUSED_PARAMETER(argc
);
197 switch( sqlite3_value_type(argv
[0]) ){
198 case SQLITE_INTEGER
: {
199 i64 iVal
= sqlite3_value_int64(argv
[0]);
201 if( iVal
==SMALLEST_INT64
){
202 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
203 ** then abs(X) throws an integer overflow error since there is no
204 ** equivalent positive 64-bit two complement value. */
205 sqlite3_result_error(context
, "integer overflow", -1);
210 sqlite3_result_int64(context
, iVal
);
214 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
215 sqlite3_result_null(context
);
219 /* Because sqlite3_value_double() returns 0.0 if the argument is not
220 ** something that can be converted into a number, we have:
221 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
222 ** that cannot be converted to a numeric value.
224 double rVal
= sqlite3_value_double(argv
[0]);
225 if( rVal
<0 ) rVal
= -rVal
;
226 sqlite3_result_double(context
, rVal
);
233 ** Implementation of the instr() function.
235 ** instr(haystack,needle) finds the first occurrence of needle
236 ** in haystack and returns the number of previous characters plus 1,
237 ** or 0 if needle does not occur within haystack.
239 ** If both haystack and needle are BLOBs, then the result is one more than
240 ** the number of bytes in haystack prior to the first occurrence of needle,
241 ** or 0 if needle never occurs in haystack.
243 static void instrFunc(
244 sqlite3_context
*context
,
248 const unsigned char *zHaystack
;
249 const unsigned char *zNeedle
;
252 int typeHaystack
, typeNeedle
;
255 unsigned char firstChar
;
256 sqlite3_value
*pC1
= 0;
257 sqlite3_value
*pC2
= 0;
259 UNUSED_PARAMETER(argc
);
260 typeHaystack
= sqlite3_value_type(argv
[0]);
261 typeNeedle
= sqlite3_value_type(argv
[1]);
262 if( typeHaystack
==SQLITE_NULL
|| typeNeedle
==SQLITE_NULL
) return;
263 nHaystack
= sqlite3_value_bytes(argv
[0]);
264 nNeedle
= sqlite3_value_bytes(argv
[1]);
266 if( typeHaystack
==SQLITE_BLOB
&& typeNeedle
==SQLITE_BLOB
){
267 zHaystack
= sqlite3_value_blob(argv
[0]);
268 zNeedle
= sqlite3_value_blob(argv
[1]);
270 }else if( typeHaystack
!=SQLITE_BLOB
&& typeNeedle
!=SQLITE_BLOB
){
271 zHaystack
= sqlite3_value_text(argv
[0]);
272 zNeedle
= sqlite3_value_text(argv
[1]);
275 pC1
= sqlite3_value_dup(argv
[0]);
276 zHaystack
= sqlite3_value_text(pC1
);
277 if( zHaystack
==0 ) goto endInstrOOM
;
278 nHaystack
= sqlite3_value_bytes(pC1
);
279 pC2
= sqlite3_value_dup(argv
[1]);
280 zNeedle
= sqlite3_value_text(pC2
);
281 if( zNeedle
==0 ) goto endInstrOOM
;
282 nNeedle
= sqlite3_value_bytes(pC2
);
285 if( zNeedle
==0 || (nHaystack
&& zHaystack
==0) ) goto endInstrOOM
;
286 firstChar
= zNeedle
[0];
287 while( nNeedle
<=nHaystack
288 && (zHaystack
[0]!=firstChar
|| memcmp(zHaystack
, zNeedle
, nNeedle
)!=0)
294 }while( isText
&& (zHaystack
[0]&0xc0)==0x80 );
296 if( nNeedle
>nHaystack
) N
= 0;
298 sqlite3_result_int(context
, N
);
300 sqlite3_value_free(pC1
);
301 sqlite3_value_free(pC2
);
304 sqlite3_result_error_nomem(context
);
309 ** Implementation of the printf() (a.k.a. format()) SQL function.
311 static void printfFunc(
312 sqlite3_context
*context
,
320 sqlite3
*db
= sqlite3_context_db_handle(context
);
322 if( argc
>=1 && (zFormat
= (const char*)sqlite3_value_text(argv
[0]))!=0 ){
326 sqlite3StrAccumInit(&str
, db
, 0, 0, db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
327 str
.printfFlags
= SQLITE_PRINTF_SQLFUNC
;
328 sqlite3_str_appendf(&str
, zFormat
, &x
);
330 sqlite3_result_text(context
, sqlite3StrAccumFinish(&str
), n
,
336 ** Implementation of the substr() function.
338 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
339 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
340 ** of x. If x is text, then we actually count UTF-8 characters.
341 ** If x is a blob, then we count bytes.
343 ** If p1 is negative, then we begin abs(p1) from the end of x[].
345 ** If p2 is negative, return the p2 characters preceding p1.
347 static void substrFunc(
348 sqlite3_context
*context
,
352 const unsigned char *z
;
353 const unsigned char *z2
;
359 assert( argc
==3 || argc
==2 );
360 if( sqlite3_value_type(argv
[1])==SQLITE_NULL
361 || (argc
==3 && sqlite3_value_type(argv
[2])==SQLITE_NULL
)
365 p0type
= sqlite3_value_type(argv
[0]);
366 p1
= sqlite3_value_int(argv
[1]);
367 if( p0type
==SQLITE_BLOB
){
368 len
= sqlite3_value_bytes(argv
[0]);
369 z
= sqlite3_value_blob(argv
[0]);
371 assert( len
==sqlite3_value_bytes(argv
[0]) );
373 z
= sqlite3_value_text(argv
[0]);
377 for(z2
=z
; *z2
; len
++){
378 SQLITE_SKIP_UTF8(z2
);
382 #ifdef SQLITE_SUBSTR_COMPATIBILITY
383 /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
384 ** as substr(X,1,N) - it returns the first N characters of X. This
385 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
386 ** from 2009-02-02 for compatibility of applications that exploited the
387 ** old buggy behavior. */
388 if( p1
==0 ) p1
= 1; /* <rdar://problem/6778339> */
391 p2
= sqlite3_value_int(argv
[2]);
397 p2
= sqlite3_context_db_handle(context
)->aLimit
[SQLITE_LIMIT_LENGTH
];
418 assert( p1
>=0 && p2
>=0 );
419 if( p0type
!=SQLITE_BLOB
){
424 for(z2
=z
; *z2
&& p2
; p2
--){
425 SQLITE_SKIP_UTF8(z2
);
427 sqlite3_result_text64(context
, (char*)z
, z2
-z
, SQLITE_TRANSIENT
,
434 sqlite3_result_blob64(context
, (char*)&z
[p1
], (u64
)p2
, SQLITE_TRANSIENT
);
439 ** Implementation of the round() function
441 #ifndef SQLITE_OMIT_FLOATING_POINT
442 static void roundFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
446 assert( argc
==1 || argc
==2 );
448 if( SQLITE_NULL
==sqlite3_value_type(argv
[1]) ) return;
449 n
= sqlite3_value_int(argv
[1]);
453 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
) return;
454 r
= sqlite3_value_double(argv
[0]);
455 /* If Y==0 and X will fit in a 64-bit int,
456 ** handle the rounding directly,
457 ** otherwise use printf.
459 if( r
<-4503599627370496.0 || r
>+4503599627370496.0 ){
460 /* The value has no fractional part so there is nothing to round */
462 r
= (double)((sqlite_int64
)(r
+(r
<0?-0.5:+0.5)));
464 zBuf
= sqlite3_mprintf("%!.*f",n
,r
);
466 sqlite3_result_error_nomem(context
);
469 sqlite3AtoF(zBuf
, &r
, sqlite3Strlen30(zBuf
), SQLITE_UTF8
);
472 sqlite3_result_double(context
, r
);
477 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
478 ** allocation fails, call sqlite3_result_error_nomem() to notify
479 ** the database handle that malloc() has failed and return NULL.
480 ** If nByte is larger than the maximum string or blob length, then
481 ** raise an SQLITE_TOOBIG exception and return NULL.
483 static void *contextMalloc(sqlite3_context
*context
, i64 nByte
){
485 sqlite3
*db
= sqlite3_context_db_handle(context
);
487 testcase( nByte
==db
->aLimit
[SQLITE_LIMIT_LENGTH
] );
488 testcase( nByte
==db
->aLimit
[SQLITE_LIMIT_LENGTH
]+1 );
489 if( nByte
>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
490 sqlite3_result_error_toobig(context
);
493 z
= sqlite3Malloc(nByte
);
495 sqlite3_result_error_nomem(context
);
502 ** Implementation of the upper() and lower() SQL functions.
504 static void upperFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
508 UNUSED_PARAMETER(argc
);
509 z2
= (char*)sqlite3_value_text(argv
[0]);
510 n
= sqlite3_value_bytes(argv
[0]);
511 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
512 assert( z2
==(char*)sqlite3_value_text(argv
[0]) );
514 z1
= contextMalloc(context
, ((i64
)n
)+1);
517 z1
[i
] = (char)sqlite3Toupper(z2
[i
]);
519 sqlite3_result_text(context
, z1
, n
, sqlite3_free
);
523 static void lowerFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
527 UNUSED_PARAMETER(argc
);
528 z2
= (char*)sqlite3_value_text(argv
[0]);
529 n
= sqlite3_value_bytes(argv
[0]);
530 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
531 assert( z2
==(char*)sqlite3_value_text(argv
[0]) );
533 z1
= contextMalloc(context
, ((i64
)n
)+1);
536 z1
[i
] = sqlite3Tolower(z2
[i
]);
538 sqlite3_result_text(context
, z1
, n
, sqlite3_free
);
544 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
545 ** as VDBE code so that unused argument values do not have to be computed.
546 ** However, we still need some kind of function implementation for this
547 ** routines in the function table. The noopFunc macro provides this.
548 ** noopFunc will never be called so it doesn't matter what the implementation
549 ** is. We might as well use the "version()" function as a substitute.
551 #define noopFunc versionFunc /* Substitute function - never called */
554 ** Implementation of random(). Return a random integer.
556 static void randomFunc(
557 sqlite3_context
*context
,
559 sqlite3_value
**NotUsed2
562 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
563 sqlite3_randomness(sizeof(r
), &r
);
565 /* We need to prevent a random number of 0x8000000000000000
566 ** (or -9223372036854775808) since when you do abs() of that
567 ** number of you get the same value back again. To do this
568 ** in a way that is testable, mask the sign bit off of negative
569 ** values, resulting in a positive value. Then take the
570 ** 2s complement of that positive value. The end result can
571 ** therefore be no less than -9223372036854775807.
573 r
= -(r
& LARGEST_INT64
);
575 sqlite3_result_int64(context
, r
);
579 ** Implementation of randomblob(N). Return a random blob
580 ** that is N bytes long.
582 static void randomBlob(
583 sqlite3_context
*context
,
590 UNUSED_PARAMETER(argc
);
591 n
= sqlite3_value_int64(argv
[0]);
595 p
= contextMalloc(context
, n
);
597 sqlite3_randomness(n
, p
);
598 sqlite3_result_blob(context
, (char*)p
, n
, sqlite3_free
);
603 ** Implementation of the last_insert_rowid() SQL function. The return
604 ** value is the same as the sqlite3_last_insert_rowid() API function.
606 static void last_insert_rowid(
607 sqlite3_context
*context
,
609 sqlite3_value
**NotUsed2
611 sqlite3
*db
= sqlite3_context_db_handle(context
);
612 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
613 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
614 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
616 sqlite3_result_int64(context
, sqlite3_last_insert_rowid(db
));
620 ** Implementation of the changes() SQL function.
622 ** IMP: R-32760-32347 The changes() SQL function is a wrapper
623 ** around the sqlite3_changes64() C/C++ function and hence follows the
624 ** same rules for counting changes.
627 sqlite3_context
*context
,
629 sqlite3_value
**NotUsed2
631 sqlite3
*db
= sqlite3_context_db_handle(context
);
632 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
633 sqlite3_result_int64(context
, sqlite3_changes64(db
));
637 ** Implementation of the total_changes() SQL function. The return value is
638 ** the same as the sqlite3_total_changes64() API function.
640 static void total_changes(
641 sqlite3_context
*context
,
643 sqlite3_value
**NotUsed2
645 sqlite3
*db
= sqlite3_context_db_handle(context
);
646 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
647 /* IMP: R-11217-42568 This function is a wrapper around the
648 ** sqlite3_total_changes64() C/C++ interface. */
649 sqlite3_result_int64(context
, sqlite3_total_changes64(db
));
653 ** A structure defining how to do GLOB-style comparisons.
656 u8 matchAll
; /* "*" or "%" */
657 u8 matchOne
; /* "?" or "_" */
658 u8 matchSet
; /* "[" or 0 */
659 u8 noCase
; /* true to ignore case differences */
663 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
664 ** character is exactly one byte in size. Also, provide the Utf8Read()
665 ** macro for fast reading of the next character in the common case where
666 ** the next character is ASCII.
668 #if defined(SQLITE_EBCDIC)
669 # define sqlite3Utf8Read(A) (*((*A)++))
670 # define Utf8Read(A) (*(A++))
672 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
675 static const struct compareInfo globInfo
= { '*', '?', '[', 0 };
676 /* The correct SQL-92 behavior is for the LIKE operator to ignore
677 ** case. Thus 'a' LIKE 'A' would be true. */
678 static const struct compareInfo likeInfoNorm
= { '%', '_', 0, 1 };
679 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
680 ** is case sensitive causing 'a' LIKE 'A' to be false */
681 static const struct compareInfo likeInfoAlt
= { '%', '_', 0, 0 };
684 ** Possible error returns from patternMatch()
686 #define SQLITE_MATCH 0
687 #define SQLITE_NOMATCH 1
688 #define SQLITE_NOWILDCARDMATCH 2
691 ** Compare two UTF-8 strings for equality where the first string is
692 ** a GLOB or LIKE expression. Return values:
694 ** SQLITE_MATCH: Match
695 ** SQLITE_NOMATCH: No match
696 ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
700 ** '*' Matches any sequence of zero or more characters.
702 ** '?' Matches exactly one character.
704 ** [...] Matches one character from the enclosed list of
707 ** [^...] Matches one character not in the enclosed list.
709 ** With the [...] and [^...] matching, a ']' character can be included
710 ** in the list by making it the first character after '[' or '^'. A
711 ** range of characters can be specified using '-'. Example:
712 ** "[a-z]" matches any single lower-case letter. To match a '-', make
713 ** it the last character in the list.
715 ** Like matching rules:
717 ** '%' Matches any sequence of zero or more characters
719 *** '_' Matches any one character
721 ** Ec Where E is the "esc" character and c is any other
722 ** character, including '%', '_', and esc, match exactly c.
724 ** The comments within this routine usually assume glob matching.
726 ** This routine is usually quick, but can be N**2 in the worst case.
728 static int patternCompare(
729 const u8
*zPattern
, /* The glob pattern */
730 const u8
*zString
, /* The string to compare against the glob */
731 const struct compareInfo
*pInfo
, /* Information about how to do the compare */
732 u32 matchOther
/* The escape char (LIKE) or '[' (GLOB) */
734 u32 c
, c2
; /* Next pattern and input string chars */
735 u32 matchOne
= pInfo
->matchOne
; /* "?" or "_" */
736 u32 matchAll
= pInfo
->matchAll
; /* "*" or "%" */
737 u8 noCase
= pInfo
->noCase
; /* True if uppercase==lowercase */
738 const u8
*zEscaped
= 0; /* One past the last escaped input char */
740 while( (c
= Utf8Read(zPattern
))!=0 ){
741 if( c
==matchAll
){ /* Match "*" */
742 /* Skip over multiple "*" characters in the pattern. If there
743 ** are also "?" characters, skip those as well, but consume a
744 ** single character of the input string for each "?" skipped */
745 while( (c
=Utf8Read(zPattern
)) == matchAll
746 || (c
== matchOne
&& matchOne
!=0) ){
747 if( c
==matchOne
&& sqlite3Utf8Read(&zString
)==0 ){
748 return SQLITE_NOWILDCARDMATCH
;
752 return SQLITE_MATCH
; /* "*" at the end of the pattern matches */
753 }else if( c
==matchOther
){
754 if( pInfo
->matchSet
==0 ){
755 c
= sqlite3Utf8Read(&zPattern
);
756 if( c
==0 ) return SQLITE_NOWILDCARDMATCH
;
758 /* "[...]" immediately follows the "*". We have to do a slow
759 ** recursive search in this case, but it is an unusual case. */
760 assert( matchOther
<0x80 ); /* '[' is a single-byte character */
762 int bMatch
= patternCompare(&zPattern
[-1],zString
,pInfo
,matchOther
);
763 if( bMatch
!=SQLITE_NOMATCH
) return bMatch
;
764 SQLITE_SKIP_UTF8(zString
);
766 return SQLITE_NOWILDCARDMATCH
;
770 /* At this point variable c contains the first character of the
771 ** pattern string past the "*". Search in the input string for the
772 ** first matching character and recursively continue the match from
775 ** For a case-insensitive search, set variable cx to be the same as
776 ** c but in the other case and search the input string for either
783 zStop
[0] = sqlite3Toupper(c
);
784 zStop
[1] = sqlite3Tolower(c
);
791 zString
+= strcspn((const char*)zString
, zStop
);
792 if( zString
[0]==0 ) break;
794 bMatch
= patternCompare(zPattern
,zString
,pInfo
,matchOther
);
795 if( bMatch
!=SQLITE_NOMATCH
) return bMatch
;
799 while( (c2
= Utf8Read(zString
))!=0 ){
800 if( c2
!=c
) continue;
801 bMatch
= patternCompare(zPattern
,zString
,pInfo
,matchOther
);
802 if( bMatch
!=SQLITE_NOMATCH
) return bMatch
;
805 return SQLITE_NOWILDCARDMATCH
;
808 if( pInfo
->matchSet
==0 ){
809 c
= sqlite3Utf8Read(&zPattern
);
810 if( c
==0 ) return SQLITE_NOMATCH
;
816 c
= sqlite3Utf8Read(&zString
);
817 if( c
==0 ) return SQLITE_NOMATCH
;
818 c2
= sqlite3Utf8Read(&zPattern
);
821 c2
= sqlite3Utf8Read(&zPattern
);
824 if( c
==']' ) seen
= 1;
825 c2
= sqlite3Utf8Read(&zPattern
);
827 while( c2
&& c2
!=']' ){
828 if( c2
=='-' && zPattern
[0]!=']' && zPattern
[0]!=0 && prior_c
>0 ){
829 c2
= sqlite3Utf8Read(&zPattern
);
830 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
838 c2
= sqlite3Utf8Read(&zPattern
);
840 if( c2
==0 || (seen
^ invert
)==0 ){
841 return SQLITE_NOMATCH
;
846 c2
= Utf8Read(zString
);
847 if( c
==c2
) continue;
848 if( noCase
&& sqlite3Tolower(c
)==sqlite3Tolower(c2
) && c
<0x80 && c2
<0x80 ){
851 if( c
==matchOne
&& zPattern
!=zEscaped
&& c2
!=0 ) continue;
852 return SQLITE_NOMATCH
;
854 return *zString
==0 ? SQLITE_MATCH
: SQLITE_NOMATCH
;
858 ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
859 ** non-zero if there is no match.
861 int sqlite3_strglob(const char *zGlobPattern
, const char *zString
){
863 return zGlobPattern
!=0;
864 }else if( zGlobPattern
==0 ){
867 return patternCompare((u8
*)zGlobPattern
, (u8
*)zString
, &globInfo
, '[');
872 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
873 ** a miss - like strcmp().
875 int sqlite3_strlike(const char *zPattern
, const char *zStr
, unsigned int esc
){
878 }else if( zPattern
==0 ){
881 return patternCompare((u8
*)zPattern
, (u8
*)zStr
, &likeInfoNorm
, esc
);
886 ** Count the number of times that the LIKE operator (or GLOB which is
887 ** just a variation of LIKE) gets called. This is used for testing
891 int sqlite3_like_count
= 0;
896 ** Implementation of the like() SQL function. This function implements
897 ** the built-in LIKE operator. The first argument to the function is the
898 ** pattern and the second argument is the string. So, the SQL statements:
902 ** is implemented as like(B,A).
904 ** This same function (with a different compareInfo structure) computes
905 ** the GLOB operator.
907 static void likeFunc(
908 sqlite3_context
*context
,
912 const unsigned char *zA
, *zB
;
915 sqlite3
*db
= sqlite3_context_db_handle(context
);
916 struct compareInfo
*pInfo
= sqlite3_user_data(context
);
917 struct compareInfo backupInfo
;
919 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
920 if( sqlite3_value_type(argv
[0])==SQLITE_BLOB
921 || sqlite3_value_type(argv
[1])==SQLITE_BLOB
924 sqlite3_like_count
++;
926 sqlite3_result_int(context
, 0);
931 /* Limit the length of the LIKE or GLOB pattern to avoid problems
932 ** of deep recursion and N*N behavior in patternCompare().
934 nPat
= sqlite3_value_bytes(argv
[0]);
935 testcase( nPat
==db
->aLimit
[SQLITE_LIMIT_LIKE_PATTERN_LENGTH
] );
936 testcase( nPat
==db
->aLimit
[SQLITE_LIMIT_LIKE_PATTERN_LENGTH
]+1 );
937 if( nPat
> db
->aLimit
[SQLITE_LIMIT_LIKE_PATTERN_LENGTH
] ){
938 sqlite3_result_error(context
, "LIKE or GLOB pattern too complex", -1);
942 /* The escape character string must consist of a single UTF-8 character.
943 ** Otherwise, return an error.
945 const unsigned char *zEsc
= sqlite3_value_text(argv
[2]);
946 if( zEsc
==0 ) return;
947 if( sqlite3Utf8CharLen((char*)zEsc
, -1)!=1 ){
948 sqlite3_result_error(context
,
949 "ESCAPE expression must be a single character", -1);
952 escape
= sqlite3Utf8Read(&zEsc
);
953 if( escape
==pInfo
->matchAll
|| escape
==pInfo
->matchOne
){
954 memcpy(&backupInfo
, pInfo
, sizeof(backupInfo
));
956 if( escape
==pInfo
->matchAll
) pInfo
->matchAll
= 0;
957 if( escape
==pInfo
->matchOne
) pInfo
->matchOne
= 0;
960 escape
= pInfo
->matchSet
;
962 zB
= sqlite3_value_text(argv
[0]);
963 zA
= sqlite3_value_text(argv
[1]);
966 sqlite3_like_count
++;
968 sqlite3_result_int(context
,
969 patternCompare(zB
, zA
, pInfo
, escape
)==SQLITE_MATCH
);
974 ** Implementation of the NULLIF(x,y) function. The result is the first
975 ** argument if the arguments are different. The result is NULL if the
976 ** arguments are equal to each other.
978 static void nullifFunc(
979 sqlite3_context
*context
,
983 CollSeq
*pColl
= sqlite3GetFuncCollSeq(context
);
984 UNUSED_PARAMETER(NotUsed
);
985 if( sqlite3MemCompare(argv
[0], argv
[1], pColl
)!=0 ){
986 sqlite3_result_value(context
, argv
[0]);
991 ** Implementation of the sqlite_version() function. The result is the version
992 ** of the SQLite library that is running.
994 static void versionFunc(
995 sqlite3_context
*context
,
997 sqlite3_value
**NotUsed2
999 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
1000 /* IMP: R-48699-48617 This function is an SQL wrapper around the
1001 ** sqlite3_libversion() C-interface. */
1002 sqlite3_result_text(context
, sqlite3_libversion(), -1, SQLITE_STATIC
);
1006 ** Implementation of the sqlite_source_id() function. The result is a string
1007 ** that identifies the particular version of the source code used to build
1010 static void sourceidFunc(
1011 sqlite3_context
*context
,
1013 sqlite3_value
**NotUsed2
1015 UNUSED_PARAMETER2(NotUsed
, NotUsed2
);
1016 /* IMP: R-24470-31136 This function is an SQL wrapper around the
1017 ** sqlite3_sourceid() C interface. */
1018 sqlite3_result_text(context
, sqlite3_sourceid(), -1, SQLITE_STATIC
);
1022 ** Implementation of the sqlite_log() function. This is a wrapper around
1023 ** sqlite3_log(). The return value is NULL. The function exists purely for
1024 ** its side-effects.
1026 static void errlogFunc(
1027 sqlite3_context
*context
,
1029 sqlite3_value
**argv
1031 UNUSED_PARAMETER(argc
);
1032 UNUSED_PARAMETER(context
);
1033 sqlite3_log(sqlite3_value_int(argv
[0]), "%s", sqlite3_value_text(argv
[1]));
1037 ** Implementation of the sqlite_compileoption_used() function.
1038 ** The result is an integer that identifies if the compiler option
1039 ** was used to build SQLite.
1041 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1042 static void compileoptionusedFunc(
1043 sqlite3_context
*context
,
1045 sqlite3_value
**argv
1047 const char *zOptName
;
1049 UNUSED_PARAMETER(argc
);
1050 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
1051 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
1054 if( (zOptName
= (const char*)sqlite3_value_text(argv
[0]))!=0 ){
1055 sqlite3_result_int(context
, sqlite3_compileoption_used(zOptName
));
1058 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1061 ** Implementation of the sqlite_compileoption_get() function.
1062 ** The result is a string that identifies the compiler options
1063 ** used to build SQLite.
1065 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1066 static void compileoptiongetFunc(
1067 sqlite3_context
*context
,
1069 sqlite3_value
**argv
1073 UNUSED_PARAMETER(argc
);
1074 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
1075 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
1077 n
= sqlite3_value_int(argv
[0]);
1078 sqlite3_result_text(context
, sqlite3_compileoption_get(n
), -1, SQLITE_STATIC
);
1080 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
1082 /* Array for converting from half-bytes (nybbles) into ASCII hex
1084 static const char hexdigits
[] = {
1085 '0', '1', '2', '3', '4', '5', '6', '7',
1086 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
1090 ** Append to pStr text that is the SQL literal representation of the
1091 ** value contained in pValue.
1093 void sqlite3QuoteValue(StrAccum
*pStr
, sqlite3_value
*pValue
){
1094 /* As currently implemented, the string must be initially empty.
1095 ** we might relax this requirement in the future, but that will
1096 ** require enhancements to the implementation. */
1097 assert( pStr
!=0 && pStr
->nChar
==0 );
1099 switch( sqlite3_value_type(pValue
) ){
1100 case SQLITE_FLOAT
: {
1103 r1
= sqlite3_value_double(pValue
);
1104 sqlite3_str_appendf(pStr
, "%!.15g", r1
);
1105 zVal
= sqlite3_str_value(pStr
);
1107 sqlite3AtoF(zVal
, &r2
, pStr
->nChar
, SQLITE_UTF8
);
1109 sqlite3_str_reset(pStr
);
1110 sqlite3_str_appendf(pStr
, "%!.20e", r1
);
1115 case SQLITE_INTEGER
: {
1116 sqlite3_str_appendf(pStr
, "%lld", sqlite3_value_int64(pValue
));
1120 char const *zBlob
= sqlite3_value_blob(pValue
);
1121 i64 nBlob
= sqlite3_value_bytes(pValue
);
1122 assert( zBlob
==sqlite3_value_blob(pValue
) ); /* No encoding change */
1123 sqlite3StrAccumEnlarge(pStr
, nBlob
*2 + 4);
1124 if( pStr
->accError
==0 ){
1125 char *zText
= pStr
->zText
;
1127 for(i
=0; i
<nBlob
; i
++){
1128 zText
[(i
*2)+2] = hexdigits
[(zBlob
[i
]>>4)&0x0F];
1129 zText
[(i
*2)+3] = hexdigits
[(zBlob
[i
])&0x0F];
1131 zText
[(nBlob
*2)+2] = '\'';
1132 zText
[(nBlob
*2)+3] = '\0';
1135 pStr
->nChar
= nBlob
*2 + 3;
1140 const unsigned char *zArg
= sqlite3_value_text(pValue
);
1141 sqlite3_str_appendf(pStr
, "%Q", zArg
);
1145 assert( sqlite3_value_type(pValue
)==SQLITE_NULL
);
1146 sqlite3_str_append(pStr
, "NULL", 4);
1153 ** Implementation of the QUOTE() function.
1155 ** The quote(X) function returns the text of an SQL literal which is the
1156 ** value of its argument suitable for inclusion into an SQL statement.
1157 ** Strings are surrounded by single-quotes with escapes on interior quotes
1158 ** as needed. BLOBs are encoded as hexadecimal literals. Strings with
1159 ** embedded NUL characters cannot be represented as string literals in SQL
1160 ** and hence the returned string literal is truncated prior to the first NUL.
1162 static void quoteFunc(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
1164 sqlite3
*db
= sqlite3_context_db_handle(context
);
1166 UNUSED_PARAMETER(argc
);
1167 sqlite3StrAccumInit(&str
, db
, 0, 0, db
->aLimit
[SQLITE_LIMIT_LENGTH
]);
1168 sqlite3QuoteValue(&str
,argv
[0]);
1169 sqlite3_result_text(context
, sqlite3StrAccumFinish(&str
), str
.nChar
,
1171 if( str
.accError
!=SQLITE_OK
){
1172 sqlite3_result_null(context
);
1173 sqlite3_result_error_code(context
, str
.accError
);
1178 ** The unicode() function. Return the integer unicode code-point value
1179 ** for the first character of the input string.
1181 static void unicodeFunc(
1182 sqlite3_context
*context
,
1184 sqlite3_value
**argv
1186 const unsigned char *z
= sqlite3_value_text(argv
[0]);
1188 if( z
&& z
[0] ) sqlite3_result_int(context
, sqlite3Utf8Read(&z
));
1192 ** The char() function takes zero or more arguments, each of which is
1193 ** an integer. It constructs a string where each character of the string
1194 ** is the unicode character for the corresponding integer argument.
1196 static void charFunc(
1197 sqlite3_context
*context
,
1199 sqlite3_value
**argv
1201 unsigned char *z
, *zOut
;
1203 zOut
= z
= sqlite3_malloc64( argc
*4+1 );
1205 sqlite3_result_error_nomem(context
);
1208 for(i
=0; i
<argc
; i
++){
1211 x
= sqlite3_value_int64(argv
[i
]);
1212 if( x
<0 || x
>0x10ffff ) x
= 0xfffd;
1213 c
= (unsigned)(x
& 0x1fffff);
1215 *zOut
++ = (u8
)(c
&0xFF);
1216 }else if( c
<0x00800 ){
1217 *zOut
++ = 0xC0 + (u8
)((c
>>6)&0x1F);
1218 *zOut
++ = 0x80 + (u8
)(c
& 0x3F);
1219 }else if( c
<0x10000 ){
1220 *zOut
++ = 0xE0 + (u8
)((c
>>12)&0x0F);
1221 *zOut
++ = 0x80 + (u8
)((c
>>6) & 0x3F);
1222 *zOut
++ = 0x80 + (u8
)(c
& 0x3F);
1224 *zOut
++ = 0xF0 + (u8
)((c
>>18) & 0x07);
1225 *zOut
++ = 0x80 + (u8
)((c
>>12) & 0x3F);
1226 *zOut
++ = 0x80 + (u8
)((c
>>6) & 0x3F);
1227 *zOut
++ = 0x80 + (u8
)(c
& 0x3F);
1231 sqlite3_result_text64(context
, (char*)z
, zOut
-z
, sqlite3_free
, SQLITE_UTF8
);
1235 ** The hex() function. Interpret the argument as a blob. Return
1236 ** a hexadecimal rendering as text.
1238 static void hexFunc(
1239 sqlite3_context
*context
,
1241 sqlite3_value
**argv
1244 const unsigned char *pBlob
;
1247 UNUSED_PARAMETER(argc
);
1248 pBlob
= sqlite3_value_blob(argv
[0]);
1249 n
= sqlite3_value_bytes(argv
[0]);
1250 assert( pBlob
==sqlite3_value_blob(argv
[0]) ); /* No encoding change */
1251 z
= zHex
= contextMalloc(context
, ((i64
)n
)*2 + 1);
1253 for(i
=0; i
<n
; i
++, pBlob
++){
1254 unsigned char c
= *pBlob
;
1255 *(z
++) = hexdigits
[(c
>>4)&0xf];
1256 *(z
++) = hexdigits
[c
&0xf];
1259 sqlite3_result_text(context
, zHex
, n
*2, sqlite3_free
);
1264 ** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr
1265 ** contains character ch, or 0 if it does not.
1267 static int strContainsChar(const u8
*zStr
, int nStr
, u32 ch
){
1268 const u8
*zEnd
= &zStr
[nStr
];
1271 u32 tst
= Utf8Read(z
);
1272 if( tst
==ch
) return 1;
1278 ** The unhex() function. This function may be invoked with either one or
1279 ** two arguments. In both cases the first argument is interpreted as text
1280 ** a text value containing a set of pairs of hexadecimal digits which are
1281 ** decoded and returned as a blob.
1283 ** If there is only a single argument, then it must consist only of an
1284 ** even number of hexadecimal digits. Otherwise, return NULL.
1286 ** Or, if there is a second argument, then any character that appears in
1287 ** the second argument is also allowed to appear between pairs of hexadecimal
1288 ** digits in the first argument. If any other character appears in the
1289 ** first argument, or if one of the allowed characters appears between
1290 ** two hexadecimal digits that make up a single byte, NULL is returned.
1292 ** The following expressions are all true:
1294 ** unhex('ABCD') IS x'ABCD'
1295 ** unhex('AB CD') IS NULL
1296 ** unhex('AB CD', ' ') IS x'ABCD'
1297 ** unhex('A BCD', ' ') IS NULL
1299 static void unhexFunc(
1300 sqlite3_context
*pCtx
,
1302 sqlite3_value
**argv
1304 const u8
*zPass
= (const u8
*)"";
1306 const u8
*zHex
= sqlite3_value_text(argv
[0]);
1307 int nHex
= sqlite3_value_bytes(argv
[0]);
1309 const u8
*zEnd
= zHex
? &zHex
[nHex
] : 0;
1314 assert( argc
==1 || argc
==2 );
1316 zPass
= sqlite3_value_text(argv
[1]);
1317 nPass
= sqlite3_value_bytes(argv
[1]);
1319 if( !zHex
|| !zPass
) return;
1321 p
= pBlob
= contextMalloc(pCtx
, (nHex
/2)+1);
1323 u8 c
; /* Most significant digit of next byte */
1324 u8 d
; /* Least significant digit of next byte */
1326 while( (c
= *zHex
)!=0x00 ){
1327 while( !sqlite3Isxdigit(c
) ){
1328 u32 ch
= Utf8Read(zHex
);
1329 assert( zHex
<=zEnd
);
1330 if( !strContainsChar(zPass
, nPass
, ch
) ) goto unhex_null
;
1332 if( c
==0x00 ) goto unhex_done
;
1335 assert( *zEnd
==0x00 );
1336 assert( zHex
<=zEnd
);
1338 if( !sqlite3Isxdigit(d
) ) goto unhex_null
;
1339 *(p
++) = (sqlite3HexToInt(c
)<<4) | sqlite3HexToInt(d
);
1344 sqlite3_result_blob(pCtx
, pBlob
, (p
- pBlob
), sqlite3_free
);
1348 sqlite3_free(pBlob
);
1354 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
1356 static void zeroblobFunc(
1357 sqlite3_context
*context
,
1359 sqlite3_value
**argv
1364 UNUSED_PARAMETER(argc
);
1365 n
= sqlite3_value_int64(argv
[0]);
1367 rc
= sqlite3_result_zeroblob64(context
, n
); /* IMP: R-00293-64994 */
1369 sqlite3_result_error_code(context
, rc
);
1374 ** The replace() function. Three arguments are all strings: call
1375 ** them A, B, and C. The result is also a string which is derived
1376 ** from A by replacing every occurrence of B with C. The match
1377 ** must be exact. Collating sequences are not used.
1379 static void replaceFunc(
1380 sqlite3_context
*context
,
1382 sqlite3_value
**argv
1384 const unsigned char *zStr
; /* The input string A */
1385 const unsigned char *zPattern
; /* The pattern string B */
1386 const unsigned char *zRep
; /* The replacement string C */
1387 unsigned char *zOut
; /* The output */
1388 int nStr
; /* Size of zStr */
1389 int nPattern
; /* Size of zPattern */
1390 int nRep
; /* Size of zRep */
1391 i64 nOut
; /* Maximum size of zOut */
1392 int loopLimit
; /* Last zStr[] that might match zPattern[] */
1393 int i
, j
; /* Loop counters */
1394 unsigned cntExpand
; /* Number zOut expansions */
1395 sqlite3
*db
= sqlite3_context_db_handle(context
);
1398 UNUSED_PARAMETER(argc
);
1399 zStr
= sqlite3_value_text(argv
[0]);
1400 if( zStr
==0 ) return;
1401 nStr
= sqlite3_value_bytes(argv
[0]);
1402 assert( zStr
==sqlite3_value_text(argv
[0]) ); /* No encoding change */
1403 zPattern
= sqlite3_value_text(argv
[1]);
1405 assert( sqlite3_value_type(argv
[1])==SQLITE_NULL
1406 || sqlite3_context_db_handle(context
)->mallocFailed
);
1409 if( zPattern
[0]==0 ){
1410 assert( sqlite3_value_type(argv
[1])!=SQLITE_NULL
);
1411 sqlite3_result_value(context
, argv
[0]);
1414 nPattern
= sqlite3_value_bytes(argv
[1]);
1415 assert( zPattern
==sqlite3_value_text(argv
[1]) ); /* No encoding change */
1416 zRep
= sqlite3_value_text(argv
[2]);
1417 if( zRep
==0 ) return;
1418 nRep
= sqlite3_value_bytes(argv
[2]);
1419 assert( zRep
==sqlite3_value_text(argv
[2]) );
1421 assert( nOut
<SQLITE_MAX_LENGTH
);
1422 zOut
= contextMalloc(context
, (i64
)nOut
);
1426 loopLimit
= nStr
- nPattern
;
1428 for(i
=j
=0; i
<=loopLimit
; i
++){
1429 if( zStr
[i
]!=zPattern
[0] || memcmp(&zStr
[i
], zPattern
, nPattern
) ){
1430 zOut
[j
++] = zStr
[i
];
1432 if( nRep
>nPattern
){
1433 nOut
+= nRep
- nPattern
;
1434 testcase( nOut
-1==db
->aLimit
[SQLITE_LIMIT_LENGTH
] );
1435 testcase( nOut
-2==db
->aLimit
[SQLITE_LIMIT_LENGTH
] );
1436 if( nOut
-1>db
->aLimit
[SQLITE_LIMIT_LENGTH
] ){
1437 sqlite3_result_error_toobig(context
);
1442 if( (cntExpand
&(cntExpand
-1))==0 ){
1443 /* Grow the size of the output buffer only on substitutions
1444 ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
1447 zOut
= sqlite3Realloc(zOut
, (int)nOut
+ (nOut
- nStr
- 1));
1449 sqlite3_result_error_nomem(context
);
1455 memcpy(&zOut
[j
], zRep
, nRep
);
1460 assert( j
+nStr
-i
+1<=nOut
);
1461 memcpy(&zOut
[j
], &zStr
[i
], nStr
-i
);
1465 sqlite3_result_text(context
, (char*)zOut
, j
, sqlite3_free
);
1469 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
1470 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
1472 static void trimFunc(
1473 sqlite3_context
*context
,
1475 sqlite3_value
**argv
1477 const unsigned char *zIn
; /* Input string */
1478 const unsigned char *zCharSet
; /* Set of characters to trim */
1479 unsigned int nIn
; /* Number of bytes in input */
1480 int flags
; /* 1: trimleft 2: trimright 3: trim */
1481 int i
; /* Loop counter */
1482 unsigned int *aLen
= 0; /* Length of each character in zCharSet */
1483 unsigned char **azChar
= 0; /* Individual characters in zCharSet */
1484 int nChar
; /* Number of characters in zCharSet */
1486 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1489 zIn
= sqlite3_value_text(argv
[0]);
1490 if( zIn
==0 ) return;
1491 nIn
= (unsigned)sqlite3_value_bytes(argv
[0]);
1492 assert( zIn
==sqlite3_value_text(argv
[0]) );
1494 static const unsigned lenOne
[] = { 1 };
1495 static unsigned char * const azOne
[] = { (u8
*)" " };
1497 aLen
= (unsigned*)lenOne
;
1498 azChar
= (unsigned char **)azOne
;
1500 }else if( (zCharSet
= sqlite3_value_text(argv
[1]))==0 ){
1503 const unsigned char *z
;
1504 for(z
=zCharSet
, nChar
=0; *z
; nChar
++){
1505 SQLITE_SKIP_UTF8(z
);
1508 azChar
= contextMalloc(context
,
1509 ((i64
)nChar
)*(sizeof(char*)+sizeof(unsigned)));
1513 aLen
= (unsigned*)&azChar
[nChar
];
1514 for(z
=zCharSet
, nChar
=0; *z
; nChar
++){
1515 azChar
[nChar
] = (unsigned char *)z
;
1516 SQLITE_SKIP_UTF8(z
);
1517 aLen
[nChar
] = (unsigned)(z
- azChar
[nChar
]);
1522 flags
= SQLITE_PTR_TO_INT(sqlite3_user_data(context
));
1525 unsigned int len
= 0;
1526 for(i
=0; i
<nChar
; i
++){
1528 if( len
<=nIn
&& memcmp(zIn
, azChar
[i
], len
)==0 ) break;
1530 if( i
>=nChar
) break;
1537 unsigned int len
= 0;
1538 for(i
=0; i
<nChar
; i
++){
1540 if( len
<=nIn
&& memcmp(&zIn
[nIn
-len
],azChar
[i
],len
)==0 ) break;
1542 if( i
>=nChar
) break;
1547 sqlite3_free(azChar
);
1550 sqlite3_result_text(context
, (char*)zIn
, nIn
, SQLITE_TRANSIENT
);
1554 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1556 ** The "unknown" function is automatically substituted in place of
1557 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
1558 ** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used.
1559 ** When the "sqlite3" command-line shell is built using this functionality,
1560 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
1561 ** involving application-defined functions to be examined in a generic
1564 static void unknownFunc(
1565 sqlite3_context
*context
,
1567 sqlite3_value
**argv
1574 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
1577 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
1578 ** is only available if the SQLITE_SOUNDEX compile-time option is used
1579 ** when SQLite is built.
1581 #ifdef SQLITE_SOUNDEX
1583 ** Compute the soundex encoding of a word.
1585 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
1586 ** soundex encoding of the string X.
1588 static void soundexFunc(
1589 sqlite3_context
*context
,
1591 sqlite3_value
**argv
1596 static const unsigned char iCode
[] = {
1597 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1598 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1599 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1600 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1601 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1602 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1603 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1604 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1607 zIn
= (u8
*)sqlite3_value_text(argv
[0]);
1608 if( zIn
==0 ) zIn
= (u8
*)"";
1609 for(i
=0; zIn
[i
] && !sqlite3Isalpha(zIn
[i
]); i
++){}
1611 u8 prevcode
= iCode
[zIn
[i
]&0x7f];
1612 zResult
[0] = sqlite3Toupper(zIn
[i
]);
1613 for(j
=1; j
<4 && zIn
[i
]; i
++){
1614 int code
= iCode
[zIn
[i
]&0x7f];
1616 if( code
!=prevcode
){
1618 zResult
[j
++] = code
+ '0';
1628 sqlite3_result_text(context
, zResult
, 4, SQLITE_TRANSIENT
);
1630 /* IMP: R-64894-50321 The string "?000" is returned if the argument
1631 ** is NULL or contains no ASCII alphabetic characters. */
1632 sqlite3_result_text(context
, "?000", 4, SQLITE_STATIC
);
1635 #endif /* SQLITE_SOUNDEX */
1637 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1639 ** A function that loads a shared-library extension then returns NULL.
1641 static void loadExt(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
1642 const char *zFile
= (const char *)sqlite3_value_text(argv
[0]);
1644 sqlite3
*db
= sqlite3_context_db_handle(context
);
1647 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
1648 ** flag is set. See the sqlite3_enable_load_extension() API.
1650 if( (db
->flags
& SQLITE_LoadExtFunc
)==0 ){
1651 sqlite3_result_error(context
, "not authorized", -1);
1656 zProc
= (const char *)sqlite3_value_text(argv
[1]);
1660 if( zFile
&& sqlite3_load_extension(db
, zFile
, zProc
, &zErrMsg
) ){
1661 sqlite3_result_error(context
, zErrMsg
, -1);
1662 sqlite3_free(zErrMsg
);
1669 ** An instance of the following structure holds the context of a
1670 ** sum() or avg() aggregate computation.
1672 typedef struct SumCtx SumCtx
;
1674 double rSum
; /* Running sum as as a double */
1675 double rErr
; /* Error term for Kahan-Babushka-Neumaier summation */
1676 i64 iSum
; /* Running sum as a signed integer */
1677 i64 cnt
; /* Number of elements summed */
1678 u8 approx
; /* True if any non-integer value was input to the sum */
1679 u8 ovrfl
; /* Integer overflow seen */
1683 ** Do one step of the Kahan-Babushka-Neumaier summation.
1685 ** https://en.wikipedia.org/wiki/Kahan_summation_algorithm
1687 ** Variables are marked "volatile" to defeat c89 x86 floating point
1688 ** optimizations can mess up this algorithm.
1690 static void kahanBabuskaNeumaierStep(
1691 volatile SumCtx
*pSum
,
1694 volatile double s
= pSum
->rSum
;
1695 volatile double t
= s
+ r
;
1696 if( fabs(s
) > fabs(r
) ){
1697 pSum
->rErr
+= (s
- t
) + r
;
1699 pSum
->rErr
+= (r
- t
) + s
;
1705 ** Add a (possibly large) integer to the running sum.
1707 static void kahanBabuskaNeumaierStepInt64(volatile SumCtx
*pSum
, i64 iVal
){
1708 if( iVal
<=-4503599627370496LL || iVal
>=+4503599627370496LL ){
1712 kahanBabuskaNeumaierStep(pSum
, iBig
);
1713 kahanBabuskaNeumaierStep(pSum
, iSm
);
1715 kahanBabuskaNeumaierStep(pSum
, (double)iVal
);
1720 ** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer
1722 static void kahanBabuskaNeumaierInit(
1726 if( iVal
<=-4503599627370496LL || iVal
>=+4503599627370496LL ){
1727 i64 iSm
= iVal
% 16384;
1728 p
->rSum
= (double)(iVal
- iSm
);
1729 p
->rErr
= (double)iSm
;
1731 p
->rSum
= (double)iVal
;
1737 ** Routines used to compute the sum, average, and total.
1739 ** The SUM() function follows the (broken) SQL standard which means
1740 ** that it returns NULL if it sums over no inputs. TOTAL returns
1741 ** 0.0 in that case. In addition, TOTAL always returns a float where
1742 ** SUM might return an integer if it never encounters a floating point
1743 ** value. TOTAL never fails, but SUM might through an exception if
1744 ** it overflows an integer.
1746 static void sumStep(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
1750 UNUSED_PARAMETER(argc
);
1751 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
1752 type
= sqlite3_value_numeric_type(argv
[0]);
1753 if( p
&& type
!=SQLITE_NULL
){
1756 if( type
!=SQLITE_INTEGER
){
1757 kahanBabuskaNeumaierInit(p
, p
->iSum
);
1759 kahanBabuskaNeumaierStep(p
, sqlite3_value_double(argv
[0]));
1762 if( sqlite3AddInt64(&x
, sqlite3_value_int64(argv
[0]))==0 ){
1766 kahanBabuskaNeumaierInit(p
, p
->iSum
);
1768 kahanBabuskaNeumaierStepInt64(p
, sqlite3_value_int64(argv
[0]));
1772 if( type
==SQLITE_INTEGER
){
1773 kahanBabuskaNeumaierStepInt64(p
, sqlite3_value_int64(argv
[0]));
1776 kahanBabuskaNeumaierStep(p
, sqlite3_value_double(argv
[0]));
1781 #ifndef SQLITE_OMIT_WINDOWFUNC
1782 static void sumInverse(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
1786 UNUSED_PARAMETER(argc
);
1787 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
1788 type
= sqlite3_value_numeric_type(argv
[0]);
1789 /* p is always non-NULL because sumStep() will have been called first
1790 ** to initialize it */
1791 if( ALWAYS(p
) && type
!=SQLITE_NULL
){
1795 p
->iSum
-= sqlite3_value_int64(argv
[0]);
1796 }else if( type
==SQLITE_INTEGER
){
1797 i64 iVal
= sqlite3_value_int64(argv
[0]);
1798 if( iVal
!=SMALLEST_INT64
){
1799 kahanBabuskaNeumaierStepInt64(p
, -iVal
);
1801 kahanBabuskaNeumaierStepInt64(p
, LARGEST_INT64
);
1802 kahanBabuskaNeumaierStepInt64(p
, 1);
1805 kahanBabuskaNeumaierStep(p
, -sqlite3_value_double(argv
[0]));
1810 # define sumInverse 0
1811 #endif /* SQLITE_OMIT_WINDOWFUNC */
1812 static void sumFinalize(sqlite3_context
*context
){
1814 p
= sqlite3_aggregate_context(context
, 0);
1815 if( p
&& p
->cnt
>0 ){
1818 sqlite3_result_error(context
,"integer overflow",-1);
1819 }else if( !sqlite3IsNaN(p
->rErr
) ){
1820 sqlite3_result_double(context
, p
->rSum
+p
->rErr
);
1822 sqlite3_result_double(context
, p
->rSum
);
1825 sqlite3_result_int64(context
, p
->iSum
);
1829 static void avgFinalize(sqlite3_context
*context
){
1831 p
= sqlite3_aggregate_context(context
, 0);
1832 if( p
&& p
->cnt
>0 ){
1836 if( !sqlite3IsNaN(p
->rErr
) ) r
+= p
->rErr
;
1838 r
= (double)(p
->iSum
);
1840 sqlite3_result_double(context
, r
/(double)p
->cnt
);
1843 static void totalFinalize(sqlite3_context
*context
){
1846 p
= sqlite3_aggregate_context(context
, 0);
1850 if( !sqlite3IsNaN(p
->rErr
) ) r
+= p
->rErr
;
1852 r
= (double)(p
->iSum
);
1855 sqlite3_result_double(context
, r
);
1859 ** The following structure keeps track of state information for the
1860 ** count() aggregate function.
1862 typedef struct CountCtx CountCtx
;
1866 int bInverse
; /* True if xInverse() ever called */
1871 ** Routines to implement the count() aggregate function.
1873 static void countStep(sqlite3_context
*context
, int argc
, sqlite3_value
**argv
){
1875 p
= sqlite3_aggregate_context(context
, sizeof(*p
));
1876 if( (argc
==0 || SQLITE_NULL
!=sqlite3_value_type(argv
[0])) && p
){
1880 #ifndef SQLITE_OMIT_DEPRECATED
1881 /* The sqlite3_aggregate_count() function is deprecated. But just to make
1882 ** sure it still operates correctly, verify that its count agrees with our
1883 ** internal count when using count(*) and when the total count can be
1884 ** expressed as a 32-bit integer. */
1885 assert( argc
==1 || p
==0 || p
->n
>0x7fffffff || p
->bInverse
1886 || p
->n
==sqlite3_aggregate_count(context
) );
1889 static void countFinalize(sqlite3_context
*context
){
1891 p
= sqlite3_aggregate_context(context
, 0);
1892 sqlite3_result_int64(context
, p
? p
->n
: 0);
1894 #ifndef SQLITE_OMIT_WINDOWFUNC
1895 static void countInverse(sqlite3_context
*ctx
, int argc
, sqlite3_value
**argv
){
1897 p
= sqlite3_aggregate_context(ctx
, sizeof(*p
));
1898 /* p is always non-NULL since countStep() will have been called first */
1899 if( (argc
==0 || SQLITE_NULL
!=sqlite3_value_type(argv
[0])) && ALWAYS(p
) ){
1907 # define countInverse 0
1908 #endif /* SQLITE_OMIT_WINDOWFUNC */
1911 ** Routines to implement min() and max() aggregate functions.
1913 static void minmaxStep(
1914 sqlite3_context
*context
,
1916 sqlite3_value
**argv
1918 Mem
*pArg
= (Mem
*)argv
[0];
1920 UNUSED_PARAMETER(NotUsed
);
1922 pBest
= (Mem
*)sqlite3_aggregate_context(context
, sizeof(*pBest
));
1923 if( !pBest
) return;
1925 if( sqlite3_value_type(pArg
)==SQLITE_NULL
){
1926 if( pBest
->flags
) sqlite3SkipAccumulatorLoad(context
);
1927 }else if( pBest
->flags
){
1930 CollSeq
*pColl
= sqlite3GetFuncCollSeq(context
);
1931 /* This step function is used for both the min() and max() aggregates,
1932 ** the only difference between the two being that the sense of the
1933 ** comparison is inverted. For the max() aggregate, the
1934 ** sqlite3_user_data() function returns (void *)-1. For min() it
1935 ** returns (void *)db, where db is the sqlite3* database pointer.
1936 ** Therefore the next statement sets variable 'max' to 1 for the max()
1937 ** aggregate, or 0 for min().
1939 max
= sqlite3_user_data(context
)!=0;
1940 cmp
= sqlite3MemCompare(pBest
, pArg
, pColl
);
1941 if( (max
&& cmp
<0) || (!max
&& cmp
>0) ){
1942 sqlite3VdbeMemCopy(pBest
, pArg
);
1944 sqlite3SkipAccumulatorLoad(context
);
1947 pBest
->db
= sqlite3_context_db_handle(context
);
1948 sqlite3VdbeMemCopy(pBest
, pArg
);
1951 static void minMaxValueFinalize(sqlite3_context
*context
, int bValue
){
1952 sqlite3_value
*pRes
;
1953 pRes
= (sqlite3_value
*)sqlite3_aggregate_context(context
, 0);
1956 sqlite3_result_value(context
, pRes
);
1958 if( bValue
==0 ) sqlite3VdbeMemRelease(pRes
);
1961 #ifndef SQLITE_OMIT_WINDOWFUNC
1962 static void minMaxValue(sqlite3_context
*context
){
1963 minMaxValueFinalize(context
, 1);
1966 # define minMaxValue 0
1967 #endif /* SQLITE_OMIT_WINDOWFUNC */
1968 static void minMaxFinalize(sqlite3_context
*context
){
1969 minMaxValueFinalize(context
, 0);
1973 ** group_concat(EXPR, ?SEPARATOR?)
1975 ** The SEPARATOR goes before the EXPR string. This is tragic. The
1976 ** groupConcatInverse() implementation would have been easier if the
1977 ** SEPARATOR were appended after EXPR. And the order is undocumented,
1978 ** so we could change it, in theory. But the old behavior has been
1979 ** around for so long that we dare not, for fear of breaking something.
1982 StrAccum str
; /* The accumulated concatenation */
1983 #ifndef SQLITE_OMIT_WINDOWFUNC
1984 int nAccum
; /* Number of strings presently concatenated */
1985 int nFirstSepLength
; /* Used to detect separator length change */
1986 /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
1987 ** stored as actually incorporated into presently accumulated result.
1988 ** (Hence, its slots in use number nAccum-1 between method calls.)
1989 ** If pnSepLengths==0, nFirstSepLength is the length used throughout.
1995 static void groupConcatStep(
1996 sqlite3_context
*context
,
1998 sqlite3_value
**argv
2001 GroupConcatCtx
*pGCC
;
2004 assert( argc
==1 || argc
==2 );
2005 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
) return;
2006 pGCC
= (GroupConcatCtx
*)sqlite3_aggregate_context(context
, sizeof(*pGCC
));
2008 sqlite3
*db
= sqlite3_context_db_handle(context
);
2009 int firstTerm
= pGCC
->str
.mxAlloc
==0;
2010 pGCC
->str
.mxAlloc
= db
->aLimit
[SQLITE_LIMIT_LENGTH
];
2013 sqlite3_str_appendchar(&pGCC
->str
, 1, ',');
2015 #ifndef SQLITE_OMIT_WINDOWFUNC
2017 pGCC
->nFirstSepLength
= 1;
2020 }else if( !firstTerm
){
2021 zSep
= (char*)sqlite3_value_text(argv
[1]);
2022 nSep
= sqlite3_value_bytes(argv
[1]);
2024 sqlite3_str_append(&pGCC
->str
, zSep
, nSep
);
2026 #ifndef SQLITE_OMIT_WINDOWFUNC
2030 if( nSep
!= pGCC
->nFirstSepLength
|| pGCC
->pnSepLengths
!= 0 ){
2031 int *pnsl
= pGCC
->pnSepLengths
;
2033 /* First separator length variation seen, start tracking them. */
2034 pnsl
= (int*)sqlite3_malloc64((pGCC
->nAccum
+1) * sizeof(int));
2036 int i
= 0, nA
= pGCC
->nAccum
-1;
2037 while( i
<nA
) pnsl
[i
++] = pGCC
->nFirstSepLength
;
2040 pnsl
= (int*)sqlite3_realloc64(pnsl
, pGCC
->nAccum
* sizeof(int));
2043 if( ALWAYS(pGCC
->nAccum
>0) ){
2044 pnsl
[pGCC
->nAccum
-1] = nSep
;
2046 pGCC
->pnSepLengths
= pnsl
;
2048 sqlite3StrAccumSetError(&pGCC
->str
, SQLITE_NOMEM
);
2053 #ifndef SQLITE_OMIT_WINDOWFUNC
2055 pGCC
->nFirstSepLength
= sqlite3_value_bytes(argv
[1]);
2059 zVal
= (char*)sqlite3_value_text(argv
[0]);
2060 nVal
= sqlite3_value_bytes(argv
[0]);
2061 if( zVal
) sqlite3_str_append(&pGCC
->str
, zVal
, nVal
);
2065 #ifndef SQLITE_OMIT_WINDOWFUNC
2066 static void groupConcatInverse(
2067 sqlite3_context
*context
,
2069 sqlite3_value
**argv
2071 GroupConcatCtx
*pGCC
;
2072 assert( argc
==1 || argc
==2 );
2073 (void)argc
; /* Suppress unused parameter warning */
2074 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
) return;
2075 pGCC
= (GroupConcatCtx
*)sqlite3_aggregate_context(context
, sizeof(*pGCC
));
2076 /* pGCC is always non-NULL since groupConcatStep() will have always
2077 ** run first to initialize it */
2080 /* Must call sqlite3_value_text() to convert the argument into text prior
2081 ** to invoking sqlite3_value_bytes(), in case the text encoding is UTF16 */
2082 (void)sqlite3_value_text(argv
[0]);
2083 nVS
= sqlite3_value_bytes(argv
[0]);
2085 if( pGCC
->pnSepLengths
!=0 ){
2086 assert(pGCC
->nAccum
>= 0);
2087 if( pGCC
->nAccum
>0 ){
2088 nVS
+= *pGCC
->pnSepLengths
;
2089 memmove(pGCC
->pnSepLengths
, pGCC
->pnSepLengths
+1,
2090 (pGCC
->nAccum
-1)*sizeof(int));
2093 /* If removing single accumulated string, harmlessly over-do. */
2094 nVS
+= pGCC
->nFirstSepLength
;
2096 if( nVS
>=(int)pGCC
->str
.nChar
){
2097 pGCC
->str
.nChar
= 0;
2099 pGCC
->str
.nChar
-= nVS
;
2100 memmove(pGCC
->str
.zText
, &pGCC
->str
.zText
[nVS
], pGCC
->str
.nChar
);
2102 if( pGCC
->str
.nChar
==0 ){
2103 pGCC
->str
.mxAlloc
= 0;
2104 sqlite3_free(pGCC
->pnSepLengths
);
2105 pGCC
->pnSepLengths
= 0;
2110 # define groupConcatInverse 0
2111 #endif /* SQLITE_OMIT_WINDOWFUNC */
2112 static void groupConcatFinalize(sqlite3_context
*context
){
2113 GroupConcatCtx
*pGCC
2114 = (GroupConcatCtx
*)sqlite3_aggregate_context(context
, 0);
2116 sqlite3ResultStrAccum(context
, &pGCC
->str
);
2117 #ifndef SQLITE_OMIT_WINDOWFUNC
2118 sqlite3_free(pGCC
->pnSepLengths
);
2122 #ifndef SQLITE_OMIT_WINDOWFUNC
2123 static void groupConcatValue(sqlite3_context
*context
){
2124 GroupConcatCtx
*pGCC
2125 = (GroupConcatCtx
*)sqlite3_aggregate_context(context
, 0);
2127 StrAccum
*pAccum
= &pGCC
->str
;
2128 if( pAccum
->accError
==SQLITE_TOOBIG
){
2129 sqlite3_result_error_toobig(context
);
2130 }else if( pAccum
->accError
==SQLITE_NOMEM
){
2131 sqlite3_result_error_nomem(context
);
2133 const char *zText
= sqlite3_str_value(pAccum
);
2134 sqlite3_result_text(context
, zText
, pAccum
->nChar
, SQLITE_TRANSIENT
);
2139 # define groupConcatValue 0
2140 #endif /* SQLITE_OMIT_WINDOWFUNC */
2143 ** This routine does per-connection function registration. Most
2144 ** of the built-in functions above are part of the global function set.
2145 ** This routine only deals with those that are not global.
2147 void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3
*db
){
2148 int rc
= sqlite3_overload_function(db
, "MATCH", 2);
2149 assert( rc
==SQLITE_NOMEM
|| rc
==SQLITE_OK
);
2150 if( rc
==SQLITE_NOMEM
){
2151 sqlite3OomFault(db
);
2153 /* BEGIN SQLCIPHER */
2154 #ifdef SQLITE_HAS_CODEC
2156 extern void sqlcipher_exportFunc(sqlite3_context
*, int, sqlite3_value
**);
2157 sqlite3CreateFunc(db
, "sqlcipher_export", -1, SQLITE_TEXT
, 0, sqlcipher_exportFunc
, 0, 0, 0, 0, 0);
2159 #ifdef SQLCIPHER_EXT
2160 #include "sqlcipher_funcs_init.h"
2167 ** Re-register the built-in LIKE functions. The caseSensitive
2168 ** parameter determines whether or not the LIKE operator is case
2171 void sqlite3RegisterLikeFunctions(sqlite3
*db
, int caseSensitive
){
2173 struct compareInfo
*pInfo
;
2176 if( caseSensitive
){
2177 pInfo
= (struct compareInfo
*)&likeInfoAlt
;
2178 flags
= SQLITE_FUNC_LIKE
| SQLITE_FUNC_CASE
;
2180 pInfo
= (struct compareInfo
*)&likeInfoNorm
;
2181 flags
= SQLITE_FUNC_LIKE
;
2183 for(nArg
=2; nArg
<=3; nArg
++){
2184 sqlite3CreateFunc(db
, "like", nArg
, SQLITE_UTF8
, pInfo
, likeFunc
,
2186 pDef
= sqlite3FindFunction(db
, "like", nArg
, SQLITE_UTF8
, 0);
2187 pDef
->funcFlags
|= flags
;
2188 pDef
->funcFlags
&= ~SQLITE_FUNC_UNSAFE
;
2193 ** pExpr points to an expression which implements a function. If
2194 ** it is appropriate to apply the LIKE optimization to that function
2195 ** then set aWc[0] through aWc[2] to the wildcard characters and the
2196 ** escape character and then return TRUE. If the function is not a
2197 ** LIKE-style function then return FALSE.
2199 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
2200 ** operator if c is a string literal that is exactly one byte in length.
2201 ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
2202 ** no ESCAPE clause.
2204 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
2205 ** the function (default for LIKE). If the function makes the distinction
2206 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
2209 int sqlite3IsLikeFunction(sqlite3
*db
, Expr
*pExpr
, int *pIsNocase
, char *aWc
){
2213 assert( pExpr
->op
==TK_FUNCTION
);
2214 assert( ExprUseXList(pExpr
) );
2215 if( !pExpr
->x
.pList
){
2218 nExpr
= pExpr
->x
.pList
->nExpr
;
2219 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2220 pDef
= sqlite3FindFunction(db
, pExpr
->u
.zToken
, nExpr
, SQLITE_UTF8
, 0);
2221 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2222 if( pDef
==0 ) return 0;
2224 if( NEVER(pDef
==0) || (pDef
->funcFlags
& SQLITE_FUNC_LIKE
)==0 ){
2228 /* The memcpy() statement assumes that the wildcard characters are
2229 ** the first three statements in the compareInfo structure. The
2230 ** asserts() that follow verify that assumption
2232 memcpy(aWc
, pDef
->pUserData
, 3);
2233 assert( (char*)&likeInfoAlt
== (char*)&likeInfoAlt
.matchAll
);
2234 assert( &((char*)&likeInfoAlt
)[1] == (char*)&likeInfoAlt
.matchOne
);
2235 assert( &((char*)&likeInfoAlt
)[2] == (char*)&likeInfoAlt
.matchSet
);
2240 Expr
*pEscape
= pExpr
->x
.pList
->a
[2].pExpr
;
2242 if( pEscape
->op
!=TK_STRING
) return 0;
2243 assert( !ExprHasProperty(pEscape
, EP_IntValue
) );
2244 zEscape
= pEscape
->u
.zToken
;
2245 if( zEscape
[0]==0 || zEscape
[1]!=0 ) return 0;
2246 if( zEscape
[0]==aWc
[0] ) return 0;
2247 if( zEscape
[0]==aWc
[1] ) return 0;
2248 aWc
[3] = zEscape
[0];
2251 *pIsNocase
= (pDef
->funcFlags
& SQLITE_FUNC_CASE
)==0;
2255 /* Mathematical Constants */
2257 # define M_PI 3.141592653589793238462643383279502884
2260 # define M_LN10 2.302585092994045684017991454684364208
2263 # define M_LN2 0.693147180559945309417232121458176568
2267 /* Extra math functions that require linking with -lm
2269 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2271 ** Implementation SQL functions:
2277 ** The sqlite3_user_data() pointer is a pointer to the libm implementation
2278 ** of the underlying C function.
2280 static void ceilingFunc(
2281 sqlite3_context
*context
,
2283 sqlite3_value
**argv
2286 switch( sqlite3_value_numeric_type(argv
[0]) ){
2287 case SQLITE_INTEGER
: {
2288 sqlite3_result_int64(context
, sqlite3_value_int64(argv
[0]));
2291 case SQLITE_FLOAT
: {
2292 double (*x
)(double) = (double(*)(double))sqlite3_user_data(context
);
2293 sqlite3_result_double(context
, x(sqlite3_value_double(argv
[0])));
2303 ** On some systems, ceil() and floor() are intrinsic function. You are
2304 ** unable to take a pointer to these functions. Hence, we here wrap them
2305 ** in our own actual functions.
2307 static double xCeil(double x
){ return ceil(x
); }
2308 static double xFloor(double x
){ return floor(x
); }
2311 ** Some systems do not have log2() and log10() in their standard math
2314 #if defined(HAVE_LOG10) && HAVE_LOG10==0
2315 # define log10(X) (0.4342944819032517867*log(X))
2317 #if defined(HAVE_LOG2) && HAVE_LOG2==0
2318 # define log2(X) (1.442695040888963456*log(X))
2323 ** Implementation of SQL functions:
2325 ** ln(X) - natural logarithm
2326 ** log(X) - log X base 10
2327 ** log10(X) - log X base 10
2328 ** log(B,X) - log X base B
2330 static void logFunc(
2331 sqlite3_context
*context
,
2333 sqlite3_value
**argv
2336 assert( argc
==1 || argc
==2 );
2337 switch( sqlite3_value_numeric_type(argv
[0]) ){
2338 case SQLITE_INTEGER
:
2340 x
= sqlite3_value_double(argv
[0]);
2341 if( x
<=0.0 ) return;
2347 switch( sqlite3_value_numeric_type(argv
[0]) ){
2348 case SQLITE_INTEGER
:
2351 if( b
<=0.0 ) return;
2352 x
= sqlite3_value_double(argv
[1]);
2353 if( x
<=0.0 ) return;
2360 switch( SQLITE_PTR_TO_INT(sqlite3_user_data(context
)) ){
2372 sqlite3_result_double(context
, ans
);
2376 ** Functions to converts degrees to radians and radians to degrees.
2378 static double degToRad(double x
){ return x
*(M_PI
/180.0); }
2379 static double radToDeg(double x
){ return x
*(180.0/M_PI
); }
2382 ** Implementation of 1-argument SQL math functions:
2384 ** exp(X) - Compute e to the X-th power
2386 static void math1Func(
2387 sqlite3_context
*context
,
2389 sqlite3_value
**argv
2393 double (*x
)(double);
2395 type0
= sqlite3_value_numeric_type(argv
[0]);
2396 if( type0
!=SQLITE_INTEGER
&& type0
!=SQLITE_FLOAT
) return;
2397 v0
= sqlite3_value_double(argv
[0]);
2398 x
= (double(*)(double))sqlite3_user_data(context
);
2400 sqlite3_result_double(context
, ans
);
2404 ** Implementation of 2-argument SQL math functions:
2406 ** power(X,Y) - Compute X to the Y-th power
2408 static void math2Func(
2409 sqlite3_context
*context
,
2411 sqlite3_value
**argv
2415 double (*x
)(double,double);
2417 type0
= sqlite3_value_numeric_type(argv
[0]);
2418 if( type0
!=SQLITE_INTEGER
&& type0
!=SQLITE_FLOAT
) return;
2419 type1
= sqlite3_value_numeric_type(argv
[1]);
2420 if( type1
!=SQLITE_INTEGER
&& type1
!=SQLITE_FLOAT
) return;
2421 v0
= sqlite3_value_double(argv
[0]);
2422 v1
= sqlite3_value_double(argv
[1]);
2423 x
= (double(*)(double,double))sqlite3_user_data(context
);
2425 sqlite3_result_double(context
, ans
);
2429 ** Implementation of 0-argument pi() function.
2432 sqlite3_context
*context
,
2434 sqlite3_value
**argv
2438 sqlite3_result_double(context
, M_PI
);
2441 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2444 ** Implementation of sign(X) function.
2446 static void signFunc(
2447 sqlite3_context
*context
,
2449 sqlite3_value
**argv
2453 UNUSED_PARAMETER(argc
);
2455 type0
= sqlite3_value_numeric_type(argv
[0]);
2456 if( type0
!=SQLITE_INTEGER
&& type0
!=SQLITE_FLOAT
) return;
2457 x
= sqlite3_value_double(argv
[0]);
2458 sqlite3_result_int(context
, x
<0.0 ? -1 : x
>0.0 ? +1 : 0);
2463 ** Implementation of fpdecode(x,y,z) function.
2465 ** x is a real number that is to be decoded. y is the precision.
2466 ** z is the maximum real precision.
2468 static void fpdecodeFunc(
2469 sqlite3_context
*context
,
2471 sqlite3_value
**argv
2477 UNUSED_PARAMETER(argc
);
2479 x
= sqlite3_value_double(argv
[0]);
2480 y
= sqlite3_value_int(argv
[1]);
2481 z
= sqlite3_value_int(argv
[2]);
2482 sqlite3FpDecode(&s
, x
, y
, z
);
2483 if( s
.isSpecial
==2 ){
2484 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "NaN");
2486 sqlite3_snprintf(sizeof(zBuf
), zBuf
, "%c%.*s/%d", s
.sign
, s
.n
, s
.z
, s
.iDP
);
2488 sqlite3_result_text(context
, zBuf
, -1, SQLITE_TRANSIENT
);
2490 #endif /* SQLITE_DEBUG */
2493 ** All of the FuncDef structures in the aBuiltinFunc[] array above
2494 ** to the global function hash table. This occurs at start-time (as
2495 ** a consequence of calling sqlite3_initialize()).
2497 ** After this routine runs
2499 void sqlite3RegisterBuiltinFunctions(void){
2501 ** The following array holds FuncDef structures for all of the functions
2502 ** defined in this file.
2504 ** The array cannot be constant since changes are made to the
2505 ** FuncDef.pHash elements at start-time. The elements of this array
2506 ** are read-only after initialization is complete.
2508 ** For peak efficiency, put the most frequently used function last.
2510 static FuncDef aBuiltinFunc
[] = {
2511 /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
2512 #if !defined(SQLITE_UNTESTABLE)
2513 TEST_FUNC(implies_nonnull_row
, 2, INLINEFUNC_implies_nonnull_row
, 0),
2514 TEST_FUNC(expr_compare
, 2, INLINEFUNC_expr_compare
, 0),
2515 TEST_FUNC(expr_implies_expr
, 2, INLINEFUNC_expr_implies_expr
, 0),
2516 TEST_FUNC(affinity
, 1, INLINEFUNC_affinity
, 0),
2517 #endif /* !defined(SQLITE_UNTESTABLE) */
2518 /***** Regular functions *****/
2519 #ifdef SQLITE_SOUNDEX
2520 FUNCTION(soundex
, 1, 0, 0, soundexFunc
),
2522 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2523 SFUNCTION(load_extension
, 1, 0, 0, loadExt
),
2524 SFUNCTION(load_extension
, 2, 0, 0, loadExt
),
2526 #if SQLITE_USER_AUTHENTICATION
2527 FUNCTION(sqlite_crypt
, 2, 0, 0, sqlite3CryptFunc
),
2529 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
2530 DFUNCTION(sqlite_compileoption_used
,1, 0, 0, compileoptionusedFunc
),
2531 DFUNCTION(sqlite_compileoption_get
, 1, 0, 0, compileoptiongetFunc
),
2532 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
2533 INLINE_FUNC(unlikely
, 1, INLINEFUNC_unlikely
, SQLITE_FUNC_UNLIKELY
),
2534 INLINE_FUNC(likelihood
, 2, INLINEFUNC_unlikely
, SQLITE_FUNC_UNLIKELY
),
2535 INLINE_FUNC(likely
, 1, INLINEFUNC_unlikely
, SQLITE_FUNC_UNLIKELY
),
2536 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
2537 INLINE_FUNC(sqlite_offset
, 1, INLINEFUNC_sqlite_offset
, 0 ),
2539 FUNCTION(ltrim
, 1, 1, 0, trimFunc
),
2540 FUNCTION(ltrim
, 2, 1, 0, trimFunc
),
2541 FUNCTION(rtrim
, 1, 2, 0, trimFunc
),
2542 FUNCTION(rtrim
, 2, 2, 0, trimFunc
),
2543 FUNCTION(trim
, 1, 3, 0, trimFunc
),
2544 FUNCTION(trim
, 2, 3, 0, trimFunc
),
2545 FUNCTION(min
, -1, 0, 1, minmaxFunc
),
2546 FUNCTION(min
, 0, 0, 1, 0 ),
2547 WAGGREGATE(min
, 1, 0, 1, minmaxStep
, minMaxFinalize
, minMaxValue
, 0,
2548 SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
),
2549 FUNCTION(max
, -1, 1, 1, minmaxFunc
),
2550 FUNCTION(max
, 0, 1, 1, 0 ),
2551 WAGGREGATE(max
, 1, 1, 1, minmaxStep
, minMaxFinalize
, minMaxValue
, 0,
2552 SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
),
2553 FUNCTION2(typeof, 1, 0, 0, typeofFunc
, SQLITE_FUNC_TYPEOF
),
2554 FUNCTION2(subtype
, 1, 0, 0, subtypeFunc
, SQLITE_FUNC_TYPEOF
),
2555 FUNCTION2(length
, 1, 0, 0, lengthFunc
, SQLITE_FUNC_LENGTH
),
2556 FUNCTION2(octet_length
, 1, 0, 0, bytelengthFunc
,SQLITE_FUNC_BYTELEN
),
2557 FUNCTION(instr
, 2, 0, 0, instrFunc
),
2558 FUNCTION(printf
, -1, 0, 0, printfFunc
),
2559 FUNCTION(format
, -1, 0, 0, printfFunc
),
2560 FUNCTION(unicode
, 1, 0, 0, unicodeFunc
),
2561 FUNCTION(char, -1, 0, 0, charFunc
),
2562 FUNCTION(abs
, 1, 0, 0, absFunc
),
2564 FUNCTION(fpdecode
, 3, 0, 0, fpdecodeFunc
),
2566 #ifndef SQLITE_OMIT_FLOATING_POINT
2567 FUNCTION(round
, 1, 0, 0, roundFunc
),
2568 FUNCTION(round
, 2, 0, 0, roundFunc
),
2570 FUNCTION(upper
, 1, 0, 0, upperFunc
),
2571 FUNCTION(lower
, 1, 0, 0, lowerFunc
),
2572 FUNCTION(hex
, 1, 0, 0, hexFunc
),
2573 FUNCTION(unhex
, 1, 0, 0, unhexFunc
),
2574 FUNCTION(unhex
, 2, 0, 0, unhexFunc
),
2575 INLINE_FUNC(ifnull
, 2, INLINEFUNC_coalesce
, 0 ),
2576 VFUNCTION(random
, 0, 0, 0, randomFunc
),
2577 VFUNCTION(randomblob
, 1, 0, 0, randomBlob
),
2578 FUNCTION(nullif
, 2, 0, 1, nullifFunc
),
2579 DFUNCTION(sqlite_version
, 0, 0, 0, versionFunc
),
2580 DFUNCTION(sqlite_source_id
, 0, 0, 0, sourceidFunc
),
2581 FUNCTION(sqlite_log
, 2, 0, 0, errlogFunc
),
2582 FUNCTION(quote
, 1, 0, 0, quoteFunc
),
2583 VFUNCTION(last_insert_rowid
, 0, 0, 0, last_insert_rowid
),
2584 VFUNCTION(changes
, 0, 0, 0, changes
),
2585 VFUNCTION(total_changes
, 0, 0, 0, total_changes
),
2586 FUNCTION(replace
, 3, 0, 0, replaceFunc
),
2587 FUNCTION(zeroblob
, 1, 0, 0, zeroblobFunc
),
2588 FUNCTION(substr
, 2, 0, 0, substrFunc
),
2589 FUNCTION(substr
, 3, 0, 0, substrFunc
),
2590 FUNCTION(substring
, 2, 0, 0, substrFunc
),
2591 FUNCTION(substring
, 3, 0, 0, substrFunc
),
2592 WAGGREGATE(sum
, 1,0,0, sumStep
, sumFinalize
, sumFinalize
, sumInverse
, 0),
2593 WAGGREGATE(total
, 1,0,0, sumStep
,totalFinalize
,totalFinalize
,sumInverse
, 0),
2594 WAGGREGATE(avg
, 1,0,0, sumStep
, avgFinalize
, avgFinalize
, sumInverse
, 0),
2595 WAGGREGATE(count
, 0,0,0, countStep
,
2596 countFinalize
, countFinalize
, countInverse
,
2597 SQLITE_FUNC_COUNT
|SQLITE_FUNC_ANYORDER
),
2598 WAGGREGATE(count
, 1,0,0, countStep
,
2599 countFinalize
, countFinalize
, countInverse
, SQLITE_FUNC_ANYORDER
),
2600 WAGGREGATE(group_concat
, 1, 0, 0, groupConcatStep
,
2601 groupConcatFinalize
, groupConcatValue
, groupConcatInverse
, 0),
2602 WAGGREGATE(group_concat
, 2, 0, 0, groupConcatStep
,
2603 groupConcatFinalize
, groupConcatValue
, groupConcatInverse
, 0),
2605 LIKEFUNC(glob
, 2, &globInfo
, SQLITE_FUNC_LIKE
|SQLITE_FUNC_CASE
),
2606 #ifdef SQLITE_CASE_SENSITIVE_LIKE
2607 LIKEFUNC(like
, 2, &likeInfoAlt
, SQLITE_FUNC_LIKE
|SQLITE_FUNC_CASE
),
2608 LIKEFUNC(like
, 3, &likeInfoAlt
, SQLITE_FUNC_LIKE
|SQLITE_FUNC_CASE
),
2610 LIKEFUNC(like
, 2, &likeInfoNorm
, SQLITE_FUNC_LIKE
),
2611 LIKEFUNC(like
, 3, &likeInfoNorm
, SQLITE_FUNC_LIKE
),
2613 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
2614 FUNCTION(unknown
, -1, 0, 0, unknownFunc
),
2616 FUNCTION(coalesce
, 1, 0, 0, 0 ),
2617 FUNCTION(coalesce
, 0, 0, 0, 0 ),
2618 #ifdef SQLITE_ENABLE_MATH_FUNCTIONS
2619 MFUNCTION(ceil
, 1, xCeil
, ceilingFunc
),
2620 MFUNCTION(ceiling
, 1, xCeil
, ceilingFunc
),
2621 MFUNCTION(floor
, 1, xFloor
, ceilingFunc
),
2622 #if SQLITE_HAVE_C99_MATH_FUNCS
2623 MFUNCTION(trunc
, 1, trunc
, ceilingFunc
),
2625 FUNCTION(ln
, 1, 0, 0, logFunc
),
2626 FUNCTION(log
, 1, 1, 0, logFunc
),
2627 FUNCTION(log10
, 1, 1, 0, logFunc
),
2628 FUNCTION(log2
, 1, 2, 0, logFunc
),
2629 FUNCTION(log
, 2, 0, 0, logFunc
),
2630 MFUNCTION(exp
, 1, exp
, math1Func
),
2631 MFUNCTION(pow
, 2, pow
, math2Func
),
2632 MFUNCTION(power
, 2, pow
, math2Func
),
2633 MFUNCTION(mod
, 2, fmod
, math2Func
),
2634 MFUNCTION(acos
, 1, acos
, math1Func
),
2635 MFUNCTION(asin
, 1, asin
, math1Func
),
2636 MFUNCTION(atan
, 1, atan
, math1Func
),
2637 MFUNCTION(atan2
, 2, atan2
, math2Func
),
2638 MFUNCTION(cos
, 1, cos
, math1Func
),
2639 MFUNCTION(sin
, 1, sin
, math1Func
),
2640 MFUNCTION(tan
, 1, tan
, math1Func
),
2641 MFUNCTION(cosh
, 1, cosh
, math1Func
),
2642 MFUNCTION(sinh
, 1, sinh
, math1Func
),
2643 MFUNCTION(tanh
, 1, tanh
, math1Func
),
2644 #if SQLITE_HAVE_C99_MATH_FUNCS
2645 MFUNCTION(acosh
, 1, acosh
, math1Func
),
2646 MFUNCTION(asinh
, 1, asinh
, math1Func
),
2647 MFUNCTION(atanh
, 1, atanh
, math1Func
),
2649 MFUNCTION(sqrt
, 1, sqrt
, math1Func
),
2650 MFUNCTION(radians
, 1, degToRad
, math1Func
),
2651 MFUNCTION(degrees
, 1, radToDeg
, math1Func
),
2652 FUNCTION(pi
, 0, 0, 0, piFunc
),
2653 #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */
2654 FUNCTION(sign
, 1, 0, 0, signFunc
),
2655 INLINE_FUNC(coalesce
, -1, INLINEFUNC_coalesce
, 0 ),
2656 INLINE_FUNC(iif
, 3, INLINEFUNC_iif
, 0 ),
2658 #ifndef SQLITE_OMIT_ALTERTABLE
2659 sqlite3AlterFunctions();
2661 sqlite3WindowFunctions();
2662 sqlite3RegisterDateTimeFunctions();
2663 sqlite3RegisterJsonFunctions();
2664 sqlite3InsertBuiltinFuncs(aBuiltinFunc
, ArraySize(aBuiltinFunc
));
2666 #if 0 /* Enable to print out how the built-in functions are hashed */
2670 for(i
=0; i
<SQLITE_FUNC_HASH_SZ
; i
++){
2671 printf("FUNC-HASH %02d:", i
);
2672 for(p
=sqlite3BuiltinFunctions
.a
[i
]; p
; p
=p
->u
.pHash
){
2673 int n
= sqlite3Strlen30(p
->zName
);
2674 int h
= p
->zName
[0] + n
;
2675 assert( p
->funcFlags
& SQLITE_FUNC_BUILTIN
);
2676 printf(" %s(%d)", p
->zName
, h
);