crdb

package module
v0.0.0-...-85c1763 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 30, 2018 License: MIT Imports: 8 Imported by: 10

README

crdb

Database initialization Utility methods for cockroachDB and Postgres.

usage

go get the package:

go get -u github.com/tomogoma/crdb

Use to initialize your cockroach/postgres database, godoc here:


// 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: "my_username",
    Password: "my_strong_password",
    DBName: "my_db_name",
    SSLMode: "disable",
}
// 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)
}

Documentation

Index

Examples

Constants

View Source
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"
)
View Source
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

func CloseDBOnError(db *sql.DB, err error) (*sql.DB, error)

CloseDBOnError closes connection to the given database if err != nil. It then returns the error.

func ColDesc

func ColDesc(cols ...string) string

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

func ColDescTbl(tbl string, cols ...string) string

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 DBConn

func DBConn(dsn string) (*sql.DB, error)

DBConn establishes a connection to the database.

func IgnoreDBNotFoundError

func IgnoreDBNotFoundError(err error) error

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

func InstantiateDB(db *sql.DB, dbName string, tableDescs ...string) error

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

func OrderBy(co *ColOrders, mapFunc func(modelCol interface{}) (string, error)) (string, error)

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

func Pagination(offset, count int64, args []interface{}) (string, []interface{})

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

func TryConnect(dsn string, db *sql.DB) (*sql.DB, error)

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

type BoolUpdate struct {
	Updating bool
	NewVal   bool
}

func (BoolUpdate) IsUpdating

func (su BoolUpdate) IsUpdating() bool

func (BoolUpdate) Value

func (su BoolUpdate) Value() interface{}

type ColOrders

type ColOrders struct {
	Orders []string
	Cols   []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

func (d Config) FormatDSN() string

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

type Float64Update struct {
	Updating bool
	NewVal   float64
}

func (Float64Update) IsUpdating

func (su Float64Update) IsUpdating() bool

func (Float64Update) Value

func (su Float64Update) Value() interface{}

type Int64Update

type Int64Update struct {
	Updating bool
	NewVal   int64
}

func (Int64Update) IsUpdating

func (su Int64Update) IsUpdating() bool

func (Int64Update) Value

func (su Int64Update) Value() interface{}

type StringUpdate

type StringUpdate struct {
	Updating bool
	NewVal   string
}

func (StringUpdate) IsUpdating

func (su StringUpdate) IsUpdating() bool

func (StringUpdate) Value

func (su StringUpdate) Value() interface{}

type Update

type Update interface {
	IsUpdating() bool
	Value() interface{}
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL