dat

package module
v0.0.0-...-7a19689 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2015 License: MIT Imports: 22 Imported by: 0

README

** The legacy branch contains the original dat **

dat

GoDoc

dat (Data Access Toolkit) is a fast, lightweight and intuitive Postgres library for Go.

How it is different than other toolkits:

  • Focused on Postgres. See Insect, Upsert, SelectDoc, QueryJSON.

  • Light layer over sqlx

  • SQL and backtick friendly.

    DB.SQL(`SELECT * FROM people LIMIT 10`).QueryStructs(&people)
    
  • Intuitive JSON Document retrieval (single trip to database!)

    DB.SelectDoc("id", "user_name", "avatar").
        Many("recent_comments", `SELECT id, title FROM comments WHERE id = users.id LIMIT 10`).
        Many("recent_posts", `SELECT id, title FROM posts WHERE author_id = users.id LIMIT 10`).
        One("account", `SELECT balance FROM accounts WHERE user_id = users.id`).
        From("users").
        Where("id = $1", 4).
        QueryStruct(&obj) // obj must be agreeable with json.Unmarshal()
    

    results in

    {
        "id": 4,
        "user_name": "mario",
        "avatar": "https://imgur.com/a23x.jpg",
        "recent_comments": [{"id": 1, "title": "..."}],
        "recent_posts": [{"id": 1, "title": "..."}],
        "account": {
            "balance": 42.00
        }
    }
    
  • Simpler JSON retrieval from database (requires Postgres 9.3+)

    var json []byte
    json, _ = DB.SQL(`SELECT id, user_name, created_at FROM users WHERE user_name = $1 `,
        "mario",
    ).QueryJSON()
    
    // straight into map
    var obj map[string]interface{}
    DB.SQL(`SELECT id, user_name, created_at FROM users WHERE user_name = $1 `,
        "mario",
    ).QueryObject(&obj)
    

    both result in

    {
        "id": 1,
        "user_name": "mario",
        "created_at": "2015-03-01T14:23"
    }
    
  • Ordinal placeholders - friendlier than ?

    DB.SQL(`SELECT * FROM people WHERE state = $1`, "CA").Exec()
    
  • Minimal API Surface. No AST-like language to learn.

    err := DB.
        Select("id, user_name").
        From("users").
        Where("id = $1", id).
        QueryStruct(&user)
    
  • Performant

    • ordinal placeholder logic is optimized to be nearly as fast as using ?
    • dat can interpolate queries locally resulting in performance increase over plain database/sql and sqlx. Benchmarks

Getting Started

Get it

go get -u gopkg.in/mgutz/dat.v1

Use it

import (
    "database/sql"

    _ "github.com/lib/pq"
    "gopkg.in/mgutz/data.v1"
    "gopkg.in/mgutz/data.v1/sqlx-runner"
)

// global database (pooling provided by SQL driver)
var DB *runner.DB

func init() {
    // create a normal database connection through database/sql
    db, err := sql.Open("postgres", "dbname=dat_test user=dat password=!test host=localhost sslmode=disable")
    if err != nil {
        panic(err)
    }

    // set this to enable interpolation
    dat.EnableInterpolation = true
    // set to check things like sessions closing.
    // Should be disabled in production/release builds.
    dat.Strict = false
    DB = runner.NewDB(db, "postgres")
}

type Post struct {
    ID        int64         `db:"id"`
    Title     string        `db:"title"`
    Body      string        `db:"body"`
    UserID    int64         `db:"user_id"`
    State     string        `db:"state"`
    UpdatedAt dat.Nulltime  `db:"updated_at"`
    CreatedAt dat.NullTime  `db:"created_at"`
}

func main() {
    var post Post
    err := DB.
        Select("id, title").
        From("posts").
        Where("id = $1", 13).
        QueryStruct(&post)
    fmt.Println("Title", post.Title)
}

Feature highlights

Use Builders or SQL

Query Builder

var posts []*Post
err := DB.
    Select("title", "body").
    From("posts").
    Where("created_at > $1", someTime).
    OrderBy("id ASC").
    Limit(10).
    QueryStructs(&posts)

Plain SQL

err = DB.SQL(`
    SELECT title, body
    FROM posts WHERE created_at > $1
    ORDER BY id ASC LIMIT 10`,
    someTime,
).QueryStructs(&posts)

Note: dat does not trim the SQL string, thus any extra whitespace is transmitted to the database.

In practice, SQL is easier to write with backticks. Indeed, the reason this library exists is my dissatisfaction with other SQL builders introducing another domain language or AST-like expressions.

Query builders shine when dealing with data transfer objects, structs.

Fetch Data Simply

Query then scan result to struct(s)

var post Post
err := DB.
    Select("id, title, body").
    From("posts").
    Where("id = $1", id).
    QueryStruct(&post)

var posts []*Post
err = DB.
    Select("id, title, body").
    From("posts").
    Where("id > $1", 100).
    QueryStructs(&posts)

Query scalar values or a slice of values

var n int64
DB.SQL("SELECT count(*) FROM posts WHERE title=$1", title).QueryScalar(&n)

var ids []int64
DB.SQL("SELECT id FROM posts", title).QuerySlice(&ids)
Blacklist and Whitelist

