From 0b5404da32b5c77308fa2eee6a693e98e67ae470 Mon Sep 17 00:00:00 2001 From: Leandro Franciscato Date: Mon, 17 Oct 2022 12:02:38 -0300 Subject: [PATCH] adding function file --- clause/function.go | 42 ++++++++++++++++++++++++++++++++++++++++++ tests/query_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 clause/function.go diff --git a/clause/function.go b/clause/function.go new file mode 100644 index 00000000..ae39f743 --- /dev/null +++ b/clause/function.go @@ -0,0 +1,42 @@ +package clause + +import ( + "fmt" + "log" +) + +type Database string + +var ( + Postgres Database = "postgres" + Sqlite Database = "sqlite" +) + +type Function interface { + GetSql() string +} + +type FuncDateWithoutTime struct { + Database Database + Field string + Alias string + SQL string +} + +func (fnc FuncDateWithoutTime) GetSql() string { + alias := fnc.Alias + if fnc.Alias == "" { + alias = fnc.Field + } + switch fnc.Database { + case Postgres: + fnc.SQL = fmt.Sprintf(" to_char(%s, %s) as %s", fnc.Field, "'YYYY-MM-DD'", alias) + case Sqlite: + fnc.SQL = fmt.Sprintf(" strftime(%s, %s) as %s", "'%Y-%m-%d' ", fnc.Field, alias) + default: + log.Print("database not implemented yet for this function") + return "" + } + + return fnc.SQL +} diff --git a/tests/query_test.go b/tests/query_test.go index eccf0133..eb281df9 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -1359,3 +1359,32 @@ func TestQueryResetNullValue(t *testing.T) { AssertEqual(t, q1, qs[0]) AssertEqual(t, q2, qs[1]) } + +func TestFuncDateWihtoutTimeSQLITE(t *testing.T) { + users := []User{ + *GetUser("find", Config{}), + *GetUser("find", Config{}), + *GetUser("find", Config{}), + } + + if err := DB.Create(&users).Error; err != nil { + t.Fatalf("errors happened when create users: %v", err) + } + + t.Run("First with Function", func(t *testing.T) { + var first struct { + Birthday string + Name string + } + var fn clause.FuncDateWithoutTime = clause.FuncDateWithoutTime{Database: "sqlite", Field: "birthday"} + var sql string = fn.GetSql() + if err := DB.Model(&User{}).Select([]string{sql, "name"}).Where("name = ?", "find").First(&first).Error; err != nil { + t.Errorf("errors happened when query first: %v", err) + } else { + now := time.Now().Format("2006-01-02") + AssertEqual(t, &first.Birthday, now) + AssertEqual(t, &first.Name, "find") + + } + }) +}