dbr

package module
v0.0.0-...-18a56f9 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2015 License: MIT Imports: 12 Imported by: 0

README

gocraft/dbr (database records) GoDoc

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

Getting Started

package main

import (
	"database/sql"
  "fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gocraft/dbr"
)

// Simple data model
type Suggestion struct {
	Id        int64
	Title     string
	CreatedAt dbr.NullTime
}

// Hold a single global connection (pooling provided by sql driver)
var connection *dbr.Connection

func main() {
	// Create the connection during application initialization
	db, _ := sql.Open("mysql", "root@unix(/tmp/mysqld.sock)/your_database")
	connection = dbr.NewConnection(db, nil)

	// Create a session for each business unit of execution (e.g. a web request or goworkers job)
	dbrSess := connection.NewSession(nil)

	// Get a record
	var suggestion Suggestion
	err := dbrSess.Select("id, title").From("suggestions").Where("id = ?", 13).LoadStruct(&suggestion)

	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println("Title:", suggestion.Title)
	}

	// JSON-ready, with dbr.Null* types serialized like you want
	recordJson, _ := json.Marshal(&suggestion)
	fmt.Println(string(recordJson))
}

Feature highlights

Automatically map results to structs

Querying is the heart of gocraft/dbr. Automatically map results to structs:

var posts []*struct {
	Id int64
	Title string
	Body dbr.NullString
}
err := sess.Select("id, title, body").
	From("posts").Where("id = ?", id).LoadStruct(&post)

Additionally, easily query a single value or a slice of values:

id, err := sess.SelectBySql("SELECT id FROM posts WHERE title=?", title).ReturnInt64()
ids, err := sess.SelectBySql("SELECT id FROM posts", title).ReturnInt64s()

See below for many more examples.

Use a Sweet Query Builder or use Plain SQL

gocraft/dbr supports both.

Sweet Query Builder:

builder := sess.Select("title", "body").
	From("posts").
	Where("created_at > ?", someTime).
	OrderBy("id ASC").
	Limit(10)

var posts []*Post
n, err := builder.LoadStructs(&posts)

Plain SQL:

n, err := sess.SelectBySql(`SELECT title, body FROM posts WHERE created_at > ?
                              ORDER BY id ASC LIMIT 10`, someTime).LoadStructs(&post)
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. gocraft/dbr, on the other hand, handles interpolation itself so that you can easily use a single question mark paired with a dynamically sized slice.

