hood: github.com/eaigner/hood Index | Files | Directories

package hood

import "github.com/eaigner/hood"

Package hood provides a database agnostic, transactional ORM for the sql package

Index

Package Files

base.go dialect.go error.go hood.go mysql.go postgres.go util.go

Constants

const (
    ValidationErrorValueNotSet = (1<<16 + iota)
    ValidationErrorValueTooSmall
    ValidationErrorValueTooBig
    ValidationErrorValueTooShort
    ValidationErrorValueTooLong
    ValidationErrorValueNotMatch
)
const (
    InnerJoin = Join(iota)
    LeftJoin
    RightJoin
    FullJoin
)

func NewValidationError Uses

func NewValidationError(id int, field string) error

NewValidationError returns a new validation error with the specified id and text. The id's purpose is to distinguish different validation error types. Built-in validation error ids start at 65536, so you should keep your custom ids under that value.

func RegisterDialect Uses

func RegisterDialect(name string, dialect Dialect)

RegisterDialect registers a new dialect using the specified name and dialect.

type Config Uses

type Config map[string]string

Config represents an environment entry in the config.json file

type Created Uses

type Created struct {
    time.Time
}

Created denotes a timestamp field that is automatically set on insert.

type Dialect Uses

type Dialect interface {
    // NextMarker returns the dialect specific marker for a prepared statement,
    // for instance $1, $2, ... and increments the position by one.
    // The position starts at 0.
    NextMarker(pos *int) string

    // Quote will quote identifiers in a SQL statement.
    Quote(s string) string

    // SqlType returns the SQL type for the provided interface type. The size
    // parameter delcares the data size for the column (e.g. for VARCHARs).
    SqlType(f interface{}, size int) string

    // If database do not support boolean type this can be used to parse int
    // value to boolean value.
    ParseBool(value reflect.Value) bool

    // SetModelValue sets a model field from a db value.
    //
    // For example: time.Time objects needs to be marshalled back and forth
    // as Strings for databases that don't have a native "time" type.
    SetModelValue(value reflect.Value, field reflect.Value) error

    // ConvertHoodType converts special types such as Created or Updated to
    // values the driver can understand.
    ConvertHoodType(f interface{}) interface{}

    // QuerySql returns the resulting query sql and attributes.
    QuerySql(hood *Hood) (sql string, args []interface{})

    // Insert inserts the values in model and returns the inserted rows Id.
    Insert(hood *Hood, model *Model) (Id, error)

    // InsertSql returns the sql for inserting the passed model.
    InsertSql(model *Model) (sql string, args []interface{})

    // Update updates the values in the specified model and returns the
    // updated rows Id.
    Update(hood *Hood, model *Model) (Id, error)

    // UpdateSql returns the sql for updating the specified model.
    UpdateSql(model *Model) (string, []interface{})

    // Delete drops the row matching the primary key of model and returns the affected Id.
    Delete(hood *Hood, model *Model) (Id, error)

    // DeleteSql returns the sql for deleting the row matching model's primary key.
    DeleteSql(model *Model) (string, []interface{})

    // DeleteFrom deletes the matching rows in the specified table
    DeleteFrom(hood *Hood, table string) error

    // DeleteFromSql returns the sql for DeleteFrom
    DeleteFromSql(hood *Hood, table string) (string, []interface{})

    // CreateTable creates the table specified in model.
    CreateTable(hood *Hood, model *Model) error

    // CreateTableIfNotExists creates the table specified in model if it does not exist.
    CreateTableIfNotExists(hood *Hood, model *Model) error

    // CreateTableSql returns the sql for creating a table.
    CreateTableSql(model *Model, ifNotExists bool) string

    // DropTable drops the specified table.
    DropTable(hood *Hood, table string) error

    // DropTableIfExists drops the table if it exists.
    DropTableIfExists(hood *Hood, table string) error

    // DropTableSql returns the sql for dropping the specified table.
    DropTableSql(table string, ifExists bool) string

    // RenameTable renames the specified table.
    RenameTable(hood *Hood, from, to string) error

    // RenameTableSql returns the sql for renaming the specified table.
    RenameTableSql(from, to string) string

    // AddColumn adds the columns to the corresponding table.
    AddColumn(hood *Hood, table, column string, typ interface{}, size int) error

    // AddColumnSql returns the sql for adding the specified column in table.
    AddColumnSql(table, column string, typ interface{}, size int) string

    // RenameColumn renames a table column in the specified table.
    RenameColumn(hood *Hood, table, from, to string) error

    // RenameColumnSql returns the sql for renaming the specified column in table.
    RenameColumnSql(table, from, to string) string

    // ChangeColumn changes the data type of the specified column.
    ChangeColumn(hood *Hood, table, column string, typ interface{}, size int) error

    // ChangeColumnSql returns the sql for changing the column data type.
    ChangeColumnSql(table, column string, typ interface{}, size int) string

    // DropColumn removes the specified column.
    DropColumn(hood *Hood, table, column string) error

    // DropColumnSql returns the sql for removing the column.
    DropColumnSql(table, column string) string

    // CreateIndex creates an index on the specified column.
    CreateIndex(hood *Hood, name, table string, unique bool, columns ...string) error

    // CreateIndexSql returns the sql for creating an index on the specified column.
    CreateIndexSql(name, table string, unique bool, columns ...string) string

    // DropIndex drops the index.
    DropIndex(hood *Hood, name string) error

    // DropIndexSql returns the sql for dropping the index.
    DropIndexSql(name string) string

    // KeywordNotNull returns the dialect specific keyword for 'NOT NULL'.
    KeywordNotNull() string

    // KeywordDefault returns the dialect specific keyword for 'DEFAULT'.
    KeywordDefault(s string) string

    // KeywordPrimaryKey returns the dialect specific keyword for 'PRIMARY KEY'.
    KeywordPrimaryKey() string

    // KeywordAutoIncrement returns the dialect specific keyword for 'AUTO_INCREMENT'.
    KeywordAutoIncrement() string
}

