dbx

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2021 License: MIT Imports: 6 Imported by: 4

README

go-db

Database library for go which wraps existing database implementations and attempts to have a single contract (when possible) to easily add common handlers to database operations. Exposes interfaces on the database wrappers for easy mocking.

Documentation

Index

Constants

View Source
const (
	ErrNotFound = ErrType(iota >> 1)
	ErrFileAccess
	ErrDbAccess
	ErrDbOperation
	ErrMigrationFailed
)

Variables

This section is empty.

Functions

func Register

func Register(dbType string, provider IDbProvider, setPrimary ...bool) error

Types

type CallbackFunc

type CallbackFunc func()

type DbConfig

type DbConfig struct {
	// Host is the hostname where the database is located
	Host string `json:"host" yaml:"host"`

	// Port is the port where the database is listening to connections
	Port int `json:"port" yaml:"port"`

	// Username is the username to authenticate to the database
	Username string `json:"username" yaml:"username"`

	// Password is the password to authenticate to the database
	Password string `json:"password" yaml:"password"`

	// Database indicates the database name to connect to
	Database string `json:"database" yaml:"database"`

	// Options is any additional options to be added to the connection string
	Options string `json:"options,omitempty" yaml:"options,omitempty"`

	// DialMaxRetries defines the maximum amount of retries to attempt when dialing to a db
	DialMaxRetries int `json:"dial_max_retries" yaml:"dial_max_retries"`

	// DialRetryTimeout defines the timeout in milliseconds between retries when dialing to a db
	DialRetryTimeout int64 `json:"dial_retry_timeout" yaml:"dial_retry_timeout"`
}

DbConfig contains all database configuration fields.

type DbError

type DbError struct {
	Code    ErrType
	Message string
}

func (*DbError) Error

func (err *DbError) Error() string

func (*DbError) Is

func (err *DbError) Is(t ErrType) bool

func (*DbError) IsNotFound

func (err *DbError) IsNotFound() bool

func (*DbError) String

func (err *DbError) String() string

type ErrType

type ErrType int

type ICallbacksHandler

type ICallbacksHandler interface {
	// Before adds a new callback which will be executed before the operation.
	Before(name string, handler CallbackFunc) ICallbacksHandler

	// After adds a new callback which will be executed after the operation.
	After(name string, handler CallbackFunc) ICallbacksHandler

	// OnError
	OnError(name string, handler CallbackFunc) ICallbacksHandler

	// Remove a registered callback
	Remove(name string)
}

type ICallbacksManager

type ICallbacksManager interface {
	// Create could be used to register callbacks for creating object
	//     db.Callback().Create().After("gorm:create").Register("plugin:run_after_create", func(*Scope) {
	//       // business logic
	//       ...
	//
	//       // set error if some thing wrong happened, will rollback the creating
	//       scope.Err(errors.New("error"))
	//     })
	Create()
	// Update could be used to register callbacks for updating object, refer `Create` for usage
	Update() ICallbacksHandler
	// Delete could be used to register callbacks for deleting object, refer `Create` for usage
	Delete() ICallbacksHandler
	// Query could be used to register callbacks for querying objects with query methods like `Find`, `First`, `Related`, `Association`...
	// Refer `Create` for usage
	Query() ICallbacksHandler
}

ICallbacksManager ...

type IDatabase

type IDatabase interface {
	// Clone clones a new db connection without search conditions
	Clone() IDatabase

	// Close close current db connection.
	Close()

	// Callbacks returns the callbacks container to be able to add callbacks on Create, Update, Delete or Query.
	Callbacks() ICallbacksManager

	// SetLogger replaces default logger
	SetLogger(log log.ILogger)

	// R returns an instance of a repository (table if SQL, collection if Mongo). Alias 'Repo'
	R(name string) IRepository

	// Repo returns an instance of a repository (table if SQL, collection if Mongo). Alias 'R'
	Repo(name string) IRepository

	// Exec executes the provided script (sql script for SQL, javascript for MongoDB) and attempts to unmarshal the result.
	Exec(script string, result interface{}) error

	// Run executes the provided script (sql script for SQL, javascript for MongoDB)
	Run(script string) error

	// HasRepo check has table or not
	HasRepo(name string) bool

	// CreateRepo creates a repository in the database by the given name (table if SQL, collection if Mongo).
	// Uses the reference object to create the schema (SQL).
	CreateRepo(name string, ref ...interface{}) error

	// Migrate starts a migration process using the scripts located in the 'dataDir'
	Migrate(dataDir string, failOnOrderMismatch ...bool) error

	// SetScriptExecutor sets a custom script executor to be used when running Exec
	SetScriptExecutor(executor ScriptExecutor)
}

IDatabase ...

func Dial

func Dial(cfg *DbConfig, dbType ...string) (IDatabase, error)

type IDbProvider

type IDbProvider interface {
	Dial(cfg *DbConfig) (IDatabase, error)
}

func GetProvider

func GetProvider(dbType ...string) IDbProvider

type IQuery

type IQuery interface {
	// Set of extension functions that are not present in the original `mgo` package are defined in the following interface(s):
	IQueryPageExtension

	// Limit restricts the maximum number of records retrieved to n, and also changes the batch size to the same value.
	Limit(n int) IQuery

	// Skip skips over the n initial documents from the query results. Note that this only makes sense with capped collections where documents are naturally ordered by insertion
	// time, or with sorted results.
	Skip(n int) IQuery

	// Sort asks the Database to order returned records according to the provided field names. A field name may be prefixed by - (minus) for it to be sorted in reverse order.
	Sort(fields ...string) IQuery

	// 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
	Select(query interface{}, args ...interface{}) IQuery

	// Where adds an additional condition to match records in the query. It is associated with the previous queries with an AND prepares a query script using the provided condition object to match any records that meet the provided condition.
	// Accepts `map`, `struct`. For SQL, it also accepts `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
	Where(condition interface{}, args ...interface{}) IQuery

	// Not prepares a query script using the provided condition object to match any records that do not meet the provided condition.
	// Accepts `map`, `struct`. For SQL, it also accepts `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
	Not(condition interface{}, args ...interface{}) IQuery

	// Or indicates that any following queries in the chain will be OR'ed with the previous queries
	Or() IQuery

	// Count returns the total number of records in the result set.
	Count() (n int, err error)

	// First executes the query and unmarshals the first obtained record into the result argument. Alias 'One'
	First(result interface{}) error

	// One executes the query and unmarshals the first obtained record into the result argument. Alias 'First'
	One(result interface{}) error

	// Last executes the query and unmarshals the last obtained record into the result argument
	Last(result interface{}) error

	// All works like Iter.All.
	All(result interface{}) error

	// Distinct unmarshals into result the list of distinct values for the given key.
	Distinct(key string, result interface{}) error

	// Update update attributes with callbacks, refer: https://jinzhu.github.io/gorm/crud.html#update
	Update(update interface{}) error

	// Delete deletes the records resulting from executing the query. Alias 'Remove'
	Delete() error

	// Remove deletes the records resulting from executing the query. Alias 'Delete'
	Remove() error
}

IQuery is an interface which matches the contract for the `query` struct in `gopkg.in/mgo.v2` package. The function documentation has been narrowed from the original in `gopkg.in/mgo.v2`. For additional documentation, please refer to the `mgo.Collection` in the `gopkg.in/mgo.v2` package.

type IQueryPageExtension

type IQueryPageExtension interface {
	// Page adds to the query the information required to fetch the requested page of objects.
	Page(p ...*pages.Page) IQuery

	// WrapPage attempts to obtain the items in the requested page and wraps the result in *pages.Paginated
	WrapPage(result interface{}, p ...*pages.Page) (*pages.Paginated, error)
}

IQueryPageExtension encapsulates the new extended functions to the original IQuery

type IRepository

type IRepository interface {
	// Insert inserts one or more records in the respective repository.
	Insert(docs ...interface{}) error

	// Drop drops the repository (table if SQL, collection if MongoDB)
	Drop() error

	// Where prepares a query script using the provided condition object to match any records that meet the provided condition.
	// Accepts `map`, `struct`. For SQL, it also accepts `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query/
	Where(condition interface{}, args ...interface{}) IQuery

	// Not prepares a query script using the provided condition object to match any records that do not meet the provided condition.
	// Accepts `map`, `struct`. For SQL, it also accepts `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
	Not(condition interface{}, args ...interface{}) IQuery

	// AddIndex adds an index for the provided fields (columns for SQL, keys for MongoDB)
	AddIndex(indexName string, fields ...string) error

	// Removes all records that meet the provided query
	Delete(query interface{}, args ...interface{}) error

	// DropIndex remove index with name
	DropIndex(indexName string) error

	// AddUniqueIndex adds a unique index for the provided fields (columns for SQL, keys for MongoDB)
	AddUniqueIndex(indexName string, fields ...string) error
}

IRepository represents a repository of records (table for SQL, collection for MongoDB)

type ITransaction

type ITransaction interface {
}

type ITransactional

type ITransactional interface {
	// Begin begins a transaction
	Begin() ITransaction

	// Commit commits a transaction
	Commit() ITransaction

	// Rollback rollback a transaction
	Rollback() ITransaction
}

TODO: Implement

type M

type M map[string]interface{}

M is an alias for map[string]interface{}

type ScriptExecutor added in v1.0.3

type ScriptExecutor func(script string) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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