Control which columns get inserted or updated when processing external data

// userData came in from http.Handler, prevent them from setting protected fields
DB.InsertInto("payments").
    Blacklist("id", "updated_at", "created_at").
    Record(userData).
    Returning("id").
    QueryScalar(&userData.ID)

// ensure session user can only update his information
DB.Update("users").
    SetWhitelist(user, "user_name", "avatar", "quote").
    Where("id = $1", session.UserID).
    Exec()
IN queries

applicable when dat.EnableInterpolation == true

Simpler IN queries which expand correctly

ids := []int64{10,20,30,40,50}
b := DB.SQL("SELECT * FROM posts WHERE id IN $1", ids)
b.MustInterpolate() == "SELECT * FROM posts WHERE id IN (10,20,30,40,50)"
Runners

dat was designed to have clear separation between SQL builders and Query execers. This is why the runner is in its own package.

  • sqlx-runner - based on sqlx
Tracing SQL

dat uses logxi for logging. To trace SQL set environment variable

LOGXI=dat* yourapp

CRUD

Create

Use Returning and QueryStruct to insert and update struct fields in one trip

post := Post{Title: "Swith to Postgres", State: "open"}

err := DB.
    InsertInto("posts").
    Columns("title", "state").
    Values("My Post", "draft").
    Returning("id", "created_at", "updated_at").
    QueryStruct(&post)

Use Blacklist and Whitelist to control which record (input struct) fields are inserted.

post := Post{Title: "Go is awesome", State: "open"}
err := DB.
    InsertInto("posts").
    Blacklist("id", "user_id", "created_at", "updated_at").
    Record(post).
    Returning("id", "created_at", "updated_at").
    QueryStruct(&post)

// use wildcard to include all columns
err := DB.
    InsertInto("posts").
    Whitelist("*").
    Record(post).
    Returning("id", "created_at", "updated_at").
    QueryStruct(&post)

Insert Multiple Records

// create builder
b := DB.InsertInto("posts").Columns("title")

// add some new posts
for i := 0; i < 3; i++ {
    b.Record(&Post{Title: fmt.Sprintf("Article %s", i)})
}

// OR (this is more efficient as it does not do any reflection)
for i := 0; i < 3; i++ {
    b.Values(fmt.Sprintf("Article %s", i))
}

// execute statement
_, err := b.Exec()

Inserts if not exists or select in one-trip to database

sql, args := DB.
    Insect("tab").
    Columns("b", "c").
    Values(1, 2).
    Where("d = $1", 3).
    Returning("id", "f", "g").
    ToSQL()

sql == `
WITH
    sel AS (SELECT id, f, g FROM tab WHERE (d = $1)),
    ins AS (
        INSERT INTO "tab"("b","c")
        SELECT $2,$3
        WHERE NOT EXISTS (SELECT 1 FROM sel)
        RETURNING "id","f","g"
    )
SELECT * FROM ins UNION ALL SELECT * FROM sel
`
Read
var other Post

err = DB.
    Select("id, title").
    From("posts").
    Where("id = $1", post.ID).
    QueryStruct(&other)

published := dat.NewScope(
    "WHERE user_id = :userID AND state = 'published'",
    dat.M{"userID": 0},
)

var posts []*Post
err = DB.
    Select("id, title").
    From("posts").
    ScopeMap(published, dat.M{"userID": 100})
    QueryStructs(&posts)
Update

Use Returning to fetch columns updated by triggers. For example, an update trigger on "updated_at" column

err = DB.
    Update("posts").
    Set("title", "My New Title").
    Set("body", "markdown text here").
    Where("id = $1", post.ID).
    Returning("updated_at").
    QueryScalar(&post.UpdatedAt)

Upsert - Update or Insert

sql, args := DB.
    Upsert("tab").
    Columns("b", "c").
    Values(1, 2).
    Where("d=$1", 4).
    Returning("f", "g").
    ToSQL()

expected := `
WITH
    upd AS (
        UPDATE tab
        SET "b" = $1, "c" = $2
        WHERE (d=$3)
        RETURNING "f","g"
    ), ins AS (
        INSERT INTO "tab"("b","c")
        SELECT $1,$2
        WHERE NOT EXISTS (SELECT 1 FROM upd)
        RETURNING "f","g"
    )
SELECT * FROM ins UNION ALL SELECT * FROM upd
`

applicable when dat.EnableInterpolation == true

To reset columns to their default DDL value, use DEFAULT. For example, to reset payment\_type

res, err := DB.
    Update("payments").
    Set("payment_type", dat.DEFAULT).
    Where("id = $1", 1).
    Exec()

Use SetBlacklist and SetWhitelist to control which fields are updated.

// create blacklists for each of your structs
blacklist := []string{"id", "created_at"}
p := paymentStructFromHandler

err := DB.
    Update("payments").
    SetBlacklist(p, blacklist...)
    Where("id = $1", p.ID).
    Exec()

Use a map of attributes

attrsMap := map[string]interface{}{"name": "Gopher", "language": "Go"}
result, err := DB.
    Update("developers").
    SetMap(attrsMap).
    Where("language = $1", "Ruby").
    Exec()
Delete
result, err = DB.
    DeleteFrom("posts").
    Where("id = $1", otherPost.ID).
    Limit(1).
    Exec()
