jorm

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2019 License: Apache-2.0 Imports: 5 Imported by: 0

README

jorm

jorm is an interface wrapper around gorm

jorm can replace gorm with very little code change, and allows the benefit of easier testing via mocks and the ability to trace a query with using the OpenTracing instrumentation by opentracing-gorm

To set the context simply call db.WithContext(ctx) and use the db returned by that function

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is a wrapper struct around a *gorm.DB

func NewDB

func NewDB(db *gorm.DB) *DB

NewDB returns a new interface wrapper around the given *gorm.DB

func (*DB) AddError

func (db *DB) AddError(err error) error

AddError add error to the db

func (*DB) AddForeignKey

func (db *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate string) Interface

AddForeignKey Add foreign key to the given scope, e.g:

db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")

func (*DB) AddIndex

func (db *DB) AddIndex(indexName string, columns ...string) Interface

AddIndex add index for columns with given name

func (*DB) AddUniqueIndex

func (db *DB) AddUniqueIndex(indexName string, columns ...string) Interface

AddUniqueIndex add unique index for columns with given name

func (*DB) Assign

func (db *DB) Assign(attrs ...interface{}) Interface

Assign assign result with argument regardless it is found or not with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate

func (*DB) Association

func (db *DB) Association(column string) *gorm.Association

Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode

func (*DB) Attrs

func (db *DB) Attrs(attrs ...interface{}) Interface

Attrs initialize struct with argument if record not found with `FirstOrInit` https://jinzhu.github.io/gorm/crud.html#firstorinit or `FirstOrCreate` https://jinzhu.github.io/gorm/crud.html#firstorcreate

func (*DB) AutoMigrate

func (db *DB) AutoMigrate(values ...interface{}) Interface

AutoMigrate run auto migration for given models, will only add missing fields, won't delete/change current data

func (*DB) Begin

func (db *DB) Begin() Interface

Begin begin a transaction

func (*DB) BlockGlobalUpdate

func (db *DB) BlockGlobalUpdate(enable bool) Interface

BlockGlobalUpdate if true, generates an error on update/delete without where clause. This is to prevent eventual error with empty objects updates/deletions

func (*DB) Callback

func (db *DB) Callback() *gorm.Callback

Callback return `Callbacks` container, you could add/change/delete callbacks with it

db.Callback().Create().Register("update_created_at", updateCreated)

Refer https://jinzhu.github.io/gorm/development.html#callbacks

func (*DB) Close

func (db *DB) Close() error

Close close current db connection. If database connection is not an io.Closer, returns an error.

func (*DB) Commit

func (db *DB) Commit() Interface

Commit commit a transaction

func (*DB) CommonDB

func (db *DB) CommonDB() gorm.SQLCommon

CommonDB return the underlying `*sql.DB` or `*sql.Tx` instance, mainly intended to allow coexistence with legacy non-GORM code.

func (*DB) Count

func (db *DB) Count(value interface{}) Interface

Count get how many records for a model

func (*DB) Create

func (db *DB) Create(value interface{}) Interface

Create insert the value into database

func (*DB) CreateTable

func (db *DB) CreateTable(models ...interface{}) Interface

CreateTable create table for models

func (*DB) DB

func (db *DB) DB() *sql.DB

DB get `*sql.DB` from current connection If the underlying database connection is not a *sql.DB, returns nil

func (*DB) Debug

func (db *DB) Debug() Interface

Debug start debug mode

func (*DB) Delete

func (db *DB) Delete(value interface{}, where ...interface{}) Interface

Delete delete value match given conditions, if the value has primary key, then will including the primary key as condition

func (*DB) Dialect

func (db *DB) Dialect() gorm.Dialect

Dialect get dialect

func (*DB) DropColumn

func (db *DB) DropColumn(column string) Interface

DropColumn drop a column

func (*DB) DropTable

func (db *DB) DropTable(values ...interface{}) Interface

DropTable drop table for models

func (*DB) DropTableIfExists

func (db *DB) DropTableIfExists(values ...interface{}) Interface

DropTableIfExists drop table if it is exist

func (*DB) Error

func (db *DB) Error() error

Error is a wrapper function for the Error field

func (*DB) Exec

