dbr

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2023 License: MIT Imports: 15 Imported by: 6

README

dbr (fork of gocraft/dbr) provides additions to Go's database/sql for super fast performance and convenience.

Build Status Go Report Card Coverage Status

Getting Started

// create a connection (e.g. "postgres", "mysql", or "sqlite3")
conn, _ := dbr.Open("postgres", "...")

// create a session for each business unit of execution (e.g. a web request or goworkers job)
sess := conn.NewSession(nil)

// get a record
var suggestion Suggestion
sess.Select("id", "title").From("suggestions").Where("id = ?", 1).Load(&suggestion)

// JSON-ready, with dbr.Null* types serialized like you want
json.Marshal(&suggestion)

Feature highlights

Use a Sweet Query Builder or use Plain SQL

mailru/dbr supports both.

Sweet Query Builder:

stmt := dbr.Select("title", "body").
	From("suggestions").
	OrderBy("id").
	Limit(10)

Plain SQL:

builder := dbr.SelectBySql("SELECT `title`, `body` FROM `suggestions` ORDER BY `id` ASC LIMIT 10")

Amazing instrumentation with session

All queries in mailru/dbr are made in the context of a session. This is because when instrumenting your app, it's important to understand which business action the query took place in.

Writing instrumented code is a first-class concern for mailru/dbr. We instrument each query to emit to a EventReceiver interface.

Faster performance than using database/sql directly

Every time you call database/sql's db.Query("SELECT ...") method, under the hood, the mysql driver will create a prepared statement, execute it, and then throw it away. This has a big performance cost.

mailru/dbr doesn't use prepared statements. We ported mysql's query escape functionality directly into our package, which means we interpolate all of those question marks with their arguments before they get to MySQL. The result of this is that it's way faster, and just as secure.

Check out these benchmarks.

IN queries that aren't horrible

Traditionally, database/sql uses prepared statements, which means each argument in an IN clause needs its own question mark. mailru/dbr, on the other hand, handles interpolation itself so that you can easily use a single question mark paired with a dynamically sized slice.

ids := []int64{1, 2, 3, 4, 5}
builder.Where("id IN ?", ids) // `id` IN ?

map object can be used for IN queries as well. Note: interpolation map is slower than slice and it is preferable to use slice when it is possible.

ids := map[int64]string{1: "one", 2: "two"}
builder.Where("id IN ?", ids)  // `id` IN ?

JSON Friendly

Every try to JSON-encode a sql.NullString? You get:

{
	"str1": {
		"Valid": true,
		"String": "Hi!"
	},
	"str2": {
		"Valid": false,
		"String": ""
  }
}

Not quite what you want. mailru/dbr has dbr.NullString (and the rest of the Null* types) that encode correctly, giving you:

{
	"str1": "Hi!",
	"str2": null
}

Inserting multiple records

sess.InsertInto("suggestions").Columns("title", "body").
  Record(suggestion1).
  Record(suggestion2)

Updating records on conflict

stmt := sess.InsertInto("suggestions").Columns("title", "body").Record(suggestion1)
stmt.OnConflict("suggestions_pkey").Action("body", dbr.Proposed("body"))

Updating records

sess.Update("suggestions").
	Set("title", "Gopher").
	Set("body", "I love go.").
	Where("id = ?", 1)

Transactions

tx, err := sess.Begin()
if err != nil {
  return err
}
defer tx.RollbackUnlessCommitted()

// do stuff...

return tx.Commit()

Load database values to variables

Querying is the heart of mailru/dbr.

  • Load(&any): load everything!
  • LoadStruct(&oneStruct): load struct
  • LoadStructs(&manyStructs): load a slice of structs
  • LoadValue(&oneValue): load basic type
  • LoadValues(&manyValues): load a slice of basic types
// columns are mapped by tag then by field
type Suggestion struct {
	ID int64  // id, will be autoloaded by last insert id
	Title string // title
	Url string `db:"-"` // ignored
	secret string // ignored
	Body dbr.NullString `db:"content"` // content
	User User
}