Joins

Define JOINs as arguments to From

err = DB.
    Select("u.*, p.*").
    From(`
        users u
        INNER JOIN posts p on (p.author_id = u.id)
    `).
    WHERE("p.state = 'published'").
    QueryStructs(&liveAuthors)
Scopes

Scopes predefine JOIN and WHERE conditions. Scopes may be used with DeleteFrom, Select and Update.

As an example, a "published" scoped might define published posts by user.

publishedPosts := `
    INNER JOIN users u on (p.author_id = u.id)
    WHERE
        p.state == 'published' AND
        p.deleted_at IS NULL AND
        u.user_name = $1
`

unpublishedPosts := `
    INNER JOIN users u on (p.author_id = u.id)
    WHERE
        p.state != 'published' AND
        p.deleted_at IS NULL AND
        u.user_name = $1
`

err = DB.
    Select("p.*").                      // must qualify columns
    From("posts p").
    Scope(publishedPosts, "mgutz").
    QueryStructs(&posts)

Creating Connections

All queries are made in the context of a connection which are acquired from the underlying SQL driver's pool

For one-off operations, use DB directly

// a global connection usually created in `init`
DB := runner.NewDB(db, "postgres")

err := DB.SQL(...).QueryStruct(&post)

For multiple operations, create a Tx transaction. defer Tx.AutoCommit() or defer Tx.AutoRollback() MUST be called


func PostsIndex(rw http.ResponseWriter, r *http.Request) {
    tx, _ := DB.Begin()
    defer tx.AutoRollback()

    // Do queries with the session
    var post Post
    err := tx.Select("id, title").
        From("posts").
        Where("id = $1", post.ID).
        QueryStruct(&post)
    )
    if err != nil {
        // `defer AutoRollback()` is used, no need to rollback on error
        r.WriteHeader(500)
        return
    }

    // do more queries with transaction ...

    // MUST commit or AutoRollback() will rollback
    tx.Commit()
}

DB and Tx implement runner.Connection interface

func getUsers(conn runner.Connection) ([]*dto.Users, error) {
    sql := `
        SELECT *
        FROM users
    `
    var users dto.Users
    err := conn.SQL(sql).QueryStructs(&users)
    if err != nil {
        return err
    }
    return users
}
Dates

Dates are a pain in go. Use dat.NullTime type to properly handle nullable dates from JSON and Postgres.

Constants

applicable when dat.EnableInterpolation == true

dat provides often used constants in SQL statements

  • dat.DEFAULT - inserts DEFAULT
  • dat.NOW - inserts NOW()
Defining Constants

UnsafeStrings and constants will panic unless dat.EnableInterpolation == true

To define SQL constants, use UnsafeString

const CURRENT_TIMESTAMP = dat.UnsafeString("NOW()")
DB.SQL("UPDATE table SET updated_at = $1", CURRENT_TIMESTAMP)

UnsafeString is exactly that, UNSAFE. If you must use it, create a constant and NEVER use UnsafeString directly as an argument. This is asking for a SQL injection attack

DB.SQL("UPDATE table SET updated_at = $1", dat.UnsafeString(someVar))
Primitive Values

Load scalar and slice values.

var id int64
var userID string
err := DB.
    Select("id", "user_id").From("posts").Limit(1).QueryScalar(&id, &userID)

var ids []int64
err = DB.Select("id").From("posts").QuerySlice(&ids)
Embedded structs
// Columns are mapped to fields breadth-first
type Post struct {
    ID        int64      `db:"id"`
    Title     string     `db:"title"`
    User      *struct {
        ID int64         `db:"user_id"`
    }
}

var post Post
err := DB.
    Select("id, title, user_id").
    From("posts").
    Limit(1).
    QueryStruct(&post)
Transactions
// Start transaction
tx, err := DB.Begin()
if err != nil {
    return err
}
// safe to call tx.Rollback() or tx.Commit() when deferring AutoCommit()
defer tx.AutoCommit()

// AutoRollback() is also available if you would rather Commit() at the end
// and not deal with Rollback on every error.

// Issue statements that might cause errors
res, err := tx.
    Update("posts").
    Set("state", "deleted").
    Where("deleted_at IS NOT NULL").
    Exec()

if err != nil {
    tx.Rollback()
    return err
}
Nested Transactions

Simple nested transaction support works as follows:

  • If Commit is called in a nested transaction, the operation results in a NOOP. Only the top level Commit commits a transaction to the database.

  • If Rollback is called in a nested transaction, then the entire transaction is rollbacked. Tx.IsRollbacked is set to true.

  • Either defer Tx.AutoCommit() or defer Tx.AutoRollback() MUST BE CALLED for each corresponding Begin. The internal state of nested transaction is cleaned up in these two methods.

func nested(conn runner.Connection) error {
    tx, err := conn.Begin()
    if err != nil {
        return err
    }
    defer tx.AutoRollback()

    _, err := tx.SQL(`INSERT INTO users (email) values $1`, 'me@home.com').Exec()
    if err != nil {
        return err
    }
    // prevents AutoRollback
    tx.Commit()
}

