Add Debug Mode

This commit is contained in:
Jinzhu 2013-10-29 19:33:26 +08:00
parent 6ac0012879
commit 94bd2eb8d5
3 changed files with 25 additions and 3 deletions

View File

@ -12,6 +12,7 @@ import (
type Chain struct {
db *sql.DB
driver string
debug bool
value interface{}
Errors []error
@ -27,10 +28,20 @@ type Chain struct {
unscoped bool
}
func (s *Chain) msg(str string) {
if s.debug {
debug(str)
}
}
func (s *Chain) err(err error) error {
if err != nil {
s.Errors = append(s.Errors, err)
s.Error = err
if s.debug {
debug(err)
}
}
return err
}
@ -206,6 +217,11 @@ func (s *Chain) Table(name string) *Chain {
return s
}
func (s *Chain) Debug() *Chain {
s.debug = true
return s
}
func (s *Chain) validSql(str string) (result bool) {
result = regexp.MustCompile("^\\s*[\\w][\\w\\s,.]*[\\w]\\s*$").MatchString(str)
if !result {

View File

@ -48,6 +48,7 @@ func init() {
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
}
db.SetPool(10)
db.DebugMode = true
err = db.Exec("drop table users;").Error
if err != nil {

View File

@ -5,6 +5,7 @@ import "database/sql"
type DB struct {
db *sql.DB
driver string
DebugMode bool
}
func Open(driver, source string) (db DB, err error) {
@ -18,7 +19,7 @@ func (s *DB) SetPool(n int) {
}
func (s *DB) buildChain() *Chain {
return &Chain{db: s.db, driver: s.driver}
return &Chain{db: s.db, driver: s.driver, debug: s.DebugMode}
}
func (s *DB) Where(querystring interface{}, args ...interface{}) *Chain {
@ -81,6 +82,10 @@ func (s *DB) Table(name string) *Chain {
return s.buildChain().Table(name)
}
func (s *DB) Debug() *Chain {
return s.buildChain().Debug()
}
func (s *DB) CreateTable(value interface{}) *Chain {
return s.buildChain().CreateTable(value)
}