date.c

Go to the documentation of this file.
00001 /*
00002 ** 2003 October 31
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains the C functions that implement date and time
00013 ** functions for SQLite.  
00014 **
00015 ** There is only one exported symbol in this file - the function
00016 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
00017 ** All other code has file scope.
00018 **
00019 ** $Id: date.c,v 1.92 2008/10/13 15:35:09 drh Exp $
00020 **
00021 ** SQLite processes all times and dates as Julian Day numbers.  The
00022 ** dates and times are stored as the number of days since noon
00023 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
00024 ** calendar system. 
00025 **
00026 ** 1970-01-01 00:00:00 is JD 2440587.5
00027 ** 2000-01-01 00:00:00 is JD 2451544.5
00028 **
00029 ** This implemention requires years to be expressed as a 4-digit number
00030 ** which means that only dates between 0000-01-01 and 9999-12-31 can
00031 ** be represented, even though julian day numbers allow a much wider
00032 ** range of dates.
00033 **
00034 ** The Gregorian calendar system is used for all dates and times,
00035 ** even those that predate the Gregorian calendar.  Historians usually
00036 ** use the Julian calendar for dates prior to 1582-10-15 and for some
00037 ** dates afterwards, depending on locale.  Beware of this difference.
00038 **
00039 ** The conversion algorithms are implemented based on descriptions
00040 ** in the following text:
00041 **
00042 **      Jean Meeus
00043 **      Astronomical Algorithms, 2nd Edition, 1998
00044 **      ISBM 0-943396-61-1
00045 **      Willmann-Bell, Inc
00046 **      Richmond, Virginia (USA)
00047 */
00048 #include "sqliteInt.h"
00049 #include <ctype.h>
00050 #include <stdlib.h>
00051 #include <assert.h>
00052 #include <time.h>
00053 
00054 #ifndef SQLITE_OMIT_DATETIME_FUNCS
00055 
00056 /*
00057 ** On recent Windows platforms, the localtime_s() function is available
00058 ** as part of the "Secure CRT". It is essentially equivalent to 
00059 ** localtime_r() available under most POSIX platforms, except that the 
00060 ** order of the parameters is reversed.
00061 **
00062 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
00063 **
00064 ** If the user has not indicated to use localtime_r() or localtime_s()
00065 ** already, check for an MSVC build environment that provides 
00066 ** localtime_s().
00067 */
00068 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
00069      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
00070 #define HAVE_LOCALTIME_S 1
00071 #endif
00072 
00073 /*
00074 ** A structure for holding a single date and time.
00075 */
00076 typedef struct DateTime DateTime;
00077 struct DateTime {
00078   sqlite3_int64 iJD; /* The julian day number times 86400000 */
00079   int Y, M, D;       /* Year, month, and day */
00080   int h, m;          /* Hour and minutes */
00081   int tz;            /* Timezone offset in minutes */
00082   double s;          /* Seconds */
00083   char validYMD;     /* True if Y,M,D are valid */
00084   char validHMS;     /* True if h,m,s are valid */
00085   char validJD;      /* True if iJD is valid */
00086   char validTZ;      /* True if tz is valid */
00087 };
00088 
00089 
00090 /*
00091 ** Convert zDate into one or more integers.  Additional arguments
00092 ** come in groups of 5 as follows:
00093 **
00094 **       N       number of digits in the integer
00095 **       min     minimum allowed value of the integer
00096 **       max     maximum allowed value of the integer
00097 **       nextC   first character after the integer
00098 **       pVal    where to write the integers value.
00099 **
00100 ** Conversions continue until one with nextC==0 is encountered.
00101 ** The function returns the number of successful conversions.
00102 */
00103 static int getDigits(const char *zDate, ...){
00104   va_list ap;
00105   int val;
00106   int N;
00107   int min;
00108   int max;
00109   int nextC;
00110   int *pVal;
00111   int cnt = 0;
00112   va_start(ap, zDate);
00113   do{
00114     N = va_arg(ap, int);
00115     min = va_arg(ap, int);
00116     max = va_arg(ap, int);
00117     nextC = va_arg(ap, int);
00118     pVal = va_arg(ap, int*);
00119     val = 0;
00120     while( N-- ){
00121       if( !isdigit(*(u8*)zDate) ){
00122         goto end_getDigits;
00123       }
00124       val = val*10 + *zDate - '0';
00125       zDate++;
00126     }
00127     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
00128       goto end_getDigits;
00129     }
00130     *pVal = val;
00131     zDate++;
00132     cnt++;
00133   }while( nextC );
00134 end_getDigits:
00135   va_end(ap);
00136   return cnt;
00137 }
00138 
00139 /*
00140 ** Read text from z[] and convert into a floating point number.  Return
00141 ** the number of digits converted.
00142 */
00143 #define getValue sqlite3AtoF
00144 
00145 /*
00146 ** Parse a timezone extension on the end of a date-time.
00147 ** The extension is of the form:
00148 **
00149 **        (+/-)HH:MM
00150 **
00151 ** Or the "zulu" notation:
00152 **
00153 **        Z
00154 **
00155 ** If the parse is successful, write the number of minutes
00156 ** of change in p->tz and return 0.  If a parser error occurs,
00157 ** return non-zero.
00158 **
00159 ** A missing specifier is not considered an error.
00160 */
00161 static int parseTimezone(const char *zDate, DateTime *p){
00162   int sgn = 0;
00163   int nHr, nMn;
00164   int c;
00165   while( isspace(*(u8*)zDate) ){ zDate++; }
00166   p->tz = 0;
00167   c = *zDate;
00168   if( c=='-' ){
00169     sgn = -1;
00170   }else if( c=='+' ){
00171     sgn = +1;
00172   }else if( c=='Z' || c=='z' ){
00173     zDate++;
00174     goto zulu_time;
00175   }else{
00176     return c!=0;
00177   }
00178   zDate++;
00179   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
00180     return 1;
00181   }
00182   zDate += 5;
00183   p->tz = sgn*(nMn + nHr*60);
00184 zulu_time:
00185   while( isspace(*(u8*)zDate) ){ zDate++; }
00186   return *zDate!=0;
00187 }
00188 
00189 /*
00190 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
00191 ** The HH, MM, and SS must each be exactly 2 digits.  The
00192 ** fractional seconds FFFF can be one or more digits.
00193 **
00194 ** Return 1 if there is a parsing error and 0 on success.
00195 */
00196 static int parseHhMmSs(const char *zDate, DateTime *p){
00197   int h, m, s;
00198   double ms = 0.0;
00199   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
00200     return 1;
00201   }
00202   zDate += 5;
00203   if( *zDate==':' ){
00204     zDate++;
00205     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
00206       return 1;
00207     }
00208     zDate += 2;
00209     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
00210       double rScale = 1.0;
00211       zDate++;
00212       while( isdigit(*(u8*)zDate) ){
00213         ms = ms*10.0 + *zDate - '0';
00214         rScale *= 10.0;
00215         zDate++;
00216       }
00217       ms /= rScale;
00218     }
00219   }else{
00220     s = 0;
00221   }
00222   p->validJD = 0;
00223   p->validHMS = 1;
00224   p->h = h;
00225   p->m = m;
00226   p->s = s + ms;
00227   if( parseTimezone(zDate, p) ) return 1;
00228   p->validTZ = p->tz!=0;
00229   return 0;
00230 }
00231 
00232 /*
00233 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
00234 ** that the YYYY-MM-DD is according to the Gregorian calendar.
00235 **
00236 ** Reference:  Meeus page 61
00237 */
00238 static void computeJD(DateTime *p){
00239   int Y, M, D, A, B, X1, X2;
00240 
00241   if( p->validJD ) return;
00242   if( p->validYMD ){
00243     Y = p->Y;
00244     M = p->M;
00245     D = p->D;
00246   }else{
00247     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
00248     M = 1;
00249     D = 1;
00250   }
00251   if( M<=2 ){
00252     Y--;
00253     M += 12;
00254   }
00255   A = Y/100;
00256   B = 2 - A + (A/4);
00257   X1 = 365.25*(Y+4716);
00258   X2 = 30.6001*(M+1);
00259   p->iJD = (X1 + X2 + D + B - 1524.5)*86400000;
00260   p->validJD = 1;
00261   if( p->validHMS ){
00262     p->iJD += p->h*3600000 + p->m*60000 + p->s*1000;
00263     if( p->validTZ ){
00264       p->iJD -= p->tz*60000;
00265       p->validYMD = 0;
00266       p->validHMS = 0;
00267       p->validTZ = 0;
00268     }
00269   }
00270 }
00271 
00272 /*
00273 ** Parse dates of the form
00274 **
00275 **     YYYY-MM-DD HH:MM:SS.FFF
00276 **     YYYY-MM-DD HH:MM:SS
00277 **     YYYY-MM-DD HH:MM
00278 **     YYYY-MM-DD
00279 **
00280 ** Write the result into the DateTime structure and return 0
00281 ** on success and 1 if the input string is not a well-formed
00282 ** date.
00283 */
00284 static int parseYyyyMmDd(const char *zDate, DateTime *p){
00285   int Y, M, D, neg;
00286 
00287   if( zDate[0]=='-' ){
00288     zDate++;
00289     neg = 1;
00290   }else{
00291     neg = 0;
00292   }
00293   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
00294     return 1;
00295   }
00296   zDate += 10;
00297   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
00298   if( parseHhMmSs(zDate, p)==0 ){
00299     /* We got the time */
00300   }else if( *zDate==0 ){
00301     p->validHMS = 0;
00302   }else{
00303     return 1;
00304   }
00305   p->validJD = 0;
00306   p->validYMD = 1;
00307   p->Y = neg ? -Y : Y;
00308   p->M = M;
00309   p->D = D;
00310   if( p->validTZ ){
00311     computeJD(p);
00312   }
00313   return 0;
00314 }
00315 
00316 /*
00317 ** Set the time to the current time reported by the VFS
00318 */
00319 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
00320   double r;
00321   sqlite3 *db = sqlite3_context_db_handle(context);
00322   sqlite3OsCurrentTime(db->pVfs, &r);
00323   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
00324   p->validJD = 1;
00325 }
00326 
00327 /*
00328 ** Attempt to parse the given string into a Julian Day Number.  Return
00329 ** the number of errors.
00330 **
00331 ** The following are acceptable forms for the input string:
00332 **
00333 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
00334 **      DDDD.DD 
00335 **      now
00336 **
00337 ** In the first form, the +/-HH:MM is always optional.  The fractional
00338 ** seconds extension (the ".FFF") is optional.  The seconds portion
00339 ** (":SS.FFF") is option.  The year and date can be omitted as long
00340 ** as there is a time string.  The time string can be omitted as long
00341 ** as there is a year and date.
00342 */
00343 static int parseDateOrTime(
00344   sqlite3_context *context, 
00345   const char *zDate, 
00346   DateTime *p
00347 ){
00348   if( parseYyyyMmDd(zDate,p)==0 ){
00349     return 0;
00350   }else if( parseHhMmSs(zDate, p)==0 ){
00351     return 0;
00352   }else if( sqlite3StrICmp(zDate,"now")==0){
00353     setDateTimeToCurrent(context, p);
00354     return 0;
00355   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
00356     double r;
00357     getValue(zDate, &r);
00358     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
00359     p->validJD = 1;
00360     return 0;
00361   }
00362   return 1;
00363 }
00364 
00365 /*
00366 ** Compute the Year, Month, and Day from the julian day number.
00367 */
00368 static void computeYMD(DateTime *p){
00369   int Z, A, B, C, D, E, X1;
00370   if( p->validYMD ) return;
00371   if( !p->validJD ){
00372     p->Y = 2000;
00373     p->M = 1;
00374     p->D = 1;
00375   }else{
00376     Z = (p->iJD + 43200000)/86400000;
00377     A = (Z - 1867216.25)/36524.25;
00378     A = Z + 1 + A - (A/4);
00379     B = A + 1524;
00380     C = (B - 122.1)/365.25;
00381     D = 365.25*C;
00382     E = (B-D)/30.6001;
00383     X1 = 30.6001*E;
00384     p->D = B - D - X1;
00385     p->M = E<14 ? E-1 : E-13;
00386     p->Y = p->M>2 ? C - 4716 : C - 4715;
00387   }
00388   p->validYMD = 1;
00389 }
00390 
00391 /*
00392 ** Compute the Hour, Minute, and Seconds from the julian day number.
00393 */
00394 static void computeHMS(DateTime *p){
00395   int s;
00396   if( p->validHMS ) return;
00397   computeJD(p);
00398   s = (p->iJD + 43200000) % 86400000;
00399   p->s = s/1000.0;
00400   s = p->s;
00401   p->s -= s;
00402   p->h = s/3600;
00403   s -= p->h*3600;
00404   p->m = s/60;
00405   p->s += s - p->m*60;
00406   p->validHMS = 1;
00407 }
00408 
00409 /*
00410 ** Compute both YMD and HMS
00411 */
00412 static void computeYMD_HMS(DateTime *p){
00413   computeYMD(p);
00414   computeHMS(p);
00415 }
00416 
00417 /*
00418 ** Clear the YMD and HMS and the TZ
00419 */
00420 static void clearYMD_HMS_TZ(DateTime *p){
00421   p->validYMD = 0;
00422   p->validHMS = 0;
00423   p->validTZ = 0;
00424 }
00425 
00426 #ifndef SQLITE_OMIT_LOCALTIME
00427 /*
00428 ** Compute the difference (in milliseconds)
00429 ** between localtime and UTC (a.k.a. GMT)
00430 ** for the time value p where p is in UTC.
00431 */
00432 static int localtimeOffset(DateTime *p){
00433   DateTime x, y;
00434   time_t t;
00435   x = *p;
00436   computeYMD_HMS(&x);
00437   if( x.Y<1971 || x.Y>=2038 ){
00438     x.Y = 2000;
00439     x.M = 1;
00440     x.D = 1;
00441     x.h = 0;
00442     x.m = 0;
00443     x.s = 0.0;
00444   } else {
00445     int s = x.s + 0.5;
00446     x.s = s;
00447   }
00448   x.tz = 0;
00449   x.validJD = 0;
00450   computeJD(&x);
00451   t = x.iJD/1000 - 2440587.5*86400.0;
00452 #ifdef HAVE_LOCALTIME_R
00453   {
00454     struct tm sLocal;
00455     localtime_r(&t, &sLocal);
00456     y.Y = sLocal.tm_year + 1900;
00457     y.M = sLocal.tm_mon + 1;
00458     y.D = sLocal.tm_mday;
00459     y.h = sLocal.tm_hour;
00460     y.m = sLocal.tm_min;
00461     y.s = sLocal.tm_sec;
00462   }
00463 #elif defined(HAVE_LOCALTIME_S)
00464   {
00465     struct tm sLocal;
00466     localtime_s(&sLocal, &t);
00467     y.Y = sLocal.tm_year + 1900;
00468     y.M = sLocal.tm_mon + 1;
00469     y.D = sLocal.tm_mday;
00470     y.h = sLocal.tm_hour;
00471     y.m = sLocal.tm_min;
00472     y.s = sLocal.tm_sec;
00473   }
00474 #else
00475   {
00476     struct tm *pTm;
00477     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
00478     pTm = localtime(&t);
00479     y.Y = pTm->tm_year + 1900;
00480     y.M = pTm->tm_mon + 1;
00481     y.D = pTm->tm_mday;
00482     y.h = pTm->tm_hour;
00483     y.m = pTm->tm_min;
00484     y.s = pTm->tm_sec;
00485     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
00486   }
00487 #endif
00488   y.validYMD = 1;
00489   y.validHMS = 1;
00490   y.validJD = 0;
00491   y.validTZ = 0;
00492   computeJD(&y);
00493   return y.iJD - x.iJD;
00494 }
00495 #endif /* SQLITE_OMIT_LOCALTIME */
00496 
00497 /*
00498 ** Process a modifier to a date-time stamp.  The modifiers are
00499 ** as follows:
00500 **
00501 **     NNN days
00502 **     NNN hours
00503 **     NNN minutes
00504 **     NNN.NNNN seconds
00505 **     NNN months
00506 **     NNN years
00507 **     start of month
00508 **     start of year
00509 **     start of week
00510 **     start of day
00511 **     weekday N
00512 **     unixepoch
00513 **     localtime
00514 **     utc
00515 **
00516 ** Return 0 on success and 1 if there is any kind of error.
00517 */
00518 static int parseModifier(const char *zMod, DateTime *p){
00519   int rc = 1;
00520   int n;
00521   double r;
00522   char *z, zBuf[30];
00523   z = zBuf;
00524   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
00525     z[n] = tolower(zMod[n]);
00526   }
00527   z[n] = 0;
00528   switch( z[0] ){
00529 #ifndef SQLITE_OMIT_LOCALTIME
00530     case 'l': {
00531       /*    localtime
00532       **
00533       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
00534       ** show local time.
00535       */
00536       if( strcmp(z, "localtime")==0 ){
00537         computeJD(p);
00538         p->iJD += localtimeOffset(p);
00539         clearYMD_HMS_TZ(p);
00540         rc = 0;
00541       }
00542       break;
00543     }
00544 #endif
00545     case 'u': {
00546       /*
00547       **    unixepoch
00548       **
00549       ** Treat the current value of p->iJD as the number of
00550       ** seconds since 1970.  Convert to a real julian day number.
00551       */
00552       if( strcmp(z, "unixepoch")==0 && p->validJD ){
00553         p->iJD = p->iJD/86400.0 + 2440587.5*86400000.0;
00554         clearYMD_HMS_TZ(p);
00555         rc = 0;
00556       }
00557 #ifndef SQLITE_OMIT_LOCALTIME
00558       else if( strcmp(z, "utc")==0 ){
00559         int c1;
00560         computeJD(p);
00561         c1 = localtimeOffset(p);
00562         p->iJD -= c1;
00563         clearYMD_HMS_TZ(p);
00564         p->iJD += c1 - localtimeOffset(p);
00565         rc = 0;
00566       }
00567 #endif
00568       break;
00569     }
00570     case 'w': {
00571       /*
00572       **    weekday N
00573       **
00574       ** Move the date to the same time on the next occurrence of
00575       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
00576       ** date is already on the appropriate weekday, this is a no-op.
00577       */
00578       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
00579                  && (n=r)==r && n>=0 && r<7 ){
00580         sqlite3_int64 Z;
00581         computeYMD_HMS(p);
00582         p->validTZ = 0;
00583         p->validJD = 0;
00584         computeJD(p);
00585         Z = ((p->iJD + 129600000)/86400000) % 7;
00586         if( Z>n ) Z -= 7;
00587         p->iJD += (n - Z)*86400000;
00588         clearYMD_HMS_TZ(p);
00589         rc = 0;
00590       }
00591       break;
00592     }
00593     case 's': {
00594       /*
00595       **    start of TTTTT
00596       **
00597       ** Move the date backwards to the beginning of the current day,
00598       ** or month or year.
00599       */
00600       if( strncmp(z, "start of ", 9)!=0 ) break;
00601       z += 9;
00602       computeYMD(p);
00603       p->validHMS = 1;
00604       p->h = p->m = 0;
00605       p->s = 0.0;
00606       p->validTZ = 0;
00607       p->validJD = 0;
00608       if( strcmp(z,"month")==0 ){
00609         p->D = 1;
00610         rc = 0;
00611       }else if( strcmp(z,"year")==0 ){
00612         computeYMD(p);
00613         p->M = 1;
00614         p->D = 1;
00615         rc = 0;
00616       }else if( strcmp(z,"day")==0 ){
00617         rc = 0;
00618       }
00619       break;
00620     }
00621     case '+':
00622     case '-':
00623     case '0':
00624     case '1':
00625     case '2':
00626     case '3':
00627     case '4':
00628     case '5':
00629     case '6':
00630     case '7':
00631     case '8':
00632     case '9': {
00633       n = getValue(z, &r);
00634       assert( n>=1 );
00635       if( z[n]==':' ){
00636         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
00637         ** specified number of hours, minutes, seconds, and fractional seconds
00638         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
00639         ** omitted.
00640         */
00641         const char *z2 = z;
00642         DateTime tx;
00643         sqlite3_int64 day;
00644         if( !isdigit(*(u8*)z2) ) z2++;
00645         memset(&tx, 0, sizeof(tx));
00646         if( parseHhMmSs(z2, &tx) ) break;
00647         computeJD(&tx);
00648         tx.iJD -= 43200000;
00649         day = tx.iJD/86400000;
00650         tx.iJD -= day*86400000;
00651         if( z[0]=='-' ) tx.iJD = -tx.iJD;
00652         computeJD(p);
00653         clearYMD_HMS_TZ(p);
00654         p->iJD += tx.iJD;
00655         rc = 0;
00656         break;
00657       }
00658       z += n;
00659       while( isspace(*(u8*)z) ) z++;
00660       n = strlen(z);
00661       if( n>10 || n<3 ) break;
00662       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
00663       computeJD(p);
00664       rc = 0;
00665       if( n==3 && strcmp(z,"day")==0 ){
00666         p->iJD += r*86400000.0 + 0.5;
00667       }else if( n==4 && strcmp(z,"hour")==0 ){
00668         p->iJD += r*(86400000.0/24.0) + 0.5;
00669       }else if( n==6 && strcmp(z,"minute")==0 ){
00670         p->iJD += r*(86400000.0/(24.0*60.0)) + 0.5;
00671       }else if( n==6 && strcmp(z,"second")==0 ){
00672         p->iJD += r*(86400000.0/(24.0*60.0*60.0)) + 0.5;
00673       }else if( n==5 && strcmp(z,"month")==0 ){
00674         int x, y;
00675         computeYMD_HMS(p);
00676         p->M += r;
00677         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
00678         p->Y += x;
00679         p->M -= x*12;
00680         p->validJD = 0;
00681         computeJD(p);
00682         y = r;
00683         if( y!=r ){
00684           p->iJD += (r - y)*30.0*86400000.0 + 0.5;
00685         }
00686       }else if( n==4 && strcmp(z,"year")==0 ){
00687         computeYMD_HMS(p);
00688         p->Y += r;
00689         p->validJD = 0;
00690         computeJD(p);
00691       }else{
00692         rc = 1;
00693       }
00694       clearYMD_HMS_TZ(p);
00695       break;
00696     }
00697     default: {
00698       break;
00699     }
00700   }
00701   return rc;
00702 }
00703 
00704 /*
00705 ** Process time function arguments.  argv[0] is a date-time stamp.
00706 ** argv[1] and following are modifiers.  Parse them all and write
00707 ** the resulting time into the DateTime structure p.  Return 0
00708 ** on success and 1 if there are any errors.
00709 **
00710 ** If there are zero parameters (if even argv[0] is undefined)
00711 ** then assume a default value of "now" for argv[0].
00712 */
00713 static int isDate(
00714   sqlite3_context *context, 
00715   int argc, 
00716   sqlite3_value **argv, 
00717   DateTime *p
00718 ){
00719   int i;
00720   const unsigned char *z;
00721   int eType;
00722   memset(p, 0, sizeof(*p));
00723   if( argc==0 ){
00724     setDateTimeToCurrent(context, p);
00725   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
00726                    || eType==SQLITE_INTEGER ){
00727     p->iJD = sqlite3_value_double(argv[0])*86400000.0 + 0.5;
00728     p->validJD = 1;
00729   }else{
00730     z = sqlite3_value_text(argv[0]);
00731     if( !z || parseDateOrTime(context, (char*)z, p) ){
00732       return 1;
00733     }
00734   }
00735   for(i=1; i<argc; i++){
00736     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
00737       return 1;
00738     }
00739   }
00740   return 0;
00741 }
00742 
00743 
00744 /*
00745 ** The following routines implement the various date and time functions
00746 ** of SQLite.
00747 */
00748 
00749 /*
00750 **    julianday( TIMESTRING, MOD, MOD, ...)
00751 **
00752 ** Return the julian day number of the date specified in the arguments
00753 */
00754 static void juliandayFunc(
00755   sqlite3_context *context,
00756   int argc,
00757   sqlite3_value **argv
00758 ){
00759   DateTime x;
00760   if( isDate(context, argc, argv, &x)==0 ){
00761     computeJD(&x);
00762     sqlite3_result_double(context, x.iJD/86400000.0);
00763   }
00764 }
00765 
00766 /*
00767 **    datetime( TIMESTRING, MOD, MOD, ...)
00768 **
00769 ** Return YYYY-MM-DD HH:MM:SS
00770 */
00771 static void datetimeFunc(
00772   sqlite3_context *context,
00773   int argc,
00774   sqlite3_value **argv
00775 ){
00776   DateTime x;
00777   if( isDate(context, argc, argv, &x)==0 ){
00778     char zBuf[100];
00779     computeYMD_HMS(&x);
00780     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
00781                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
00782     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
00783   }
00784 }
00785 
00786 /*
00787 **    time( TIMESTRING, MOD, MOD, ...)
00788 **
00789 ** Return HH:MM:SS
00790 */
00791 static void timeFunc(
00792   sqlite3_context *context,
00793   int argc,
00794   sqlite3_value **argv
00795 ){
00796   DateTime x;
00797   if( isDate(context, argc, argv, &x)==0 ){
00798     char zBuf[100];
00799     computeHMS(&x);
00800     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
00801     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
00802   }
00803 }
00804 
00805 /*
00806 **    date( TIMESTRING, MOD, MOD, ...)
00807 **
00808 ** Return YYYY-MM-DD
00809 */
00810 static void dateFunc(
00811   sqlite3_context *context,
00812   int argc,
00813   sqlite3_value **argv
00814 ){
00815   DateTime x;
00816   if( isDate(context, argc, argv, &x)==0 ){
00817     char zBuf[100];
00818     computeYMD(&x);
00819     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
00820     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
00821   }
00822 }
00823 
00824 /*
00825 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
00826 **
00827 ** Return a string described by FORMAT.  Conversions as follows:
00828 **
00829 **   %d  day of month
00830 **   %f  ** fractional seconds  SS.SSS
00831 **   %H  hour 00-24
00832 **   %j  day of year 000-366
00833 **   %J  ** Julian day number
00834 **   %m  month 01-12
00835 **   %M  minute 00-59
00836 **   %s  seconds since 1970-01-01
00837 **   %S  seconds 00-59
00838 **   %w  day of week 0-6  sunday==0
00839 **   %W  week of year 00-53
00840 **   %Y  year 0000-9999
00841 **   %%  %
00842 */
00843 static void strftimeFunc(
00844   sqlite3_context *context,
00845   int argc,
00846   sqlite3_value **argv
00847 ){
00848   DateTime x;
00849   u64 n;
00850   int i, j;
00851   char *z;
00852   sqlite3 *db;
00853   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
00854   char zBuf[100];
00855   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
00856   db = sqlite3_context_db_handle(context);
00857   for(i=0, n=1; zFmt[i]; i++, n++){
00858     if( zFmt[i]=='%' ){
00859       switch( zFmt[i+1] ){
00860         case 'd':
00861         case 'H':
00862         case 'm':
00863         case 'M':
00864         case 'S':
00865         case 'W':
00866           n++;
00867           /* fall thru */
00868         case 'w':
00869         case '%':
00870           break;
00871         case 'f':
00872           n += 8;
00873           break;
00874         case 'j':
00875           n += 3;
00876           break;
00877         case 'Y':
00878           n += 8;
00879           break;
00880         case 's':
00881         case 'J':
00882           n += 50;
00883           break;
00884         default:
00885           return;  /* ERROR.  return a NULL */
00886       }
00887       i++;
00888     }
00889   }
00890   if( n<sizeof(zBuf) ){
00891     z = zBuf;
00892   }else if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
00893     sqlite3_result_error_toobig(context);
00894     return;
00895   }else{
00896     z = sqlite3DbMallocRaw(db, n);
00897     if( z==0 ){
00898       sqlite3_result_error_nomem(context);
00899       return;
00900     }
00901   }
00902   computeJD(&x);
00903   computeYMD_HMS(&x);
00904   for(i=j=0; zFmt[i]; i++){
00905     if( zFmt[i]!='%' ){
00906       z[j++] = zFmt[i];
00907     }else{
00908       i++;
00909       switch( zFmt[i] ){
00910         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
00911         case 'f': {
00912           double s = x.s;
00913           if( s>59.999 ) s = 59.999;
00914           sqlite3_snprintf(7, &z[j],"%06.3f", s);
00915           j += strlen(&z[j]);
00916           break;
00917         }
00918         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
00919         case 'W': /* Fall thru */
00920         case 'j': {
00921           int nDay;             /* Number of days since 1st day of year */
00922           DateTime y = x;
00923           y.validJD = 0;
00924           y.M = 1;
00925           y.D = 1;
00926           computeJD(&y);
00927           nDay = (x.iJD - y.iJD)/86400000.0 + 0.5;
00928           if( zFmt[i]=='W' ){
00929             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
00930             wd = ((x.iJD+43200000)/86400000) % 7;
00931             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
00932             j += 2;
00933           }else{
00934             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
00935             j += 3;
00936           }
00937           break;
00938         }
00939         case 'J': {
00940           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
00941           j+=strlen(&z[j]);
00942           break;
00943         }
00944         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
00945         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
00946         case 's': {
00947           sqlite3_snprintf(30,&z[j],"%d",
00948                            (int)(x.iJD/1000.0 - 210866760000.0));
00949           j += strlen(&z[j]);
00950           break;
00951         }
00952         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
00953         case 'w':  z[j++] = (((x.iJD+129600000)/86400000) % 7) + '0'; break;
00954         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
00955         default:   z[j++] = '%'; break;
00956       }
00957     }
00958   }
00959   z[j] = 0;
00960   sqlite3_result_text(context, z, -1,
00961                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
00962 }
00963 
00964 /*
00965 ** current_time()
00966 **
00967 ** This function returns the same value as time('now').
00968 */
00969 static void ctimeFunc(
00970   sqlite3_context *context,
00971   int argc,
00972   sqlite3_value **argv
00973 ){
00974   timeFunc(context, 0, 0);
00975 }
00976 
00977 /*
00978 ** current_date()
00979 **
00980 ** This function returns the same value as date('now').
00981 */
00982 static void cdateFunc(
00983   sqlite3_context *context,
00984   int argc,
00985   sqlite3_value **argv
00986 ){
00987   dateFunc(context, 0, 0);
00988 }
00989 
00990 /*
00991 ** current_timestamp()
00992 **
00993 ** This function returns the same value as datetime('now').
00994 */
00995 static void ctimestampFunc(
00996   sqlite3_context *context,
00997   int argc,
00998   sqlite3_value **argv
00999 ){
01000   datetimeFunc(context, 0, 0);
01001 }
01002 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
01003 
01004 #ifdef SQLITE_OMIT_DATETIME_FUNCS
01005 /*
01006 ** If the library is compiled to omit the full-scale date and time
01007 ** handling (to get a smaller binary), the following minimal version
01008 ** of the functions current_time(), current_date() and current_timestamp()
01009 ** are included instead. This is to support column declarations that
01010 ** include "DEFAULT CURRENT_TIME" etc.
01011 **
01012 ** This function uses the C-library functions time(), gmtime()
01013 ** and strftime(). The format string to pass to strftime() is supplied
01014 ** as the user-data for the function.
01015 */
01016 static void currentTimeFunc(
01017   sqlite3_context *context,
01018   int argc,
01019   sqlite3_value **argv
01020 ){
01021   time_t t;
01022   char *zFormat = (char *)sqlite3_user_data(context);
01023   sqlite3 *db;
01024   double rT;
01025   char zBuf[20];
01026 
01027   db = sqlite3_context_db_handle(context);
01028   sqlite3OsCurrentTime(db->pVfs, &rT);
01029   t = 86400.0*(rT - 2440587.5) + 0.5;
01030 #ifdef HAVE_GMTIME_R
01031   {
01032     struct tm sNow;
01033     gmtime_r(&t, &sNow);
01034     strftime(zBuf, 20, zFormat, &sNow);
01035   }
01036 #else
01037   {
01038     struct tm *pTm;
01039     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
01040     pTm = gmtime(&t);
01041     strftime(zBuf, 20, zFormat, pTm);
01042     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
01043   }
01044 #endif
01045 
01046   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
01047 }
01048 #endif
01049 
01050 /*
01051 ** This function registered all of the above C functions as SQL
01052 ** functions.  This should be the only routine in this file with
01053 ** external linkage.
01054 */
01055 void sqlite3RegisterDateTimeFunctions(void){
01056   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
01057 #ifndef SQLITE_OMIT_DATETIME_FUNCS
01058     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
01059     FUNCTION(date,             -1, 0, 0, dateFunc      ),
01060     FUNCTION(time,             -1, 0, 0, timeFunc      ),
01061     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
01062     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
01063     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
01064     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
01065     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
01066 #else
01067     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
01068     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
01069     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
01070 #endif
01071   };
01072   int i;
01073   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
01074   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
01075 
01076   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
01077     sqlite3FuncDefInsert(pHash, &aFunc[i]);
01078   }
01079 }

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:52 2011 by Doxygen 1.6.1