func NewMysql Uses

func NewMysql() Dialect

func NewPostgres Uses

func NewPostgres() Dialect

type Environment Uses

type Environment map[string]Config

Environment represents a configuration map for each environment specified in the config.json file

type Hood Uses

type Hood struct {
    Db      *sql.DB
    Dialect Dialect
    Log     bool
    // contains filtered or unexported fields
}

Hood is an ORM handle.

func Dry Uses

func Dry() *Hood

Dry creates a new Hood instance for schema generation.

func Load Uses

func Load(path, env string) (*Hood, error)

Load opens a new database from a config.json file with the specified environment, or development if none is specified.

func New Uses

func New(database *sql.DB, dialect Dialect) *Hood

New creates a new Hood using the specified DB and dialect.

func Open Uses

func Open(driverName, dataSourceName string) (*Hood, error)

Open opens a new database connection using the specified driver and data source name. It matches the sql.Open method signature.

func (*Hood) AddColumns Uses

func (hood *Hood) AddColumns(table, columns interface{}) error

AddColumns adds the columns in the specified schema to the table.

func (*Hood) And Uses

func (hood *Hood) And(a Path, op string, b interface{}) *Hood

Where adds a AND clause to the WHERE query. You can concatenate using the And and Or methods.

func (*Hood) Asc Uses

func (hood *Hood) Asc() *Hood

func (*Hood) Begin Uses

func (hood *Hood) Begin() *Hood

Begin starts a new transaction and returns a copy of Hood. You have to call subsequent methods on the newly returned object.

func (*Hood) ChangeColumns Uses

func (hood *Hood) ChangeColumns(table, column interface{}) error

ChangeColumn changes the data type of the specified column.

func (*Hood) Commit Uses

func (hood *Hood) Commit() error

Commit commits a started transaction and will report the first error that occurred inside the transaction.

func (*Hood) Copy Uses

func (hood *Hood) Copy() *Hood

Copy copies the hood instance for safe context manipulation.

func (*Hood) CreateIndex Uses

func (hood *Hood) CreateIndex(table interface{}, name string, unique bool, columns ...string) error

CreateIndex creates the specified index on table.

func (*Hood) CreateTable Uses

func (hood *Hood) CreateTable(table interface{}) error

CreateTable creates a new table based on the provided schema.

func (*Hood) CreateTableIfNotExists Uses

func (hood *Hood) CreateTableIfNotExists(table interface{}) error

CreateTableIfNotExists creates a new table based on the provided schema if it does not exist yet.

func (*Hood) Delete Uses

func (hood *Hood) Delete(f interface{}) (Id, error)

Delete deletes the row matching the specified structs Id.

func (*Hood) DeleteAll Uses

func (hood *Hood) DeleteAll(f interface{}) ([]Id, error)

DeleteAll deletes the rows matching the specified struct slice Ids.

func (*Hood) DeleteFrom Uses

func (hood *Hood) DeleteFrom(table interface{}) error

DeleteFrom deletes the rows matched by the previous Where clause. table can either be a table struct or a string.

Example:

hd.Where("amount", "=", 0).DeleteFrom("stock")

func (*Hood) Desc Uses

func (hood *Hood) Desc() *Hood

func (*Hood) DropIndex Uses

func (hood *Hood) DropIndex(table interface{}, name string) error

DropIndex drops the specified index from table.

func (*Hood) DropTable Uses

func (hood *Hood) DropTable(table interface{}) error

DropTable drops the table matching the provided table name.

func (*Hood) DropTableIfExists Uses

func (hood *Hood) DropTableIfExists(table interface{}) error

DropTableIfExists drops the table matching the provided table name if it exists.

func (*Hood) Exec Uses

func (hood *Hood) Exec(query string, args ...interface{}) (sql.Result, error)

Exec executes a raw sql query.

func (*Hood) Find Uses

func (hood *Hood) Find(out interface{}) error

Find performs a find using the previously specified query. If no explicit SELECT clause was specified earlier, the select is inferred from the passed interface type.

func (*Hood) FindSql Uses

func (hood *Hood) FindSql(out interface{}, query string, args ...interface{}) error

FindSql performs a find using the specified custom sql query and arguments and writes the results to the specified out interface{}.

func (*Hood) GoSchema Uses

func (hood *Hood) GoSchema() string

GoSchema returns a string of the schema file in Go syntax.

func (*Hood) GroupBy Uses

func (hood *Hood) GroupBy(path Path) *Hood

GroupBy adds a GROUP BY clause to the query.

func (*Hood) Having Uses

func (hood *Hood) Having(condition string, args ...interface{}) *Hood

Having adds a HAVING clause to the query.

func (*Hood) IsTransaction Uses

func (hood *Hood) IsTransaction() bool

IsTransaction returns wether the hood object represents an active transaction or not.

func (*Hood) Join Uses

func (hood *Hood) Join(op Join, table interface{}, a Path, b Path) *Hood

Join performs a JOIN on tables, for example

Join(hood.InnerJoin, &User{}, "user.id", "order.id")

func (*Hood) Limit Uses

func (hood *Hood) Limit(limit int) *Hood

Limit adds a LIMIT clause to the query.

func (*Hood) Offset Uses

func (hood *Hood) Offset(offset int) *Hood

Offset adds an OFFSET clause to the query.

func (*Hood) Or Uses

func (hood *Hood) Or(a Path, op string, b interface{}) *Hood

Where adds a OR clause to the WHERE query. You can concatenate using the And and Or methods.

func (*Hood) OrderBy Uses

func (hood *Hood) OrderBy(path Path) *Hood

OrderBy adds an ORDER BY clause to the query.

func (*Hood) Query Uses

func (hood *Hood) Query(query string, args ...interface{}) (*sql.Rows, error)

Query executes a query that returns rows, typically a SELECT

func (*Hood) QueryRow Uses

func (hood *Hood) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow executes a query that is expected to return at most one row. QueryRow always return a non-nil value. Errors are deferred until Row's Scan method is called.

func (*Hood) RemoveColumns Uses

func (hood *Hood) RemoveColumns(table, columns interface{}) error

RemoveColumns removes the specified columns from the table.

func (*Hood) RenameColumn Uses

func (hood *Hood) RenameColumn(table interface{}, from, to string) error

RenameColumn renames the column in the specified table.

func (*Hood) RenameTable Uses

func (hood *Hood) RenameTable(from, to interface{}) error

RenameTable renames a table. The arguments can either be a schema definition or plain strings.

func (*Hood) Reset Uses

func (hood *Hood) Reset()

Reset resets the internal state.

func (*Hood) Rollback Uses

func (hood *Hood) Rollback() error

Rollback rolls back a started transaction.

func (*Hood) Save Uses

func (hood *Hood) Save(f interface{}) (Id, error)

Save performs an INSERT, or UPDATE if the passed structs Id is set.

func (*Hood) SaveAll Uses

func (hood *Hood) SaveAll(f interface{}) ([]Id, error)

SaveAll performs an INSERT or UPDATE on a slice of structs.

func (*Hood) Select Uses

func (hood *Hood) Select(table interface{}, paths ...Path) *Hood

Select adds a SELECT clause to the query with the specified table and columns. The table can either be a string or it's name can be inferred from the passed interface{} type.

func (*Hood) Validate Uses

func (hood *Hood) Validate(f interface{}) error

Validate validates the provided struct

func (*Hood) Where Uses

func (hood *Hood) Where(a Path, op string, b interface{}) *Hood

Where adds a WHERE clause to the query. You can concatenate using the And and Or methods.

type Id Uses

type Id int64

Id represents a auto-incrementing integer primary key type.

type Index Uses

type Index struct {
    Name    string
    Columns []string
    Unique  bool
}

Index represents a table index and is returned via the Indexed interface.

func (*Index) GoDeclaration Uses

func (index *Index) GoDeclaration() string

type Indexed Uses

type Indexed interface {
    Indexes(indexes *Indexes)
}

Indexed defines the indexes for a table. You can invoke Add on the passed instance.

type Indexes Uses

type Indexes []*Index

Indexes represents an array of indexes.

func (*Indexes) Add Uses

func (ix *Indexes) Add(name string, columns ...string)

Add adds an index

func (*Indexes) AddUnique Uses

func (ix *Indexes) AddUnique(name string, columns ...string)

AddUnique adds an unique index

type Join Uses

type Join int

type Model Uses

type Model struct {
    Pk      *ModelField
    Table   string
    Fields  []*ModelField
    Indexes Indexes
}

Model represents a parsed schema interface{}.

func (*Model) GoDeclaration Uses

func (model *Model) GoDeclaration() string

func (*Model) Validate Uses

func (model *Model) Validate() error

type ModelField Uses

type ModelField struct {
    Name         string            // Column name
    Value        interface{}       // Value
    SqlTags      map[string]string // The sql struct tags for this field
    ValidateTags map[string]string // The validate struct tags for this field
    RawTag       reflect.StructTag // The raw tag
}

ModelField represents a schema field of a parsed model.

func (*ModelField) Default Uses

func (field *ModelField) Default() string

Default returns the default value for the field

func (*ModelField) GoDeclaration Uses

func (field *ModelField) GoDeclaration() string

func (*ModelField) Int Uses

func (field *ModelField) Int() (int64, bool)

Int returns the field int value and a bool flag indication if the conversion was successful

func (*ModelField) NotNull Uses

func (field *ModelField) NotNull() bool

NotNull tests if the field is declared as NOT NULL

func (*ModelField) PrimaryKey Uses

func (field *ModelField) PrimaryKey() bool

PrimaryKey tests if the field is declared using the sql tag "pk" or is of type Id

func (*ModelField) Size Uses

func (field *ModelField) Size() int

Size returns the field size, e.g. for varchars

func (*ModelField) String Uses

func (field *ModelField) String() (string, bool)

String returns the field string value and a bool flag indicating if the conversion was successful

func (*ModelField) Validate Uses

func (field *ModelField) Validate() error

Validate tests if the field conforms to it's validation constraints specified int the "validate" struct tag

func (*ModelField) Zero Uses

func (field *ModelField) Zero() bool

Zero tests wether or not the field is set

type Path Uses

type Path string

Path denotes a combined sql identifier such as 'table.column'

func (Path) Quote Uses

func (p Path) Quote(d Dialect) string

Quote quotes the path using the given dialects Quote method

type Schema Uses

type Schema []*Model

Schema is a collection of models

func (Schema) GoDeclaration Uses

func (schema Schema) GoDeclaration() string

type Updated Uses

type Updated struct {
    time.Time
}

Updated denotes a timestamp field that is automatically set on update.

type ValidationError Uses

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

Validation error type

func (*ValidationError) Error Uses

func (e *ValidationError) Error() string

func (*ValidationError) Field Uses

func (e *ValidationError) Field() string

func (*ValidationError) Kind Uses

func (e *ValidationError) Kind() int

Directories

PathSynopsis
cmd
cmd/gen

Package hood imports 14 packages (graph) and is imported by 52 packages. Updated 2016-07-23. Refresh now. Tools for package owners.