62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package orm
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
type SqliteDialect struct{}
|
|
|
|
func NewSqliteDialect() *SqliteDialect {
|
|
return &SqliteDialect{}
|
|
}
|
|
|
|
func convertType(f dbfield) string {
|
|
switch f.stype {
|
|
case "string", "*string":
|
|
return "text"
|
|
case "bool", "int", "*int", "time.Time", "*time.Time":
|
|
return "numeric"
|
|
case "[]byte":
|
|
return "blob"
|
|
}
|
|
return "text"
|
|
}
|
|
|
|
func defaultValue(f dbfield) string {
|
|
if f.dbname == "_date_created" {
|
|
return "current_timestamp"
|
|
}
|
|
switch f.stype {
|
|
case "string":
|
|
return "''"
|
|
case "bool", "int", "time.Time":
|
|
return "0"
|
|
}
|
|
return "''"
|
|
}
|
|
|
|
func (d *SqliteDialect) TableExists(db *sql.DB, tableName string) (bool, error) {
|
|
sql := "select name from sqlite_schema where type='table' and name=$1"
|
|
rows, err := db.Query(sql, tableName)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if rows.Next() {
|
|
rows.Close()
|
|
return true, nil
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
func (d *SqliteDialect) ColumnSpec(f dbfield) (string, error) {
|
|
if f.dbname == "id" {
|
|
return "id text not null primary key", nil
|
|
}
|
|
if strings.HasPrefix(f.stype, "*") || strings.HasPrefix(f.stype, "[]") {
|
|
return fmt.Sprintf("%s %s", f.dbname, convertType(f)), nil
|
|
}
|
|
return fmt.Sprintf("%s %s not null default %s", f.dbname, convertType(f), defaultValue(f)), nil
|
|
}
|