db: upper.io/db Index | Files | Directories

package db

import "upper.io/db"

Package db provides a single interface for interacting with different data sources through the use of adapters that wrap well-known database drivers.

As of today, `upper.io/db` fully supports MySQL, PostgreSQL and SQLite (CRUD + Transactions) and provides partial support for MongoDB and QL (CRUD only).

Usage:

import(
	// Main package.
	"upper.io/db"
	// PostgreSQL adapter.
	"upper.io/db/postgresql"
)

`upper.io/db` is not an ORM and thus does not impose any hard restrictions on data structures:

// This code works the same for all supported databases.
var people []Person
res = col.Find(db.Cond{"name": "Max"}).Limit(2).Sort("-input")
err = res.All(&people)

Index

Package Files

error.go main.go net.go settings.go wrapper.go

Constants

const EnvEnableDebug = `UPPERIO_DB_DEBUG`

EnvEnableDebug may 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 (
    ErrExpectingPointer        = errors.New(`Argument must be an address.`)
    ErrExpectingSlicePointer   = errors.New(`Argument must be a slice address.`)
    ErrExpectingSliceMapStruct = errors.New(`Argument must be a slice address of maps or structs.`)
    ErrExpectingMapOrStruct    = errors.New(`Argument must be either a map or a struct.`)
    ErrNoMoreRows              = errors.New(`There are no more rows in this result set.`)
    ErrNotConnected            = errors.New(`You're currently not connected.`)
    ErrMissingDatabaseName     = errors.New(`Missing database name.`)
    ErrMissingCollectionName   = errors.New(`Missing collection name.`)
    ErrCollectionDoesNotExist  = errors.New(`Collection does not exist.`)
    ErrSockerOrHost            = errors.New(`You may connect either to a unix socket or a tcp address, but not both.`)
    ErrQueryLimitParam         = errors.New(`A query can accept only one db.Limit() parameter.`)
    ErrQuerySortParam          = errors.New(`A query can accept only one db.Sort{} parameter.`)
    ErrQueryOffsetParam        = errors.New(`A query can accept only one db.Offset() parameter.`)
    ErrMissingConditions       = errors.New(`Missing selector conditions.`)
    ErrUnsupported             = errors.New(`This action is currently unsupported on this database.`)
    ErrUndefined               = errors.New(`This value is undefined.`)
    ErrQueryIsPending          = errors.New(`Can't execute this instruction while the result set is still open.`)
    ErrUnsupportedDestination  = errors.New(`Unsupported destination type.`)
    ErrUnsupportedType         = errors.New(`This type does not support marshaling.`)
    ErrUnsupportedValue        = errors.New(`This value does not support unmarshaling.`)
    ErrUnknownConditionType    = errors.New(`Arguments of type %s can't be used as constraints.`)
)

Shared error messages.

var ErrCollectionDoesNotExists = ErrCollectionDoesNotExist

Deprecated but kept for backwards compatibility. See: https://github.com/upper/db/issues/18

func Register Uses

func Register(name string, adapter Database)

Register associates an adapter's name with a type. Panics if the adapter name is empty or the adapter is nil.

type Address Uses

type Address interface {
    String() string
    Host() (string, error)
    Port() (uint, error)
    Path() (string, error)
}

Address is an interface that represents the host part of an URL.

func ParseAddress Uses

func ParseAddress(s string) Address

ParseAddress parses s into a host or socket structures.

type And Uses

type And []interface{}

And is an array of interfaces that is used to join two or more expressions under logical conjunction, it accepts `db.Cond{}`, `db.Or{}`, `db.Raw{}` and other `db.And{}` values.

Examples:

// SQL: name = "Peter" AND last_name = "Parker"
db.And (
	db.Cond { "name": "Peter" },
	db.Cond { "last_name": "Parker "},
)

// SQL: (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" },
}

type Collection Uses

type Collection interface {

    // Inserts a new item into the collection. Accepts a map or a struct as
    // argument.
    Append(interface{}) (interface{}, error)

    // Returns true if the collection exists.
    Exists() bool

    // Sets a filter on the collection with the given conditions and returns a
    // result set.
    Find(...interface{}) Result

    // Removes all elements on the collection and resets the IDs.
    Truncate() error

    // Returns the name of the collection.
    Name() string
}

Collection is an interface that defines methods for handling data sources or tables.

type Cond Uses

type Cond map[string]interface{}

Cond is a map used to define conditions passed to `db.Collection.Find()` and `db.Result.Where()`.

Examples:

// Where age equals 18.
db.Cond { "age": 18 }

Where age is greater than or equal to 18.
db.Cond { "age >=": 18 }

Where age is lower than 18 (On MongoDB context).
db.Cond { "age $lt": 18 }

