db

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2019 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrStatementInvalid is returned when a statement is invalid.
	ErrStatementInvalid = errors.New("sqlkit/db: statement invalid")
	// ErrNotAQuery is returned when Decode is called on an Exec.
	ErrNotAQuery = errors.New("sqlkit/db: query was not issued")
	// ErrNestedTransactionsNotAllowed is returned when a nested transaction
	// cannot be executed.
	ErrNestedTransactionsNotAllowed = errors.New("sqlkit/db: nested transactions not allowed")
)

Functions

func StdLogger

func StdLogger(s SQL)

StdLogger is a basic logger that uses the "log" package to log sql queries.

Types

type DB

type DB interface {
	// Query will execute an SQL query returning a result object. If the context
	// is a transaction then this will be used to run the query.
	Query(context.Context, SQL) *Result
	// Exec will execute an SQL query returning a result object. If the context
	// is a transaction then this will be used to run the query.
	Exec(context.Context, SQL) *Result
	// Close will close the underlying DB connection.
	Close() error
	// Begin will create a new transaction. If the passed in context is a TX
	// then a savepoint will be used. If the passed in context is cancellable it
	// will monitor this context and rollback.
	Begin(context.Context) (TX, error)
	// TX provides a safe way to execute a transaction. It ensures that if an
	// error is raised Rollback() is called and if no error is raised Commit()
	// is called.
	TX(ctx context.Context, fn func(ctx context.Context) error) error
	// Select returns a SelectStmt for the dialect.
	Select(cols ...string) SelectStmt
	// Insert returns an InsertStmt for the dialect.
	Insert() InsertStmt
	// Update returns an UpdateStmt for the dialect.
	Update(string) UpdateStmt
	// Delete returns a DeleteStmt for the dialect.
	Delete() DeleteStmt
}

DB is the interface for the DB object.

func New

func New(opts ...Option) DB

New initializes a new DB agnostic to the underlying SQL connection.

func Open

func Open(driverName, dataSourceName string, opts ...Option) (DB, error)

Open will call database/sql Open under the hood and configure a database with an appropriate dialect.

Example
package main

import (
	"context"
	"fmt"

	"github.com/colinjfw/sqlkit/db"
)

func main() {
	d, err := db.Open("sqlite3", ":memory:", db.WithLogger(db.StdLogger))
	if err != nil {
		panic(err)
	}

	ctx, err := d.Begin(context.Background())
	if err != nil {
		panic(err)
	}

	err = d.Exec(ctx, db.Raw("create table test (id int primary key)")).Err()
	if err != nil {
		panic(err)
	}

	err = d.Exec(
		ctx,
		d.Insert().
			Into("test").
			Value("id", 1).
			Value("id", 2),
	).Err()
	if err != nil {
		panic(err)
	}

	var rows []int
	err = d.Query(ctx, d.Select("*").From("test")).Decode(&rows)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v\n", rows)

	var count int
	err = d.Query(ctx, d.Select("count(*)").From("test")).Decode(&count)
	if err != nil {
		panic(err)
	}
	fmt.Println(count)

}
Output:

[1 2]
2

type DeleteStmt

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

DeleteStmt represents a DELETE in sql.

func Delete

func Delete() DeleteStmt

Delete returns a new DeleteStmt.

func (DeleteStmt) From

func (q DeleteStmt) From(table string) DeleteStmt

From configures the table.

func (DeleteStmt) InnerJoin

func (q DeleteStmt) InnerJoin(table, on string) DeleteStmt

InnerJoin adds a join of type INNER.

func (DeleteStmt) Join

func (q DeleteStmt) Join(kind, table, on string, values ...interface{}) DeleteStmt

Join adds a join statement of a specific kind.

func (DeleteStmt) LeftJoin

func (q DeleteStmt) LeftJoin(table, on string) DeleteStmt

LeftJoin adds a join of type LEFT.

func (DeleteStmt) RightJoin

func (q DeleteStmt) RightJoin(table, on string) DeleteStmt

RightJoin adds a join of type RIGHT.

func (DeleteStmt) SQL

func (q DeleteStmt) SQL() (string, []interface{}, error)

SQL implements the SQL interface.

func (DeleteStmt) Where

func (q DeleteStmt) Where(where string, values ...interface{}) DeleteStmt

Where configures the WHERE clause in a DELETE statement. It follows the same format as the select statement where statement.

type Dialect

type Dialect int

Dialect represents the SQL dialect type.

const (
	Generic Dialect = iota
	Postgres
	MySQL
)

Dialect selections.

type InsertStmt

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

InsertStmt represents an INSERT in SQL.

func Insert

func Insert() InsertStmt

Insert constructs an InsertStmt.

func (InsertStmt) Columns

func (i InsertStmt) Columns(cols ...string) InsertStmt

Columns configures the columns.

func (InsertStmt) Into

func (i InsertStmt) Into(table string) InsertStmt

Into configures the table name.

func (InsertStmt) Record

func (i InsertStmt) Record(obj interface{}) InsertStmt

Record will decode using the decoder into a list of fields and values.

func (InsertStmt) Row

func (i InsertStmt) Row(cols []string, vals []interface{}) InsertStmt

Row configures a single row into the insert statement. If the columns don't match previous insert statements then an error is forwarded.

func (InsertStmt) SQL

func (i InsertStmt) SQL() (string, []interface{}, error)

SQL implements the SQL interface.

func (InsertStmt) Value

func (i InsertStmt) Value(column string, value interface{}) InsertStmt

Value configures a single value insert.

func (InsertStmt) Values

func (i InsertStmt) Values(vals ...interface{}) InsertStmt

Values configures a single row of values.

type Option

type Option func(db *db)

Option represents option configurations.

func WithConn

func WithConn(conn *sql.DB) Option

WithConn configures a custom *sql.DB connection.

func WithDialect

func WithDialect(dialect Dialect) Option

WithDialect configures the SQL dialect.

func WithDisabledSavepoints

func WithDisabledSavepoints(enc encoding.Encoder) Option

WithDisabledSavepoints will disable savepoints for a database.

func WithEncoder

func WithEncoder(enc encoding.Encoder) Option

WithEncoder configures a custom encoder if a different mapper were needed.

func WithLogger

func WithLogger(logger func(SQL)) Option

WithLogger configures a logging function.

type Result

type Result struct {
	*sql.Rows
	LastID       int64
	RowsAffected int64
	// contains filtered or unexported fields
}

Result wraps a database/sql query result. It returns the same result for both Exec and Query responses.

func (*Result) Decode

func (r *Result) Decode(val interface{}) (err error)

Decode will decode the results into an interface.

func (*Result) Err

func (r *Result) Err() error

Err forwards the error that may have come from the connection.

type SQL

type SQL interface {
	SQL() (string, []interface{}, error)
}

SQL is an interface for an SQL query that contains a string of SQL and arguments. This is the interface that must be implemented to exec or query on the database. Raw(...) can be used to transform a raw string into an SQL interface.

func Raw

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

Raw implements the SQL intorerface for providing SQL queries.

type SelectStmt

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

SelectStmt represents a SELECT in sql.

func Select

func Select(cols ...string) SelectStmt

Select returns a new SelectStmt.

func (SelectStmt) From

func (q SelectStmt) From(table string) SelectStmt

From configures the table.

func (SelectStmt) GroupBy

func (q SelectStmt) GroupBy(groupBy ...string) SelectStmt

GroupBy configures the GROUP BY clause.

func (SelectStmt) InnerJoin

func (q SelectStmt) InnerJoin(table, on string) SelectStmt

InnerJoin adds a join of type INNER.

func (SelectStmt) Join

func (q SelectStmt) Join(kind, table, on string, values ...interface{}) SelectStmt

Join adds a join statement of a specific kind.

func (SelectStmt) LeftJoin

func (q SelectStmt) LeftJoin(table, on string) SelectStmt

LeftJoin adds a join of type LEFT.

func (SelectStmt) Limit

func (q SelectStmt) Limit(limit int) SelectStmt

Limit configures the LIMIT clause.

func (SelectStmt) Offset

func (q SelectStmt) Offset(offset int) SelectStmt

Offset configures the OFFSET clause.

func (SelectStmt) OrderBy

func (q SelectStmt) OrderBy(orderBy ...string) SelectStmt

OrderBy configures the ORDER BY clause.

func (SelectStmt) RightJoin

func (q SelectStmt) RightJoin(table, on string) SelectStmt

RightJoin adds a join of type RIGHT.

func (SelectStmt) SQL

func (q SelectStmt) SQL() (string, []interface{}, error)

SQL implements the SQL interface.

func (SelectStmt) Select

func (q SelectStmt) Select(cols ...string) SelectStmt

Select configures the columns to select.

func (SelectStmt) Where

func (q SelectStmt) Where(where string, values ...interface{}) SelectStmt

Where configures the WHERE clause. It expects values to be interpolated using the question (?) mark parameter. For values that are slices, the question mark will be transformed in the where query. This means that IN queries can be writted without knowing the specific number of arguments needed in the array.

type TX

type TX interface {
	context.Context

	// Rollback will rollback the current transaction. If this is a savepoint
	// then the savepoint will be rolled back. If Rollback or Commit has already
	// been called then Rollback will take no action and return no error. If the
	// context is already closed then Rollback will return.
	Rollback() error
	// Commit will commit the current transaction. If this is a savepoint then
	// the savepoint will be released.
	Commit() error
	// WithContext will copy the transaction using a new context as the base.
	// This can be used to set a new context with a cancel or deadline.
	WithContext(ctx context.Context) TX
}

TX represents a transaction. It contains a context as well as commit and rollback calls. It implements the Context interface so it can be passed into the query and exec calls.

type UpdateStmt

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

UpdateStmt represents an UPDATE in SQL.

func Update

func Update(table string) UpdateStmt

Update returns a new Update statement.

func (UpdateStmt) Columns

func (i UpdateStmt) Columns(cols ...string) UpdateStmt

Columns sets the colums for the update.

func (UpdateStmt) Record

func (i UpdateStmt) Record(obj interface{}) UpdateStmt

Record will encode the struct and append the columns and returned values.

func (UpdateStmt) SQL

func (i UpdateStmt) SQL() (string, []interface{}, error)

SQL implements the SQL interface.

func (UpdateStmt) Table

func (i UpdateStmt) Table(table string) UpdateStmt

Table configures the table for the query.

func (UpdateStmt) Value

func (i UpdateStmt) Value(name string, val interface{}) UpdateStmt

Value configures a single value for the query.

func (UpdateStmt) Values

func (i UpdateStmt) Values(vals ...interface{}) UpdateStmt

Values sets the values for the update.

func (UpdateStmt) Where

func (i UpdateStmt) Where(where string, args ...interface{}) UpdateStmt

Where configures the WHERE block.

Jump to

Keyboard shortcuts

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