000001  /*
000002  ** 2003 October 31
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file contains the C functions that implement date and time
000013  ** functions for SQLite.  
000014  **
000015  ** There is only one exported symbol in this file - the function
000016  ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
000017  ** All other code has file scope.
000018  **
000019  ** SQLite processes all times and dates as julian day numbers.  The
000020  ** dates and times are stored as the number of days since noon
000021  ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
000022  ** calendar system. 
000023  **
000024  ** 1970-01-01 00:00:00 is JD 2440587.5
000025  ** 2000-01-01 00:00:00 is JD 2451544.5
000026  **
000027  ** This implementation requires years to be expressed as a 4-digit number
000028  ** which means that only dates between 0000-01-01 and 9999-12-31 can
000029  ** be represented, even though julian day numbers allow a much wider
000030  ** range of dates.
000031  **
000032  ** The Gregorian calendar system is used for all dates and times,
000033  ** even those that predate the Gregorian calendar.  Historians usually
000034  ** use the julian calendar for dates prior to 1582-10-15 and for some
000035  ** dates afterwards, depending on locale.  Beware of this difference.
000036  **
000037  ** The conversion algorithms are implemented based on descriptions
000038  ** in the following text:
000039  **
000040  **      Jean Meeus
000041  **      Astronomical Algorithms, 2nd Edition, 1998
000042  **      ISBM 0-943396-61-1
000043  **      Willmann-Bell, Inc
000044  **      Richmond, Virginia (USA)
000045  */
000046  #include "sqliteInt.h"
000047  #include <stdlib.h>
000048  #include <assert.h>
000049  #include <time.h>
000050  
000051  #ifndef SQLITE_OMIT_DATETIME_FUNCS
000052  
000053  /*
000054  ** The MSVC CRT on Windows CE may not have a localtime() function.
000055  ** So declare a substitute.  The substitute function itself is
000056  ** defined in "os_win.c".
000057  */
000058  #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
000059      (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
000060  struct tm *__cdecl localtime(const time_t *);
000061  #endif
000062  
000063  /*
000064  ** A structure for holding a single date and time.
000065  */
000066  typedef struct DateTime DateTime;
000067  struct DateTime {
000068    sqlite3_int64 iJD;  /* The julian day number times 86400000 */
000069    int Y, M, D;        /* Year, month, and day */
000070    int h, m;           /* Hour and minutes */
000071    int tz;             /* Timezone offset in minutes */
000072    double s;           /* Seconds */
000073    char validJD;       /* True (1) if iJD is valid */
000074    char rawS;          /* Raw numeric value stored in s */
000075    char validYMD;      /* True (1) if Y,M,D are valid */
000076    char validHMS;      /* True (1) if h,m,s are valid */
000077    char validTZ;       /* True (1) if tz is valid */
000078    char tzSet;         /* Timezone was set explicitly */
000079    char isError;       /* An overflow has occurred */
000080  };
000081  
000082  
000083  /*
000084  ** Convert zDate into one or more integers according to the conversion
000085  ** specifier zFormat.
000086  **
000087  ** zFormat[] contains 4 characters for each integer converted, except for
000088  ** the last integer which is specified by three characters.  The meaning
000089  ** of a four-character format specifiers ABCD is:
000090  **
000091  **    A:   number of digits to convert.  Always "2" or "4".
000092  **    B:   minimum value.  Always "0" or "1".
000093  **    C:   maximum value, decoded as:
000094  **           a:  12
000095  **           b:  14
000096  **           c:  24
000097  **           d:  31
000098  **           e:  59
000099  **           f:  9999
000100  **    D:   the separator character, or \000 to indicate this is the
000101  **         last number to convert.
000102  **
000103  ** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
000104  ** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
000105  ** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
000106  ** the 2-digit day which is the last integer in the set.
000107  **
000108  ** The function returns the number of successful conversions.
000109  */
000110  static int getDigits(const char *zDate, const char *zFormat, ...){
000111    /* The aMx[] array translates the 3rd character of each format
000112    ** spec into a max size:    a   b   c   d   e     f */
000113    static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
000114    va_list ap;
000115    int cnt = 0;
000116    char nextC;
000117    va_start(ap, zFormat);
000118    do{
000119      char N = zFormat[0] - '0';
000120      char min = zFormat[1] - '0';
000121      int val = 0;
000122      u16 max;
000123  
000124      assert( zFormat[2]>='a' && zFormat[2]<='f' );
000125      max = aMx[zFormat[2] - 'a'];
000126      nextC = zFormat[3];
000127      val = 0;
000128      while( N-- ){
000129        if( !sqlite3Isdigit(*zDate) ){
000130          goto end_getDigits;
000131        }
000132        val = val*10 + *zDate - '0';
000133        zDate++;
000134      }
000135      if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
000136        goto end_getDigits;
000137      }
000138      *va_arg(ap,int*) = val;
000139      zDate++;
000140      cnt++;
000141      zFormat += 4;
000142    }while( nextC );
000143  end_getDigits:
000144    va_end(ap);
000145    return cnt;
000146  }
000147  
000148  /*
000149  ** Parse a timezone extension on the end of a date-time.
000150  ** The extension is of the form:
000151  **
000152  **        (+/-)HH:MM
000153  **
000154  ** Or the "zulu" notation:
000155  **
000156  **        Z
000157  **
000158  ** If the parse is successful, write the number of minutes
000159  ** of change in p->tz and return 0.  If a parser error occurs,
000160  ** return non-zero.
000161  **
000162  ** A missing specifier is not considered an error.
000163  */
000164  static int parseTimezone(const char *zDate, DateTime *p){
000165    int sgn = 0;
000166    int nHr, nMn;
000167    int c;
000168    while( sqlite3Isspace(*zDate) ){ zDate++; }
000169    p->tz = 0;
000170    c = *zDate;
000171    if( c=='-' ){
000172      sgn = -1;
000173    }else if( c=='+' ){
000174      sgn = +1;
000175    }else if( c=='Z' || c=='z' ){
000176      zDate++;
000177      goto zulu_time;
000178    }else{
000179      return c!=0;
000180    }
000181    zDate++;
000182    if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
000183      return 1;
000184    }
000185    zDate += 5;
000186    p->tz = sgn*(nMn + nHr*60);
000187  zulu_time:
000188    while( sqlite3Isspace(*zDate) ){ zDate++; }
000189    p->tzSet = 1;
000190    return *zDate!=0;
000191  }
000192  
000193  /*
000194  ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
000195  ** The HH, MM, and SS must each be exactly 2 digits.  The
000196  ** fractional seconds FFFF can be one or more digits.
000197  **
000198  ** Return 1 if there is a parsing error and 0 on success.
000199  */
000200  static int parseHhMmSs(const char *zDate, DateTime *p){
000201    int h, m, s;
000202    double ms = 0.0;
000203    if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
000204      return 1;
000205    }
000206    zDate += 5;
000207    if( *zDate==':' ){
000208      zDate++;
000209      if( getDigits(zDate, "20e", &s)!=1 ){
000210        return 1;
000211      }
000212      zDate += 2;
000213      if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
000214        double rScale = 1.0;
000215        zDate++;
000216        while( sqlite3Isdigit(*zDate) ){
000217          ms = ms*10.0 + *zDate - '0';
000218          rScale *= 10.0;
000219          zDate++;
000220        }
000221        ms /= rScale;
000222      }
000223    }else{
000224      s = 0;
000225    }
000226    p->validJD = 0;
000227    p->rawS = 0;
000228    p->validHMS = 1;
000229    p->h = h;
000230    p->m = m;
000231    p->s = s + ms;
000232    if( parseTimezone(zDate, p) ) return 1;
000233    p->validTZ = (p->tz!=0)?1:0;
000234    return 0;
000235  }
000236  
000237  /*
000238  ** Put the DateTime object into its error state.
000239  */
000240  static void datetimeError(DateTime *p){
000241    memset(p, 0, sizeof(*p));
000242    p->isError = 1;
000243  }
000244  
000245  /*
000246  ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
000247  ** that the YYYY-MM-DD is according to the Gregorian calendar.
000248  **
000249  ** Reference:  Meeus page 61
000250  */
000251  static void computeJD(DateTime *p){
000252    int Y, M, D, A, B, X1, X2;
000253  
000254    if( p->validJD ) return;
000255    if( p->validYMD ){
000256      Y = p->Y;
000257      M = p->M;
000258      D = p->D;
000259    }else{
000260      Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
000261      M = 1;
000262      D = 1;
000263    }
000264    if( Y<-4713 || Y>9999 || p->rawS ){
000265      datetimeError(p);
000266      return;
000267    }
000268    if( M<=2 ){
000269      Y--;
000270      M += 12;
000271    }
000272    A = Y/100;
000273    B = 2 - A + (A/4);
000274    X1 = 36525*(Y+4716)/100;
000275    X2 = 306001*(M+1)/10000;
000276    p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
000277    p->validJD = 1;
000278    if( p->validHMS ){
000279      p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
000280      if( p->validTZ ){
000281        p->iJD -= p->tz*60000;
000282        p->validYMD = 0;
000283        p->validHMS = 0;
000284        p->validTZ = 0;
000285      }
000286    }
000287  }
000288  
000289  /*
000290  ** Parse dates of the form
000291  **
000292  **     YYYY-MM-DD HH:MM:SS.FFF
000293  **     YYYY-MM-DD HH:MM:SS
000294  **     YYYY-MM-DD HH:MM
000295  **     YYYY-MM-DD
000296  **
000297  ** Write the result into the DateTime structure and return 0
000298  ** on success and 1 if the input string is not a well-formed
000299  ** date.
000300  */
000301  static int parseYyyyMmDd(const char *zDate, DateTime *p){
000302    int Y, M, D, neg;
000303  
000304    if( zDate[0]=='-' ){
000305      zDate++;
000306      neg = 1;
000307    }else{
000308      neg = 0;
000309    }
000310    if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
000311      return 1;
000312    }
000313    zDate += 10;
000314    while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
000315    if( parseHhMmSs(zDate, p)==0 ){
000316      /* We got the time */
000317    }else if( *zDate==0 ){
000318      p->validHMS = 0;
000319    }else{
000320      return 1;
000321    }
000322    p->validJD = 0;
000323    p->validYMD = 1;
000324    p->Y = neg ? -Y : Y;
000325    p->M = M;
000326    p->D = D;
000327    if( p->validTZ ){
000328      computeJD(p);
000329    }
000330    return 0;
000331  }
000332  
000333  /*
000334  ** Set the time to the current time reported by the VFS.
000335  **
000336  ** Return the number of errors.
000337  */
000338  static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
000339    p->iJD = sqlite3StmtCurrentTime(context);
000340    if( p->iJD>0 ){
000341      p->validJD = 1;
000342      return 0;
000343    }else{
000344      return 1;
000345    }
000346  }
000347  
000348  /*
000349  ** Input "r" is a numeric quantity which might be a julian day number,
000350  ** or the number of seconds since 1970.  If the value if r is within
000351  ** range of a julian day number, install it as such and set validJD.
000352  ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
000353  */
000354  static void setRawDateNumber(DateTime *p, double r){
000355    p->s = r;
000356    p->rawS = 1;
000357    if( r>=0.0 && r<5373484.5 ){
000358      p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
000359      p->validJD = 1;
000360    }
000361  }
000362  
000363  /*
000364  ** Attempt to parse the given string into a julian day number.  Return
000365  ** the number of errors.
000366  **
000367  ** The following are acceptable forms for the input string:
000368  **
000369  **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
000370  **      DDDD.DD 
000371  **      now
000372  **
000373  ** In the first form, the +/-HH:MM is always optional.  The fractional
000374  ** seconds extension (the ".FFF") is optional.  The seconds portion
000375  ** (":SS.FFF") is option.  The year and date can be omitted as long
000376  ** as there is a time string.  The time string can be omitted as long
000377  ** as there is a year and date.
000378  */
000379  static int parseDateOrTime(
000380    sqlite3_context *context, 
000381    const char *zDate, 
000382    DateTime *p
000383  ){
000384    double r;
000385    if( parseYyyyMmDd(zDate,p)==0 ){
000386      return 0;
000387    }else if( parseHhMmSs(zDate, p)==0 ){
000388      return 0;
000389    }else if( sqlite3StrICmp(zDate,"now")==0){
000390      return setDateTimeToCurrent(context, p);
000391    }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
000392      setRawDateNumber(p, r);
000393      return 0;
000394    }
000395    return 1;
000396  }
000397  
000398  /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
000399  ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
000400  ** for DateTime.iJD.
000401  **
000402  ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with 
000403  ** such a large integer literal, so we have to encode it.
000404  */
000405  #define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
000406  
000407  /*
000408  ** Return TRUE if the given julian day number is within range.
000409  **
000410  ** The input is the JulianDay times 86400000.
000411  */
000412  static int validJulianDay(sqlite3_int64 iJD){
000413    return iJD>=0 && iJD<=INT_464269060799999;
000414  }
000415  
000416  /*
000417  ** Compute the Year, Month, and Day from the julian day number.
000418  */
000419  static void computeYMD(DateTime *p){
000420    int Z, A, B, C, D, E, X1;
000421    if( p->validYMD ) return;
000422    if( !p->validJD ){
000423      p->Y = 2000;
000424      p->M = 1;
000425      p->D = 1;
000426    }else{
000427      assert( validJulianDay(p->iJD) );
000428      Z = (int)((p->iJD + 43200000)/86400000);
000429      A = (int)((Z - 1867216.25)/36524.25);
000430      A = Z + 1 + A - (A/4);
000431      B = A + 1524;
000432      C = (int)((B - 122.1)/365.25);
000433      D = (36525*(C&32767))/100;
000434      E = (int)((B-D)/30.6001);
000435      X1 = (int)(30.6001*E);
000436      p->D = B - D - X1;
000437      p->M = E<14 ? E-1 : E-13;
000438      p->Y = p->M>2 ? C - 4716 : C - 4715;
000439    }
000440    p->validYMD = 1;
000441  }
000442  
000443  /*
000444  ** Compute the Hour, Minute, and Seconds from the julian day number.
000445  */
000446  static void computeHMS(DateTime *p){
000447    int s;
000448    if( p->validHMS ) return;
000449    computeJD(p);
000450    s = (int)((p->iJD + 43200000) % 86400000);
000451    p->s = s/1000.0;
000452    s = (int)p->s;
000453    p->s -= s;
000454    p->h = s/3600;
000455    s -= p->h*3600;
000456    p->m = s/60;
000457    p->s += s - p->m*60;
000458    p->rawS = 0;
000459    p->validHMS = 1;
000460  }
000461  
000462  /*
000463  ** Compute both YMD and HMS
000464  */
000465  static void computeYMD_HMS(DateTime *p){
000466    computeYMD(p);
000467    computeHMS(p);
000468  }
000469  
000470  /*
000471  ** Clear the YMD and HMS and the TZ
000472  */
000473  static void clearYMD_HMS_TZ(DateTime *p){
000474    p->validYMD = 0;
000475    p->validHMS = 0;
000476    p->validTZ = 0;
000477  }
000478  
000479  #ifndef SQLITE_OMIT_LOCALTIME
000480  /*
000481  ** On recent Windows platforms, the localtime_s() function is available
000482  ** as part of the "Secure CRT". It is essentially equivalent to 
000483  ** localtime_r() available under most POSIX platforms, except that the 
000484  ** order of the parameters is reversed.
000485  **
000486  ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
000487  **
000488  ** If the user has not indicated to use localtime_r() or localtime_s()
000489  ** already, check for an MSVC build environment that provides 
000490  ** localtime_s().
000491  */
000492  #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
000493      && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
000494  #undef  HAVE_LOCALTIME_S
000495  #define HAVE_LOCALTIME_S 1
000496  #endif
000497  
000498  /*
000499  ** The following routine implements the rough equivalent of localtime_r()
000500  ** using whatever operating-system specific localtime facility that
000501  ** is available.  This routine returns 0 on success and
000502  ** non-zero on any kind of error.
000503  **
000504  ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
000505  ** routine will always fail.
000506  **
000507  ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
000508  ** library function localtime_r() is used to assist in the calculation of
000509  ** local time.
000510  */
000511  static int osLocaltime(time_t *t, struct tm *pTm){
000512    int rc;
000513  #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
000514    struct tm *pX;
000515  #if SQLITE_THREADSAFE>0
000516    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
000517  #endif
000518    sqlite3_mutex_enter(mutex);
000519    pX = localtime(t);
000520  #ifndef SQLITE_UNTESTABLE
000521    if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
000522  #endif
000523    if( pX ) *pTm = *pX;
000524    sqlite3_mutex_leave(mutex);
000525    rc = pX==0;
000526  #else
000527  #ifndef SQLITE_UNTESTABLE
000528    if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
000529  #endif
000530  #if HAVE_LOCALTIME_R
000531    rc = localtime_r(t, pTm)==0;
000532  #else
000533    rc = localtime_s(pTm, t);
000534  #endif /* HAVE_LOCALTIME_R */
000535  #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
000536    return rc;
000537  }
000538  #endif /* SQLITE_OMIT_LOCALTIME */
000539  
000540  
000541  #ifndef SQLITE_OMIT_LOCALTIME
000542  /*
000543  ** Compute the difference (in milliseconds) between localtime and UTC
000544  ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
000545  ** return this value and set *pRc to SQLITE_OK. 
000546  **
000547  ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
000548  ** is undefined in this case.
000549  */
000550  static sqlite3_int64 localtimeOffset(
000551    DateTime *p,                    /* Date at which to calculate offset */
000552    sqlite3_context *pCtx,          /* Write error here if one occurs */
000553    int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
000554  ){
000555    DateTime x, y;
000556    time_t t;
000557    struct tm sLocal;
000558  
000559    /* Initialize the contents of sLocal to avoid a compiler warning. */
000560    memset(&sLocal, 0, sizeof(sLocal));
000561  
000562    x = *p;
000563    computeYMD_HMS(&x);
000564    if( x.Y<1971 || x.Y>=2038 ){
000565      /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
000566      ** works for years between 1970 and 2037. For dates outside this range,
000567      ** SQLite attempts to map the year into an equivalent year within this
000568      ** range, do the calculation, then map the year back.
000569      */
000570      x.Y = 2000;
000571      x.M = 1;
000572      x.D = 1;
000573      x.h = 0;
000574      x.m = 0;
000575      x.s = 0.0;
000576    } else {
000577      int s = (int)(x.s + 0.5);
000578      x.s = s;
000579    }
000580    x.tz = 0;
000581    x.validJD = 0;
000582    computeJD(&x);
000583    t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
000584    if( osLocaltime(&t, &sLocal) ){
000585      sqlite3_result_error(pCtx, "local time unavailable", -1);
000586      *pRc = SQLITE_ERROR;
000587      return 0;
000588    }
000589    y.Y = sLocal.tm_year + 1900;
000590    y.M = sLocal.tm_mon + 1;
000591    y.D = sLocal.tm_mday;
000592    y.h = sLocal.tm_hour;
000593    y.m = sLocal.tm_min;
000594    y.s = sLocal.tm_sec;
000595    y.validYMD = 1;
000596    y.validHMS = 1;
000597    y.validJD = 0;
000598    y.rawS = 0;
000599    y.validTZ = 0;
000600    y.isError = 0;
000601    computeJD(&y);
000602    *pRc = SQLITE_OK;
000603    return y.iJD - x.iJD;
000604  }
000605  #endif /* SQLITE_OMIT_LOCALTIME */
000606  
000607  /*
000608  ** The following table defines various date transformations of the form
000609  **
000610  **            'NNN days'
000611  **
000612  ** Where NNN is an arbitrary floating-point number and "days" can be one
000613  ** of several units of time.
000614  */
000615  static const struct {
000616    u8 eType;           /* Transformation type code */
000617    u8 nName;           /* Length of th name */
000618    char *zName;        /* Name of the transformation */
000619    double rLimit;      /* Maximum NNN value for this transform */
000620    double rXform;      /* Constant used for this transform */
000621  } aXformType[] = {
000622    { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
000623    { 0, 6, "minute", 7737817680.0,   86400000.0/(24.0*60.0)      },
000624    { 0, 4, "hour",   128963628.0,    86400000.0/24.0             },
000625    { 0, 3, "day",    5373485.0,      86400000.0                  },
000626    { 1, 5, "month",  176546.0,       30.0*86400000.0             },
000627    { 2, 4, "year",   14713.0,        365.0*86400000.0            },
000628  };
000629  
000630  /*
000631  ** Process a modifier to a date-time stamp.  The modifiers are
000632  ** as follows:
000633  **
000634  **     NNN days
000635  **     NNN hours
000636  **     NNN minutes
000637  **     NNN.NNNN seconds
000638  **     NNN months
000639  **     NNN years
000640  **     start of month
000641  **     start of year
000642  **     start of week
000643  **     start of day
000644  **     weekday N
000645  **     unixepoch
000646  **     localtime
000647  **     utc
000648  **
000649  ** Return 0 on success and 1 if there is any kind of error. If the error
000650  ** is in a system call (i.e. localtime()), then an error message is written
000651  ** to context pCtx. If the error is an unrecognized modifier, no error is
000652  ** written to pCtx.
000653  */
000654  static int parseModifier(
000655    sqlite3_context *pCtx,      /* Function context */
000656    const char *z,              /* The text of the modifier */
000657    int n,                      /* Length of zMod in bytes */
000658    DateTime *p                 /* The date/time value to be modified */
000659  ){
000660    int rc = 1;
000661    double r;
000662    switch(sqlite3UpperToLower[(u8)z[0]] ){
000663  #ifndef SQLITE_OMIT_LOCALTIME
000664      case 'l': {
000665        /*    localtime
000666        **
000667        ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
000668        ** show local time.
000669        */
000670        if( sqlite3_stricmp(z, "localtime")==0 ){
000671          computeJD(p);
000672          p->iJD += localtimeOffset(p, pCtx, &rc);
000673          clearYMD_HMS_TZ(p);
000674        }
000675        break;
000676      }
000677  #endif
000678      case 'u': {
000679        /*
000680        **    unixepoch
000681        **
000682        ** Treat the current value of p->s as the number of
000683        ** seconds since 1970.  Convert to a real julian day number.
000684        */
000685        if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
000686          r = p->s*1000.0 + 210866760000000.0;
000687          if( r>=0.0 && r<464269060800000.0 ){
000688            clearYMD_HMS_TZ(p);
000689            p->iJD = (sqlite3_int64)r;
000690            p->validJD = 1;
000691            p->rawS = 0;
000692            rc = 0;
000693          }
000694        }
000695  #ifndef SQLITE_OMIT_LOCALTIME
000696        else if( sqlite3_stricmp(z, "utc")==0 ){
000697          if( p->tzSet==0 ){
000698            sqlite3_int64 c1;
000699            computeJD(p);
000700            c1 = localtimeOffset(p, pCtx, &rc);
000701            if( rc==SQLITE_OK ){
000702              p->iJD -= c1;
000703              clearYMD_HMS_TZ(p);
000704              p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
000705            }
000706            p->tzSet = 1;
000707          }else{
000708            rc = SQLITE_OK;
000709          }
000710        }
000711  #endif
000712        break;
000713      }
000714      case 'w': {
000715        /*
000716        **    weekday N
000717        **
000718        ** Move the date to the same time on the next occurrence of
000719        ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
000720        ** date is already on the appropriate weekday, this is a no-op.
000721        */
000722        if( sqlite3_strnicmp(z, "weekday ", 8)==0
000723                 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
000724                 && (n=(int)r)==r && n>=0 && r<7 ){
000725          sqlite3_int64 Z;
000726          computeYMD_HMS(p);
000727          p->validTZ = 0;
000728          p->validJD = 0;
000729          computeJD(p);
000730          Z = ((p->iJD + 129600000)/86400000) % 7;
000731          if( Z>n ) Z -= 7;
000732          p->iJD += (n - Z)*86400000;
000733          clearYMD_HMS_TZ(p);
000734          rc = 0;
000735        }
000736        break;
000737      }
000738      case 's': {
000739        /*
000740        **    start of TTTTT
000741        **
000742        ** Move the date backwards to the beginning of the current day,
000743        ** or month or year.
000744        */
000745        if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
000746        z += 9;
000747        computeYMD(p);
000748        p->validHMS = 1;
000749        p->h = p->m = 0;
000750        p->s = 0.0;
000751        p->validTZ = 0;
000752        p->validJD = 0;
000753        if( sqlite3_stricmp(z,"month")==0 ){
000754          p->D = 1;
000755          rc = 0;
000756        }else if( sqlite3_stricmp(z,"year")==0 ){
000757          computeYMD(p);
000758          p->M = 1;
000759          p->D = 1;
000760          rc = 0;
000761        }else if( sqlite3_stricmp(z,"day")==0 ){
000762          rc = 0;
000763        }
000764        break;
000765      }
000766      case '+':
000767      case '-':
000768      case '0':
000769      case '1':
000770      case '2':
000771      case '3':
000772      case '4':
000773      case '5':
000774      case '6':
000775      case '7':
000776      case '8':
000777      case '9': {
000778        double rRounder;
000779        int i;
000780        for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
000781        if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
000782          rc = 1;
000783          break;
000784        }
000785        if( z[n]==':' ){
000786          /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
000787          ** specified number of hours, minutes, seconds, and fractional seconds
000788          ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
000789          ** omitted.
000790          */
000791          const char *z2 = z;
000792          DateTime tx;
000793          sqlite3_int64 day;
000794          if( !sqlite3Isdigit(*z2) ) z2++;
000795          memset(&tx, 0, sizeof(tx));
000796          if( parseHhMmSs(z2, &tx) ) break;
000797          computeJD(&tx);
000798          tx.iJD -= 43200000;
000799          day = tx.iJD/86400000;
000800          tx.iJD -= day*86400000;
000801          if( z[0]=='-' ) tx.iJD = -tx.iJD;
000802          computeJD(p);
000803          clearYMD_HMS_TZ(p);
000804          p->iJD += tx.iJD;
000805          rc = 0;
000806          break;
000807        }
000808  
000809        /* If control reaches this point, it means the transformation is
000810        ** one of the forms like "+NNN days".  */
000811        z += n;
000812        while( sqlite3Isspace(*z) ) z++;
000813        n = sqlite3Strlen30(z);
000814        if( n>10 || n<3 ) break;
000815        if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
000816        computeJD(p);
000817        rc = 1;
000818        rRounder = r<0 ? -0.5 : +0.5;
000819        for(i=0; i<ArraySize(aXformType); i++){
000820          if( aXformType[i].nName==n
000821           && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
000822           && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
000823          ){
000824            switch( aXformType[i].eType ){
000825              case 1: { /* Special processing to add months */
000826                int x;
000827                computeYMD_HMS(p);
000828                p->M += (int)r;
000829                x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
000830                p->Y += x;
000831                p->M -= x*12;
000832                p->validJD = 0;
000833                r -= (int)r;
000834                break;
000835              }
000836              case 2: { /* Special processing to add years */
000837                int y = (int)r;
000838                computeYMD_HMS(p);
000839                p->Y += y;
000840                p->validJD = 0;
000841                r -= (int)r;
000842                break;
000843              }
000844            }
000845            computeJD(p);
000846            p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
000847            rc = 0;
000848            break;
000849          }
000850        }
000851        clearYMD_HMS_TZ(p);
000852        break;
000853      }
000854      default: {
000855        break;
000856      }
000857    }
000858    return rc;
000859  }
000860  
000861  /*
000862  ** Process time function arguments.  argv[0] is a date-time stamp.
000863  ** argv[1] and following are modifiers.  Parse them all and write
000864  ** the resulting time into the DateTime structure p.  Return 0
000865  ** on success and 1 if there are any errors.
000866  **
000867  ** If there are zero parameters (if even argv[0] is undefined)
000868  ** then assume a default value of "now" for argv[0].
000869  */
000870  static int isDate(
000871    sqlite3_context *context, 
000872    int argc, 
000873    sqlite3_value **argv, 
000874    DateTime *p
000875  ){
000876    int i, n;
000877    const unsigned char *z;
000878    int eType;
000879    memset(p, 0, sizeof(*p));
000880    if( argc==0 ){
000881      return setDateTimeToCurrent(context, p);
000882    }
000883    if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
000884                     || eType==SQLITE_INTEGER ){
000885      setRawDateNumber(p, sqlite3_value_double(argv[0]));
000886    }else{
000887      z = sqlite3_value_text(argv[0]);
000888      if( !z || parseDateOrTime(context, (char*)z, p) ){
000889        return 1;
000890      }
000891    }
000892    for(i=1; i<argc; i++){
000893      z = sqlite3_value_text(argv[i]);
000894      n = sqlite3_value_bytes(argv[i]);
000895      if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
000896    }
000897    computeJD(p);
000898    if( p->isError || !validJulianDay(p->iJD) ) return 1;
000899    return 0;
000900  }
000901  
000902  
000903  /*
000904  ** The following routines implement the various date and time functions
000905  ** of SQLite.
000906  */
000907  
000908  /*
000909  **    julianday( TIMESTRING, MOD, MOD, ...)
000910  **
000911  ** Return the julian day number of the date specified in the arguments
000912  */
000913  static void juliandayFunc(
000914    sqlite3_context *context,
000915    int argc,
000916    sqlite3_value **argv
000917  ){
000918    DateTime x;
000919    if( isDate(context, argc, argv, &x)==0 ){
000920      computeJD(&x);
000921      sqlite3_result_double(context, x.iJD/86400000.0);
000922    }
000923  }
000924  
000925  /*
000926  **    datetime( TIMESTRING, MOD, MOD, ...)
000927  **
000928  ** Return YYYY-MM-DD HH:MM:SS
000929  */
000930  static void datetimeFunc(
000931    sqlite3_context *context,
000932    int argc,
000933    sqlite3_value **argv
000934  ){
000935    DateTime x;
000936    if( isDate(context, argc, argv, &x)==0 ){
000937      char zBuf[100];
000938      computeYMD_HMS(&x);
000939      sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
000940                       x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
000941      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
000942    }
000943  }
000944  
000945  /*
000946  **    time( TIMESTRING, MOD, MOD, ...)
000947  **
000948  ** Return HH:MM:SS
000949  */
000950  static void timeFunc(
000951    sqlite3_context *context,
000952    int argc,
000953    sqlite3_value **argv
000954  ){
000955    DateTime x;
000956    if( isDate(context, argc, argv, &x)==0 ){
000957      char zBuf[100];
000958      computeHMS(&x);
000959      sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
000960      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
000961    }
000962  }
000963  
000964  /*
000965  **    date( TIMESTRING, MOD, MOD, ...)
000966  **
000967  ** Return YYYY-MM-DD
000968  */
000969  static void dateFunc(
000970    sqlite3_context *context,
000971    int argc,
000972    sqlite3_value **argv
000973  ){
000974    DateTime x;
000975    if( isDate(context, argc, argv, &x)==0 ){
000976      char zBuf[100];
000977      computeYMD(&x);
000978      sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
000979      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
000980    }
000981  }
000982  
000983  /*
000984  **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
000985  **
000986  ** Return a string described by FORMAT.  Conversions as follows:
000987  **
000988  **   %d  day of month
000989  **   %f  ** fractional seconds  SS.SSS
000990  **   %H  hour 00-24
000991  **   %j  day of year 000-366
000992  **   %J  ** julian day number
000993  **   %m  month 01-12
000994  **   %M  minute 00-59
000995  **   %s  seconds since 1970-01-01
000996  **   %S  seconds 00-59
000997  **   %w  day of week 0-6  sunday==0
000998  **   %W  week of year 00-53
000999  **   %Y  year 0000-9999
001000  **   %%  %
001001  */
001002  static void strftimeFunc(
001003    sqlite3_context *context,
001004    int argc,
001005    sqlite3_value **argv
001006  ){
001007    DateTime x;
001008    u64 n;
001009    size_t i,j;
001010    char *z;
001011    sqlite3 *db;
001012    const char *zFmt;
001013    char zBuf[100];
001014    if( argc==0 ) return;
001015    zFmt = (const char*)sqlite3_value_text(argv[0]);
001016    if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
001017    db = sqlite3_context_db_handle(context);
001018    for(i=0, n=1; zFmt[i]; i++, n++){
001019      if( zFmt[i]=='%' ){
001020        switch( zFmt[i+1] ){
001021          case 'd':
001022          case 'H':
001023          case 'm':
001024          case 'M':
001025          case 'S':
001026          case 'W':
001027            n++;
001028            /* fall thru */
001029          case 'w':
001030          case '%':
001031            break;
001032          case 'f':
001033            n += 8;
001034            break;
001035          case 'j':
001036            n += 3;
001037            break;
001038          case 'Y':
001039            n += 8;
001040            break;
001041          case 's':
001042          case 'J':
001043            n += 50;
001044            break;
001045          default:
001046            return;  /* ERROR.  return a NULL */
001047        }
001048        i++;
001049      }
001050    }
001051    testcase( n==sizeof(zBuf)-1 );
001052    testcase( n==sizeof(zBuf) );
001053    testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
001054    testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
001055    if( n<sizeof(zBuf) ){
001056      z = zBuf;
001057    }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
001058      sqlite3_result_error_toobig(context);
001059      return;
001060    }else{
001061      z = sqlite3DbMallocRawNN(db, (int)n);
001062      if( z==0 ){
001063        sqlite3_result_error_nomem(context);
001064        return;
001065      }
001066    }
001067    computeJD(&x);
001068    computeYMD_HMS(&x);
001069    for(i=j=0; zFmt[i]; i++){
001070      if( zFmt[i]!='%' ){
001071        z[j++] = zFmt[i];
001072      }else{
001073        i++;
001074        switch( zFmt[i] ){
001075          case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
001076          case 'f': {
001077            double s = x.s;
001078            if( s>59.999 ) s = 59.999;
001079            sqlite3_snprintf(7, &z[j],"%06.3f", s);
001080            j += sqlite3Strlen30(&z[j]);
001081            break;
001082          }
001083          case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
001084          case 'W': /* Fall thru */
001085          case 'j': {
001086            int nDay;             /* Number of days since 1st day of year */
001087            DateTime y = x;
001088            y.validJD = 0;
001089            y.M = 1;
001090            y.D = 1;
001091            computeJD(&y);
001092            nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
001093            if( zFmt[i]=='W' ){
001094              int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
001095              wd = (int)(((x.iJD+43200000)/86400000)%7);
001096              sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
001097              j += 2;
001098            }else{
001099              sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
001100              j += 3;
001101            }
001102            break;
001103          }
001104          case 'J': {
001105            sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
001106            j+=sqlite3Strlen30(&z[j]);
001107            break;
001108          }
001109          case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
001110          case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
001111          case 's': {
001112            sqlite3_snprintf(30,&z[j],"%lld",
001113                             (i64)(x.iJD/1000 - 21086676*(i64)10000));
001114            j += sqlite3Strlen30(&z[j]);
001115            break;
001116          }
001117          case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
001118          case 'w': {
001119            z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
001120            break;
001121          }
001122          case 'Y': {
001123            sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
001124            break;
001125          }
001126          default:   z[j++] = '%'; break;
001127        }
001128      }
001129    }
001130    z[j] = 0;
001131    sqlite3_result_text(context, z, -1,
001132                        z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
001133  }
001134  
001135  /*
001136  ** current_time()
001137  **
001138  ** This function returns the same value as time('now').
001139  */
001140  static void ctimeFunc(
001141    sqlite3_context *context,
001142    int NotUsed,
001143    sqlite3_value **NotUsed2
001144  ){
001145    UNUSED_PARAMETER2(NotUsed, NotUsed2);
001146    timeFunc(context, 0, 0);
001147  }
001148  
001149  /*
001150  ** current_date()
001151  **
001152  ** This function returns the same value as date('now').
001153  */
001154  static void cdateFunc(
001155    sqlite3_context *context,
001156    int NotUsed,
001157    sqlite3_value **NotUsed2
001158  ){
001159    UNUSED_PARAMETER2(NotUsed, NotUsed2);
001160    dateFunc(context, 0, 0);
001161  }
001162  
001163  /*
001164  ** current_timestamp()
001165  **
001166  ** This function returns the same value as datetime('now').
001167  */
001168  static void ctimestampFunc(
001169    sqlite3_context *context,
001170    int NotUsed,
001171    sqlite3_value **NotUsed2
001172  ){
001173    UNUSED_PARAMETER2(NotUsed, NotUsed2);
001174    datetimeFunc(context, 0, 0);
001175  }
001176  #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
001177  
001178  #ifdef SQLITE_OMIT_DATETIME_FUNCS
001179  /*
001180  ** If the library is compiled to omit the full-scale date and time
001181  ** handling (to get a smaller binary), the following minimal version
001182  ** of the functions current_time(), current_date() and current_timestamp()
001183  ** are included instead. This is to support column declarations that
001184  ** include "DEFAULT CURRENT_TIME" etc.
001185  **
001186  ** This function uses the C-library functions time(), gmtime()
001187  ** and strftime(). The format string to pass to strftime() is supplied
001188  ** as the user-data for the function.
001189  */
001190  static void currentTimeFunc(
001191    sqlite3_context *context,
001192    int argc,
001193    sqlite3_value **argv
001194  ){
001195    time_t t;
001196    char *zFormat = (char *)sqlite3_user_data(context);
001197    sqlite3_int64 iT;
001198    struct tm *pTm;
001199    struct tm sNow;
001200    char zBuf[20];
001201  
001202    UNUSED_PARAMETER(argc);
001203    UNUSED_PARAMETER(argv);
001204  
001205    iT = sqlite3StmtCurrentTime(context);
001206    if( iT<=0 ) return;
001207    t = iT/1000 - 10000*(sqlite3_int64)21086676;
001208  #if HAVE_GMTIME_R
001209    pTm = gmtime_r(&t, &sNow);
001210  #else
001211    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
001212    pTm = gmtime(&t);
001213    if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
001214    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
001215  #endif
001216    if( pTm ){
001217      strftime(zBuf, 20, zFormat, &sNow);
001218      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
001219    }
001220  }
001221  #endif
001222  
001223  /*
001224  ** This function registered all of the above C functions as SQL
001225  ** functions.  This should be the only routine in this file with
001226  ** external linkage.
001227  */
001228  void sqlite3RegisterDateTimeFunctions(void){
001229    static FuncDef aDateTimeFuncs[] = {
001230  #ifndef SQLITE_OMIT_DATETIME_FUNCS
001231      DFUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
001232      DFUNCTION(date,             -1, 0, 0, dateFunc      ),
001233      DFUNCTION(time,             -1, 0, 0, timeFunc      ),
001234      DFUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
001235      DFUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
001236      DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
001237      DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
001238      DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
001239  #else
001240      STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
001241      STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
001242      STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
001243  #endif
001244    };
001245    sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
001246  }