1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
|
/*
Copyright (c) 2017 James Ahlborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.healthmarketscience.jackcess.impl.expr;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.WeekFields;
import com.healthmarketscience.jackcess.expr.EvalContext;
import com.healthmarketscience.jackcess.expr.EvalException;
import com.healthmarketscience.jackcess.expr.Function;
import com.healthmarketscience.jackcess.expr.LocaleContext;
import com.healthmarketscience.jackcess.expr.TemporalConfig;
import com.healthmarketscience.jackcess.expr.Value;
import com.healthmarketscience.jackcess.impl.ColumnImpl;
import static com.healthmarketscience.jackcess.impl.expr.DefaultFunctions.*;
import static com.healthmarketscience.jackcess.impl.expr.FunctionSupport.*;
/**
*
* @author James Ahlborn
*/
public class DefaultDateFunctions
{
// min, valid, recognizable date: January 1, 100 A.D. 00:00:00
private static final double MIN_DATE = -657434.0d;
// max, valid, recognizable date: December 31, 9999 A.D. 23:59:59
private static final double MAX_DATE = 2958465.999988426d;
private static final String INTV_YEAR = "yyyy";
private static final String INTV_QUARTER = "q";
private static final String INTV_MONTH = "m";
private static final String INTV_DAY_OF_YEAR = "y";
private static final String INTV_DAY = "d";
private static final String INTV_WEEKDAY = "w";
private static final String INTV_WEEK = "ww";
private static final String INTV_HOUR = "h";
private static final String INTV_MINUTE = "n";
private static final String INTV_SECOND = "s";
private static final WeekFields SUNDAY_FIRST =
WeekFields.of(DayOfWeek.SUNDAY, 1);
private DefaultDateFunctions() {}
static void init() {
// dummy method to ensure this class is loaded
}
public static final Function DATE = registerFunc(new Func0("Date") {
@Override
protected Value eval0(EvalContext ctx) {
return ValueSupport.toValue(LocalDate.now());
}
});
public static final Function DATEVALUE = registerFunc(new Func1NullIsNull("DateValue") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
Value dv = param1.getAsDateTimeValue(ctx);
if(dv.getType() == Value.Type.DATE) {
return dv;
}
return ValueSupport.toValue(dv.getAsLocalDateTime(ctx).toLocalDate());
}
});
public static final Function DATESERIAL = registerFunc(new Func3("DateSerial") {
@Override
protected Value eval3(EvalContext ctx, Value param1, Value param2, Value param3) {
int year = param1.getAsLongInt(ctx);
int month = param2.getAsLongInt(ctx);
int day = param3.getAsLongInt(ctx);
// "default" two digit year handling
if(year < 100) {
year += ((year <= 29) ? 2000 : 1900);
}
// we have to construct incrementatlly to handle out of range values
LocalDate ld = LocalDate.of(year,1,1).plusMonths(month - 1)
.plusDays(day - 1);
return ValueSupport.toValue(ld);
}
});
public static final Function DATEPART = registerFunc(new FuncVar("DatePart", 2, 4) {
@Override
protected Value evalVar(EvalContext ctx, Value[] params) {
Value param2 = params[1];
if(param2.isNull()) {
return ValueSupport.NULL_VAL;
}
int firstDay = getFirstDayParam(ctx, params, 2);
int firstWeekType = getFirstWeekTypeParam(ctx, params, 3);
String intv = params[0].getAsString(ctx).trim();
int result = -1;
if(intv.equalsIgnoreCase(INTV_YEAR)) {
result = param2.getAsLocalDateTime(ctx).getYear();
} else if(intv.equalsIgnoreCase(INTV_QUARTER)) {
result = getQuarter(param2.getAsLocalDateTime(ctx));
} else if(intv.equalsIgnoreCase(INTV_MONTH)) {
result = param2.getAsLocalDateTime(ctx).getMonthValue();
} else if(intv.equalsIgnoreCase(INTV_DAY_OF_YEAR)) {
result = param2.getAsLocalDateTime(ctx).getDayOfYear();
} else if(intv.equalsIgnoreCase(INTV_DAY)) {
result = param2.getAsLocalDateTime(ctx).getDayOfMonth();
} else if(intv.equalsIgnoreCase(INTV_WEEKDAY)) {
int dayOfWeek = param2.getAsLocalDateTime(ctx)
.get(SUNDAY_FIRST.dayOfWeek());
result = dayOfWeekToWeekDay(dayOfWeek, firstDay);
} else if(intv.equalsIgnoreCase(INTV_WEEK)) {
result = weekOfYear(ctx, param2, firstDay, firstWeekType);
} else if(intv.equalsIgnoreCase(INTV_HOUR)) {
result = param2.getAsLocalDateTime(ctx).getHour();
} else if(intv.equalsIgnoreCase(INTV_MINUTE)) {
result = param2.getAsLocalDateTime(ctx).getMinute();
} else if(intv.equalsIgnoreCase(INTV_SECOND)) {
result = param2.getAsLocalDateTime(ctx).getSecond();
} else {
throw new EvalException("Invalid interval " + intv);
}
return ValueSupport.toValue(result);
}
});
public static final Function DATEADD = registerFunc(new Func3("DateAdd") {
@Override
protected Value eval3(EvalContext ctx,
Value param1, Value param2, Value param3) {
if(param3.isNull()) {
return ValueSupport.NULL_VAL;
}
String intv = param1.getAsString(ctx).trim();
int val = param2.getAsLongInt(ctx);
LocalDateTime ldt = param3.getAsLocalDateTime(ctx);
if(intv.equalsIgnoreCase(INTV_YEAR)) {
ldt = ldt.plus(val, ChronoUnit.YEARS);
} else if(intv.equalsIgnoreCase(INTV_QUARTER)) {
ldt = ldt.plus(val * 3, ChronoUnit.MONTHS);
} else if(intv.equalsIgnoreCase(INTV_MONTH)) {
ldt = ldt.plus(val, ChronoUnit.MONTHS);
} else if(intv.equalsIgnoreCase(INTV_DAY_OF_YEAR) ||
intv.equalsIgnoreCase(INTV_DAY) ||
intv.equalsIgnoreCase(INTV_WEEKDAY)) {
ldt = ldt.plus(val, ChronoUnit.DAYS);
} else if(intv.equalsIgnoreCase(INTV_WEEK)) {
ldt = ldt.plus(val, ChronoUnit.WEEKS);
} else if(intv.equalsIgnoreCase(INTV_HOUR)) {
ldt = ldt.plus(val, ChronoUnit.HOURS);
} else if(intv.equalsIgnoreCase(INTV_MINUTE)) {
ldt = ldt.plus(val, ChronoUnit.MINUTES);
} else if(intv.equalsIgnoreCase(INTV_SECOND)) {
ldt = ldt.plus(val, ChronoUnit.SECONDS);
} else {
throw new EvalException("Invalid interval " + intv);
}
return ValueSupport.toValue(ldt);
}
});
public static final Function DATEDIFF = registerFunc(new FuncVar("DateDiff", 3, 5) {
@Override
protected Value evalVar(EvalContext ctx, Value[] params) {
Value param2 = params[1];
Value param3 = params[2];
if(param2.isNull() || param3.isNull()) {
return ValueSupport.NULL_VAL;
}
int firstDay = getFirstDayParam(ctx, params, 3);
int firstWeekType = getFirstWeekTypeParam(ctx, params, 4);
String intv = params[0].getAsString(ctx).trim();
LocalDateTime ldt1 = param2.getAsLocalDateTime(ctx);
LocalDateTime ldt2 = param3.getAsLocalDateTime(ctx);
int sign = 1;
if(ldt1.isAfter(ldt2)) {
LocalDateTime tmp = ldt1;
ldt1 = ldt2;
ldt2 = tmp;
sign = -1;
}
// NOTE: DateDiff understands leap years, but not daylight savings time
// (i.e. it doesn't really take into account timezones). so all time
// based calculations assume 24 hour days.
int result = -1;
if(intv.equalsIgnoreCase(INTV_YEAR)) {
result = ldt2.getYear() - ldt1.getYear();
} else if(intv.equalsIgnoreCase(INTV_QUARTER)) {
int y1 = ldt1.getYear();
int q1 = getQuarter(ldt1);
int y2 = ldt2.getYear();
int q2 = getQuarter(ldt2);
while(y2 > y1) {
q2 += 4;
--y2;
}
result = q2 - q1;
} else if(intv.equalsIgnoreCase(INTV_MONTH)) {
int y1 = ldt1.getYear();
int m1 = ldt1.getMonthValue();
int y2 = ldt2.getYear();
int m2 = ldt2.getMonthValue();
while(y2 > y1) {
m2 += 12;
--y2;
}
result = m2 - m1;
} else if(intv.equalsIgnoreCase(INTV_DAY_OF_YEAR) ||
intv.equalsIgnoreCase(INTV_DAY)) {
result = getDayDiff(ldt1, ldt2);
} else if(intv.equalsIgnoreCase(INTV_WEEKDAY)) {
// this calulates number of 7 day periods between two dates
result = getDayDiff(ldt1, ldt2) / 7;
} else if(intv.equalsIgnoreCase(INTV_WEEK)) {
// this counts number of "week of year" intervals between two dates
WeekFields weekFields = weekFields(firstDay, firstWeekType);
int w1 = ldt1.get(weekFields.weekOfWeekBasedYear());
int y1 = ldt1.get(weekFields.weekBasedYear());
int w2 = ldt2.get(weekFields.weekOfWeekBasedYear());
int y2 = ldt2.get(weekFields.weekBasedYear());
while(y2 > y1) {
--y2;
w2 += weeksInYear(y2, weekFields);
}
result = w2 - w1;
} else if(intv.equalsIgnoreCase(INTV_HOUR)) {
result = getHourDiff(ldt1, ldt2);
} else if(intv.equalsIgnoreCase(INTV_MINUTE)) {
result = getMinuteDiff(ldt1, ldt2);
} else if(intv.equalsIgnoreCase(INTV_SECOND)) {
int s1 = ldt1.getSecond();
int s2 = ldt2.getSecond();
int minuteDiff = getMinuteDiff(ldt1, ldt2);
result = (s2 + (60 * minuteDiff)) - s1;
} else {
throw new EvalException("Invalid interval " + intv);
}
return ValueSupport.toValue(result * sign);
}
});
public static final Function NOW = registerFunc(new Func0("Now") {
@Override
protected Value eval0(EvalContext ctx) {
return ValueSupport.toValue(Value.Type.DATE_TIME,
LocalDateTime.now(ctx.getZoneId()));
}
});
public static final Function TIME = registerFunc(new Func0("Time") {
@Override
protected Value eval0(EvalContext ctx) {
return ValueSupport.toValue(LocalTime.now(ctx.getZoneId()));
}
});
public static final Function TIMEVALUE = registerFunc(new Func1NullIsNull("TimeValue") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
Value dv = param1.getAsDateTimeValue(ctx);
if(dv.getType() == Value.Type.TIME) {
return dv;
}
return ValueSupport.toValue(dv.getAsLocalDateTime(ctx).toLocalTime());
}
});
public static final Function TIMER = registerFunc(new Func0("Timer") {
@Override
protected Value eval0(EvalContext ctx) {
double dd = LocalTime.now(ctx.getZoneId())
.get(ChronoField.MILLI_OF_DAY) / 1000d;
return ValueSupport.toValue(dd);
}
});
public static final Function TIMESERIAL = registerFunc(new Func3("TimeSerial") {
@Override
protected Value eval3(EvalContext ctx, Value param1, Value param2, Value param3) {
int hours = param1.getAsLongInt(ctx);
int minutes = param2.getAsLongInt(ctx);
int seconds = param3.getAsLongInt(ctx);
// we have to construct incrementatlly to handle out of range values
LocalTime lt = ColumnImpl.BASE_LT.plusHours(hours).plusMinutes(minutes)
.plusSeconds(seconds);
return ValueSupport.toValue(lt);
}
});
public static final Function HOUR = registerFunc(new Func1NullIsNull("Hour") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
return ValueSupport.toValue(param1.getAsLocalDateTime(ctx).getHour());
}
});
public static final Function MINUTE = registerFunc(new Func1NullIsNull("Minute") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
return ValueSupport.toValue(param1.getAsLocalDateTime(ctx).getMinute());
}
});
public static final Function SECOND = registerFunc(new Func1NullIsNull("Second") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
return ValueSupport.toValue(param1.getAsLocalDateTime(ctx).getSecond());
}
});
public static final Function YEAR = registerFunc(new Func1NullIsNull("Year") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
return ValueSupport.toValue(param1.getAsLocalDateTime(ctx).getYear());
}
});
public static final Function MONTH = registerFunc(new Func1NullIsNull("Month") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
return ValueSupport.toValue(param1.getAsLocalDateTime(ctx).getMonthValue());
}
});
public static final Function MONTHNAME = registerFunc(new FuncVar("MonthName", 1, 2) {
@Override
protected Value evalVar(EvalContext ctx, Value[] params) {
Value param1 = params[0];
if(param1.isNull()) {
return ValueSupport.NULL_VAL;
}
Month month = Month.of(param1.getAsLongInt(ctx));
TextStyle textStyle = getTextStyle(ctx, params, 1);
String monthName = month.getDisplayName(
textStyle, ctx.getTemporalConfig().getLocale());
return ValueSupport.toValue(monthName);
}
});
public static final Function DAY = registerFunc(new Func1NullIsNull("Day") {
@Override
protected Value eval1(EvalContext ctx, Value param1) {
return ValueSupport.toValue(
param1.getAsLocalDateTime(ctx).getDayOfMonth());
}
});
public static final Function WEEKDAY = registerFunc(new FuncVar("Weekday", 1, 2) {
@Override
protected Value evalVar(EvalContext ctx, Value[] params) {
Value param1 = params[0];
if(param1.isNull()) {
return ValueSupport.NULL_VAL;
}
int dayOfWeek = param1.getAsLocalDateTime(ctx)
.get(SUNDAY_FIRST.dayOfWeek());
int firstDay = getFirstDayParam(ctx, params, 1);
return ValueSupport.toValue(dayOfWeekToWeekDay(dayOfWeek, firstDay));
}
});
public static final Function WEEKDAYNAME = registerFunc(new FuncVar("WeekdayName", 1, 3) {
@Override
protected Value evalVar(EvalContext ctx, Value[] params) {
Value param1 = params[0];
if(param1.isNull()) {
return ValueSupport.NULL_VAL;
}
int weekday = param1.getAsLongInt(ctx);
TextStyle textStyle = getTextStyle(ctx, params, 1);
int firstDay = getFirstDayParam(ctx, params, 2);
int dayOfWeek = weekDayToDayOfWeek(weekday, firstDay);
String weekdayName = dayOfWeek(dayOfWeek).getDisplayName(
textStyle, ctx.getTemporalConfig().getLocale());
return ValueSupport.toValue(weekdayName);
}
});
static Value stringToDateValue(LocaleContext ctx, String valStr) {
// see if we can coerce to date/time
TemporalConfig.Type valTempType = ExpressionTokenizer.determineDateType(
valStr, ctx);
if(valTempType != null) {
DateTimeFormatter parseDf = ctx.createDateFormatter(
ctx.getTemporalConfig().getDateTimeFormat(valTempType));
try {
TemporalAccessor parsedInfo = parseDf.parse(valStr);
LocalDate ld = ColumnImpl.BASE_LD;
if(valTempType.includesDate()) {
// the year may not be explicitly specified
if(parsedInfo.isSupported(ChronoField.YEAR)) {
ld = LocalDate.from(parsedInfo);
} else {
ld = MonthDay.from(parsedInfo).atYear(
Year.now(ctx.getZoneId()).getValue());
}
}
LocalTime lt = ColumnImpl.BASE_LT;
if(valTempType.includesTime()) {
lt = LocalTime.from(parsedInfo);
}
return ValueSupport.toValue(LocalDateTime.of(ld, lt));
} catch(DateTimeException de) {
// note a valid date/time
}
}
// not a valid date string, not a date/time
return null;
}
static boolean isValidDateDouble(double dd) {
return ((dd >= MIN_DATE) && (dd <= MAX_DATE));
}
static Value numberToDateValue(double dd) {
if(!isValidDateDouble(dd)) {
// outside valid date range
return null;
}
LocalDateTime ldt = ColumnImpl.ldtFromLocalDateDouble(dd);
return ValueSupport.toValue(ldt);
}
private static int dayOfWeekToWeekDay(int day, int firstDay) {
// shift all the values to 0 based to calculate the correct value, then
// back to 1 based to return the result
return (((day - 1) - (firstDay - 1) + 7) % 7) + 1;
}
private static int weekDayToDayOfWeek(int weekday, int firstDay) {
// shift all the values to 0 based to calculate the correct value, then
// back to 1 based to return the result
return (((firstDay - 1) + (weekday - 1)) % 7) + 1;
}
static int getFirstDayParam(
LocaleContext ctx, Value[] params, int idx) {
// vbSunday (default) 1
// vbUseSystem 0
return getOptionalIntParam(ctx, params, idx, 1, 0);
}
static int getFirstWeekTypeParam(
LocaleContext ctx, Value[] params, int idx) {
// vbFirstJan1 (default) 1
// vbUseSystem 0
return getOptionalIntParam(ctx, params, idx, 1, 0);
}
static WeekFields weekFields(int firstDay, int firstWeekType) {
int minDays = 1;
switch(firstWeekType) {
case 1:
// vbUseSystem 0
// vbFirstJan1 1 (default)
break;
case 2:
// vbFirstFourDays 2
minDays = 4;
break;
case 3:
// vbFirstFullWeek 3
minDays = 7;
break;
default:
throw new EvalException("Invalid first week of year type " +
firstWeekType);
}
return WeekFields.of(dayOfWeek(firstDay), minDays);
}
private static DayOfWeek dayOfWeek(int dayOfWeek) {
return DayOfWeek.SUNDAY.plus(dayOfWeek - 1);
}
private static TextStyle getTextStyle(EvalContext ctx, Value[] params,
int idx) {
boolean abbreviate = getOptionalBooleanParam(ctx, params, idx);
return (abbreviate ? TextStyle.SHORT : TextStyle.FULL);
}
private static int weekOfYear(EvalContext ctx, Value param, int firstDay,
int firstWeekType) {
return weekOfYear(param.getAsLocalDateTime(ctx), firstDay, firstWeekType);
}
private static int weekOfYear(LocalDateTime ldt, int firstDay,
int firstWeekType) {
WeekFields weekFields = weekFields(firstDay, firstWeekType);
return ldt.get(weekFields.weekOfWeekBasedYear());
}
private static int weeksInYear(int year, WeekFields weekFields) {
return (int)LocalDate.of(year,2,1).range(weekFields.weekOfWeekBasedYear())
.getMaximum();
}
private static int getQuarter(LocalDateTime ldt) {
int month = ldt.getMonthValue() - 1;
return (month / 3) + 1;
}
private static int getDayDiff(LocalDateTime ldt1, LocalDateTime ldt2) {
int y1 = ldt1.getYear();
int d1 = ldt1.getDayOfYear();
int y2 = ldt2.getYear();
int d2 = ldt2.getDayOfYear();
while(y2 > y1) {
ldt2 = ldt2.minusYears(1);
d2 += ldt2.range(ChronoField.DAY_OF_YEAR).getMaximum();
y2 = ldt2.getYear();
}
return d2 - d1;
}
private static int getHourDiff(LocalDateTime ldt1, LocalDateTime ldt2) {
int h1 = ldt1.getHour();
int h2 = ldt2.getHour();
int dayDiff = getDayDiff(ldt1, ldt2);
return (h2 + (24 * dayDiff)) - h1;
}
private static int getMinuteDiff(LocalDateTime ldt1, LocalDateTime ldt2) {
int m1 = ldt1.getMinute();
int m2 = ldt2.getMinute();
int hourDiff = getHourDiff(ldt1, ldt2);
return (m2 + (60 * hourDiff)) - m1;
}
}
|