Documentation
¶
Overview ¶
Package db (or upper/db) provides an agnostic data access layer to work with different databases.
Install upper/db:
go get github.com/upper/db
Usage
package main
import (
"log"
"github.com/upper/db/v4/adapter/postgresql" // Imports the postgresql adapter.
)
var settings = postgresql.ConnectionURL{
Database: `booktown`,
Host: `demo.upper.io`,
User: `demouser`,
Password: `demop4ss`,
}
// Book represents a book.
type Book struct {
ID uint `db:"id"`
Title string `db:"title"`
AuthorID uint `db:"author_id"`
SubjectID uint `db:"subject_id"`
}
func main() {
sess, err := postgresql.Open(settings)
if err != nil {
log.Fatal(err)
}
defer sess.Close()
var books []Book
if err := sess.Collection("books").Find().OrderBy("title").All(&books); err != nil {
log.Fatal(err)
}
log.Println("Books:")
for _, book := range books {
log.Printf("%q (ID: %d)\n", book.Title, book.ID)
}
}
Index ¶
- Variables
- func RegisterAdapter(name string, adapter Adapter)
- type Adapter
- type AfterCreateHook
- type AfterDeleteHook
- type AfterUpdateHook
- type AndExpr
- type BeforeCreateHook
- type BeforeDeleteHook
- type BeforeUpdateHook
- type Collection
- type Comparison
- func After(value time.Time) *Comparison
- func Before(value time.Time) *Comparison
- func Between(lowerBound interface{}, upperBound interface{}) *Comparison
- func Eq(value interface{}) *Comparison
- func Gt(value interface{}) *Comparison
- func Gte(value interface{}) *Comparison
- func In(value ...interface{}) *Comparison
- func Is(value interface{}) *Comparison
- func IsNot(value interface{}) *Comparison
- func IsNotNull() *Comparison
- func IsNull() *Comparison
- func Like(value string) *Comparison
- func Lt(value interface{}) *Comparison
- func Lte(value interface{}) *Comparison
- func NotBetween(lowerBound interface{}, upperBound interface{}) *Comparison
- func NotEq(value interface{}) *Comparison
- func NotIn(value ...interface{}) *Comparison
- func NotLike(value string) *Comparison
- func NotRegExp(value string) *Comparison
- func OnOrAfter(value time.Time) *Comparison
- func OnOrBefore(value time.Time) *Comparison
- func Op(customOperator string, value interface{}) *Comparison
- func RegExp(value string) *Comparison
- type Cond
- type ConnectionURL
- type FuncExpr
- type HasSave
- type ID
- type InsertResult
- type Item
- type LogLevel
- type Logger
- type LoggingCollector
- type LogicalExpr
- type LogicalOperator
- type M
- type Marshaler
- type Model
- type OrExpr
- type RawExpr
- type Result
- type Session
- type Settings
- type Tx
- type Unmarshaler
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ( ErrAlreadyWithinTransaction = errors.New(`already within a transaction`) ErrCollectionDoesNotExist = errors.New(`collection does not exist`) ErrExpectingNonNilModel = errors.New(`expecting non nil model`) ErrExpectingPointerToStruct = errors.New(`expecting pointer to struct`) ErrGivingUpTryingToConnect = errors.New(`giving up trying to connect: too many clients`) ErrInvalidCollection = errors.New(`invalid collection`) ErrMissingCollectionName = errors.New(`missing collection name`) ErrMissingConditions = errors.New(`missing selector conditions`) ErrMissingConnURL = errors.New(`missing DSN`) ErrMissingDatabaseName = errors.New(`missing database name`) ErrNoMoreRows = errors.New(`no more rows in this result set`) ErrNotConnected = errors.New(`not connected to a database`) ErrNotImplemented = errors.New(`call not implemented`) ErrQueryIsPending = errors.New(`can't execute this instruction while the result set is still open`) ErrQueryLimitParam = errors.New(`a query can accept only one limit parameter`) ErrQueryOffsetParam = errors.New(`a query can accept only one offset parameter`) ErrQuerySortParam = errors.New(`a query can accept only one order-by parameter`) ErrSockerOrHost = errors.New(`you may connect either to a UNIX socket or a TCP address, but not both`) ErrTooManyClients = errors.New(`can't connect to database server: too many clients`) ErrUndefined = errors.New(`value is undefined`) ErrUnknownConditionType = errors.New(`arguments of type %T can't be used as constraints`) ErrUnsupported = errors.New(`action is not supported by the DBMS`) ErrUnsupportedDestination = errors.New(`unsupported destination type`) ErrUnsupportedType = errors.New(`type does not support marshaling`) ErrUnsupportedValue = errors.New(`value does not support unmarshaling`) ErrNilItem = errors.New(`invalid item (nil)`) ErrZeroItemID = errors.New(`item ID is not defined`) ErrMissingPrimaryKeys = errors.New(`collection has no primary keys`) ErrWarnSlowQuery = errors.New(`slow query`) )
Error messages
Functions ¶
func RegisterAdapter ¶
RegisterAdapter registers a generic database adapter.
Types ¶
type Adapter ¶
type Adapter interface {
Open(ConnectionURL) (Session, error)
}
Adapter interface defines an adapter
func LookupAdapter ¶
LookupAdapter returns a previously registered adapter by name.
type AfterCreateHook ¶
AfterCreateHook is an interface that defines an AfterCreate function for models that is called after creating an item. If AfterCreate returns an error the create process is rolled back.
type AfterDeleteHook ¶
AfterDeleteHook is an interface that defines a AfterDelete function for models that is called after removing an item. If AfterDelete returns an error the delete process is rolled back.
type AfterUpdateHook ¶
AfterUpdateHook is an interface that defines an AfterUpdate function for models that is called after updating an item. If AfterUpdate returns an error the update process is rolled back.
type AndExpr ¶
type AndExpr struct {
*adapter.LogicalExprGroup
}
AndExpr represents an expression joined by a logical conjuction (AND).
func And ¶
func And(conds ...LogicalExpr) *AndExpr
And joins conditions under logical conjunction. Conditions can be represented by `db.Cond{}`, `db.Or()` or `db.And()`.
Examples:
// name = "Peter" AND last_name = "Parker"
db.And(
db.Cond{"name": "Peter"},
db.Cond{"last_name": "Parker "},
)
// (name = "Peter" OR name = "Mickey") AND last_name = "Mouse"
db.And(
db.Or(
db.Cond{"name": "Peter"},
db.Cond{"name": "Mickey"},
),
db.Cond{"last_name": "Mouse"},
)
func (*AndExpr) And ¶
func (a *AndExpr) And(andConds ...LogicalExpr) *AndExpr
And adds more expressions to the group.
type BeforeCreateHook ¶
BeforeCreateHook is an interface that defines an BeforeCreate function for models that is called before creating an item. If BeforeCreate returns an error the create process is rolled back.
type BeforeDeleteHook ¶
BeforeDeleteHook is an interface that defines a BeforeDelete function for models that is called before removing an item. If BeforeDelete returns an error the delete process is rolled back.
type BeforeUpdateHook ¶
BeforeUpdateHook is an interface that defines a BeforeUpdate function for models that is called before updating an item. If BeforeUpdate returns an error the update process is rolled back.
type Collection ¶
type Collection interface {
// Name returns the name of the collection.
Name() string
// Session returns the Session that was used to create the collection
// reference.
Session() Session
// Find defines a new result set.
Find(...interface{}) Result
Count() (uint64, error)
// Insert inserts a new item into the collection, the type of this item could
// be a map, a struct or pointer to either of them. If the call succeeds and
// if the collection has a primary key, Insert returns the ID of the newly
// added element as an `interface{}`. The underlying type of this ID depends
// on both the database adapter and the column storing the ID. The ID
// returned by Insert() could be passed directly to Find() to retrieve the
// newly added element.
Insert(interface{}) (*InsertResult, error)
// InsertReturning is like Insert() but it takes a pointer to map or struct
// and, if the operation succeeds, updates it with data from the newly
// inserted row. If the database does not support transactions this method
// returns db.ErrUnsupported.
InsertReturning(interface{}) error
// UpdateReturning takes a pointer to a map or struct and tries to update the
// row the item is refering to. If the element is updated sucessfully,
// UpdateReturning will fetch the row and update the fields of the passed
// item. If the database does not support transactions this method returns
// db.ErrUnsupported
UpdateReturning(interface{}) error
// Exists returns true if the collection exists, false otherwise.
Exists() (bool, error)
// Truncate removes all elements on the collection.
Truncate() error
}
Collection defines methods to work with database tables or collections.
type Comparison ¶
type Comparison struct {
*adapter.Comparison
}
Comparison represents a relationship between values.
func After ¶
func After(value time.Time) *Comparison
After is a comparison that means: is after the (time.Time) value.
func Before ¶
func Before(value time.Time) *Comparison
Before is a comparison that means: is before the (time.Time) value.
func Between ¶
func Between(lowerBound interface{}, upperBound interface{}) *Comparison
Between is a comparison that means: is between lowerBound and upperBound.
func Gt ¶
func Gt(value interface{}) *Comparison
Gt is a comparison that means: is greater than value.
func Gte ¶
func Gte(value interface{}) *Comparison
Gte is a comparison that means: is greater than or equal to value.
func In ¶
func In(value ...interface{}) *Comparison
In is a comparison that means: is any of the values.
func Is ¶
func Is(value interface{}) *Comparison
Is is a comparison that means: is equivalent to nil, true or false.
func IsNot ¶
func IsNot(value interface{}) *Comparison
IsNot is a comparison that means: is not equivalent to nil, true nor false.
func IsNotNull ¶
func IsNotNull() *Comparison
IsNotNull is a comparison that means: is not equivalent to nil.
func Like ¶
func Like(value string) *Comparison
Like is a comparison that checks whether the reference matches the wildcard value.
func Lte ¶
func Lte(value interface{}) *Comparison
Lte is a comparison that means: is less than or equal to value.
func NotBetween ¶
func NotBetween(lowerBound interface{}, upperBound interface{}) *Comparison
NotBetween is a comparison that means: is not between lowerBound and upperBound.
func NotEq ¶
func NotEq(value interface{}) *Comparison
NotEq is a comparison that means: is not equal to value.
func NotIn ¶
func NotIn(value ...interface{}) *Comparison
NotIn is a comparison that means: is none of the values.
func NotLike ¶
func NotLike(value string) *Comparison
NotLike is a comparison that checks whether the reference does not match the wildcard value.
func NotRegExp ¶
func NotRegExp(value string) *Comparison
NotRegExp is a comparison that checks whether the reference does not match the regular expression.
func OnOrAfter ¶
func OnOrAfter(value time.Time) *Comparison
OnOrAfter is a comparison that means: is on or after the (time.Time) value.
func OnOrBefore ¶
func OnOrBefore(value time.Time) *Comparison
OnOrBefore is a comparison that means: is on or before the (time.Time) value.
func Op ¶
func Op(customOperator string, value interface{}) *Comparison
Op returns a custom comparison operator.
func RegExp ¶
func RegExp(value string) *Comparison
RegExp is a comparison that checks whether the reference matches the regular expression.
type Cond ¶
type Cond map[interface{}]interface{}
Cond is a map that defines conditions for a query.
Each entry of the map represents a condition (a column-value relation bound by a comparison Operator). The comparison can be specified after the column name, if no comparison operator is provided the equality operator is used as default.
Examples:
// Age equals 18.
db.Cond{"age": 18}
// Age is greater than or equal to 18.
db.Cond{"age >=": 18}
// id is any of the values 1, 2 or 3.
db.Cond{"id IN": []{1, 2, 3}}
// Age is lower than 18 (MongoDB syntax)
db.Cond{"age $lt": 18}
// age > 32 and age < 35
db.Cond{"age >": 32, "age <": 35}
func (Cond) Constraints ¶
func (c Cond) Constraints() []adapter.Constraint
Constraints returns each one of the Cond map entires as a constraint.
func (Cond) Expressions ¶
func (c Cond) Expressions() []LogicalExpr
Expressions returns all the expressions contained in the condition.
func (Cond) Operator ¶
func (c Cond) Operator() LogicalOperator
Operator returns the equality operator.
type ConnectionURL ¶
type ConnectionURL interface {
// String returns the connection string that is going to be passed to the
// adapter.
String() string
}
ConnectionURL represents a data source name (DSN).
type HasSave ¶
HasSave is an interface that defines an (optional) Save function for models that is called when persisting an item (creating or updating). If Save is not defined, bond will attempt to either create or update the item based on whether the values for item's primary key are defined.
type InsertResult ¶
type InsertResult struct {
// contains filtered or unexported fields
}
func NewInsertResult ¶
func NewInsertResult(id interface{}) *InsertResult
func (*InsertResult) ID ¶
func (r *InsertResult) ID() ID
type Item ¶
type Item interface {
Save(Session) error
Delete(Session) error
Update(Session, M) error
Changes() M
}
Item provides methods for
type Logger ¶
type Logger interface {
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
Print(v ...interface{})
Printf(format string, v ...interface{})
Panic(v ...interface{})
Panicf(format string, v ...interface{})
}
Logger
type LoggingCollector ¶
type LoggingCollector interface {
Enabled(LogLevel) bool
Level() LogLevel
SetLogger(Logger)
SetLevel(LogLevel)
Trace(v ...interface{})
Tracef(format string, v ...interface{})
Debug(v ...interface{})
Debugf(format string, v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Warn(v ...interface{})
Warnf(format string, v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
Panic(v ...interface{})
Panicf(format string, v ...interface{})
}
LoggingCollector represents a logging collector.
func Log ¶
func Log() LoggingCollector
type LogicalExpr ¶
type LogicalExpr = adapter.LogicalExpr
LogicalExpr represents an expression to be used in logical statements.
type LogicalOperator ¶
type LogicalOperator = adapter.LogicalOperator
LogicalOperator represents a logical operation.
type Marshaler ¶
type Marshaler interface {
// MarshalDB returns the internal database representation of the Go value.
MarshalDB() (interface{}, error)
}
Marshaler is the interface implemented by struct fields that can transform themselves into values to be stored in a database.
type Model ¶
type Model interface {
Collection(sess Session) Collection
}
Model is the equivalence between concrete database schemas and Go values.
type OrExpr ¶
type OrExpr struct {
*adapter.LogicalExprGroup
}
OrExpr represents a logical expression joined by logical disjunction (OR).
func Or ¶
func Or(conds ...LogicalExpr) *OrExpr
Or joins conditions under logical disjunction. Conditions can be represented by `db.Cond{}`, `db.Or()` or `db.And()`.
Example:
// year = 2012 OR year = 1987
db.Or(
db.Cond{"year": 2012},
db.Cond{"year": 1987},
)
func (*OrExpr) Or ¶
func (o *OrExpr) Or(orConds ...LogicalExpr) *OrExpr
Or adds more expressions to the group.
type Result ¶
type Result interface {
// String returns the SQL statement to be used in the query.
String() string
// Limit defines the maximum number of results for this set. It only has
// effect on `One()`, `All()` and `Next()`. A negative limit cancels any
// previous limit settings.
Limit(int) Result
// Offset ignores the first n results. It only has effect on `One()`, `All()`
// and `Next()`. A negative offset cancels any previous offset settings.
Offset(int) Result
// OrderBy receives one or more field names that define the order in which
// elements will be returned in a query, field names may be prefixed with a
// minus sign (-) indicating descending order, ascending order will be used
// otherwise.
OrderBy(...interface{}) Result
// Select defines specific columns to be fetched on every column in the
// result set.
Select(...interface{}) Result
// And adds more filtering conditions on top of the existing constraints.
//
// res := col.Find(...).And(...)
And(...interface{}) Result
// GroupBy is used to group results that have the same value in the same column
// or columns.
GroupBy(...interface{}) Result
// Delete deletes all items within the result set. `Offset()` and `Limit()`
// are not honoured by `Delete()`.
Delete() error
// Update modifies all items within the result set. `Offset()` and `Limit()`
// are not honoured by `Update()`.
Update(interface{}) error
// Count returns the number of items that match the set conditions.
// `Offset()` and `Limit()` are not honoured by `Count()`
Count() (uint64, error)
// Exists returns true if at least one item on the collection exists. False
// otherwise.
Exists() (bool, error)
// Next fetches the next result within the result set and dumps it into the
// given pointer to struct or pointer to map. You must call
// `Close()` after finishing using `Next()`.
Next(ptrToStruct interface{}) bool
// Err returns the last error that has happened with the result set, nil
// otherwise.
Err() error
// One fetches the first result within the result set and dumps it into the
// given pointer to struct or pointer to map. The result set is automatically
// closed after picking the element, so there is no need to call Close()
// after using One().
One(ptrToStruct interface{}) error
// All fetches all results within the result set and dumps them into the
// given pointer to slice of maps or structs. The result set is
// automatically closed, so there is no need to call Close() after
// using All().
All(sliceOfStructs interface{}) error
// Paginate splits the results of the query into pages containing pageSize
// items. When using pagination previous settings for `Limit()` and
// `Offset()` are ignored. Page numbering starts at 1.
//
// Use `Page()` to define the specific page to get results from.
//
// Example:
//
// r = q.Paginate(12)
//
// You can provide constraints an order settings when using pagination:
//
// Example:
//
// res := q.Where(conds).OrderBy("-id").Paginate(12)
// err := res.Page(4).All(&items)
Paginate(pageSize uint) Result
// Page makes the result set return results only from the page identified by
// pageNumber. Page numbering starts from 0.
//
// Example:
//
// r = q.Paginate(12).Page(4)
Page(pageNumber uint) Result
// Cursor defines the column that is going to be taken as basis for
// cursor-based pagination.
//
// Example:
//
// a = q.Paginate(10).Cursor("id")
// b = q.Paginate(12).Cursor("-id")
//
// You can set "" as cursorColumn to disable cursors.
Cursor(cursorColumn string) Result
// NextPage returns the next results page according to the cursor. It expects
// a cursorValue, which is the value the cursor column had on the last item
// of the current result set (lower bound).
//
// Example:
//
// cursor = q.Paginate(12).Cursor("id")
// res = cursor.NextPage(items[len(items)-1].ID)
//
// Note that `NextPage()` requires a cursor, any column with an absolute
// order (given two values one always precedes the other) can be a cursor.
//
// You can define the pagination order and add constraints to your result:
//
// cursor = q.Where(...).OrderBy("id").Paginate(10).Cursor("id")
// res = cursor.NextPage(lowerBound)
NextPage(cursorValue interface{}) Result
// PrevPage returns the previous results page according to the cursor. It
// expects a cursorValue, which is the value the cursor column had on the
// fist item of the current result set.
//
// Example:
//
// current = current.PrevPage(items[0].ID)
//
// Note that PrevPage requires a cursor, any column with an absolute order
// (given two values one always precedes the other) can be a cursor.
//
// You can define the pagination order and add constraints to your result:
//
// cursor = q.Where(...).OrderBy("id").Paginate(10).Cursor("id")
// res = cursor.PrevPage(upperBound)
PrevPage(cursorValue interface{}) Result
// TotalPages returns the total number of pages the result set could produce.
// If no pagination parameters have been set this value equals 1.
TotalPages() (uint, error)
// TotalEntries returns the total number of matching items in the result set.
TotalEntries() (uint64, error)
// Close closes the result set and frees all locked resources.
Close() error
}
Result is an interface that defines methods for result sets.
type Session ¶
type Session interface {
// ConnectionURL returns the DSN that was used to set up the adapter.
ConnectionURL() ConnectionURL
// Name returns the name of the database.
Name() string
// Ping returns an error if the DBMS could not be reached.
Ping() error
// Collection receives a table name and returns a collection reference. The
// information retrieved from a collection is cached.
Collection(name string) Collection
// Collections returns a collection reference of all non system tables on the
// database.
Collections() ([]Collection, error)
Save(model Model) error
Get(model Model, id interface{}) error
// Reset resets all the caching mechanisms the adapter is using.
Reset()
// Close terminates the currently active connection to the DBMS and clears
// all caches.
Close() error
// Driver returns the underlying driver of the adapter as an interface.
//
// In order to actually use the driver, the `interface{}` value needs to be
// casted into the appropriate type.
//
// Example:
// internalSQLDriver := sess.Driver().(*sql.DB)
Driver() interface{}
Settings
}
Session is an interface that defines methods for database adapters.
type Settings ¶
type Settings interface {
// SetPreparedStatementCache enables or disables the prepared statement
// cache.
SetPreparedStatementCache(bool)
// PreparedStatementCacheEnabled returns true if the prepared statement cache
// is enabled, false otherwise.
PreparedStatementCacheEnabled() bool
// SetConnMaxLifetime sets the default maximum amount of time a connection
// may be reused.
SetConnMaxLifetime(time.Duration)
// ConnMaxLifetime returns the default maximum amount of time a connection
// may be reused.
ConnMaxLifetime() time.Duration
// SetMaxIdleConns sets the default maximum number of connections in the idle
// connection pool.
SetMaxIdleConns(int)
// MaxIdleConns returns the default maximum number of connections in the idle
// connection pool.
MaxIdleConns() int
// SetMaxOpenConns sets the default maximum number of open connections to the
// database.
SetMaxOpenConns(int)
// MaxOpenConns returns the default maximum number of open connections to the
// database.
MaxOpenConns() int
}
Settings defines methods to get or set configuration values.
var DefaultSettings Settings = &settings{ preparedStatementCacheEnabled: 0, connMaxLifetime: time.Duration(0), maxIdleConns: 10, maxOpenConns: 0, }
DefaultSettings provides default global configuration settings for database sessions.
func NewSettings ¶
func NewSettings() Settings
NewSettings returns a new settings value prefilled with the current default settings.
type Tx ¶
type Tx interface {
// Rollback discards all the operations executed on the current transaction.
Rollback() error
// Commit commits the current transaction.
Commit() error
}
Tx defines methods for transactions.
type Unmarshaler ¶
type Unmarshaler interface {
// UnmarshalDB receives an internal database representation of a value and
// transforms it into a Go value.
UnmarshalDB(interface{}) error
}
Unmarshaler is the interface implemented by struct fields that can transform themselves from database values into Go values.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
adapter
|
|
|
cockroachdb
Package cockroachdb wraps the github.com/lib/pq driver and provides a compatibility later with CockroachDB.
|
Package cockroachdb wraps the github.com/lib/pq driver and provides a compatibility later with CockroachDB. |
|
mongo
Package mongo wraps the gopkg.in/mgo.v2 MongoDB driver.
|
Package mongo wraps the gopkg.in/mgo.v2 MongoDB driver. |
|
mssql
Package mssql wraps the github.com/go-sql-driver/mssql MySQL driver.
|
Package mssql wraps the github.com/go-sql-driver/mssql MySQL driver. |
|
mysql
Package mysql wraps the github.com/go-sql-driver/mysql MySQL driver.
|
Package mysql wraps the github.com/go-sql-driver/mysql MySQL driver. |
|
postgresql
Package postgresql wraps the github.com/lib/pq PostgreSQL driver.
|
Package postgresql wraps the github.com/lib/pq PostgreSQL driver. |
|
ql
Package ql wraps the modernc.org/ql/driver QL driver.
|
Package ql wraps the modernc.org/ql/driver QL driver. |
|
sqlite
Package sqlite wraps the github.com/lib/sqlite SQLite driver.
|
Package sqlite wraps the github.com/lib/sqlite SQLite driver. |
|
internal
|
|
|
reflectx
Package reflectx implements extensions to the standard reflect lib suitable for implementing marshaling and unmarshaling packages.
|
Package reflectx implements extensions to the standard reflect lib suitable for implementing marshaling and unmarshaling packages. |
|
sqladapter
Package sqladapter provides common logic for SQL adapters.
|
Package sqladapter provides common logic for SQL adapters. |
|
Package sqlbuilder provides tools for building custom SQL queries.
|
Package sqlbuilder provides tools for building custom SQL queries. |
