modl

package module
v0.0.0-...-b0cda50 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2014 License: MIT Imports: 9 Imported by: 0

README

Modl: Go database model & mapping

Build Status Godoc

Modl is a library which provides database modelling and mapping. It is a fork of James Cooper's wonderful gorp.

Note. Modl's public facing interface is considered unfinished and open to change. The current API will not be broken lightly, but additions are likely. As Gorp's behavior moves on, Modl may adopt some of it or may not.

Goals

Modl's goal is to clean up bits of gorp's API, add some additional features like query building helpers and additional control over SQL generation, and to reuse lower level abstractions provided in sqlx. The driving philosophies behind modl are:

  • If something can be done in database/sql, do it that way
  • Go is not a good declarative language, do not abuse struct tags
  • Expose as much as possible to facilitate extension by other libraries
  • Avoid abstractions which provide initial convenience but must eventually be abandoned
  • Avoid reflect and cache its results where possible, use where necessary
Features
  • Bind struct models to tables
  • CRUD helpers for bound structs
  • Create schema from database model (great for testing)
  • Pre/post insert/update/delete hooks
  • Automatic binding of auto increment PKs after insert
  • Delete & Fetch by primary keys (w/ multi-key support)
  • Sql trace logging
  • Bind arbitrary SQL queries to a struct
  • Optional optimistic locking using a version column (for update/deletes)
Differences from Gorp

Since modl is a gorp fork, here are some of its major behavioral differences:

  • Field names are mapped to all-lowercase sql equivalents. Capitalization is an artifact of visibility, and this was required for compatibility with sqlx.
  • No more struct/slice returns, pass pointers to methods instead
  • Many panics in gorp are errors in modl
  • TypeConverters are removed in favor of implementing sql.Scanner & driver.Valuer for custom types.

Testing

To use the test-all script, set the following environment variables:

# mysql DSN, note parseTime arg for time scanning support:
MODL_MYSQL_DSN="username:password@/dbname?parseTime=true"

# postgres DSN, like:
MODL_POSTGRES_DSN="user=username password=pw dbname=dbname sslmode=disable"

# sqlite DSN, which is a path
MODL_SQLITE_DSN="/dev/shm/modltest.db"

# optional, will fail the test if any DBs are skipped (for CI, mostly)
MODL_FAIL_ON_SKIP=true

In addition to this, you can create an environ file in this directory which will be sourced and ignored by git. You can continue to use the MODL_TEST_DSN and MODL_TEST_DIALECT variables if you want to manually run go test or if you want to run the benchmarks, as described below.

The original README.md follows:

API Stability

The API of Modl has been quite stable since its conception. Changes to the API are avoided as much as possible but there is currently no promise of forward or backward compatibility.

Supported Databases

Modl relies heavily upon the database/sql package, and has a Dialect interface which can be used to smooth over differences between databases. There is a list of sql drivers on the Go wiki, most of which Modl should be compatible with. Dialects are provided for:

  • MySQL
  • PostgreSQL
  • sqlite3

The test suite is continuously run against all of these databases.

Documentation

API Documentation is available on godoc.

Performance

Modl performs similar to Gorp. There are benchmarks in modl_test.go which will benchmark native querying w/ database/sql and manual Scanning with what modl does. Modl should perform between 2-3% slower than hand-done SQL.

Contributors

The original contributors to gorp are:

  • @coopernurse - James Cooper
  • @robfig - Rob Figueiredo
  • @sqs - Quinn Slack
  • matthias-margush - column aliasing via tags

Documentation

Overview

Package modl provides a non-declarative database modelling layer to ease the use of frequently repeated patterns in database-backed applications and centralize database use to ease profiling and reporting.

It is a fork of the wonderful github.com/coopernurse/gorp package, but is rewritten to use github.com/jmoiron/sqlx as a base.

Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.

Index

Constants

This section is empty.

Variables

View Source
var TableNameMapper = strings.ToLower

TableNameMapper is the function used by AddTable to map struct names to database table names, in analogy to sqlx.NameMapper which does the same for struct field name to database column names.

Functions

func ReBind

func ReBind(query string, dialect Dialect) string

ReBind formats the bindvars in the query string (these are '?') for the dialect.

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.
	Unique bool

	// Passed to Dialect.ToSqlType() to assist in informing the
	// correct column type to map to in CreateTables()
	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 for validation by Insert/Update/Delete/Get.

func (*ColumnMap) SetMaxSize

func (c *ColumnMap) SetMaxSize(size int) *ColumnMap

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) SetSqlCreate

func (c *ColumnMap) SetSqlCreate(s string) *ColumnMap

SetSqlCreate overrides the default create statement used when this column is created by CreateTable. This will override all other options (like SetMaxSize, SetSqlType, etc). To unset, call with the empty string.

func (*ColumnMap) SetSqlType

func (c *ColumnMap) SetSqlType(t string) *ColumnMap

SetSqlType sets an override for the column's sql type. This is a string, such as 'varchar(32)' or 'text', which will be used by CreateTable and nothing else. It is the caller's responsibility to ensure this will map cleanly to the underlying struct field via rows.Scan

func (*ColumnMap) SetTransient

func (c *ColumnMap) SetTransient(b bool) *ColumnMap

SetTransient allows you to mark the column as transient. If true this column will be skipped when SQL statements are generated

func (*ColumnMap) SetUnique

func (c *ColumnMap) SetUnique(b bool) *ColumnMap

SetUnique sets the unqiue clause for this column. If true, a unique clause will be added to create table statements for this column.

type DbMap

type DbMap struct {
	// Db handle to use with this map
	Db  *sql.DB
	Dbx *sqlx.DB

	// Dialect implementation to use with this map
	Dialect Dialect
	// contains filtered or unexported fields
}

DbMap is the root modl mapping object. Create one of these for each database schema you wish to map. Each DbMap contains a list of mapped tables.

Example:

dialect := modl.MySQLDialect{"InnoDB", "UTF8"}
dbmap := &modl.DbMap{Db: db, Dialect: dialect}

func NewDbMap

func NewDbMap(db *sql.DB, dialect Dialect) *DbMap

NewDbMap returns a new DbMap using the db connection and dialect.

func (*DbMap) AddTable

func (m *DbMap) AddTable(i interface{}, name ...string) *TableMap

AddTable registers the given interface type with modl. The table name will be given the name of the TypeOf(i), lowercased.

This operation is idempotent. If i's type is already mapped, the existing *TableMap is returned.

func (*DbMap) AddTableWithName

func (m *DbMap) AddTableWithName(i interface{}, name string) *TableMap

AddTableWithName adds a new mapping of the interface to a table name.

func (*DbMap) Begin

func (m *DbMap) Begin() (*Transaction, error)

Begin starts a modl Transaction.

func (*DbMap) CreateTables

func (m *DbMap) CreateTables() error

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) CreateTablesIfNotExists

func (m *DbMap) CreateTablesIfNotExists() error

CreateTablesIfNotExists is similar to CreateTables, but starts each statement with "create table if not exists" so that existing tables do not raise errors.

func (*DbMap) CreateTablesSql

func (m *DbMap) CreateTablesSql() (map[string]string, error)

CreateTablesSql returns create table SQL as a map of table names to their associated CREATE TABLE statements.

func (*DbMap) Delete

func (m *DbMap) Delete(list ...interface{}) (int64, error)

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 or if any interface in the list has not been registered with AddTable.

func (*DbMap) DropTables

func (m *DbMap) DropTables() error

DropTables iterates through TableMaps registered to this DbMap and executes "drop table" statements against the database for each.

func (*DbMap) Exec

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

Exec runs an arbitrary SQL statement. args represent the bind parameters. This is equivalent to running Exec() using database/sql.

func (*DbMap) Get

func (m *DbMap) Get(dest interface{}, keys ...interface{}) error

Get runs a SQL SELECT to fetch a single row from the table based on the primary key(s)

dest 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 it.

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 or if any interface in the list has not been registered with AddTable.

func (*DbMap) Insert

func (m *DbMap) Insert(list ...interface{}) error

Insert runs a SQL INSERT statement for each element in list. List items must be pointers, because any interface whose TableMap has an auto-increment PK will have its insert Id bound to the PK struct field.

Hook functions PreInsert() and/or PostInsert() will be executed before/after the INSERT statement if the interface defines them.

func (*DbMap) Select

func (m *DbMap) Select(dest interface{}, query string, args ...interface{}) error

Select runs an arbitrary SQL query, binding the columns in the result to fields on the struct specified by dest. 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 dest. 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 it.

Values are returned in one of two ways:

1. If dest is a struct or a pointer to a struct, returns a slice of pointers to matching rows of type dest.

2. If dest is a pointer to a slice, the results will be appended to that slice and nil returned.

dest does NOT need to be registered with AddTable().

func (*DbMap) SelectOne

func (m *DbMap) SelectOne(dest interface{}, query string, args ...interface{}) error

SelectOne runs an arbitrary SQL Query, binding the columns in the result to fields on the struct specified by dest.

func (*DbMap) TableFor

func (m *DbMap) TableFor(i interface{}) *TableMap

TableFor returns any matching tables for the interface i or nil if not found. If i is a slice, then the table is given for the base slice type.

func (*DbMap) TableForType

func (m *DbMap) TableForType(t reflect.Type) *TableMap

TableForType returns any matching tables for the type t or nil if not found.

func (*DbMap) TraceOff

func (m *DbMap) TraceOff()

TraceOff turns off tracing. It is idempotent.

func (*DbMap) TraceOn

func (m *DbMap) TraceOn(prefix string, logger *log.Logger)

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 modl generates.

func (*DbMap) TruncateTables

func (m *DbMap) TruncateTables() error

TruncateTables truncates all tables in the DbMap.

func (*DbMap) TruncateTablesIdentityRestart

func (m *DbMap) TruncateTablesIdentityRestart() error

TruncateTablesIdentityRestart truncates all tables in the DbMap and resets the identity counter.

func (*DbMap) Update

func (m *DbMap) Update(list ...interface{}) (int64, error)

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 or 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(col *ColumnMap) string

	// AutoIncrStr returns a string to append to primary key column definitions
	AutoIncrStr() string

	//AutoIncrBindValue returns the default value for an auto increment row in an insert.
	AutoIncrBindValue() string

	// AutoIncrInsertSuffix returns a string to append to an insert statement which
	// will make it return the auto-increment key on insert.
	AutoIncrInsertSuffix(col *ColumnMap) string

	// CreateTableSuffix returns a string to append to "create table" statement for
	// vendor specific table attributes, eg. MySQL engine
	CreateTableSuffix() string

	// InsertAutoIncr
	InsertAutoIncr(e SqlExecutor, insertSql string, params ...interface{}) (int64, error)
	// InsertAutIncrAny takes a destination for non-integer auto-incr, like
	// uuids which scan to strings, hashes, etc.
	InsertAutoIncrAny(e SqlExecutor, insertSql string, dest interface{}, params ...interface{}) error

	// BindVar returns the variable string to use when forming SQL statements
	// in many dbs it is "?", but Postgres requires '$#'
	//
	// The supplied int is a zero based index of the bindvar in the statement
	BindVar(i int) string

	// QuoteField returns a quoted version of the field name.
	QuoteField(field string) string

	// TruncateClause is a string used to truncate tables.
	TruncateClause() string

	// RestartIdentityClause returns a string used to reset the identity counter
	// when truncating tables.  If the string starts with a ';', it is assumed to
	// be a separate query and is executed separately.
	RestartIdentityClause(table string) string

	// DriverName returns the driver name for a dialect.
	DriverName() string
}

Dialect is an interface that encapsulates behaviors that differ across SQL databases.

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
}

MySQLDialect is an implementation of Dialect for MySQL databases.

func (MySQLDialect) AutoIncrBindValue

func (d MySQLDialect) AutoIncrBindValue() string

AutoIncrBindValue returns "null", default for auto increment fields in MySQL.

func (MySQLDialect) AutoIncrInsertSuffix

func (d MySQLDialect) AutoIncrInsertSuffix(col *ColumnMap) string

AutoIncrInsertSuffix returns "".

func (MySQLDialect) AutoIncrStr

func (d MySQLDialect) AutoIncrStr() string

AutoIncrStr returns "auto_increment".

func (MySQLDialect) BindVar

func (d MySQLDialect) BindVar(i int) string

BindVar returns "?"

func (MySQLDialect) CreateTableSuffix

func (d MySQLDialect) CreateTableSuffix() string

CreateTableSuffix returns engine=%s charset=%s based on values stored on struct

func (MySQLDialect) DriverName

func (d MySQLDialect) DriverName() string

DriverName returns "mysql", used by the ziutek and the go-sql-driver versions of the MySQL driver.

func (MySQLDialect) InsertAutoIncr

func (d MySQLDialect) InsertAutoIncr(e SqlExecutor, insertSql string, params ...interface{}) (int64, error)

InsertAutoIncr runs the standard Insert Exec, which uses LastInsertId to get the value of the auto increment column.

func (MySQLDialect) InsertAutoIncrAny

func (d MySQLDialect) InsertAutoIncrAny(e SqlExecutor, insertSql string, dest interface{}, params ...interface{}) error

func (MySQLDialect) QuoteField

func (d MySQLDialect) QuoteField(f string) string

QuoteField quotes f using “.

func (MySQLDialect) RestartIdentityClause

func (d MySQLDialect) RestartIdentityClause(table string) string

RestartIdentityClause alters the table's AUTO_INCREMENT value after truncation, as MySQL doesn't have an identity clause for the truncate statement.

func (MySQLDialect) ToSqlType

func (d MySQLDialect) ToSqlType(col *ColumnMap) string

ToSqlType maps go types to MySQL types.

func (MySQLDialect) TruncateClause

func (d MySQLDialect) TruncateClause() string

TruncateClause returns 'truncate'.

type NoKeysErr

type NoKeysErr struct {
	Table *TableMap
}

NoKeysErr is a special error type returned when modl's CRUD helpers are used on tables which have not been set up with a primary key.

func (NoKeysErr) Error

func (n NoKeysErr) Error() string

Error returns the string representation of a NoKeysError.

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 PostDeleter

type PostDeleter interface {
	PostDelete(SqlExecutor) error
}

PostDeleter is an interface used to determine if a table type implements a PostDelete hook

type PostGetter

type PostGetter interface {
	PostGet(SqlExecutor) error
}

PostGetter is an interface used to determine if a table type implements a PostGet hook

type PostInserter

type PostInserter interface {
	PostInsert(SqlExecutor) error
}

PostInserter is an interface used to determine if a table type implements a PostInsert hook

type PostUpdater

type PostUpdater interface {
	PostUpdate(SqlExecutor) error
}

PostUpdater is an interface used to determine if a table type implements a PostUpdate hook

type PostgresDialect

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

PostgresDialect implements the Dialect interface for PostgreSQL.

func (PostgresDialect) AutoIncrBindValue

func (d PostgresDialect) AutoIncrBindValue() string

AutoIncrBindValue returns 'default' for default auto incr bind values.

func (PostgresDialect) AutoIncrInsertSuffix

func (d PostgresDialect) AutoIncrInsertSuffix(col *ColumnMap) string

AutoIncrInsertSuffix appnds 'returning colname' to a query so that the new autoincrement value for the column name is returned by Insert.

func (PostgresDialect) AutoIncrStr

func (d PostgresDialect) AutoIncrStr() string

AutoIncrStr returns empty string, as it's not used in postgres.

func (PostgresDialect) BindVar

func (d PostgresDialect) BindVar(i int) string

BindVar returns "$(i+1)"

func (PostgresDialect) CreateTableSuffix

func (d PostgresDialect) CreateTableSuffix() string

CreateTableSuffix returns the configured suffix.

func (PostgresDialect) DriverName

func (d PostgresDialect) DriverName() string

DriverName returns the driverName for postgres.

func (PostgresDialect) InsertAutoIncr

func (d PostgresDialect) InsertAutoIncr(e SqlExecutor, insertSql string, params ...interface{}) (int64, error)

InsertAutoIncr inserts via a query and reads the resultant rows for the new auto increment ID, as it's not returned with the result in PostgreSQL.

func (PostgresDialect) InsertAutoIncrAny

func (d PostgresDialect) InsertAutoIncrAny(e SqlExecutor, insertSql string, dest interface{}, params ...interface{}) error

func (PostgresDialect) QuoteField

func (d PostgresDialect) QuoteField(f string) string

QuoteField quotes f with ""

func (PostgresDialect) RestartIdentityClause

func (d PostgresDialect) RestartIdentityClause(table string) string

RestartIdentityClause returns 'restart identity', which will restart serial sequences for this table at the same time as a truncation is performed.

func (PostgresDialect) ToSqlType

func (d PostgresDialect) ToSqlType(col *ColumnMap) string

ToSqlType maps go types to postgres types.

func (PostgresDialect) TruncateClause

func (d PostgresDialect) TruncateClause() string

TruncateClause returns 'truncate'

type PreDeleter

type PreDeleter interface {
	PreDelete(SqlExecutor) error
}

PreDeleter is an interface used to determine if a table type implements a PreDelete hook

type PreInserter

type PreInserter interface {
	PreInsert(SqlExecutor) error
}

PreInserter is an interface used to determine if a table type implements a PreInsert hook

type PreUpdater

type PreUpdater interface {
	PreUpdate(SqlExecutor) error
}

PreUpdater is an interface used to determine if a table type implements a PreUpdate hook

type SqlExecutor

type SqlExecutor interface {
	Get(dest interface{}, keys ...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(dest interface{}, query string, args ...interface{}) error
	SelectOne(dest interface{}, query string, args ...interface{}) error
	// contains filtered or unexported methods
}

SqlExecutor exposes modl 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
}

SqliteDialect implements the Dialect interface for Sqlite3.

func (SqliteDialect) AutoIncrBindValue

func (d SqliteDialect) AutoIncrBindValue() string

AutoIncrBindValue returns the bind value for auto incr fields in sqlite.

func (SqliteDialect) AutoIncrInsertSuffix

func (d SqliteDialect) AutoIncrInsertSuffix(col *ColumnMap) string

AutoIncrInsertSuffix returns the auto incr insert suffix for sqlite.

func (SqliteDialect) AutoIncrStr

func (d SqliteDialect) AutoIncrStr() string

AutoIncrStr returns autoincrement clause for sqlite.

func (SqliteDialect) BindVar

func (d SqliteDialect) BindVar(i int) string

BindVar returns "?", the simpler of the sqlite bindvars.

func (SqliteDialect) CreateTableSuffix

func (d SqliteDialect) CreateTableSuffix() string

CreateTableSuffix returns d.suffix

func (SqliteDialect) DriverName

func (d SqliteDialect) DriverName() string

DriverName returns the driverName for sqlite.

func (SqliteDialect) InsertAutoIncr

func (d SqliteDialect) InsertAutoIncr(e SqlExecutor, insertSql string, params ...interface{}) (int64, error)

InsertAutoIncr runs the standard

func (SqliteDialect) InsertAutoIncrAny

func (d SqliteDialect) InsertAutoIncrAny(e SqlExecutor, insertSql string, dest interface{}, params ...interface{}) error

func (SqliteDialect) QuoteField

func (d SqliteDialect) QuoteField(f string) string

QuoteField quotes f with "" for sqlite

func (SqliteDialect) RestartIdentityClause

func (d SqliteDialect) RestartIdentityClause(table string) string

RestartIdentityClause restarts the sqlite_sequence for the provided table. It is executed by TruncateTable as a separate query.

func (SqliteDialect) ToSqlType

func (d SqliteDialect) ToSqlType(col *ColumnMap) string

ToSqlType maps go types to sqlite types.

func (SqliteDialect) TruncateClause

func (d SqliteDialect) TruncateClause() string

TruncateClause returns the truncate clause for sqlite. There is no TRUNCATE statement in sqlite3, but DELETE FROM uses a truncate optimization: http://www.sqlite.org/lang_delete.html

type TableMap

type TableMap struct {
	// Name of database table.
	TableName string
	Keys      []*ColumnMap
	Columns   []*ColumnMap

	// Cached capabilities for the struct mapped to this table
	CanPreInsert  bool
	CanPostInsert bool
	CanPostGet    bool
	CanPreUpdate  bool
	CanPostUpdate bool
	CanPreDelete  bool
	CanPostDelete bool
	// 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

func (t *TableMap) ColMap(field string) *ColumnMap

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

func (t *TableMap) SetKeys(isAutoIncr bool, fieldNames ...string) *TableMap

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

func (t *TableMap) SetVersionCol(field string) *ColumnMap

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 {
	Tx *sqlx.Tx
	// 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

Commit commits the underlying database transaction.

func (*Transaction) Delete

func (t *Transaction) Delete(list ...interface{}) (int64, error)

Delete has the same behavior as DbMap.Delete(), but runs in a transaction.

func (*Transaction) Exec

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

Exec has the same behavior as DbMap.Exec(), but runs in a transaction.

func (*Transaction) Get

func (t *Transaction) Get(dest interface{}, keys ...interface{}) error

Get has the Same behavior as DbMap.Get(), but runs in a transaction.

func (*Transaction) Insert

func (t *Transaction) Insert(list ...interface{}) error

Insert has the same behavior as DbMap.Insert(), but runs in a transaction.

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback rolls back the underlying database transaction.

func (*Transaction) Select

func (t *Transaction) Select(dest interface{}, query string, args ...interface{}) error

Select has the Same behavior as DbMap.Select(), but runs in a transaction.

func (*Transaction) SelectOne

func (t *Transaction) SelectOne(dest interface{}, query string, args ...interface{}) error

func (*Transaction) Update

func (t *Transaction) Update(list ...interface{}) (int64, error)

Update has the same behavior as DbMap.Update(), but runs in a transaction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL