github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/time_format.go (about)

     1  // Copyright 2020-2021 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package function
    16  
    17  import (
    18  	"fmt"
    19  	"time"
    20  
    21  	"github.com/lestrrat-go/strftime"
    22  
    23  	"github.com/dolthub/go-mysql-server/sql"
    24  	"github.com/dolthub/go-mysql-server/sql/expression"
    25  	"github.com/dolthub/go-mysql-server/sql/types"
    26  )
    27  
    28  var mysqlTimeFormatSpec = strftime.NewSpecificationSet()
    29  var timeFormatSpecifierToFunc = map[byte]func(time.Time) string{
    30  	'f': microsecondsStr,
    31  	'H': nil,
    32  	'h': twelveHourPadded,
    33  	'I': twelveHourPadded,
    34  	'i': minutesStr,
    35  	'p': nil,
    36  	'r': ampmClockStr,
    37  	'S': nil,
    38  	's': secondsStr,
    39  	'T': nil,
    40  }
    41  
    42  func init() {
    43  	for specifier, fn := range timeFormatSpecifierToFunc {
    44  		if fn != nil {
    45  			panicIfErr(mysqlTimeFormatSpec.Set(specifier, wrap(fn)))
    46  		}
    47  	}
    48  
    49  	// replace any strftime specifiers that aren't supported
    50  	fn := func(b byte) {
    51  		if _, ok := timeFormatSpecifierToFunc[b]; !ok {
    52  			panicIfErr(mysqlTimeFormatSpec.Set(b, wrap(func(time.Time) string {
    53  				return string(b)
    54  			})))
    55  		}
    56  	}
    57  
    58  	capToLower := byte('a' - 'A')
    59  	for i := byte('A'); i <= 'Z'; i++ {
    60  		fn(i)
    61  		fn(i + capToLower)
    62  	}
    63  }
    64  
    65  func formatTime(format string, t time.Time) (string, error) {
    66  	formatter, err := strftime.New(format, strftime.WithSpecificationSet(mysqlTimeFormatSpec))
    67  	if err != nil {
    68  		return "", err
    69  	}
    70  
    71  	return formatter.FormatString(t), nil
    72  }
    73  
    74  // TimeFormat function returns a string representation of the date specified in the format specified
    75  type TimeFormat struct {
    76  	expression.BinaryExpressionStub
    77  }
    78  
    79  var _ sql.FunctionExpression = (*TimeFormat)(nil)
    80  var _ sql.CollationCoercible = (*TimeFormat)(nil)
    81  
    82  // FunctionName implements sql.FunctionExpression
    83  func (f *TimeFormat) FunctionName() string {
    84  	return "time_format"
    85  }
    86  
    87  // Description implements sql.FunctionExpression
    88  func (f *TimeFormat) Description() string {
    89  	return "format time as specified."
    90  }
    91  
    92  // NewTimeFormat returns a new TimeFormat UDF
    93  func NewTimeFormat(ex, value sql.Expression) sql.Expression {
    94  	return &TimeFormat{
    95  		expression.BinaryExpressionStub{
    96  			LeftChild:  ex,
    97  			RightChild: value,
    98  		},
    99  	}
   100  }
   101  
   102  // Eval implements the Expression interface.
   103  func (f *TimeFormat) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
   104  	if f.LeftChild == nil || f.RightChild == nil {
   105  		return nil, nil
   106  	}
   107  
   108  	left, err := f.LeftChild.Eval(ctx, row)
   109  	if err != nil {
   110  		return nil, err
   111  	}
   112  
   113  	if left == nil {
   114  		return nil, nil
   115  	}
   116  
   117  	d, err := types.Time.ConvertToTimeDuration(left)
   118  	if err != nil {
   119  		return nil, err
   120  	}
   121  
   122  	right, err := f.RightChild.Eval(ctx, row)
   123  	if err != nil {
   124  		return nil, err
   125  	}
   126  
   127  	if right == nil {
   128  		return nil, nil
   129  	}
   130  
   131  	formatStr, ok := right.(string)
   132  	if !ok {
   133  		return nil, sql.ErrInvalidArgumentDetails.New("time_format", "format must be a string")
   134  	}
   135  
   136  	return formatTime(
   137  		formatStr,
   138  		time.Date(1980, time.January, 1, int(d.Hours())%24, int(d.Minutes())%60, int(d.Seconds())%60, int(d.Nanoseconds())%1e9, time.UTC),
   139  	)
   140  }
   141  
   142  // Type implements the Expression interface.
   143  func (f *TimeFormat) Type() sql.Type {
   144  	return types.Text
   145  }
   146  
   147  // CollationCoercibility implements the interface sql.CollationCoercible.
   148  func (*TimeFormat) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
   149  	return ctx.GetCollation(), 4
   150  }
   151  
   152  // IsNullable implements the Expression interface.
   153  func (f *TimeFormat) IsNullable() bool {
   154  	if types.IsNull(f.LeftChild) {
   155  		if types.IsNull(f.RightChild) {
   156  			return true
   157  		}
   158  		return f.RightChild.IsNullable()
   159  	}
   160  	return f.LeftChild.IsNullable()
   161  }
   162  
   163  func (f *TimeFormat) String() string {
   164  	return fmt.Sprintf("%s(%s,%s)", f.FunctionName(), f.LeftChild, f.RightChild)
   165  }
   166  
   167  // WithChildren implements the Expression interface.
   168  func (f *TimeFormat) WithChildren(children ...sql.Expression) (sql.Expression, error) {
   169  	if len(children) != 2 {
   170  		return nil, sql.ErrInvalidChildrenNumber.New(f, len(children), 2)
   171  	}
   172  	return NewTimeFormat(children[0], children[1]), nil
   173  }