func top() {
    tx, err := DB.Begin()
    if err != nil {
        logger.Fatal("Could not create transaction")
    }
    defer tx.AutoRollback()

    err := nested(tx)
    if err != nil {
        return
    }

    // top level commits the transaction
    tx.Commit()
}
Local Interpolation

Interpolation is DISABLED by default. Set dat.EnableInterpolation = true to enable.

dat can interpolate locally to inline query arguments. Let's start with a normal SQL statements with arguments

db.Exec(
    "INSERT INTO (a, b, c, d) VALUES ($1, $2, $3, $4)",
    []interface{}[1, 2, 3, 4],
)

When the statement agove gets executed:

  1. The driver checks if this SQL has been prepared previously on the current connection, using the SQL as the key
  2. If not, the driver sends the SQL statement to the database to prepare the statement
  3. The prepared statement is assigned to the connection
  4. The prepared satement is executed along with arguments
  5. Received data is sent back to the caller

In contrast, dat can interpolate the statement locally resulting in a SQL statement with often no arguments. The code above results in this interpolated SQL

"INSERT INTO (a, b, c, d) VALUES (1, 2, 3, 4)"

When the statement agove gets executed:

  1. The statement is treated as simple exec and sent with args to database, since len(args) == 0
  2. Received data is sent back to the caller
Interpolation Safety

As of Postgres 9.1, the database does not process escape sequence by default. See String Constants with C-style Escapes. In short, all backslashes are treated literally.

dat escapes single quotes (apostrophes) on small strings, otherwise it uses Postgres' dollar quotes to escape strings. The dollar quote tag is randomized at init. If a string contains the dollar quote tag, the tag is randomized again and if the string still contains the tag, then single quote escaping is used.

As an added safety measure, dat checks the Postgres database standard_conforming_strings setting value on a new connection when dat.EnableInterpolation == true. If standard_conforming_strings != "on" then set set it to "on" or disable interpolation. dat will panic if it the setting is incompatible.

Why is Interpolation Faster?

Here is a comment from lib/pq connection source, which was prompted by me asking why was Python's psycopg2 so much faster in my benchmarks a year or so back:

// Check to see if we can use the "simpleExec" interface, which is
// *much* faster than going through prepare/exec
if len(args) == 0 {
    // ignore commandTag, our caller doesn't care
    r, _, err := cn.simpleExec(query)
    return r, err
}

That snippet bypasses the prepare/exec roundtrip to the database.

Keep in mind that prepared statements are only valid for the current session and unless the same query is be executed MANY times in the same session there is little benefit in using prepared statements other than protecting against SQL injections. See Interpolation Safety section above.

More Reasons to Use Interpolation
  • Performance improvement
  • Debugging is simpler with interpolated SQL
  • Use SQL constants like NOW and DEFAULT
  • Expand placeholders with expanded slice values $1 => (1, 2, 3)

[]byte, []*byte and any unhandled values are passed through to the driver when interpolating.

Use With Other Libraries
import "github.com/mgutz/dat"

builder := dat.Select("*").From("posts").Where("user_id = $1", 1)

// Get builder's SQL and arguments
sql, args := builder.ToSQL()
fmt.Println(sql)    // SELECT * FROM posts WHERE (user_id = $1)
fmt.Println(args)   // [1]

// Use raw database/sql for actual query
rows, err := db.Query(sql, args...)

// Alternatively build the interpolated sql statement
sql, args, err := builder.Interpolate()
if len(args) == 0 {
    rows, err = db.Query(sql)
} else {
    rows, err = db.Query(sql, args...)
}

Running Tests and Benchmarks

To setup the task runner and create database

# install godo task runner
go get -u gopkg.in/godo.v2/cmd/godo

# install dependencies
cd tasks
go get -a

# back to project
cd ..

Then run any task

# (re)create database
godo createdb

# run tests with traced SQL (optional)
LOGXI=dat* godo test

# run tests without logs
godo test

# run benchmarks
godo bench

# see other tasks
godo

When createdb prompts for superuser, enter superuser like 'postgres' to create the test database. On Mac + Postgress.app use your own user name and password.

Documentation

Index

Constants

View Source
const DEFAULT = UnsafeString("DEFAULT")

DEFAULT SQL value

View Source
const NOW = UnsafeString("NOW()")

NOW SQL value

Variables

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

Whether to enable interpolation

View Source
var NameMapping = camelCaseToSnakeCase

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

View Source
var Strict = false

Strict tells dat to raise errors

Functions

func CalculateFieldMap

func CalculateFieldMap(recordType reflect.Type, columns []string,
	requireAllColumns bool) ([][]int, error)

CalculateFieldMap recordType is the type of a structure

func Generate

func Generate(srcDir string, destDir string) error

func Interpolate

