Documentation
¶
Index ¶
- Constants
- func AppendUpdate(upd Update, updCol, updCols string, updArgs []interface{}) (string, []interface{})
- func CloseDBOnError(db *sql.DB, err error) (*sql.DB, error)
- func ColDesc(cols ...string) string
- func ColDescTbl(tbl string, cols ...string) string
- func ConcatWhereClause(c *Comparison, col, where, whereOp string, args []interface{}) (string, []interface{})
- func DBConn(dsn string) (*sql.DB, error)
- func IgnoreDBNotFoundError(err error) error
- func InstantiateDB(db *sql.DB, dbName string, tableDescs ...string) error
- func OrderBy(co *ColOrders, mapFunc func(modelCol interface{}) (string, error)) (string, error)
- func Pagination(offset, count int64, args []interface{}) (string, []interface{})
- func TryConnect(dsn string, db *sql.DB) (*sql.DB, error)
- func WhereClause(c *Comparison, col string, args []interface{}) (string, []interface{})
- type BoolUpdate
- type ColOrders
- type Comparison
- type Config
- type DSNFormatter
- type Float64Update
- type Int64Update
- type StringUpdate
- type Update
Examples ¶
Constants ¶
const ( // Greater than. OpGT = ">" // Greater than or equal to. OpGTOrET = ">=" // Equal to. OpET = "=" // Less than or equal to. OpLTOrET = "<=" // Less than. OpLT = "<" OpIsNull = "is_null" OpIsNotNull = "is_not_null" // This Operator is not a one to one mapping like the rest OpContain = "CONTAIN" // This Operator is not a one to one mapping like the rest OpContainFold = "CONTAIN_FOLD" )
const ( OrderAsc = "ASC" OrderDesc = "DESC" )
Variables ¶
This section is empty.
Functions ¶
func AppendUpdate ¶
func AppendUpdate(upd Update, updCol, updCols string, updArgs []interface{}) (string, []interface{})
AppendUpdate adds the value of upd to updArgs and updCol (column to be updated) to updCols if upd IsUpdating. The result of appending to updCols and updArgs are returned respectively. If upd IsUpdating is false, updCols and updArgs are returned unmodified.
func CloseDBOnError ¶
CloseDBOnError closes connection to the given database if err != nil. It then returns the error.
func ColDesc ¶
ColDesc returns a string containing cols in the given order separated by ",".
Example ¶
package main
import (
"fmt"
"github.com/tomogoma/crdb"
)
func main() {
colDesc := crdb.ColDesc("name", "unit_price", "quantity")
fmt.Print(colDesc)
}
Output: name, unit_price, quantity
func ColDescTbl ¶
ColDescTbl returns a string containing cols for tbl in the given order separated by ",".
Example ¶
package main
import (
"fmt"
"github.com/tomogoma/crdb"
)
func main() {
tblName := "items"
colDesc := crdb.ColDescTbl(tblName, "name", "unit_price", "quantity")
fmt.Print(colDesc)
}
Output: items.name, items.unit_price, items.quantity
func ConcatWhereClause ¶
func ConcatWhereClause(c *Comparison, col, where, whereOp string, args []interface{}) (string, []interface{})
ConcatWhereClause calls WhereClause on c, col, args and concatenates it to a previous where clause to have an SQL statement part of the form
col_one >= 4 AND col_two IS NULL
'col_one >= 4' is picked from where while 'AND' is picked from whereOp and 'col_two IS NULL' is generated using WhereClause. See WhereClause for details.
func IgnoreDBNotFoundError ¶
IgnoreDBNotFoundError returns nil if err is nil or is a *pq.Error and has the DB-not-found code (3D000) otherwise it returns err.
func InstantiateDB ¶
InstantiateDB creates the database and tables based on dbName and tableDescs.
Example ¶
package main
import (
"github.com/tomogoma/crdb"
"log"
)
func main() {
// 1. Define a DSN to connect to the DB.
// See https://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters
// for all DSN options.
// Config can be read from a JSON or YAML file.
config := crdb.Config{
User: "root",
Port: 26257,
DBName: "crdb_test",
SSLMode: "require",
SSLCert: "/etc/cockroachdb/certs/node.crt",
SSLKey: "/etc/cockroachdb/certs/node.key",
SSLRootCert: "/etc/cockroachdb/certs/ca.crt",
}
// config#FormatDSN() yields a string like
// "user='my_username' password='my_strong_password' dbname='my_db_name' sslmode='disable'"
// You can use crdb.Config or format DSN on your own.
DSN := config.FormatDSN()
// 2. Connect to and ping the DBMS.
db, err := crdb.DBConn(DSN)
if err != nil {
log.Fatalf("Error establishing connection to DB: %v", err)
}
// 3. Instantiate your database and its tables (if not already instantiated)
tableDescs := []string{
"CREATE TABLE IF NOT EXISTS foos (name VARCHAR(25))",
"CREATE TABLE IF NOT EXISTS bars (name VARCHAR(25))",
}
err = crdb.InstantiateDB(db, config.DBName, tableDescs...)
if err != nil {
log.Fatalf("Error instantiating database: %v", err)
}
}
func OrderBy ¶
OrderBy generates an SQL statement part of the form
ORDER BY col_one ASC, col_two DESC
It determines this using co. mapFunc is used to map the col in each Col to a real column e.g. col_one of tbl_a.col_one. The error returned by mapFunc is returned as is and OrderBy stops generating.
func Pagination ¶
Pagination generates an SQL statement part of the form
LIMIT $3 OFFSET $4
It appends offset and count to the args and uses the length of the args to determine the index of the offset and count args (3 and 4) before returning the new set of args.
func TryConnect ¶
TryConnect attempts to connect to db using dsn if db is nil.
func WhereClause ¶
func WhereClause(c *Comparison, col string, args []interface{}) (string, []interface{})
WhereClause generates an SQL statement part of the form
column_one >= $4
...or aborts if c is nil. Note that the 'WHERE' keyword is NOT included in the result. It uses args to determine the index (4) in the statement and returns the same args with c.Val appended. Mapping in the example is done as follows, col => 'column_one', c.Op => '>=' and $4 is generated based on len(args). c.Op uses the provided c.Op value if no standard operator is found.
Types ¶
type BoolUpdate ¶
func (BoolUpdate) IsUpdating ¶
func (su BoolUpdate) IsUpdating() bool
func (BoolUpdate) Value ¶
func (su BoolUpdate) Value() interface{}
type Comparison ¶
type Comparison struct {
Op string
Val interface{}
}
func NewComparisonString ¶
func NewComparisonString(op string, val string) *Comparison
NewComparisonString returns a pointer to Comparison if val is not empty otherwise nil.
type Config ¶
type Config struct {
User string `json:"user,omitempty" yaml:"user,omitempty"`
Password string `json:"password,omitempty" yaml:"password,omitempty"`
Host string `json:"host,omitempty" yaml:"host,omitempty"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
DBName string `json:"dbName,omitempty" yaml:"dbName,omitempty"`
ConnectTimeout int `json:"connectTimeout,omitempty" yaml:"connectTimeout,omitempty"`
SSLMode string `json:"sslMode,omitempty" yaml:"sslMode,omitempty"`
SSLCert string `json:"sslCert,omitempty" yaml:"sslCert,omitempty"`
SSLKey string `json:"sslKey,omitempty" yaml:"sslKey,omitempty"`
SSLRootCert string `json:"sslRootCert,omitempty" yaml:"sslRootCert,omitempty"`
ConnMaxLifetime *time.Duration `json:"connMaxLifeTime,omitempty" yaml:"connMaxLifeTime,omitempty"`
MaxIdleConns *int `json:"maxIdleConns,omitempty" yaml:"maxIdleConns,omitempty"`
MaxOpenConns *int `json:"maxOpenConns,omitempty" yaml:"maxOpenConns,omitempty"`
}
More detail at https://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters
func (Config) FormatDSN ¶
FormatDSN formats Config values into a connection as per https://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters
type DSNFormatter ¶
type DSNFormatter interface {
FormatDSN() string
}
type Float64Update ¶
func (Float64Update) IsUpdating ¶
func (su Float64Update) IsUpdating() bool
func (Float64Update) Value ¶
func (su Float64Update) Value() interface{}
type Int64Update ¶
func (Int64Update) IsUpdating ¶
func (su Int64Update) IsUpdating() bool
func (Int64Update) Value ¶
func (su Int64Update) Value() interface{}
type StringUpdate ¶
func (StringUpdate) IsUpdating ¶
func (su StringUpdate) IsUpdating() bool
func (StringUpdate) Value ¶
func (su StringUpdate) Value() interface{}