97 lines
2.3 KiB
Go
97 lines
2.3 KiB
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
)
|
|
|
|
type Transaction struct {
|
|
Tx *sql.Tx
|
|
Rx *sql.DB
|
|
Config *DBConfig
|
|
ConnectionName string
|
|
}
|
|
type TxClosure func(tx *Transaction) (interface{}, error)
|
|
|
|
func (t *Transaction) Table(tableName string) *Builder {
|
|
builder := NewTxBuilder(t)
|
|
if t.Config.Driver == DriverMysql {
|
|
builder.Grammar = &MysqlGrammar{}
|
|
} else if t.Config.Driver == DriverSqlite3 {
|
|
builder.Grammar = &Sqlite3Grammar{}
|
|
} else {
|
|
panic("不支持的数据库类型")
|
|
}
|
|
builder.Grammar.SetTablePrefix(t.Config.Prefix)
|
|
builder.Tx = t
|
|
builder.Grammar.SetBuilder(builder)
|
|
builder.From(tableName)
|
|
return builder
|
|
}
|
|
|
|
func (t *Transaction) Select(query string, bindings []interface{}, dest interface{}) (result sql.Result, err error) {
|
|
var stmt *sql.Stmt
|
|
var rows *sql.Rows
|
|
stmt, err = t.Rx.Prepare(query)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer stmt.Close()
|
|
rows, err = stmt.Query(bindings...)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
return ScanResult(rows, dest), nil
|
|
}
|
|
func (t *Transaction) AffectingStatement(query string, bindings []interface{}) (result sql.Result, err error) {
|
|
stmt, errP := t.Tx.Prepare(query)
|
|
if errP != nil {
|
|
err = errP
|
|
return
|
|
}
|
|
defer stmt.Close()
|
|
result, err = stmt.Exec(bindings...)
|
|
if err != nil {
|
|
return
|
|
}
|
|
return
|
|
}
|
|
func (t *Transaction) Insert(query string, bindings []interface{}) (sql.Result, error) {
|
|
return t.AffectingStatement(query, bindings)
|
|
}
|
|
|
|
func (t *Transaction) Update(query string, bindings []interface{}) (sql.Result, error) {
|
|
return t.AffectingStatement(query, bindings)
|
|
}
|
|
|
|
func (t *Transaction) Delete(query string, bindings []interface{}) (sql.Result, error) {
|
|
return t.AffectingStatement(query, bindings)
|
|
}
|
|
|
|
func (t *Transaction) Statement(query string, bindings []interface{}) (sql.Result, error) {
|
|
return t.AffectingStatement(query, bindings)
|
|
}
|
|
|
|
func (t *Transaction) Commit() error {
|
|
return t.Tx.Commit()
|
|
}
|
|
|
|
func (t *Transaction) Rollback() error {
|
|
return t.Tx.Rollback()
|
|
}
|
|
|
|
func (t *Transaction) Query() *Builder {
|
|
builder := NewTxBuilder(t)
|
|
if t.Config.Driver == DriverMysql {
|
|
builder.Grammar = &MysqlGrammar{}
|
|
} else if t.Config.Driver == DriverSqlite3 {
|
|
builder.Grammar = &Sqlite3Grammar{}
|
|
} else {
|
|
panic("不支持的数据库类型")
|
|
}
|
|
builder.Grammar.SetBuilder(builder)
|
|
builder.Grammar.SetTablePrefix(t.Config.Prefix)
|
|
return builder
|
|
}
|