...

Source file src/github.com/DATA-DOG/go-sqlmock/driver.go

Documentation: github.com/DATA-DOG/go-sqlmock

     1  package sqlmock
     2  
     3  import (
     4  	"database/sql"
     5  	"database/sql/driver"
     6  	"fmt"
     7  	"sync"
     8  )
     9  
    10  var pool *mockDriver
    11  
    12  func init() {
    13  	pool = &mockDriver{
    14  		conns: make(map[string]*sqlmock),
    15  	}
    16  	sql.Register("sqlmock", pool)
    17  }
    18  
    19  type mockDriver struct {
    20  	sync.Mutex
    21  	counter int
    22  	conns   map[string]*sqlmock
    23  }
    24  
    25  func (d *mockDriver) Open(dsn string) (driver.Conn, error) {
    26  	d.Lock()
    27  	defer d.Unlock()
    28  
    29  	c, ok := d.conns[dsn]
    30  	if !ok {
    31  		return c, fmt.Errorf("expected a connection to be available, but it is not")
    32  	}
    33  
    34  	c.opened++
    35  	return c, nil
    36  }
    37  
    38  // New creates sqlmock database connection and a mock to manage expectations.
    39  // Accepts options, like ValueConverterOption, to use a ValueConverter from
    40  // a specific driver.
    41  // Pings db so that all expectations could be
    42  // asserted.
    43  func New(options ...func(*sqlmock) error) (*sql.DB, Sqlmock, error) {
    44  	pool.Lock()
    45  	dsn := fmt.Sprintf("sqlmock_db_%d", pool.counter)
    46  	pool.counter++
    47  
    48  	smock := &sqlmock{dsn: dsn, drv: pool, ordered: true}
    49  	pool.conns[dsn] = smock
    50  	pool.Unlock()
    51  
    52  	return smock.open(options)
    53  }
    54  
    55  // NewWithDSN creates sqlmock database connection with a specific DSN
    56  // and a mock to manage expectations.
    57  // Accepts options, like ValueConverterOption, to use a ValueConverter from
    58  // a specific driver.
    59  // Pings db so that all expectations could be asserted.
    60  //
    61  // This method is introduced because of sql abstraction
    62  // libraries, which do not provide a way to initialize
    63  // with sql.DB instance. For example GORM library.
    64  //
    65  // Note, it will error if attempted to create with an
    66  // already used dsn
    67  //
    68  // It is not recommended to use this method, unless you
    69  // really need it and there is no other way around.
    70  func NewWithDSN(dsn string, options ...func(*sqlmock) error) (*sql.DB, Sqlmock, error) {
    71  	pool.Lock()
    72  	if _, ok := pool.conns[dsn]; ok {
    73  		pool.Unlock()
    74  		return nil, nil, fmt.Errorf("cannot create a new mock database with the same dsn: %s", dsn)
    75  	}
    76  	smock := &sqlmock{dsn: dsn, drv: pool, ordered: true}
    77  	pool.conns[dsn] = smock
    78  	pool.Unlock()
    79  
    80  	return smock.open(options)
    81  }
    82  

View as plain text