From b25b2aa2133276497c923cf003b72eae092a93d5 Mon Sep 17 00:00:00 2001 From: Branislav Lazic Date: Fri, 20 Sep 2024 09:47:40 +0200 Subject: [PATCH 1/2] Add Postgres DATE_TRUNC function --- postgres/functions.go | 9 +++++++++ postgres/functions_test.go | 13 ++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/postgres/functions.go b/postgres/functions.go index 7b6d1e16..75a69258 100644 --- a/postgres/functions.go +++ b/postgres/functions.go @@ -332,6 +332,15 @@ var LOCALTIMESTAMP = jet.LOCALTIMESTAMP // NOW returns current date and time var NOW = jet.NOW +// DATE_TRUNC returns the truncated date and time using optional time zone +func DATE_TRUNC(field unit, source Expression, timezone ...string) TimestampExpression { + if len(timezone) > 0 { + return jet.NewTimestampFunc("DATE_TRUNC", jet.FixedLiteral(unitToString(field)), source, jet.FixedLiteral(timezone[0])) + } + + return jet.NewTimestampFunc("DATE_TRUNC", jet.FixedLiteral(unitToString(field)), source) +} + // --------------- Conditional Expressions Functions -------------// // COALESCE function returns the first of its arguments that is not null. diff --git a/postgres/functions_test.go b/postgres/functions_test.go index 4190f703..d0081b05 100644 --- a/postgres/functions_test.go +++ b/postgres/functions_test.go @@ -1,6 +1,8 @@ package postgres -import "testing" +import ( + "testing" +) func TestROW(t *testing.T) { assertSerialize(t, ROW(SELECT(Int(1))), `ROW(( @@ -10,3 +12,12 @@ func TestROW(t *testing.T) { SELECT $2 ), $3)`) } + +func TestDATE_TRUNC(t *testing.T) { + assertSerialize(t, DATE_TRUNC(YEAR, NOW()), "DATE_TRUNC('YEAR', NOW())") + assertSerialize( + t, + DATE_TRUNC(DAY, NOW().ADD(INTERVAL(1, HOUR)), "Australia/Sydney"), + "DATE_TRUNC('DAY', NOW() + INTERVAL '1 HOUR', 'Australia/Sydney')", + ) +} From dce5fd6552e9cd22c346b9aa83eabb7de3cbd518 Mon Sep 17 00:00:00 2001 From: Branislav Lazic Date: Mon, 23 Sep 2024 09:11:53 +0200 Subject: [PATCH 2/2] Add return type switching note --- postgres/functions.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/postgres/functions.go b/postgres/functions.go index 75a69258..7e71a960 100644 --- a/postgres/functions.go +++ b/postgres/functions.go @@ -332,7 +332,8 @@ var LOCALTIMESTAMP = jet.LOCALTIMESTAMP // NOW returns current date and time var NOW = jet.NOW -// DATE_TRUNC returns the truncated date and time using optional time zone +// DATE_TRUNC returns the truncated date and time using optional time zone. +// Use TimestampzExp if you need timestamp with time zone and IntervalExp if you need interval. func DATE_TRUNC(field unit, source Expression, timezone ...string) TimestampExpression { if len(timezone) > 0 { return jet.NewTimestampFunc("DATE_TRUNC", jet.FixedLiteral(unitToString(field)), source, jet.FixedLiteral(timezone[0]))