github.com/solongordon/pop@v4.10.0+incompatible/connection.go (about) 1 package pop 2 3 import ( 4 "sync/atomic" 5 "time" 6 7 "github.com/jmoiron/sqlx" 8 "github.com/markbates/going/defaults" 9 "github.com/markbates/going/randx" 10 "github.com/pkg/errors" 11 ) 12 13 // Connections contains all available connections 14 var Connections = map[string]*Connection{} 15 16 // Connection represents all necessary details to talk with a datastore 17 type Connection struct { 18 ID string 19 Store store 20 Dialect dialect 21 Elapsed int64 22 TX *Tx 23 eager bool 24 eagerFields []string 25 } 26 27 func (c *Connection) String() string { 28 return c.URL() 29 } 30 31 // URL returns the datasource connection string 32 func (c *Connection) URL() string { 33 return c.Dialect.URL() 34 } 35 36 // MigrationURL returns the datasource connection string used for running the migrations 37 func (c *Connection) MigrationURL() string { 38 return c.Dialect.MigrationURL() 39 } 40 41 // MigrationTableName returns the name of the table to track migrations 42 func (c *Connection) MigrationTableName() string { 43 return c.Dialect.Details().MigrationTableName() 44 } 45 46 // NewConnection creates a new connection, and sets it's `Dialect` 47 // appropriately based on the `ConnectionDetails` passed into it. 48 func NewConnection(deets *ConnectionDetails) (*Connection, error) { 49 err := deets.Finalize() 50 if err != nil { 51 return nil, errors.WithStack(err) 52 } 53 c := &Connection{ 54 ID: randx.String(30), 55 } 56 57 if nc, ok := newConnection[deets.Dialect]; ok { 58 c.Dialect, err = nc(deets) 59 if err != nil { 60 return c, errors.Wrap(err, "could not create new connection") 61 } 62 return c, nil 63 } 64 return nil, errors.Errorf("could not found connection creator for %v", deets.Dialect) 65 } 66 67 // Connect takes the name of a connection, default is "development", and will 68 // return that connection from the available `Connections`. If a connection with 69 // that name can not be found an error will be returned. If a connection is 70 // found, and it has yet to open a connection with its underlying datastore, 71 // a connection to that store will be opened. 72 func Connect(e string) (*Connection, error) { 73 if len(Connections) == 0 { 74 err := LoadConfigFile() 75 if err != nil { 76 return nil, errors.WithStack(err) 77 } 78 } 79 e = defaults.String(e, "development") 80 c := Connections[e] 81 if c == nil { 82 return c, errors.Errorf("could not find connection named %s", e) 83 } 84 err := c.Open() 85 return c, errors.Wrapf(err, "couldn't open connection for %s", e) 86 } 87 88 // Open creates a new datasource connection 89 func (c *Connection) Open() error { 90 if c.Store != nil { 91 return nil 92 } 93 if c.Dialect == nil { 94 return errors.New("invalid connection instance") 95 } 96 details := c.Dialect.Details() 97 db, err := sqlx.Open(details.Dialect, c.Dialect.URL()) 98 if err != nil { 99 return errors.Wrap(err, "could not open database connection") 100 } 101 db.SetMaxOpenConns(details.Pool) 102 db.SetMaxIdleConns(details.IdlePool) 103 c.Store = &dB{db} 104 105 if d, ok := c.Dialect.(afterOpenable); ok { 106 err = d.AfterOpen(c) 107 if err != nil { 108 c.Store = nil 109 } 110 } 111 return errors.Wrap(err, "could not open database connection") 112 } 113 114 // Close destroys an active datasource connection 115 func (c *Connection) Close() error { 116 return errors.Wrap(c.Store.Close(), "couldn't close connection") 117 } 118 119 // Transaction will start a new transaction on the connection. If the inner function 120 // returns an error then the transaction will be rolled back, otherwise the transaction 121 // will automatically commit at the end. 122 func (c *Connection) Transaction(fn func(tx *Connection) error) error { 123 return c.Dialect.Lock(func() error { 124 var dberr error 125 cn, err := c.NewTransaction() 126 if err != nil { 127 return err 128 } 129 err = fn(cn) 130 if err != nil { 131 dberr = cn.TX.Rollback() 132 } else { 133 dberr = cn.TX.Commit() 134 } 135 if err != nil { 136 return errors.WithStack(err) 137 } 138 return errors.Wrap(dberr, "error committing or rolling back transaction") 139 }) 140 141 } 142 143 // Rollback will open a new transaction and automatically rollback that transaction 144 // when the inner function returns, regardless. This can be useful for tests, etc... 145 func (c *Connection) Rollback(fn func(tx *Connection)) error { 146 cn, err := c.NewTransaction() 147 if err != nil { 148 return err 149 } 150 fn(cn) 151 return cn.TX.Rollback() 152 } 153 154 // NewTransaction starts a new transaction on the connection 155 func (c *Connection) NewTransaction() (*Connection, error) { 156 var cn *Connection 157 if c.TX == nil { 158 tx, err := c.Store.Transaction() 159 if err != nil { 160 return cn, errors.Wrap(err, "couldn't start a new transaction") 161 } 162 cn = &Connection{ 163 ID: randx.String(30), 164 Store: tx, 165 Dialect: c.Dialect, 166 TX: tx, 167 } 168 } else { 169 cn = c 170 } 171 return cn, nil 172 } 173 174 func (c *Connection) copy() *Connection { 175 return &Connection{ 176 ID: randx.String(30), 177 Store: c.Store, 178 Dialect: c.Dialect, 179 TX: c.TX, 180 } 181 } 182 183 // Q creates a new "empty" query for the current connection. 184 func (c *Connection) Q() *Query { 185 return Q(c) 186 } 187 188 // disableEager disables eager mode for current connection. 189 func (c *Connection) disableEager() { 190 c.eager = false 191 c.eagerFields = []string{} 192 } 193 194 // TruncateAll truncates all data from the datasource 195 func (c *Connection) TruncateAll() error { 196 return c.Dialect.TruncateAll(c) 197 } 198 199 func (c *Connection) timeFunc(name string, fn func() error) error { 200 start := time.Now() 201 err := fn() 202 atomic.AddInt64(&c.Elapsed, int64(time.Since(start))) 203 if err != nil { 204 return errors.WithStack(err) 205 } 206 return nil 207 }