Skip to content

Commit

Permalink
Merge pull request #389 from BranislavLazic/add-pg-date-trunc
Browse files Browse the repository at this point in the history
Add Postgres DATE_TRUNC function
  • Loading branch information
go-jet committed Sep 23, 2024
2 parents b835e25 + dce5fd6 commit 1c42ff1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
10 changes: 10 additions & 0 deletions postgres/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,16 @@ 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.
// 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]))
}

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.
Expand Down
13 changes: 12 additions & 1 deletion postgres/functions_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package postgres

import "testing"
import (
"testing"
)

func TestROW(t *testing.T) {
assertSerialize(t, ROW(SELECT(Int(1))), `ROW((
Expand All @@ -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')",
)
}

0 comments on commit 1c42ff1

Please sign in to comment.