Skip to content

Instantly share code, notes, and snippets.

@unknwon
Created June 16, 2014 14:25
Show Gist options
  • Save unknwon/a7c9162bce3f20d3bee6 to your computer and use it in GitHub Desktop.
Save unknwon/a7c9162bce3f20d3bee6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
)
var printFn = func(idx int, bean interface{}) error {
fmt.Printf("%d: %#v\n", idx, bean.(*Account))
return nil
}
func main() {
fmt.Println("Welcome bank of xorm!")
count, err := getAccountCount()
if err != nil {
log.Fatalf("Fail to get account count: %v", err)
}
fmt.Println("Account count:", count)
// Auto-create 10 accounts.
for i := count; i < 10; i++ {
if err = newAccount(fmt.Sprintf("joe%d", i), float64(i)*100); err != nil {
log.Fatalf("Fail to create account: %v", err)
}
}
// Iterative query.
fmt.Println("Query all columns:")
x.Iterate(new(Account), printFn)
// More flexible iteration.
a := new(Account)
rows, err := x.Rows(a)
if err != nil {
log.Fatalf("Fail to rows: %v", err)
}
defer rows.Close()
for rows.Next() {
if err = rows.Scan(a); err != nil {
log.Fatalf("Fail get row: %v", err)
}
fmt.Printf("%#v\n", a)
}
// Only query specified fields.
fmt.Println("\nOnly query name:")
x.Cols("name").Iterate(new(Account), printFn)
// Not query specified fields.
fmt.Println("\nQuery all but name:")
x.Omit("name").Iterate(new(Account), printFn)
// Results offset.
fmt.Println("\nOffest 2 and limit 3:")
x.Limit(3, 2).Iterate(new(Account), printFn)
// Test LRU cache.
getAccount(1)
getAccount(1)
}
package main
import (
"errors"
"log"
"os"
"github.com/go-xorm/xorm"
_ "github.com/mattn/go-sqlite3"
)
// Account.
type Account struct {
Id int64
Name string `xorm:"unique"`
Balance float64
Version int `xorm:"version"`
}
func (a *Account) BeforeInsert() {
log.Printf("before insert: %s", a.Name)
}
func (a *Account) AfterInsert() {
log.Printf("after insert: %s", a.Name)
}
// ORM engine.
var x *xorm.Engine
func init() {
var err error
x, err = xorm.NewEngine("sqlite3", "./bank.db")
if err != nil {
log.Fatalf("Fail to create engine: %v\n", err)
}
if err = x.Sync(new(Account)); err != nil {
log.Fatalf("Fail to sync database: %v\n", err)
}
// Record log.
f, err := os.Create("sql.log")
if err != nil {
log.Fatalf("Fail to create log file: %v\n", err)
return
}
x.Logger = xorm.NewSimpleLogger(f)
x.ShowSQL = true
// Setting default LRU cache.
cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
x.SetDefaultCacher(cacher)
}
func newAccount(name string, balance float64) error {
_, err := x.Insert(&Account{Name: name, Balance: balance})
return err
}
// Get account count.
func getAccountCount() (int64, error) {
return x.Count(new(Account))
}
func getAccount(id int64) (*Account, error) {
a := &Account{}
has, err := x.Id(id).Get(a)
if err != nil {
return nil, err
} else if !has {
return nil, errors.New("Account does not exist")
}
return a, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment