Refact do

This commit is contained in:
Jinzhu 2013-11-16 13:28:22 +08:00
parent c3d2746912
commit ca6b074dc6
4 changed files with 17 additions and 7 deletions

11
do.go
View File

@ -5,6 +5,7 @@ import (
"database/sql/driver" "database/sql/driver"
"errors" "errors"
"fmt" "fmt"
"github.com/jinzhu/gorm/dialect"
"reflect" "reflect"
"regexp" "regexp"
"strconv" "strconv"
@ -37,6 +38,10 @@ func (s *Do) table() string {
return s.tableName return s.tableName
} }
func (s *Do) dialect() dialect.Dialect {
return s.db.parent.dialect
}
func (s *Do) err(err error) error { func (s *Do) err(err error) error {
if err != nil { if err != nil {
s.db.err(err) s.db.err(err)
@ -57,7 +62,7 @@ func (s *Do) setModel(value interface{}) *Do {
func (s *Do) addToVars(value interface{}) string { func (s *Do) addToVars(value interface{}) string {
s.sqlVars = append(s.sqlVars, value) s.sqlVars = append(s.sqlVars, value)
return fmt.Sprintf(s.db.dialect.BinVar(), len(s.sqlVars)) return fmt.Sprintf(s.dialect().BinVar(), len(s.sqlVars))
} }
func (s *Do) trace(t time.Time) { func (s *Do) trace(t time.Time) {
@ -97,7 +102,7 @@ func (s *Do) prepareCreateSql() {
s.table(), s.table(),
strings.Join(columns, ","), strings.Join(columns, ","),
strings.Join(sqls, ","), strings.Join(sqls, ","),
s.db.dialect.ReturningStr(s.model.primaryKeyDb()), s.dialect().ReturningStr(s.model.primaryKeyDb()),
) )
return return
} }
@ -173,7 +178,7 @@ func (s *Do) create() (i interface{}) {
var id interface{} var id interface{}
now := time.Now() now := time.Now()
if s.db.dialect.SupportLastInsertId() { if s.dialect().SupportLastInsertId() {
if sql_result, err := s.db.db.Exec(s.sql, s.sqlVars...); s.err(err) == nil { if sql_result, err := s.db.db.Exec(s.sql, s.sqlVars...); s.err(err) == nil {
id, err = sql_result.LastInsertId() id, err = sql_result.LastInsertId()
s.err(err) s.err(err)

View File

@ -61,9 +61,9 @@ func (f *Field) sqlTag() (str string) {
if len(typ) == 0 { if len(typ) == 0 {
if f.isPrimaryKey { if f.isPrimaryKey {
typ = f.model.do.db.dialect.PrimaryKeyTag(value, size) typ = f.model.do.dialect().PrimaryKeyTag(value, size)
} else { } else {
typ = f.model.do.db.dialect.SqlTag(value, size) typ = f.model.do.dialect().SqlTag(value, size)
} }
} }

View File

@ -147,7 +147,7 @@ func init() {
func TestSaveAndFind(t *testing.T) { func TestSaveAndFind(t *testing.T) {
name := "save_and_find" name := "save_and_find"
u := &User{Name: name, Age: 1} u := &User{Name: name, Age: 1}
db.Save(u) db.Debug().Save(u)
if u.Id == 0 { if u.Id == 0 {
t.Errorf("Should have ID after create record") t.Errorf("Should have ID after create record")
} }

View File

@ -6,7 +6,12 @@ import (
) )
func (s *DB) clone() *DB { func (s *DB) clone() *DB {
db := &DB{db: s.db, parent: s.parent, search: s.parent.search.clone()} db := &DB{db: s.db, parent: s.parent}
if s.parent.search == nil {
db.search = &search{}
} else {
db.search = s.parent.search.clone()
}
db.search.db = db db.search.db = db
return db return db
} }