orm

package module
v0.0.0-...-d60461c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2016 License: MIT Imports: 7 Imported by: 0

README

Golang ORM

ORM library for Go Golang

Import

import "github.com/dotcoo/orm"

Environment

Database
DROP TABLE IF EXISTS test_user;
CREATE TABLE test_user (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(16) CHARACTER SET ascii NOT NULL,
  password varchar(32) CHARACTER SET ascii NOT NULL,
  reg_time int(11) NOT NULL,
  reg_ip int(11) NOT NULL,
  update_time int(11) NOT NULL,
  update_ip int(11) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY username_UNIQUE (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS test_blog;
CREATE TABLE test_blog (
  id int(11) NOT NULL AUTO_INCREMENT,
  user_id int(11) NOT NULL,
  title varchar(45) NOT NULL,
  content text NOT NULL,
  add_time int(11) NOT NULL,
  update_time int(11) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Models

type User struct {
	ID         int `orm:"pk"`
	Username   string
	Password   string
	RegTime    int `orm:"created"`
	RegIP      uint32
	UpdateTime int `orm:"updated"`
	UpdateIP   uint32
	OtherField string `orm:"-"`
}

type Blog struct {
	ID         int `orm:"pk"`
	UserID     int
	Title      string
	Content    string
	AddTime    int `orm:"created"`
	UpdateTime int `orm:"updated"`
}

Initialization

SetDB
db, err := sql.Open("mysql", "root:123456@/mingo?charset=utf8")
if err != nil {
	panic(err)
}
orm.SetDB(db)
SetPrefix
orm.SetPrefix("test_")
Variables
var user *User
var users []User
var users_map map[int]User
var result sql.Result
var ok bool
var sq *orm.SQL
var n int

CRUD

Create
user = new(User)
user.Username = "dotcoo"
user.Password = "123456"

result = orm.Add(user)
// result = orm.Add(user, "id", "username")

log.Println(user.ID)
log.Println(result.LastInsertId())
Read/Retrieve
user = new(User)
user.ID = 1

ok = orm.Get(user)
// ok = orm.Get(user, "id", "username")

if ok {
	log.Println(user)
} else {
	log.Println("user not find")
}
GetBy
user = new(User)
user.Username = "dotcoo"
ok = orm.GetBy(user, "username")
// ok = orm.GetBy(user, "id", "username")

if ok {
	log.Println(user)
} else {
	log.Println("user not find")
}
Update
user = new(User)
user.ID = 1
user.Password = "654321"

result = orm.Up(user, "password")
// result = orm.Up(user, "id", "username")

log.Println(result.RowsAffected())
Delete
user = new(User)
user.ID = 1

result = orm.Del(user)

log.Println(result.RowsAffected())
Save
// insert
user = new(User)
user.ID = 0
user.Username = "dotcoo2"
user.Password = "123456"

result = orm.Save(user)
// result = orm.Save(user, "id", "username")

log.Println(result.LastInsertId())
log.Println(result.RowsAffected())

// update
user = new(User)
user.ID = 2
user.Username = "dotcoo2"
user.Password = "654321"

result = orm.Save(user, "username, password")

log.Println(result.LastInsertId())
log.Println(result.RowsAffected())

SQL CRUD

Insert
user = new(User)
user.ID = 1
user.Username = "dotcoo"
user.Password = "123456"

result = orm.Insert(user, "id, username, password")
// result = orm.Insert(user, "id", "username", "password")

log.Println(result.LastInsertId())
Select Model
sq = orm.NewSQL().Where("username = ?", "dotcoo")

user = new(User)

ok = orm.Select(sq, user)
// ok = orm.Select(sq, user, "id", "username", "password")

if ok {
	log.Println(user)
} else {
	log.Println("user not find")
}
Select Models
Slice
sq = orm.NewSQL().Where("username like ?", "dotcoo%")

users = make([]User, 0, 10)

ok = orm.Select(sq, &users)
// ok = orm.Select(sq, &users, "id", "username", "password")

log.Println(users)
Map
sq = orm.NewSQL().Where("username like ?", "dotcoo%")

users_map = make(map[int]User)

ok = orm.Select(sq, &users_map)
// ok = orm.Select(sq, &users_map, "id", "username", "password")

log.Println(users_map)
Count
n = orm.Count(sq)

log.Println(n)
Select Row
sq = orm.NewSQL("user").Columns("count(*)", "sum(id)", "avg(id)")

var count, sum int
var avg float64

ok = orm.SelectVal(sq, &count, &sum, &avg)

log.Println(count, sum, avg)
Update
sq = orm.NewSQL().Where("username like ?", "dotcoo%")

user = new(User)
user.Password = "123321"

result = orm.Update(sq, user, "password")
// result = orm.Update(sq, user) // Error
// result = orm.Update(sq, user, "*") // Correct

log.Println(result.RowsAffected())
Delete
sq = orm.NewSQL().Where("username like ?", "dotcoo%")

user = new(User)

result = orm.Delete(sq, user)

log.Println(result.RowsAffected())

SQL

Where
orm.NewSQL("user").Where("username = ?", "dotcoo").ToSelect()
// SELECT * FROM `test_user` WHERE username = ? [dotcoo]
Where OR
orm.NewSQL("user").Where("(username = ?", "dotcoo").Where(" OR username = ?)", "dotcoo2").ToSelect()
// SELECT * FROM `test_user` WHERE (username = ? OR username = ?) [dotcoo dotcoo2]
Columns and Table
orm.NewSQL().Columns("id", "username").From("user").Where("username = ?", "dotcoo").ToSelect()
// SELECT id, username FROM `test_user` WHERE username = ? [dotcoo]
Group
orm.NewSQL("user").Group("username").Having("id > ?", 100).ToSelect()
// SELECT * FROM `test_user` GROUP BY username HAVING id > ? [100]
Order
orm.NewSQL("user").Group("username desc, id asc").ToSelect()
// SELECT * FROM `test_user` GROUP BY username desc, id asc []
Limit Offset
orm.NewSQL("user").Limit(10).Offset(30).ToSelect()
// SELECT * FROM `test_user` LIMIT 10 OFFSET 30 []
Join
orm.NewSQL().From("blog AS b").Join("user AS u", "b.user_id = u.id").ToSelect()
SELECT * FROM `test_blog` AS `b` LEFT JOIN `test_user` AS `u` ON b.user_id = u.id []
Update
orm.NewSQL("user").Set("password", "123123").Set("age", 28).Where("id = ?", 1).ToUpdate()
// UPDATE `test_user` SET `password` = ?, `age` = ? WHERE id = ? [123123 28 1]
Delete
orm.NewSQL("user").Where("id = ?", 1).ToDelete()
// DELETE FROM `test_user` WHERE id = ? [1]
Plus
orm.NewSQL("user").Plus("age", 1).Where("id = ?", 1).ToUpdate()
// UPDATE `test_user` SET `age` = `age` + ? WHERE id = ? [1 1]
Incr
orm.NewSQL("user").Incr("age", 1).Where("id = ?", 1).ToUpdate()
// UPDATE `test_user` SET `age` = last_insert_id(`age` + ?) WHERE id = ? [1 1]

Custom SQL

Exec
result = orm.Exec("delete from test_user where id < ?", 10)
Query
rows := orm.Query("select * from test_user where id < ?", 10)
QueryRow
row := orm.Query("select * from test_user where id = ?", 10)

Other Method

BatchInsert
users = []User{
	{Username: "dotcoo3", Password: "123456", RegTime: 100},
	{Username: "dotcoo4", Password: "123456", RegTime: 101},
}
orm.BatchInsert(&users, "username, password, reg_time")
BatchReplace
users = []User{
	{ID: 3, Username: "dotcoo3", Password: "654321"},
	{ID: 4, Username: "dotcoo4", Password: "654321"},
}
orm.BatchReplace(&users, "id, username, password")
ForeignKey
blogs := []Blog{
	{ID: 1, Title: "blog title 1", UserID: 3},
	{ID: 2, Title: "blog title 2", UserID: 4},
	{ID: 3, Title: "blog title 3", UserID: 3},
}

users_map = make(map[int]User)

orm.ForeignKey(&blogs, "user_id", &users_map, "id")
// orm.ForeignKey(&blogs, "user_id", &users_map, "id", "id", "username", "password")

for _, b := range blogs {
	log.Println(b.ID, b.Title, users_map[b.UserID].Username)
}

Transaction

o := orm.DefaultORM

otx := o.Begin()

sq = otx.NewSQL().Where("id = ?", 3).ForUpdate()
user = new(User)
ok = otx.Select(sq, user)

if !ok {
	otx.Rollback()
	log.Println("Rollback")
} else {
	user.RegTime++
	otx.Up(user, "reg_time")

	otx.Commit()
	log.Println("Commit")
}

ModelInfo

m := orm.DefaultORM.Manager()

user = new(User)

mi := m.Get(reflect.ValueOf(user).Elem().Type())

if mi == nil {
	// if not exist, modify table name
	mi = orm.NewModelInfo(user, "prefix_", "users")
} else {
	// if exist, modify table name
	mi.Table = "prefix_users"
}

m.Set(mi)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Column2Field map[string]string = map[string]string{"id": "ID", "ip": "IP"}

Functions

func Add

func Add(model interface{}, columns ...string) sql.Result

func BatchInsert

func BatchInsert(models interface{}, columns ...string)

func BatchReplace

func BatchReplace(models interface{}, columns ...string)

func Commit

func Commit()

func Count

func Count(s *SQL) int

func Del

func Del(model interface{}) sql.Result

func Delete

func Delete(s *SQL, model interface{}) sql.Result

func Exec

func Exec(query string, args ...interface{}) sql.Result

func ForeignKey

func ForeignKey(sources interface{}, fk_column string, models interface{}, pk_column string, columns ...string)

func Get

func Get(model interface{}, columns ...string) bool

func GetBy

func GetBy(model interface{}, columns ...string) bool

func Insert

func Insert(model interface{}, columns ...string) sql.Result

func Query

func Query(query string, args ...interface{}) *sql.Rows

func QueryRow

func QueryRow(query string, args ...interface{}) *sql.Row

func Replace

func Replace(model interface{}, columns ...string) sql.Result

func Rollback

func Rollback()

func Save

func Save(model interface{}, columns ...string) sql.Result

func Select

func Select(s *SQL, model interface{}, columns ...string) bool

func SelectVal

func SelectVal(s *SQL, vals ...interface{}) bool

func SetDB

func SetDB(db *sql.DB)

func SetPrefix

func SetPrefix(prefix string)

func Up

func Up(model interface{}, columns ...string) sql.Result

func Update

func Update(s *SQL, model interface{}, columns ...string) sql.Result

Types

type ModelField

type ModelField struct {
	Field   string
	Column  string
	PK      bool
	Kind    reflect.Kind
	Created bool
	Updated bool
}

type ModelInfo

type ModelInfo struct {
	Value reflect.Value
	Type  reflect.Type

	Map       bool
	Slice     bool
	KeyPtr    bool
	KeyType   reflect.Type
	ValPtr    bool
	ValType   reflect.Type
	ModelType reflect.Type

	Table         string
	PK            *ModelField
	Columns       []*ModelField
	Fields        []*ModelField
	Column2Field  map[string]*ModelField
	Field2Column  map[string]*ModelField
	ColumnNames   []string
	FieldNames    []string
	FieldsCreated []string
	FieldsUpdated []string
}

func NewModelInfo

func NewModelInfo(model interface{}, prefix, table string) *ModelInfo

func (*ModelInfo) Column

func (mi *ModelInfo) Column(field string) *ModelField

func (*ModelInfo) Field

func (mi *ModelInfo) Field(column string) *ModelField

type ModelInfoManager

type ModelInfoManager struct {
	// contains filtered or unexported fields
}
var DefaultModelInfoManager *ModelInfoManager = NewModelInfoManager()

func NewModelInfoManager

func NewModelInfoManager() *ModelInfoManager

func (*ModelInfoManager) Get

func (*ModelInfoManager) Set

func (m *ModelInfoManager) Set(mi *ModelInfo)

func (*ModelInfoManager) SetPrefix

func (m *ModelInfoManager) SetPrefix(prefix string)

func (*ModelInfoManager) TableOf

func (m *ModelInfoManager) TableOf(table string) *ModelInfo

func (*ModelInfoManager) ValueOf

func (m *ModelInfoManager) ValueOf(model interface{}) (*ModelInfo, reflect.Value)

type ORM

type ORM struct {
	BatchRow int
	// contains filtered or unexported fields
}
var DefaultORM *ORM = NewORM(nil)

func Begin

func Begin() *ORM

func NewORM

func NewORM(db *sql.DB) *ORM

func (*ORM) Add

func (o *ORM) Add(model interface{}, columns ...string) sql.Result

func (*ORM) BatchInsert

func (o *ORM) BatchInsert(models interface{}, columns ...string)

func (*ORM) BatchReplace

func (o *ORM) BatchReplace(models interface{}, columns ...string)

func (*ORM) Begin

func (o *ORM) Begin() *ORM

func (*ORM) Commit

func (o *ORM) Commit()

func (*ORM) Count

func (o *ORM) Count(s *SQL) int

func (*ORM) Del

func (o *ORM) Del(model interface{}) sql.Result

func (*ORM) Delete

func (o *ORM) Delete(s *SQL, model interface{}) sql.Result

func (*ORM) Exec

func (o *ORM) Exec(query string, args ...interface{}) sql.Result

func (*ORM) ForeignKey

func (o *ORM) ForeignKey(sources interface{}, fk_column string, models interface{}, pk_column string, columns ...string)

func (*ORM) Get

func (o *ORM) Get(model interface{}, columns ...string) bool

func (*ORM) GetBy

func (o *ORM) GetBy(model interface{}, columns ...string) bool

func (*ORM) Insert

func (o *ORM) Insert(model interface{}, columns ...string) sql.Result

func (*ORM) Manager

func (o *ORM) Manager() *ModelInfoManager

func (*ORM) NewManager

func (o *ORM) NewManager()

func (*ORM) NewSQL

func (o *ORM) NewSQL() *SQL

func (*ORM) Query

func (o *ORM) Query(query string, args ...interface{}) *sql.Rows

func (*ORM) QueryRow

func (o *ORM) QueryRow(query string, args ...interface{}) *sql.Row

func (*ORM) RawAdd

func (o *ORM) RawAdd(model interface{}, columns ...string) (sql.Result, error)

func (*ORM) RawBatchInsert

func (o *ORM) RawBatchInsert(models interface{}, columns ...string) error

func (*ORM) RawBatchReplace

func (o *ORM) RawBatchReplace(models interface{}, columns ...string) error

func (*ORM) RawBegin

func (o *ORM) RawBegin() (*ORM, error)

func (*ORM) RawCommit

func (o *ORM) RawCommit() error

func (*ORM) RawCount

func (o *ORM) RawCount(s *SQL) (count int, err error)

func (*ORM) RawDel

func (o *ORM) RawDel(model interface{}) (sql.Result, error)

func (*ORM) RawDelete

func (o *ORM) RawDelete(s *SQL, model interface{}) (sql.Result, error)

func (*ORM) RawExec

func (o *ORM) RawExec(query string, args ...interface{}) (sql.Result, error)

func (*ORM) RawForeignKey

func (o *ORM) RawForeignKey(sources interface{}, fk_column string, models interface{}, pk_column string, columns ...string) error

func (*ORM) RawGet

func (o *ORM) RawGet(model interface{}, columns ...string) (bool, error)

func (*ORM) RawGetBy

func (o *ORM) RawGetBy(model interface{}, cols_nil_columns ...string) (bool, error)

func (*ORM) RawInsert

func (o *ORM) RawInsert(model interface{}, columns ...string) (sql.Result, error)

func (*ORM) RawQuery

func (o *ORM) RawQuery(query string, args ...interface{}) (*sql.Rows, error)

func (*ORM) RawQueryRow

func (o *ORM) RawQueryRow(query string, args ...interface{}) (*sql.Row, error)

func (*ORM) RawReplace

func (o *ORM) RawReplace(model interface{}, columns ...string) (sql.Result, error)

func (*ORM) RawRollback

func (o *ORM) RawRollback() error

func (*ORM) RawSave

func (o *ORM) RawSave(model interface{}, columns ...string) (sql.Result, error)

func (*ORM) RawSelect

func (o *ORM) RawSelect(s *SQL, model interface{}, columns ...string) (bool, error)

func (*ORM) RawSelectVal

func (o *ORM) RawSelectVal(s *SQL, vals ...interface{}) (bool, error)

func (*ORM) RawUp

func (o *ORM) RawUp(model interface{}, columns ...string) (sql.Result, error)

func (*ORM) RawUpdate

func (o *ORM) RawUpdate(s *SQL, model interface{}, columns ...string) (sql.Result, error)

func (*ORM) Replace

func (o *ORM) Replace(model interface{}, columns ...string) sql.Result

func (*ORM) Rollback

func (o *ORM) Rollback()

func (*ORM) Save

func (o *ORM) Save(model interface{}, columns ...string) sql.Result

func (*ORM) Select

func (o *ORM) Select(s *SQL, model interface{}, columns ...string) bool

func (*ORM) SelectVal

func (o *ORM) SelectVal(s *SQL, vals ...interface{}) bool

func (*ORM) SetDB

func (o *ORM) SetDB(db *sql.DB)

func (*ORM) SetPrefix

func (o *ORM) SetPrefix(prefix string)

func (*ORM) Up

func (o *ORM) Up(model interface{}, columns ...string) sql.Result

func (*ORM) Update

func (o *ORM) Update(s *SQL, model interface{}, columns ...string) sql.Result

type SQL

type SQL struct {
	// contains filtered or unexported fields
}

func NewSQL

func NewSQL() *SQL

func (*SQL) CalcFoundRows

func (s *SQL) CalcFoundRows() *SQL

func (*SQL) Columns

func (s *SQL) Columns(columns ...string) *SQL

func (*SQL) Count

func (s *SQL) Count() int

func (*SQL) Delete

func (s *SQL) Delete(model interface{}) sql.Result

func (*SQL) ForUpdate

func (s *SQL) ForUpdate() *SQL

func (*SQL) From

func (s *SQL) From(table string) *SQL

func (*SQL) Group

func (s *SQL) Group(groups ...string) *SQL

func (*SQL) Having

func (s *SQL) Having(having string, args ...interface{}) *SQL

func (*SQL) Incr

func (s *SQL) Incr(col string, val int) *SQL

func (*SQL) Join

func (s *SQL) Join(table, cond string) *SQL

func (*SQL) Keywords

func (s *SQL) Keywords(keywords ...string) *SQL

func (*SQL) Limit

func (s *SQL) Limit(limit int) *SQL

func (*SQL) LockInShareMode

func (s *SQL) LockInShareMode() *SQL

func (*SQL) NewCount

func (s *SQL) NewCount() *SQL

func (*SQL) Offset

func (s *SQL) Offset(offset int) *SQL

func (*SQL) Order

func (s *SQL) Order(orders ...string) *SQL

func (*SQL) Page

func (s *SQL) Page(page, pagesize int) *SQL

func (*SQL) Plus

func (s *SQL) Plus(col string, val int) *SQL

func (*SQL) RawCount

func (s *SQL) RawCount() (int, error)

func (*SQL) RawDelete

func (s *SQL) RawDelete(model interface{}) (sql.Result, error)

func (*SQL) RawSelect

func (s *SQL) RawSelect(model interface{}, columns ...string) (bool, error)

func (*SQL) RawSelectVal

func (s *SQL) RawSelectVal(vals ...interface{}) (bool, error)

func (*SQL) RawUpdate

func (s *SQL) RawUpdate(model interface{}, columns ...string) (sql.Result, error)

func (*SQL) Reset

func (s *SQL) Reset() *SQL

func (*SQL) Select

func (s *SQL) Select(model interface{}, columns ...string) bool

func (*SQL) SelectCount

func (s *SQL) SelectCount(model interface{}, columns ...string) (bool, int)

func (*SQL) SelectVal

func (s *SQL) SelectVal(vals ...interface{}) bool

func (*SQL) Set

func (s *SQL) Set(col string, val interface{}) *SQL

func (*SQL) SetMap

func (s *SQL) SetMap(data map[string]interface{}) *SQL

func (*SQL) ToDelete

func (s *SQL) ToDelete() (string, []interface{})

func (*SQL) ToInsert

func (s *SQL) ToInsert() (string, []interface{})

func (*SQL) ToReplace

func (s *SQL) ToReplace() (string, []interface{})

func (*SQL) ToSelect

func (s *SQL) ToSelect() (string, []interface{})

func (*SQL) ToUpdate

func (s *SQL) ToUpdate() (string, []interface{})

func (*SQL) Update

func (s *SQL) Update(model interface{}, columns ...string) sql.Result

func (*SQL) Where

func (s *SQL) Where(where string, args ...interface{}) *SQL

func (*SQL) WhereIn

func (s *SQL) WhereIn(where string, args ...interface{}) *SQL

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL