fjord

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2017 License: MIT Imports: 13 Imported by: 0

README

fjord

CircleCI

fjord is a Golang Struct/databaseRecord Mapper (thin O/R Mapper) package.

fjord

Driver support

  • PostgreSQL 9.6
  • (MySQL 5.6)

Go versions

  • 1.8

Install

go get "github.com/iktakahiro/fjord"

If you use glide:

glide get "github.com/iktakahiro/fjord"

Getting Started

import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/iktakahiro/fjord"
)


dsn := "fj_test:password@tcp(127.0.0.1:3306)/fj_test?charset=utf8mb4,utf8"
conn, _ := fjord.Open("mysql", dsn)

// for PostgreSQL
// dsn := "user=fj_test dbname=fj_test password=password sslmode=disable"
// conn, _ := fjord.Open("postgres", dsn)


sess := conn.NewSession(nil)

var suggestion Suggestion

sess.Select("id", "title").
    From("suggestions").
    Where("id = ?", 1).
    Load(&suggestion)

Context Support

fjord supports context:

conn, _ := fjord.Open("mysql", dsn)

ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)

sess := conn.NewSessionContext(ctx, nil)

options := &sql.TxOptions{
    Isolation: sql.LevelDefault,
    ReadOnly:  false,
}

// options may be nil.
tx, _ := sess.BeginTx(options)

// sleep to time out
time.Sleep(200 * time.Millisecond)

_, err = tx.Update("person").Where(Eq("id", 1)).Set("name", "john Titor").Exec()
if err != nil {
   // context.DeadlineExceeded is occurred.
}

JOIN using Tag and Identifier

This syntax is one of the key features in fjord.

import (
    _ "github.com/go-sql-driver/mysql"
    fj "github.com/iktakahiro/fjord"
)

type Person struct {
    ID   int    `db:"p.id"` // "p" is the alias name of "person table", "id" is a column name.
    Name string `db:"p.name"`
}

type Role struct {
    PersonID int    `db:"r.person_id"`
    Name     string `db:"r.name"`
}

type PersonForJoin struct {
    Person
    Role
}

// ...

person := &PersonForJoin{ID: 1}

sess.Select(fj.I("p.id"), fj.I("p.name"), fj.I("r.person_id"), fj.I("r.name")).
    From(fj.I("person").As("p")).
    LeftJoin(fj.I("role").As("r"), "p.id = r.person_id").
    Where("p.id = ?", person.ID).
    Load(person)

// In MySQL dialect:
// SELECT `p`.`id` AS p__id, `p`.`name` AS p__Name, `r`.`person_id` r__person_id, `r`.`name`
//    FROM `person` AS p
//    LEFT JOIN `role` AS r on p.id = r.person_id
//    WHERE p.id = 1;
//
// Results of mapping:
//     person.id      => PersonForJoin.Person.ID
//     person.name    => PersonForJoin.Person.Name
//     role.person_id => PersonForJoin.Role.PersonID
//     role.name      => PersonForJoin.Role.Name

When a tag contains ".", converts a column name for loading destination into the alias format.

  • db:"p.id" => p__id

And, when you use I() function in a select statement, a column alias is generated automatically.

  • Select(I("p.id")) => SELECT p.id AS p__id FROM...

The above syntax is same as:

  • Select(I("p.id").As("p__id"))
  • Select("p.id AS p__id")

CRUD

CRUD example using the bellow struct.

type Suggestion struct {
    ID    int64
    Title string
    Body  fjord.NullString
}
SELECT
var suggestion Suggestion

sess.Select("id", "title").
    From("suggestion").
    Where("id = ?", 1).
    Load(&suggestion)

You can implement as a method:

func (s *Suggestion) LoadByID(sess *fjord.session) (count int, err error) {
    count, err = sess.Select("id", "title").
    From("suggestion").
    Where("id = ?", s.ID).
    Load(&s)
           
    return
}

// suggestion := &Suggestion{ID: 1}
// count, err := suggestion.LoadByID(sess)
INSERT
suggestion := &Suggestion{Title: "Gopher", Body: "I love Go."}

sess.InsertInto("suggestion").
    Columns("title", "body").
    Record(suggestion).
    Exec()

As a method:

func(s *Suggestion) Save(sess *fjord.session) (err error) {
    err = sess.InsertInto("suggestion").
        Columns("title", "body").
        Record(s).
        Exec()
           
    return
}

You can also set values to insert directly:

sess.InsertInto("suggestion").
    Columns("title", "body").
    Values("Gopher", "I love Go.").
    Exec()

