date.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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 implemention 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. ** ISBM 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. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  51. /*
  52. ** A structure for holding a single date and time.
  53. */
  54. typedef struct DateTime DateTime;
  55. struct DateTime {
  56. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  57. int Y, M, D; /* Year, month, and day */
  58. int h, m; /* Hour and minutes */
  59. int tz; /* Timezone offset in minutes */
  60. double s; /* Seconds */
  61. char validYMD; /* True (1) if Y,M,D are valid */
  62. char validHMS; /* True (1) if h,m,s are valid */
  63. char validJD; /* True (1) if iJD is valid */
  64. char validTZ; /* True (1) if tz is valid */
  65. };
  66. /*
  67. ** Convert zDate into one or more integers. Additional arguments
  68. ** come in groups of 5 as follows:
  69. **
  70. ** N number of digits in the integer
  71. ** min minimum allowed value of the integer
  72. ** max maximum allowed value of the integer
  73. ** nextC first character after the integer
  74. ** pVal where to write the integers value.
  75. **
  76. ** Conversions continue until one with nextC==0 is encountered.
  77. ** The function returns the number of successful conversions.
  78. */
  79. static int getDigits(const char *zDate, ...){
  80. va_list ap;
  81. int val;
  82. int N;
  83. int min;
  84. int max;
  85. int nextC;
  86. int *pVal;
  87. int cnt = 0;
  88. va_start(ap, zDate);
  89. do{
  90. N = va_arg(ap, int);
  91. min = va_arg(ap, int);
  92. max = va_arg(ap, int);
  93. nextC = va_arg(ap, int);
  94. pVal = va_arg(ap, int*);
  95. val = 0;
  96. while( N-- ){
  97. if( !sqlite3Isdigit(*zDate) ){
  98. goto end_getDigits;
  99. }
  100. val = val*10 + *zDate - '0';
  101. zDate++;
  102. }
  103. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  104. goto end_getDigits;
  105. }
  106. *pVal = val;
  107. zDate++;
  108. cnt++;
  109. }while( nextC );
  110. end_getDigits:
  111. va_end(ap);
  112. return cnt;
  113. }
  114. /*
  115. ** Parse a timezone extension on the end of a date-time.
  116. ** The extension is of the form:
  117. **
  118. ** (+/-)HH:MM
  119. **
  120. ** Or the "zulu" notation:
  121. **
  122. ** Z
  123. **
  124. ** If the parse is successful, write the number of minutes
  125. ** of change in p->tz and return 0. If a parser error occurs,
  126. ** return non-zero.
  127. **
  128. ** A missing specifier is not considered an error.
  129. */
  130. static int parseTimezone(const char *zDate, DateTime *p){
  131. int sgn = 0;
  132. int nHr, nMn;
  133. int c;
  134. while( sqlite3Isspace(*zDate) ){ zDate++; }
  135. p->tz = 0;
  136. c = *zDate;
  137. if( c=='-' ){
  138. sgn = -1;
  139. }else if( c=='+' ){
  140. sgn = +1;
  141. }else if( c=='Z' || c=='z' ){
  142. zDate++;
  143. goto zulu_time;
  144. }else{
  145. return c!=0;
  146. }
  147. zDate++;
  148. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  149. return 1;
  150. }
  151. zDate += 5;
  152. p->tz = sgn*(nMn + nHr*60);
  153. zulu_time:
  154. while( sqlite3Isspace(*zDate) ){ zDate++; }
  155. return *zDate!=0;
  156. }
  157. /*
  158. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  159. ** The HH, MM, and SS must each be exactly 2 digits. The
  160. ** fractional seconds FFFF can be one or more digits.
  161. **
  162. ** Return 1 if there is a parsing error and 0 on success.
  163. */
  164. static int parseHhMmSs(const char *zDate, DateTime *p){
  165. int h, m, s;
  166. double ms = 0.0;
  167. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  168. return 1;
  169. }
  170. zDate += 5;
  171. if( *zDate==':' ){
  172. zDate++;
  173. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  174. return 1;
  175. }
  176. zDate += 2;
  177. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  178. double rScale = 1.0;
  179. zDate++;
  180. while( sqlite3Isdigit(*zDate) ){
  181. ms = ms*10.0 + *zDate - '0';
  182. rScale *= 10.0;
  183. zDate++;
  184. }
  185. ms /= rScale;
  186. }
  187. }else{
  188. s = 0;
  189. }
  190. p->validJD = 0;
  191. p->validHMS = 1;
  192. p->h = h;
  193. p->m = m;
  194. p->s = s + ms;
  195. if( parseTimezone(zDate, p) ) return 1;
  196. p->validTZ = (p->tz!=0)?1:0;
  197. return 0;
  198. }
  199. /*
  200. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  201. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  202. **
  203. ** Reference: Meeus page 61
  204. */
  205. static void computeJD(DateTime *p){
  206. int Y, M, D, A, B, X1, X2;
  207. if( p->validJD ) return;
  208. if( p->validYMD ){
  209. Y = p->Y;
  210. M = p->M;
  211. D = p->D;
  212. }else{
  213. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  214. M = 1;
  215. D = 1;
  216. }
  217. if( M<=2 ){
  218. Y--;
  219. M += 12;
  220. }
  221. A = Y/100;
  222. B = 2 - A + (A/4);
  223. X1 = 36525*(Y+4716)/100;
  224. X2 = 306001*(M+1)/10000;
  225. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  226. p->validJD = 1;
  227. if( p->validHMS ){
  228. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  229. if( p->validTZ ){
  230. p->iJD -= p->tz*60000;
  231. p->validYMD = 0;
  232. p->validHMS = 0;
  233. p->validTZ = 0;
  234. }
  235. }
  236. }
  237. /*
  238. ** Parse dates of the form
  239. **
  240. ** YYYY-MM-DD HH:MM:SS.FFF
  241. ** YYYY-MM-DD HH:MM:SS
  242. ** YYYY-MM-DD HH:MM
  243. ** YYYY-MM-DD
  244. **
  245. ** Write the result into the DateTime structure and return 0
  246. ** on success and 1 if the input string is not a well-formed
  247. ** date.
  248. */
  249. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  250. int Y, M, D, neg;
  251. if( zDate[0]=='-' ){
  252. zDate++;
  253. neg = 1;
  254. }else{
  255. neg = 0;
  256. }
  257. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  258. return 1;
  259. }
  260. zDate += 10;
  261. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  262. if( parseHhMmSs(zDate, p)==0 ){
  263. /* We got the time */
  264. }else if( *zDate==0 ){
  265. p->validHMS = 0;
  266. }else{
  267. return 1;
  268. }
  269. p->validJD = 0;
  270. p->validYMD = 1;
  271. p->Y = neg ? -Y : Y;
  272. p->M = M;
  273. p->D = D;
  274. if( p->validTZ ){
  275. computeJD(p);
  276. }
  277. return 0;
  278. }
  279. /*
  280. ** Set the time to the current time reported by the VFS.
  281. **
  282. ** Return the number of errors.
  283. */
  284. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  285. p->iJD = sqlite3StmtCurrentTime(context);
  286. if( p->iJD>0 ){
  287. p->validJD = 1;
  288. return 0;
  289. }else{
  290. return 1;
  291. }
  292. }
  293. /*
  294. ** Attempt to parse the given string into a Julian Day Number. Return
  295. ** the number of errors.
  296. **
  297. ** The following are acceptable forms for the input string:
  298. **
  299. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  300. ** DDDD.DD
  301. ** now
  302. **
  303. ** In the first form, the +/-HH:MM is always optional. The fractional
  304. ** seconds extension (the ".FFF") is optional. The seconds portion
  305. ** (":SS.FFF") is option. The year and date can be omitted as long
  306. ** as there is a time string. The time string can be omitted as long
  307. ** as there is a year and date.
  308. */
  309. static int parseDateOrTime(
  310. sqlite3_context *context,
  311. const char *zDate,
  312. DateTime *p
  313. ){
  314. double r;
  315. if( parseYyyyMmDd(zDate,p)==0 ){
  316. return 0;
  317. }else if( parseHhMmSs(zDate, p)==0 ){
  318. return 0;
  319. }else if( sqlite3StrICmp(zDate,"now")==0){
  320. return setDateTimeToCurrent(context, p);
  321. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  322. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  323. p->validJD = 1;
  324. return 0;
  325. }
  326. return 1;
  327. }
  328. /*
  329. ** Compute the Year, Month, and Day from the julian day number.
  330. */
  331. static void computeYMD(DateTime *p){
  332. int Z, A, B, C, D, E, X1;
  333. if( p->validYMD ) return;
  334. if( !p->validJD ){
  335. p->Y = 2000;
  336. p->M = 1;
  337. p->D = 1;
  338. }else{
  339. Z = (int)((p->iJD + 43200000)/86400000);
  340. A = (int)((Z - 1867216.25)/36524.25);
  341. A = Z + 1 + A - (A/4);
  342. B = A + 1524;
  343. C = (int)((B - 122.1)/365.25);
  344. D = (36525*C)/100;
  345. E = (int)((B-D)/30.6001);
  346. X1 = (int)(30.6001*E);
  347. p->D = B - D - X1;
  348. p->M = E<14 ? E-1 : E-13;
  349. p->Y = p->M>2 ? C - 4716 : C - 4715;
  350. }
  351. p->validYMD = 1;
  352. }
  353. /*
  354. ** Compute the Hour, Minute, and Seconds from the julian day number.
  355. */
  356. static void computeHMS(DateTime *p){
  357. int s;
  358. if( p->validHMS ) return;
  359. computeJD(p);
  360. s = (int)((p->iJD + 43200000) % 86400000);
  361. p->s = s/1000.0;
  362. s = (int)p->s;
  363. p->s -= s;
  364. p->h = s/3600;
  365. s -= p->h*3600;
  366. p->m = s/60;
  367. p->s += s - p->m*60;
  368. p->validHMS = 1;
  369. }
  370. /*
  371. ** Compute both YMD and HMS
  372. */
  373. static void computeYMD_HMS(DateTime *p){
  374. computeYMD(p);
  375. computeHMS(p);
  376. }
  377. /*
  378. ** Clear the YMD and HMS and the TZ
  379. */
  380. static void clearYMD_HMS_TZ(DateTime *p){
  381. p->validYMD = 0;
  382. p->validHMS = 0;
  383. p->validTZ = 0;
  384. }
  385. /*
  386. ** On recent Windows platforms, the localtime_s() function is available
  387. ** as part of the "Secure CRT". It is essentially equivalent to
  388. ** localtime_r() available under most POSIX platforms, except that the
  389. ** order of the parameters is reversed.
  390. **
  391. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  392. **
  393. ** If the user has not indicated to use localtime_r() or localtime_s()
  394. ** already, check for an MSVC build environment that provides
  395. ** localtime_s().
  396. */
  397. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  398. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  399. #define HAVE_LOCALTIME_S 1
  400. #endif
  401. #ifndef SQLITE_OMIT_LOCALTIME
  402. /*
  403. ** The following routine implements the rough equivalent of localtime_r()
  404. ** using whatever operating-system specific localtime facility that
  405. ** is available. This routine returns 0 on success and
  406. ** non-zero on any kind of error.
  407. **
  408. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  409. ** routine will always fail.
  410. **
  411. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  412. ** library function localtime_r() is used to assist in the calculation of
  413. ** local time.
  414. */
  415. static int osLocaltime(time_t *t, struct tm *pTm){
  416. int rc;
  417. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  418. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  419. struct tm *pX;
  420. #if SQLITE_THREADSAFE>0
  421. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  422. #endif
  423. sqlite3_mutex_enter(mutex);
  424. pX = localtime(t);
  425. #ifndef SQLITE_OMIT_BUILTIN_TEST
  426. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  427. #endif
  428. if( pX ) *pTm = *pX;
  429. sqlite3_mutex_leave(mutex);
  430. rc = pX==0;
  431. #else
  432. #ifndef SQLITE_OMIT_BUILTIN_TEST
  433. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  434. #endif
  435. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  436. rc = localtime_r(t, pTm)==0;
  437. #else
  438. rc = localtime_s(pTm, t);
  439. #endif /* HAVE_LOCALTIME_R */
  440. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  441. return rc;
  442. }
  443. #endif /* SQLITE_OMIT_LOCALTIME */
  444. #ifndef SQLITE_OMIT_LOCALTIME
  445. /*
  446. ** Compute the difference (in milliseconds) between localtime and UTC
  447. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  448. ** return this value and set *pRc to SQLITE_OK.
  449. **
  450. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  451. ** is undefined in this case.
  452. */
  453. static sqlite3_int64 localtimeOffset(
  454. DateTime *p, /* Date at which to calculate offset */
  455. sqlite3_context *pCtx, /* Write error here if one occurs */
  456. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  457. ){
  458. DateTime x, y;
  459. time_t t;
  460. struct tm sLocal;
  461. /* Initialize the contents of sLocal to avoid a compiler warning. */
  462. memset(&sLocal, 0, sizeof(sLocal));
  463. x = *p;
  464. computeYMD_HMS(&x);
  465. if( x.Y<1971 || x.Y>=2038 ){
  466. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  467. ** works for years between 1970 and 2037. For dates outside this range,
  468. ** SQLite attempts to map the year into an equivalent year within this
  469. ** range, do the calculation, then map the year back.
  470. */
  471. x.Y = 2000;
  472. x.M = 1;
  473. x.D = 1;
  474. x.h = 0;
  475. x.m = 0;
  476. x.s = 0.0;
  477. } else {
  478. int s = (int)(x.s + 0.5);
  479. x.s = s;
  480. }
  481. x.tz = 0;
  482. x.validJD = 0;
  483. computeJD(&x);
  484. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  485. if( osLocaltime(&t, &sLocal) ){
  486. sqlite3_result_error(pCtx, "local time unavailable", -1);
  487. *pRc = SQLITE_ERROR;
  488. return 0;
  489. }
  490. y.Y = sLocal.tm_year + 1900;
  491. y.M = sLocal.tm_mon + 1;
  492. y.D = sLocal.tm_mday;
  493. y.h = sLocal.tm_hour;
  494. y.m = sLocal.tm_min;
  495. y.s = sLocal.tm_sec;
  496. y.validYMD = 1;
  497. y.validHMS = 1;
  498. y.validJD = 0;
  499. y.validTZ = 0;
  500. computeJD(&y);
  501. *pRc = SQLITE_OK;
  502. return y.iJD - x.iJD;
  503. }
  504. #endif /* SQLITE_OMIT_LOCALTIME */
  505. /*
  506. ** Process a modifier to a date-time stamp. The modifiers are
  507. ** as follows:
  508. **
  509. ** NNN days
  510. ** NNN hours
  511. ** NNN minutes
  512. ** NNN.NNNN seconds
  513. ** NNN months
  514. ** NNN years
  515. ** start of month
  516. ** start of year
  517. ** start of week
  518. ** start of day
  519. ** weekday N
  520. ** unixepoch
  521. ** localtime
  522. ** utc
  523. **
  524. ** Return 0 on success and 1 if there is any kind of error. If the error
  525. ** is in a system call (i.e. localtime()), then an error message is written
  526. ** to context pCtx. If the error is an unrecognized modifier, no error is
  527. ** written to pCtx.
  528. */
  529. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  530. int rc = 1;
  531. int n;
  532. double r;
  533. char *z, zBuf[30];
  534. z = zBuf;
  535. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  536. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  537. }
  538. z[n] = 0;
  539. switch( z[0] ){
  540. #ifndef SQLITE_OMIT_LOCALTIME
  541. case 'l': {
  542. /* localtime
  543. **
  544. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  545. ** show local time.
  546. */
  547. if( strcmp(z, "localtime")==0 ){
  548. computeJD(p);
  549. p->iJD += localtimeOffset(p, pCtx, &rc);
  550. clearYMD_HMS_TZ(p);
  551. }
  552. break;
  553. }
  554. #endif
  555. case 'u': {
  556. /*
  557. ** unixepoch
  558. **
  559. ** Treat the current value of p->iJD as the number of
  560. ** seconds since 1970. Convert to a real julian day number.
  561. */
  562. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  563. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  564. clearYMD_HMS_TZ(p);
  565. rc = 0;
  566. }
  567. #ifndef SQLITE_OMIT_LOCALTIME
  568. else if( strcmp(z, "utc")==0 ){
  569. sqlite3_int64 c1;
  570. computeJD(p);
  571. c1 = localtimeOffset(p, pCtx, &rc);
  572. if( rc==SQLITE_OK ){
  573. p->iJD -= c1;
  574. clearYMD_HMS_TZ(p);
  575. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  576. }
  577. }
  578. #endif
  579. break;
  580. }
  581. case 'w': {
  582. /*
  583. ** weekday N
  584. **
  585. ** Move the date to the same time on the next occurrence of
  586. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  587. ** date is already on the appropriate weekday, this is a no-op.
  588. */
  589. if( strncmp(z, "weekday ", 8)==0
  590. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  591. && (n=(int)r)==r && n>=0 && r<7 ){
  592. sqlite3_int64 Z;
  593. computeYMD_HMS(p);
  594. p->validTZ = 0;
  595. p->validJD = 0;
  596. computeJD(p);
  597. Z = ((p->iJD + 129600000)/86400000) % 7;
  598. if( Z>n ) Z -= 7;
  599. p->iJD += (n - Z)*86400000;
  600. clearYMD_HMS_TZ(p);
  601. rc = 0;
  602. }
  603. break;
  604. }
  605. case 's': {
  606. /*
  607. ** start of TTTTT
  608. **
  609. ** Move the date backwards to the beginning of the current day,
  610. ** or month or year.
  611. */
  612. if( strncmp(z, "start of ", 9)!=0 ) break;
  613. z += 9;
  614. computeYMD(p);
  615. p->validHMS = 1;
  616. p->h = p->m = 0;
  617. p->s = 0.0;
  618. p->validTZ = 0;
  619. p->validJD = 0;
  620. if( strcmp(z,"month")==0 ){
  621. p->D = 1;
  622. rc = 0;
  623. }else if( strcmp(z,"year")==0 ){
  624. computeYMD(p);
  625. p->M = 1;
  626. p->D = 1;
  627. rc = 0;
  628. }else if( strcmp(z,"day")==0 ){
  629. rc = 0;
  630. }
  631. break;
  632. }
  633. case '+':
  634. case '-':
  635. case '0':
  636. case '1':
  637. case '2':
  638. case '3':
  639. case '4':
  640. case '5':
  641. case '6':
  642. case '7':
  643. case '8':
  644. case '9': {
  645. double rRounder;
  646. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  647. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  648. rc = 1;
  649. break;
  650. }
  651. if( z[n]==':' ){
  652. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  653. ** specified number of hours, minutes, seconds, and fractional seconds
  654. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  655. ** omitted.
  656. */
  657. const char *z2 = z;
  658. DateTime tx;
  659. sqlite3_int64 day;
  660. if( !sqlite3Isdigit(*z2) ) z2++;
  661. memset(&tx, 0, sizeof(tx));
  662. if( parseHhMmSs(z2, &tx) ) break;
  663. computeJD(&tx);
  664. tx.iJD -= 43200000;
  665. day = tx.iJD/86400000;
  666. tx.iJD -= day*86400000;
  667. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  668. computeJD(p);
  669. clearYMD_HMS_TZ(p);
  670. p->iJD += tx.iJD;
  671. rc = 0;
  672. break;
  673. }
  674. z += n;
  675. while( sqlite3Isspace(*z) ) z++;
  676. n = sqlite3Strlen30(z);
  677. if( n>10 || n<3 ) break;
  678. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  679. computeJD(p);
  680. rc = 0;
  681. rRounder = r<0 ? -0.5 : +0.5;
  682. if( n==3 && strcmp(z,"day")==0 ){
  683. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  684. }else if( n==4 && strcmp(z,"hour")==0 ){
  685. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  686. }else if( n==6 && strcmp(z,"minute")==0 ){
  687. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  688. }else if( n==6 && strcmp(z,"second")==0 ){
  689. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  690. }else if( n==5 && strcmp(z,"month")==0 ){
  691. int x, y;
  692. computeYMD_HMS(p);
  693. p->M += (int)r;
  694. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  695. p->Y += x;
  696. p->M -= x*12;
  697. p->validJD = 0;
  698. computeJD(p);
  699. y = (int)r;
  700. if( y!=r ){
  701. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  702. }
  703. }else if( n==4 && strcmp(z,"year")==0 ){
  704. int y = (int)r;
  705. computeYMD_HMS(p);
  706. p->Y += y;
  707. p->validJD = 0;
  708. computeJD(p);
  709. if( y!=r ){
  710. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  711. }
  712. }else{
  713. rc = 1;
  714. }
  715. clearYMD_HMS_TZ(p);
  716. break;
  717. }
  718. default: {
  719. break;
  720. }
  721. }
  722. return rc;
  723. }
  724. /*
  725. ** Process time function arguments. argv[0] is a date-time stamp.
  726. ** argv[1] and following are modifiers. Parse them all and write
  727. ** the resulting time into the DateTime structure p. Return 0
  728. ** on success and 1 if there are any errors.
  729. **
  730. ** If there are zero parameters (if even argv[0] is undefined)
  731. ** then assume a default value of "now" for argv[0].
  732. */
  733. static int isDate(
  734. sqlite3_context *context,
  735. int argc,
  736. sqlite3_value **argv,
  737. DateTime *p
  738. ){
  739. int i;
  740. const unsigned char *z;
  741. int eType;
  742. memset(p, 0, sizeof(*p));
  743. if( argc==0 ){
  744. return setDateTimeToCurrent(context, p);
  745. }
  746. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  747. || eType==SQLITE_INTEGER ){
  748. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  749. p->validJD = 1;
  750. }else{
  751. z = sqlite3_value_text(argv[0]);
  752. if( !z || parseDateOrTime(context, (char*)z, p) ){
  753. return 1;
  754. }
  755. }
  756. for(i=1; i<argc; i++){
  757. z = sqlite3_value_text(argv[i]);
  758. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  759. }
  760. return 0;
  761. }
  762. /*
  763. ** The following routines implement the various date and time functions
  764. ** of SQLite.
  765. */
  766. /*
  767. ** julianday( TIMESTRING, MOD, MOD, ...)
  768. **
  769. ** Return the julian day number of the date specified in the arguments
  770. */
  771. static void juliandayFunc(
  772. sqlite3_context *context,
  773. int argc,
  774. sqlite3_value **argv
  775. ){
  776. DateTime x;
  777. if( isDate(context, argc, argv, &x)==0 ){
  778. computeJD(&x);
  779. sqlite3_result_double(context, x.iJD/86400000.0);
  780. }
  781. }
  782. /*
  783. ** datetime( TIMESTRING, MOD, MOD, ...)
  784. **
  785. ** Return YYYY-MM-DD HH:MM:SS
  786. */
  787. static void datetimeFunc(
  788. sqlite3_context *context,
  789. int argc,
  790. sqlite3_value **argv
  791. ){
  792. DateTime x;
  793. if( isDate(context, argc, argv, &x)==0 ){
  794. char zBuf[100];
  795. computeYMD_HMS(&x);
  796. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  797. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  798. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  799. }
  800. }
  801. /*
  802. ** time( TIMESTRING, MOD, MOD, ...)
  803. **
  804. ** Return HH:MM:SS
  805. */
  806. static void timeFunc(
  807. sqlite3_context *context,
  808. int argc,
  809. sqlite3_value **argv
  810. ){
  811. DateTime x;
  812. if( isDate(context, argc, argv, &x)==0 ){
  813. char zBuf[100];
  814. computeHMS(&x);
  815. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  816. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  817. }
  818. }
  819. /*
  820. ** date( TIMESTRING, MOD, MOD, ...)
  821. **
  822. ** Return YYYY-MM-DD
  823. */
  824. static void dateFunc(
  825. sqlite3_context *context,
  826. int argc,
  827. sqlite3_value **argv
  828. ){
  829. DateTime x;
  830. if( isDate(context, argc, argv, &x)==0 ){
  831. char zBuf[100];
  832. computeYMD(&x);
  833. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  834. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  835. }
  836. }
  837. /*
  838. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  839. **
  840. ** Return a string described by FORMAT. Conversions as follows:
  841. **
  842. ** %d day of month
  843. ** %f ** fractional seconds SS.SSS
  844. ** %H hour 00-24
  845. ** %j day of year 000-366
  846. ** %J ** Julian day number
  847. ** %m month 01-12
  848. ** %M minute 00-59
  849. ** %s seconds since 1970-01-01
  850. ** %S seconds 00-59
  851. ** %w day of week 0-6 sunday==0
  852. ** %W week of year 00-53
  853. ** %Y year 0000-9999
  854. ** %% %
  855. */
  856. static void strftimeFunc(
  857. sqlite3_context *context,
  858. int argc,
  859. sqlite3_value **argv
  860. ){
  861. DateTime x;
  862. u64 n;
  863. size_t i,j;
  864. char *z;
  865. sqlite3 *db;
  866. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  867. char zBuf[100];
  868. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  869. db = sqlite3_context_db_handle(context);
  870. for(i=0, n=1; zFmt[i]; i++, n++){
  871. if( zFmt[i]=='%' ){
  872. switch( zFmt[i+1] ){
  873. case 'd':
  874. case 'H':
  875. case 'm':
  876. case 'M':
  877. case 'S':
  878. case 'W':
  879. n++;
  880. /* fall thru */
  881. case 'w':
  882. case '%':
  883. break;
  884. case 'f':
  885. n += 8;
  886. break;
  887. case 'j':
  888. n += 3;
  889. break;
  890. case 'Y':
  891. n += 8;
  892. break;
  893. case 's':
  894. case 'J':
  895. n += 50;
  896. break;
  897. default:
  898. return; /* ERROR. return a NULL */
  899. }
  900. i++;
  901. }
  902. }
  903. testcase( n==sizeof(zBuf)-1 );
  904. testcase( n==sizeof(zBuf) );
  905. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  906. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  907. if( n<sizeof(zBuf) ){
  908. z = zBuf;
  909. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  910. sqlite3_result_error_toobig(context);
  911. return;
  912. }else{
  913. z = sqlite3DbMallocRaw(db, (int)n);
  914. if( z==0 ){
  915. sqlite3_result_error_nomem(context);
  916. return;
  917. }
  918. }
  919. computeJD(&x);
  920. computeYMD_HMS(&x);
  921. for(i=j=0; zFmt[i]; i++){
  922. if( zFmt[i]!='%' ){
  923. z[j++] = zFmt[i];
  924. }else{
  925. i++;
  926. switch( zFmt[i] ){
  927. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  928. case 'f': {
  929. double s = x.s;
  930. if( s>59.999 ) s = 59.999;
  931. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  932. j += sqlite3Strlen30(&z[j]);
  933. break;
  934. }
  935. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  936. case 'W': /* Fall thru */
  937. case 'j': {
  938. int nDay; /* Number of days since 1st day of year */
  939. DateTime y = x;
  940. y.validJD = 0;
  941. y.M = 1;
  942. y.D = 1;
  943. computeJD(&y);
  944. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  945. if( zFmt[i]=='W' ){
  946. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  947. wd = (int)(((x.iJD+43200000)/86400000)%7);
  948. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  949. j += 2;
  950. }else{
  951. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  952. j += 3;
  953. }
  954. break;
  955. }
  956. case 'J': {
  957. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  958. j+=sqlite3Strlen30(&z[j]);
  959. break;
  960. }
  961. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  962. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  963. case 's': {
  964. sqlite3_snprintf(30,&z[j],"%lld",
  965. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  966. j += sqlite3Strlen30(&z[j]);
  967. break;
  968. }
  969. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  970. case 'w': {
  971. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  972. break;
  973. }
  974. case 'Y': {
  975. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  976. break;
  977. }
  978. default: z[j++] = '%'; break;
  979. }
  980. }
  981. }
  982. z[j] = 0;
  983. sqlite3_result_text(context, z, -1,
  984. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  985. }
  986. /*
  987. ** current_time()
  988. **
  989. ** This function returns the same value as time('now').
  990. */
  991. static void ctimeFunc(
  992. sqlite3_context *context,
  993. int NotUsed,
  994. sqlite3_value **NotUsed2
  995. ){
  996. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  997. timeFunc(context, 0, 0);
  998. }
  999. /*
  1000. ** current_date()
  1001. **
  1002. ** This function returns the same value as date('now').
  1003. */
  1004. static void cdateFunc(
  1005. sqlite3_context *context,
  1006. int NotUsed,
  1007. sqlite3_value **NotUsed2
  1008. ){
  1009. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  1010. dateFunc(context, 0, 0);
  1011. }
  1012. /*
  1013. ** current_timestamp()
  1014. **
  1015. ** This function returns the same value as datetime('now').
  1016. */
  1017. static void ctimestampFunc(
  1018. sqlite3_context *context,
  1019. int NotUsed,
  1020. sqlite3_value **NotUsed2
  1021. ){
  1022. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  1023. datetimeFunc(context, 0, 0);
  1024. }
  1025. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  1026. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  1027. /*
  1028. ** If the library is compiled to omit the full-scale date and time
  1029. ** handling (to get a smaller binary), the following minimal version
  1030. ** of the functions current_time(), current_date() and current_timestamp()
  1031. ** are included instead. This is to support column declarations that
  1032. ** include "DEFAULT CURRENT_TIME" etc.
  1033. **
  1034. ** This function uses the C-library functions time(), gmtime()
  1035. ** and strftime(). The format string to pass to strftime() is supplied
  1036. ** as the user-data for the function.
  1037. */
  1038. static void currentTimeFunc(
  1039. sqlite3_context *context,
  1040. int argc,
  1041. sqlite3_value **argv
  1042. ){
  1043. time_t t;
  1044. char *zFormat = (char *)sqlite3_user_data(context);
  1045. sqlite3 *db;
  1046. sqlite3_int64 iT;
  1047. struct tm *pTm;
  1048. struct tm sNow;
  1049. char zBuf[20];
  1050. UNUSED_PARAMETER(argc);
  1051. UNUSED_PARAMETER(argv);
  1052. iT = sqlite3StmtCurrentTime(context);
  1053. if( iT<=0 ) return;
  1054. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  1055. #ifdef HAVE_GMTIME_R
  1056. pTm = gmtime_r(&t, &sNow);
  1057. #else
  1058. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  1059. pTm = gmtime(&t);
  1060. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  1061. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  1062. #endif
  1063. if( pTm ){
  1064. strftime(zBuf, 20, zFormat, &sNow);
  1065. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  1066. }
  1067. }
  1068. #endif
  1069. /*
  1070. ** This function registered all of the above C functions as SQL
  1071. ** functions. This should be the only routine in this file with
  1072. ** external linkage.
  1073. */
  1074. void sqlite3RegisterDateTimeFunctions(void){
  1075. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  1076. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  1077. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  1078. FUNCTION(date, -1, 0, 0, dateFunc ),
  1079. FUNCTION(time, -1, 0, 0, timeFunc ),
  1080. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  1081. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  1082. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  1083. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  1084. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  1085. #else
  1086. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  1087. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  1088. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  1089. #endif
  1090. };
  1091. int i;
  1092. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  1093. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  1094. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  1095. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  1096. }
  1097. }