Skip to content

Instantly share code, notes, and snippets.

@sgykfjsm
Created February 20, 2016 10:19
Show Gist options
  • Save sgykfjsm/3ac087aa18c90687fd63 to your computer and use it in GitHub Desktop.
Save sgykfjsm/3ac087aa18c90687fd63 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"time"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
ID int
Name string `orm:"size(100)"`
Profile *Profile `orm:"rel(one)"` // OneToOne relation
}
type Profile struct {
ID int
Age int16
User *User `orm:"reverse(one)"` // Reverse relationship
}
const (
dbAlias = "default"
mysqlUser = "root"
mysqlPassword = "root"
mysqlHost = "localhost"
mysqlPort = 3306
mysqlDatabase = "test"
mysqlCharset = "utf8"
)
var (
mysqlCon = fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=%s",
mysqlUser,
mysqlPassword,
mysqlHost,
mysqlPort,
mysqlDatabase,
mysqlCharset,
)
)
func init() {
// register driver
orm.RegisterDriver("mysql", orm.DRMySQL)
// register model
orm.RegisterModel(new(User), new(Profile))
// set timezone
orm.DefaultTimeLoc = time.UTC
// set default database
orm.RegisterDataBase(dbAlias, "mysql", mysqlCon)
}
func main() {
// Print SQL
orm.Debug = true
force := true // Drop table and re-create.
verbose := true // Print log
// generate Tables
if err := orm.RunSyncdb(dbAlias, force, verbose); err != nil {
log.Println(err)
}
o := orm.NewOrm()
o.Using("default")
profileA := new(Profile)
profileA.Age = 30
profileB := new(Profile)
profileB.Age = 40
profileC := new(Profile)
profileC.Age = 50
profiles := []*Profile{profileB, profileC}
user := new(User)
user.Profile = profileA
user.Name = "alpha"
var res int64
var err error
// Insert
if res, err = o.Insert(profileA); err != nil {
log.Println(err)
}
log.Printf("inserted: %d row", res)
if res, err = o.InsertMulti(10, profiles); err != nil {
log.Println(err)
}
log.Printf("inserted: %d row", res)
if res, err = o.Insert(user); err != nil {
log.Println(err)
}
log.Printf("inserted: %d row", res)
// Update
updateTarget := User{ID: 1}
if o.Read(&updateTarget) == nil {
updateTarget.Name = "ALPHA"
if num, err := o.Update(&updateTarget); err != nil {
log.Println(err)
} else {
log.Printf("updated %d rows", num)
}
}
// Read
readTarget := User{ID: 1}
err = o.Read(&readTarget)
if err == orm.ErrNoRows {
log.Println("No result found.")
} else if err == orm.ErrMissPK {
log.Println("No primary key found.")
} else {
log.Println(readTarget.ID, readTarget.Name)
}
// Raw Query
var params []orm.Params
num, err := o.Raw("SELECT * FROM profile WHERE age > ?", 30).Values(&params)
if err != nil {
log.Println(err)
}
log.Printf("selectd %d rows", num)
if num > 0 {
log.Printf("result %v", params)
}
}
drop table `user`
DROP TABLE IF EXISTS `user`
drop table `profile`
DROP TABLE IF EXISTS `profile`
create table `user`
-- --------------------------------------------------
-- Table Structure for `main.User`
-- --------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`i_d` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(100) NOT NULL DEFAULT '' ,
`profile_id` integer NOT NULL UNIQUE
) ENGINE=InnoDB;
create table `profile`
-- --------------------------------------------------
-- Table Structure for `main.Profile`
-- --------------------------------------------------
CREATE TABLE IF NOT EXISTS `profile` (
`i_d` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`age` smallint NOT NULL DEFAULT 0
) ENGINE=InnoDB;
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.Exec / 1.2ms] - [INSERT INTO `profile` (`age`) VALUES (?)] - `30`
2016/02/20 18:48:52 inserted: 1 row
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.Exec / 1.7ms] - [INSERT INTO `profile` (`age`) VALUES (?), (?)] - `40`, `50`
2016/02/20 18:48:52 inserted: 2 row
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.Exec / 1.7ms] - [INSERT INTO `user` (`name`, `profile_id`) VALUES (?, ?)] - `alpha`, `1`
2016/02/20 18:48:52 inserted: 1 row
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.QueryRow / 1.3ms] - [SELECT `i_d`, `name`, `profile_id` FROM `user` WHERE `i_d` = ?] - `1`
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.Exec / 2.2ms] - [UPDATE `user` SET `name` = ?, `profile_id` = ? WHERE `i_d` = ?] - `ALPHA`, `1`, `1`
2016/02/20 18:48:52 updated 1 rows
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.QueryRow / 0.7ms] - [SELECT `i_d`, `name`, `profile_id` FROM `user` WHERE `i_d` = ?] - `1`
2016/02/20 18:48:52 1 ALPHA
[ORM] - 2016-02-20 18:48:52 - [Queries/default] - [ OK / db.Query / 0.7ms] - [SELECT * FROM profile WHERE age > ?] - `30`
2016/02/20 18:48:52 selectd 2 rows
2016/02/20 18:48:52 result [map[i_d:2 age:40] map[i_d:3 age:50]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment