mydb/internal/sqlbuilder/wrapper.go

65 lines
1.9 KiB
Go
Raw Normal View History

2023-09-18 15:15:42 +08:00
package sqlbuilder
import (
"database/sql"
"git.hexq.cn/tiglog/mydb"
)
// Tx represents a transaction on a SQL database. A transaction is like a
// regular Session except it has two extra methods: Commit and Rollback.
//
// A transaction needs to be committed (with Commit) to make changes permanent,
// changes can be discarded before committing by rolling back (with Rollback).
// After either committing or rolling back a transaction it can not longer be
// used and it's automatically closed.
type Tx interface {
// All mydb.Session methods are available on transaction sessions. They will
// run on the same transaction.
mydb.Session
Commit() error
Rollback() error
}
// Adapter represents a SQL adapter.
type Adapter interface {
// New wraps an active *sql.DB session and returns a SQLBuilder database. The
// adapter needs to be imported to the blank namespace in order for it to be
// used here.
//
// This method is internally used by upper-db to create a builder backed by the
// given database. You may want to use your adapter's New function instead of
// this one.
New(*sql.DB) (mydb.Session, error)
// NewTx wraps an active *sql.Tx transation and returns a SQLBuilder
// transaction. The adapter needs to be imported to the blank namespace in
// order for it to be used.
//
// This method is internally used by upper-db to create a builder backed by the
// given transaction. You may want to use your adapter's NewTx function
// instead of this one.
NewTx(*sql.Tx) (Tx, error)
// Open opens a SQL database.
OpenDSN(mydb.ConnectionURL) (mydb.Session, error)
}
type dbAdapter struct {
Adapter
}
func (d *dbAdapter) Open(conn mydb.ConnectionURL) (mydb.Session, error) {
sess, err := d.Adapter.OpenDSN(conn)
if err != nil {
return nil, err
}
return sess.(mydb.Session), nil
}
func NewCompatAdapter(adapter Adapter) mydb.Adapter {
return &dbAdapter{adapter}
}