date.c 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. ** $Id: date.c,v 1.73 2007/09/12 17:01:45 danielk1977 Exp $
  20. **
  21. ** SQLite processes all times and dates as Julian Day numbers. The
  22. ** dates and times are stored as the number of days since noon
  23. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  24. ** calendar system.
  25. **
  26. ** 1970-01-01 00:00:00 is JD 2440587.5
  27. ** 2000-01-01 00:00:00 is JD 2451544.5
  28. **
  29. ** This implemention requires years to be expressed as a 4-digit number
  30. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  31. ** be represented, even though julian day numbers allow a much wider
  32. ** range of dates.
  33. **
  34. ** The Gregorian calendar system is used for all dates and times,
  35. ** even those that predate the Gregorian calendar. Historians usually
  36. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  37. ** dates afterwards, depending on locale. Beware of this difference.
  38. **
  39. ** The conversion algorithms are implemented based on descriptions
  40. ** in the following text:
  41. **
  42. ** Jean Meeus
  43. ** Astronomical Algorithms, 2nd Edition, 1998
  44. ** ISBM 0-943396-61-1
  45. ** Willmann-Bell, Inc
  46. ** Richmond, Virginia (USA)
  47. */
  48. #include "sqliteInt.h"
  49. #include <ctype.h>
  50. #include <stdlib.h>
  51. #include <assert.h>
  52. #include <time.h>
  53. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  54. /*
  55. ** A structure for holding a single date and time.
  56. */
  57. typedef struct DateTime DateTime;
  58. struct DateTime {
  59. double rJD; /* The julian day number */
  60. int Y, M, D; /* Year, month, and day */
  61. int h, m; /* Hour and minutes */
  62. int tz; /* Timezone offset in minutes */
  63. double s; /* Seconds */
  64. char validYMD; /* True if Y,M,D are valid */
  65. char validHMS; /* True if h,m,s are valid */
  66. char validJD; /* True if rJD is valid */
  67. char validTZ; /* True if tz is valid */
  68. };
  69. /*
  70. ** Convert zDate into one or more integers. Additional arguments
  71. ** come in groups of 5 as follows:
  72. **
  73. ** N number of digits in the integer
  74. ** min minimum allowed value of the integer
  75. ** max maximum allowed value of the integer
  76. ** nextC first character after the integer
  77. ** pVal where to write the integers value.
  78. **
  79. ** Conversions continue until one with nextC==0 is encountered.
  80. ** The function returns the number of successful conversions.
  81. */
  82. static int getDigits(const char *zDate, ...){
  83. va_list ap;
  84. int val;
  85. int N;
  86. int min;
  87. int max;
  88. int nextC;
  89. int *pVal;
  90. int cnt = 0;
  91. va_start(ap, zDate);
  92. do{
  93. N = va_arg(ap, int);
  94. min = va_arg(ap, int);
  95. max = va_arg(ap, int);
  96. nextC = va_arg(ap, int);
  97. pVal = va_arg(ap, int*);
  98. val = 0;
  99. while( N-- ){
  100. if( !isdigit(*(u8*)zDate) ){
  101. goto end_getDigits;
  102. }
  103. val = val*10 + *zDate - '0';
  104. zDate++;
  105. }
  106. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  107. goto end_getDigits;
  108. }
  109. *pVal = val;
  110. zDate++;
  111. cnt++;
  112. }while( nextC );
  113. end_getDigits:
  114. va_end(ap);
  115. return cnt;
  116. }
  117. /*
  118. ** Read text from z[] and convert into a floating point number. Return
  119. ** the number of digits converted.
  120. */
  121. #define getValue sqlite3AtoF
  122. /*
  123. ** Parse a timezone extension on the end of a date-time.
  124. ** The extension is of the form:
  125. **
  126. ** (+/-)HH:MM
  127. **
  128. ** If the parse is successful, write the number of minutes
  129. ** of change in *pnMin and return 0. If a parser error occurs,
  130. ** return 0.
  131. **
  132. ** A missing specifier is not considered an error.
  133. */
  134. static int parseTimezone(const char *zDate, DateTime *p){
  135. int sgn = 0;
  136. int nHr, nMn;
  137. while( isspace(*(u8*)zDate) ){ zDate++; }
  138. p->tz = 0;
  139. if( *zDate=='-' ){
  140. sgn = -1;
  141. }else if( *zDate=='+' ){
  142. sgn = +1;
  143. }else{
  144. return *zDate!=0;
  145. }
  146. zDate++;
  147. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  148. return 1;
  149. }
  150. zDate += 5;
  151. p->tz = sgn*(nMn + nHr*60);
  152. while( isspace(*(u8*)zDate) ){ zDate++; }
  153. return *zDate!=0;
  154. }
  155. /*
  156. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  157. ** The HH, MM, and SS must each be exactly 2 digits. The
  158. ** fractional seconds FFFF can be one or more digits.
  159. **
  160. ** Return 1 if there is a parsing error and 0 on success.
  161. */
  162. static int parseHhMmSs(const char *zDate, DateTime *p){
  163. int h, m, s;
  164. double ms = 0.0;
  165. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  166. return 1;
  167. }
  168. zDate += 5;
  169. if( *zDate==':' ){
  170. zDate++;
  171. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  172. return 1;
  173. }
  174. zDate += 2;
  175. if( *zDate=='.' && isdigit((u8)zDate[1]) ){
  176. double rScale = 1.0;
  177. zDate++;
  178. while( isdigit(*(u8*)zDate) ){
  179. ms = ms*10.0 + *zDate - '0';
  180. rScale *= 10.0;
  181. zDate++;
  182. }
  183. ms /= rScale;
  184. }
  185. }else{
  186. s = 0;
  187. }
  188. p->validJD = 0;
  189. p->validHMS = 1;
  190. p->h = h;
  191. p->m = m;
  192. p->s = s + ms;
  193. if( parseTimezone(zDate, p) ) return 1;
  194. p->validTZ = p->tz!=0;
  195. return 0;
  196. }
  197. /*
  198. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  199. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  200. **
  201. ** Reference: Meeus page 61
  202. */
  203. static void computeJD(DateTime *p){
  204. int Y, M, D, A, B, X1, X2;
  205. if( p->validJD ) return;
  206. if( p->validYMD ){
  207. Y = p->Y;
  208. M = p->M;
  209. D = p->D;
  210. }else{
  211. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  212. M = 1;
  213. D = 1;
  214. }
  215. if( M<=2 ){
  216. Y--;
  217. M += 12;
  218. }
  219. A = Y/100;
  220. B = 2 - A + (A/4);
  221. X1 = 365.25*(Y+4716);
  222. X2 = 30.6001*(M+1);
  223. p->rJD = X1 + X2 + D + B - 1524.5;
  224. p->validJD = 1;
  225. if( p->validHMS ){
  226. p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
  227. if( p->validTZ ){
  228. p->rJD -= p->tz*60/86400.0;
  229. p->validYMD = 0;
  230. p->validHMS = 0;
  231. p->validTZ = 0;
  232. }
  233. }
  234. }
  235. /*
  236. ** Parse dates of the form
  237. **
  238. ** YYYY-MM-DD HH:MM:SS.FFF
  239. ** YYYY-MM-DD HH:MM:SS
  240. ** YYYY-MM-DD HH:MM
  241. ** YYYY-MM-DD
  242. **
  243. ** Write the result into the DateTime structure and return 0
  244. ** on success and 1 if the input string is not a well-formed
  245. ** date.
  246. */
  247. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  248. int Y, M, D, neg;
  249. if( zDate[0]=='-' ){
  250. zDate++;
  251. neg = 1;
  252. }else{
  253. neg = 0;
  254. }
  255. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  256. return 1;
  257. }
  258. zDate += 10;
  259. while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  260. if( parseHhMmSs(zDate, p)==0 ){
  261. /* We got the time */
  262. }else if( *zDate==0 ){
  263. p->validHMS = 0;
  264. }else{
  265. return 1;
  266. }
  267. p->validJD = 0;
  268. p->validYMD = 1;
  269. p->Y = neg ? -Y : Y;
  270. p->M = M;
  271. p->D = D;
  272. if( p->validTZ ){
  273. computeJD(p);
  274. }
  275. return 0;
  276. }
  277. /*
  278. ** Attempt to parse the given string into a Julian Day Number. Return
  279. ** the number of errors.
  280. **
  281. ** The following are acceptable forms for the input string:
  282. **
  283. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  284. ** DDDD.DD
  285. ** now
  286. **
  287. ** In the first form, the +/-HH:MM is always optional. The fractional
  288. ** seconds extension (the ".FFF") is optional. The seconds portion
  289. ** (":SS.FFF") is option. The year and date can be omitted as long
  290. ** as there is a time string. The time string can be omitted as long
  291. ** as there is a year and date.
  292. */
  293. static int parseDateOrTime(
  294. sqlite3_context *context,
  295. const char *zDate,
  296. DateTime *p
  297. ){
  298. memset(p, 0, sizeof(*p));
  299. if( parseYyyyMmDd(zDate,p)==0 ){
  300. return 0;
  301. }else if( parseHhMmSs(zDate, p)==0 ){
  302. return 0;
  303. }else if( sqlite3StrICmp(zDate,"now")==0){
  304. double r;
  305. sqlite3OsCurrentTime((sqlite3_vfs *)sqlite3_user_data(context), &r);
  306. p->rJD = r;
  307. p->validJD = 1;
  308. return 0;
  309. }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
  310. getValue(zDate, &p->rJD);
  311. p->validJD = 1;
  312. return 0;
  313. }
  314. return 1;
  315. }
  316. /*
  317. ** Compute the Year, Month, and Day from the julian day number.
  318. */
  319. static void computeYMD(DateTime *p){
  320. int Z, A, B, C, D, E, X1;
  321. if( p->validYMD ) return;
  322. if( !p->validJD ){
  323. p->Y = 2000;
  324. p->M = 1;
  325. p->D = 1;
  326. }else{
  327. Z = p->rJD + 0.5;
  328. A = (Z - 1867216.25)/36524.25;
  329. A = Z + 1 + A - (A/4);
  330. B = A + 1524;
  331. C = (B - 122.1)/365.25;
  332. D = 365.25*C;
  333. E = (B-D)/30.6001;
  334. X1 = 30.6001*E;
  335. p->D = B - D - X1;
  336. p->M = E<14 ? E-1 : E-13;
  337. p->Y = p->M>2 ? C - 4716 : C - 4715;
  338. }
  339. p->validYMD = 1;
  340. }
  341. /*
  342. ** Compute the Hour, Minute, and Seconds from the julian day number.
  343. */
  344. static void computeHMS(DateTime *p){
  345. int Z, s;
  346. if( p->validHMS ) return;
  347. computeJD(p);
  348. Z = p->rJD + 0.5;
  349. s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
  350. p->s = 0.001*s;
  351. s = p->s;
  352. p->s -= s;
  353. p->h = s/3600;
  354. s -= p->h*3600;
  355. p->m = s/60;
  356. p->s += s - p->m*60;
  357. p->validHMS = 1;
  358. }
  359. /*
  360. ** Compute both YMD and HMS
  361. */
  362. static void computeYMD_HMS(DateTime *p){
  363. computeYMD(p);
  364. computeHMS(p);
  365. }
  366. /*
  367. ** Clear the YMD and HMS and the TZ
  368. */
  369. static void clearYMD_HMS_TZ(DateTime *p){
  370. p->validYMD = 0;
  371. p->validHMS = 0;
  372. p->validTZ = 0;
  373. }
  374. /*
  375. ** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
  376. ** for the time value p where p is in UTC.
  377. */
  378. static double localtimeOffset(DateTime *p){
  379. DateTime x, y;
  380. time_t t;
  381. x = *p;
  382. computeYMD_HMS(&x);
  383. if( x.Y<1971 || x.Y>=2038 ){
  384. x.Y = 2000;
  385. x.M = 1;
  386. x.D = 1;
  387. x.h = 0;
  388. x.m = 0;
  389. x.s = 0.0;
  390. } else {
  391. int s = x.s + 0.5;
  392. x.s = s;
  393. }
  394. x.tz = 0;
  395. x.validJD = 0;
  396. computeJD(&x);
  397. t = (x.rJD-2440587.5)*86400.0 + 0.5;
  398. #ifdef HAVE_LOCALTIME_R
  399. {
  400. struct tm sLocal;
  401. localtime_r(&t, &sLocal);
  402. y.Y = sLocal.tm_year + 1900;
  403. y.M = sLocal.tm_mon + 1;
  404. y.D = sLocal.tm_mday;
  405. y.h = sLocal.tm_hour;
  406. y.m = sLocal.tm_min;
  407. y.s = sLocal.tm_sec;
  408. }
  409. #else
  410. {
  411. struct tm *pTm;
  412. sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
  413. pTm = localtime(&t);
  414. y.Y = pTm->tm_year + 1900;
  415. y.M = pTm->tm_mon + 1;
  416. y.D = pTm->tm_mday;
  417. y.h = pTm->tm_hour;
  418. y.m = pTm->tm_min;
  419. y.s = pTm->tm_sec;
  420. sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
  421. }
  422. #endif
  423. y.validYMD = 1;
  424. y.validHMS = 1;
  425. y.validJD = 0;
  426. y.validTZ = 0;
  427. computeJD(&y);
  428. return y.rJD - x.rJD;
  429. }
  430. /*
  431. ** Process a modifier to a date-time stamp. The modifiers are
  432. ** as follows:
  433. **
  434. ** NNN days
  435. ** NNN hours
  436. ** NNN minutes
  437. ** NNN.NNNN seconds
  438. ** NNN months
  439. ** NNN years
  440. ** start of month
  441. ** start of year
  442. ** start of week
  443. ** start of day
  444. ** weekday N
  445. ** unixepoch
  446. ** localtime
  447. ** utc
  448. **
  449. ** Return 0 on success and 1 if there is any kind of error.
  450. */
  451. static int parseModifier(const char *zMod, DateTime *p){
  452. int rc = 1;
  453. int n;
  454. double r;
  455. char *z, zBuf[30];
  456. z = zBuf;
  457. for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
  458. z[n] = tolower(zMod[n]);
  459. }
  460. z[n] = 0;
  461. switch( z[0] ){
  462. case 'l': {
  463. /* localtime
  464. **
  465. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  466. ** show local time.
  467. */
  468. if( strcmp(z, "localtime")==0 ){
  469. computeJD(p);
  470. p->rJD += localtimeOffset(p);
  471. clearYMD_HMS_TZ(p);
  472. rc = 0;
  473. }
  474. break;
  475. }
  476. case 'u': {
  477. /*
  478. ** unixepoch
  479. **
  480. ** Treat the current value of p->rJD as the number of
  481. ** seconds since 1970. Convert to a real julian day number.
  482. */
  483. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  484. p->rJD = p->rJD/86400.0 + 2440587.5;
  485. clearYMD_HMS_TZ(p);
  486. rc = 0;
  487. }else if( strcmp(z, "utc")==0 ){
  488. double c1;
  489. computeJD(p);
  490. c1 = localtimeOffset(p);
  491. p->rJD -= c1;
  492. clearYMD_HMS_TZ(p);
  493. p->rJD += c1 - localtimeOffset(p);
  494. rc = 0;
  495. }
  496. break;
  497. }
  498. case 'w': {
  499. /*
  500. ** weekday N
  501. **
  502. ** Move the date to the same time on the next occurrence of
  503. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  504. ** date is already on the appropriate weekday, this is a no-op.
  505. */
  506. if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
  507. && (n=r)==r && n>=0 && r<7 ){
  508. int Z;
  509. computeYMD_HMS(p);
  510. p->validTZ = 0;
  511. p->validJD = 0;
  512. computeJD(p);
  513. Z = p->rJD + 1.5;
  514. Z %= 7;
  515. if( Z>n ) Z -= 7;
  516. p->rJD += n - Z;
  517. clearYMD_HMS_TZ(p);
  518. rc = 0;
  519. }
  520. break;
  521. }
  522. case 's': {
  523. /*
  524. ** start of TTTTT
  525. **
  526. ** Move the date backwards to the beginning of the current day,
  527. ** or month or year.
  528. */
  529. if( strncmp(z, "start of ", 9)!=0 ) break;
  530. z += 9;
  531. computeYMD(p);
  532. p->validHMS = 1;
  533. p->h = p->m = 0;
  534. p->s = 0.0;
  535. p->validTZ = 0;
  536. p->validJD = 0;
  537. if( strcmp(z,"month")==0 ){
  538. p->D = 1;
  539. rc = 0;
  540. }else if( strcmp(z,"year")==0 ){
  541. computeYMD(p);
  542. p->M = 1;
  543. p->D = 1;
  544. rc = 0;
  545. }else if( strcmp(z,"day")==0 ){
  546. rc = 0;
  547. }
  548. break;
  549. }
  550. case '+':
  551. case '-':
  552. case '0':
  553. case '1':
  554. case '2':
  555. case '3':
  556. case '4':
  557. case '5':
  558. case '6':
  559. case '7':
  560. case '8':
  561. case '9': {
  562. n = getValue(z, &r);
  563. assert( n>=1 );
  564. if( z[n]==':' ){
  565. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  566. ** specified number of hours, minutes, seconds, and fractional seconds
  567. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  568. ** omitted.
  569. */
  570. const char *z2 = z;
  571. DateTime tx;
  572. int day;
  573. if( !isdigit(*(u8*)z2) ) z2++;
  574. memset(&tx, 0, sizeof(tx));
  575. if( parseHhMmSs(z2, &tx) ) break;
  576. computeJD(&tx);
  577. tx.rJD -= 0.5;
  578. day = (int)tx.rJD;
  579. tx.rJD -= day;
  580. if( z[0]=='-' ) tx.rJD = -tx.rJD;
  581. computeJD(p);
  582. clearYMD_HMS_TZ(p);
  583. p->rJD += tx.rJD;
  584. rc = 0;
  585. break;
  586. }
  587. z += n;
  588. while( isspace(*(u8*)z) ) z++;
  589. n = strlen(z);
  590. if( n>10 || n<3 ) break;
  591. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  592. computeJD(p);
  593. rc = 0;
  594. if( n==3 && strcmp(z,"day")==0 ){
  595. p->rJD += r;
  596. }else if( n==4 && strcmp(z,"hour")==0 ){
  597. p->rJD += r/24.0;
  598. }else if( n==6 && strcmp(z,"minute")==0 ){
  599. p->rJD += r/(24.0*60.0);
  600. }else if( n==6 && strcmp(z,"second")==0 ){
  601. p->rJD += r/(24.0*60.0*60.0);
  602. }else if( n==5 && strcmp(z,"month")==0 ){
  603. int x, y;
  604. computeYMD_HMS(p);
  605. p->M += r;
  606. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  607. p->Y += x;
  608. p->M -= x*12;
  609. p->validJD = 0;
  610. computeJD(p);
  611. y = r;
  612. if( y!=r ){
  613. p->rJD += (r - y)*30.0;
  614. }
  615. }else if( n==4 && strcmp(z,"year")==0 ){
  616. computeYMD_HMS(p);
  617. p->Y += r;
  618. p->validJD = 0;
  619. computeJD(p);
  620. }else{
  621. rc = 1;
  622. }
  623. clearYMD_HMS_TZ(p);
  624. break;
  625. }
  626. default: {
  627. break;
  628. }
  629. }
  630. return rc;
  631. }
  632. /*
  633. ** Process time function arguments. argv[0] is a date-time stamp.
  634. ** argv[1] and following are modifiers. Parse them all and write
  635. ** the resulting time into the DateTime structure p. Return 0
  636. ** on success and 1 if there are any errors.
  637. */
  638. static int isDate(
  639. sqlite3_context *context,
  640. int argc,
  641. sqlite3_value **argv,
  642. DateTime *p
  643. ){
  644. int i;
  645. const unsigned char *z;
  646. if( argc==0 ) return 1;
  647. z = sqlite3_value_text(argv[0]);
  648. if( !z || parseDateOrTime(context, (char*)z, p) ){
  649. return 1;
  650. }
  651. for(i=1; i<argc; i++){
  652. if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
  653. return 1;
  654. }
  655. }
  656. return 0;
  657. }
  658. /*
  659. ** The following routines implement the various date and time functions
  660. ** of SQLite.
  661. */
  662. /*
  663. ** julianday( TIMESTRING, MOD, MOD, ...)
  664. **
  665. ** Return the julian day number of the date specified in the arguments
  666. */
  667. static void juliandayFunc(
  668. sqlite3_context *context,
  669. int argc,
  670. sqlite3_value **argv
  671. ){
  672. DateTime x;
  673. if( isDate(context, argc, argv, &x)==0 ){
  674. computeJD(&x);
  675. sqlite3_result_double(context, x.rJD);
  676. }
  677. }
  678. /*
  679. ** datetime( TIMESTRING, MOD, MOD, ...)
  680. **
  681. ** Return YYYY-MM-DD HH:MM:SS
  682. */
  683. static void datetimeFunc(
  684. sqlite3_context *context,
  685. int argc,
  686. sqlite3_value **argv
  687. ){
  688. DateTime x;
  689. if( isDate(context, argc, argv, &x)==0 ){
  690. char zBuf[100];
  691. computeYMD_HMS(&x);
  692. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  693. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  694. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  695. }
  696. }
  697. /*
  698. ** time( TIMESTRING, MOD, MOD, ...)
  699. **
  700. ** Return HH:MM:SS
  701. */
  702. static void timeFunc(
  703. sqlite3_context *context,
  704. int argc,
  705. sqlite3_value **argv
  706. ){
  707. DateTime x;
  708. if( isDate(context, argc, argv, &x)==0 ){
  709. char zBuf[100];
  710. computeHMS(&x);
  711. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  712. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  713. }
  714. }
  715. /*
  716. ** date( TIMESTRING, MOD, MOD, ...)
  717. **
  718. ** Return YYYY-MM-DD
  719. */
  720. static void dateFunc(
  721. sqlite3_context *context,
  722. int argc,
  723. sqlite3_value **argv
  724. ){
  725. DateTime x;
  726. if( isDate(context, argc, argv, &x)==0 ){
  727. char zBuf[100];
  728. computeYMD(&x);
  729. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  730. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  731. }
  732. }
  733. /*
  734. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  735. **
  736. ** Return a string described by FORMAT. Conversions as follows:
  737. **
  738. ** %d day of month
  739. ** %f ** fractional seconds SS.SSS
  740. ** %H hour 00-24
  741. ** %j day of year 000-366
  742. ** %J ** Julian day number
  743. ** %m month 01-12
  744. ** %M minute 00-59
  745. ** %s seconds since 1970-01-01
  746. ** %S seconds 00-59
  747. ** %w day of week 0-6 sunday==0
  748. ** %W week of year 00-53
  749. ** %Y year 0000-9999
  750. ** %% %
  751. */
  752. static void strftimeFunc(
  753. sqlite3_context *context,
  754. int argc,
  755. sqlite3_value **argv
  756. ){
  757. DateTime x;
  758. u64 n;
  759. int i, j;
  760. char *z;
  761. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  762. char zBuf[100];
  763. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  764. for(i=0, n=1; zFmt[i]; i++, n++){
  765. if( zFmt[i]=='%' ){
  766. switch( zFmt[i+1] ){
  767. case 'd':
  768. case 'H':
  769. case 'm':
  770. case 'M':
  771. case 'S':
  772. case 'W':
  773. n++;
  774. /* fall thru */
  775. case 'w':
  776. case '%':
  777. break;
  778. case 'f':
  779. n += 8;
  780. break;
  781. case 'j':
  782. n += 3;
  783. break;
  784. case 'Y':
  785. n += 8;
  786. break;
  787. case 's':
  788. case 'J':
  789. n += 50;
  790. break;
  791. default:
  792. return; /* ERROR. return a NULL */
  793. }
  794. i++;
  795. }
  796. }
  797. if( n<sizeof(zBuf) ){
  798. z = zBuf;
  799. }else if( n>SQLITE_MAX_LENGTH ){
  800. sqlite3_result_error_toobig(context);
  801. return;
  802. }else{
  803. z = sqlite3_malloc( n );
  804. if( z==0 ) return;
  805. }
  806. computeJD(&x);
  807. computeYMD_HMS(&x);
  808. for(i=j=0; zFmt[i]; i++){
  809. if( zFmt[i]!='%' ){
  810. z[j++] = zFmt[i];
  811. }else{
  812. i++;
  813. switch( zFmt[i] ){
  814. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  815. case 'f': {
  816. double s = x.s;
  817. if( s>59.999 ) s = 59.999;
  818. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  819. j += strlen(&z[j]);
  820. break;
  821. }
  822. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  823. case 'W': /* Fall thru */
  824. case 'j': {
  825. int nDay; /* Number of days since 1st day of year */
  826. DateTime y = x;
  827. y.validJD = 0;
  828. y.M = 1;
  829. y.D = 1;
  830. computeJD(&y);
  831. nDay = x.rJD - y.rJD + 0.5;
  832. if( zFmt[i]=='W' ){
  833. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  834. wd = ((int)(x.rJD+0.5)) % 7;
  835. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  836. j += 2;
  837. }else{
  838. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  839. j += 3;
  840. }
  841. break;
  842. }
  843. case 'J': {
  844. sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
  845. j+=strlen(&z[j]);
  846. break;
  847. }
  848. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  849. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  850. case 's': {
  851. sqlite3_snprintf(30,&z[j],"%d",
  852. (int)((x.rJD-2440587.5)*86400.0 + 0.5));
  853. j += strlen(&z[j]);
  854. break;
  855. }
  856. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  857. case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
  858. case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
  859. case '%': z[j++] = '%'; break;
  860. }
  861. }
  862. }
  863. z[j] = 0;
  864. sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  865. if( z!=zBuf ){
  866. sqlite3_free(z);
  867. }
  868. }
  869. /*
  870. ** current_time()
  871. **
  872. ** This function returns the same value as time('now').
  873. */
  874. static void ctimeFunc(
  875. sqlite3_context *context,
  876. int argc,
  877. sqlite3_value **argv
  878. ){
  879. sqlite3_value *pVal = sqlite3ValueNew(0);
  880. if( pVal ){
  881. sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
  882. timeFunc(context, 1, &pVal);
  883. sqlite3ValueFree(pVal);
  884. }
  885. }
  886. /*
  887. ** current_date()
  888. **
  889. ** This function returns the same value as date('now').
  890. */
  891. static void cdateFunc(
  892. sqlite3_context *context,
  893. int argc,
  894. sqlite3_value **argv
  895. ){
  896. sqlite3_value *pVal = sqlite3ValueNew(0);
  897. if( pVal ){
  898. sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
  899. dateFunc(context, 1, &pVal);
  900. sqlite3ValueFree(pVal);
  901. }
  902. }
  903. /*
  904. ** current_timestamp()
  905. **
  906. ** This function returns the same value as datetime('now').
  907. */
  908. static void ctimestampFunc(
  909. sqlite3_context *context,
  910. int argc,
  911. sqlite3_value **argv
  912. ){
  913. sqlite3_value *pVal = sqlite3ValueNew(0);
  914. if( pVal ){
  915. sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
  916. datetimeFunc(context, 1, &pVal);
  917. sqlite3ValueFree(pVal);
  918. }
  919. }
  920. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  921. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  922. /*
  923. ** If the library is compiled to omit the full-scale date and time
  924. ** handling (to get a smaller binary), the following minimal version
  925. ** of the functions current_time(), current_date() and current_timestamp()
  926. ** are included instead. This is to support column declarations that
  927. ** include "DEFAULT CURRENT_TIME" etc.
  928. **
  929. ** This function uses the C-library functions time(), gmtime()
  930. ** and strftime(). The format string to pass to strftime() is supplied
  931. ** as the user-data for the function.
  932. */
  933. static void currentTimeFunc(
  934. sqlite3_context *context,
  935. int argc,
  936. sqlite3_value **argv
  937. ){
  938. time_t t;
  939. char *zFormat = (char *)sqlite3_user_data(context);
  940. char zBuf[20];
  941. time(&t);
  942. #ifdef SQLITE_TEST
  943. {
  944. extern int sqlite3_current_time; /* See os_XXX.c */
  945. if( sqlite3_current_time ){
  946. t = sqlite3_current_time;
  947. }
  948. }
  949. #endif
  950. #ifdef HAVE_GMTIME_R
  951. {
  952. struct tm sNow;
  953. gmtime_r(&t, &sNow);
  954. strftime(zBuf, 20, zFormat, &sNow);
  955. }
  956. #else
  957. {
  958. struct tm *pTm;
  959. sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
  960. pTm = gmtime(&t);
  961. strftime(zBuf, 20, zFormat, pTm);
  962. sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
  963. }
  964. #endif
  965. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  966. }
  967. #endif
  968. /*
  969. ** This function registered all of the above C functions as SQL
  970. ** functions. This should be the only routine in this file with
  971. ** external linkage.
  972. */
  973. void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
  974. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  975. static const struct {
  976. char *zName;
  977. int nArg;
  978. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  979. } aFuncs[] = {
  980. { "julianday", -1, juliandayFunc },
  981. { "date", -1, dateFunc },
  982. { "time", -1, timeFunc },
  983. { "datetime", -1, datetimeFunc },
  984. { "strftime", -1, strftimeFunc },
  985. { "current_time", 0, ctimeFunc },
  986. { "current_timestamp", 0, ctimestampFunc },
  987. { "current_date", 0, cdateFunc },
  988. };
  989. int i;
  990. for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
  991. sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
  992. SQLITE_UTF8, (void *)(db->pVfs), aFuncs[i].xFunc, 0, 0);
  993. }
  994. #else
  995. static const struct {
  996. char *zName;
  997. char *zFormat;
  998. } aFuncs[] = {
  999. { "current_time", "%H:%M:%S" },
  1000. { "current_date", "%Y-%m-%d" },
  1001. { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
  1002. };
  1003. int i;
  1004. for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
  1005. sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
  1006. aFuncs[i].zFormat, currentTimeFunc, 0, 0);
  1007. }
  1008. #endif
  1009. }