func Interpolate(sql string, vals []interface{}) (string, []interface{}, 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.

func ParseDir

func ParseDir(dir string, version string)

ParseDir reads files in a directory "sproc_name"=>"sproc_body"

func ParseSprocName

func ParseSprocName(s string) string

ParseSprocName parses the functiname from given string.

Example ParseSprocName("create function foo_bar()") => "foo_bar"

func PartitionKV

func PartitionKV(r io.Reader, prefix string, assignment string) ([]map[string]string, error)

PartitionKV parses a reader for sections reder for lines containing a prefix and assingment.

func PrepareHolderFor

func PrepareHolderFor(record reflect.Value, fieldMap [][]int, holder []interface{}) ([]interface{}, error)

PrepareHolderFor creates holders for a record.

TODO: fill this in

func SQLMapFromFile

func SQLMapFromFile(filename string) (map[string]string, error)

SQLMapFromFile loads a file containing special markers and loads the SQL statements into a map.

func SQLMapFromReader

func SQLMapFromReader(r io.Reader) (map[string]string, error)

SQLMapFromReader creates a SQL map from an io.Reader.

This string

`
--@selectUsers
SELECT * FROM users;

--@selectAccounts
SELECT * FROM accounts;
`

returns map[string]string{
	"selectUsers": "SELECT * FROM users;",
	"selectACcounts": "SELECT * FROM accounts;",
}

func SQLMapFromString

func SQLMapFromString(s string) (map[string]string, error)

SQLMapFromString creates a map of strings from s.

func SQLSliceFromFile

func SQLSliceFromFile(filename string) ([]string, error)

SQLSliceFromFile reads a file's text then passes it to SQLSliceFromString.

func SQLSliceFromString

func SQLSliceFromString(s string) ([]string, error)

SQLSliceFromString converts a multiline string marked by `^GO$` into a slice of SQL statements.

This string

SELECT *
FROM users;
GO
SELECT *
FROM accounts;

returns []string{"SELECT *\nFROM users;", "SELECT *\nFROM accounts"}

func ValuesFor

func ValuesFor(recordType reflect.Type, record reflect.Value, columns []string) ([]interface{}, error)

ValuesFor does soemthing

TODO:

Types

type Builder

type Builder interface {
	// ToSQL builds the SQL and arguments from builder.
	ToSQL() (string, []interface{})

	// Interpolate builds the interpolation SQL and arguments from builder.
	// If interpolation flag is disabled then this is just a passthrough to ToSQL.
	Interpolate() (string, []interface{}, error)

	// IsInterpolated determines if this builder will interpolate when
	// Interpolate() is called.
	IsInterpolated() bool
}

Builder interface is used to tie SQL generators to executors.

type CallBuilder

type CallBuilder struct {
	Execer
	// contains filtered or unexported fields
}

CallBuilder is a store procedure call builder.

func Call

func Call(sproc string, args ...interface{}) *CallBuilder

Call creates a new CallBuilder for the given sproc and args.

func NewCallBuilder

func NewCallBuilder(sproc string, args ...interface{}) *CallBuilder

NewCallBuilder creates a new CallBuilder for the given sproc name and args.

func (*CallBuilder) Interpolate

func (b *CallBuilder) Interpolate() (string, []interface{}, error)

Interpolate interpolates this builders sql.

func (*CallBuilder) IsInterpolated

func (b *CallBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

func (*CallBuilder) SetIsInterpolated

func (b *CallBuilder) SetIsInterpolated(enable bool) *CallBuilder

SetIsInterpolated sets whether this builder should interpolate.

func (*CallBuilder) ToSQL

func (b *CallBuilder) ToSQL() (string, []interface{})

ToSQL serializes CallBuilder to a SQL string returning valid SQL with placeholders an a slice of query arguments.

type DeleteBuilder

type DeleteBuilder struct {
	Execer
	// contains filtered or unexported fields
}

DeleteBuilder contains the clauses for a DELETE statement

func DeleteFrom

func DeleteFrom(table string) *DeleteBuilder

DeleteFrom creates a new DeleteBuilder for the given table.

func NewDeleteBuilder

func NewDeleteBuilder(table string) *DeleteBuilder

NewDeleteBuilder creates a new DeleteBuilder for the given table.

func (*DeleteBuilder) Interpolate

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

Interpolate interpolates this builders sql.

func (*DeleteBuilder) IsInterpolated

func (b *DeleteBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

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

func (b *DeleteBuilder) Scope(sql string, args ...interface{}) *DeleteBuilder

Scope uses a predefined scope in place of WHERE.

func (*DeleteBuilder) ScopeMap

func (b *DeleteBuilder) ScopeMap(mapScope *MapScope, m M) *DeleteBuilder

ScopeMap uses a predefined scope in place of WHERE.

func (*DeleteBuilder) SetIsInterpolated

func (b *DeleteBuilder) SetIsInterpolated(enable bool) *DeleteBuilder

SetIsInterpolated sets whether this builder should interpolate.

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 Execer

type Execer interface {
	Exec() (*Result, error)
	QueryScalar(destinations ...interface{}) error
	QuerySlice(dest interface{}) error
	QueryStruct(dest interface{}) error
	QueryStructs(dest interface{}) error
	QueryObject(dest interface{}) error
	QueryJSON() ([]byte, error)
}

Execer is any object that executes and queries SQL.

type Expression

type Expression struct {
	Sql  string
	Args []interface{}
}

Expression holds a sub expression.

func Expr

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

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

func (*Expression) WriteRelativeArgs

func (exp *Expression) WriteRelativeArgs(buf common.BufferWriter, args *[]interface{}, pos *int64)

WriteRelativeArgs writes the args to buf adjusting the placeholder to start at pos.

type InsectBuilder

type InsectBuilder struct {
	Execer
	// contains filtered or unexported fields
}

InsectBuilder inserts or selects an existing row when executed.

// Inserts new row unless there exists a record where
// `name='mario' AND email='mario@acme.com'`
conn.Insect("people").
	Columns("name", "email").
	Values("mario", "mario@acme.com").
	Returning("id", "name", "email")

// Inserts unless there exists a record with ID of 1.
// Insect WILL NOT update the row if it exists.
conn.Insect("people").
	Columns("name", "email").
	Values("mario", "mario@acme.com").
	Where("id=$1", 1).
	Returning("id", "name", "email")

func Insect

func Insect(table string) *InsectBuilder

Insect inserts into a table if does not exist.

func NewInsectBuilder

func NewInsectBuilder(table string) *InsectBuilder

NewInsectBuilder creates a new InsectBuilder for the given table.

func (*InsectBuilder) Blacklist

func (b *InsectBuilder) Blacklist(columns ...string) *InsectBuilder

Blacklist defines a blacklist of columns and should only be used in conjunction with Record.

func (*InsectBuilder) Columns

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

Columns appends columns to insert in the statement

func (*InsectBuilder) Interpolate

func (b *InsectBuilder) Interpolate() (string, []interface{}, error)

Interpolate interpolates this builders sql.

func (*InsectBuilder) IsInterpolated

func (b *InsectBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

func (*InsectBuilder) Record

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

Record pulls in values to match Columns from the record

func (*InsectBuilder) Returning

func (b *InsectBuilder) Returning(columns ...string) *InsectBuilder

Returning sets the columns for the RETURNING clause

func (*InsectBuilder) SetIsInterpolated

func (b *InsectBuilder) SetIsInterpolated(enable bool) *InsectBuilder

SetIsInterpolated sets whether this builder should interpolate.

func (*InsectBuilder) ToSQL

func (b *InsectBuilder) ToSQL() (string, []interface{})

ToSQL serialized the InsectBuilder to a SQL string It returns the string with placeholders and a slice of query arguments

func (*InsectBuilder) Values

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

Values appends a set of values to the statement

func (*InsectBuilder) Where

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

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

func (*InsectBuilder) Whitelist

func (b *InsectBuilder) Whitelist(columns ...string) *InsectBuilder

Whitelist defines a whitelist of columns to be inserted. To specify all columsn of a record use "*".

type InsertBuilder

type InsertBuilder struct {
	Execer
	// contains filtered or unexported fields
}

InsertBuilder contains the clauses for an INSERT statement

func InsertInto

func InsertInto(table string) *InsertBuilder

InsertInto creates a new InsertBuilder for the given table.

func NewInsertBuilder

func NewInsertBuilder(table string) *InsertBuilder

NewInsertBuilder creates a new InsertBuilder for the given table.

func (*InsertBuilder) Blacklist

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

Blacklist defines a blacklist of columns and should only be used in conjunction with Record.

func (*InsertBuilder) Columns

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

Columns appends columns to insert in the statement

func (*InsertBuilder) Interpolate

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

Interpolate interpolates this builders sql.

func (*InsertBuilder) IsInterpolated

func (b *InsertBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

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

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

Returning sets the columns for the RETURNING clause

func (*InsertBuilder) SetIsInterpolated

func (b *InsertBuilder) SetIsInterpolated(enable bool) *InsertBuilder

SetIsInterpolated sets whether this builder should interpolate.

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

func (*InsertBuilder) Whitelist

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

Whitelist defines a whitelist of columns to be inserted. To specify all columsn of a record use "*".

type Interpolator

type Interpolator interface {
	Interpolate() (string, error)
}

Interpolator is the interface for types which interpolate.

type JSON

type JSON json.RawMessage

JSON is a json.RawMessage, which is a []byte underneath. Value() validates the json format in the source, and returns an error if the json is not valid. Scan does no validation. JSON additionally implements `Unmarshal`, which unmarshals the json within to an interface{}

func NewJSON

func NewJSON(any interface{}) (*JSON, error)

NewJSON creates a JSON value.

func (JSON) Interpolate

func (j JSON) Interpolate() (string, error)

Interpolate interpolates the value into a string.

func (*JSON) MarshalJSON

func (j *JSON) MarshalJSON() ([]byte, error)

MarshalJSON returns the *j as the JSON encoding of j.

func (*JSON) Scan

func (j *JSON) Scan(src interface{}) error

Scan stores the src in *j. No validation is done.

func (*JSON) Unmarshal

func (j *JSON) Unmarshal(v interface{}) error

Unmarshal unmarshal's the json in j to v, as in json.Unmarshal.

func (*JSON) UnmarshalJSON

func (j *JSON) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *j to a copy of data

func (JSON) Value

func (j JSON) Value() (driver.Value, error)

Value returns j as a value. This does a validating unmarshal into another RawMessage. If j is invalid json, it returns an error.

type M

type M map[string]interface{}

M is a generic map from string to interface{}

type MapScope

type MapScope struct {
	SQL    string
	Fields M
}

MapScope defines scope for using a fields map.

func NewScope

func NewScope(sql string, fields M) *MapScope

NewScope creates a new scope.

func (*MapScope) ToSQL

func (scope *MapScope) ToSQL(table string) (string, []interface{})

ToSQL converts this scope's SQL to SQL and args.

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 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 {
	pq.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 RawBuilder

type RawBuilder struct {
	Execer
	// contains filtered or unexported fields
}

RawBuilder builds SQL from raw SQL.

func NewRawBuilder

func NewRawBuilder(sql string, args ...interface{}) *RawBuilder

NewRawBuilder creates a new RawBuilder for the given SQL string and arguments

func SQL

func SQL(sql string, args ...interface{}) *RawBuilder

SQL creates a new raw SQL builder.

func (*RawBuilder) Interpolate

func (b *RawBuilder) Interpolate() (string, []interface{}, error)

Interpolate interpolates this builders sql.

func (*RawBuilder) IsInterpolated

func (b *RawBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

func (*RawBuilder) SetIsInterpolated

func (b *RawBuilder) SetIsInterpolated(enable bool) *RawBuilder

SetIsInterpolated sets whether this builder should interpolate.

func (*RawBuilder) ToSQL

func (b *RawBuilder) ToSQL() (string, []interface{})

ToSQL implements builder interface

type Result

type Result struct {
	LastInsertID int64
	RowsAffected int64
}

Result serves the same purpose as sql.Result. Defining it for the package avoids tight coupling with database/sql.

type SQLDialect

type SQLDialect interface {
	// WriteStringLiteral writes a string literal.
	WriteStringLiteral(buf common.BufferWriter, value string)
	// WriteIdentifier writes a quoted identifer such as a column or table.
	WriteIdentifier(buf common.BufferWriter, column string)
}

SQLDialect represents a vendor specific SQL dialect.

var Dialect SQLDialect

Dialect is the active SQLDialect.

type Scope

type Scope interface {
	ToSQL(table string) (string, []interface{})
}

Scope predefines parameterized JOIN and WHERE conditions.

type ScopeFunc

type ScopeFunc func(table string) (string, []interface{})

ScopeFunc is an ad-hoc scope function.

func (ScopeFunc) ToSQL

func (sf ScopeFunc) ToSQL(table string) (string, []interface{})

ToSQL converts scoped func to sql.

type SelectBuilder

type SelectBuilder struct {
	Execer
	// contains filtered or unexported fields
}

SelectBuilder contains the clauses for a SELECT statement

func NewSelectBuilder

func NewSelectBuilder(columns ...string) *SelectBuilder

NewSelectBuilder creates a new SelectBuilder for the given columns

func Select

func Select(columns ...string) *SelectBuilder

Select creates a new SelectBuilder for the given columns.

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. JOINs may also be defined here.

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

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

Interpolate interpolates this builders sql.

func (*SelectBuilder) IsInterpolated

func (b *SelectBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

func (*SelectBuilder) Limit

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

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

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

func (b *SelectBuilder) Scope(sql string, args ...interface{}) *SelectBuilder

Scope uses a predefined scope in place of WHERE.

func (*SelectBuilder) ScopeMap

func (b *SelectBuilder) ScopeMap(mapScope *MapScope, m M) *SelectBuilder

ScopeMap uses a predefined scope in place of WHERE.

func (*SelectBuilder) SetIsInterpolated

func (b *SelectBuilder) SetIsInterpolated(enable bool) *SelectBuilder

SetIsInterpolated sets whether this builder should interpolate.

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 SelectDocBuilder

type SelectDocBuilder struct {
	*SelectBuilder
	// contains filtered or unexported fields
}

SelectDocBuilder builds SQL that returns a JSON row.

func NewSelectDocBuilder

func NewSelectDocBuilder(columns ...string) *SelectDocBuilder

NewSelectDocBuilder creates an instance of SelectDocBuilder.

func SelectDoc

func SelectDoc(columns ...string) *SelectDocBuilder

SelectDoc creates a new SelectDocBuilder for the given columns.

func (*SelectDocBuilder) Distinct

func (b *SelectDocBuilder) Distinct() *SelectDocBuilder

Distinct marks the statement as a DISTINCT SELECT

func (*SelectDocBuilder) From

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

From sets the table to SELECT FROM

func (*SelectDocBuilder) GroupBy

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

GroupBy appends a column to group the statement

func (*SelectDocBuilder) Having

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

Having appends a HAVING clause to the statement

func (*SelectDocBuilder) InnerSQL

func (b *SelectDocBuilder) InnerSQL(sql string, a ...interface{}) *SelectDocBuilder

InnerSQL sets the SQL after the SELECT (columns...) statement

func (*SelectDocBuilder) Interpolate

func (b *SelectDocBuilder) Interpolate() (string, []interface{}, error)

Interpolate interpolates this builders sql.

func (*SelectDocBuilder) IsInterpolated

func (b *SelectDocBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

func (*SelectDocBuilder) Limit

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

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

func (*SelectDocBuilder) Many

func (b *SelectDocBuilder) Many(column string, sqlOrBuilder interface{}, a ...interface{}) *SelectDocBuilder

Many loads a sub query resulting in an array of rows as an alias.

func (*SelectDocBuilder) Offset

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

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

func (*SelectDocBuilder) One

func (b *SelectDocBuilder) One(column string, sqlOrBuilder interface{}, a ...interface{}) *SelectDocBuilder

One loads a query resulting in a single row as an alias.

func (*SelectDocBuilder) OrderBy

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

OrderBy appends a column to ORDER the statement by

func (*SelectDocBuilder) Paginate

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

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 (*SelectDocBuilder) Scope

func (b *SelectDocBuilder) Scope(sql string, args ...interface{}) *SelectDocBuilder

Scope uses a predefined scope in place of WHERE.

func (*SelectDocBuilder) ScopeMap

func (b *SelectDocBuilder) ScopeMap(mapScope *MapScope, m M) *SelectDocBuilder

ScopeMap uses a predefined scope in place of WHERE.

func (*SelectDocBuilder) SetIsInterpolated

func (b *SelectDocBuilder) SetIsInterpolated(enable bool) *SelectDocBuilder

SetIsInterpolated sets whether this builder should interpolate.

func (*SelectDocBuilder) ToSQL

func (b *SelectDocBuilder) ToSQL() (string, []interface{})

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

func (*SelectDocBuilder) Where

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

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

type UnsafeString

type UnsafeString string

UnsafeString is interpolated as an unescaped and unquoted value and should only be used to create constants.

func (UnsafeString) Value

func (u UnsafeString) Value() (driver.Value, error)

Value implements a valuer for compatibility

type UpdateBuilder

type UpdateBuilder struct {
	Execer
	// contains filtered or unexported fields
}

UpdateBuilder contains the clauses for an UPDATE statement

func NewUpdateBuilder

func NewUpdateBuilder(table string) *UpdateBuilder

NewUpdateBuilder creates a new UpdateBuilder for the given table

func Update

func Update(table string) *UpdateBuilder

Update creates a new UpdateBuilder for the given table.

func (*UpdateBuilder) Interpolate

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

Interpolate interpolates this builders sql.

func (*UpdateBuilder) IsInterpolated

func (b *UpdateBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

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

func (b *UpdateBuilder) Returning(columns ...string) *UpdateBuilder

Returning sets the columns for the RETURNING clause

func (*UpdateBuilder) Scope

func (b *UpdateBuilder) Scope(sql string, args ...interface{}) *UpdateBuilder

Scope uses a predefined scope in place of WHERE.

func (*UpdateBuilder) ScopeMap

func (b *UpdateBuilder) ScopeMap(mapScope *MapScope, m M) *UpdateBuilder

ScopeMap uses a predefined scope in place of WHERE.

func (*UpdateBuilder) Set

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

Set appends a column/value pair for the statement

func (*UpdateBuilder) SetBlacklist

func (b *UpdateBuilder) SetBlacklist(rec interface{}, columns ...string) *UpdateBuilder

SetBlacklist creates SET clause(s) using a record and blacklist of columns

func (*UpdateBuilder) SetIsInterpolated

func (b *UpdateBuilder) SetIsInterpolated(enable bool) *UpdateBuilder

SetIsInterpolated sets whether this builder should interpolate.

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

func (b *UpdateBuilder) SetWhitelist(rec interface{}, columns ...string) *UpdateBuilder

SetWhitelist creates SET clause(s) using a record and whitelist of columns. To specify all columns, use "*".

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

type UpsertBuilder

type UpsertBuilder struct {
	Execer
	// contains filtered or unexported fields
}

UpsertBuilder contains the clauses for an INSERT statement

func NewUpsertBuilder

func NewUpsertBuilder(table string) *UpsertBuilder

NewUpsertBuilder creates a new UpsertBuilder for the given table.

func Upsert

func Upsert(table string) *UpsertBuilder

Upsert insert (if it does not exist) or updates a row.

func (*UpsertBuilder) Blacklist

func (b *UpsertBuilder) Blacklist(columns ...string) *UpsertBuilder

Blacklist defines a blacklist of columns and should only be used in conjunction with Record.

func (*UpsertBuilder) Columns

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

Columns appends columns to insert in the statement

func (*UpsertBuilder) Interpolate

func (b *UpsertBuilder) Interpolate() (string, []interface{}, error)

Interpolate interpolates this builders sql.

func (*UpsertBuilder) IsInterpolated

func (b *UpsertBuilder) IsInterpolated() bool

IsInterpolated determines if this builder will interpolate when Interpolate() is called.

func (*UpsertBuilder) Record

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

Record pulls in values to match Columns from the record

func (*UpsertBuilder) Returning

func (b *UpsertBuilder) Returning(columns ...string) *UpsertBuilder

Returning sets the columns for the RETURNING clause

func (*UpsertBuilder) SetIsInterpolated

func (b *UpsertBuilder) SetIsInterpolated(enable bool) *UpsertBuilder

SetIsInterpolated sets whether this builder should interpolate.

func (*UpsertBuilder) ToSQL

func (b *UpsertBuilder) ToSQL() (string, []interface{})

ToSQL serialized the UpsertBuilder to a SQL string It returns the string with placeholders and a slice of query arguments

func (*UpsertBuilder) Values

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

Values appends a set of values to the statement

func (*UpsertBuilder) Where

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

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

func (*UpsertBuilder) Whitelist

func (b *UpsertBuilder) Whitelist(columns ...string) *UpsertBuilder

Whitelist defines a whitelist of columns to be inserted. To specify all columsn of a record use "*".

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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