Documentation ¶
Overview ¶
Package gorp provides a simple way to marshal Go structs to and from SQL databases. It uses the database/sql package, and should work with any compliant database/sql driver.
Source code and project home: https://github.com/coopernurse/gorp
Index ¶
- type ColumnMap
- type DbMap
- func (m *DbMap) AddTable(i interface{}) *TableMap
- func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap
- func (m *DbMap) Begin() (*Transaction, error)
- func (m *DbMap) CreateTables() error
- func (m *DbMap) Delete(list ...interface{}) (int64, error)
- func (m *DbMap) DropTables() error
- func (m *DbMap) Exec(query string, args ...interface{}) (sql.Result, error)
- func (m *DbMap) Get(i interface{}, keys ...interface{}) (interface{}, error)
- func (m *DbMap) Insert(list ...interface{}) error
- func (m *DbMap) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error)
- func (m *DbMap) TraceOff()
- func (m *DbMap) TraceOn(prefix string, logger *log.Logger)
- func (m *DbMap) Update(list ...interface{}) (int64, error)
- type Dialect
- type MySQLDialect
- func (m MySQLDialect) AutoIncrStr() string
- func (m MySQLDialect) BindVar(i int) string
- func (m MySQLDialect) CreateTableSuffix() string
- func (m MySQLDialect) LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error)
- func (m MySQLDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string
- type OptimisticLockError
- type PostgresDialect
- func (d PostgresDialect) AutoIncrStr() string
- func (d PostgresDialect) BindVar(i int) string
- func (d PostgresDialect) CreateTableSuffix() string
- func (d PostgresDialect) LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error)
- func (d PostgresDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string
- type SqlExecutor
- type SqliteDialect
- func (d SqliteDialect) AutoIncrStr() string
- func (d SqliteDialect) BindVar(i int) string
- func (d SqliteDialect) CreateTableSuffix() string
- func (d SqliteDialect) LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error)
- func (d SqliteDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string
- type TableMap
- type Transaction
- func (t *Transaction) Commit() error
- func (t *Transaction) Delete(list ...interface{}) (int64, error)
- func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error)
- func (t *Transaction) Get(i interface{}, keys ...interface{}) (interface{}, error)
- func (t *Transaction) Insert(list ...interface{}) error
- func (t *Transaction) Rollback() error
- func (t *Transaction) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error)
- func (t *Transaction) Update(list ...interface{}) (int64, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ColumnMap ¶
type ColumnMap struct { // Column name in db table ColumnName string // If true, this column is skipped in generated SQL statements Transient bool // If true, " unique" is added to create table statements. // Not used elsewhere Unique bool // Passed to Dialect.ToSqlType() to assist in informing the // correct column type to map to in CreateTables() // Not used elsewhere MaxSize int // contains filtered or unexported fields }
ColumnMap represents a mapping between a Go struct field and a single column in a table. Unique and MaxSize only inform the CreateTables() function and are not used by Insert/Update/Delete/Get.
func (*ColumnMap) Rename ¶
Rename allows you to specify the column name in the table
Example: table.ColMap("Updated").Rename("date_updated")
func (*ColumnMap) SetMaxSize ¶
SetMaxSize specifies the max length of values of this column. This is passed to the dialect.ToSqlType() function, which can use the value to alter the generated type for "create table" statements
func (*ColumnMap) SetTransient ¶
SetTransient allows you to mark the column as transient. If true this column will be skipped when SQL statements are generated
type DbMap ¶
type DbMap struct { // Db handle to use with this map Db *sql.DB // Dialect implementation to use with this map Dialect Dialect // contains filtered or unexported fields }
DbMap is the root gorp mapping object. Create one of these for each database schema you wish to map. Each DbMap contains a list of mapped tables.
Example:
dialect := gorp.MySQLDialect{"InnoDB", "UTF8"} dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
func (*DbMap) AddTable ¶
AddTable registers the given interface type with gorp. The table name will be given the name of the TypeOf(i). You must call this function, or AddTableWithName, for any struct type you wish to persist with the given DbMap.
This operation is idempotent. If i's type is already mapped, the existing *TableMap is returned
func (*DbMap) AddTableWithName ¶
AddTableWithName has the same behavior as AddTable, but sets table.TableName to name.
func (*DbMap) CreateTables ¶
CreateTables iterates through TableMaps registered to this DbMap and executes "create table" statements against the database for each.
This is particularly useful in unit tests where you want to create and destroy the schema automatically.
func (*DbMap) Delete ¶
Delete runs a SQL DELETE statement for each element in list. List items must be pointers.
Hook functions PreDelete() and/or PostDelete() will be executed before/after the DELETE statement if the interface defines them.
Returns number of rows deleted ¶
Returns an error if SetKeys has not been called on the TableMap Panics if any interface in the list has not been registered with AddTable
func (*DbMap) DropTables ¶
DropTables iterates through TableMaps registered to this DbMap and executes "drop table" statements against the database for each.
func (*DbMap) Exec ¶
Exec runs an arbitrary SQL statement. args represent the bind parameters. This is equivalent to running: Prepare(), Exec() using database/sql
func (*DbMap) Get ¶
Get runs a SQL SELECT to fetch a single row from the table based on the primary key(s)
i should be an empty value for the struct to load keys should be the primary key value(s) for the row to load. If multiple keys exist on the table, the order should match the column order specified in SetKeys() when the table mapping was defined.
Hook function PostGet() will be executed after the SELECT statement if the interface defines them.
Returns a pointer to a struct that matches or nil if no row is found ¶
Returns an error if SetKeys has not been called on the TableMap Panics if any interface in the list has not been registered with AddTable
func (*DbMap) Insert ¶
Insert runs a SQL INSERT statement for each element in list. List items must be pointers.
Any interface whose TableMap has an auto-increment primary key will have its last insert id bound to the PK field on the struct.
Hook functions PreInsert() and/or PostInsert() will be executed before/after the INSERT statement if the interface defines them.
Panics if any interface in the list has not been registered with AddTable
func (*DbMap) Select ¶
Select runs an arbitrary SQL query, binding the columns in the result to fields on the struct specified by i. args represent the bind parameters for the SQL statement.
Column names on the SELECT statement should be aliased to the field names on the struct i. Returns an error if one or more columns in the result do not match. It is OK if fields on i are not part of the SQL statement.
Hook function PostGet() will be executed after the SELECT statement if the interface defines them.
Returns a slice of pointers to matching rows of type i.
i does NOT need to be registered with AddTable()
func (*DbMap) TraceOn ¶
TraceOn turns on SQL statement logging for this DbMap. After this is called, all SQL statements will be sent to the logger. If prefix is a non-empty string, it will be written to the front of all logged strings, which can aid in filtering log lines.
Use TraceOn if you want to spy on the SQL statements that gorp generates.
func (*DbMap) Update ¶
Update runs a SQL UPDATE statement for each element in list. List items must be pointers.
Hook functions PreUpdate() and/or PostUpdate() will be executed before/after the UPDATE statement if the interface defines them.
Returns number of rows updated ¶
Returns an error if SetKeys has not been called on the TableMap Panics if any interface in the list has not been registered with AddTable
type Dialect ¶
type Dialect interface { // ToSqlType returns the SQL column type to use when creating a // table of the given Go Type. maxsize can be used to switch based on // size. For example, in MySQL []byte could map to BLOB, MEDIUMBLOB, // or LONGBLOB depending on the maxsize ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string // string to append to primary key column definitions AutoIncrStr() string // string to append to "create table" statement for vendor specific // table attributes CreateTableSuffix() string LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error) // bind variable string to use when forming SQL statements // in many dbs it is "?", but Postgres appears to use $1 // // i is a zero based index of the bind variable in this statement // BindVar(i int) string }
The Dialect interface encapsulates behaviors that differ across SQL databases. At present the Dialect is only used by CreateTables() but this could change in the future
type MySQLDialect ¶
type MySQLDialect struct { // Engine is the storage engine to use "InnoDB" vs "MyISAM" for example Engine string // Encoding is the character encoding to use for created tables Encoding string }
Implementation of Dialect for MySQL databases.
func (MySQLDialect) CreateTableSuffix ¶
func (m MySQLDialect) CreateTableSuffix() string
Returns engine=%s charset=%s based on values stored on struct
func (MySQLDialect) LastInsertId ¶
func (m MySQLDialect) LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error)
type OptimisticLockError ¶
type OptimisticLockError struct { // Table name where the lock error occurred TableName string // Primary key values of the row being updated/deleted Keys []interface{} // true if a row was found with those keys, indicating the // LocalVersion is stale. false if no value was found with those // keys, suggesting the row has been deleted since loaded, or // was never inserted to begin with RowExists bool // Version value on the struct passed to Update/Delete. This value is // out of sync with the database. LocalVersion int64 }
OptimisticLockError is returned by Update() or Delete() if the struct being modified has a Version field and the value is not equal to the current value in the database
func (OptimisticLockError) Error ¶
func (e OptimisticLockError) Error() string
Error returns a description of the cause of the lock error
type PostgresDialect ¶
type PostgresDialect struct {
// contains filtered or unexported fields
}
func (PostgresDialect) AutoIncrStr ¶
func (d PostgresDialect) AutoIncrStr() string
Returns empty string
func (PostgresDialect) CreateTableSuffix ¶
func (d PostgresDialect) CreateTableSuffix() string
Returns suffix
func (PostgresDialect) LastInsertId ¶
func (d PostgresDialect) LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error)
type SqlExecutor ¶
type SqlExecutor interface { Get(i interface{}, keys ...interface{}) (interface{}, error) Insert(list ...interface{}) error Update(list ...interface{}) (int64, error) Delete(list ...interface{}) (int64, error) Exec(query string, args ...interface{}) (sql.Result, error) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error) // contains filtered or unexported methods }
SqlExecutor exposes gorp operations that can be run from Pre/Post hooks. This hides whether the current operation that triggered the hook is in a transaction.
See the DbMap function docs for each of the functions below for more information.
type SqliteDialect ¶
type SqliteDialect struct {
// contains filtered or unexported fields
}
func (SqliteDialect) AutoIncrStr ¶
func (d SqliteDialect) AutoIncrStr() string
Returns autoincrement
func (SqliteDialect) CreateTableSuffix ¶
func (d SqliteDialect) CreateTableSuffix() string
Returns suffix
func (SqliteDialect) LastInsertId ¶
func (d SqliteDialect) LastInsertId(res *sql.Result, table *TableMap, exec SqlExecutor) (int64, error)
type TableMap ¶
type TableMap struct { // Name of database table. TableName string // contains filtered or unexported fields }
TableMap represents a mapping between a Go struct and a database table Use dbmap.AddTable() or dbmap.AddTableWithName() to create these
func (*TableMap) ColMap ¶
ColMap returns the ColumnMap pointer matching the given struct field name. It panics if the struct does not contain a field matching this name.
func (*TableMap) ResetSql ¶
func (t *TableMap) ResetSql()
ResetSql removes cached insert/update/select/delete SQL strings associated with this TableMap. Call this if you've modified any column names or the table name itself.
func (*TableMap) SetKeys ¶
SetKeys lets you specify the fields on a struct that map to primary key columns on the table. If isAutoIncr is set, result.LastInsertId() will be used after INSERT to bind the generated id to the Go struct.
Automatically calls ResetSql() to ensure SQL statements are regenerated.
func (*TableMap) SetVersionCol ¶
SetVersionCol sets the column to use as the Version field. By default the "Version" field is used. Returns the column found, or panics if the struct does not contain a field matching this name.
Automatically calls ResetSql() to ensure SQL statements are regenerated.
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction represents a database transaction. Insert/Update/Delete/Get/Exec operations will be run in the context of that transaction. Transactions should be terminated with a call to Commit() or Rollback()
func (*Transaction) Commit ¶
func (t *Transaction) Commit() error
Commits the underlying database transaction
func (*Transaction) Delete ¶
func (t *Transaction) Delete(list ...interface{}) (int64, error)
Same behavior as DbMap.Delete(), but runs in a transaction
func (*Transaction) Exec ¶
func (t *Transaction) Exec(query string, args ...interface{}) (sql.Result, error)
Same behavior as DbMap.Exec(), but runs in a transaction
func (*Transaction) Get ¶
func (t *Transaction) Get(i interface{}, keys ...interface{}) (interface{}, error)
Same behavior as DbMap.Get(), but runs in a transaction
func (*Transaction) Insert ¶
func (t *Transaction) Insert(list ...interface{}) error
Same behavior as DbMap.Insert(), but runs in a transaction
func (*Transaction) Rollback ¶
func (t *Transaction) Rollback() error
Rolls back the underlying database transaction
func (*Transaction) Select ¶
func (t *Transaction) Select(i interface{}, query string, args ...interface{}) ([]interface{}, error)
Same behavior as DbMap.Select(), but runs in a transaction
func (*Transaction) Update ¶
func (t *Transaction) Update(list ...interface{}) (int64, error)
Same behavior as DbMap.Update(), but runs in a transaction