// By default dbr converts CamelCase property names to snake_case column_names
// You can override this with struct tags, just like with JSON tags
// This is especially helpful while migrating from legacy systems
type Suggestion struct {
	Id        int64
	Title     dbr.NullString `db:"subject"` // subjects are called titles now
	CreatedAt dbr.NullTime
}

var suggestions []Suggestion
sess.Select("*").From("suggestions").Load(&suggestions)

Join multiple tables

dbr supports many join types:

sess.Select("*").From("suggestions").
  Join("subdomains", "suggestions.subdomain_id = subdomains.id")

sess.Select("*").From("suggestions").
  LeftJoin("subdomains", "suggestions.subdomain_id = subdomains.id")

sess.Select("*").From("suggestions").
  RightJoin("subdomains", "suggestions.subdomain_id = subdomains.id")

sess.Select("*").From("suggestions").
  FullJoin("subdomains", "suggestions.subdomain_id = subdomains.id")

You can join on multiple tables:

sess.Select("*").From("suggestions").
  Join("subdomains", "suggestions.subdomain_id = subdomains.id").
  Join("accounts", "subdomains.accounts_id = accounts.id")

Quoting/escaping identifiers (e.g. table and column names)

dbr.I("suggestions.id") // `suggestions`.`id`

Subquery

sess.Select("count(id)").From(
  dbr.Select("*").From("suggestions").As("count"),
)

Union

dbr.Union(
  dbr.Select("*"),
  dbr.Select("*"),
)

dbr.UnionAll(
  dbr.Select("*"),
  dbr.Select("*"),
)

Union can be used in subquery.

Alias/AS

  • SelectStmt
dbr.Select("*").From("suggestions").As("count")
  • Identity
dbr.I("suggestions").As("s")
  • Union
dbr.Union(
  dbr.Select("*"),
  dbr.Select("*"),
).As("u1")

dbr.UnionAll(
  dbr.Select("*"),
  dbr.Select("*"),
).As("u2")

Building arbitrary condition

One common reason to use this is to prevent string concatenation in a loop.

  • And
  • Or
  • Eq
  • Neq
  • Gt
  • Gte
  • Lt
  • Lte
dbr.And(
  dbr.Or(
    dbr.Gt("created_at", "2015-09-10"),
    dbr.Lte("created_at", "2015-09-11"),
  ),
  dbr.Eq("title", "hello world"),
)

Built with extensibility

The core of dbr is interpolation, which can expand ? with arbitrary SQL. If you need a feature that is not currently supported, you can build it on your own (or use dbr.Expr).

To do that, the value that you wish to be expaned with ? needs to implement dbr.Builder.

type Builder interface {
	Build(Dialect, Buffer) error
}

Driver support

  • MySQL
  • PostgreSQL
  • SQLite3
  • ClickHouse

These packages were developed by the engineering team at UserVoice and currently power much of its infrastructure and tech stack.

Thanks & Authors

Inspiration from these excellent libraries:

  • sqlx - various useful tools and utils for interacting with database/sql.
  • Squirrel - simple fluent query builder.

Authors:

Contributors:

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound             = errors.New("dbr: not found")
	ErrNotSupported         = errors.New("dbr: not supported")
	ErrTableNotSpecified    = errors.New("dbr: table not specified")
	ErrColumnNotSpecified   = errors.New("dbr: column not specified")
	ErrInvalidPointer       = errors.New("dbr: attempt to load into an invalid pointer")
	ErrPlaceholderCount     = errors.New("dbr: wrong placeholder count")
	ErrInvalidSliceLength   = errors.New("dbr: length of slice is 0. length must be >= 1")
	ErrCantConvertToTime    = errors.New("dbr: can't convert to time.Time")
	ErrInvalidTimestring    = errors.New("dbr: invalid time string")
	ErrPrewhereNotSupported = errors.New("dbr: PREWHERE statement is not supported")
)

package errors

View Source
var Now = nowSentinel{}

Now is a value that serializes to the current time

Functions

func InterpolateForDialect added in v1.2.0

func InterpolateForDialect(query string, value []interface{}, d Dialect) (string, error)

InterpolateForDialect replaces placeholder in query with corresponding value in dialect

func Load added in v1.2.0

func Load(rows *sql.Rows, value interface{}) (int, error)

Load loads any value from sql.Rows

func Union added in v1.2.0

func Union(builder ...Builder) interface {
	Builder
	As(string) Builder
}

Union builds "UNION ..."

func UnionAll added in v1.2.0

func UnionAll(builder ...Builder) interface {
	Builder
	As(string) Builder
}

UnionAll builds "UNION ALL ..."

Types

type Buffer added in v1.2.0

type Buffer interface {
	WriteString(s string) (n int, err error)
	String() string

	WriteValue(v ...interface{}) (err error)
	Value() []interface{}
}

Buffer is an interface used by Builder to store intermediate results

func NewBuffer added in v1.2.0

func NewBuffer() Buffer

NewBuffer creates buffer

type BuildFunc added in v1.2.0

type BuildFunc func(Dialect, Buffer) error

BuildFunc is an adapter to allow the use of ordinary functions as Builder

func (BuildFunc) Build added in v1.2.0

func (b BuildFunc) Build(d Dialect, buf Buffer) error

Build implements Builder interface

type Builder added in v1.2.0

type Builder interface {
	Build(Dialect, Buffer) error
}

Builder builds sql in one dialect like MySQL/PostgreSQL e.g. XxxBuilder

func And added in v1.2.0

func And(cond ...Builder) Builder

And creates AND from a list of conditions

func Eq

func Eq(column string, value interface{}) Builder

Eq is `=`. When value is nil, it will be translated to `IS NULL`. When value is a slice, it will be translated to `IN`. Otherwise it will be translated to `=`.

func Expr

func Expr(query string, value ...interface{}) Builder

Expr should be used when sql syntax is not supported

func Gt added in v1.2.0

func Gt(column string, value interface{}) Builder

Gt is `>`.

func Gte added in v1.2.0

func Gte(column string, value interface{}) Builder

Gte is '>='.

func Lt added in v1.2.0

func Lt(column string, value interface{}) Builder

Lt is '<'.

func Lte added in v1.2.0

func Lte(column string, value interface{}) Builder

Lte is `<=`.

func Neq added in v1.2.0

func Neq(column string, value interface{}) Builder

Neq is `!=`. When value is nil, it will be translated to `IS NOT NULL`. When value is a slice, it will be translated to `NOT IN`. Otherwise it will be translated to `!=`.

func Or added in v1.2.0

func Or(cond ...Builder) Builder

Or creates OR from a list of conditions

func Proposed added in v1.2.0

func Proposed(column string) Builder

Proposed is reference to proposed value in on conflict clause

type ConflictStmt added in v1.2.0

type ConflictStmt interface {
	Action(column string, action interface{}) ConflictStmt
}

ConflictStmt is ` ON CONFLICT ...` part of InsertStmt

type Connection

type Connection struct {
	*sql.DB
	Dialect Dialect
	EventReceiver
}

Connection is a connection to the database with an EventReceiver to send events, errors, and timings to

func Open added in v1.2.0

func Open(driver, dsn string, log EventReceiver) (*Connection, error)

Open instantiates a Connection for a given database/sql connection and event receiver

func (*Connection) NewSession

func (conn *Connection) NewSession(log EventReceiver) *Session

NewSession instantiates a Session for the Connection

func (*Connection) NewSessionContext added in v1.2.0

func (conn *Connection) NewSessionContext(ctx context.Context, log EventReceiver) *Session

NewSessionContext instantiates a Session with context for the Connection

type DeleteBuilder

type DeleteBuilder interface {
	Builder
	EventReceiver
	Executer

	Where(query interface{}, value ...interface{}) DeleteBuilder
	Limit(n uint64) DeleteBuilder
}

DeleteBuilder builds "DELETE ..." stmt

type DeleteStmt added in v1.2.0

type DeleteStmt interface {
	Builder
	Where(query interface{}, value ...interface{}) DeleteStmt
}

DeleteStmt builds `DELETE ...`

func DeleteBySql added in v1.2.0

func DeleteBySql(query string, value ...interface{}) DeleteStmt

DeleteBySql creates a DeleteStmt from raw query

func DeleteFrom added in v1.2.0

func DeleteFrom(table string) DeleteStmt

DeleteFrom creates a DeleteStmt

type Dialect added in v1.2.0

type Dialect interface {
	QuoteIdent(id string) string

	EncodeString(s string) string
	EncodeBool(b bool) string
	EncodeTime(t time.Time) string
	EncodeBytes(b []byte) string
	Placeholder(n int) string
	OnConflict(constraint string) string
	Proposed(column string) string
	Limit(offset, limit int64) string
	Prewhere() string
}

Dialect abstracts database differences

type EventReceiver

type EventReceiver interface {
	Event(eventName string)
	EventKv(eventName string, kvs map[string]string)
	EventErr(eventName string, err error) error
	EventErrKv(eventName string, err error, kvs map[string]string) error
	Timing(eventName string, nanoseconds int64)
	TimingKv(eventName string, nanoseconds int64, kvs map[string]string)
}

EventReceiver gets events from dbr methods for logging purposes

type Executer added in v1.2.0

type Executer interface {
	Exec() (sql.Result, error)
	ExecContext(ctx context.Context) (sql.Result, error)
}

Executer can execute requests to database

type I added in v1.2.0

type I string

I is a identifier, which always will be quoted

func (I) As added in v1.2.0

func (i I) As(alias string) Builder

As creates an alias for expr. e.g. SELECT `a1` AS `a2`

func (I) Build added in v1.2.0

func (i I) Build(d Dialect, buf Buffer) error

Build escapes identifier in Dialect

type InsertBuilder

type InsertBuilder interface {
	Builder
	EventReceiver
	Executer
	Columns(column ...string) InsertBuilder
	Values(value ...interface{}) InsertBuilder
	Record(structValue interface{}) InsertBuilder
	OnConflictMap(constraint string, actions map[string]interface{}) InsertBuilder
	OnConflict(constraint string) ConflictStmt
	Pair(column string, value interface{}) InsertBuilder
}

InsertBuilder builds "INSERT ..." stmt

type InsertStmt added in v1.2.0

type InsertStmt interface {
	Builder
	Columns(column ...string) InsertStmt
	Values(value ...interface{}) InsertStmt
	Record(structValue interface{}) InsertStmt
	OnConflictMap(constraint string, actions map[string]interface{}) InsertStmt
	OnConflict(constraint string) ConflictStmt
}

InsertStmt builds `INSERT INTO ...`

func InsertBySql added in v1.2.0

func InsertBySql(query string, value ...interface{}) InsertStmt

InsertBySql creates an InsertStmt from raw query

func InsertInto added in v1.2.0

func InsertInto(table string) InsertStmt

InsertInto creates an InsertStmt

type NullBool

type NullBool struct {
	sql.NullBool
}

NullBool is a type that can be null or a bool

func NewNullBool added in v1.2.0

func NewNullBool(v interface{}) (n NullBool)

NewNullBool create a NullBool from v

func (NullBool) MarshalJSON

func (n NullBool) MarshalJSON() ([]byte, error)

MarshalJSON correctly serializes a NullBool to JSON

func (*NullBool) UnmarshalJSON

func (n *NullBool) UnmarshalJSON(b []byte) error

UnmarshalJSON correctly deserializes a NullBool from JSON

type NullEventReceiver

type NullEventReceiver struct{}

NullEventReceiver is a sentinel EventReceiver; use it if the caller doesn't supply one

func (*NullEventReceiver) Event

func (n *NullEventReceiver) Event(eventName string)

Event receives a simple notification when various events occur

func (*NullEventReceiver) EventErr

func (n *NullEventReceiver) EventErr(eventName string, err error) error

EventErr receives a notification of an error if one occurs

func (*NullEventReceiver) EventErrKv

func (n *NullEventReceiver) EventErrKv(eventName string, err error, kvs map[string]string) error

EventErrKv receives a notification of an error if one occurs along with optional key/value data

func (*NullEventReceiver) EventKv

func (n *NullEventReceiver) EventKv(eventName string, kvs map[string]string)

EventKv receives a notification when various events occur along with optional key/value data

func (*NullEventReceiver) Timing

func (n *NullEventReceiver) Timing(eventName string, nanoseconds int64)

Timing receives the time an event took to happen

func (*NullEventReceiver) TimingKv

func (n *NullEventReceiver) TimingKv(eventName string, nanoseconds int64, kvs map[string]string)

TimingKv receives the time an event took to happen along with optional key/value data

type NullFloat64

type NullFloat64 struct {
	sql.NullFloat64
}

NullFloat64 is a type that can be null or a float64

func NewNullFloat64 added in v1.2.0

func NewNullFloat64(v interface{}) (n NullFloat64)

NewNullFloat64 create a NullFloat64 from v

func (NullFloat64) MarshalJSON

func (n NullFloat64) MarshalJSON() ([]byte, error)

MarshalJSON correctly serializes a NullFloat64 to JSON

func (*NullFloat64) UnmarshalJSON

func (n *NullFloat64) UnmarshalJSON(b []byte) error

UnmarshalJSON correctly deserializes a NullFloat64 from JSON

type NullInt64

type NullInt64 struct {
	sql.NullInt64
}

NullInt64 is a type that can be null or an int

func NewNullInt64 added in v1.2.0

func NewNullInt64(v interface{}) (n NullInt64)

NewNullInt64 create a NullInt64 from v

func (NullInt64) MarshalJSON

func (n NullInt64) MarshalJSON() ([]byte, error)

MarshalJSON correctly serializes a NullInt64 to JSON

func (*NullInt64) UnmarshalJSON

func (n *NullInt64) UnmarshalJSON(b []byte) error

UnmarshalJSON correctly deserializes a NullInt64 from JSON

type NullString

type NullString struct {
	sql.NullString
}

NullString is a type that can be null or a string

func NewNullString added in v1.2.0

func NewNullString(v interface{}) (n NullString)

NewNullString create a NullString from v

func (NullString) MarshalJSON

func (n NullString) MarshalJSON() ([]byte, error)

MarshalJSON correctly serializes a NullString to JSON

func (*NullString) UnmarshalJSON

func (n *NullString) UnmarshalJSON(b []byte) error

UnmarshalJSON correctly deserializes a NullString from JSON

type NullTime

type NullTime struct {
	Time  time.Time
	Valid bool // Valid is true if Time is not NULL
}

NullTime is a type that can be null or a time

func NewNullTime added in v1.2.0

func NewNullTime(v interface{}) (n NullTime)

NewNullTime create a NullTime from v

func (NullTime) MarshalJSON

func (n NullTime) MarshalJSON() ([]byte, error)

MarshalJSON correctly serializes a NullTime to JSON

func (*NullTime) Scan added in v1.2.0

func (n *NullTime) Scan(value interface{}) error

Scan implements the Scanner interface. The value type must be time.Time or string / []byte (formatted time-string), otherwise Scan fails.

func (*NullTime) UnmarshalJSON

func (n *NullTime) UnmarshalJSON(b []byte) error

UnmarshalJSON correctly deserializes a NullTime from JSON

func (NullTime) Value added in v1.2.0

func (n NullTime) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type SelectBuilder

