1
0
mirror of https://github.com/zhashkevych/go-sqlxmock.git synced 2025-06-24 21:56:48 +02:00
Files
go-sqlxmock/driver.go
gedi a071483cba concurrency support, closes #20 and closes #9 and closes #15
* c600769 do not require a connection name, unique dsn is generated
* 1b20b9c update travis
* 1097b6a add comments for godoc documentation
* c142a95 fix golint reported issues
2015-08-28 10:25:20 +03:00

57 lines
977 B
Go

package sqlmock
import (
"database/sql"
"database/sql/driver"
"fmt"
"sync"
)
var pool *mockDriver
func init() {
pool = &mockDriver{
conns: make(map[string]*Sqlmock),
}
sql.Register("sqlmock", pool)
}
type mockDriver struct {
sync.Mutex
counter int
conns map[string]*Sqlmock
}
func (d *mockDriver) Open(dsn string) (driver.Conn, error) {
d.Lock()
defer d.Unlock()
c, ok := d.conns[dsn]
if !ok {
return c, fmt.Errorf("expected a connection to be available, but it is not")
}
c.opened++
return c, nil
}
// New creates sqlmock database connection
// and a mock to manage expectations.
// Pings db so that all expectations could be
// asserted.
func New() (db *sql.DB, mock *Sqlmock, err error) {
pool.Lock()
dsn := fmt.Sprintf("sqlmock_db_%d", pool.counter)
pool.counter++
mock = &Sqlmock{dsn: dsn, drv: pool}
pool.conns[dsn] = mock
pool.Unlock()
db, err = sql.Open("sqlmock", dsn)
if err != nil {
return
}
return db, mock, db.Ping()
}