adding function file
This commit is contained in:
parent
2a788fb20c
commit
0b5404da32
42
clause/function.go
Normal file
42
clause/function.go
Normal file
@ -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
|
||||
}
|
@ -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")
|
||||
|
||||
}
|
||||
})
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user