clean up sql code

This commit is contained in:
Shengjing Zhu 2016-02-13 20:51:36 +08:00
parent d7cbcffdbf
commit abbbc3f6e3
2 changed files with 9 additions and 17 deletions

View File

@ -21,14 +21,17 @@ func init() {
func addLastAmongDup(tx *sql.Tx) error { func addLastAmongDup(tx *sql.Tx) error {
// Upgrade from early version where lastAmongDup is missing. // Upgrade from early version where lastAmongDup is missing.
rows, err := tx.Query("pragma table_info(cmd)") rows, err := tx.Query("select * from cmd limit 1")
if err != nil { if err != nil {
return err return err
} }
defer rows.Close()
hasLastAmongDup, err := hasColumn(rows, "lastAmongDup") hasLastAmongDup, err := hasColumn(rows, "lastAmongDup")
if err != nil { if err != nil {
return err return err
} }
if !hasLastAmongDup { if !hasLastAmongDup {
_, err := tx.Exec("alter table cmd add column lastAmongDup bool") _, err := tx.Exec("alter table cmd add column lastAmongDup bool")
if err != nil { if err != nil {
@ -39,7 +42,7 @@ func addLastAmongDup(tx *sql.Tx) error {
return err return err
} }
} }
return tx.Commit() return nil
} }
// NextCmdSeq returns the next sequence number of the command history. // NextCmdSeq returns the next sequence number of the command history.

View File

@ -7,19 +7,8 @@ func hasColumn(rows *sql.Rows, colname string) (bool, error) {
if err != nil { if err != nil {
return false, err return false, err
} }
dests := make([]interface{}, len(cols)) for _, col := range cols {
var name string if col == colname {
for i, col := range cols {
if col == "name" {
dests[i] = &name
} else {
dests[i] = new(interface{})
}
}
defer rows.Close()
for rows.Next() {
rows.Scan(dests...)
if name == colname {
return true, nil return true, nil
} }
} }
@ -35,9 +24,9 @@ func transaction(db *sql.DB, f func(*sql.Tx) error) error {
} }
err = f(tx) err = f(tx)
if err != nil { if err != nil {
tx.Rollback() return tx.Rollback()
} else { } else {
tx.Commit() return tx.Commit()
} }
return err return err
} }