interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / date.c

1922 lines · 51856 bytes Raw Blame History
1/*
2** 2003 October 31
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 date and time
13** functions for SQLite.
14**
15** There is only one exported symbol in this file - the function
16** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
17** All other code has file scope.
18**
19** SQLite processes all times and dates as julian day numbers. The
20** dates and times are stored as the number of days since noon
21** in Greenwich on November 24, 4714 B.C. according to the Gregorian
22** calendar system.
23**
24** 1970-01-01 00:00:00 is JD 2440587.5
25** 2000-01-01 00:00:00 is JD 2451544.5
26**
27** This implementation requires years to be expressed as a 4-digit number
28** which means that only dates between 0000-01-01 and 9999-12-31 can
29** be represented, even though julian day numbers allow a much wider
30** range of dates.
31**
32** The Gregorian calendar system is used for all dates and times,
33** even those that predate the Gregorian calendar. Historians usually
34** use the julian calendar for dates prior to 1582-10-15 and for some
35** dates afterwards, depending on locale. Beware of this difference.
36**
37** The conversion algorithms are implemented based on descriptions
38** in the following text:
39**
40** Jean Meeus
41** Astronomical Algorithms, 2nd Edition, 1998
42** ISBN 0-943396-61-1
43** Willmann-Bell, Inc
44** Richmond, Virginia (USA)
45*/
46#include "sqliteInt.h"
47#include <stdlib.h>
48#include <assert.h>
49#include <time.h>
50
51#ifndef SQLITE_OMIT_DATETIME_FUNCS
52
53/*
54** The MSVC CRT on Windows CE may not have a localtime() function.
55** So declare a substitute. The substitute function itself is
56** defined in "os_win.c".
57*/
58#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
59 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
60struct tm *__cdecl localtime(const time_t *);
61#endif
62
63/*
64** A structure for holding a single date and time.
65*/
66typedef struct DateTime DateTime;
67struct DateTime {
68 sqlite3_int64 iJD; /* The julian day number times 86400000 */
69 int Y, M, D; /* Year, month, and day */
70 int h, m; /* Hour and minutes */
71 int tz; /* Timezone offset in minutes */
72 double s; /* Seconds */
73 char validJD; /* True (1) if iJD is valid */
74 char validYMD; /* True (1) if Y,M,D are valid */
75 char validHMS; /* True (1) if h,m,s are valid */
76 char nFloor; /* Days to implement "floor" */
77 unsigned rawS : 1; /* Raw numeric value stored in s */
78 unsigned isError : 1; /* An overflow has occurred */
79 unsigned useSubsec : 1; /* Display subsecond precision */
80 unsigned isUtc : 1; /* Time is known to be UTC */
81 unsigned isLocal : 1; /* Time is known to be localtime */
82};
83
84
85/*
86** Convert zDate into one or more integers according to the conversion
87** specifier zFormat.
88**
89** zFormat[] contains 4 characters for each integer converted, except for
90** the last integer which is specified by three characters. The meaning
91** of a four-character format specifiers ABCD is:
92**
93** A: number of digits to convert. Always "2" or "4".
94** B: minimum value. Always "0" or "1".
95** C: maximum value, decoded as:
96** a: 12
97** b: 14
98** c: 24
99** d: 31
100** e: 59
101** f: 9999
102** D: the separator character, or \000 to indicate this is the
103** last number to convert.
104**
105** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
106** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
107** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
108** the 2-digit day which is the last integer in the set.
109**
110** The function returns the number of successful conversions.
111*/
112static int getDigits(const char *zDate, const char *zFormat, ...){
113 /* The aMx[] array translates the 3rd character of each format
114 ** spec into a max size: a b c d e f */
115 static const u16 aMx[] = { 12, 14, 24, 31, 59, 14712 };
116 va_list ap;
117 int cnt = 0;
118 char nextC;
119 va_start(ap, zFormat);
120 do{
121 char N = zFormat[0] - '0';
122 char min = zFormat[1] - '0';
123 int val = 0;
124 u16 max;
125
126 assert( zFormat[2]>='a' && zFormat[2]<='f' );
127 max = aMx[zFormat[2] - 'a'];
128 nextC = zFormat[3];
129 val = 0;
130 while( N-- ){
131 if( !sqlite3Isdigit(*zDate) ){
132 goto end_getDigits;
133 }
134 val = val*10 + *zDate - '0';
135 zDate++;
136 }
137 if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
138 goto end_getDigits;
139 }
140 *va_arg(ap,int*) = val;
141 zDate++;
142 cnt++;
143 zFormat += 4;
144 }while( nextC );
145end_getDigits:
146 va_end(ap);
147 return cnt;
148}
149
150/*
151** Parse a timezone extension on the end of a date-time.
152** The extension is of the form:
153**
154** (+/-)HH:MM
155**
156** Or the "zulu" notation:
157**
158** Z
159**
160** If the parse is successful, write the number of minutes
161** of change in p->tz and return 0. If a parser error occurs,
162** return non-zero.
163**
164** A missing specifier is not considered an error.
165*/
166static int parseTimezone(const char *zDate, DateTime *p){
167 int sgn = 0;
168 int nHr, nMn;
169 int c;
170 while( sqlite3Isspace(*zDate) ){ zDate++; }
171 p->tz = 0;
172 c = *zDate;
173 if( c=='-' ){
174 sgn = -1;
175 }else if( c=='+' ){
176 sgn = +1;
177 }else if( c=='Z' || c=='z' ){
178 zDate++;
179 p->isLocal = 0;
180 p->isUtc = 1;
181 goto zulu_time;
182 }else{
183 return c!=0;
184 }
185 zDate++;
186 if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
187 return 1;
188 }
189 zDate += 5;
190 p->tz = sgn*(nMn + nHr*60);
191 if( p->tz==0 ){ /* Forum post 2025-09-17T10:12:14z */
192 p->isLocal = 0;
193 p->isUtc = 1;
194 }
195zulu_time:
196 while( sqlite3Isspace(*zDate) ){ zDate++; }
197 return *zDate!=0;
198}
199
200/*
201** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
202** The HH, MM, and SS must each be exactly 2 digits. The
203** fractional seconds FFFF can be one or more digits.
204**
205** Return 1 if there is a parsing error and 0 on success.
206*/
207static int parseHhMmSs(const char *zDate, DateTime *p, int bAllowTZ){
208 int h, m, s;
209 double ms = 0.0;
210 if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
211 return 1;
212 }
213 zDate += 5;
214 if( *zDate==':' ){
215 zDate++;
216 if( getDigits(zDate, "20e", &s)!=1 ){
217 return 1;
218 }
219 zDate += 2;
220 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
221 double rScale = 1.0;
222 zDate++;
223 while( sqlite3Isdigit(*zDate) ){
224 ms = ms*10.0 + *zDate - '0';
225 rScale *= 10.0;
226 zDate++;
227 }
228 ms /= rScale;
229 /* Truncate to avoid problems with sub-milliseconds
230 ** rounding. https://sqlite.org/forum/forumpost/766a2c9231 */
231 if( ms>0.999 ) ms = 0.999;
232 }
233 }else{
234 s = 0;
235 }
236 if( h==24 && (m!=0 || s!=0 || ms!=0.0) ) return 1;
237 p->validJD = 0;
238 p->rawS = 0;
239 p->validHMS = 1;
240 p->h = h;
241 p->m = m;
242 p->s = s + ms;
243 if( !bAllowTZ && zDate[0] ) return 1;
244 if( parseTimezone(zDate, p) ) return 1;
245 return 0;
246}
247
248/*
249** Put the DateTime object into its error state.
250*/
251static void datetimeError(DateTime *p){
252 memset(p, 0, sizeof(*p));
253 p->isError = 1;
254}
255
256/*
257** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
258** that the YYYY-MM-DD is according to the Gregorian calendar.
259**
260** Reference: Meeus page 61
261*/
262static void computeJD(DateTime *p){
263 int Y, M, D, A, B, X1, X2;
264
265 if( p->validJD ) return;
266 if( p->validYMD ){
267 Y = p->Y;
268 M = p->M;
269 D = p->D;
270 }else{
271 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
272 M = 1;
273 D = 1;
274 if( p->validHMS && p->h==24 ){
275 p->h = 0;
276 D = 2;
277 }
278 }
279 if( Y<-4713 || Y>9999 || p->rawS ){
280 datetimeError(p);
281 return;
282 }
283 if( M<=2 ){
284 Y--;
285 M += 12;
286 }
287 A = (Y+4800)/100;
288 B = 38 - A + (A/4);
289 X1 = 36525*(Y+4716)/100;
290 X2 = 306001*(M+1)/10000;
291 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
292 p->validJD = 1;
293 if( p->validHMS ){
294 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000 + 0.5);
295 if( p->tz ){
296 p->iJD -= p->tz*60000;
297 p->validYMD = 0;
298 p->validHMS = 0;
299 p->tz = 0;
300 p->isUtc = 1;
301 p->isLocal = 0;
302 }
303 }
304}
305
306/*
307** Return the number of dates in a specific month.
308*/
309static int daysOfMonth(int Y, int M){
310 if( (1<<M) & 0x15aa ){
311 return 31;
312 }else if( M!=2 ){
313 return 30;
314 }else if( Y%4==0 && (Y%100!=0 || Y%400==0) ){
315 return 29;
316 }else{
317 return 28;
318 }
319}
320
321/*
322** Given the YYYY-MM-DD information current in p, determine if there
323** is day-of-month overflow and set nFloor to the number of days that
324** would need to be subtracted from the date in order to bring the
325** date back to the end of the month.
326*/
327static void computeFloor(DateTime *p){
328 int mxD; /* Maximum day number for the current month */
329 assert( p->validYMD || p->isError );
330 assert( p->D>=0 && p->D<=32 );
331 assert( p->M>=0 && p->M<=12 );
332 mxD = daysOfMonth(p->Y, p->M);
333 p->nFloor = p->D>mxD ? p->D - mxD : 0;
334}
335
336/*
337** Parse dates of the form
338**
339** YYYY-MM-DD HH:MM:SS.FFF
340** YYYY-MM-DD HH:MM:SS
341** YYYY-MM-DD HH:MM
342** YYYY-MM-DD
343**
344** Write the result into the DateTime structure and return 0
345** on success and 1 if the input string is not a well-formed
346** date.
347*/
348static int parseYyyyMmDd(const char *zDate, DateTime *p){
349 int Y, M, D, neg;
350
351 if( zDate[0]=='-' ){
352 zDate++;
353 neg = 1;
354 }else{
355 neg = 0;
356 }
357 if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
358 return 1;
359 }
360 if( neg ) Y = -Y;
361 zDate += 10;
362 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
363 if( parseHhMmSs(zDate, p, 1)==0 ){
364 if( p->h==24 ){
365 int mxD = daysOfMonth(Y,M);
366 p->h = 0;
367 D++;
368 if( D>mxD ){
369 D -= mxD;
370 M++;
371 if( M>12 ){
372 M = 1;
373 Y++;
374 }
375 }
376 }
377 }else if( *zDate==0 ){
378 p->validHMS = 0;
379 }else{
380 return 1;
381 }
382 p->validJD = 0;
383 p->validYMD = 1;
384 p->Y = Y;
385 p->M = M;
386 p->D = D;
387 computeFloor(p);
388 if( p->tz ){
389 computeJD(p);
390 }
391 return 0;
392}
393
394
395static void clearYMD_HMS_TZ(DateTime *p); /* Forward declaration */
396
397/*
398** Set the time to the current time reported by the VFS.
399**
400** Return the number of errors.
401*/
402static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
403 p->iJD = sqlite3StmtCurrentTime(context);
404 if( p->iJD>0 ){
405 p->validJD = 1;
406 p->isUtc = 1;
407 p->isLocal = 0;
408 clearYMD_HMS_TZ(p);
409 return 0;
410 }else{
411 return 1;
412 }
413}
414
415/*
416** Input "r" is a numeric quantity which might be a julian day number,
417** or the number of seconds since 1970. If the value if r is within
418** range of a julian day number, install it as such and set validJD.
419** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
420*/
421static void setRawDateNumber(DateTime *p, double r){
422 p->s = r;
423 p->rawS = 1;
424 if( r>=0.0 && r<5373484.5 ){
425 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
426 p->validJD = 1;
427 }
428}
429
430/*
431** Attempt to parse the given string into a julian day number. Return
432** the number of errors.
433**
434** The following are acceptable forms for the input string:
435**
436** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
437** DDDD.DD
438** now
439**
440** In the first form, the +/-HH:MM is always optional. The fractional
441** seconds extension (the ".FFF") is optional. The seconds portion
442** (":SS.FFF") is option. The year and date can be omitted as long
443** as there is a time string. The time string can be omitted as long
444** as there is a year and date.
445*/
446static int parseDateOrTime(
447 sqlite3_context *context,
448 const char *zDate,
449 DateTime *p
450){
451 double r;
452 if( parseYyyyMmDd(zDate,p)==0 ){
453 return 0;
454 }else if( parseHhMmSs(zDate, p, 1)==0 ){
455 return 0;
456 }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
457 return setDateTimeToCurrent(context, p);
458 }else if( sqlite3AtoF(zDate, &r)>0 ){
459 setRawDateNumber(p, r);
460 return 0;
461 }else if( (sqlite3StrICmp(zDate,"subsec")==0
462 || sqlite3StrICmp(zDate,"subsecond")==0)
463 && sqlite3NotPureFunc(context) ){
464 p->useSubsec = 1;
465 return setDateTimeToCurrent(context, p);
466 }
467 return 1;
468}
469
470/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
471** Multiplying this by 86400000 gives 464269060799999 as the maximum value
472** for DateTime.iJD.
473**
474** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
475** such a large integer literal, so we have to encode it.
476*/
477#define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
478
479/*
480** Return TRUE if the given julian day number is within range.
481**
482** The input is the JulianDay times 86400000.
483*/
484static int validJulianDay(sqlite3_int64 iJD){
485 return iJD>=0 && iJD<=INT_464269060799999;
486}
487
488/*
489** Compute the Year, Month, and Day from the julian day number.
490*/
491static void computeYMD(DateTime *p){
492 int Z, alpha, A, B, C, D, E, X1;
493 if( p->validYMD ) return;
494 if( !p->validJD ){
495 p->Y = 2000;
496 p->M = 1;
497 p->D = 1;
498 }else if( !validJulianDay(p->iJD) ){
499 datetimeError(p);
500 return;
501 }else{
502 Z = (int)((p->iJD + 43200000)/86400000);
503 alpha = (int)((Z + 32044.75)/36524.25) - 52;
504 A = Z + 1 + alpha - ((alpha+100)/4) + 25;
505 B = A + 1524;
506 C = (int)((B - 122.1)/365.25);
507 D = (36525*(C&32767))/100;
508 E = (int)((B-D)/30.6001);
509 X1 = (int)(30.6001*E);
510 p->D = B - D - X1;
511 p->M = E<14 ? E-1 : E-13;
512 p->Y = p->M>2 ? C - 4716 : C - 4715;
513 }
514 p->validYMD = 1;
515}
516
517/*
518** Compute the Hour, Minute, and Seconds from the julian day number.
519*/
520static void computeHMS(DateTime *p){
521 int day_ms, day_min; /* milliseconds, minutes into the day */
522 if( p->validHMS ) return;
523 computeJD(p);
524 day_ms = (int)((p->iJD + 43200000) % 86400000);
525 p->s = (day_ms % 60000)/1000.0;
526 day_min = day_ms/60000;
527 p->m = day_min % 60;
528 p->h = day_min / 60;
529 p->rawS = 0;
530 p->validHMS = 1;
531}
532
533/*
534** Compute both YMD and HMS
535*/
536static void computeYMD_HMS(DateTime *p){
537 computeYMD(p);
538 computeHMS(p);
539}
540
541/*
542** Clear the YMD and HMS and the TZ
543*/
544static void clearYMD_HMS_TZ(DateTime *p){
545 p->validYMD = 0;
546 p->validHMS = 0;
547 p->tz = 0;
548}
549
550#ifndef SQLITE_OMIT_LOCALTIME
551/*
552** On recent Windows platforms, the localtime_s() function is available
553** as part of the "Secure CRT". It is essentially equivalent to
554** localtime_r() available under most POSIX platforms, except that the
555** order of the parameters is reversed.
556**
557** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
558**
559** If the user has not indicated to use localtime_r() or localtime_s()
560** already, check for an MSVC build environment that provides
561** localtime_s().
562*/
563#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
564 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
565#undef HAVE_LOCALTIME_S
566#define HAVE_LOCALTIME_S 1
567#endif
568
569/*
570** The following routine implements the rough equivalent of localtime_r()
571** using whatever operating-system specific localtime facility that
572** is available. This routine returns 0 on success and
573** non-zero on any kind of error.
574**
575** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this
576** routine will always fail. If bLocaltimeFault is nonzero and
577** sqlite3GlobalConfig.xAltLocaltime is not NULL, then xAltLocaltime() is
578** invoked in place of the OS-defined localtime() function.
579**
580** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
581** library function localtime_r() is used to assist in the calculation of
582** local time.
583*/
584static int osLocaltime(time_t *t, struct tm *pTm){
585 int rc;
586#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
587 struct tm *pX;
588#if SQLITE_THREADSAFE>0
589 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
590#endif
591 sqlite3_mutex_enter(mutex);
592 pX = localtime(t);
593#ifndef SQLITE_UNTESTABLE
594 if( sqlite3GlobalConfig.bLocaltimeFault ){
595 if( sqlite3GlobalConfig.xAltLocaltime!=0
596 && 0==sqlite3GlobalConfig.xAltLocaltime((const void*)t,(void*)pTm)
597 ){
598 pX = pTm;
599 }else{
600 pX = 0;
601 }
602 }
603#endif
604 if( pX ) *pTm = *pX;
605#if SQLITE_THREADSAFE>0
606 sqlite3_mutex_leave(mutex);
607#endif
608 rc = pX==0;
609#else
610#ifndef SQLITE_UNTESTABLE
611 if( sqlite3GlobalConfig.bLocaltimeFault ){
612 if( sqlite3GlobalConfig.xAltLocaltime!=0 ){
613 return sqlite3GlobalConfig.xAltLocaltime((const void*)t,(void*)pTm);
614 }else{
615 return 1;
616 }
617 }
618#endif
619#if HAVE_LOCALTIME_R
620 rc = localtime_r(t, pTm)==0;
621#else
622 rc = localtime_s(pTm, t);
623#endif /* HAVE_LOCALTIME_R */
624#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
625 return rc;
626}
627#endif /* SQLITE_OMIT_LOCALTIME */
628
629
630#ifndef SQLITE_OMIT_LOCALTIME
631/*
632** Assuming the input DateTime is UTC, move it to its localtime equivalent.
633*/
634static int toLocaltime(
635 DateTime *p, /* Date at which to calculate offset */
636 sqlite3_context *pCtx /* Write error here if one occurs */
637){
638 time_t t;
639 struct tm sLocal;
640 int iYearDiff;
641
642 /* Initialize the contents of sLocal to avoid a compiler warning. */
643 memset(&sLocal, 0, sizeof(sLocal));
644
645 computeJD(p);
646 if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */
647 || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */
648 ){
649 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
650 ** works for years between 1970 and 2037. For dates outside this range,
651 ** SQLite attempts to map the year into an equivalent year within this
652 ** range, do the calculation, then map the year back.
653 */
654 DateTime x = *p;
655 computeYMD_HMS(&x);
656 iYearDiff = (2000 + x.Y%4) - x.Y;
657 x.Y += iYearDiff;
658 x.validJD = 0;
659 computeJD(&x);
660 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
661 }else{
662 iYearDiff = 0;
663 t = (time_t)(p->iJD/1000 - 21086676*(i64)10000);
664 }
665 if( osLocaltime(&t, &sLocal) ){
666 sqlite3_result_error(pCtx, "local time unavailable", -1);
667 return SQLITE_ERROR;
668 }
669 p->Y = sLocal.tm_year + 1900 - iYearDiff;
670 p->M = sLocal.tm_mon + 1;
671 p->D = sLocal.tm_mday;
672 p->h = sLocal.tm_hour;
673 p->m = sLocal.tm_min;
674 p->s = sLocal.tm_sec + (p->iJD%1000)*0.001;
675 p->validYMD = 1;
676 p->validHMS = 1;
677 p->validJD = 0;
678 p->rawS = 0;
679 p->tz = 0;
680 p->isError = 0;
681 return SQLITE_OK;
682}
683#endif /* SQLITE_OMIT_LOCALTIME */
684
685/*
686** The following table defines various date transformations of the form
687**
688** 'NNN days'
689**
690** Where NNN is an arbitrary floating-point number and "days" can be one
691** of several units of time.
692*/
693static const struct {
694 u8 nName; /* Length of the name */
695 char zName[7]; /* Name of the transformation */
696 float rLimit; /* Maximum NNN value for this transform */
697 float rXform; /* Constant used for this transform */
698} aXformType[] = {
699 /* 0 */ { 6, "second", 4.6427e+14, 1.0 },
700 /* 1 */ { 6, "minute", 7.7379e+12, 60.0 },
701 /* 2 */ { 4, "hour", 1.2897e+11, 3600.0 },
702 /* 3 */ { 3, "day", 5373485.0, 86400.0 },
703 /* 4 */ { 5, "month", 176546.0, 2592000.0 },
704 /* 5 */ { 4, "year", 14713.0, 31536000.0 },
705};
706
707/*
708** If the DateTime p is raw number, try to figure out if it is
709** a julian day number of a unix timestamp. Set the p value
710** appropriately.
711*/
712static void autoAdjustDate(DateTime *p){
713 if( !p->rawS || p->validJD ){
714 p->rawS = 0;
715 }else if( p->s>=-21086676*(i64)10000 /* -4713-11-24 12:00:00 */
716 && p->s<=(25340230*(i64)10000)+799 /* 9999-12-31 23:59:59 */
717 ){
718 double r = p->s*1000.0 + 210866760000000.0;
719 clearYMD_HMS_TZ(p);
720 p->iJD = (sqlite3_int64)(r + 0.5);
721 p->validJD = 1;
722 p->rawS = 0;
723 }
724}
725
726/*
727** Process a modifier to a date-time stamp. The modifiers are
728** as follows:
729**
730** NNN days
731** NNN hours
732** NNN minutes
733** NNN.NNNN seconds
734** NNN months
735** NNN years
736** +/-YYYY-MM-DD HH:MM:SS.SSS
737** ceiling
738** floor
739** start of month
740** start of year
741** start of week
742** start of day
743** weekday N
744** unixepoch
745** auto
746** localtime
747** utc
748** subsec
749** subsecond
750**
751** Return 0 on success and 1 if there is any kind of error. If the error
752** is in a system call (i.e. localtime()), then an error message is written
753** to context pCtx. If the error is an unrecognized modifier, no error is
754** written to pCtx.
755*/
756static int parseModifier(
757 sqlite3_context *pCtx, /* Function context */
758 const char *z, /* The text of the modifier */
759 int n, /* Length of zMod in bytes */
760 DateTime *p, /* The date/time value to be modified */
761 int idx /* Parameter index of the modifier */
762){
763 int rc = 1;
764 double r;
765 switch(sqlite3UpperToLower[(u8)z[0]] ){
766 case 'a': {
767 /*
768 ** auto
769 **
770 ** If rawS is available, then interpret as a julian day number, or
771 ** a unix timestamp, depending on its magnitude.
772 */
773 if( sqlite3_stricmp(z, "auto")==0 ){
774 if( idx>1 ) return 1; /* IMP: R-33611-57934 */
775 autoAdjustDate(p);
776 rc = 0;
777 }
778 break;
779 }
780 case 'c': {
781 /*
782 ** ceiling
783 **
784 ** Resolve day-of-month overflow by rolling forward into the next
785 ** month. As this is the default action, this modifier is really
786 ** a no-op that is only included for symmetry. See "floor".
787 */
788 if( sqlite3_stricmp(z, "ceiling")==0 ){
789 computeJD(p);
790 clearYMD_HMS_TZ(p);
791 rc = 0;
792 p->nFloor = 0;
793 }
794 break;
795 }
796 case 'e': {
797 /*
798 ** end of day
799 ** end of month
800 ** end of year
801 **
802 ** Move the date forwards to the last millisecond of the current
803 ** day, month or year.
804 */
805 if( sqlite3_strnicmp(z, "end of ", 7)!=0 ){
806 break;
807 }
808 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
809 z += 7;
810 computeYMD(p);
811 p->validHMS = 1;
812 p->h = 23;
813 p->m = 59;
814 p->s = 59.999;
815 p->rawS = 0;
816 p->tz = 0;
817 p->validJD = 0;
818 if( sqlite3_stricmp(z,"month")==0 ){
819 p->D = 1;
820 p->M++;
821 if( p->M>12 ){
822 p->Y++;
823 p->M = 1;
824 }
825 computeFloor(p);
826 computeJD(p);
827 p->iJD -= (p->nFloor+1)*86400000;
828 clearYMD_HMS_TZ(p);
829 rc = 0;
830 }else if( sqlite3_stricmp(z,"year")==0 ){
831 p->M = 12;
832 p->D = 31;
833 p->nFloor = 0;
834 rc = 0;
835 }else if( sqlite3_stricmp(z,"day")==0 ){
836 rc = 0;
837 }
838 break;
839 }
840 case 'f': {
841 /*
842 ** floor
843 **
844 ** Resolve day-of-month overflow by rolling back to the end of the
845 ** previous month.
846 */
847 if( sqlite3_stricmp(z, "floor")==0 ){
848 computeJD(p);
849 p->iJD -= p->nFloor*86400000;
850 p->nFloor = 0;
851 clearYMD_HMS_TZ(p);
852 rc = 0;
853 }
854 break;
855 }
856 case 'j': {
857 /*
858 ** julianday
859 **
860 ** Always interpret the prior number as a julian-day value. If this
861 ** is not the first modifier, or if the prior argument is not a numeric
862 ** value in the allowed range of julian day numbers understood by
863 ** SQLite (0..5373484.5) then the result will be NULL.
864 */
865 if( sqlite3_stricmp(z, "julianday")==0 ){
866 if( idx>1 ) return 1; /* IMP: R-31176-64601 */
867 if( p->validJD && p->rawS ){
868 rc = 0;
869 p->rawS = 0;
870 }
871 }
872 break;
873 }
874#ifndef SQLITE_OMIT_LOCALTIME
875 case 'l': {
876 /* localtime
877 **
878 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
879 ** show local time.
880 */
881 if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
882 rc = p->isLocal ? SQLITE_OK : toLocaltime(p, pCtx);
883 p->isUtc = 0;
884 p->isLocal = 1;
885 }
886 break;
887 }
888#endif
889 case 'u': {
890 /*
891 ** unixepoch
892 **
893 ** Treat the current value of p->s as the number of
894 ** seconds since 1970. Convert to a real julian day number.
895 */
896 if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
897 if( idx>1 ) return 1; /* IMP: R-49255-55373 */
898 r = p->s*1000.0 + 210866760000000.0;
899 if( r>=0.0 && r<464269060800000.0 ){
900 clearYMD_HMS_TZ(p);
901 p->iJD = (sqlite3_int64)(r + 0.5);
902 p->validJD = 1;
903 p->rawS = 0;
904 rc = 0;
905 }
906 }
907#ifndef SQLITE_OMIT_LOCALTIME
908 else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
909 if( p->isUtc==0 ){
910 i64 iOrigJD; /* Original localtime */
911 i64 iGuess; /* Guess at the corresponding utc time */
912 int cnt = 0; /* Safety to prevent infinite loop */
913 i64 iErr; /* Guess is off by this much */
914
915 computeJD(p);
916 iGuess = iOrigJD = p->iJD;
917 iErr = 0;
918 do{
919 DateTime new;
920 memset(&new, 0, sizeof(new));
921 iGuess -= iErr;
922 new.iJD = iGuess;
923 new.validJD = 1;
924 rc = toLocaltime(&new, pCtx);
925 if( rc ) return rc;
926 computeJD(&new);
927 iErr = new.iJD - iOrigJD;
928 }while( iErr && cnt++<3 );
929 memset(p, 0, sizeof(*p));
930 p->iJD = iGuess;
931 p->validJD = 1;
932 p->isUtc = 1;
933 p->isLocal = 0;
934 }
935 rc = SQLITE_OK;
936 }
937#endif
938 break;
939 }
940 case 'w': {
941 /*
942 ** weekday N
943 ** weekday -N
944 **
945 ** Move the date forward (for N>=0) or backward (for N<=-0) to the
946 ** same time on the next/previous occurrence of weekday abs(N)
947 ** where 0==Sunday, 1==Monday, and so forth. If the date is already
948 ** on the appropriate weekday, this is a no-op.
949 */
950 if( sqlite3_strnicmp(z, "weekday ", 8)==0
951 && sqlite3AtoF(&z[8], &r)>0
952 && r>=-6.0 && r<=6.0
953 && sqlite3RealSameAsInt(r,(i64)(n=(int)r))
954 ){
955 sqlite3_int64 Z;
956 computeYMD_HMS(p);
957 p->tz = 0;
958 p->validJD = 0;
959 computeJD(p);
960 Z = ((p->iJD + 129600000)/86400000) % 7;
961 if( n<0 ) n = -n;
962 if( Z!=n ){
963 if( Z>n ) Z -= 7;
964 p->iJD += (n - Z)*86400000;
965 if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000;
966 }
967 clearYMD_HMS_TZ(p);
968 p->nFloor = 0;
969 rc = 0;
970 }
971 break;
972 }
973 case 's': {
974 /*
975 ** start of day
976 ** start of month
977 ** start of year
978 **
979 ** Move the date backwards to the beginning of the current day,
980 ** or month or year.
981 **
982 ** subsecond
983 ** subsec
984 **
985 ** Show subsecond precision in the output of datetime() and
986 ** unixepoch() and strftime('%s').
987 */
988 if( sqlite3_strnicmp(z, "start of ", 9)!=0 ){
989 if( sqlite3_stricmp(z, "subsec")==0
990 || sqlite3_stricmp(z, "subsecond")==0
991 ){
992 p->useSubsec = 1;
993 rc = 0;
994 }
995 break;
996 }
997 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
998 z += 9;
999 computeYMD(p);
1000 p->validHMS = 1;
1001 p->h = p->m = 0;
1002 p->s = 0.0;
1003 p->rawS = 0;
1004 p->tz = 0;
1005 p->validJD = 0;
1006 if( sqlite3_stricmp(z,"month")==0 ){
1007 p->D = 1;
1008 p->nFloor = 0;
1009 rc = 0;
1010 }else if( sqlite3_stricmp(z,"year")==0 ){
1011 p->M = 1;
1012 p->D = 1;
1013 p->nFloor = 0;
1014 rc = 0;
1015 }else if( sqlite3_stricmp(z,"day")==0 ){
1016 rc = 0;
1017 }
1018 break;
1019 }
1020 case '+':
1021 case '-':
1022 case '0':
1023 case '1':
1024 case '2':
1025 case '3':
1026 case '4':
1027 case '5':
1028 case '6':
1029 case '7':
1030 case '8':
1031 case '9': {
1032 double rRounder;
1033 int i, rx;
1034 int Y,M,D,h,m,x;
1035 const char *z2 = z;
1036 char *zCopy;
1037 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1038 char z0 = z[0];
1039 for(n=1; z[n]; n++){
1040 if( z[n]==':' ) break;
1041 if( sqlite3Isspace(z[n]) ) break;
1042 if( z[n]=='-' ){
1043 if( n==5 && getDigits(&z[1], "40f", &Y)==1 ) break;
1044 if( n==6 && getDigits(&z[1], "50f", &Y)==1 ) break;
1045 }
1046 }
1047 zCopy = sqlite3DbStrNDup(db, z, n);
1048 if( zCopy==0 ) break;
1049 rx = sqlite3AtoF(zCopy, &r)<=0;
1050 sqlite3DbFree(db, zCopy);
1051 if( rx ){
1052 assert( rc==1 );
1053 break;
1054 }
1055 if( z[n]=='-' ){
1056 /* A modifier of the form (+|-)YYYY-MM-DD adds or subtracts the
1057 ** specified number of years, months, and days. MM is limited to
1058 ** the range 0-11 and DD is limited to 0-30.
1059 */
1060 if( z0!='+' && z0!='-' ) break; /* Must start with +/- */
1061 if( n==5 ){
1062 if( getDigits(&z[1], "40f-20a-20d", &Y, &M, &D)!=3 ) break;
1063 }else{
1064 assert( n==6 );
1065 if( getDigits(&z[1], "50f-20a-20d", &Y, &M, &D)!=3 ) break;
1066 z++;
1067 }
1068 if( M>=12 ) break; /* M range 0..11 */
1069 if( D>=31 ) break; /* D range 0..30 */
1070 computeYMD_HMS(p);
1071 p->validJD = 0;
1072 if( z0=='-' ){
1073 p->Y -= Y;
1074 p->M -= M;
1075 D = -D;
1076 }else{
1077 p->Y += Y;
1078 p->M += M;
1079 }
1080 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
1081 p->Y += x;
1082 p->M -= x*12;
1083 computeFloor(p);
1084 computeJD(p);
1085 p->validHMS = 0;
1086 p->validYMD = 0;
1087 p->iJD += (i64)D*86400000;
1088 if( z[11]==0 ){
1089 rc = 0;
1090 break;
1091 }
1092 if( sqlite3Isspace(z[11])
1093 && getDigits(&z[12], "20c:20e", &h, &m)==2
1094 ){
1095 z2 = &z[12];
1096 n = 2;
1097 }else{
1098 break;
1099 }
1100 }
1101 if( z2[n]==':' ){
1102 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
1103 ** specified number of hours, minutes, seconds, and fractional seconds
1104 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
1105 ** omitted.
1106 */
1107
1108 DateTime tx;
1109 sqlite3_int64 day;
1110 int is24hr; /* 1 for a shift of exactly 24:00 */
1111 int bTimeOnly = z2==z; /* This is not the HH:MM tail of a
1112 ** +/-YYYY-MM-DD HH:MM shift, whose own
1113 ** nFloor must survive (e0fe679e7c) */
1114 if( !sqlite3Isdigit(*z2) ) z2++;
1115 memset(&tx, 0, sizeof(tx));
1116 if( parseHhMmSs(z2, &tx, 0) ){
1117 break; /* HH:MM:SS.FFF failed to parse */
1118 }
1119 is24hr = tx.h==24;
1120 computeJD(&tx);
1121 tx.iJD -= 43200000;
1122 day = tx.iJD/86400000;
1123 tx.iJD -= day*86400000;
1124 if( is24hr ) tx.iJD += (sqlite3_int64)86400000;
1125 if( z0=='-' ) tx.iJD = -tx.iJD;
1126 computeJD(p);
1127 clearYMD_HMS_TZ(p);
1128 p->iJD += tx.iJD;
1129 if( bTimeOnly ) p->nFloor = 0;
1130 rc = 0;
1131 break;
1132 }
1133
1134 /* If control reaches this point, it means the transformation is
1135 ** one of the forms like "+NNN days". */
1136 z += n;
1137 while( sqlite3Isspace(*z) ) z++;
1138 n = sqlite3Strlen30(z);
1139 if( n<3 || n>10 ) break;
1140 if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
1141 computeJD(p);
1142 assert( rc==1 );
1143 rRounder = r<0 ? -0.5 : +0.5;
1144 p->nFloor = 0;
1145 for(i=0; i<ArraySize(aXformType); i++){
1146 if( aXformType[i].nName==n
1147 && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
1148 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
1149 ){
1150 switch( i ){
1151 case 4: { /* Special processing to add months */
1152 assert( strcmp(aXformType[4].zName,"month")==0 );
1153 computeYMD_HMS(p);
1154 p->M += (int)r;
1155 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
1156 p->Y += x;
1157 p->M -= x*12;
1158 computeFloor(p);
1159 p->validJD = 0;
1160 r -= (int)r;
1161 break;
1162 }
1163 case 5: { /* Special processing to add years */
1164 int y = (int)r;
1165 assert( strcmp(aXformType[5].zName,"year")==0 );
1166 computeYMD_HMS(p);
1167 assert( p->M>=0 && p->M<=12 );
1168 p->Y += y;
1169 computeFloor(p);
1170 p->validJD = 0;
1171 r -= (int)r;
1172 break;
1173 }
1174 }
1175 computeJD(p);
1176 p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder);
1177 rc = 0;
1178 break;
1179 }
1180 }
1181 clearYMD_HMS_TZ(p);
1182 break;
1183 }
1184 default: {
1185 break;
1186 }
1187 }
1188 return rc;
1189}
1190
1191/*
1192** Process time function arguments. argv[0] is a date-time stamp.
1193** argv[1] and following are modifiers. Parse them all and write
1194** the resulting time into the DateTime structure p. Return 0
1195** on success and 1 if there are any errors.
1196**
1197** If there are zero parameters (if even argv[0] is undefined)
1198** then assume a default value of "now" for argv[0].
1199*/
1200static int isDate(
1201 sqlite3_context *context,
1202 int argc,
1203 sqlite3_value **argv,
1204 DateTime *p
1205){
1206 int i, n;
1207 const unsigned char *z;
1208 int eType;
1209 memset(p, 0, sizeof(*p));
1210 if( argc==0 ){
1211 if( !sqlite3NotPureFunc(context) ) return 1;
1212 return setDateTimeToCurrent(context, p);
1213 }
1214 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
1215 || eType==SQLITE_INTEGER ){
1216 setRawDateNumber(p, sqlite3_value_double(argv[0]));
1217 }else{
1218 z = sqlite3_value_text(argv[0]);
1219 if( !z || parseDateOrTime(context, (char*)z, p) ){
1220 return 1;
1221 }
1222 }
1223 for(i=1; i<argc; i++){
1224 z = sqlite3_value_text(argv[i]);
1225 n = sqlite3_value_bytes(argv[i]);
1226 if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1;
1227 }
1228 computeJD(p);
1229 if( p->isError || !validJulianDay(p->iJD) ) return 1;
1230 if( p->validYMD && p->D>28 ){
1231 /* Make sure a YYYY-MM-DD is normalized.
1232 ** Example: 2023-02-31 -> 2023-03-03
1233 */
1234 assert( p->validJD );
1235 p->validYMD = 0;
1236 }
1237 return 0;
1238}
1239
1240
1241/*
1242** The following routines implement the various date and time functions
1243** of SQLite.
1244*/
1245
1246/*
1247** julianday( TIMESTRING, MOD, MOD, ...)
1248**
1249** Return the julian day number of the date specified in the arguments
1250*/
1251static void juliandayFunc(
1252 sqlite3_context *context,
1253 int argc,
1254 sqlite3_value **argv
1255){
1256 DateTime x;
1257 if( isDate(context, argc, argv, &x)==0 ){
1258 computeJD(&x);
1259 sqlite3_result_double(context, x.iJD/86400000.0);
1260 }
1261}
1262
1263/*
1264** unixepoch( TIMESTRING, MOD, MOD, ...)
1265**
1266** Return the number of seconds (including fractional seconds) since
1267** the unix epoch of 1970-01-01 00:00:00 GMT.
1268*/
1269static void unixepochFunc(
1270 sqlite3_context *context,
1271 int argc,
1272 sqlite3_value **argv
1273){
1274 DateTime x;
1275 if( isDate(context, argc, argv, &x)==0 ){
1276 computeJD(&x);
1277 if( x.useSubsec ){
1278 sqlite3_result_double(context, (x.iJD - 21086676*(i64)10000000)/1000.0);
1279 }else{
1280 sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);
1281 }
1282 }
1283}
1284
1285/*
1286** datetime( TIMESTRING, MOD, MOD, ...)
1287**
1288** Return YYYY-MM-DD HH:MM:SS
1289*/
1290static void datetimeFunc(
1291 sqlite3_context *context,
1292 int argc,
1293 sqlite3_value **argv
1294){
1295 DateTime x;
1296 if( isDate(context, argc, argv, &x)==0 ){
1297 int Y, s, n;
1298 char zBuf[32];
1299 computeYMD_HMS(&x);
1300 Y = x.Y;
1301 if( Y<0 ) Y = -Y;
1302 zBuf[1] = '0' + (Y/1000)%10;
1303 zBuf[2] = '0' + (Y/100)%10;
1304 zBuf[3] = '0' + (Y/10)%10;
1305 zBuf[4] = '0' + (Y)%10;
1306 zBuf[5] = '-';
1307 zBuf[6] = '0' + (x.M/10)%10;
1308 zBuf[7] = '0' + (x.M)%10;
1309 zBuf[8] = '-';
1310 zBuf[9] = '0' + (x.D/10)%10;
1311 zBuf[10] = '0' + (x.D)%10;
1312 zBuf[11] = ' ';
1313 zBuf[12] = '0' + (x.h/10)%10;
1314 zBuf[13] = '0' + (x.h)%10;
1315 zBuf[14] = ':';
1316 zBuf[15] = '0' + (x.m/10)%10;
1317 zBuf[16] = '0' + (x.m)%10;
1318 zBuf[17] = ':';
1319 if( x.useSubsec ){
1320 s = (int)(1000.0*x.s + 0.5);
1321 zBuf[18] = '0' + (s/10000)%10;
1322 zBuf[19] = '0' + (s/1000)%10;
1323 zBuf[20] = '.';
1324 zBuf[21] = '0' + (s/100)%10;
1325 zBuf[22] = '0' + (s/10)%10;
1326 zBuf[23] = '0' + (s)%10;
1327 zBuf[24] = 0;
1328 n = 24;
1329 }else{
1330 s = (int)x.s;
1331 zBuf[18] = '0' + (s/10)%10;
1332 zBuf[19] = '0' + (s)%10;
1333 zBuf[20] = 0;
1334 n = 20;
1335 }
1336 if( x.Y<0 ){
1337 zBuf[0] = '-';
1338 sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
1339 }else{
1340 sqlite3_result_text(context, &zBuf[1], n-1, SQLITE_TRANSIENT);
1341 }
1342 }
1343}
1344
1345/*
1346** time( TIMESTRING, MOD, MOD, ...)
1347**
1348** Return HH:MM:SS
1349*/
1350static void timeFunc(
1351 sqlite3_context *context,
1352 int argc,
1353 sqlite3_value **argv
1354){
1355 DateTime x;
1356 if( isDate(context, argc, argv, &x)==0 ){
1357 int s, n;
1358 char zBuf[16];
1359 computeHMS(&x);
1360 zBuf[0] = '0' + (x.h/10)%10;
1361 zBuf[1] = '0' + (x.h)%10;
1362 zBuf[2] = ':';
1363 zBuf[3] = '0' + (x.m/10)%10;
1364 zBuf[4] = '0' + (x.m)%10;
1365 zBuf[5] = ':';
1366 if( x.useSubsec ){
1367 s = (int)(1000.0*x.s + 0.5);
1368 zBuf[6] = '0' + (s/10000)%10;
1369 zBuf[7] = '0' + (s/1000)%10;
1370 zBuf[8] = '.';
1371 zBuf[9] = '0' + (s/100)%10;
1372 zBuf[10] = '0' + (s/10)%10;
1373 zBuf[11] = '0' + (s)%10;
1374 zBuf[12] = 0;
1375 n = 12;
1376 }else{
1377 s = (int)x.s;
1378 zBuf[6] = '0' + (s/10)%10;
1379 zBuf[7] = '0' + (s)%10;
1380 zBuf[8] = 0;
1381 n = 8;
1382 }
1383 sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT);
1384 }
1385}
1386
1387/*
1388** date( TIMESTRING, MOD, MOD, ...)
1389**
1390** Return YYYY-MM-DD
1391*/
1392static void dateFunc(
1393 sqlite3_context *context,
1394 int argc,
1395 sqlite3_value **argv
1396){
1397 DateTime x;
1398 if( isDate(context, argc, argv, &x)==0 ){
1399 int Y;
1400 char zBuf[16];
1401 computeYMD(&x);
1402 Y = x.Y;
1403 if( Y<0 ) Y = -Y;
1404 zBuf[1] = '0' + (Y/1000)%10;
1405 zBuf[2] = '0' + (Y/100)%10;
1406 zBuf[3] = '0' + (Y/10)%10;
1407 zBuf[4] = '0' + (Y)%10;
1408 zBuf[5] = '-';
1409 zBuf[6] = '0' + (x.M/10)%10;
1410 zBuf[7] = '0' + (x.M)%10;
1411 zBuf[8] = '-';
1412 zBuf[9] = '0' + (x.D/10)%10;
1413 zBuf[10] = '0' + (x.D)%10;
1414 zBuf[11] = 0;
1415 if( x.Y<0 ){
1416 zBuf[0] = '-';
1417 sqlite3_result_text(context, zBuf, 11, SQLITE_TRANSIENT);
1418 }else{
1419 sqlite3_result_text(context, &zBuf[1], 10, SQLITE_TRANSIENT);
1420 }
1421 }
1422}
1423
1424/*
1425** Compute the number of days after the most recent January 1.
1426**
1427** In other words, compute the zero-based day number for the
1428** current year:
1429**
1430** Jan01 = 0, Jan02 = 1, ..., Jan31 = 30, Feb01 = 31, ...
1431** Dec31 = 364 or 365.
1432*/
1433static int daysAfterJan01(DateTime *pDate){
1434 DateTime jan01 = *pDate;
1435 assert( jan01.validYMD );
1436 assert( jan01.validHMS );
1437 assert( pDate->validJD );
1438 jan01.validJD = 0;
1439 jan01.M = 1;
1440 jan01.D = 1;
1441 computeJD(&jan01);
1442 return (int)((pDate->iJD-jan01.iJD+43200000)/86400000);
1443}
1444
1445/*
1446** Return the number of days after the most recent Monday.
1447**
1448** In other words, return the day of the week according
1449** to this code:
1450**
1451** 0=Monday, 1=Tuesday, 2=Wednesday, ..., 6=Sunday.
1452*/
1453static int daysAfterMonday(DateTime *pDate){
1454 assert( pDate->validJD );
1455 return (int)((pDate->iJD+43200000)/86400000) % 7;
1456}
1457
1458/*
1459** Return the number of days after the most recent Sunday.
1460**
1461** In other words, return the day of the week according
1462** to this code:
1463**
1464** 0=Sunday, 1=Monday, 2=Tuesday, ..., 6=Saturday
1465*/
1466static int daysAfterSunday(DateTime *pDate){
1467 assert( pDate->validJD );
1468 return (int)((pDate->iJD+129600000)/86400000) % 7;
1469}
1470
1471/*
1472** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
1473**
1474** Return a string described by FORMAT. Conversions as follows:
1475**
1476** %d day of month 01-31
1477** %e day of month 1-31
1478** %f ** fractional seconds SS.SSS
1479** %F ISO date. YYYY-MM-DD
1480** %G ISO year corresponding to %V 0000-9999.
1481** %g 2-digit ISO year corresponding to %V 00-99
1482** %H hour 00-24
1483** %k hour 0-24 (leading zero converted to space)
1484** %I hour 01-12
1485** %j day of year 001-366
1486** %J ** julian day number
1487** %l hour 1-12 (leading zero converted to space)
1488** %m month 01-12
1489** %M minute 00-59
1490** %p "AM" or "PM"
1491** %P "am" or "pm"
1492** %R time as HH:MM
1493** %s seconds since 1970-01-01
1494** %S seconds 00-59
1495** %T time as HH:MM:SS
1496** %u day of week 1-7 Monday==1, Sunday==7
1497** %w day of week 0-6 Sunday==0, Monday==1
1498** %U week of year 00-53 (First Sunday is start of week 01)
1499** %V week of year 01-53 (First week containing Thursday is week 01)
1500** %W week of year 00-53 (First Monday is start of week 01)
1501** %Y year 0000-9999
1502** %% %
1503*/
1504static void strftimeFunc(
1505 sqlite3_context *context,
1506 int argc,
1507 sqlite3_value **argv
1508){
1509 DateTime x;
1510 size_t i,j;
1511 sqlite3 *db;
1512 const char *zFmt;
1513 sqlite3_str *pRes;
1514
1515
1516 if( argc==0 ) return;
1517 zFmt = (const char*)sqlite3_value_text(argv[0]);
1518 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
1519 db = sqlite3_context_db_handle(context);
1520 pRes = sqlite3_str_new(db);
1521
1522 computeJD(&x);
1523 computeYMD_HMS(&x);
1524 for(i=j=0; zFmt[i]; i++){
1525 char cf;
1526 if( zFmt[i]!='%' ) continue;
1527 if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j));
1528 i++;
1529 j = i + 1;
1530 cf = zFmt[i];
1531 switch( cf ){
1532 case 'd': /* Fall thru */
1533 case 'e': {
1534 sqlite3_str_appendf(pRes, cf=='d' ? "%02d" : "%2d", x.D);
1535 break;
1536 }
1537 case 'f': { /* Fractional seconds. (Non-standard) */
1538 double s = x.s;
1539 if( NEVER(s>59.999) ) s = 59.999;
1540 sqlite3_str_appendf(pRes, "%06.3f", s);
1541 break;
1542 }
1543 case 'F': {
1544 sqlite3_str_appendf(pRes, "%04d-%02d-%02d", x.Y, x.M, x.D);
1545 break;
1546 }
1547 case 'G': /* Fall thru */
1548 case 'g': {
1549 DateTime y = x;
1550 assert( y.validJD );
1551 /* Move y so that it is the Thursday in the same week as x */
1552 y.iJD += (3 - daysAfterMonday(&x))*86400000;
1553 y.validYMD = 0;
1554 computeYMD(&y);
1555 if( cf=='g' ){
1556 sqlite3_str_appendf(pRes, "%02d", y.Y%100);
1557 }else{
1558 sqlite3_str_appendf(pRes, "%04d", y.Y);
1559 }
1560 break;
1561 }
1562 case 'H':
1563 case 'k': {
1564 sqlite3_str_appendf(pRes, cf=='H' ? "%02d" : "%2d", x.h);
1565 break;
1566 }
1567 case 'I': /* Fall thru */
1568 case 'l': {
1569 int h = x.h;
1570 if( h>12 ) h -= 12;
1571 if( h==0 ) h = 12;
1572 sqlite3_str_appendf(pRes, cf=='I' ? "%02d" : "%2d", h);
1573 break;
1574 }
1575 case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */
1576 sqlite3_str_appendf(pRes,"%03d",daysAfterJan01(&x)+1);
1577 break;
1578 }
1579 case 'J': { /* Julian day number. (Non-standard) */
1580 sqlite3_str_appendf(pRes,"%.16g",x.iJD/86400000.0);
1581 break;
1582 }
1583 case 'm': {
1584 sqlite3_str_appendf(pRes,"%02d",x.M);
1585 break;
1586 }
1587 case 'M': {
1588 sqlite3_str_appendf(pRes,"%02d",x.m);
1589 break;
1590 }
1591 case 'p': /* Fall thru */
1592 case 'P': {
1593 if( x.h>=12 ){
1594 sqlite3_str_append(pRes, cf=='p' ? "PM" : "pm", 2);
1595 }else{
1596 sqlite3_str_append(pRes, cf=='p' ? "AM" : "am", 2);
1597 }
1598 break;
1599 }
1600 case 'R': {
1601 sqlite3_str_appendf(pRes, "%02d:%02d", x.h, x.m);
1602 break;
1603 }
1604 case 's': {
1605 if( x.useSubsec ){
1606 sqlite3_str_appendf(pRes,"%.3f",
1607 (x.iJD - 21086676*(i64)10000000)/1000.0);
1608 }else{
1609 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
1610 sqlite3_str_appendf(pRes,"%lld",iS);
1611 }
1612 break;
1613 }
1614 case 'S': {
1615 sqlite3_str_appendf(pRes,"%02d",(int)x.s);
1616 break;
1617 }
1618 case 'T': {
1619 sqlite3_str_appendf(pRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s);
1620 break;
1621 }
1622 case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */
1623 case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */
1624 char c = (char)daysAfterSunday(&x) + '0';
1625 if( c=='0' && cf=='u' ) c = '7';
1626 sqlite3_str_appendchar(pRes, 1, c);
1627 break;
1628 }
1629 case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */
1630 sqlite3_str_appendf(pRes,"%02d",
1631 (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7);
1632 break;
1633 }
1634 case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */
1635 DateTime y = x;
1636 /* Adjust y so that is the Thursday in the same week as x */
1637 assert( y.validJD );
1638 y.iJD += (3 - daysAfterMonday(&x))*86400000;
1639 y.validYMD = 0;
1640 computeYMD(&y);
1641 sqlite3_str_appendf(pRes,"%02d", daysAfterJan01(&y)/7+1);
1642 break;
1643 }
1644 case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */
1645 sqlite3_str_appendf(pRes,"%02d",
1646 (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7);
1647 break;
1648 }
1649 case 'Y': {
1650 sqlite3_str_appendf(pRes,"%04d",x.Y);
1651 break;
1652 }
1653 case '%': {
1654 sqlite3_str_appendchar(pRes, 1, '%');
1655 break;
1656 }
1657 default: {
1658 sqlite3_str_free(pRes);
1659 return;
1660 }
1661 }
1662 }
1663 if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j));
1664 sqlite3_result_str(context, pRes, SQLITE_FINISH);
1665}
1666
1667/*
1668** current_time()
1669**
1670** This function returns the same value as time('now').
1671*/
1672static void ctimeFunc(
1673 sqlite3_context *context,
1674 int NotUsed,
1675 sqlite3_value **NotUsed2
1676){
1677 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1678 timeFunc(context, 0, 0);
1679}
1680
1681/*
1682** current_date()
1683**
1684** This function returns the same value as date('now').
1685*/
1686static void cdateFunc(
1687 sqlite3_context *context,
1688 int NotUsed,
1689 sqlite3_value **NotUsed2
1690){
1691 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1692 dateFunc(context, 0, 0);
1693}
1694
1695/*
1696** timediff(DATE1, DATE2)
1697**
1698** Return the amount of time that must be added to DATE2 in order to
1699** convert it into DATE2. The time difference format is:
1700**
1701** +YYYY-MM-DD HH:MM:SS.SSS
1702**
1703** The initial "+" becomes "-" if DATE1 occurs before DATE2. For
1704** date/time values A and B, the following invariant should hold:
1705**
1706** datetime(A) == (datetime(B, timediff(A,B))
1707**
1708** Both DATE arguments must be either a julian day number, or an
1709** ISO-8601 string. The unix timestamps are not supported by this
1710** routine.
1711*/
1712static void timediffFunc(
1713 sqlite3_context *context,
1714 int NotUsed1,
1715 sqlite3_value **argv
1716){
1717 char sign;
1718 int Y, M;
1719 DateTime d1, d2;
1720 sqlite3_str sRes;
1721 UNUSED_PARAMETER(NotUsed1);
1722 if( isDate(context, 1, &argv[0], &d1) ) return;
1723 if( isDate(context, 1, &argv[1], &d2) ) return;
1724 computeYMD_HMS(&d1);
1725 computeYMD_HMS(&d2);
1726 if( d1.iJD>=d2.iJD ){
1727 sign = '+';
1728 Y = d1.Y - d2.Y;
1729 if( Y ){
1730 d2.Y = d1.Y;
1731 d2.validJD = 0;
1732 computeJD(&d2);
1733 }
1734 M = d1.M - d2.M;
1735 if( M<0 ){
1736 Y--;
1737 M += 12;
1738 }
1739 if( M!=0 ){
1740 d2.M = d1.M;
1741 d2.validJD = 0;
1742 computeJD(&d2);
1743 }
1744 while( d1.iJD<d2.iJD ){
1745 M--;
1746 if( M<0 ){
1747 M = 11;
1748 Y--;
1749 }
1750 d2.M--;
1751 if( d2.M<1 ){
1752 d2.M = 12;
1753 d2.Y--;
1754 }
1755 d2.validJD = 0;
1756 computeJD(&d2);
1757 }
1758 d1.iJD -= d2.iJD;
1759 d1.iJD += (u64)1486995408 * (u64)100000;
1760 }else /* d1<d2 */{
1761 sign = '-';
1762 Y = d2.Y - d1.Y;
1763 if( Y ){
1764 d2.Y = d1.Y;
1765 d2.validJD = 0;
1766 computeJD(&d2);
1767 }
1768 M = d2.M - d1.M;
1769 if( M<0 ){
1770 Y--;
1771 M += 12;
1772 }
1773 if( M!=0 ){
1774 d2.M = d1.M;
1775 d2.validJD = 0;
1776 computeJD(&d2);
1777 }
1778 while( d1.iJD>d2.iJD ){
1779 M--;
1780 if( M<0 ){
1781 M = 11;
1782 Y--;
1783 }
1784 d2.M++;
1785 if( d2.M>12 ){
1786 d2.M = 1;
1787 d2.Y++;
1788 }
1789 d2.validJD = 0;
1790 computeJD(&d2);
1791 }
1792 d1.iJD = d2.iJD - d1.iJD;
1793 d1.iJD += (u64)1486995408 * (u64)100000;
1794 }
1795 clearYMD_HMS_TZ(&d1);
1796 computeYMD_HMS(&d1);
1797 sqlite3StrAccumInit(&sRes, 0, 0, 0, 100);
1798 sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f",
1799 sign, Y, M, d1.D-1, d1.h, d1.m, d1.s);
1800 sqlite3_result_str(context, &sRes, SQLITE_XFER);
1801}
1802
1803
1804/*
1805** current_timestamp()
1806**
1807** This function returns the same value as datetime('now').
1808*/
1809static void ctimestampFunc(
1810 sqlite3_context *context,
1811 int NotUsed,
1812 sqlite3_value **NotUsed2
1813){
1814 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1815 datetimeFunc(context, 0, 0);
1816}
1817#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
1818
1819#ifdef SQLITE_OMIT_DATETIME_FUNCS
1820/*
1821** If the library is compiled to omit the full-scale date and time
1822** handling (to get a smaller binary), the following minimal version
1823** of the functions current_time(), current_date() and current_timestamp()
1824** are included instead. This is to support column declarations that
1825** include "DEFAULT CURRENT_TIME" etc.
1826**
1827** This function uses the C-library functions time(), gmtime()
1828** and strftime(). The format string to pass to strftime() is supplied
1829** as the user-data for the function.
1830*/
1831static void currentTimeFunc(
1832 sqlite3_context *context,
1833 int argc,
1834 sqlite3_value **argv
1835){
1836 time_t t;
1837 char *zFormat = (char *)sqlite3_user_data(context);
1838 sqlite3_int64 iT;
1839 struct tm *pTm;
1840 struct tm sNow;
1841 char zBuf[20];
1842
1843 UNUSED_PARAMETER(argc);
1844 UNUSED_PARAMETER(argv);
1845
1846 iT = sqlite3StmtCurrentTime(context);
1847 if( iT<=0 ) return;
1848 t = iT/1000 - 10000*(sqlite3_int64)21086676;
1849#if HAVE_GMTIME_R
1850 pTm = gmtime_r(&t, &sNow);
1851#else
1852 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
1853 pTm = gmtime(&t);
1854 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
1855 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
1856#endif
1857 if( pTm ){
1858 strftime(zBuf, 20, zFormat, &sNow);
1859 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
1860 }
1861}
1862#endif
1863
1864#if !defined(SQLITE_OMIT_DATETIME_FUNCS) && defined(SQLITE_DEBUG)
1865/*
1866** datedebug(...)
1867**
1868** This routine returns JSON that describes the internal DateTime object.
1869** Used for debugging and testing only. Subject to change.
1870*/
1871static void datedebugFunc(
1872 sqlite3_context *context,
1873 int argc,
1874 sqlite3_value **argv
1875){
1876 DateTime x;
1877 if( isDate(context, argc, argv, &x)==0 ){
1878 char *zJson;
1879 zJson = sqlite3_mprintf(
1880 "{iJD:%lld,Y:%d,M:%d,D:%d,h:%d,m:%d,tz:%d,"
1881 "s:%.3f,validJD:%d,validYMD:%d,validHMS:%d,"
1882 "nFloor:%d,rawS:%d,isError:%d,useSubsec:%d,"
1883 "isUtc:%d,isLocal:%d}",
1884 x.iJD, x.Y, x.M, x.D, x.h, x.m, x.tz,
1885 x.s, x.validJD, x.validYMD, x.validHMS,
1886 x.nFloor, x.rawS, x.isError, x.useSubsec,
1887 x.isUtc, x.isLocal);
1888 sqlite3_result_text(context, zJson, -1, sqlite3_free);
1889 }
1890}
1891#endif /* !SQLITE_OMIT_DATETIME_FUNCS && SQLITE_DEBUG */
1892
1893
1894/*
1895** This function registered all of the above C functions as SQL
1896** functions. This should be the only routine in this file with
1897** external linkage.
1898*/
1899void sqlite3RegisterDateTimeFunctions(void){
1900 static FuncDef aDateTimeFuncs[] = {
1901#ifndef SQLITE_OMIT_DATETIME_FUNCS
1902 PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
1903 PURE_DATE(unixepoch, -1, 0, 0, unixepochFunc ),
1904 PURE_DATE(date, -1, 0, 0, dateFunc ),
1905 PURE_DATE(time, -1, 0, 0, timeFunc ),
1906 PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
1907 PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
1908 PURE_DATE(timediff, 2, 0, 0, timediffFunc ),
1909#ifdef SQLITE_DEBUG
1910 PURE_DATE(datedebug, -1, 0, 0, datedebugFunc ),
1911#endif
1912 DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
1913 DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
1914 DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
1915#else
1916 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
1917 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
1918 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
1919#endif
1920 };
1921 sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
1922}