type ConnectionURL Uses

type ConnectionURL interface {
    // String returns the connection string that is going to be passed to the
    // adapter.
    String() string
}

ConnectionURL is the interface that defines methods for connection strings.

type Constrainer Uses

type Constrainer interface {
    Constraint() Cond
}

Constrainer is the interface implemented by structs that can delimit themselves.

type Database Uses

type Database interface {
    // Driver() Returns the underlying driver the wrapper uses. As an
    // `interface{}`.
    //
    // In order to actually use the `interface{}` you must cast it to the known
    // database driver type.
    //
    // Example:
    //	internalSQLDriver := sess.Driver().(*sql.DB)
    Driver() interface{}

    // Open() attempts to stablish a connection with the database server, a
    // previous call to Setup() is required.
    Open() error

    // Clone() duplicates the current database session. Returns an error if the
    // clone could not be carried out.
    Clone() (Database, error)

    // Ping() returns error if the database server cannot be reached.
    Ping() error

    // Close() closes the currently active connection to the database.
    Close() error

    // Collection() returns a `db.Collection{}` struct by name. Some databases
    // support collections of more than one source or table, refer to the
    // documentation of the specific database adapter to see if using multiple
    // sources is supported.
    Collection(...string) (Collection, error)

    // Collections() returns the names of all non-system sources or tables within
    // the active database.
    Collections() ([]string, error)

    // Use() attempts to connect to another database using the same connection
    // settings. Similar to MySQL's `USE` instruction.
    Use(string) error

    // Drop() drops the active database.
    Drop() error

    // Setup() sets the database connection settings. In order to connect, a call
    // to `db.Database.Open()` is required.
    Setup(ConnectionURL) error

    // Name() returns the name of the active database.
    Name() string

    // Transaction() starts a transaction block. Some databases do not support
    // transactions, refer to the documentation of the specific database adapter
    // to see the current status on transactions.
    Transaction() (Tx, error)
}

Database is an interface that defines methods that must be provided by database adapters.

func Open Uses

func Open(adapter string, conn ConnectionURL) (Database, error)

Open configures a database session using the given adapter's name and the provided settings.

type Func Uses

type Func struct {
    Name string
    Args interface{}
}

Func is a struct that represents database functions.

Examples:

// MOD(29, 9)
db.Func{"MOD", []int{29, 9}}

// CONCAT("foo", "bar")
db.Func{"CONCAT", []string{"foo", "bar"}}

// NOW()
db.Func{"NOW"}

// RTRIM("Hello   ")
db.Func{"RTRIM", "Hello  "}

type HostAddr Uses

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

HostAddr is the name or IP of a server coupled with an optional port number.

func Host Uses

func Host(name string) HostAddr

Host converts the given name into a host structure.

func HostPort Uses

func HostPort(name string, port uint) HostAddr

HostPort converts the given name and port into a host structure.

func (HostAddr) Host Uses

func (h HostAddr) Host() (string, error)

Host returns the hostname/ip part of the host struct.

func (HostAddr) Path Uses

func (h HostAddr) Path() (string, error)

Path is undefined in a host struct.

func (HostAddr) Port Uses

func (h HostAddr) Port() (uint, error)

Port returns the port number of the host struct.

func (HostAddr) String Uses

func (h HostAddr) String() string

String returns the string representation of the host struct.

type IDSetter Uses

type IDSetter interface {
    SetID(map[string]interface{}) error
}

IDSetter is the interface implemented by structs that can set their own ID after calling Append().

type Int64IDSetter Uses

type Int64IDSetter interface {
    SetID(int64) error
}

Int64IDSetter implements a common pattern for setting int64 IDs.

type Marshaler Uses

type Marshaler interface {
    MarshalDB() (interface{}, error)
}

Marshaler is the interface implemented by structs that can marshal themselves into data suitable for storage.

type Or Uses

type Or []interface{}

Or is an array of interfaced that is used to join two or more expressions under logical disjunction, it accepts `db.Cond{}`, `db.And{}`, `db.Raw{}` and other `db.Or{}` values.

Example:

// SQL: year = 2012 OR year = 1987
db.Or {
	db.Cond{"year": 2012},
	db.Cond{"year": 1987},
}

type Raw Uses

type Raw struct {
    Value interface{}
}

Raw holds chunks of data to be passed to the database without any filtering. Use with care.

When using `db.Raw{}`, the developer is responsible of providing a sanitized instruction to the database.

The `db.Raw{}` expression is allowed as element on `db.Cond{}`, `db.And{}`, `db.Or{}` expressions and as argument on `db.Result.Select()` and `db.Collection.Find()` methods.

Example:

// SQL: SOUNDEX('Hello')
Raw{"SOUNDEX('Hello')"}