Inserting multiple records:

sess.InsertInto("suggestion").
    Columns("title", "body").
    Record(suggestion1).
    Record(suggestion2).
    Exec()
UPDATE
sess.Update("suggestions").
    Set("title", "Gopher").
    Set("body", "We love Go.").
    Where("id = ?", 1).
    Exec()

SetMap() is helpful when you need to update multiple columns.

setMap := map[string]interface{}{
    "title": "Gopher",
    "body":  "We love Go.",
}

sess.Update("suggestion").
    SetMap(setMap).
    Where("id = ?", 1).
    Exec()
DELETE
sess.DeleteFrom("suggestion").
    Where("id = ?", 1).
    Exec()

Soft Delete is not implemented, use Update() manually.

sess.Update("suggestion").
    Set("deleted_at", time.Now().Unix()).
    Where("id = ?", 1).
    Exec()

Transactions

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

// do stuff...

return tx.Commit()

Load database values to struct fields

// Columns are mapped by tag then by field
type Suggestion struct {
    ID     int64            // id
    Title  string           // title
    Url    string           `db:"-"` // ignored
    secret string           // ignored
    Body   fjord.NullString `db:"content"` // content
    User   User
}

// By default, fjord converts CamelCase field names to snake_case column_names
// You can override this with struct tags, just like with JSON tags
type Suggestion struct {
    Id        int64
    Title     fjord.NullString `db:"subject"` // subjects are called titles now
    CreatedAt fjord.NullTime
}

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

Table name alias

sess.Select("s.id", "s.title").
    From(fjord.I("suggestion").As("s")).
    Load(&suggestions)

JOIN

sess.Select("*").From("suggestion").
  Join("subdomain", "suggestion.subdomain_id = subdomain.id")

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

sess.Select("*").From("suggestion").
  RightJoin("subdomain", "suggestion.subdomain_id = subdomain.id")

sess.Select("*").From("suggestion").
  FullJoin("subdomain", "suggestion.subdomain_id = subdomain.id")

You can join on multiple tables:

sess.Select("*").From("suggestion").
  Join("subdomain", "suggestion.subdomain_id = subdomain.id").
  Join("account", "subdomain.account_id = account.id")

Sub Query

sess.Select("count(id)").From(
    fjord.Select("*").From("suggestion").As("count"),
)

IN

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

Union

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

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

Union can be used in subquery.

fjord.Union(
    fjord.Select("*"),
    fjord.Select("*"),
).As("u1")

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

Building WHERE condition

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

Plain SQL

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

JSON Friendly Null* types

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

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

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

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

Tips

Is the package name too long for humans? Set an alias.

import (
    fj "github.com/iktakahiro/fjord"
)

condition := fj.Eq("id", 1)

Thanks

gocraft/dbr

fjord is gocraft/dbr fork. gocraft/dbr is a suitable package in many cases.

I'm deeply grateful to the awesome project.

Pictures

The pretty beautiful picture is taken by @tpsdave.

Documentation

Index

Constants

This section is empty.

Variables

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

package errors

View Source
var Now = nowSentinel{}

Now is a value that serializes to the current time

Functions

func InterpolateForDialect

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

InterpolateForDialect replaces placeholder in query with corresponding value in dialect

func Union

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

func UnionAll

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

Types

type Buffer

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

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

func NewBuffer

func NewBuffer() Buffer

type BuildFunc

type BuildFunc func(Dialect, Buffer) error

func (BuildFunc) Build

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

type Builder

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

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

func And

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

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

Gt is `>`.

func Gte

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

Gte is '>='.

func Lt

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

Lt is '<'.

func Lte

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

Lte is `<=`.

func Neq

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

func Or(cond ...Builder) Builder

Or creates OR from a list of conditions

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

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.0.0

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

type DeleteBuilder

type DeleteBuilder struct {
	EventReceiver
	Dialect Dialect

	*DeleteStmt

	LimitCount int64
	// contains filtered or unexported fields
}

func (*DeleteBuilder) Build

func (b *DeleteBuilder) Build(d Dialect, buf Buffer) error

func (*DeleteBuilder) Exec

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

func (*DeleteBuilder) Limit

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

func (*DeleteBuilder) Where

func (b *DeleteBuilder) Where(query interface{}, value ...interface{}) *DeleteBuilder

type DeleteStmt

type DeleteStmt struct {
	Table string

	WhereCond []Builder
	// contains filtered or unexported fields
}

DeleteStmt builds `DELETE ...`

func DeleteBySql

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

DeleteBySql creates a DeleteStmt from raw query

func DeleteFrom

func DeleteFrom(table string) *DeleteStmt

DeleteFrom creates a DeleteStmt

func (*DeleteStmt) Build

func (b *DeleteStmt) Build(d Dialect, buf Buffer) error

Build builds `DELETE ...` in dialect

func (*DeleteStmt) Where

func (b *DeleteStmt) Where(query interface{}, value ...interface{}) *DeleteStmt

Where adds a where condition

type Dialect

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
}

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 fjord methods for logging purposes

type I

type I string

identifier is a type of string

func (I) As

func (i I) As(alias string) Builder

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

func (I) Build

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

type InsertBuilder

type InsertBuilder struct {
	EventReceiver
	Dialect Dialect

	RecordID reflect.Value

	*InsertStmt
	// contains filtered or unexported fields
}

func (*InsertBuilder) Columns

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

func (*InsertBuilder) Exec

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

func (*InsertBuilder) Pair

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

func (*InsertBuilder) Record

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

func (*InsertBuilder) Values

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

type InsertStmt

type InsertStmt struct {
	Table  string
	Column []string
	Value  [][]interface{}
	// contains filtered or unexported fields
}

InsertStmt builds `INSERT INTO ...`

func InsertBySql

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

InsertBySql creates an InsertStmt from raw query

func InsertInto

func InsertInto(table string) *InsertStmt

InsertInto creates an InsertStmt

func (*InsertStmt) Build

func (b *InsertStmt) Build(d Dialect, buf Buffer) error

Build builds `INSERT INTO ...` in dialect

func (*InsertStmt) Columns

func (b *InsertStmt) Columns(column ...string) *InsertStmt

Columns adds columns

func (*InsertStmt) Record

func (b *InsertStmt) Record(structValue interface{}) *InsertStmt

Record adds a tuple for columns from a struct

func (*InsertStmt) Values

func (b *InsertStmt) Values(value ...interface{}) *InsertStmt

Values adds a tuple for columns

type NullBool

type NullBool struct {
	sql.NullBool
}

NullBool is a type that can be null or a bool

func NewNullBool

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

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

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

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

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

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

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

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

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

func (NullTime) MarshalJSON

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

MarshalJSON correctly serializes a NullTime to JSON

func (*NullTime) Scan

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

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

Value implements the driver Valuer interface.

type SelectBuilder

type SelectBuilder struct {
	EventReceiver
	Dialect Dialect

	*SelectStmt
	// contains filtered or unexported fields
}

func (*SelectBuilder) Distinct

func (b *SelectBuilder) Distinct() *SelectBuilder

func (*SelectBuilder) From

func (b *SelectBuilder) From(table interface{}) *SelectBuilder

func (*SelectBuilder) FullJoin

func (b *SelectBuilder) FullJoin(table, on interface{}) *SelectBuilder

func (*SelectBuilder) GroupBy

func (b *SelectBuilder) GroupBy(col ...string) *SelectBuilder

func (*SelectBuilder) Having

func (b *SelectBuilder) Having(query interface{}, value ...interface{}) *SelectBuilder

func (*SelectBuilder) Join

func (b *SelectBuilder) Join(table, on interface{}) *SelectBuilder

func (*SelectBuilder) LeftJoin

func (b *SelectBuilder) LeftJoin(table, on interface{}) *SelectBuilder

func (*SelectBuilder) Limit

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

func (*SelectBuilder) Load

func (b *SelectBuilder) Load(value interface{}) (int, error)

func (*SelectBuilder) Offset

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

func (*SelectBuilder) OrderBy

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

func (*SelectBuilder) OrderDir

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

func (*SelectBuilder) Paginate

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

func (*SelectBuilder) RightJoin

func (b *SelectBuilder) RightJoin(table, on interface{}) *SelectBuilder

func (*SelectBuilder) Where

func (b *SelectBuilder) Where(query interface{}, value ...interface{}) *SelectBuilder

type SelectStmt

type SelectStmt struct {
	IsDistinct bool

	Column    []interface{}
	Table     interface{}
	JoinTable []Builder

	WhereCond  []Builder
	Group      []Builder
	HavingCond []Builder
	Order      []Builder

	LimitCount  int64
	OffsetCount int64
	// contains filtered or unexported fields
}

SelectStmt builds `SELECT ...`

func Select

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

Select creates a SelectStmt

func SelectBySql

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

SelectBySql creates a SelectStmt from raw query

func (*SelectStmt) As

func (b *SelectStmt) As(alias string) Builder

As creates alias for select statement

func (*SelectStmt) Build

func (b *SelectStmt) Build(d Dialect, buf Buffer) error

Build builds `SELECT ...` in dialect

func (*SelectStmt) Distinct

func (b *SelectStmt) Distinct() *SelectStmt

Distinct adds `DISTINCT`

func (*SelectStmt) From

func (b *SelectStmt) From(table interface{}) *SelectStmt

From specifies table

func (*SelectStmt) FullJoin

func (b *SelectStmt) FullJoin(table, on interface{}) *SelectStmt

func (*SelectStmt) GroupBy

func (b *SelectStmt) GroupBy(col ...string) *SelectStmt

GroupBy specifies columns for grouping

func (*SelectStmt) Having

func (b *SelectStmt) Having(query interface{}, value ...interface{}) *SelectStmt

Having adds a `HAVING` condition

func (*SelectStmt) Join

func (b *SelectStmt) Join(table, on interface{}) *SelectStmt

Join joins table on condition

func (*SelectStmt) LeftJoin

func (b *SelectStmt) LeftJoin(table, on interface{}) *SelectStmt

func (*SelectStmt) Limit

func (b *SelectStmt) Limit(n uint64) *SelectStmt

Limit adds `LIMIT`

func (*SelectStmt) Offset

func (b *SelectStmt) Offset(n uint64) *SelectStmt

Offset adds `OFFSET`

func (*SelectStmt) OrderAsc

func (b *SelectStmt) OrderAsc(col string) *SelectStmt

OrderAsc specifies columns for ordering

func (*SelectStmt) OrderDesc

func (b *SelectStmt) OrderDesc(col string) *SelectStmt

OrderDesc specifies columns for ordering

func (*SelectStmt) RightJoin

func (b *SelectStmt) RightJoin(table, on interface{}) *SelectStmt

func (*SelectStmt) Where

func (b *SelectStmt) Where(query interface{}, value ...interface{}) *SelectStmt

Where adds a `WHERE` condition

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) BeginTx added in v1.0.0

func (sess *Session) BeginTx(options *sql.TxOptions) (*Tx, error)

BeginTx starts a transaction with context.

func (*Session) DeleteBySql

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

func (*Session) DeleteFrom

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

func (*Session) Exec added in v1.0.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

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

func (*Session) InsertInto

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

func (*Session) Query added in v1.0.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 ...interface{}) *SelectBuilder

func (*Session) SelectBySql

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

func (*Session) Update

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

func (*Session) UpdateBySql

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

type SessionRunner

type SessionRunner interface {
	Select(column ...interface{}) *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 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

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

func (*Tx) DeleteFrom

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

func (*Tx) Exec added in v1.0.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

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

func (*Tx) InsertInto

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

func (*Tx) Query added in v1.0.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 ...interface{}) *SelectBuilder

func (*Tx) SelectBySql

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

func (*Tx) Update

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

func (*Tx) UpdateBySql

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

type UpdateBuilder

type UpdateBuilder struct {
	EventReceiver
	Dialect Dialect

	*UpdateStmt

	LimitCount int64
	// contains filtered or unexported fields
}

func (*UpdateBuilder) Build

func (b *UpdateBuilder) Build(d Dialect, buf Buffer) error

func (*UpdateBuilder) Exec

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

func (*UpdateBuilder) Limit

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

func (*UpdateBuilder) Set

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

func (*UpdateBuilder) SetMap

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

func (*UpdateBuilder) Where

func (b *UpdateBuilder) Where(query interface{}, value ...interface{}) *UpdateBuilder

type UpdateStmt

type UpdateStmt struct {
	Table string
	Value map[string]interface{}

	WhereCond []Builder
	// contains filtered or unexported fields
}

UpdateStmt builds `UPDATE ...`

func Update

func Update(table string) *UpdateStmt

Update creates an UpdateStmt

func UpdateBySql

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

UpdateBySql creates an UpdateStmt with raw query

func (*UpdateStmt) Build

func (b *UpdateStmt) Build(d Dialect, buf Buffer) error

Build builds `UPDATE ...` in dialect

func (*UpdateStmt) Set

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

Set specifies a key-value pair

func (*UpdateStmt) SetMap

func (b *UpdateStmt) SetMap(m map[string]interface{}) *UpdateStmt

SetMap specifies a list of key-value pair

func (*UpdateStmt) Where

func (b *UpdateStmt) Where(query interface{}, value ...interface{}) *UpdateStmt

Where adds a where condition

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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