forked from dolthub/go-mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
date_format.go
346 lines (282 loc) · 7.1 KB
/
date_format.go
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
// Copyright 2020-2021 Dolthub, Inc.
//
// 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 function
import (
"fmt"
"strconv"
"time"
"github.com/lestrrat-go/strftime"
"github.com/gabereiser/go-mysql-server/sql"
"github.com/gabereiser/go-mysql-server/sql/expression"
"github.com/gabereiser/go-mysql-server/sql/types"
)
func panicIfErr(err error) {
if err != nil {
panic(err)
}
}
func monthNum(t time.Time) string {
return strconv.FormatInt(int64(t.Month()), 10)
}
func dayWithSuffix(t time.Time) string {
suffix := "th"
day := int64(t.Day())
if day < 4 || day > 20 {
switch day % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
}
}
return strconv.FormatInt(day, 10) + suffix
}
func dayOfMonth(t time.Time) string {
return strconv.FormatInt(int64(t.Day()), 10)
}
func microsecondsStr(t time.Time) string {
micros := t.Nanosecond() / int(time.Microsecond)
return fmt.Sprintf("%06d", micros)
}
func minutesStr(t time.Time) string {
return fmt.Sprintf("%02d", t.Minute())
}
func twelveHour(t time.Time) (int, string) {
ampm := "AM"
if t.Hour() >= 12 {
ampm = "PM"
}
hour := t.Hour() % 12
if hour == 0 {
hour = 12
}
return hour, ampm
}
func twelveHourPadded(t time.Time) string {
hour, _ := twelveHour(t)
return fmt.Sprintf("%02d", hour)
}
func twelveHourNoPadding(t time.Time) string {
hour, _ := twelveHour(t)
return fmt.Sprintf("%d", hour)
}
func twentyFourHourNoPadding(t time.Time) string {
return fmt.Sprintf("%d", t.Hour())
}
func fullMonthName(t time.Time) string {
return t.Month().String()
}
func ampmClockStr(t time.Time) string {
hour, ampm := twelveHour(t)
return fmt.Sprintf("%02d:%02d:%02d %s", hour, t.Minute(), t.Second(), ampm)
}
func secondsStr(t time.Time) string {
return fmt.Sprintf("%02d", t.Second())
}
func yearWeek(mode int32, t time.Time) (int32, int32) {
yw := YearWeek{expression.NewLiteral(t, types.Datetime), expression.NewLiteral(mode, types.Int32)}
res, _ := yw.Eval(nil, nil)
yr := res.(int32) / 100
wk := res.(int32) % 100
return yr, wk
}
func weekMode0(t time.Time) string {
yr, wk := yearWeek(0, t)
if yr < int32(t.Year()) {
wk = 0
} else if yr > int32(t.Year()) {
wk = 53
}
return fmt.Sprintf("%02d", wk)
}
func weekMode1(t time.Time) string {
yr, wk := yearWeek(1, t)
if yr < int32(t.Year()) {
wk = 0
} else if yr > int32(t.Year()) {
wk = 53
}
return fmt.Sprintf("%02d", wk)
}
func weekMode2(t time.Time) string {
_, wk := yearWeek(2, t)
return fmt.Sprintf("%02d", wk)
}
func weekMode3(t time.Time) string {
_, wk := yearWeek(3, t)
return fmt.Sprintf("%02d", wk)
}
func yearMode0(t time.Time) string {
yr, _ := yearWeek(0, t)
return strconv.FormatInt(int64(yr), 10)
}
func yearMode1(t time.Time) string {
yr, _ := yearWeek(1, t)
return strconv.FormatInt(int64(yr), 10)
}
func dayName(t time.Time) string {
return t.Weekday().String()
}
func yearTwoDigit(t time.Time) string {
return strconv.FormatInt(int64(t.Year())%100, 10)
}
type AppendFuncWrapper struct {
fn func(time.Time) string
}
func wrap(fn func(time.Time) string) strftime.Appender {
return AppendFuncWrapper{fn}
}
func (af AppendFuncWrapper) Append(bytes []byte, t time.Time) []byte {
s := af.fn(t)
return append(bytes, []byte(s)...)
}
var mysqlDateFormatSpec = strftime.NewSpecificationSet()
var dateFormatSpecifierToFunc = map[byte]func(time.Time) string{
'a': nil,
'b': nil,
'c': monthNum,
'D': dayWithSuffix,
'd': nil,
'e': dayOfMonth,
'f': microsecondsStr,
'H': nil,
'h': twelveHourPadded,
'I': twelveHourPadded,
'i': minutesStr,
'j': nil,
'k': twentyFourHourNoPadding,
'l': twelveHourNoPadding,
'M': fullMonthName,
'm': nil,
'p': nil,
'r': ampmClockStr,
'S': nil,
's': secondsStr,
'T': nil,
'U': weekMode0,
'u': weekMode1,
'V': weekMode2,
'v': weekMode3,
'W': dayName,
'w': nil,
'X': yearMode0,
'x': yearMode1,
'Y': nil,
'y': yearTwoDigit,
}
func init() {
for specifier, fn := range dateFormatSpecifierToFunc {
if fn != nil {
panicIfErr(mysqlDateFormatSpec.Set(specifier, wrap(fn)))
}
}
// replace any strftime specifiers that aren't supported
fn := func(b byte) {
if _, ok := dateFormatSpecifierToFunc[b]; !ok {
panicIfErr(mysqlDateFormatSpec.Set(b, wrap(func(time.Time) string {
return string(b)
})))
}
}
capToLower := byte('a' - 'A')
for i := byte('A'); i <= 'Z'; i++ {
fn(i)
fn(i + capToLower)
}
}
func formatDate(format string, t time.Time) (string, error) {
formatter, err := strftime.New(format, strftime.WithSpecificationSet(mysqlDateFormatSpec))
if err != nil {
return "", err
}
return formatter.FormatString(t), nil
}
// DateFormat function returns a string representation of the date specified in the format specified
type DateFormat struct {
expression.BinaryExpression
}
var _ sql.FunctionExpression = (*DateFormat)(nil)
// FunctionName implements sql.FunctionExpression
func (f *DateFormat) FunctionName() string {
return "date_format"
}
// Description implements sql.FunctionExpression
func (f *DateFormat) Description() string {
return "format date as specified."
}
// NewDateFormat returns a new DateFormat UDF
func NewDateFormat(ex, value sql.Expression) sql.Expression {
return &DateFormat{
expression.BinaryExpression{
Left: ex,
Right: value,
},
}
}
// Eval implements the Expression interface.
func (f *DateFormat) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
if f.Left == nil || f.Right == nil {
return nil, nil
}
left, err := f.Left.Eval(ctx, row)
if err != nil {
return nil, err
}
if left == nil {
return nil, nil
}
timeVal, err := types.Datetime.Convert(left)
if err != nil {
return nil, err
}
t := timeVal.(time.Time)
right, err := f.Right.Eval(ctx, row)
if err != nil {
return nil, err
}
if right == nil {
return nil, nil
}
formatStr, ok := right.(string)
if !ok {
return nil, sql.ErrInvalidArgumentDetails.New("DATE_FORMAT", "format must be a string")
}
return formatDate(formatStr, t)
}
// Type implements the Expression interface.
func (f *DateFormat) Type() sql.Type {
return types.Text
}
// IsNullable implements the Expression interface.
func (f *DateFormat) IsNullable() bool {
if types.IsNull(f.Left) {
if types.IsNull(f.Right) {
return true
}
return f.Right.IsNullable()
}
return f.Left.IsNullable()
}
func (f *DateFormat) String() string {
return fmt.Sprintf("date_format(%s, %s)", f.Left, f.Right)
}
// WithChildren implements the Expression interface.
func (f *DateFormat) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(f, len(children), 2)
}
return NewDateFormat(children[0], children[1]), nil
}