// Traditional database/sql way:
ids := []int64{1,2,3,4,5}
questionMarks := []string
for _, _ := range ids {
	questionMarks = append(questionMarks, "?")
}
query := fmt.Sprintf("SELECT * FROM posts WHERE id IN (%s)",
	strings.Join(questionMarks, ",") // lolwut
rows, err := db.Query(query, ids) 

// gocraft/dbr way:
ids := []int64{1,2,3,4,5}
n, err := sess.SelectBySql("SELECT * FROM posts WHERE id IN ?", ids) // yay
Amazing instrumentation

Writing instrumented code is a first-class concern for gocraft/dbr. We instrument each query to emit to a gocraft/health-compatible EventReceiver interface. NOTE: we have not released gocraft/health yet. This allows you to instrument your app to easily connect gocraft/dbr to your metrics systems, such statsd.

Faster performance than using 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.

gocraft/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.

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. gocraft/dbr has dbr.NullString (and the rest of the Null* types) that encode correctly, giving you:

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

Driver support

Currently only MySQL has been tested because that is what we use. Feel free to make an issue for Postgres if you're interested in adding support and we can discuss what it would take.

Usage Examples

Making a session

All queries in gocraft/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. See gocraft/health for more detail.

Here's an example web endpoint that makes a session:

// At app startup. If you have a gocraft/health stream, pass it here instead of nil.
dbrCxn = dbr.NewConnection(db, nil)

func SuggestionsIndex(rw http.ResponseWriter, r *http.Request) {
	// Make a session. If you have a gocraft/health job, pass it here instead of nil.
	dbrSess := connection.NewSession(nil)

	// Do queries with the session:
	var sugg Suggestion
	err := dbrSess.Select("id, title").From("suggestions").
		Where("id = ?", suggestion.Id).LoadStruct(&sugg)

	// Render stuff, etc. Nothing else needs to be done with dbr.
}
Simple Record CRUD
// Create a new suggestion record
suggestion := &Suggestion{Title: "My Cool Suggestion", State: "open"}

// Insert; inserting a record automatically sets an int64 Id field if present
response, err := dbrSess.InsertInto("suggestions").
	Columns("title", "state").Record(suggestion).Exec()

// Update
response, err = dbrSess.Update("suggestions").
	Set("title", "My New Title").Where("id = ?", suggestion.Id).Exec()

// Select
var otherSuggestion Suggestion
err = dbrSess.Select("id, title").From("suggestions").
	Where("id = ?", suggestion.Id).LoadStruct(&otherSuggestion)

// Delete
response, err = dbrSess.DeleteFrom("suggestions").
	Where("id = ?", otherSuggestion.Id).Limit(1).Exec()
Primitive Values
// Load primitives into existing variables
var ids []int64
idCount, err := sess.Select("id").From("suggestions").LoadValues(&ids)

var titles []string
titleCount, err := sess.Select("title").From("suggestions").LoadValues(&titles)

// Or return them directly
ids, err = sess.Select("id").From("suggestions").ReturnInt64s()
titles, err = sess.Select("title").From("suggestions").ReturnStrings()
Overriding Column Names With Struct Tags
// 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
}
Embedded structs
// Columns are mapped to fields breadth-first
type Suggestion struct {
    Id        int64
    Title     string
    User      *struct {
        Id int64 `db:"user_id"`
    }
}

var suggestion Suggestion
err := dbrSess.Select("id, title, user_id").From("suggestions").
	Limit(1).LoadStruct(&suggestion)
JSON encoding of Null* types
// dbr.Null* types serialize to JSON like you want
suggestion := &Suggestion{Id: 1, Title: "Test Title"}
jsonBytes, err := json.Marshal(&suggestion)
fmt.Println(string(jsonBytes)) // {"id":1,"title":"Test Title","created_at":null}
Inserting Multiple Records
// Start bulding an INSERT statement
createDevsBuilder := sess.InsertInto("developers").
	Columns("name", "language", "employee_number")

// Add some new developers
for i := 0; i < 3; i++ {
	createDevsBuilder.Record(&Dev{Name: "Gopher", Language: "Go", EmployeeNumber: i})
}

// Execute statment
_, err := createDevsBuilder.Exec()
if err != nil {
	log.Fatalln("Error creating developers", err)
}
Updating Records
// Update any rubyists to gophers
response, err := sess.Update("developers").
	Set("name", "Gopher").
	Set("language", "Go").
	Where("language = ?", "Ruby").Exec()


// Alternatively use a map of attributes to update
attrsMap := map[string]interface{}{"name": "Gopher", "language": "Go"}
response, err := sess.Update("developers").
	SetMap(attrsMap).Where("language = ?", "Ruby").Exec()
Transactions
// Start txn
tx, err := c.Dbr.Begin()
if err != nil {
	return err
}

// Rollback unless we're successful. You can also manually call tx.Rollback() if you'd like.
defer tx.RollbackUnlessCommitted()

// Issue statements that might cause errors
res, err := tx.Update("suggestions").Set("state", "deleted").Where("deleted_at IS NOT NULL").Exec()
if err != nil {
	return err
}

// Commit the transaction
if err := tx.Commit(); err != nil {
	return err
}
Generate SQL without executing
// Create builder
builder := dbrSess.Select("*").From("suggestions").Where("subdomain_id = ?", 1)

