blob: 10f0e089051cd5fe38b8825feee5c5728341afea [file] [log] [blame]
drhdc04c582002-02-24 01:55:15 +00001/*
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**
drh771d8c32003-08-09 21:32:28 +000019** $Id: func.c,v 1.27 2003/08/09 21:32:28 drh Exp $
drhdc04c582002-02-24 01:55:15 +000020*/
21#include <ctype.h>
drhd3a149e2002-02-24 17:12:53 +000022#include <math.h>
23#include <stdlib.h>
drh0bce8352002-02-28 00:41:10 +000024#include <assert.h>
25#include "sqliteInt.h"
drh771d8c32003-08-09 21:32:28 +000026#include "os.h"
drh0bce8352002-02-28 00:41:10 +000027
28/*
29** Implementation of the non-aggregate min() and max() functions
30*/
31static void minFunc(sqlite_func *context, int argc, const char **argv){
32 const char *zBest;
33 int i;
34
drh89425d52002-02-28 03:04:48 +000035 if( argc==0 ) return;
drh0bce8352002-02-28 00:41:10 +000036 zBest = argv[0];
drh8912d102002-05-26 21:34:58 +000037 if( zBest==0 ) return;
drh0bce8352002-02-28 00:41:10 +000038 for(i=1; i<argc; i++){
drh8912d102002-05-26 21:34:58 +000039 if( argv[i]==0 ) return;
drh0bce8352002-02-28 00:41:10 +000040 if( sqliteCompare(argv[i], zBest)<0 ){
41 zBest = argv[i];
42 }
43 }
44 sqlite_set_result_string(context, zBest, -1);
45}
46static void maxFunc(sqlite_func *context, int argc, const char **argv){
47 const char *zBest;
48 int i;
49
drh89425d52002-02-28 03:04:48 +000050 if( argc==0 ) return;
drh0bce8352002-02-28 00:41:10 +000051 zBest = argv[0];
drh8912d102002-05-26 21:34:58 +000052 if( zBest==0 ) return;
drh0bce8352002-02-28 00:41:10 +000053 for(i=1; i<argc; i++){
drh8912d102002-05-26 21:34:58 +000054 if( argv[i]==0 ) return;
drh0bce8352002-02-28 00:41:10 +000055 if( sqliteCompare(argv[i], zBest)>0 ){
56 zBest = argv[i];
57 }
58 }
59 sqlite_set_result_string(context, zBest, -1);
60}
61
62/*
63** Implementation of the length() function
64*/
65static void lengthFunc(sqlite_func *context, int argc, const char **argv){
66 const char *z;
67 int len;
68
69 assert( argc==1 );
70 z = argv[0];
drh8912d102002-05-26 21:34:58 +000071 if( z==0 ) return;
drh0bce8352002-02-28 00:41:10 +000072#ifdef SQLITE_UTF8
drh8912d102002-05-26 21:34:58 +000073 for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
drh0bce8352002-02-28 00:41:10 +000074#else
drh8912d102002-05-26 21:34:58 +000075 len = strlen(z);
drh0bce8352002-02-28 00:41:10 +000076#endif
drh0bce8352002-02-28 00:41:10 +000077 sqlite_set_result_int(context, len);
78}
79
80/*
81** Implementation of the abs() function
82*/
83static void absFunc(sqlite_func *context, int argc, const char **argv){
84 const char *z;
85 assert( argc==1 );
86 z = argv[0];
drh8912d102002-05-26 21:34:58 +000087 if( z==0 ) return;
88 if( z[0]=='-' && isdigit(z[1]) ) z++;
drh0bce8352002-02-28 00:41:10 +000089 sqlite_set_result_string(context, z, -1);
90}
91
92/*
93** Implementation of the substr() function
94*/
95static void substrFunc(sqlite_func *context, int argc, const char **argv){
96 const char *z;
97#ifdef SQLITE_UTF8
98 const char *z2;
99 int i;
100#endif
101 int p1, p2, len;
102 assert( argc==3 );
103 z = argv[0];
104 if( z==0 ) return;
105 p1 = atoi(argv[1]?argv[1]:0);
106 p2 = atoi(argv[2]?argv[2]:0);
107#ifdef SQLITE_UTF8
drh47c8a672002-02-28 04:00:12 +0000108 for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
drh0bce8352002-02-28 00:41:10 +0000109#else
110 len = strlen(z);
111#endif
112 if( p1<0 ){
drh89425d52002-02-28 03:04:48 +0000113 p1 += len;
drh653bc752002-02-28 03:31:10 +0000114 if( p1<0 ){
115 p2 += p1;
116 p1 = 0;
117 }
drh0bce8352002-02-28 00:41:10 +0000118 }else if( p1>0 ){
119 p1--;
120 }
121 if( p1+p2>len ){
122 p2 = len-p1;
123 }
124#ifdef SQLITE_UTF8
125 for(i=0; i<p1; i++){
126 assert( z[i] );
drh47c8a672002-02-28 04:00:12 +0000127 if( (z[i]&0xc0)==0x80 ) p1++;
drh0bce8352002-02-28 00:41:10 +0000128 }
drh47c8a672002-02-28 04:00:12 +0000129 while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
drh0bce8352002-02-28 00:41:10 +0000130 for(; i<p1+p2; i++){
131 assert( z[i] );
drh47c8a672002-02-28 04:00:12 +0000132 if( (z[i]&0xc0)==0x80 ) p2++;
drh0bce8352002-02-28 00:41:10 +0000133 }
drh47c8a672002-02-28 04:00:12 +0000134 while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
drh0bce8352002-02-28 00:41:10 +0000135#endif
drh653bc752002-02-28 03:31:10 +0000136 if( p2<0 ) p2 = 0;
drh0bce8352002-02-28 00:41:10 +0000137 sqlite_set_result_string(context, &z[p1], p2);
138}
139
140/*
141** Implementation of the round() function
142*/
143static void roundFunc(sqlite_func *context, int argc, const char **argv){
144 int n;
145 double r;
146 char zBuf[100];
147 assert( argc==1 || argc==2 );
drh8912d102002-05-26 21:34:58 +0000148 if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
149 n = argc==2 ? atoi(argv[1]) : 0;
drh0bce8352002-02-28 00:41:10 +0000150 if( n>30 ) n = 30;
151 if( n<0 ) n = 0;
drh8912d102002-05-26 21:34:58 +0000152 r = atof(argv[0]);
drh0bce8352002-02-28 00:41:10 +0000153 sprintf(zBuf,"%.*f",n,r);
154 sqlite_set_result_string(context, zBuf, -1);
155}
drhdc04c582002-02-24 01:55:15 +0000156
157/*
158** Implementation of the upper() and lower() SQL functions.
159*/
drh1350b032002-02-27 19:00:20 +0000160static void upperFunc(sqlite_func *context, int argc, const char **argv){
drhdc04c582002-02-24 01:55:15 +0000161 char *z;
162 int i;
163 if( argc<1 || argv[0]==0 ) return;
164 z = sqlite_set_result_string(context, argv[0], -1);
165 if( z==0 ) return;
166 for(i=0; z[i]; i++){
167 if( islower(z[i]) ) z[i] = toupper(z[i]);
168 }
169}
drh1350b032002-02-27 19:00:20 +0000170static void lowerFunc(sqlite_func *context, int argc, const char **argv){
drhdc04c582002-02-24 01:55:15 +0000171 char *z;
172 int i;
173 if( argc<1 || argv[0]==0 ) return;
174 z = sqlite_set_result_string(context, argv[0], -1);
175 if( z==0 ) return;
176 for(i=0; z[i]; i++){
177 if( isupper(z[i]) ) z[i] = tolower(z[i]);
178 }
179}
180
181/*
drhfbc99082002-02-28 03:14:18 +0000182** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
183** All three do the same thing. They return the first argument
184** non-NULL argument.
drh3212e182002-02-28 00:46:26 +0000185*/
186static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
drhfbc99082002-02-28 03:14:18 +0000187 int i;
188 for(i=0; i<argc; i++){
189 if( argv[i] ){
190 sqlite_set_result_string(context, argv[i], -1);
191 break;
192 }
193 }
drh3212e182002-02-28 00:46:26 +0000194}
195
196/*
drhf9ffac92002-03-02 19:00:31 +0000197** Implementation of random(). Return a random integer.
198*/
199static void randomFunc(sqlite_func *context, int argc, const char **argv){
200 sqlite_set_result_int(context, sqliteRandomInteger());
201}
202
203/*
drh6ed41ad2002-04-06 14:10:47 +0000204** Implementation of the last_insert_rowid() SQL function. The return
205** value is the same as the sqlite_last_insert_rowid() API function.
206*/
drh0ac65892002-04-20 14:24:41 +0000207static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
drh6ed41ad2002-04-06 14:10:47 +0000208 sqlite *db = sqlite_user_data(context);
209 sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
210}
211
212/*
drh0ac65892002-04-20 14:24:41 +0000213** Implementation of the like() SQL function. This function implements
214** the build-in LIKE operator. The first argument to the function is the
215** string and the second argument is the pattern. So, the SQL statements:
216**
217** A LIKE B
218**
219** is implemented as like(A,B).
220*/
221static void likeFunc(sqlite_func *context, int arg, const char **argv){
drh8912d102002-05-26 21:34:58 +0000222 if( argv[0]==0 || argv[1]==0 ) return;
223 sqlite_set_result_int(context, sqliteLikeCompare(argv[0], argv[1]));
drh0ac65892002-04-20 14:24:41 +0000224}
225
226/*
227** Implementation of the glob() SQL function. This function implements
228** the build-in GLOB operator. The first argument to the function is the
229** string and the second argument is the pattern. So, the SQL statements:
230**
231** A GLOB B
232**
233** is implemented as glob(A,B).
234*/
235static void globFunc(sqlite_func *context, int arg, const char **argv){
drh8912d102002-05-26 21:34:58 +0000236 if( argv[0]==0 || argv[1]==0 ) return;
237 sqlite_set_result_int(context, sqliteGlobCompare(argv[0], argv[1]));
238}
239
240/*
241** Implementation of the NULLIF(x,y) function. The result is the first
242** argument if the arguments are different. The result is NULL if the
243** arguments are equal to each other.
244*/
245static void nullifFunc(sqlite_func *context, int argc, const char **argv){
246 if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
247 sqlite_set_result_string(context, argv[0], -1);
248 }
drh0ac65892002-04-20 14:24:41 +0000249}
250
drh647cb0e2002-11-04 19:32:25 +0000251/*
252** Implementation of the VERSION(*) function. The result is the version
253** of the SQLite library that is running.
254*/
255static void versionFunc(sqlite_func *context, int argc, const char **argv){
256 sqlite_set_result_string(context, sqlite_version, -1);
257}
258
drhd24cc422003-03-27 12:51:24 +0000259#ifdef SQLITE_SOUNDEX
260/*
261** Compute the soundex encoding of a word.
262*/
263static void soundexFunc(sqlite_func *context, int argc, const char **argv){
264 char zResult[8];
265 const char *zIn;
266 int i, j;
267 static const unsigned char iCode[] = {
268 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
269 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
270 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
273 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
274 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
275 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
276 };
277 assert( argc==1 );
278 zIn = argv[0];
279 for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
280 if( zIn[i] ){
281 zResult[0] = toupper(zIn[i]);
282 for(j=1; j<4 && zIn[i]; i++){
283 int code = iCode[zIn[i]&0x7f];
284 if( code>0 ){
285 zResult[j++] = code + '0';
286 }
287 }
288 while( j<4 ){
289 zResult[j++] = '0';
290 }
291 zResult[j] = 0;
292 sqlite_set_result_string(context, zResult, 4);
293 }else{
drh937dd842003-06-28 16:20:22 +0000294 sqlite_set_result_string(context, "?000", 4);
drhd24cc422003-03-27 12:51:24 +0000295 }
296}
297#endif
298
drh193a6b42002-07-07 16:52:46 +0000299#ifdef SQLITE_TEST
300/*
301** This function generates a string of random characters. Used for
302** generating test data.
303*/
304static void randStr(sqlite_func *context, int argc, const char **argv){
305 static const char zSrc[] =
306 "abcdefghijklmnopqrstuvwxyz"
307 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
308 "0123456789"
309 ".-!,:*^+=_|?/<> ";
310 int iMin, iMax, n, r, i;
311 char zBuf[1000];
312 if( argc>=1 ){
313 iMin = atoi(argv[0]);
314 if( iMin<0 ) iMin = 0;
315 if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
316 }else{
317 iMin = 1;
318 }
319 if( argc>=2 ){
320 iMax = atoi(argv[1]);
321 if( iMax<iMin ) iMax = iMin;
322 if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf);
323 }else{
324 iMax = 50;
325 }
326 n = iMin;
327 if( iMax>iMin ){
drh39581962003-05-13 01:52:31 +0000328 r = sqliteRandomInteger() & 0x7fffffff;
drh193a6b42002-07-07 16:52:46 +0000329 n += r%(iMax + 1 - iMin);
330 }
331 r = 0;
332 for(i=0; i<n; i++){
333 r = (r + sqliteRandomByte())% (sizeof(zSrc)-1);
334 zBuf[i] = zSrc[r];
335 }
336 zBuf[n] = 0;
337 sqlite_set_result_string(context, zBuf, n);
338}
339#endif
340
drh0ac65892002-04-20 14:24:41 +0000341/*
drhd3a149e2002-02-24 17:12:53 +0000342** An instance of the following structure holds the context of a
drhdd5baa92002-02-27 19:50:59 +0000343** sum() or avg() aggregate computation.
344*/
345typedef struct SumCtx SumCtx;
346struct SumCtx {
347 double sum; /* Sum of terms */
drh739105c2002-05-29 23:22:23 +0000348 int cnt; /* Number of elements summed */
drhdd5baa92002-02-27 19:50:59 +0000349};
350
351/*
352** Routines used to compute the sum or average.
353*/
354static void sumStep(sqlite_func *context, int argc, const char **argv){
355 SumCtx *p;
drhdd5baa92002-02-27 19:50:59 +0000356 if( argc<1 ) return;
357 p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000358 if( p && argv[0] ){
359 p->sum += atof(argv[0]);
360 p->cnt++;
361 }
drhdd5baa92002-02-27 19:50:59 +0000362}
363static void sumFinalize(sqlite_func *context){
364 SumCtx *p;
365 p = sqlite_aggregate_context(context, sizeof(*p));
drh89425d52002-02-28 03:04:48 +0000366 sqlite_set_result_double(context, p ? p->sum : 0.0);
drhdd5baa92002-02-27 19:50:59 +0000367}
368static void avgFinalize(sqlite_func *context){
369 SumCtx *p;
drhdd5baa92002-02-27 19:50:59 +0000370 p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000371 if( p && p->cnt>0 ){
372 sqlite_set_result_double(context, p->sum/(double)p->cnt);
drhdd5baa92002-02-27 19:50:59 +0000373 }
374}
375
376/*
377** An instance of the following structure holds the context of a
drha2ed5602002-02-26 23:55:31 +0000378** variance or standard deviation computation.
drhd3a149e2002-02-24 17:12:53 +0000379*/
380typedef struct StdDevCtx StdDevCtx;
381struct StdDevCtx {
382 double sum; /* Sum of terms */
383 double sum2; /* Sum of the squares of terms */
drh739105c2002-05-29 23:22:23 +0000384 int cnt; /* Number of terms counted */
drhd3a149e2002-02-24 17:12:53 +0000385};
386
drhef2daf52002-03-04 02:26:15 +0000387#if 0 /* Omit because math library is required */
drhd3a149e2002-02-24 17:12:53 +0000388/*
389** Routines used to compute the standard deviation as an aggregate.
390*/
drh1350b032002-02-27 19:00:20 +0000391static void stdDevStep(sqlite_func *context, int argc, const char **argv){
drhd3a149e2002-02-24 17:12:53 +0000392 StdDevCtx *p;
393 double x;
drh1350b032002-02-27 19:00:20 +0000394 if( argc<1 ) return;
395 p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000396 if( p && argv[0] ){
397 x = atof(argv[0]);
398 p->sum += x;
399 p->sum2 += x*x;
400 p->cnt++;
401 }
drhd3a149e2002-02-24 17:12:53 +0000402}
drh1350b032002-02-27 19:00:20 +0000403static void stdDevFinalize(sqlite_func *context){
drhdd5baa92002-02-27 19:50:59 +0000404 double rN = sqlite_aggregate_count(context);
drh1350b032002-02-27 19:00:20 +0000405 StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000406 if( p && p->cnt>1 ){
407 double rCnt = cnt;
drhd3a149e2002-02-24 17:12:53 +0000408 sqlite_set_result_double(context,
drh739105c2002-05-29 23:22:23 +0000409 sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
drhd3a149e2002-02-24 17:12:53 +0000410 }
drhd3a149e2002-02-24 17:12:53 +0000411}
drhef2daf52002-03-04 02:26:15 +0000412#endif
drhd3a149e2002-02-24 17:12:53 +0000413
drh0bce8352002-02-28 00:41:10 +0000414/*
415** The following structure keeps track of state information for the
416** count() aggregate function.
417*/
418typedef struct CountCtx CountCtx;
419struct CountCtx {
420 int n;
421};
drhdd5baa92002-02-27 19:50:59 +0000422
drh0bce8352002-02-28 00:41:10 +0000423/*
424** Routines to implement the count() aggregate function.
425*/
426static void countStep(sqlite_func *context, int argc, const char **argv){
427 CountCtx *p;
428 p = sqlite_aggregate_context(context, sizeof(*p));
429 if( (argc==0 || argv[0]) && p ){
430 p->n++;
431 }
432}
433static void countFinalize(sqlite_func *context){
434 CountCtx *p;
435 p = sqlite_aggregate_context(context, sizeof(*p));
drhf55f25f2002-02-28 01:46:11 +0000436 sqlite_set_result_int(context, p ? p->n : 0);
drh0bce8352002-02-28 00:41:10 +0000437}
438
439/*
440** This function tracks state information for the min() and max()
441** aggregate functions.
442*/
443typedef struct MinMaxCtx MinMaxCtx;
444struct MinMaxCtx {
445 char *z; /* The best so far */
446 char zBuf[28]; /* Space that can be used for storage */
447};
448
449/*
450** Routines to implement min() and max() aggregate functions.
451*/
452static void minStep(sqlite_func *context, int argc, const char **argv){
453 MinMaxCtx *p;
454 p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000455 if( p==0 || argc<1 || argv[0]==0 ) return;
drhf570f012002-05-31 15:51:25 +0000456 if( p->z==0 || sqliteCompare(argv[0],p->z)<0 ){
drh8912d102002-05-26 21:34:58 +0000457 int len;
drh0bce8352002-02-28 00:41:10 +0000458 if( p->z && p->z!=p->zBuf ){
459 sqliteFree(p->z);
460 }
drh8912d102002-05-26 21:34:58 +0000461 len = strlen(argv[0]);
462 if( len < sizeof(p->zBuf) ){
463 p->z = p->zBuf;
drh0bce8352002-02-28 00:41:10 +0000464 }else{
drh8912d102002-05-26 21:34:58 +0000465 p->z = sqliteMalloc( len+1 );
466 if( p->z==0 ) return;
drh0bce8352002-02-28 00:41:10 +0000467 }
drh8912d102002-05-26 21:34:58 +0000468 strcpy(p->z, argv[0]);
drh0bce8352002-02-28 00:41:10 +0000469 }
470}
471static void maxStep(sqlite_func *context, int argc, const char **argv){
472 MinMaxCtx *p;
473 p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000474 if( p==0 || argc<1 || argv[0]==0 ) return;
drhf570f012002-05-31 15:51:25 +0000475 if( p->z==0 || sqliteCompare(argv[0],p->z)>0 ){
drh8912d102002-05-26 21:34:58 +0000476 int len;
drh0bce8352002-02-28 00:41:10 +0000477 if( p->z && p->z!=p->zBuf ){
478 sqliteFree(p->z);
479 }
drh8912d102002-05-26 21:34:58 +0000480 len = strlen(argv[0]);
481 if( len < sizeof(p->zBuf) ){
482 p->z = p->zBuf;
drh0bce8352002-02-28 00:41:10 +0000483 }else{
drh8912d102002-05-26 21:34:58 +0000484 p->z = sqliteMalloc( len+1 );
485 if( p->z==0 ) return;
drh0bce8352002-02-28 00:41:10 +0000486 }
drh8912d102002-05-26 21:34:58 +0000487 strcpy(p->z, argv[0]);
drh0bce8352002-02-28 00:41:10 +0000488 }
489}
490static void minMaxFinalize(sqlite_func *context){
491 MinMaxCtx *p;
492 p = sqlite_aggregate_context(context, sizeof(*p));
drh739105c2002-05-29 23:22:23 +0000493 if( p && p->z ){
drh0bce8352002-02-28 00:41:10 +0000494 sqlite_set_result_string(context, p->z, strlen(p->z));
495 }
496 if( p && p->z && p->z!=p->zBuf ){
497 sqliteFree(p->z);
498 }
499}
drhdd5baa92002-02-27 19:50:59 +0000500
drh771d8c32003-08-09 21:32:28 +0000501/****************************************************************************
502** Time and date functions.
503**
504** SQLite processes all times and dates as Julian Day numbers. The
505** dates and times are stored as the number of days since noon
506** in Greenwich on January 01, 4713 B.C. (a.k.a -4713-01-01 12:00:00)
507** This implement requires years to be expressed as a 4-digit number
508** which means that only dates between 0000-01-01 and 9999-12-31 can
509** be represented, even though julian day numbers allow a much wider
510** range of dates.
511**
512** The Gregorian calendar system is used for all dates and times,
513** even those that predate the Gregorian calendar. Historians often
514** use the Julian calendar for dates prior to 1582-10-15 and for some
515** dates afterwards, depending on locale. Beware of this difference.
516**
517** The conversion algorithms are implemented based on descriptions
518** in the following text:
519**
520** Jean Meeus
521** Astronomical Algorithms, 2nd Edition, 1998
522** ISBM 0-943396-61-1
523** Willmann-Bell, Inc
524** Richmond, Virginia (USA)
525*/
526#ifndef SQLITE_OMIT_DATETIME_FUNCS
527
528/*
529** Convert N digits from zDate into an integer. Return
530** -1 if zDate does not begin with N digits.
531*/
532static int getDigits(const char *zDate, int N){
533 int val = 0;
534 while( N-- ){
535 if( !isdigit(*zDate) ) return -1;
536 val = val*10 + *zDate - '0';
537 zDate++;
538 }
539 return val;
540}
541
542/*
543** Parse dates of the form HH:MM:SS or HH:MM. Store the
544** result (in days) in *prJD.
545**
546** Return 1 if there is a parsing error and 0 on success.
547*/
548static int parseHhMmSs(const char *zDate, double *prJD){
549 int h, m, s;
550 h = getDigits(zDate, 2);
551 if( h<0 || zDate[2]!=':' ) return 1;
552 zDate += 3;
553 m = getDigits(zDate, 2);
554 if( m<0 || m>59 ) return 1;
555 zDate += 2;
556 if( *zDate==':' ){
557 s = getDigits(&zDate[1], 2);
558 if( s<0 || s>59 ) return 1;
559 zDate += 3;
560 }else{
561 s = 0;
562 }
563 while( isspace(*zDate) ){ zDate++; }
564 *prJD = (h*3600.0 + m*60.0 + s)/86400.0;
565 return 0;
566}
567
568/*
569** Parse dates of the form
570**
571** YYYY-MM-DD HH:MM:SS
572** YYYY-MM-DD HH:MM
573** YYYY-MM-DD
574**
575** Write the result as a julian day number in *prJD. Return 0
576** on success and 1 if the input string is not a well-formed
577** date.
578*/
579static int parseYyyyMmDd(const char *zDate, double *prJD){
580 int Y, M, D;
581 double rTime;
582 int A, B, X1, X2;
583
584 Y = getDigits(zDate, 4);
585 if( Y<0 || zDate[4]!='-' ) return 1;
586 zDate += 5;
587 M = getDigits(zDate, 2);
588 if( M<=0 || M>12 || zDate[2]!='-' ) return 1;
589 zDate += 3;
590 D = getDigits(zDate, 2);
591 if( D<=0 || D>31 ) return 1;
592 zDate += 2;
593 while( isspace(*zDate) ){ zDate++; }
594 if( isdigit(*zDate) ){
595 if( parseHhMmSs(zDate, &rTime) ) return 1;
596 }else if( *zDate==0 ){
597 rTime = 0.0;
598 }else{
599 return 1;
600 }
601
602 /* The year, month, and day are now stored in Y, M, and D. Convert
603 ** these into the Julian Day number. See Meeus page 61.
604 */
605 if( M<=2 ){
606 Y--;
607 M += 12;
608 }
609 A = Y/100;
610 B = 2 - A + (A/4);
611 X1 = 365.25*(Y+4716);
612 X2 = 30.6001*(M+1);
613 *prJD = X1 + X2 + D + B - 1524.5 + rTime;
614 return 0;
615}
616
617/*
618** Attempt to parse the given string into a Julian Day Number. Return
619** the number of errors.
620**
621** The following are acceptable forms for the input string:
622**
623** YYYY-MM-DD
624** YYYY-MM-DD HH:MM
625** YYYY-MM-DD HH:MM:SS
626** HH:MM
627** HH:MM:SS
628** DDDD.DD
629** now
630*/
631static int parseDateOrTime(const char *zDate, double *prJD){
632 int i;
633 for(i=0; isdigit(zDate[i]); i++){}
634 if( i==4 && zDate[i]=='-' ){
635 return parseYyyyMmDd(zDate, prJD);
636 }else if( i==2 && zDate[i]==':' ){
637 return parseHhMmSs(zDate, prJD);
638 }else if( i==0 && sqliteStrICmp(zDate,"now")==0 ){
639 return sqliteOsCurrentTime(prJD);
640 }else if( sqliteIsNumber(zDate) ){
641 *prJD = atof(zDate);
642 return 0;
643 }
644 return 1;
645}
646
647/*
648** Break up a julian day number into year, month, day, and seconds.
649** This function assume the Gregorian calendar - even for dates prior
650** to the invention of the Gregorian calendar in 1582.
651**
652** See Meeus page 63.
653*/
654static void decomposeDate(double JD, int *pY, int *pM, int *pD, int *pS){
655 int Z, A, B, C, D, E, X1;
656 Z = JD + 0.5;
657 A = (Z - 1867216.25)/36524.25;
658 A = Z + 1 + A - (A/4);
659 B = A + 1524;
660 C = (B - 122.1)/365.25;
661 D = 365.25*C;
662 E = (B-D)/30.6001;
663 X1 = 30.6001*E;
664 *pD = B - D - X1;
665 *pM = E<14 ? E-1 : E-13;
666 *pY = *pD>2 ? C - 4716 : C - 4715;
667 *pS = (JD + 0.5 - Z)*86400.0;
668}
669
670/*
671** Check to see that all arguments are valid date strings. If any is
672** not a valid date string, return 0. If all are valid, return 1.
673** Write into *prJD the sum of the julian day numbers for all date
674** strings.
675*/
676static int isDate(
677 sqlite_func *context,
678 int argc,
679 const char **argv,
680 double *prJD
681){
682 double r;
683 int i;
684 *prJD = 0.0;
685 for(i=0; i<argc; i++){
686 if( argv[i]==0 ) return 0;
687 if( parseDateOrTime(argv[i], &r) ) return 0;
688 *prJD += r;
689 }
690 return 1;
691}
692
693/*
694** The following routines implement the various date and time functions
695** of SQLite.
696*/
697static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
698 double JD;
699 if( isDate(context, argc, argv, &JD) ){
700 sqlite_set_result_double(context, JD);
701 }
702}
703static void timestampFunc(sqlite_func *context, int argc, const char **argv){
704 double JD;
705 if( isDate(context, argc, argv, &JD) ){
706 int Y, M, D, h, m, s;
707 char zBuf[100];
708 decomposeDate(JD, &Y, &M, &D, &s);
709 h = s/3600;
710 s -= h*3600;
711 m = s/60;
712 s -= m*60;
713 sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d", Y, M, D, h, m, s);
714 sqlite_set_result_string(context, zBuf, -1);
715 }
716}
717static void timeFunc(sqlite_func *context, int argc, const char **argv){
718 double JD;
719 if( isDate(context, argc, argv, &JD) ){
720 int Y, M, D, h, m, s;
721 char zBuf[100];
722 decomposeDate(JD, &Y, &M, &D, &s);
723 h = s/3600;
724 s -= h*3600;
725 m = s/60;
726 s -= m*60;
727 sprintf(zBuf, "%02d:%02d:%02d", h, m, s);
728 sqlite_set_result_string(context, zBuf, -1);
729 }
730}
731static void dateFunc(sqlite_func *context, int argc, const char **argv){
732 double JD;
733 if( isDate(context, argc, argv, &JD) ){
734 int Y, M, D, s;
735 char zBuf[100];
736 decomposeDate(JD, &Y, &M, &D, &s);
737 sprintf(zBuf, "%04d-%02d-%02d", Y, M, D);
738 sqlite_set_result_string(context, zBuf, -1);
739 }
740}
741static void yearFunc(sqlite_func *context, int argc, const char **argv){
742 double JD;
743 if( isDate(context, argc, argv, &JD) ){
744 int Y, M, D, s;
745 decomposeDate(JD, &Y, &M, &D, &s);
746 sqlite_set_result_int(context, Y);
747 }
748}
749static void monthFunc(sqlite_func *context, int argc, const char **argv){
750 double JD;
751 if( isDate(context, argc, argv, &JD) ){
752 int Y, M, D, s;
753 decomposeDate(JD, &Y, &M, &D, &s);
754 sqlite_set_result_int(context, M);
755 }
756}
757static void dayofweekFunc(sqlite_func *context, int argc, const char **argv){
758 double JD;
759 if( isDate(context, argc, argv, &JD) ){
760 int Z = JD + 1.5;
761 sqlite_set_result_int(context, Z % 7);
762 }
763}
764static void dayofmonthFunc(sqlite_func *context, int argc, const char **argv){
765 double JD;
766 if( isDate(context, argc, argv, &JD) ){
767 int Y, M, D, s;
768 decomposeDate(JD, &Y, &M, &D, &s);
769 sqlite_set_result_int(context, D);
770 }
771}
772static void secondFunc(sqlite_func *context, int argc, const char **argv){
773 double JD;
774 if( isDate(context, argc, argv, &JD) ){
775 int Y, M, D, h, m, s;
776 decomposeDate(JD, &Y, &M, &D, &s);
777 h = s/3600;
778 s -= h*3600;
779 m = s/60;
780 s -= m*60;
781 sqlite_set_result_int(context, s);
782 }
783}
784static void minuteFunc(sqlite_func *context, int argc, const char **argv){
785 double JD;
786 if( isDate(context, argc, argv, &JD) ){
787 int Y, M, D, h, m, s;
788 decomposeDate(JD, &Y, &M, &D, &s);
789 h = s/3600;
790 s -= h*3600;
791 m = s/60;
792 sqlite_set_result_int(context, m);
793 }
794}
795static void hourFunc(sqlite_func *context, int argc, const char **argv){
796 double JD;
797 if( isDate(context, argc, argv, &JD) ){
798 int Y, M, D, h, s;
799 decomposeDate(JD, &Y, &M, &D, &s);
800 h = s/3600;
801 sqlite_set_result_int(context, h);
802 }
803}
804#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
805/***************************************************************************/
806
drhd3a149e2002-02-24 17:12:53 +0000807/*
drha2ed5602002-02-26 23:55:31 +0000808** This function registered all of the above C functions as SQL
809** functions. This should be the only routine in this file with
810** external linkage.
drhdc04c582002-02-24 01:55:15 +0000811*/
drh28f4b682002-06-09 10:14:18 +0000812void sqliteRegisterBuiltinFunctions(sqlite *db){
drh0bce8352002-02-28 00:41:10 +0000813 static struct {
814 char *zName;
815 int nArg;
drhc9b84a12002-06-20 11:36:48 +0000816 int dataType;
drh0bce8352002-02-28 00:41:10 +0000817 void (*xFunc)(sqlite_func*,int,const char**);
818 } aFuncs[] = {
drhc9b84a12002-06-20 11:36:48 +0000819 { "min", -1, SQLITE_ARGS, minFunc },
820 { "min", 0, 0, 0 },
821 { "max", -1, SQLITE_ARGS, maxFunc },
822 { "max", 0, 0, 0 },
823 { "length", 1, SQLITE_NUMERIC, lengthFunc },
824 { "substr", 3, SQLITE_TEXT, substrFunc },
825 { "abs", 1, SQLITE_NUMERIC, absFunc },
826 { "round", 1, SQLITE_NUMERIC, roundFunc },
827 { "round", 2, SQLITE_NUMERIC, roundFunc },
828 { "upper", 1, SQLITE_TEXT, upperFunc },
829 { "lower", 1, SQLITE_TEXT, lowerFunc },
830 { "coalesce", -1, SQLITE_ARGS, ifnullFunc },
831 { "coalesce", 0, 0, 0 },
832 { "coalesce", 1, 0, 0 },
833 { "ifnull", 2, SQLITE_ARGS, ifnullFunc },
834 { "random", -1, SQLITE_NUMERIC, randomFunc },
835 { "like", 2, SQLITE_NUMERIC, likeFunc },
836 { "glob", 2, SQLITE_NUMERIC, globFunc },
837 { "nullif", 2, SQLITE_ARGS, nullifFunc },
drh647cb0e2002-11-04 19:32:25 +0000838 { "sqlite_version",0,SQLITE_TEXT, versionFunc},
drh771d8c32003-08-09 21:32:28 +0000839#ifndef SQLITE_OMIT_DATETIME_FUNCS
840 { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
841 { "timestamp", -1, SQLITE_TEXT, timestampFunc },
842 { "time", -1, SQLITE_TEXT, timeFunc },
843 { "date", -1, SQLITE_TEXT, dateFunc },
844 { "year", -1, SQLITE_NUMERIC, yearFunc },
845 { "month", -1, SQLITE_NUMERIC, monthFunc },
846 { "dayofmonth",-1, SQLITE_NUMERIC, dayofmonthFunc },
847 { "dayofweek", -1, SQLITE_NUMERIC, dayofweekFunc },
848 { "hour", -1, SQLITE_NUMERIC, hourFunc },
849 { "minute", -1, SQLITE_NUMERIC, minuteFunc },
850 { "second", -1, SQLITE_NUMERIC, secondFunc },
851#endif
drhd24cc422003-03-27 12:51:24 +0000852#ifdef SQLITE_SOUNDEX
853 { "soundex", 1, SQLITE_TEXT, soundexFunc},
854#endif
drh193a6b42002-07-07 16:52:46 +0000855#ifdef SQLITE_TEST
856 { "randstr", 2, SQLITE_TEXT, randStr },
857#endif
drh0bce8352002-02-28 00:41:10 +0000858 };
859 static struct {
860 char *zName;
861 int nArg;
drhc9b84a12002-06-20 11:36:48 +0000862 int dataType;
drh0bce8352002-02-28 00:41:10 +0000863 void (*xStep)(sqlite_func*,int,const char**);
864 void (*xFinalize)(sqlite_func*);
865 } aAggs[] = {
drhc9b84a12002-06-20 11:36:48 +0000866 { "min", 1, 0, minStep, minMaxFinalize },
867 { "max", 1, 0, maxStep, minMaxFinalize },
868 { "sum", 1, SQLITE_NUMERIC, sumStep, sumFinalize },
869 { "avg", 1, SQLITE_NUMERIC, sumStep, avgFinalize },
870 { "count", 0, SQLITE_NUMERIC, countStep, countFinalize },
871 { "count", 1, SQLITE_NUMERIC, countStep, countFinalize },
drhef2daf52002-03-04 02:26:15 +0000872#if 0
drhc9b84a12002-06-20 11:36:48 +0000873 { "stddev", 1, SQLITE_NUMERIC, stdDevStep, stdDevFinalize },
drhef2daf52002-03-04 02:26:15 +0000874#endif
drh0bce8352002-02-28 00:41:10 +0000875 };
876 int i;
877
878 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
879 sqlite_create_function(db, aFuncs[i].zName,
880 aFuncs[i].nArg, aFuncs[i].xFunc, 0);
drhc9b84a12002-06-20 11:36:48 +0000881 if( aFuncs[i].xFunc ){
882 sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
883 }
drh0bce8352002-02-28 00:41:10 +0000884 }
drh6ed41ad2002-04-06 14:10:47 +0000885 sqlite_create_function(db, "last_insert_rowid", 0,
886 last_insert_rowid, db);
drhc9b84a12002-06-20 11:36:48 +0000887 sqlite_function_type(db, "last_insert_rowid", SQLITE_NUMERIC);
drh0bce8352002-02-28 00:41:10 +0000888 for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
889 sqlite_create_aggregate(db, aAggs[i].zName,
890 aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, 0);
drhc9b84a12002-06-20 11:36:48 +0000891 sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
drh0bce8352002-02-28 00:41:10 +0000892 }
drhdc04c582002-02-24 01:55:15 +0000893}