quote map for utils

This commit is contained in:
Jinzhu 2013-10-26 10:06:57 +08:00
parent 11758c647f
commit c26e10813d
4 changed files with 15 additions and 6 deletions

5
orm.go
View File

@ -11,6 +11,7 @@ import (
type Orm struct { type Orm struct {
TableName string TableName string
PrimaryKey string PrimaryKey string
SqlResult sql.Result
Error error Error error
Sql string Sql string
SqlVars []interface{} SqlVars []interface{}
@ -105,9 +106,9 @@ func (s *Orm) Updates(values map[string]string) *Orm {
func (s *Orm) Exec(sql ...string) *Orm { func (s *Orm) Exec(sql ...string) *Orm {
if len(sql) == 0 { if len(sql) == 0 {
s.db.Exec(s.Sql, s.SqlVars...) s.SqlResult, s.Error = s.db.Exec(s.Sql, s.SqlVars...)
} else { } else {
s.db.Exec(sql[0]) s.SqlResult, s.Error = s.db.Exec(sql[0])
} }
return s return s
} }

View File

@ -12,15 +12,16 @@ type User struct {
} }
func getDB() DB { func getDB() DB {
db, _ := Open("postgres", "user=gorm dbname=gorm") db, _ := Open("postgres", "user=gorm dbname=gorm sslmode=disable")
return db return db
} }
func TestSaveAndFirst(t *testing.T) { func TestSaveAndFirst(t *testing.T) {
db := getDB() db := getDB()
u := &User{Name: "jinzhu"} u := &User{Name: "jinzhu"}
fmt.Println("*******")
fmt.Println(db.Save(u).Sql) fmt.Println(db.Save(u).Sql)
fmt.Println(db.Save(u).Error)
fmt.Println(time.Now().String()) fmt.Println(time.Now().String())
user := &User{} user := &User{}

4
sql.go
View File

@ -20,9 +20,9 @@ func (s *Orm) explain(value interface{}, operation string) {
func (s *Orm) saveSql(value interface{}) { func (s *Orm) saveSql(value interface{}) {
columns, values := modelValues(value) columns, values := modelValues(value)
s.Sql = fmt.Sprintf( s.Sql = fmt.Sprintf(
"INSERT INTO %v (%v) VALUES (%v)", "INSERT INTO \"%v\" (%v) VALUES (%v)",
s.TableName, s.TableName,
strings.Join(columns, ","), strings.Join(quoteMap(columns), ","),
valuesToBinVar(values), valuesToBinVar(values),
) )
s.SqlVars = values s.SqlVars = values

View File

@ -27,3 +27,10 @@ func valuesToBinVar(values []interface{}) string {
} }
return strings.Join(sqls, ",") return strings.Join(sqls, ",")
} }
func quoteMap(values []string) (results []string) {
for _, value := range values {
results = append(results, "\""+value+"\"")
}
return
}