// Get builder's SQL and arguments
sql, args := builder.ToSql()
fmt.Println(sql) // SELECT * FROM suggestions WHERE (subdomain_id = ?)
fmt.Println(args) // [1]

// Use raw database/sql for actual query
rows, err := db.Query(sql, args...)
if err != nil {
    log.Fatalln(err)
}

// Alternatively you can build the full query
query, err := dbr.Interpolate(builder.ToSql())
if err != nil {
    log.Fatalln(err)
}
fmt.Println(query) // SELECT * FROM suggestions WHERE (subdomain_id = 1)

gocraft

gocraft offers a toolkit for building web apps. Currently these packages are available:

  • gocraft/web - Go Router + Middleware. Your Contexts.
  • gocraft/dbr - Additions to Go's database/sql for super fast performance and convenience.
  • gocraft/health - Instrument your web apps with logging and metrics.

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:

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound           = errors.New("not found")
	ErrNotUTF8            = errors.New("invalid UTF-8")
	ErrInvalidSliceLength = errors.New("length of slice is 0. length must be >= 1")
	ErrInvalidSliceValue  = errors.New("trying to interpolate invalid slice value into query")
	ErrInvalidValue       = errors.New("trying to interpolate invalid value into query")
	ErrArgumentMismatch   = errors.New("mismatch between ? (placeholders) and arguments")
)
View Source
var NameMapping = camelCaseToSnakeCase

NameMapping is the routine to use when mapping column names to struct properties

View Source
var Now = nowSentinel{}

Now is a value that serializes to the curren time

View Source
var Quoter quoter = MysqlQuoter{}

Quoter is the quoter to use for quoting text; use Mysql quoting by default

Functions

func Expr

func Expr(sql string, values ...interface{}) *expr

Expr is a SQL fragment with placeholders, and a slice of args to replace them with

func Interpolate

func Interpolate(sql string, vals []interface{}) (string, error)

Interpolate takes a SQL string with placeholders and a list of arguments to replace them with. Returns a blank string and error if the number of placeholders does not match the number of arguments.

Types

type Connection

type Connection struct {
	Db *sql.DB
	EventReceiver
}

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

func NewConnection

func NewConnection(db *sql.DB, log EventReceiver) *Connection

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

func (*Connection) NewSession

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

NewSession instantiates a Session for the Connection

type DeleteBuilder

type DeleteBuilder struct {
	*Session

	From           string
	WhereFragments []*whereFragment
	OrderBys       []string
	LimitCount     uint64
	LimitValid     bool
	OffsetCount    uint64
	OffsetValid    bool
	// contains filtered or unexported fields
}

DeleteBuilder contains the clauses for a DELETE statement

func (*DeleteBuilder) Exec

func (b *DeleteBuilder) Exec() (sql.Result, error)

Exec executes the statement represented by the DeleteBuilder It returns the raw database/sql Result and an error if there was one

func (*DeleteBuilder) Limit

func (b *DeleteBuilder) Limit(limit uint64) *DeleteBuilder

Limit sets a LIMIT clause for the statement; overrides any existing LIMIT

func (*DeleteBuilder) Offset

func (b *DeleteBuilder) Offset(offset uint64) *DeleteBuilder

Offset sets an OFFSET clause for the statement; overrides any existing OFFSET

func (*DeleteBuilder) OrderBy

func (b *DeleteBuilder) OrderBy(ord string) *DeleteBuilder

OrderBy appends an ORDER BY clause to the statement

func (*DeleteBuilder) OrderDir

func (b *DeleteBuilder) OrderDir(ord string, isAsc bool) *DeleteBuilder

OrderDir appends an ORDER BY clause with a direction to the statement

func (*DeleteBuilder) ToSql

func (b *DeleteBuilder) ToSql() (string, []interface{})

ToSql serialized the DeleteBuilder to a SQL string It returns the string with placeholders and a slice of query arguments

