xorm/examples/conversion.go

82 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
2014-01-07 09:33:27 +00:00
"errors"
"fmt"
2014-01-25 02:31:07 +00:00
"os"
"xorm.io/xorm"
2014-01-07 09:33:27 +00:00
_ "github.com/mattn/go-sqlite3"
)
2017-01-09 01:52:23 +00:00
// Status describes a status
type Status struct {
2014-01-07 09:33:27 +00:00
Name string
Color string
}
2017-01-09 01:52:23 +00:00
// defines some statuses
var (
2017-01-09 01:52:23 +00:00
Registered = Status{"Registered", "white"}
Approved = Status{"Approved", "green"}
Removed = Status{"Removed", "red"}
Statuses = map[string]Status{
Registered.Name: Registered,
Approved.Name: Approved,
Removed.Name: Removed,
2014-01-07 09:33:27 +00:00
}
)
2017-01-09 01:56:02 +00:00
// FromDB implemented xorm.Conversion convent database data to self
func (s *Status) FromDB(bytes []byte) error {
2014-01-07 09:33:27 +00:00
if r, ok := Statuses[string(bytes)]; ok {
*s = r
return nil
}
2017-01-09 01:58:23 +00:00
return errors.New("no this data")
}
2017-01-09 01:56:02 +00:00
// ToDB implemented xorm.Conversion convent to database data
func (s *Status) ToDB() ([]byte, error) {
2014-01-07 09:33:27 +00:00
return []byte(s.Name), nil
}
2017-01-09 01:52:23 +00:00
// User describes a user
type User struct {
2014-01-07 09:33:27 +00:00
Id int64
Name string
Status Status `xorm:"varchar(40)"`
}
func main() {
2014-01-07 09:33:27 +00:00
f := "conversion.db"
os.Remove(f)
2014-01-25 02:31:07 +00:00
Orm, err := xorm.NewEngine("sqlite3", f)
2014-01-07 09:33:27 +00:00
if err != nil {
fmt.Println(err)
return
}
2016-03-16 15:05:25 +00:00
Orm.ShowSQL(true)
2014-01-07 09:33:27 +00:00
err = Orm.CreateTables(&User{})
if err != nil {
fmt.Println(err)
return
}
2017-01-09 01:52:23 +00:00
_, err = Orm.Insert(&User{1, "xlw", Registered})
2014-01-07 09:33:27 +00:00
if err != nil {
fmt.Println(err)
return
}
2014-01-07 09:33:27 +00:00
users := make([]User, 0)
err = Orm.Find(&users)
if err != nil {
fmt.Println(err)
return
}
2014-01-07 09:33:27 +00:00
fmt.Println(users)
}