Fix error for chain query

This commit is contained in:
Jinzhu 2013-10-27 16:47:02 +08:00
parent 2600e1099e
commit f9658716e4
3 changed files with 19 additions and 7 deletions

View File

@ -3,8 +3,9 @@
Yet Another ORM library for Go, aims for developer friendly Yet Another ORM library for Go, aims for developer friendly
## TODO ## TODO
* Soft Delete
* Better First method (First(&user, primary_key, where conditions)) * Better First method (First(&user, primary_key, where conditions))
* Update, Updates
* Soft Delete
* Even more complex where query (with map or struct) * Even more complex where query (with map or struct)
* FindOrInitialize / FindOrCreate * FindOrInitialize / FindOrCreate
* SQL Log * SQL Log

18
orm.go
View File

@ -36,6 +36,12 @@ func (s *Orm) err(err error) {
} }
} }
func (s *Orm) Copy() *Orm {
c := *s
c.SqlVars = c.SqlVars[:0]
return &c
}
func (s *Orm) Model(model interface{}) *Orm { func (s *Orm) Model(model interface{}) *Orm {
s.model = s.toModel(model) s.model = s.toModel(model)
s.TableName = s.model.TableName() s.TableName = s.model.TableName()
@ -114,12 +120,12 @@ func (s *Orm) Save(value interface{}) *Orm {
} else { } else {
s.update(value) s.update(value)
} }
return s return s.Copy()
} }
func (s *Orm) Delete(value interface{}) *Orm { func (s *Orm) Delete(value interface{}) *Orm {
s.explain(value, "Delete").delete(value) s.explain(value, "Delete").delete(value)
return s return s.Copy()
} }
func (s *Orm) Update(column string, value string) *Orm { func (s *Orm) Update(column string, value string) *Orm {
@ -138,22 +144,22 @@ func (s *Orm) Exec(sql ...string) *Orm {
s.SqlResult, err = s.db.Exec(sql[0]) s.SqlResult, err = s.db.Exec(sql[0])
} }
s.err(err) s.err(err)
return s return s.Copy()
} }
func (s *Orm) First(out interface{}) *Orm { func (s *Orm) First(out interface{}) *Orm {
s.explain(out, "Query").query(out) s.explain(out, "Query").query(out)
return s return s.Copy()
} }
func (s *Orm) Find(out interface{}) *Orm { func (s *Orm) Find(out interface{}) *Orm {
s.explain(out, "Query").query(out) s.explain(out, "Query").query(out)
return s return s.Copy()
} }
func (s *Orm) Pluck(column string, value interface{}) (orm *Orm) { func (s *Orm) Pluck(column string, value interface{}) (orm *Orm) {
s.Select(column).explain(s.model.Data, "Query").pluck(value) s.Select(column).explain(s.model.Data, "Query").pluck(value)
return s return s.Copy()
} }
func (s *Orm) Or(querystring interface{}, args ...interface{}) *Orm { func (s *Orm) Or(querystring interface{}, args ...interface{}) *Orm {

View File

@ -61,6 +61,11 @@ func init() {
db.Save(&User{Name: "5", Age: 26, Birthday: t4}) db.Save(&User{Name: "5", Age: 26, Birthday: t4})
} }
func TestFirst(t *testing.T) {
var u1, u2 User
db.Where("name = ?", "3").Order("age desc").First(&u1).First(&u2)
}
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}