func (*DeleteBuilder) Where

func (b *DeleteBuilder) Where(whereSqlOrMap interface{}, args ...interface{}) *DeleteBuilder

Where appends a WHERE clause to the statement whereSqlOrMap can be a string or map. If it's a string, args wil replaces any places holders

type Eq

type Eq map[string]interface{}

Eq is a map column -> value pairs which must be matched in a query

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 InsertBuilder

type InsertBuilder struct {
	*Session

	Into string
	Cols []string
	Vals [][]interface{}
	Recs []interface{}
	// contains filtered or unexported fields
}

InsertBuilder contains the clauses for an INSERT statement

func (*InsertBuilder) Columns

func (b *InsertBuilder) Columns(columns ...string) *InsertBuilder

Columns appends columns to insert in the statement

func (*InsertBuilder) Exec

func (b *InsertBuilder) Exec() (sql.Result, error)

Exec executes the statement represented by the InsertBuilder It returns the raw database/sql Result and an error if there was one

func (*InsertBuilder) Pair

func (b *InsertBuilder) Pair(column string, value interface{}) *InsertBuilder

Pair adds a key/value pair to the statement

func (*InsertBuilder) Record

func (b *InsertBuilder) Record(record interface{}) *InsertBuilder

Record pulls in values to match Columns from the record

func (*InsertBuilder) ToSql

func (b *InsertBuilder) ToSql() (string, []interface{})

ToSql serialized the InsertBuilder to a SQL string It returns the string with placeholders and a slice of query arguments

func (*InsertBuilder) Values

func (b *InsertBuilder) Values(vals ...interface{}) *InsertBuilder

Values appends a set of values to the statement

type MysqlQuoter

type MysqlQuoter struct{}

MysqlQuoter implements Mysql-specific quoting

type NullBool

type NullBool struct {
	sql.NullBool
}

