Add support for EXTRACT time/date function.

This commit is contained in:
go-jet 2022-05-06 11:54:44 +02:00
parent bc776f947b
commit 2101088d0e
15 changed files with 222 additions and 14 deletions

View file

@ -1,6 +1,8 @@
package postgres
import "github.com/go-jet/jet/v2/internal/jet"
import (
"github.com/go-jet/jet/v2/internal/jet"
)
// This functions can be used, instead of its method counterparts, to have a better indentation of a complex condition
// in the Go code and in the generated SQL.
@ -279,6 +281,26 @@ var TO_TIMESTAMP = jet.TO_TIMESTAMP
//----------------- Date/Time Functions and Operators ------------//
// Additional time unit types for EXTRACT function
const (
DOW unit = MILLENNIUM + 1 + iota
DOY
EPOCH
ISODOW
ISOYEAR
JULIAN
QUARTER
TIMEZONE
TIMEZONE_HOUR
TIMEZONE_MINUTE
)
// EXTRACT function retrieves subfields such as year or hour from date/time values
// EXTRACT(DAY, User.CreatedAt)
func EXTRACT(field unit, from Expression) FloatExpression {
return FloatExp(jet.EXTRACT(unitToString(field), from))
}
// CURRENT_DATE returns current date
var CURRENT_DATE = jet.CURRENT_DATE

View file

@ -10,10 +10,11 @@ import (
)
type quantityAndUnit = float64
type unit = float64
// Interval unit types
const (
YEAR quantityAndUnit = 123456789 + iota
YEAR unit = 123456789 + iota
MONTH
WEEK
DAY
@ -119,7 +120,7 @@ type intervalExpression struct {
}
// INTERVAL creates new interval expression from the list of quantity-unit pairs.
// For example: INTERVAL(1, DAY, 3, MINUTE)
// INTERVAL(1, DAY, 3, MINUTE)
func INTERVAL(quantityAndUnit ...quantityAndUnit) IntervalExpression {
quantityAndUnitLen := len(quantityAndUnit)
if quantityAndUnitLen == 0 || quantityAndUnitLen%2 != 0 {
@ -208,6 +209,27 @@ func unitToString(unit quantityAndUnit) string {
return "CENTURY"
case MILLENNIUM:
return "MILLENNIUM"
// additional field units for EXTRACT function
case DOW:
return "DOW"
case DOY:
return "DOY"
case EPOCH:
return "EPOCH"
case ISODOW:
return "ISODOW"
case ISOYEAR:
return "ISOYEAR"
case JULIAN:
return "JULIAN"
case QUARTER:
return "QUARTER"
case TIMEZONE:
return "TIMEZONE"
case TIMEZONE_HOUR:
return "TIMEZONE_HOUR"
case TIMEZONE_MINUTE:
return "TIMEZONE_MINUTE"
default:
panic("jet: invalid INTERVAL unit type")
}