type Result Uses

type Result interface {

    // Limit() defines the maximum number of results in this set.
    Limit(uint) Result

    // Skip() ignores the first *n* results.
    Skip(uint) Result

    // Sort() receives 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 would be used by default.
    Sort(...interface{}) Result

    // Select() defines specific fields to be fulfilled on results in this result
    // set.
    Select(...interface{}) Result

    // Where() discards the initial filtering conditions and sets new ones.
    Where(...interface{}) Result

    // Group() is used to group results that have the same value in the same
    // column or columns.
    Group(...interface{}) Result

    // Remove() deletes all items within the result set.
    Remove() error

    // Update() modified all items within the result set. Receives an struct or
    // an interface{}.
    Update(interface{}) error

    // Count() returns the number of items that match the set conditions (Limit
    // and Offset settings are excluded from this query).
    Count() (uint64, 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 manually call Close()
    // after finishing using Next().
    Next(interface{}) error

    // One() fetches the first result within the result set and dumps it into the
    // given pointer to struct or pointer to map. Then it calls Close() to free
    // the result set.
    One(interface{}) error

    // All() fetches all results within the result set and dumps them into the
    // given pointer to slice of maps or structs. Then it calls Close() to free
    // the result set.
    All(interface{}) error

    // Close() closes the result set.
    Close() error
}

Result is an interface that defines methods for working with result sets.

type Settings Uses

type Settings struct {
    // Database server hostname or IP. This field is ignored if using unix
    // sockets or if the database does not require a connection to any host
    // (SQLite, QL).
    Host string
    // Database server port. This field is ignored if using unix sockets or if
    // the database does not require a connection to any host (SQLite, QL). If
    // not provided, the default database port is tried.
    Port int
    // Name of the database. You can also use a filename if the database supports
    // opening a raw file (SQLite, QL).
    Database string
    // Username for authentication, if required.
    User string
    // Password for authentication, if required.
    Password string
    // A path to a UNIX socket file. Leave blank if you rather use host and port.
    Socket string
    // Database charset. You can leave this field blank to use the default
    // database charset.
    Charset string
}

Settings holds database connection and authentication data. Not all fields are mandatory, if any field is skipped, the database adapter will either try to use database defaults or return an error. Refer to the specific adapter to see which fields are required.

Example:

db.Settings{
	Host: "127.0.0.1",
	Database: "tests",
	User: "john",
	Password: "doe",
}

func (Settings) String Uses

func (s Settings) String() string

String is provided for backwards compatibility.

type SocketAddr Uses

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

SocketAddr is a UNIX address.

func Socket Uses

func Socket(path string) SocketAddr

Socket converts the given name into a socket structure.

func (SocketAddr) Host Uses

func (s SocketAddr) Host() (string, error)

Host is undefined in a socket struct.

func (SocketAddr) Path Uses

func (s SocketAddr) Path() (string, error)

Path returns the file path of the socket struct.

func (SocketAddr) Port Uses

func (s SocketAddr) Port() (uint, error)

Port is undefined in a socket struct.

func (SocketAddr) String Uses

func (s SocketAddr) String() string

String() returns the string representation of the socket struct.

type Tx Uses

type Tx interface {
    Database

    // Discards all the instructions issued during the transaction.
    Rollback() error

    // Verifies that all the instructions isssued during the transaction were
    // executed.
    Commit() error
}

Tx is an interface that provides the same methods that the `db.Database` does, plus some other that help the user deal with database transactions. In order to get a proper `db.Tx` interface the `db.Database.Transaction()` method must be called on an already opened database session.

Example:

...
if sess, err = db.Open(postgresql.Adapter, settings); err != nil {
	log.Fatal(err)
}

var tx db.Tx
if tx, err = sess.Transaction(); err != nil {
	log.Fatal(err)
}

var artist db.Collection
if artist, err = tx.Collection("artist"); err != nil {
	log.Fatal(err)
}
...

type Uint64IDSetter Uses

type Uint64IDSetter interface {
    SetID(uint64) error
}

Uint64IDSetter implements a common pattern for setting uint64 IDs.

type Unmarshaler Uses

type Unmarshaler interface {
    UnmarshalDB(interface{}) error
}

Unmarshaler is the interface implemented by structs that can transform themselves from storage data into a valid value.

Directories

PathSynopsis
internal/cache
mongo
mysql
mysql/_example
postgresql
postgresql/_example
ql
ql/_example
sqlite
sqlite/_example
util
util/schemaPackage schema provides basic information on relational database schemas.
util/sqlgen
util/sqlutil

Package db imports 5 packages (graph) and is imported by 145 packages. Updated 2018-11-23. Refresh now. Tools for package owners.