NullBool is a type that can be null or a bool

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 (*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 (*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 (*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 {
	mysql.NullTime
}

NullTime is a type that can be null or a time

func (*NullTime) MarshalJSON

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

MarshalJSON correctly serializes a NullTime to JSON

func (*NullTime) UnmarshalJSON

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

UnmarshalJSON correctly deserializes a NullTime from JSON

type PostgresQuoter

type PostgresQuoter struct{}

PostgresQuoter implements PostgreSQL-specific quoting

type SelectBuilder

type SelectBuilder struct {
	*Session

	RawFullSql   string
	RawArguments []interface{}

	IsDistinct      bool
	Columns         []string
	FromTable       string
	WhereFragments  []*whereFragment
	GroupBys        []string
	HavingFragments []*whereFragment
	OrderBys        []string
	LimitCount      uint64
	LimitValid      bool
	OffsetCount     uint64
	OffsetValid     bool
	// contains filtered or unexported fields
}

SelectBuilder contains the clauses for a SELECT statement

func (*SelectBuilder) Distinct

func (b *SelectBuilder) Distinct() *SelectBuilder

Distinct marks the statement as a DISTINCT SELECT

func (*SelectBuilder) From

func (b *SelectBuilder) From(from string) *SelectBuilder

From sets the table to SELECT FROM

func (*SelectBuilder) GroupBy

func (b *SelectBuilder) GroupBy(group string) *SelectBuilder

GroupBy appends a column to group the statement

func (*SelectBuilder) Having

func (b *SelectBuilder) Having(whereSqlOrMap interface{}, args ...interface{}) *SelectBuilder

Having appends a HAVING clause to the statement

func (*SelectBuilder) Limit

func (b *SelectBuilder) Limit(limit uint64) *SelectBuilder

Limit sets a limit for the statement; overrides any existing LIMIT

func (*SelectBuilder) LoadStruct

func (b *SelectBuilder) LoadStruct(dest interface{}) error

LoadStruct executes the SelectBuilder and loads the resulting data into a struct dest must be a pointer to a struct Returns ErrNotFound if nothing was found

func (*SelectBuilder) LoadStructs

func (b *SelectBuilder) LoadStructs(dest interface{}) (int, error)

LoadStructs executes the SelectBuilder and loads the resulting data into a slice of structs dest must be a pointer to a slice of pointers to structs Returns the number of items found (which is not necessarily the # of items set)

func (*SelectBuilder) LoadValue

func (b *SelectBuilder) LoadValue(dest interface{}) error

LoadValue executes the SelectBuilder and loads the resulting data into a primitive value Returns ErrNotFound if no value was found, and it was therefore not set.

func (*SelectBuilder) LoadValues

func (b *SelectBuilder) LoadValues(dest interface{}) (int, error)

LoadValues executes the SelectBuilder and loads the resulting data into a slice of primitive values Returns ErrNotFound if no value was found, and it was therefore not set.

func (*SelectBuilder) Offset

func (b *SelectBuilder) Offset(offset uint64) *SelectBuilder

Offset sets an offset for the statement; overrides any existing OFFSET

func (*SelectBuilder) OrderBy

func (b *SelectBuilder) OrderBy(ord string) *SelectBuilder

OrderBy appends a column to ORDER the statement by

func (*SelectBuilder) OrderDir

func (b *SelectBuilder) OrderDir(ord string, isAsc bool) *SelectBuilder

OrderDir appends a column to ORDER the statement by with a given direction

func (*SelectBuilder) Paginate

func (b *SelectBuilder) Paginate(page, perPage uint64) *SelectBuilder

Paginate sets LIMIT/OFFSET for the statement based on the given page/perPage Assumes page/perPage are valid. Page and perPage must be >= 1

func (*SelectBuilder) ReturnInt64

func (b *SelectBuilder) ReturnInt64() (int64, error)

ReturnInt64 executes the SelectBuilder and returns the value as an int64

func (*SelectBuilder) ReturnInt64s

func (b *SelectBuilder) ReturnInt64s() ([]int64, error)

ReturnInt64s executes the SelectBuilder and returns the value as a slice of int64s

func (*SelectBuilder) ReturnString

func (b *SelectBuilder) ReturnString() (string, error)

ReturnString executes the SelectBuilder and returns the value as a string

func (*SelectBuilder) ReturnStrings

func (b *SelectBuilder) ReturnStrings() ([]string, error)

ReturnStrings executes the SelectBuilder and returns the value as a slice of strings

func (*SelectBuilder) ReturnUint64

func (b *SelectBuilder) ReturnUint64() (uint64, error)

ReturnUint64 executes the SelectBuilder and returns the value as an uint64

func (*SelectBuilder) ReturnUint64s

func (b *SelectBuilder) ReturnUint64s() ([]uint64, error)

ReturnUint64s executes the SelectBuilder and returns the value as a slice of uint64s

func (*SelectBuilder) ToSql

func (b *SelectBuilder) ToSql() (string, []interface{})

ToSql serialized the SelectBuilder to a SQL string It returns the string with placeholders and a slice of query arguments

func (*SelectBuilder) Where

func (b *SelectBuilder) Where(whereSqlOrMap interface{}, args ...interface{}) *SelectBuilder

Where appends a WHERE clause to the statement for the given string and args or map of column/value pairs

type Session

type Session struct {
	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) DeleteFrom

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

DeleteFrom creates a new DeleteBuilder for the given table

func (*Session) InsertInto

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

InsertInto instantiates a InsertBuilder for the given table

func (*Session) Select

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

Select creates a new SelectBuilder that select that given columns

func (*Session) SelectBySql

func (sess *Session) SelectBySql(sql string, args ...interface{}) *SelectBuilder

SelectBySql creates a new SelectBuilder for the given SQL string and arguments

func (*Session) Update

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

Update creates a new UpdateBuilder for the given table

func (*Session) UpdateBySql

func (sess *Session) UpdateBySql(sql string, args ...interface{}) *UpdateBuilder

UpdateBySql creates a new UpdateBuilder for the given SQL string and arguments

type SessionRunner

type SessionRunner interface {
	Select(cols ...string) *SelectBuilder
	SelectBySql(sql string, args ...interface{}) *SelectBuilder

	InsertInto(into string) *InsertBuilder
	Update(table string) *UpdateBuilder
	UpdateBySql(sql string, args ...interface{}) *UpdateBuilder
	DeleteFrom(from string) *DeleteBuilder
}

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

type Tx

type Tx struct {
	*Session
	*sql.Tx
}

Tx is a transaction for the given Session

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit finishes the transaction

func (*Tx) DeleteFrom

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

DeleteFrom creates a new DeleteBuilder for the given table in the context for a transaction

func (*Tx) InsertInto

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

InsertInto instantiates a InsertBuilder for the given table bound to a transaction

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(cols ...string) *SelectBuilder

Select creates a new SelectBuilder that select that given columns bound to the transaction

func (*Tx) SelectBySql

func (tx *Tx) SelectBySql(sql string, args ...interface{}) *SelectBuilder

SelectBySql creates a new SelectBuilder for the given SQL string and arguments bound to the transaction

func (*Tx) Update

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

Update creates a new UpdateBuilder for the given table bound to a transaction

func (*Tx) UpdateBySql

func (tx *Tx) UpdateBySql(sql string, args ...interface{}) *UpdateBuilder

UpdateBySql creates a new UpdateBuilder for the given SQL string and arguments bound to a transaction

type UpdateBuilder

type UpdateBuilder struct {
	*Session

	RawFullSql   string
	RawArguments []interface{}

	Table          string
	SetClauses     []*setClause
	WhereFragments []*whereFragment
	OrderBys       []string
	LimitCount     uint64
	LimitValid     bool
	OffsetCount    uint64
	OffsetValid    bool
	// contains filtered or unexported fields
}

UpdateBuilder contains the clauses for an UPDATE statement

func (*UpdateBuilder) Exec

func (b *UpdateBuilder) Exec() (sql.Result, error)

Exec executes the statement represented by the UpdateBuilder It returns the raw database/sql Result and an error if there was one

func (*UpdateBuilder) Limit

func (b *UpdateBuilder) Limit(limit uint64) *UpdateBuilder

Limit sets a limit for the statement; overrides any existing LIMIT

func (*UpdateBuilder) Offset

func (b *UpdateBuilder) Offset(offset uint64) *UpdateBuilder

Offset sets an offset for the statement; overrides any existing OFFSET

func (*UpdateBuilder) OrderBy

func (b *UpdateBuilder) OrderBy(ord string) *UpdateBuilder

OrderBy appends a column to ORDER the statement by

func (*UpdateBuilder) OrderDir

func (b *UpdateBuilder) OrderDir(ord string, isAsc bool) *UpdateBuilder

OrderDir appends a column to ORDER the statement by with a given direction

func (*UpdateBuilder) Set

func (b *UpdateBuilder) Set(column string, value interface{}) *UpdateBuilder

Set appends a column/value pair for the statement

func (*UpdateBuilder) SetMap

func (b *UpdateBuilder) SetMap(clauses map[string]interface{}) *UpdateBuilder

SetMap appends the elements of the map as column/value pairs for the statement

func (*UpdateBuilder) ToSql

func (b *UpdateBuilder) ToSql() (string, []interface{})

ToSql serialized the UpdateBuilder to a SQL string It returns the string with placeholders and a slice of query arguments

func (*UpdateBuilder) Where

func (b *UpdateBuilder) Where(whereSqlOrMap interface{}, args ...interface{}) *UpdateBuilder

Where appends a WHERE clause to the statement

Jump to

Keyboard shortcuts

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