qbs: github.com/coocood/qbs Index | Files | Directories

package qbs

import "github.com/coocood/qbs"


Package Files

assert.go base.go benchmark_test_util.go criteria.go db_test_util.go dialect.go migration.go model.go mysql.go oracle.go postgres.go qbs.go sqlite3.go syntax_test_util.go


const QBS_COLTYPE_BIGINT = "bigint"
const QBS_COLTYPE_BOOL = "boolean"
const QBS_COLTYPE_DOUBLE = "double"
const QBS_COLTYPE_INT = "int"
const QBS_COLTYPE_TEXT = "text"
const QBS_COLTYPE_TIME = "timestamp"


var ColumnNameToFieldName func(string) string = snakeToUpperCamel

onvert column name to struct field name.

var ConnectionLimitError = errors.New("Connection limit reached")
var FieldNameToColumnName func(string) string = toSnake

convert struct field name to column name.

var StructNameToTableName func(string) string = toSnake

convert struct name to table name.

var TableNameToStructName func(string) string = snakeToUpperCamel

convert table name to struct name.

var ValidTags = map[string]bool{
    "pk":      true,
    "fk":      true,
    "size":    true,
    "default": true,
    "join":    true,
    "-":       true,
    "index":   true,
    "unique":  true,
    "notnull": true,
    "updated": true,
    "created": true,
    "coltype": true,

func ChangePoolSize Uses

func ChangePoolSize(size int)

The default connection pool size is 100.

func IntsToInterfaces Uses

func IntsToInterfaces(ints ...int64) []interface{}

func Register Uses

func Register(driverName, driverSourceName, databaseName string, dialect Dialect)

Register a database, should be call at the beginning of the application.

func RegisterSqlite3 Uses

func RegisterSqlite3(dbFileName string)

func RegisterWithDataSourceName Uses

func RegisterWithDataSourceName(dsn *DataSourceName)

func RegisterWithDb Uses

func RegisterWithDb(driverName string, database *sql.DB, dialect Dialect)

func SetConnectionLimit Uses

func SetConnectionLimit(maxCon int, blocking bool)

Set the connection limit, there is no limit by default. If blocking is true, GetQbs method will be blocked, otherwise returns ConnectionLimitError.

func SetLogger Uses

func SetLogger(query *log.Logger, err *log.Logger)

func StringsToInterfaces Uses

func StringsToInterfaces(strs ...string) []interface{}

Used for in condition.

func WithMigration Uses

func WithMigration(task func(mg *Migration) error) error

A safe and easy way to work with Migration instance without the need to open and close it.

func WithQbs Uses

func WithQbs(task func(*Qbs) error) error

A safe and easy way to work with *Qbs instance without the need to open and close it.

type Assert Uses

type Assert struct {
    // contains filtered or unexported fields

func NewAssert Uses

func NewAssert(t tester) *Assert

func (*Assert) Equal Uses

func (ast *Assert) Equal(expected, actual interface{}, logs ...interface{})

func (*Assert) MustEqual Uses

func (ast *Assert) MustEqual(expected, actual interface{}, logs ...interface{})

func (*Assert) MustNil Uses

func (ast *Assert) MustNil(value interface{}, logs ...interface{})

func (*Assert) MustNotEqual Uses

func (ast *Assert) MustNotEqual(expected, actual interface{}, logs ...interface{})

func (*Assert) MustNotNil Uses

func (ast *Assert) MustNotNil(value interface{}, logs ...interface{})

func (*Assert) MustTrue Uses

func (ast *Assert) MustTrue(boolValue bool, logs ...interface{})

func (*Assert) Nil Uses

func (ast *Assert) Nil(value interface{}, logs ...interface{})

func (*Assert) NotEqual Uses

func (ast *Assert) NotEqual(expected, actual interface{}, logs ...interface{})

func (*Assert) NotNil Uses

func (ast *Assert) NotNil(value interface{}, logs ...interface{})

func (*Assert) True Uses

func (ast *Assert) True(boolValue bool, logs ...interface{})

type Condition Uses

type Condition struct {
    // contains filtered or unexported fields

Conditions are structured in a way to define complex where clause easily.

func NewCondition Uses

func NewCondition(expr string, args ...interface{}) *Condition

func NewEqualCondition Uses

func NewEqualCondition(column string, value interface{}) *Condition

Snakecase column name

func NewInCondition Uses

func NewInCondition(column string, values []interface{}) *Condition

func (*Condition) And Uses

func (c *Condition) And(expr string, args ...interface{}) *Condition

func (*Condition) AndCondition Uses

func (c *Condition) AndCondition(subCondition *Condition) *Condition

func (*Condition) AndEqual Uses

func (c *Condition) AndEqual(column string, value interface{}) *Condition

Snakecase column name

func (*Condition) Merge Uses

func (c *Condition) Merge() (expr string, args []interface{})

func (*Condition) Or Uses

func (c *Condition) Or(expr string, args ...interface{}) *Condition

func (*Condition) OrCondition Uses

func (c *Condition) OrCondition(subCondition *Condition) *Condition

func (*Condition) OrEqual Uses

func (c *Condition) OrEqual(column string, value interface{}) *Condition

Snakecase column name

type DataSourceName Uses

type DataSourceName struct {
    DbName     string
    Username   string
    Password   string
    UnixSocket bool
    Host       string
    Port       string
    Variables  []string
    Dialect    Dialect

func DefaultMysqlDataSourceName Uses

func DefaultMysqlDataSourceName(dbName string) *DataSourceName

func DefaultPostgresDataSourceName Uses

func DefaultPostgresDataSourceName(dbName string) *DataSourceName

func (*DataSourceName) Append Uses

func (dsn *DataSourceName) Append(key, value string) *DataSourceName

func (*DataSourceName) String Uses

func (dsn *DataSourceName) String() string

type Dialect Uses

type Dialect interface {
    // contains filtered or unexported methods

func NewMysql Uses

func NewMysql() Dialect

func NewOracle Uses

func NewOracle() Dialect

func NewPostgres Uses

func NewPostgres() Dialect

func NewSqlite3 Uses

func NewSqlite3() Dialect

type Indexed Uses

type Indexed interface {
    Indexes(indexes *Indexes)

type Indexes Uses

type Indexes []*index

Indexes represents an array of indexes.

func (*Indexes) Add Uses

func (ix *Indexes) Add(columns ...string)

Add adds an index

func (*Indexes) AddUnique Uses

func (ix *Indexes) AddUnique(columns ...string)

AddUnique adds an unique index

type Migration Uses

type Migration struct {
    Log bool
    // contains filtered or unexported fields

func GetMigration Uses

func GetMigration() (mg *Migration, err error)

Get a Migration instance should get closed like Qbs instance.

func (*Migration) Close Uses

func (mg *Migration) Close()

func (*Migration) CreateIndexIfNotExists Uses

func (mg *Migration) CreateIndexIfNotExists(table interface{}, name string, unique bool, columns ...string) error

CreateIndex creates the specified index on table. Some databases like mysql do not support this feature directly, So dialect may need to query the database schema table to find out if an index exists. Normally you don't need to do it explicitly, it will be created automatically in CreateTableIfNotExists method.

func (*Migration) CreateTableIfNotExists Uses

func (mg *Migration) CreateTableIfNotExists(structPtr interface{}) error

CreateTableIfNotExists creates a new table and its indexes based on the table struct type It will panic if table creation failed, and it will return error if the index creation failed.

func (*Migration) DropTable Uses

func (mg *Migration) DropTable(strutPtr interface{})

Can only drop table on database which name has "test" suffix. Used for testing

type Qbs Uses

type Qbs struct {
    Dialect Dialect
    Log     bool //Set to true to print out sql statement.
    // contains filtered or unexported fields

func GetQbs Uses

func GetQbs() (q *Qbs, err error)

Get an Qbs instance, should call `defer q.Close()` next, like:

	q, err := qbs.GetQbs()
  	if err != nil {
	defer q.Close()

func (*Qbs) Begin Uses

func (q *Qbs) Begin() error

Begin create a transaction object internally You can perform queries with the same Qbs object no matter it is in transaction or not. It panics if it's already in a transaction.

func (*Qbs) BulkInsert Uses

func (q *Qbs) BulkInsert(sliceOfStructPtr interface{}) error

func (*Qbs) Close Uses

func (q *Qbs) Close() error

If the connection pool is not full, the Db will be sent back into the pool, otherwise the Db will get closed.

func (*Qbs) Commit Uses

func (q *Qbs) Commit() error

Commit commits a started transaction and will report the first error that occurred inside the transaction.

func (*Qbs) Condition Uses

func (q *Qbs) Condition(condition *Condition) *Qbs

Condition defines the SQL "WHERE" clause If other condition can be inferred by the struct argument in Find method, it will be merged with AND

func (*Qbs) ContainsValue Uses

func (q *Qbs) ContainsValue(table interface{}, column string, value interface{}) bool

This method can be used to validate unique column before trying to save The table parameter can be either a string or a struct pointer

func (*Qbs) Count Uses

func (q *Qbs) Count(table interface{}) int64

Query the count of rows in a table the talbe parameter can be either a string or struct pointer. If condition is given, the count will be the count of rows meet that condition.

func (*Qbs) Delete Uses

func (q *Qbs) Delete(structPtr interface{}) (affected int64, err error)

The delete condition can be inferred by the Id value of the struct If neither Id value or condition are provided, it would cause runtime panic

func (*Qbs) Exec Uses

func (q *Qbs) Exec(query string, args ...interface{}) (sql.Result, error)

Same as sql.Db.Exec or sql.Tx.Exec depends on if transaction has began

func (*Qbs) Find Uses

func (q *Qbs) Find(structPtr interface{}) error

Perform select query by parsing the struct's type and then fill the values into the struct All fields of supported types in the struct will be added in select clause. If Id value is provided, it will be added into the where clause If a foreign key field with its referenced struct pointer field are provided, It will perform a join query, the referenced struct pointer field will be filled in the values obtained by the query. If not found, "sql.ErrNoRows" will be returned.

func (*Qbs) FindAll Uses

func (q *Qbs) FindAll(ptrOfSliceOfStructPtr interface{}) error

Similar to Find, except that FindAll accept pointer of slice of struct pointer, rows will be appended to the slice.

func (*Qbs) InTransaction Uses

func (q *Qbs) InTransaction() bool

func (*Qbs) Iterate Uses

func (q *Qbs) Iterate(structPtr interface{}, do func() error) error

Iterate the rows, the first parameter is a struct pointer, the second parameter is a fucntion which will get called on each row, the in `do` function the structPtr's value will be set to the current row's value.. if `do` function returns an error, the iteration will be stopped.

func (*Qbs) Limit Uses

func (q *Qbs) Limit(limit int) *Qbs

func (*Qbs) Offset Uses

func (q *Qbs) Offset(offset int) *Qbs

func (*Qbs) OmitFields Uses

func (q *Qbs) OmitFields(fieldName ...string) *Qbs

Camel case field names

func (*Qbs) OmitJoin Uses

func (q *Qbs) OmitJoin() *Qbs

func (*Qbs) OrderBy Uses

func (q *Qbs) OrderBy(path string) *Qbs

func (*Qbs) OrderByDesc Uses

func (q *Qbs) OrderByDesc(path string) *Qbs

func (*Qbs) Query Uses

func (q *Qbs) Query(query string, args ...interface{}) (rows *sql.Rows, err error)

Same as sql.Db.Query or sql.Tx.Query depends on if transaction has began

func (*Qbs) QueryMap Uses

func (q *Qbs) QueryMap(query string, args ...interface{}) (map[string]interface{}, error)

Query raw sql and return a map.

func (*Qbs) QueryMapSlice Uses

func (q *Qbs) QueryMapSlice(query string, args ...interface{}) ([]map[string]interface{}, error)

Query raw sql and return a slice of map..

func (*Qbs) QueryRow Uses

func (q *Qbs) QueryRow(query string, args ...interface{}) *sql.Row

Same as sql.Db.QueryRow or sql.Tx.QueryRow depends on if transaction has began

func (*Qbs) QueryStruct Uses

func (q *Qbs) QueryStruct(dest interface{}, query string, args ...interface{}) error

Do a raw sql query and set the result values in dest parameter. The dest parameter can be either a struct pointer or a pointer of struct pointer.slice This method do not support pointer field in the struct.

func (*Qbs) Reset Uses

func (q *Qbs) Reset()

Create a new criteria for subsequent query

func (*Qbs) Rollback Uses

func (q *Qbs) Rollback() error

Rollback rolls back a started transaction.

func (*Qbs) Save Uses

func (q *Qbs) Save(structPtr interface{}) (affected int64, err error)

If Id value is not provided, save will insert the record, and the Id value will be filled in the struct after insertion. If Id value is provided, save will do a query count first to see if the row exists, if not then insert it, otherwise update it. If struct implements Validator interface, it will be validated first

func (*Qbs) Update Uses

func (q *Qbs) Update(structPtr interface{}) (affected int64, err error)

If the struct type implements Validator interface, values will be validated before update. In order to avoid inadvertently update the struct field to zero value, it is better to define a temporary struct in function, only define the fields that should be updated. But the temporary struct can not implement Validator interface, we have to validate values manually. The update condition can be inferred by the Id value of the struct. If neither Id value or condition are provided, it would cause runtime panic

func (*Qbs) Where Uses

func (q *Qbs) Where(expr string, args ...interface{}) *Qbs

Where is a shortcut method to call Condtion(NewCondtition(expr, args...)).

func (*Qbs) WhereEqual Uses

func (q *Qbs) WhereEqual(column string, value interface{}) *Qbs

Snakecase column name

func (*Qbs) WhereIn Uses

func (q *Qbs) WhereIn(column string, values []interface{}) *Qbs

type TableNamer Uses

type TableNamer interface {
    TableName() string

type Validator Uses

type Validator interface {
    Validate(*Qbs) error



Package qbs imports 13 packages (graph) and is imported by 52 packages. Updated 2017-04-25. Refresh now. Tools for package owners.