func (db *DB) Exec(sql string, values ...interface{}) Interface

Exec execute raw sql

func (*DB) Find

func (db *DB) Find(out interface{}, where ...interface{}) Interface

Find find records that match given conditions

func (*DB) First

func (db *DB) First(out interface{}, where ...interface{}) Interface

First find first record that match given conditions, order by primary key

func (*DB) FirstOrCreate

func (db *DB) FirstOrCreate(out interface{}, where ...interface{}) Interface

FirstOrCreate find first matched record or create a new one with given conditions (only works with struct, map conditions) https://jinzhu.github.io/gorm/crud.html#firstorcreate

func (*DB) FirstOrInit

func (db *DB) FirstOrInit(out interface{}, where ...interface{}) Interface

FirstOrInit find first matched record or initialize a new one with given conditions (only works with struct, map conditions) https://jinzhu.github.io/gorm/crud.html#firstorinit

func (*DB) Get

func (db *DB) Get(name string) (value interface{}, ok bool)

Get get setting by name

func (*DB) GetErrors

func (db *DB) GetErrors() []error

GetErrors get happened errors from the db

func (*DB) GetGormDB

func (db *DB) GetGormDB() *gorm.DB

GetGormDB returns the underlying gorm DB

func (*DB) Group

func (db *DB) Group(query string) Interface

Group specify the group method on the find

func (*DB) HasBlockGlobalUpdate

func (db *DB) HasBlockGlobalUpdate() bool

HasBlockGlobalUpdate return state of block

func (*DB) HasTable

func (db *DB) HasTable(value interface{}) bool

HasTable check has table or not

func (*DB) Having

func (db *DB) Having(query interface{}, values ...interface{}) Interface

Having specify HAVING conditions for GROUP BY

func (*DB) InstantSet

func (db *DB) InstantSet(name string, value interface{}) Interface

InstantSet instant set setting, will affect current db

func (*DB) Joins

func (db *DB) Joins(query string, args ...interface{}) Interface

Joins specify Joins conditions

db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)

func (*DB) Last

func (db *DB) Last(out interface{}, where ...interface{}) Interface

Last find last record that match given conditions, order by primary key

func (*DB) Limit

func (db *DB) Limit(limit interface{}) Interface

Limit specify the number of records to be retrieved

func (*DB) LogMode

func (db *DB) LogMode(enable bool) Interface

LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs

func (*DB) Model

func (db *DB) Model(value interface{}) Interface

Model specify the model you would like to run db operations

// update all users's name to `hello`
db.Model(&User{}).Update("name", "hello")
// if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
db.Model(&user).Update("name", "hello")

func (*DB) ModifyColumn

func (db *DB) ModifyColumn(column string, typ string) Interface

ModifyColumn modify column to type

func (*DB) New

func (db *DB) New() Interface

New clone a new db connection without search conditions

func (*DB) NewRecord

func (db *DB) NewRecord(value interface{}) bool

NewRecord check if value's primary key is blank

func (*DB) Not

func (db *DB) Not(query interface{}, args ...interface{}) Interface

Not filter records that don't match current conditions, similar to `Where`

func (*DB) Offset

func (db *DB) Offset(offset interface{}) Interface

Offset specify the number of records to skip before starting to return the records

func (*DB) Omit

func (db *DB) Omit(columns ...string) Interface

Omit specify fields that you want to ignore when saving to database for creating, updating

func (*DB) Or

func (db *DB) Or(query interface{}, args ...interface{}) Interface

Or filter records that match before conditions or this one, similar to `Where`

func (*DB) Order

func (db *DB) Order(value interface{}, reorder ...bool) Interface

Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions

db.Order("name DESC")
db.Order("name DESC", true) // reorder
db.Order(gorm.Expr("name = ? DESC", "first")) // sql expression

func (*DB) Pluck

func (db *DB) Pluck(column string, value interface{}) Interface

Pluck used to query single column from a model as a map

var ages []int64
db.Find(&users).Pluck("age", &ages)

func (*DB) Preload

func (db *DB) Preload(column string, conditions ...interface{}) Interface

Preload preload associations with given conditions

db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)

func (*DB) Raw

func (db *DB) Raw(sql string, values ...interface{}) Interface

Raw use raw sql as conditions, won't run it unless invoked by other methods

db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)

func (*DB) RecordNotFound

func (db *DB) RecordNotFound() bool

RecordNotFound check if returning ErrRecordNotFound error

func (*DB) Related

func (db *DB) Related(value interface{}, foreignKeys ...string) Interface

Related get related associations

func (*DB) RemoveForeignKey

func (db *DB) RemoveForeignKey(field string, dest string) Interface

RemoveForeignKey Remove foreign key from the given scope, e.g:

db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")

func (*DB) RemoveIndex

func (db *DB) RemoveIndex(indexName string) Interface

RemoveIndex remove index with name

func (*DB) Rollback

func (db *DB) Rollback() Interface

Rollback rollback a transaction

func (*DB) Row

func (db *DB) Row() Row

Row return `*sql.Row` with given conditions

func (*DB) Rows

func (db *DB) Rows() (Rows, error)

Rows return `*sql.Rows` with given conditions

func (*DB) RowsAffected

func (db *DB) RowsAffected() int64

RowsAffected is a wrapper function for the RowsAffected field

func (*DB) Save

func (db *DB) Save(value interface{}) Interface

Save update value in database, if the value doesn't have primary key, will insert it

func (*DB) Scan

func (db *DB) Scan(dest interface{}) Interface

Scan scan value to a struct

func (*DB) ScanRows

func (db *DB) ScanRows(rows *sql.Rows, result interface{}) error

ScanRows scan `*sql.Rows` to give struct

func (*DB) Scopes

func (db *DB) Scopes(funcs ...func(*gorm.DB) *gorm.DB) Interface

Scopes pass current database connection to arguments `func(*DB) *DB`, which could be used to add conditions dynamically

func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
    return db.Where("amount > ?", 1000)
}

func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
    return func (db *gorm.DB) *gorm.DB {
        return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
    }
}

db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)

Refer https://jinzhu.github.io/gorm/crud.html#scopes

func (*DB) Select

func (db *DB) Select(query interface{}, args ...interface{}) Interface

Select specify fields that you want to retrieve from database when querying, by default, will select all fields; When creating/updating, specify fields that you want to save to database

func (*DB) Set

func (db *DB) Set(name string, value interface{}) Interface

Set set setting by name, which could be used in callbacks, will clone a new db, and update its setting

func (*DB) SetJoinTableHandler

func (db *DB) SetJoinTableHandler(source interface{}, column string, handler gorm.JoinTableHandlerInterface)

SetJoinTableHandler set a model's join table handler for a relation

func (*DB) SetLogger

func (db *DB) SetLogger(log mysql.Logger)

SetLogger replace default logger

func (*DB) SingularTable

func (db *DB) SingularTable(enable bool)

SingularTable use singular table by default

func (*DB) Table

func (db *DB) Table(name string) Interface

Table specify the table you would like to run db operations

func (*DB) Take

func (db *DB) Take(out interface{}, where ...interface{}) Interface

Take return a record that match given conditions, the order will depend on the database implementation

func (*DB) Unscoped

func (db *DB) Unscoped() Interface

Unscoped return all record including deleted record, refer Soft Delete https://jinzhu.github.io/gorm/crud.html#soft-delete

func (*DB) Update

func (db *DB) Update(attrs ...interface{}) Interface

Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update

func (*DB) UpdateColumn

func (db *DB) UpdateColumn(attrs ...interface{}) Interface

UpdateColumn update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update

func (*DB) UpdateColumns

func (db *DB) UpdateColumns(values interface{}) Interface

UpdateColumns update attributes without callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update

func (*DB) Updates

func (db *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) Interface

Updates update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update

func (*DB) Value

func (db *DB) Value() interface{}

Value is a wrapper function for the Value field

func (*DB) Where

func (db *DB) Where(query interface{}, args ...interface{}) Interface

Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query

func (*DB) WithContext

func (db *DB) WithContext(ctx context.Context) Interface

WithContext returns a clone of the current db with parent Span ID set to that of the context

type Interface

type Interface interface {
	// Adds context propagation
	WithContext(ctx context.Context) Interface
	// Allow field values to be accessed via function calls
	Value() interface{}
	Error() error
	RowsAffected() int64
	// Allow users access to the underlying gorm DB
	GetGormDB() *gorm.DB
	// Wrap the functions
	New() Interface
	Close() error
	DB() *sql.DB
	CommonDB() gorm.SQLCommon
	Dialect() gorm.Dialect
	Callback() *gorm.Callback
	SetLogger(log mysql.Logger)
	LogMode(enable bool) Interface
	BlockGlobalUpdate(enable bool) Interface
	HasBlockGlobalUpdate() bool
	SingularTable(enable bool)
	Where(query interface{}, args ...interface{}) Interface
	Or(query interface{}, args ...interface{}) Interface
	Not(query interface{}, args ...interface{}) Interface
	Limit(limit interface{}) Interface
	Offset(offset interface{}) Interface
	Order(value interface{}, reorder ...bool) Interface
	Select(query interface{}, args ...interface{}) Interface
	Omit(columns ...string) Interface
	Group(query string) Interface
	Having(query interface{}, values ...interface{}) Interface
	Joins(query string, args ...interface{}) Interface
	Scopes(funcs ...func(*gorm.DB) *gorm.DB) Interface
	Unscoped() Interface
	Assign(attrs ...interface{}) Interface
	Attrs(attrs ...interface{}) Interface
	First(out interface{}, where ...interface{}) Interface
	Take(out interface{}, where ...interface{}) Interface
	Last(out interface{}, where ...interface{}) Interface
	Find(out interface{}, where ...interface{}) Interface
	Scan(dest interface{}) Interface
	Row() Row
	Rows() (Rows, error)
	ScanRows(rows *sql.Rows, result interface{}) error
	Pluck(column string, value interface{}) Interface
	Count(value interface{}) Interface
	Related(value interface{}, foreignKeys ...string) Interface
	FirstOrInit(out interface{}, where ...interface{}) Interface
	FirstOrCreate(out interface{}, where ...interface{}) Interface
	Update(attrs ...interface{}) Interface
	Updates(values interface{}, ignoreProtectedAttrs ...bool) Interface
	UpdateColumn(attrs ...interface{}) Interface
	UpdateColumns(values interface{}) Interface
	Save(value interface{}) Interface
	Create(value interface{}) Interface
	Delete(value interface{}, where ...interface{}) Interface
	Raw(sql string, values ...interface{}) Interface
	Exec(sql string, values ...interface{}) Interface
	Model(value interface{}) Interface
	Table(name string) Interface
	Debug() Interface
	Begin() Interface
	Commit() Interface
	Rollback() Interface
	NewRecord(value interface{}) bool
	RecordNotFound() bool
	CreateTable(models ...interface{}) Interface
	DropTable(values ...interface{}) Interface
	DropTableIfExists(values ...interface{}) Interface
	HasTable(value interface{}) bool
	AutoMigrate(values ...interface{}) Interface
	ModifyColumn(column string, typ string) Interface
	DropColumn(column string) Interface
	AddIndex(indexName string, columns ...string) Interface
	AddUniqueIndex(indexName string, columns ...string) Interface
	RemoveIndex(indexName string) Interface
	AddForeignKey(field string, dest string, onDelete string, onUpdate string) Interface
	RemoveForeignKey(field string, dest string) Interface
	Association(column string) *gorm.Association
	Preload(column string, conditions ...interface{}) Interface
	Set(name string, value interface{}) Interface
	InstantSet(name string, value interface{}) Interface
	Get(name string) (value interface{}, ok bool)
	SetJoinTableHandler(source interface{}, column string, handler gorm.JoinTableHandlerInterface)
	AddError(err error) error
	GetErrors() []error
}

Interface contains all of the funcs a *gorm.DB has

type Row

type Row interface {
	Scan(dest ...interface{}) error
}

Row is an interface wrapper for sql.Row

type Rows

type Rows interface {
	Next() bool
	NextResultSet() bool
	Err() error
	Columns() ([]string, error)
	ColumnTypes() ([]*sql.ColumnType, error)
	Scan(dest ...interface{}) error
	Close() error
}

Rows is an interface wrapper for sql.Rows

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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