Overview
Models - Beego ORM
Beego ORM is a powerful ORM framework written in Go. It is inspired by Django ORM and SQLAlchemy.
This framework is still under development so compatibility is not guaranteed.
Supported Database:
- MySQL:github.com/go-sql-driver/mysql
- PostgreSQL:github.com/lib/pq
- Sqlite3:github.com/mattn/go-sqlite3
All of the database drivers have passed the tests, but we still need your feedback and bug reports.
ORM Features:
- Supports all the types in Go.
- CRUD is easy to use.
- Auto join connection tables.
- Compatible with crossing database queries.
- Supports raw SQL query and mapping.
- Strict and well-covered test cases ensure the ORM’s stability.
You can learn more in this documentation.
Install ORM:
go get github.com/beego/beego/v2/client/orm
Quickstart
Demo
package main
import (
"fmt"
"github.com/beego/beego/v2/client/orm"
_ "github.com/go-sql-driver/mysql" // import your required driver
)
// Model Struct
type User struct {
Id int
Name string `orm:"size(100)"`
}
func init() {
// register model
orm.RegisterModel(new(User))
// set default database
orm.RegisterDataBase("default", "mysql", "root:root@/my_db?charset=utf8")
}
func main() {
o := orm.NewOrm()
user := User{Name: "slene"}
// insert
id, err := o.Insert(&user)
fmt.Printf("ID: %d, ERR: %v\n", id, err)
// update
user.Name = "astaxie"
num, err := o.Update(&user)
fmt.Printf("NUM: %d, ERR: %v\n", num, err)
// read one
u := User{Id: user.Id}
err = o.Read(&u)
fmt.Printf("ERR: %v\n", err)
// delete
num, err = o.Delete(&u)
fmt.Printf("NUM: %d, ERR: %v\n", num, err)
}
Relation Query
type Post struct {
Id int `orm:"auto"`
Title string `orm:"size(100)"`
User *User `orm:"rel(fk)"`
}
var posts []*Post
qs := o.QueryTable("post")
num, err := qs.Filter("User__Name", "slene").All(&posts)
Raw SQL query
You can always use raw SQL to query and mapping.
var maps []Params
num, err := o.Raw("SELECT id FROM user WHERE name = ?", "slene").Values(&maps)
if num > 0 {
fmt.Println(maps[0]["id"])
}
Transactions
o.Begin()
...
user := User{Name: "slene"}
id, err := o.Insert(&user)
if err == nil {
o.Commit()
} else {
o.Rollback()
}
Debugging query log
In development environment, you can enable debug mode by:
func main() {
orm.Debug = true
...
It will output every query statement including execution, preparation and transactions.
For example:
[ORM] - 2013-08-09 13:18:16 - [Queries/default] - [ db.Exec / 0.4ms] - [INSERT INTO `user` (`name`) VALUES (?)] - `slene`
...
Notes: It is not recommended to enable debug mode in a production environment.