Documentation ¶
Overview ¶
Package db (or upper-db) provides a common interface to work with a variety of data sources using adapters that wrap mature database drivers.
Install upper-db:
go get upper.io/db.v3
Usage
package main import ( "log" "upper.io/db.v3/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) } }
See more usage examples and documentation for users at https://upper.io/db.v3.
Index ¶
- Constants
- Variables
- func RegisterAdapter(name string, adapter *AdapterFuncMap)
- type AdapterFuncMap
- type Collection
- type Comparison
- func After(t time.Time) Comparison
- func Before(t time.Time) Comparison
- func Between(a interface{}, b interface{}) Comparison
- func Eq(v interface{}) Comparison
- func Gt(v interface{}) Comparison
- func Gte(v interface{}) Comparison
- func In(v interface{}) Comparison
- func Is(v interface{}) Comparison
- func IsNot(v interface{}) Comparison
- func IsNotNull() Comparison
- func IsNull() Comparison
- func Like(v string) Comparison
- func Lt(v interface{}) Comparison
- func Lte(v interface{}) Comparison
- func NotBetween(a interface{}, b interface{}) Comparison
- func NotEq(v interface{}) Comparison
- func NotIn(v interface{}) Comparison
- func NotLike(v string) Comparison
- func NotRegExp(v string) Comparison
- func OnOrAfter(t time.Time) Comparison
- func OnOrBefore(t time.Time) Comparison
- func Op(customOperator string, v interface{}) Comparison
- func RegExp(v string) Comparison
- type ComparisonOperator
- type Compound
- type CompoundOperator
- type Cond
- type ConnectionURL
- type Constraint
- type Constraints
- type Database
- type Function
- type Intersection
- func (a *Intersection) And(andConds ...Compound) *Intersection
- func (c Intersection) Base() interface{}
- func (a *Intersection) Empty() bool
- func (c Intersection) Fn(in interface{}) error
- func (a *Intersection) Operator() CompoundOperator
- func (c Intersection) Prev() immutable.Immutable
- func (c Intersection) Sentences() []Compound
- type Logger
- type Marshaler
- type QueryStatus
- type RawValue
- type Result
- type Settings
- type Tx
- type Union
- type Unmarshaler
Constants ¶
const (
EnvEnableDebug = `UPPERIO_DB_DEBUG`
)
EnvEnableDebug can be used by adapters to determine if the user has enabled debugging.
If the user sets the `UPPERIO_DB_DEBUG` environment variable to a non-empty value, all generated statements will be printed at runtime to the standard logger.
Example:
UPPERIO_DB_DEBUG=1 go test UPPERIO_DB_DEBUG=1 ./go-program
Variables ¶
var ( ErrNoMoreRows = errors.New(`upper: no more rows in this result set`) ErrNotConnected = errors.New(`upper: not connected to a database`) ErrMissingDatabaseName = errors.New(`upper: missing database name`) ErrMissingCollectionName = errors.New(`upper: missing collection name`) ErrCollectionDoesNotExist = errors.New(`upper: collection does not exist`) ErrSockerOrHost = errors.New(`upper: you may connect either to a unix socket or a tcp address, but not both`) ErrQueryLimitParam = errors.New(`upper: a query can accept only one limit parameter`) ErrQuerySortParam = errors.New(`upper: a query can accept only one order by parameter`) ErrQueryOffsetParam = errors.New(`upper: a query can accept only one offset parameter`) ErrMissingConditions = errors.New(`upper: missing selector conditions`) ErrUnsupported = errors.New(`upper: this action is currently unsupported on this database`) ErrUndefined = errors.New(`upper: this value is undefined`) ErrQueryIsPending = errors.New(`upper: can't execute this instruction while the result set is still open`) ErrUnsupportedDestination = errors.New(`upper: unsupported destination type`) ErrUnsupportedType = errors.New(`upper: this type does not support marshaling`) ErrUnsupportedValue = errors.New(`upper: this value does not support unmarshaling`) ErrUnknownConditionType = errors.New(`upper: arguments of type %T can't be used as constraints`) ErrTooManyClients = errors.New(`upper: can't connect to database server: too many clients`) ErrGivingUpTryingToConnect = errors.New(`upper: giving up trying to connect: too many clients`) ErrMissingConnURL = errors.New(`upper: missing DSN`) ErrNotImplemented = errors.New(`upper: call not implemented`) ErrAlreadyWithinTransaction = errors.New(`upper: already within a transaction`) )
Error messages.
Functions ¶
func RegisterAdapter ¶
func RegisterAdapter(name string, adapter *AdapterFuncMap)
RegisterAdapter registers a generic Database adapter. This function must be called from adapter packages upon initialization.
Types ¶
type AdapterFuncMap ¶
type AdapterFuncMap struct {
Open func(settings ConnectionURL) (Database, error)
}
AdapterFuncMap defines functions that need to be implemented by adapters.
type Collection ¶
type Collection interface { // Insert inserts a new item into the collection, it accepts one argument // that can be either a map or a struct. If the call succeeds, it returns the // ID of the newly added element as an `interface{}` (the actual type of this // ID depends on both the database adapter and the column that stores this // ID). The ID returned by Insert() could be passed directly to Find() to // retrieve the newly added element. Insert(interface{}) (interface{}, error) // InsertReturning is like Insert() but it updates the passed map or struct // with the newly inserted element (and with automatic fields, like IDs, // timestamps, etc). This is all done atomically within a transaction. If // the database does not support transactions this method returns // db.ErrUnsupported. InsertReturning(interface{}) error // UpdateReturning takes a pointer to map or struct and tries to update the // given item on the collection based on the item's primary keys. Once the // element is updated, UpdateReturning will query the element that was just // updated. 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 // Find defines a new result set with elements from the collection. Find(...interface{}) Result // Truncate removes all elements on the collection and resets the // collection's IDs. Truncate() error // Name returns the name of the collection. Name() string }
Collection is an interface that defines methods useful for handling tables.
type Comparison ¶
type Comparison interface { Operator() ComparisonOperator Value() interface{} }
Comparison defines methods for representing comparison operators in a portable way across databases.
func After ¶
func After(t time.Time) Comparison
After indicates whether the reference is after the given time.
func Before ¶
func Before(t time.Time) Comparison
Before indicates whether the reference is before the given time.
func Between ¶
func Between(a interface{}, b interface{}) Comparison
Between indicates whether the reference is contained between the two given values.
func Eq ¶
func Eq(v interface{}) Comparison
Eq indicates whether the constraint is equal to the given argument.
func Gt ¶
func Gt(v interface{}) Comparison
Gt indicates whether the constraint is greater than the given argument.
func Gte ¶
func Gte(v interface{}) Comparison
Gte indicates whether the reference is greater than or equal to the given argument.
func In ¶
func In(v interface{}) Comparison
In indicates whether the argument is part of the reference.
func Is ¶
func Is(v interface{}) Comparison
Is indicates whether the reference is nil, true or false.
func IsNot ¶
func IsNot(v interface{}) Comparison
IsNot indicates whether the reference is not nil, true nor false.
func IsNotNull ¶
func IsNotNull() Comparison
IsNotNull indicates whether the reference is a NULL value.
func Like ¶
func Like(v string) Comparison
Like indicates whether the reference matches the wildcard value.
func Lt ¶
func Lt(v interface{}) Comparison
Lt indicates whether the constraint is less than the given argument.
func Lte ¶
func Lte(v interface{}) Comparison
Lte indicates whether the reference is less than or equal to the given argument.
func NotBetween ¶
func NotBetween(a interface{}, b interface{}) Comparison
NotBetween indicates whether the reference is not contained between the two given values.
func NotEq ¶
func NotEq(v interface{}) Comparison
NotEq indicates whether the constraint is not equal to the given argument.
func NotIn ¶
func NotIn(v interface{}) Comparison
NotIn indicates whether the argument is not part of the reference.
func NotLike ¶
func NotLike(v string) Comparison
NotLike indicates whether the reference does not match the wildcard value.
func NotRegExp ¶
func NotRegExp(v string) Comparison
NotRegExp indicates whether the reference does not match the regexp pattern.
func OnOrAfter ¶
func OnOrAfter(t time.Time) Comparison
OnOrAfter indicater whether the reference is after or equal to the given time value.
func OnOrBefore ¶
func OnOrBefore(t time.Time) Comparison
OnOrBefore indicates whether the reference is before or equal to the given time value.
func Op ¶
func Op(customOperator string, v interface{}) Comparison
Op represents a custom comparison operator against the reference.
func RegExp ¶
func RegExp(v string) Comparison
RegExp indicates whether the reference matches the regexp pattern.
type ComparisonOperator ¶
type ComparisonOperator uint8
ComparisonOperator is a type we use to label comparison operators.
const ( ComparisonOperatorNone ComparisonOperator = iota ComparisonOperatorEqual ComparisonOperatorNotEqual ComparisonOperatorLessThan ComparisonOperatorGreaterThan ComparisonOperatorLessThanOrEqualTo ComparisonOperatorGreaterThanOrEqualTo ComparisonOperatorBetween ComparisonOperatorNotBetween ComparisonOperatorIn ComparisonOperatorNotIn ComparisonOperatorIs ComparisonOperatorIsNot ComparisonOperatorLike ComparisonOperatorNotLike ComparisonOperatorRegExp ComparisonOperatorNotRegExp ComparisonOperatorAfter ComparisonOperatorBefore ComparisonOperatorOnOrAfter ComparisonOperatorOnOrBefore )
Comparison operators
type Compound ¶
type Compound interface { // Sentences returns child sentences. Sentences() []Compound // Operator returns the operator that joins the compound's child sentences. Operator() CompoundOperator // Empty returns true if the compound has zero children, false otherwise. Empty() bool }
Compound represents an statement that has one or many sentences joined by by an operator like "AND" or "OR". This is an exported interface but it was designed for internal usage, you may want to use the `db.And()` or `db.Or()` functions instead.
type CompoundOperator ¶
type CompoundOperator uint
CompoundOperator represents the operation on a compound statement.
const ( OperatorNone CompoundOperator = iota OperatorAnd OperatorOr )
Compound operators.
type Cond ¶
type Cond map[interface{}]interface{}
Cond is a map that defines conditions for a query and satisfies the Constraints and Compound interfaces.
Each entry of the map represents a condition (a column-value relation bound by a comparison operator). The comparison operator is optional and can be specified after the column name, if no comparison operator is provided the equality operator is used as default.
Examples:
// Where age equals 18. db.Cond{"age": 18} // // Where age is greater than or equal to 18. db.Cond{"age >=": 18} // Where id is in a list of ids. db.Cond{"id IN": []{1, 2, 3}} // Where age is lower than 18 (you could use this syntax when using // mongodb). db.Cond{"age $lt": 18} // Where age > 32 and age < 35 db.Cond{"age >": 32, "age <": 35}
func (Cond) Constraints ¶
func (c Cond) Constraints() []Constraint
Constraints returns each one of the Cond map records as a constraint.
func (Cond) Keys ¶
func (c Cond) Keys() []interface{}
Keys returns the keys of this map sorted by name.
func (Cond) Operator ¶
func (c Cond) Operator() CompoundOperator
Operator returns the default compound 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 connection string.
type Constraint ¶
type Constraint interface { // Key is the leftmost part of the constraint and usually contains a column // name. Key() interface{} // Value if the rightmost part of the constraint and usually contains a // column value. Value() interface{} }
Constraint interface represents a single condition, like "a = 1". where `a` is the key and `1` is the value. This is an exported interface but it's rarely used directly, you may want to use the `db.Cond{}` map instead.
func NewConstraint ¶
func NewConstraint(key interface{}, value interface{}) Constraint
NewConstraint creates a constraint.
type Constraints ¶
type Constraints interface { // Constraints returns an array of constraints. Constraints() []Constraint // Keys returns the map keys always in the same order. Keys() []interface{} }
Constraints interface represents an array or constraints, like "a = 1, b = 2, c = 3".
type Database ¶
type Database interface { // Driver returns the underlying driver the wrapper uses 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{} // Open attempts to establish a connection with a DBMS. Open(ConnectionURL) error // Ping returns an error if the database manager could not be reached. Ping() error // Close closes the currently active connection to the database and clears // caches. Close() error // Collection returns a collection reference given a table name. Collection(string) Collection // Collections returns the names of all non-system tables on the database. Collections() ([]string, error) // Name returns the name of the active database. Name() string // ConnectionURL returns the data used to set up the adapter. ConnectionURL() ConnectionURL // ClearCache clears all the cache mechanisms the adapter is using. ClearCache() Settings }
Database is an interface that defines methods that must be satisfied by all database adapters.
type Function ¶
type Function interface { // Name returns the function name. Name() string // Argument returns the function arguments. Arguments() []interface{} }
Function interface defines methods for representing database functions. This is an exported interface but it's rarely used directly, you may want to use the `db.Func()` function instead.
type Intersection ¶
type Intersection struct {
// contains filtered or unexported fields
}
Intersection represents a compound joined by AND.
func And ¶
func And(conds ...Compound) *Intersection
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 (*Intersection) And ¶
func (a *Intersection) And(andConds ...Compound) *Intersection
And adds more terms to the compound.
func (*Intersection) Empty ¶
func (a *Intersection) Empty() bool
Empty returns false if this struct holds no conditions.
func (*Intersection) Operator ¶
func (a *Intersection) Operator() CompoundOperator
Operator returns the AND operator.
type Logger ¶
type Logger interface {
Log(*QueryStatus)
}
Logger represents a logging collector. You can pass a logging collector to db.DefaultSettings.SetLogger(myCollector) to make it collect db.QueryStatus messages after executing a query.
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 that can be stored on a database.
type QueryStatus ¶
type QueryStatus struct { SessID uint64 TxID uint64 RowsAffected *int64 LastInsertID *int64 Query string Args []interface{} Err error Start time.Time End time.Time Context context.Context }
QueryStatus represents the status of a query after being executed.
func (*QueryStatus) String ¶
func (q *QueryStatus) String() string
String returns a formatted log message.
type RawValue ¶
type RawValue interface { fmt.Stringer Compound // Raw returns the string representation of the value that the user wants to // pass without any escaping. Raw() string // Arguments returns the arguments to be replaced on the query. Arguments() []interface{} }
RawValue interface represents values that can bypass SQL filters. This is an exported interface but it's rarely used directly, you may want to use the `db.Raw()` function instead.
type Result ¶
type Result interface { // String satisfies fmt.Stringer and returns a SELECT statement for // the result. 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 returned from the elements of the // set. Select(...interface{}) Result // Where discards all the previously set filtering constraints (if any) and // sets new ones. Commonly used when the conditions of the result depend on // external parameters that are yet to be evaluated: // // res := col.Find() // // if ... { // res.Where(...) // } else { // res.Where(...) // } Where(...interface{}) Result // And adds more filtering conditions on top of the existing constraints. // // res := col.Find(...).And(...) And(...interface{}) Result // Group is used to group results that have the same value in the same column // or columns. Group(...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 (upper bound). // // 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 could produce. If // no pagination has been set this value equals 1. TotalPages() (uint, error) // TotalEntries returns the total number of entries in the query. TotalEntries() (uint64, error) // Close closes the result set and frees all locked resources. Close() error }
Result is an interface that defines methods which are useful for working with result sets.
type Settings ¶
type Settings interface { // SetLogging enables or disables logging. SetLogging(bool) // LoggingEnabled returns true if logging is enabled, false otherwise. LoggingEnabled() bool // SetLogger defines which logger to use. SetLogger(Logger) // Returns the currently configured logger. Logger() Logger // 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 instructions on the current transaction. Rollback() error // Commit commits the current transaction. Commit() error }
Tx has methods for transactions that can be either committed or rolled back.
type Union ¶
type Union struct {
// contains filtered or unexported fields
}
Union represents a compound joined by OR.
func Or ¶
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 (*Union) Operator ¶
func (o *Union) Operator() CompoundOperator
Operator returns the OR operator.
type Unmarshaler ¶
type Unmarshaler interface { // UnmarshalDB receives an internal database representation of a value and // must transform that into a Go value. UnmarshalDB(interface{}) error }
Unmarshaler is the interface implemented by struct fields that can transform themselves from stored database values into Go values.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
internal
|
|
sqladapter
Package sqladapter provides common logic for SQL adapters.
|
Package sqladapter provides common logic for SQL adapters. |
lib
|
|
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. |
sqlbuilder
Package sqlbuilder provides tools for building custom SQL queries.
|
Package sqlbuilder provides tools for building custom SQL queries. |
Package mongo wraps the gopkg.in/mgo.v2 MongoDB driver.
|
Package mongo wraps the gopkg.in/mgo.v2 MongoDB driver. |
Package mssql wraps the github.com/go-sql-driver/mssql MySQL driver.
|
Package mssql wraps the github.com/go-sql-driver/mssql MySQL driver. |
Package mysql wraps the github.com/go-sql-driver/mysql MySQL driver.
|
Package mysql wraps the github.com/go-sql-driver/mysql MySQL driver. |
Package postgresql wraps the github.com/lib/pq PostgreSQL driver.
|
Package postgresql wraps the github.com/lib/pq PostgreSQL driver. |
Package ql wraps the modernc.org/ql/driver QL driver.
|
Package ql wraps the modernc.org/ql/driver QL driver. |
Package sqlite wraps the github.com/lib/sqlite SQLite driver.
|
Package sqlite wraps the github.com/lib/sqlite SQLite driver. |