Documentation
¶
Overview ¶
Package sqlize helps with on-demand transactions, SQL logging and running scripts with Go's standard database/sql package.
Moular DB Code with Transactions ¶
In Go the object to perform DB operations is explicitly passed around – for good reasons. These objects are either of type *sql.DB and *sql.Tx. If one wants to perfom a single atomic DB operation its fast and simple to use sql.DB.Exec et al. If one needs to combine more than one operation into a tarnsaction, then sql.Tx.Exed et al must be used. Now consider a DB function
func simpleDBOp(db *sql.DB) error {
… a single DB operation …
}
Nice and smooth! Now we want to use it in a complex DB transaction:
func complexDBOp(tx *sql.Tx) error { // complex ⇒ need a Tx
…
simpleDBOp(tx) // compile error
…
}
One would have to rewrite simpleDBOp(tx *sql.Tx)… which imposes the costs of explicit transactions to all users of simpleDBOp. That's why sqlize uses the Querier interface that has the common methods of sql.DB and sql.Tx. This makes the sqlize API reusable and allows to implement application code in a more modular way:
// Now, complexDBOp(tx *sql.Tx) will compile
func simpleDBOp(db sqlize.Cmd) error {
… a single DB operation …
}
Example (SplitPara) ¶
rd := strings.NewReader(`1 one line
1 next line
2 another line
3 third 1
3 third 2`)
scn := bufio.NewScanner(rd)
scn.Split(splitPara)
for scn.Scan() {
fmt.Print(scn.Text())
fmt.Println("¶")
}
Output: 1 one line 1 next line¶ 2 another line¶ 3 third 1 3 third 2¶
Index ¶
- func Begin(q CtxCmd) (tx *sql.Tx, ok bool, err error)
- func BeginTx(q CtxCmd, ctx context.Context, opts *sql.TxOptions) (*sql.Tx, bool, error)
- func CommitOrRollbackOn(err *error, tx *sql.Tx)
- func LogDriver(name string, drv driver.Driver, logTo Logger, flags LogFlag)
- func MustBegin(q CtxCmd) (tx *sql.Tx, ok bool)
- func MustBeginTx(q CtxCmd, ctx context.Context, opts *sql.TxOptions) (*sql.Tx, bool)
- func NotNoRows(err error) error
- func RunScript(db Cmd, rd io.Reader, ignoreErr bool) error
- func RunScriptContext(ctx context.Context, db Cmd, rd io.Reader, ignoreErr bool) error
- func RunScriptFile(db Cmd, file string, ignoreErr bool) error
- func RunScriptFileContext(ctx context.Context, db Cmd, file string, ignoreErr bool) error
- func Xaction(q CtxCmd, do func(*sql.Tx) error) (err error)
- func XactionTx(q CtxCmd, ctx context.Context, opts *sql.TxOptions, do func(*sql.Tx) error) (err error)
- type CallRef
- type Cmd
- type CtxCmd
- type LogFlag
- type Logger
- type RollbackError
- type ScannerFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Begin ¶ added in v0.7.2
Begin starts a new transaction tx if q is a DB and returns tx, true. If q is altrady a transaction tx then tx, false is returned. If an error occurs it will be returned as err.
func BeginTx ¶ added in v0.7.2
BeginTx starts a new transaction if the provided Querier is a *sql.DB, or returns the existing transaction if it is a *sql.Tx. If the Querier is neither, an error is returned. The boolean return value indicates whether a new transaction was started (true) or an existing one was used (false).
func CommitOrRollbackOn ¶ added in v0.7.2
CommitOrRollbackOn handles transaction completion based on error state. If err is not nil, it rolls back the transaction and wraps any rollback error with the original error into a RollbackError. If err is nil, it commits the transaction and assigns any commit error to err.
Example ¶
sql.Register("CommitOrRollbackOn", sqlmw.Driver(&sqlite3.SQLiteDriver{}, new(printCommitNRollbackstruct)))
db, _ := sql.Open("CommitOrRollbackOn", ":memory:")
defer db.Close()
tx, ok, err := Begin(db)
if err != nil {
fmt.Println(err)
return
}
if ok {
defer CommitOrRollbackOn(&err, tx)
}
// An non-nil err will rool back
err = errors.New("Just an error")
Output: TxRollback
func LogDriver ¶ added in v0.7.2
LogDriver registers a new sql driver that wraps the real driver drv with calls to the Logger logTo. With flags one can select which driver methods are logged. If logTo is nil the driver will log to the standard logger from Go's log package.
Example ¶
const loggingDriverName = "log-sqlite3"
LogDriver(
loggingDriverName, &sqlite3.SQLiteDriver{},
NewStdLogger(log.New(os.Stdout, "DB: #", 0)),
LogAll,
)
db, err := sql.Open(loggingDriverName, ":memory:")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
db.QueryRow("SELECT * FROM sqlize")
Output: DB: #1 Connect DB: #1 OK Connect DB: #2 Query [SELECT * FROM sqlize []] DB: #2 ERR Query no such table: sqlize
func MustBeginTx ¶ added in v0.7.2
func NotNoRows ¶
NotNoRows filters out sql.ErrNoRows from the input error. If the input error is sql.ErrNoRows, it returns nil. For all other errors, it returns the original error unchanged.
func RunScriptContext ¶
func RunScriptFileContext ¶
func Xaction ¶ added in v0.2.0
Xaction executes a function within a database transaction context. It begins a transaction using the provided Querier, and if a transaction is started, it ensures that the transaction is either committed or rolled back depending on the outcome.
Example ¶
sql.Register("ExampleXaction", sqlmw.Driver(&sqlite3.SQLiteDriver{}, new(printCommitNRollbackstruct)))
db, _ := sql.Open("ExampleXaction", ":memory:")
defer db.Close()
Xaction(db, func(tx *sql.Tx) error {
return errors.New("Just an error")
})
Output: TxRollback
Types ¶
type CtxCmd ¶
type CtxCmd interface {
Cmd
Exec(query string, args ...any) (sql.Result, error)
Query(query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...any) *sql.Row
}
CtxCmd allows to run or execute queries against a database or to prepare statements. It is used to drop the distinction between sql.DB, sql.Tx and sql.Conn in application code. See also Xaction and XactionTx.
func BackgroundCmd ¶
type LogFlag ¶ added in v0.7.2
type LogFlag uint
const ( LogBeginTx LogFlag = (1 << iota) LogPrepare LogPing LogExec LogQuery LogConnect LogInsertId LogRowsAffected LogRowsNext LogRowsClose LogStmtExec LogStmtQuery LogStmtClose LogTxCommit LogTxRollback LogDefault = LogExec | LogQuery | LogStmtExec | LogStmtQuery | LogInsertId LogAll = ^LogFlag(0) )
type Logger ¶ added in v0.7.2
type Logger interface {
Call(name string, args ...any) CallRef
Result(ref CallRef, err error, args ...any)
}
func NewStdLogger ¶ added in v0.7.2
NewStdLogger creates a new SQL logger that logs with Go's standard log package. If l is nil the log.Default() logger is used.
type RollbackError ¶
type RollbackError struct {
Cause error // The error that coused the rollback
Rollback error // The error that occured during rollback
}
func (RollbackError) Error ¶
func (ce RollbackError) Error() string
func (RollbackError) Unwrap ¶
func (ce RollbackError) Unwrap() error
type ScannerFunc ¶ added in v0.9.0
func (ScannerFunc) Scan ¶ added in v0.9.0
func (f ScannerFunc) Scan(src any) error
Directories
¶
| Path | Synopsis |
|---|---|
|
keywords
Package keywords defines some handy SQL keywords as const strings for use with the bsq query builder.
|
Package keywords defines some handy SQL keywords as const strings for use with the bsq query builder. |
|
cmd
|
|
|
sqlize
command
|
|
|
Package dbtest has utilities to help with writing DB related tests in conjunction with sqlize.
|
Package dbtest has utilities to help with writing DB related tests in conjunction with sqlize. |
|
queries
command
|
|
|
Package null implements typed adapters for Go values to nullable DB columns.
|
Package null implements typed adapters for Go values to nullable DB columns. |