type SelectBuilder interface {
	Builder
	EventReceiver

	As(alias string) Builder
	Comment(text string) SelectBuilder
	Distinct() SelectBuilder
	ForUpdate() SelectBuilder
	From(table interface{}) SelectBuilder
	FullJoin(table, on interface{}) SelectBuilder
	GroupBy(col ...string) SelectBuilder
	Having(query interface{}, value ...interface{}) SelectBuilder
	InTimezone(loc *time.Location) SelectBuilder
	Join(table, on interface{}) SelectBuilder
	LeftJoin(table, on interface{}) SelectBuilder
	Limit(n uint64) SelectBuilder
	Offset(n uint64) SelectBuilder
	OrderAsc(col string) SelectBuilder
	OrderBy(col string) SelectBuilder
	OrderDesc(col string) SelectBuilder
	OrderDir(col string, isAsc bool) SelectBuilder
	Paginate(page, perPage uint64) SelectBuilder
	Prewhere(query interface{}, value ...interface{}) SelectBuilder
	RightJoin(table, on interface{}) SelectBuilder
	SkipLocked() SelectBuilder
	Where(query interface{}, value ...interface{}) SelectBuilder
	GetRows() (*sql.Rows, error)
	GetRowsContext(context.Context) (*sql.Rows, error)
	// contains filtered or unexported methods
}

SelectBuilder build "SELECT" stmt

type SelectStmt added in v1.2.0

type SelectStmt interface {
	Builder

	From(table interface{}) SelectStmt
	Distinct() SelectStmt
	Prewhere(query interface{}, value ...interface{}) SelectStmt
	Where(query interface{}, value ...interface{}) SelectStmt
	Having(query interface{}, value ...interface{}) SelectStmt
	GroupBy(col ...string) SelectStmt
	OrderAsc(col string) SelectStmt
	OrderDesc(col string) SelectStmt
	Limit(n uint64) SelectStmt
	Offset(n uint64) SelectStmt
	ForUpdate() SelectStmt
	SkipLocked() SelectStmt
	Join(table, on interface{}) SelectStmt
	LeftJoin(table, on interface{}) SelectStmt
	RightJoin(table, on interface{}) SelectStmt
	FullJoin(table, on interface{}) SelectStmt
	AddComment(text string) SelectStmt
	As(alias string) Builder
}

SelectStmt builds `SELECT ...`

func Select added in v1.2.0

func Select(column ...interface{}) SelectStmt

Select creates a SelectStmt

func SelectBySql added in v1.2.0

func SelectBySql(query string, value ...interface{}) SelectStmt

SelectBySql creates a SelectStmt from raw query

type Session

type Session struct {
	*Connection
	EventReceiver
	// contains filtered or unexported fields
}

Session represents a business unit of execution for some connection

func (*Session) Begin

func (sess *Session) Begin() (*Tx, error)

Begin creates a transaction for the given session

func (*Session) BeginWithOpts added in v1.2.0

func (sess *Session) BeginWithOpts(opts *sql.TxOptions) (*Tx, error)

BeginWithOpts creates a transaction for the given section with ability to set TxOpts

func (*Session) DeleteBySql added in v1.2.0

func (sess *Session) DeleteBySql(query string, value ...interface{}) DeleteBuilder

DeleteBySql creates a DeleteBuilder from raw query

func (*Session) DeleteFrom

func (sess *Session) DeleteFrom(table string) DeleteBuilder

DeleteFrom creates a DeleteBuilder

func (*Session) Exec added in v1.2.0

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

Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*Session) InsertBySql added in v1.2.0

func (sess *Session) InsertBySql(query string, value ...interface{}) InsertBuilder

InsertBySql creates a InsertBuilder from raw query

func (*Session) InsertInto

func (sess *Session) InsertInto(table string) InsertBuilder

InsertInto creates a InsertBuilder

func (*Session) NewSession added in v1.2.0

func (sess *Session) NewSession(log EventReceiver) *Session

NewSession forks current session

func (*Session) Query added in v1.2.0

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

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*Session) Select

func (sess *Session) Select(column ...string) SelectBuilder

Select creates a SelectBuilder

func (*Session) SelectBySql

func (sess *Session) SelectBySql(query string, value ...interface{}) SelectBuilder

SelectBySql creates a SelectBuilder from raw query

func (*Session) Update

func (sess *Session) Update(table string) UpdateBuilder

Update creates a UpdateBuilder

func (*Session) UpdateBySql

func (sess *Session) UpdateBySql(query string, value ...interface{}) UpdateBuilder

UpdateBySql creates a UpdateBuilder from raw query

type SessionRunner

type SessionRunner interface {
	Select(column ...string) SelectBuilder
	SelectBySql(query string, value ...interface{}) SelectBuilder

	InsertInto(table string) InsertBuilder
	InsertBySql(query string, value ...interface{}) InsertBuilder

	Update(table string) UpdateBuilder
	UpdateBySql(query string, value ...interface{}) UpdateBuilder

	DeleteFrom(table string) DeleteBuilder
	DeleteBySql(query string, value ...interface{}) DeleteBuilder
}

SessionRunner can do anything that a Session can except start a transaction.

type TracingEventReceiver added in v1.2.0

type TracingEventReceiver interface {
	SpanStart(ctx context.Context, eventName, query string) context.Context
	SpanError(ctx context.Context, err error)
	SpanFinish(ctx context.Context)
}

TracingEventReceiver is an optional interface an EventReceiver type can implement to allow tracing instrumentation

type Tx

type Tx struct {
	EventReceiver
	Dialect Dialect
	*sql.Tx
	// contains filtered or unexported fields
}

Tx is a transaction for the given Session

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit finishes the transaction

func (*Tx) DeleteBySql added in v1.2.0

func (tx *Tx) DeleteBySql(query string, value ...interface{}) DeleteBuilder

DeleteBySql creates a DeleteBuilder from raw query

func (*Tx) DeleteFrom

func (tx *Tx) DeleteFrom(table string) DeleteBuilder

DeleteFrom creates a DeleteBuilder

func (*Tx) Exec added in v1.2.0

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

Exec executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*Tx) InsertBySql added in v1.2.0

func (tx *Tx) InsertBySql(query string, value ...interface{}) InsertBuilder

InsertBySql creates a InsertBuilder from raw query

func (*Tx) InsertInto

func (tx *Tx) InsertInto(table string) InsertBuilder

InsertInto creates a InsertBuilder

func (*Tx) Query added in v1.2.0

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

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback cancels the transaction

func (*Tx) RollbackUnlessCommitted

func (tx *Tx) RollbackUnlessCommitted()

RollbackUnlessCommitted rollsback the transaction unless it has already been committed or rolled back. Useful to defer tx.RollbackUnlessCommitted() -- so you don't have to handle N failure cases Keep in mind the only way to detect an error on the rollback is via the event log.

func (*Tx) Select

func (tx *Tx) Select(column ...string) SelectBuilder

Select creates a SelectBuilder

func (*Tx) SelectBySql

func (tx *Tx) SelectBySql(query string, value ...interface{}) SelectBuilder

SelectBySql creates a SelectBuilder from raw query

func (*Tx) Update

func (tx *Tx) Update(table string) UpdateBuilder

Update creates a UpdateBuilder

func (*Tx) UpdateBySql

func (tx *Tx) UpdateBySql(query string, value ...interface{}) UpdateBuilder

UpdateBySql creates a UpdateBuilder from raw query

type UpdateBuilder

type UpdateBuilder interface {
	Builder
	EventReceiver
	Executer

	Where(query interface{}, value ...interface{}) UpdateBuilder
	Set(column string, value interface{}) UpdateBuilder
	SetMap(m map[string]interface{}) UpdateBuilder
	Limit(n uint64) UpdateBuilder
}

UpdateBuilder builds `UPDATE ...`

type UpdateStmt added in v1.2.0

type UpdateStmt interface {
	Builder

	Where(query interface{}, value ...interface{}) UpdateStmt
	Set(column string, value interface{}) UpdateStmt
	SetMap(m map[string]interface{}) UpdateStmt
	SetRecord(structValue interface{}) UpdateStmt
}

UpdateStmt builds `UPDATE ...`

func Update added in v1.2.0

func Update(table string) UpdateStmt

Update creates an UpdateStmt

func UpdateBySql added in v1.2.0

func UpdateBySql(query string, value ...interface{}) UpdateStmt

UpdateBySql creates an UpdateStmt with raw query

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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