Add postgres interval cast.

This commit is contained in:
go-jet 2019-12-07 13:52:51 +01:00
parent 4a3579e7f9
commit a2fbc4f53a
4 changed files with 56 additions and 20 deletions

View file

@ -2,8 +2,9 @@ package postgres
import (
"fmt"
"github.com/go-jet/jet/internal/jet"
"strconv"
"github.com/go-jet/jet/internal/jet"
)
type cast interface {
@ -32,7 +33,7 @@ type cast interface {
AS_TIME() TimeExpression
// Cast expression AS text type
AS_TEXT() StringExpression
// Cast expression AS bytea type
AS_BYTEA() StringExpression
// Cast expression AS time with time timezone type
AS_TIMEZ() TimezExpression
@ -40,6 +41,8 @@ type cast interface {
AS_TIMESTAMP() TimestampExpression
// Cast expression AS timestamp with timezone type
AS_TIMESTAMPZ() TimestampzExpression
// Cast expression AS interval type
AS_INTERVAL() IntervalExpression
}
type castImpl struct {
@ -151,3 +154,8 @@ func (b *castImpl) AS_TIMESTAMP() TimestampExpression {
func (b *castImpl) AS_TIMESTAMPZ() TimestampzExpression {
return TimestampzExp(b.AS("timestamp with time zone"))
}
// Cast expression AS interval type
func (b *castImpl) AS_INTERVAL() IntervalExpression {
return IntervalExp(b.AS("interval"))
}

View file

@ -62,3 +62,10 @@ func TestExpressionCAST_AS_TIMESTAMP(t *testing.T) {
func TestExpressionCAST_AS_TIMESTAMPZ(t *testing.T) {
assertSerialize(t, CAST(table2Col3).AS_TIMESTAMPZ(), "table2.col3::timestamp with time zone")
}
func TestExpressionCAST_AS_INTERVAL(t *testing.T) {
assertSerialize(t, CAST(table2ColTimez).AS_INTERVAL(), "table2.col_timez::interval")
assertSerialize(t, CAST(Time(20, 11, 10)).AS_INTERVAL(), "$1::time without time zone::interval", "20:11:10")
assertSerialize(t, table2ColDate.SUB(CAST(Time(20, 11, 10)).AS_INTERVAL()),
"(table2.col_date - $1::time without time zone::interval)", "20:11:10")
}

View file

@ -129,3 +129,22 @@ func unitToString(unit quantityAndUnit) string {
panic("jet: invalid INTERVAL unit type")
}
}
//---------------------------------------------------//
type intervalWrapper struct {
jet.IsInterval
Expression
}
func newIntervalExpressionWrap(expression Expression) IntervalExpression {
intervalWrap := intervalWrapper{Expression: expression}
return &intervalWrap
}
// IntervalExp is interval expression wrapper around arbitrary expression.
// Allows go compiler to see any expression as interval expression.
// Does not add sql cast to generated sql builder output.
func IntervalExp(expression Expression) IntervalExpression {
return newIntervalExpressionWrap(expression)
}