aspect

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2015 License: MIT Imports: 13 Imported by: 25

README

Aspect GoDoc Build Status

A relational database toolkit for Go:

  • Build complete database schemas
  • Create reusable and cross-dialect SQL statements
  • Allow struct instances and slices to be directly populated by the database

Quickstart

package main

import (
    "log"

    sql "github.com/aodin/aspect"
    _ "github.com/aodin/aspect/sqlite3"
)

// Create a database schema using aspect's Table function
var Users = sql.Table("users",
    sql.Column("id", sql.Integer{NotNull: true}),
    sql.Column("name", sql.String{Length: 32, NotNull: true}),
    sql.Column("password", sql.String{Length: 128}),
    sql.PrimaryKey("id"),
)

// Structs are used to send and receive values to the database
type User struct {
    ID       int64  `db:"id"`
    Name     string `db:"name"`
    Password string `db:"password"`
}

func main() {
    // Connect to an in-memory sqlite3 instance
    conn, err := sql.Connect("sqlite3", ":memory:")
    if err != nil {
        log.Panic(err)
    }
    defer conn.Close()

    // Create the users table
    conn.MustExecute(Users.Create())

    // Insert a user - they can be inserted by value or reference
    admin := User{ID: 1, Name: "admin", Password: "secret"}
    conn.MustExecute(Users.Insert().Values(admin))

    // Select a user - query methods must be given a pointer
    var user User
    conn.MustQueryOne(Users.Select(), &user)
    log.Println(user)
}

Statements

Don't forget to import aspect and at least one driver. I alias the aspect package to sql:

import (
    sql "github.com/aodin/aspect"
    _ "github.com/aodin/aspect/postgres"
    _ "github.com/aodin/aspect/sqlite3"
)

Statements that do not return selections can be run with the Execute method of database connections DB or transactions TX. Both also implement the interface Connection.

A successful Connect will return a database connection pool ready for use. Its Execute method returns an instance of database/sql package's Result and an error if one occurred:

conn, err := sql.Connect("sqlite3", ":memory:")
if err != nil {
    log.Panic(err)
}
defer conn.Close()

result, err := conn.Execute(Users.Create())

Results are often ignored, as in the Quickstart example above.

The following commands are usually used with the Execute method:

CREATE TABLE

Once a schema has been specified with Table, such as:

var Users = sql.Table("users",
    sql.Column("id", sql.Integer{NotNull: true}),
    sql.Column("name", sql.String{Length: 32, NotNull: true}),
    sql.Column("password", sql.String{Length: 128}),
    sql.PrimaryKey("id"),
)

A CREATE TABLE statement can be created with:

Users.Create()

And will output the following SQL with its String() method (a dialect neutral version) or with conn.String() (a dialect specific version):

CREATE TABLE "users" (
  "id" INTEGER NOT NULL,
  "name" VARCHAR(32) NOT NULL,
  "password" VARCHAR(128),
  PRIMARY KEY ("id")
);
DROP TABLE

Using the Users schema, a DROP TABLE statement can be created with:

Users.Drop()
DROP TABLE "users"
INSERT

Insert statements can be created without specifying values. For instance, the method Insert() on a schema such as Users can be created with:

Users.Insert()

And produces the SQL (in this example for the sqlite3 dialect):

INSERT INTO "users" ("id", "name", "password") VALUES (?, ?, ?)

Values can be inserted to the database using structs or aspect.Values instances. If given a struct, Aspect first attempts to match field names or db tags. Columns without matching values will be dropped. The following struct and chained function:

type user struct {
    Name     string `db:"name"`
    Password string `db:"password"`
    Extra    string
    manager  *manager
}
Users.Insert().Values(user{Name: "Totti", Password: "GOAL"})
INSERT INTO "users" ("name", "password") VALUES (?, ?)

Fields must be exported (i.e. start with an uppercase character) to work with Aspect. Unexported fields and those that do not match column names will be ignored.

Structs without db tags or fields that match column names can be inserted, but only if the number of exported fields equals the number of columns being inserted.

Slices of structs can also be inserted:

users := []user{
    {Name: "Howard", Password: "DENIED"},
    {Name: "Beckham", Password: "RETIRED"},
}

And would produce the following (note: this syntax for multiple inserts is only valid in later versions of sqlite3):

INSERT INTO "users" ("name", "password") VALUES (?, ?), (?, ?)

To manually specify which columns should be inserted, use Aspect's Insert function, rather than the table method:

sql.Insert(Users.C["name"]).Values(users)
INSERT INTO "users" ("name") VALUES (?), (?)

Values can also be inserted using the map type Values or a slice of them:

Users.Insert().Values(sql.Values{"name": "Ronaldo"})
INSERT INTO "users" ("name") VALUES (?)

Keys in Values maps must match column names or the statement will error.

UPDATE

Rows in a table can be updated using either of:

Users.Update()
sql.Update(Users)

Both will produce the same output:

UPDATE "users" SET "id" = ?, "name" = ?, "password" = ?

Columns are set according to the values given. Values keys that do not match a column will error.

Users.Update().Values(sql.Values{"name": "Ronaldo", "password": "STRIKER"})
UPDATE "users" SET "name" = ?, "password" = ?

Conditionals can be specified with the Where() method:

Users.Update().Values(
    sql.Values{"password": "FIFA2014"},
).Where(Users.C["name"].Equals("Ronaldo"))
UPDATE "users" SET "password" = ? WHERE "users"."name" = ?
DELETE

If you want to delete all the rows in a table:

Users.Delete()
DELETE FROM "users"

A conditional delete can be created with Where():

Users.Delete().Where(Users.C["name"].Equals("Ronaldo"))
DELETE FROM "users" WHERE "users"."name" = ?

If the schema has a single column primary key specified, deletes can be performed with structs:

Users.Delete().Values(user{ID: 1})
DELETE FROM "users" WHERE "users"."id" = ?

Or slices of structs:

Users.Delete().Values([]user{{ID: 1}, {ID: 2}})
DELETE FROM "users" WHERE "users"."id" IN (?, ?)
SELECT

Results can be queried in a number of ways. Each of the following statements will produce the same SQL output:

Users.Select()
sql.Select(Users)
sql.Select(Users.C["id"], Users.C["name"], Users.C["password"])
SELECT "users"."id", "users"."name", "users"."password" FROM "users"

Results can be returned directly into structs:

var users []User
conn.MustQueryAll(Users.Select(), &users)
log.Println(users)
// [1: admin 2: client 3: daemon]

It's okay to have a destination struct larger than the expected results (vice-versa!), as long as the struct has db tags:

type username struct {
    Name    string `db:"name"`
    manager *manager
}

var usernames []username
conn.MustQueryAll(sql.Select(Users.C["name"]), &usernames)

Single column queries can be returned into slice types:

stmt := sql.Select(Users.C["id"]).OrderBy(Users.C["id"].Desc())
SELECT "users"."id" FROM "users" ORDER BY "users"."id" DESC
var ids []int64
conn.MustQueryAll(s, &ids)
log.Println(ids)
// [3, 2, 1]

Single results can also be queried into instantiated instances of Values, which is included with the package:

result := sql.Values{}
conn.MustQueryOne(Users.Select(), result)

Or multiple results with a pointer to a slice of Values:

var results []sql.Values
conn.QueryAll(Users.Select(), &results)

A warning, however: string results are added to the map as []byte types. Since this is done internally by the database/sql standard library package, this is unlikely to change in the future.

map[id:1 name:[84 111 116 116 105] password:[71 79 65 76]]

To get string output, simply cast the value to a string after asserting that it is a []byte:

log.Println(string(result["name"].([]byte)))
// Totti

Schema

More advanced schemas can be created with foreign keys, unique constraints, and composite primary keys:

var Posts = sql.Table("posts",
    sql.ForeignKey("uid", Users.C["id"], sql.BigInt{}).OnDelete(sql.Cascade),
    sql.Column("name", sql.String{Length: 32, NotNull: true}),
    sql.Column("is_published", sql.Boolean{Default: sql.True}),
    sql.Unique("name"),
    sql.PrimaryKey("uid", "name"),
)
CREATE TABLE "posts" (
  "uid" BIGINT REFERENCES users("id") ON DELETE CASCADE,
  "name" VARCHAR(32) NOT NULL,
  "is_published" BOOLEAN DEFAULT TRUE,
  UNIQUE ("name"),
  PRIMARY KEY ("uid", "name")
);

Development

To perform tests, copy the db.example.json file into each driver package requiring credentials as db.json (currently required only by the postgres package) and set it for your local configuration.

All compilable statements implement a String method for dialect-neutral logging and the Compile method for building dialect-specific and parameterized output:

type Compiles interface {
    String() string
    Compile(Dialect, *Parameters) (string, error)
}

Statements and clauses can be tested by creating a new dialect-specific tester; for example using the postgres package:

expect := NewTester(t, &postgres.PostGres{})

The instance's SQL method will test expected output and parameterization:

expect.SQL(`DELETE FROM "users"`, users.Delete())

expect.SQL(
    `INSERT INTO "users" ("name") VALUES ($1), ($2)`,
    users.Insert().Values([]sql.Values{{"name": "Totti"}, {"name": "De Rossi"}}),
    "Totti",
    "De Rossi",
)

And the Error method will test that an error occurred:

expect.Error(sql.Select(users.C["does-not-exist"]))

Happy Hacking!

aodin, 2014-15

Death and Light are everywhere, always, and they begin, end, strive, attend, into and upon the Dream of the Nameless that is the world, burning words within Samsara, perhaps to create a thing of beauty.

Lord of Light by Roger Zelazny

Documentation

Overview

Aspect is a relational database toolkit for Go:

- Build complete database schemas

- Create reusable and cross-dialect SQL statements

- Allow struct instances and slices to be directly populated by the database

Index

Constants

View Source
const (
	NoAction   fkAction = "NO ACTION"
	Restrict   fkAction = "RESTRICT"
	Cascade    fkAction = "CASCADE"
	SetNull    fkAction = "SET NULL"
	SetDefault fkAction = "SET DEFAULT"
)

The following constants represent possible foreign key actions that can be used in ON DELETE and ON UPDATE clauses.

View Source
const OmitEmpty = "omitempty"

Common options

View Source
const VERSION = "0.5.3"

Variables

View Source
var (
	True  = &internalTrue
	False = &internalFalse
)

Provide a nullable boolean for Boolean type default values

View Source
var (
	ErrNoResult = errors.New("aspect: no result to return")
	ErrWrongMap = errors.New(
		"aspect: maps must have key type string and value type interface{}",
	)
)
View Source
var (
	Blank = &internalBlank
)

Provide a blank string for default values

View Source
var (
	ErrNoColumns = errors.New(
		"aspect: attempt to create a statement with zero columns",
	)
)

Functions

func AlignColumns

func AlignColumns(columns []string, fields []field) fields

AlignColumns will reorder the given fields array to match the columns. Columns that do not match fields will be given empty field structs.

func FakeTx

func FakeTx(tx Transaction) *fakeTX

FakeTx allows testing of transactional blocks of code. Commit and Rollback do nothing.

func NewTester

func NewTester(t *testing.T, d Dialect) *sqlTest

func RegisterDialect

func RegisterDialect(name string, d Dialect)

RegisterDialect adds the given Dialect to the registry at the given name.

func SelectFields

func SelectFields(v interface{}) fields

SelectFields returns the ordered list of fields from the given interface.

func SelectFieldsFromElem

func SelectFieldsFromElem(elem reflect.Type) fields

SelectFieldsFromElem returns the ordered list of fields from the given reflect Type

Types

type ArrayClause

type ArrayClause struct {
	Clauses []Clause
	Sep     string
}

ArrayClause is any number of clauses with a column join

func (ArrayClause) Compile

func (c ArrayClause) Compile(d Dialect, params *Parameters) (string, error)

func (ArrayClause) String

func (c ArrayClause) String() string

type BigInt

type BigInt struct {
	NotNull    bool
	Unique     bool
	PrimaryKey bool
}

BigInt represents BIGINT column types.

func (BigInt) Create

func (s BigInt) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (BigInt) IsPrimaryKey

func (s BigInt) IsPrimaryKey() bool

func (BigInt) IsRequired

func (s BigInt) IsRequired() bool

func (BigInt) IsUnique

func (s BigInt) IsUnique() bool

func (BigInt) Validate

func (s BigInt) Validate(i interface{}) (interface{}, error)

type BinaryClause

type BinaryClause struct {
	Pre, Post Clause
	Sep       string
}

BinaryClause is two clauses with a separator

func (BinaryClause) Compile

func (c BinaryClause) Compile(d Dialect, params *Parameters) (string, error)

func (BinaryClause) String

func (c BinaryClause) String() string

type Boolean

type Boolean struct {
	NotNull bool
	Default *bool
}

Boolean represents BOOL column types. It contains a Default field that can be left nil, or set with the included variables True and False.

func (Boolean) Create

func (s Boolean) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Boolean) IsPrimaryKey

func (s Boolean) IsPrimaryKey() bool

func (Boolean) IsRequired

func (s Boolean) IsRequired() bool

func (Boolean) IsUnique

func (s Boolean) IsUnique() bool

func (Boolean) Validate

func (s Boolean) Validate(i interface{}) (interface{}, error)

type Clause

type Clause interface {
	Compiles
}

Clause is a common interface that most components implement.

func AllOf

func AllOf(clauses ...Clause) Clause

AllOf joins the given clauses with 'AND' and wraps them in parentheses

func AnyOf

func AnyOf(clauses ...Clause) Clause

AnyOf joins the given clauses with 'OR' and wraps them in parentheses

type ColumnClause

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

ColumnClause is a clause used for column selections.

func ColumnClauseFromColumn added in v0.4.0

func ColumnClauseFromColumn(c ColumnElem) ColumnClause

ColumnClauseFromColumn creates a ColumnClause from a ColumnElem

func ColumnOnlyClause added in v0.4.0

func ColumnOnlyClause(c ColumnElem) ColumnClause

ColumnClauseFromColumn creates a ColumnClause from a ColumnElem's name only

func (ColumnClause) Compile

func (c ColumnClause) Compile(d Dialect, params *Parameters) (string, error)

Compile creates the SQL to represent a table column using the given dialect, optionally without a table prefix.

func (ColumnClause) String

func (c ColumnClause) String() string

String returns the ColumnClause's SQL using the default dialect.

type ColumnElem

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

ColumnElem represents a table column. It implements the Compiles, Selectable, and Orderable interfaces for use in statements as well as the TableModifier and Creatable interfaces.

func Avg

func Avg(c ColumnElem) ColumnElem

func Column

func Column(name string, t Type) ColumnElem

Column constructs a ColumnElem with the given name and Type.

func Count

func Count(c ColumnElem) ColumnElem

func DateOf

func DateOf(c ColumnElem) ColumnElem

func DatePart

func DatePart(c ColumnElem, part string) ColumnElem

func Lower

func Lower(c ColumnElem) ColumnElem

func Max

func Max(c ColumnElem) ColumnElem

func Sum

func Sum(c ColumnElem) ColumnElem

func Upper added in v0.4.0

func Upper(c ColumnElem) ColumnElem

func (ColumnElem) As

func (c ColumnElem) As(alias string) ColumnElem

As specifies an alias for this ColumnElem

func (ColumnElem) Asc

func (c ColumnElem) Asc() OrderedColumn

Asc returns an OrderedColumn. It is the same as passing the column itself to an OrderBy clause.

func (ColumnElem) Between

func (c ColumnElem) Between(a, b interface{}) Clause

func (ColumnElem) Compile

func (c ColumnElem) Compile(d Dialect, params *Parameters) (string, error)

Compile produces the dialect specific SQL and adds any parameters in the clause to the given Parameters instance

func (ColumnElem) Create

func (c ColumnElem) Create(d Dialect) (string, error)

Create implements the Creatable interface that outputs a column of a CREATE TABLE statement.

func (ColumnElem) Desc

func (c ColumnElem) Desc() OrderedColumn

Desc returns an OrderedColumn that will sort in descending order.

func (ColumnElem) DoesNotEqual

func (c ColumnElem) DoesNotEqual(i interface{}) BinaryClause

DoesNotEqual creates a does not equal clause that can be used in conditional clauses.

table.Select().Where(table.C["id"].DoesNotEqual(3))

func (ColumnElem) Equals

func (c ColumnElem) Equals(i interface{}) BinaryClause

Equals creates an equals clause that can be used in conditional clauses.

table.Select().Where(table.C["id"].Equals(3))

func (ColumnElem) GTE

func (c ColumnElem) GTE(i interface{}) BinaryClause

GTE creates a greater than or equal to clause that can be used in conditional clauses.

table.Select().Where(table.C["id"].GTE(3))

func (ColumnElem) GreaterThan

func (c ColumnElem) GreaterThan(i interface{}) BinaryClause

GreaterThan creates a greater than clause that can be used in conditional clauses.

table.Select().Where(table.C["id"].GreaterThan(3))

func (ColumnElem) ILike

func (c ColumnElem) ILike(i string) BinaryClause

Like creates a case insensitive pattern matching clause that can be used in conditional clauses.

table.Select().Where(table.C["name"].ILike(`_b%`))

func (ColumnElem) In

func (c ColumnElem) In(args interface{}) BinaryClause

In creates a comparison clause with an IN operator that can be used in conditional clauses. An interface is used because the args may be of any type: ints, strings...

table.Select().Where(table.C["id"].In([]int64{1, 2, 3}))

func (ColumnElem) InLocation

func (c ColumnElem) InLocation(loc *time.Location) ColumnElem

func (ColumnElem) Inner

func (c ColumnElem) Inner() Clause

Inner returns the inner Clause of the ColumnElem. This operation is used for setting external casts and functions on the ColumnElem.

func (ColumnElem) IsNotNull

func (c ColumnElem) IsNotNull() UnaryClause

IsNotNull creates a comparison clause that can be used for checking absence of NULLs in conditional clauses.

table.Select().Where(table.C["name"].IsNotNull())

func (ColumnElem) IsNull

func (c ColumnElem) IsNull() UnaryClause

IsNull creates a comparison clause that can be used for checking existence of NULLs in conditional clauses.

table.Select().Where(table.C["name"].IsNull())

func (ColumnElem) LTE

func (c ColumnElem) LTE(i interface{}) BinaryClause

LTE creates a less than or equal to clause that can be used in conditional clauses.

table.Select().Where(table.C["id"].LTE(3))

func (ColumnElem) LessThan

func (c ColumnElem) LessThan(i interface{}) BinaryClause

LessThan creates a less than clause that can be used in conditional clauses.

table.Select().Where(table.C["id"].LessThan(3))

func (ColumnElem) Like

func (c ColumnElem) Like(i string) BinaryClause

Like creates a pattern matching clause that can be used in conditional clauses.

table.Select().Where(table.C["name"].Like(`_b%`))

func (ColumnElem) Modify

func (c ColumnElem) Modify(t *TableElem) error

Modify implements the TableModifier interface. It creates a column and adds the same column to the create array.

func (ColumnElem) Name

func (c ColumnElem) Name() string

Name returns the column's name

func (ColumnElem) NotBetween

func (c ColumnElem) NotBetween(a, b interface{}) Clause

func (ColumnElem) NotLike

func (c ColumnElem) NotLike(i string) BinaryClause

NotLike creates a pattern matching clause that can be used in conditional clauses.

table.Select().Where(table.C["name"].NotLike(`_b%`))

func (ColumnElem) NotSimilarTo

func (c ColumnElem) NotSimilarTo(i string) BinaryClause

NotSimilarTo creates a SQL regular expression matching clause that can be used in conditional clauses.

table.Select().Where(table.C["name"].NotSimilarTo(`_b%`))

func (ColumnElem) NullsFirst

func (c ColumnElem) NullsFirst() OrderedColumn

NullsFirst returns an OrderedColumn that will sort NULLs first.

func (ColumnElem) NullsLast

func (c ColumnElem) NullsLast() OrderedColumn

NullsLast returns an OrderedColumn that will sort NULLs last.

func (ColumnElem) Orderable

func (c ColumnElem) Orderable() OrderedColumn

Orerable implements the Orderable interface that allows the column itself to be used in an OrderBy clause.

func (ColumnElem) Selectable

func (c ColumnElem) Selectable() []ColumnElem

Selectable implements the sql.Selectable interface for building SELECT statements from ColumnElem instances.

func (ColumnElem) SetInner

func (c ColumnElem) SetInner(clause Clause) ColumnElem

SetInner sets the inner Clause of the ColumnElem. This operation is used for setting external casts and functions on the ColumnElem.

func (ColumnElem) SimilarTo

func (c ColumnElem) SimilarTo(i string) BinaryClause

SimilarTo creates a SQL regular expression matching clause that can be used in conditional clauses.

table.Select().Where(table.C["name"].SimilarTo(`_b%`))

func (ColumnElem) String

func (c ColumnElem) String() string

String outputs a parameter-less SQL representation of the column using a neutral dialect. If an error occurred during compilation, then an empty string will be returned.

func (ColumnElem) Table

func (c ColumnElem) Table() *TableElem

Table returns the column's table

func (ColumnElem) Type

func (c ColumnElem) Type() Type

Type returns the column's SQL type

type ColumnSet

type ColumnSet map[string]ColumnElem

ColumnSet maintains a map of ColumnElem instances by column name

func (ColumnSet) Add

func (set ColumnSet) Add(c ColumnElem) error

Add adds a ColumnElem to the ColumnSet, returning an error if the name already exists.

type Compiles

type Compiles interface {
	String() string // Output a neutral dialect logging string
	Compile(Dialect, *Parameters) (string, error)
}

The main SQL statement interface. All clauses must implement this interface in order to be an executable statement or fragment.

type ConditionalStmt added in v0.4.0

type ConditionalStmt struct {
	Stmt
	// contains filtered or unexported fields
}

ConditionalStmt includes SELECT, DELETE, and UPDATE statements

func (*ConditionalStmt) AddConditional added in v0.5.0

func (stmt *ConditionalStmt) AddConditional(cond Clause)

AddConditional adds a conditional clause to the statement. If a conditional clause already exists, they will be joined with an AND.

func (ConditionalStmt) Conditional added in v0.4.0

func (stmt ConditionalStmt) Conditional() Clause

Conditional returns the statement's conditional Clause

type Connection

type Connection interface {
	Begin() (Transaction, error)
	Execute(stmt Executable, args ...interface{}) (sql.Result, error)
	Query(stmt Executable, args ...interface{}) (*Result, error)
	QueryAll(stmt Executable, i interface{}) error
	QueryOne(stmt Executable, i interface{}) error
	String(stmt Executable) string // Parameter-less output for logging

	// Must operations will panic on error
	MustBegin() Transaction
	MustExecute(stmt Executable, args ...interface{}) sql.Result
	MustQuery(stmt Executable, args ...interface{}) *Result
	MustQueryAll(stmt Executable, i interface{})
	MustQueryOne(stmt Executable, i interface{}) bool
}

Connection is a common interface for database connections or transactions

type Creatable

type Creatable interface {
	Create(d Dialect) (string, error)
}

Creatable is the interface that clauses used in CREATE TABLE statements must implement.

type CreateStmt

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

CreateStmt is the internal representation of an CREATE TABLE statement.

func (CreateStmt) Compile

func (stmt CreateStmt) Compile(d Dialect, p *Parameters) (string, error)

Compile outputs the CREATE TABLE statement using the given dialect and parameters. An error may be returned because of a pre-existing error or because an error occurred during compilation.

func (CreateStmt) String

func (stmt CreateStmt) String() string

String outputs the parameter-less CREATE TABLE statement in a neutral dialect.

type DB

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

DB wraps the current sql.DB connection pool and includes the Dialect associated with the connection.

func Connect

func Connect(driver, credentials string) (*DB, error)

Connect connects to the database using the given driver and credentials. It returns a database connection pool and an error if one occurred.

func (*DB) Begin

func (db *DB) Begin() (Transaction, error)

Begin starts a new transaction using the current database connection pool.

func (*DB) Close

func (db *DB) Close() error

Close closes the current database connection pool.

func (*DB) Dialect

func (db *DB) Dialect() Dialect

Dialect returns the dialect associated with the current database connection pool.

func (*DB) Execute

func (db *DB) Execute(stmt Executable, args ...interface{}) (sql.Result, error)

Execute executes the Executable statement with optional arguments. It returns the database/sql package's Result object, which may contain information on rows affected and last ID inserted depending on the driver.

func (*DB) MustBegin

func (db *DB) MustBegin() Transaction

MustBegin starts a new transaction using the current database connection pool. It will panic on error.

func (*DB) MustExecute

func (db *DB) MustExecute(stmt Executable, args ...interface{}) sql.Result

MustExecute will panic on error.

func (*DB) MustQuery

func (db *DB) MustQuery(stmt Executable, args ...interface{}) *Result

MustQuery

func (*DB) MustQueryAll

func (db *DB) MustQueryAll(stmt Executable, i interface{})

MustQueryAll

func (*DB) MustQueryOne

func (db *DB) MustQueryOne(stmt Executable, i interface{}) bool

MustQueryOne

func (*DB) Query

func (db *DB) Query(stmt Executable, args ...interface{}) (*Result, error)

Query executes an Executable statement with the optional arguments. It returns a Result object, that can scan rows in various data types.

func (*DB) QueryAll

func (db *DB) QueryAll(stmt Executable, i interface{}) error

QueryAll will query the statement and populate the given interface with all results.

func (*DB) QueryOne

func (db *DB) QueryOne(stmt Executable, i interface{}) error

QueryOne will query the statement and populate the given interface with a single result.

func (*DB) String

func (db *DB) String(stmt Executable) string

String returns parameter-less SQL. If an error occurred during compilation, then the string output of the error will be returned.

type Date

type Date struct {
	NotNull    bool
	PrimaryKey bool
	Unique     bool
}

Date represents DATE column types.

func (Date) Create

func (s Date) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Date) IsPrimaryKey

func (s Date) IsPrimaryKey() bool

func (Date) IsRequired

func (s Date) IsRequired() bool

func (Date) IsUnique

func (s Date) IsUnique() bool

func (Date) Validate

func (s Date) Validate(i interface{}) (interface{}, error)

type DeleteStmt

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

DeleteStmt is the internal representation of a DELETE statement.

func Delete

func Delete(table *TableElem) (stmt DeleteStmt)

Delete creates a DELETE statement for the given table.

func (DeleteStmt) Compile

func (stmt DeleteStmt) Compile(d Dialect, params *Parameters) (string, error)

Compile outputs the DELETE statement using the given dialect and parameters. An error may be returned because of a pre-existing error or because an error occurred during compilation.

func (DeleteStmt) String

func (stmt DeleteStmt) String() string

String outputs the parameter-less DELETE statement in a neutral dialect.

func (DeleteStmt) Values

func (stmt DeleteStmt) Values(arg interface{}) DeleteStmt

Values sets the conditional clause using the given struct or slice of structs. The table must have a single primary key field.

func (DeleteStmt) Where

func (stmt DeleteStmt) Where(conds ...Clause) DeleteStmt

Where adds a conditional WHERE clause to the DELETE statement.

type Dialect

type Dialect interface {
	Parameterize(int) string
}

Dialect is the common interface that all database drivers must implement.

func GetDialect

func GetDialect(name string) (Dialect, error)

GetDialect returns the Dialect in the registry with the given name. An error will be returned if no Dialect with that name exists.

func MustGetDialect

func MustGetDialect(name string) Dialect

MustGetDialect returns the Dialect in the registry with the given name. It will panic if no Dialect with that name is found.

type Double

type Double struct {
	NotNull    bool
	Unique     bool
	PrimaryKey bool
}

Double represents DOUBLE PRECISION column types.

func (Double) Create

func (s Double) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Double) IsPrimaryKey

func (s Double) IsPrimaryKey() bool

func (Double) IsRequired

func (s Double) IsRequired() bool

func (Double) IsUnique

func (s Double) IsUnique() bool

func (Double) Validate

func (s Double) Validate(i interface{}) (interface{}, error)

type DropStmt

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

DropStmt is the internal representation of an DROP TABLE statement.

func (DropStmt) Compile

func (stmt DropStmt) Compile(d Dialect, p *Parameters) (string, error)

Compile outputs the DROP TABLE statement using the given dialect and parameters. An error may be returned because of a pre-existing error or because an error occurred during compilation.

func (DropStmt) IfExists

func (stmt DropStmt) IfExists() DropStmt

IfExists adds the IF EXISTS modifier to a DROP TABLE statement.

func (DropStmt) String

func (stmt DropStmt) String() string

String outputs the parameter-less CREATE TABLE statement in a neutral dialect.

type Executable

type Executable interface {
	Compiles
}

Executable statements implement the Compiles interface

type ForeignKeyElem

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

ForeignKeyElem is an internal type representation. It implements the Creatable interface so it can be used in CREATE TABLE statements.

func ForeignKey

func ForeignKey(name string, fk ColumnElem, ts ...Type) ForeignKeyElem

ForeignKey creates a ForeignKeyElem from the given name and column. The given column must already have an assigned table. The new ColumnElem will inherit its type from the given column's type, but a different type can be overridden by a single optional type.

func (ForeignKeyElem) Create

func (fk ForeignKeyElem) Create(d Dialect) (string, error)

Create returns the element's syntax for a CREATE TABLE statement.

func (ForeignKeyElem) ForeignName

func (fk ForeignKeyElem) ForeignName() string

func (ForeignKeyElem) Modify

func (fk ForeignKeyElem) Modify(t *TableElem) error

Modify implements the TableModifier interface. It creates a column and adds the same column to the create array.

func (ForeignKeyElem) Name

func (fk ForeignKeyElem) Name() string

func (ForeignKeyElem) OnDelete

func (fk ForeignKeyElem) OnDelete(b fkAction) ForeignKeyElem

OnDelete adds an ON DELETE clause to the foreign key

func (ForeignKeyElem) OnUpdate

func (fk ForeignKeyElem) OnUpdate(b fkAction) ForeignKeyElem

OnUpdate add an ON UPDATE clause to the foreign key

func (ForeignKeyElem) ReferencesTable

func (fk ForeignKeyElem) ReferencesTable() *TableElem

ReferencesTable returns the table that this foreign key references.

func (ForeignKeyElem) Table

func (fk ForeignKeyElem) Table() *TableElem

Table returns the parent table of this foreign key.

func (ForeignKeyElem) Type

func (fk ForeignKeyElem) Type() Type

Type returns the Type of this foreign key.

type FuncClause

type FuncClause struct {
	Inner Clause
	F     string
}

func (FuncClause) Compile

func (c FuncClause) Compile(d Dialect, params *Parameters) (string, error)

func (FuncClause) String

func (c FuncClause) String() string

type InsertStmt

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

InsertStmt is the internal representation of an INSERT statement.

func Insert

func Insert(selection Selectable, selections ...Selectable) (stmt InsertStmt)

Insert creates an INSERT statement for the given columns. There must be at least one column and all columns must belong to the same table.

func (*InsertStmt) AppendColumn

func (stmt *InsertStmt) AppendColumn(c ColumnElem)

func (InsertStmt) Compile

func (stmt InsertStmt) Compile(d Dialect, params *Parameters) (string, error)

Compile outputs the INSERT statement using the given dialect and parameters. An error may be returned because of a pre-existing error or because an error occurred during compilation.

func (InsertStmt) HasColumn

func (stmt InsertStmt) HasColumn(name string) bool

func (InsertStmt) String

func (stmt InsertStmt) String() string

String outputs the parameter-less INSERT statement in a neutral dialect.

func (InsertStmt) Table

func (stmt InsertStmt) Table() *TableElem

Table returns the table of this statement

func (InsertStmt) Values

func (stmt InsertStmt) Values(arg interface{}) InsertStmt

Values adds parameters to the INSERT statement. If the given values do not match the statement's current columns, the columns will be updated. Valid values include structs, Values maps, or slices of structs or Values.

type IntClause

type IntClause struct {
	D int
}

TODO This is a dangerous clause that leads to parameters not being escaped

func (IntClause) Compile

func (c IntClause) Compile(d Dialect, params *Parameters) (string, error)

func (IntClause) String

func (c IntClause) String() string

type Integer

type Integer struct {
	NotNull       bool
	Unique        bool
	PrimaryKey    bool
	Autoincrement bool
}

Integer represents INTEGER column types.

func (Integer) Create

func (s Integer) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Integer) IsPrimaryKey

func (s Integer) IsPrimaryKey() bool

func (Integer) IsRequired

func (s Integer) IsRequired() bool

func (Integer) IsUnique

func (s Integer) IsUnique() bool

func (Integer) Validate

func (s Integer) Validate(i interface{}) (interface{}, error)

type JoinOnStmt

type JoinOnStmt struct {
	ArrayClause
	// contains filtered or unexported fields
}

JoinOnStmt implements a variety of joins

func (JoinOnStmt) Compile

func (j JoinOnStmt) Compile(d Dialect, params *Parameters) (string, error)

Compile compiles a JoinOnStmt

func (JoinOnStmt) String

func (j JoinOnStmt) String() string

String returns a default string representation of the JoinOnStmt

type Orderable

type Orderable interface {
	Orderable() OrderedColumn
}

Both ColumnElem and OrderedColumns will implement the Orderable interface

type OrderedColumn

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

OrderedColumn represents a ColumnElem that will be used in an ORDER BY clause within SELECT statements. It provides additional sorting features, such as ASC, DESC, NULLS FIRST, and NULLS LAST. If not specified, ASC is assumed by default. In Postgres: the default behavior is NULLS LAST when ASC is specified or implied, and NULLS FIRST when DESC is specified http://www.postgresql.org/docs/9.2/static/sql-select.html#SQL-ORDERBY

func (OrderedColumn) Asc

func (o OrderedColumn) Asc() OrderedColumn

func (OrderedColumn) Compile

func (o OrderedColumn) Compile(d Dialect, params *Parameters) (string, error)

func (OrderedColumn) Desc

func (o OrderedColumn) Desc() OrderedColumn

func (OrderedColumn) NullsFirst

func (o OrderedColumn) NullsFirst() OrderedColumn

func (OrderedColumn) NullsLast

func (o OrderedColumn) NullsLast() OrderedColumn

func (OrderedColumn) Orderable

func (o OrderedColumn) Orderable() OrderedColumn

func (OrderedColumn) String

func (o OrderedColumn) String() string

type Parameter

type Parameter struct {
	Value interface{}
}

Parameter stores a single value of type interface{}

func (*Parameter) Compile

func (p *Parameter) Compile(d Dialect, params *Parameters) (string, error)

Parameter compilation is dialect dependent. For instance, dialects such as PostGres require the parameter index.

func (*Parameter) String

func (p *Parameter) String() string

type Parameters

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

Parameters holds a slice of interface{} parameters

func Params

func Params() *Parameters

Params creates a new Parameters instance

func (*Parameters) Add

func (p *Parameters) Add(i interface{}) int

Add adds a parameter to the parameter slice

func (*Parameters) Args

func (p *Parameters) Args() []interface{}

func (*Parameters) Len

func (p *Parameters) Len() int

Len returns the number of parameters in the slice

type PrimaryKeyArray

type PrimaryKeyArray []string

PrimaryKeyArray is a list of columns representing the table's primary key array. It implements the TableModifier and Creatable interfaces.

func PrimaryKey

func PrimaryKey(names ...string) PrimaryKeyArray

PrimaryKey creates a new PrimaryKeyArray. Only one primary key is allowed per table.

func (PrimaryKeyArray) Contains

func (pk PrimaryKeyArray) Contains(key string) bool

Contains returns true if the PrimaryKeyArray contains the given column name.

func (PrimaryKeyArray) Create

func (pk PrimaryKeyArray) Create(d Dialect) (string, error)

Create returns the proper syntax for CREATE TABLE commands.

func (PrimaryKeyArray) Modify

func (pk PrimaryKeyArray) Modify(table *TableElem) error

Modify implements the TableModifier interface. It confirms that every column given exists in the parent table.

type Real

type Real struct {
	NotNull    bool
	Unique     bool
	PrimaryKey bool
}

Real represents REAL column types.

func (Real) Create

func (s Real) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Real) IsPrimaryKey

func (s Real) IsPrimaryKey() bool

func (Real) IsRequired

func (s Real) IsRequired() bool

func (Real) IsUnique

func (s Real) IsUnique() bool

func (Real) Validate

func (s Real) Validate(i interface{}) (interface{}, error)

type Result

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

func (*Result) All

func (r *Result) All(arg interface{}) error

All returns all result rows into the given interface, which must be a pointer to a slice of either structs, values, or a native type.

func (*Result) Close

func (r *Result) Close() error

func (*Result) Next

func (r *Result) Next() bool

func (*Result) One

func (r *Result) One(arg interface{}) error

One returns a single row from Result. The destination interface must be a pointer to a struct or a native type.

type Scanner

type Scanner interface {
	Close() error
	Columns() ([]string, error)
	Err() error
	Next() bool
	Scan(...interface{}) error
}

Scanner is used for building mock result rows for testing

type SelectStmt

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

SelectStmt is the internal representation of an SQL SELECT statement.

func Select

func Select(selections ...Selectable) (stmt SelectStmt)

Select generates a new SELECT statement from the given columns and tables.

func SelectTable

func SelectTable(table *TableElem, selects ...Selectable) (stmt SelectStmt)

SelectTable creates a SELECT statement from the given table and its columns. Any additional selections will not have their table added to the SelectStmt's tables field - they must be added with the JoinOn syntax. To perform selections using cartesian logic, use Select() instead.

func (SelectStmt) All added in v0.5.2

func (stmt SelectStmt) All() SelectStmt

All removes the DISTINCT clause from the SELECT statment.

func (SelectStmt) Compile

func (stmt SelectStmt) Compile(d Dialect, params *Parameters) (string, error)

Compile outputs the SELECT statement using the given dialect and parameters. An error may be returned because of a pre-existing error or because an error occurred during compilation.

func (SelectStmt) CompileColumns

func (stmt SelectStmt) CompileColumns(d Dialect, params *Parameters) []string

func (SelectStmt) CompileTables

func (stmt SelectStmt) CompileTables(d Dialect, params *Parameters) []string

func (SelectStmt) Distinct added in v0.5.2

func (stmt SelectStmt) Distinct(columns ...ColumnElem) SelectStmt

Distinct adds a DISTINCT clause to the SELECT statement. If any column are provided, the clause will be compiled as a DISTINCT ON.

func (SelectStmt) From

func (stmt SelectStmt) From(tables ...*TableElem) SelectStmt

From allows the SelectStmt's FROM clause to be manually specified Since selections and joins will change the statement's currently selected tables, this method should be added to the end of a selection chain.

func (SelectStmt) GroupBy

func (stmt SelectStmt) GroupBy(columns ...ColumnElem) SelectStmt

GroupBy adds a GROUP BY to the SELECT statement. Only one GROUP BY is allowed per statement. Additional calls to GroupBy will overwrite the existing GROUP BY clause.

func (SelectStmt) JoinOn

func (stmt SelectStmt) JoinOn(table *TableElem, clauses ...Clause) SelectStmt

Join adds a JOIN ... ON ... clause to the SELECT statement. TODO At least on clause should be required

func (SelectStmt) LeftOuterJoinOn

func (stmt SelectStmt) LeftOuterJoinOn(table *TableElem, clauses ...Clause) SelectStmt

Join adds a LEFT OUTER JOIN ... ON ... clause to the SELECT statement. TODO At least on clause should be required

func (SelectStmt) Limit

func (stmt SelectStmt) Limit(limit int) SelectStmt

Limit adds a LIMIT to the SELECT statement. Only one LIMIT is allowed per // statement. Additional calls to Limit will overwrite the existing LIMIT clause.

func (SelectStmt) Offset

func (stmt SelectStmt) Offset(offset int) SelectStmt

Offset adds an OFFSET to the SELECT statement. Only one OFFSET is allowed per statement. Additional calls to Offset will overwrite the existing OFFSET clause.

func (SelectStmt) OrderBy

func (stmt SelectStmt) OrderBy(params ...Orderable) SelectStmt

OrderBy adds an ORDER BY to the SELECT statement. Only one ORDER BY is allowed per statement. Additional calls to OrderBy will overwrite the existing ORDER BY clause.

func (SelectStmt) String

func (stmt SelectStmt) String() string

String outputs the parameter-less SELECT statement in a neutral dialect.

func (SelectStmt) TableExists

func (stmt SelectStmt) TableExists(name string) bool

TableExists checks if a table already exists in the SELECT statement.

func (SelectStmt) Where

func (stmt SelectStmt) Where(conds ...Clause) SelectStmt

Where adds a conditional clause to the SELECT statement. Only one WHERE is allowed per statement. Additional calls to Where will overwrite the existing WHERE clause.

type Selectable

type Selectable interface {
	Selectable() []ColumnElem
}

Selectable is an interface that allows both tables and columns to be selected. It is implemented by TableElem and ColumnElem.

type SelfForeignKeyElem

type SelfForeignKeyElem struct {
	ForeignKeyElem
	// contains filtered or unexported fields
}

func SelfForeignKey

func SelfForeignKey(name, ref string, ts ...Type) SelfForeignKeyElem

func (SelfForeignKeyElem) Modify

func (fk SelfForeignKeyElem) Modify(t *TableElem) error

type Stmt added in v0.4.0

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

Stmt is the base of all statements, including SELECT, UPDATE, DELETE, and INSERT statements

func (Stmt) Error added in v0.4.0

func (stmt Stmt) Error() error

Error returns the statement's inner error

func (*Stmt) SetError added in v0.4.0

func (stmt *Stmt) SetError(msg string, args ...interface{})

type String

type String struct {
	Length     int
	NotNull    bool
	Unique     bool
	PrimaryKey bool
	Default    *string
}

String represents VARCHAR column types.

func (String) Create

func (s String) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (String) IsPrimaryKey

func (s String) IsPrimaryKey() bool

func (String) IsRequired

func (s String) IsRequired() bool

func (String) IsUnique

func (s String) IsUnique() bool

func (String) Validate

func (s String) Validate(i interface{}) (interface{}, error)

type StringClause

type StringClause struct {
	Name string
}

TODO This is a dangerous clause that leads to parameters not being escaped

func (StringClause) Compile

func (c StringClause) Compile(d Dialect, params *Parameters) (string, error)

func (StringClause) String

func (c StringClause) String() string

type TX

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

TX wraps the current sql.Tx transaction and the Dialect associated with the transaction.

func WrapTx

func WrapTx(tx *sql.Tx, dialect Dialect) *TX

WrapTx allows aspect to take control of an existing database/sql transaction and execute queries using the given dialect.

func (*TX) Begin

func (tx *TX) Begin() (Transaction, error)

Begin returns the existing transaction. TODO Are nested transactions possible? And on what dialects?

func (*TX) Commit

func (tx *TX) Commit() error

Commit calls the wrapped transactions Commit method.

func (*TX) CommitIf

func (tx *TX) CommitIf(commit *bool) error

func (*TX) Execute

func (tx *TX) Execute(stmt Executable, args ...interface{}) (sql.Result, error)

Execute executes the Executable statement with optional arguments using the current transaction. It returns the database/sql package's Result object, which may contain information on rows affected and last ID inserted depending on the driver.

func (*TX) MustBegin

func (tx *TX) MustBegin() Transaction

Begin returns the existing transaction.

func (*TX) MustCommitIf

func (tx *TX) MustCommitIf(commit *bool) bool

func (*TX) MustExecute

func (tx *TX) MustExecute(stmt Executable, args ...interface{}) sql.Result

MustExecute will panic on error.

func (*TX) MustQuery

func (tx *TX) MustQuery(stmt Executable, args ...interface{}) *Result

MustQuery

func (*TX) MustQueryAll

func (tx *TX) MustQueryAll(stmt Executable, i interface{})

MustQueryAll

func (*TX) MustQueryOne

func (tx *TX) MustQueryOne(stmt Executable, i interface{}) bool

MustQueryOne

func (*TX) MustRollbackIf

func (tx *TX) MustRollbackIf(rollback *bool)

func (*TX) Query

func (tx *TX) Query(stmt Executable, args ...interface{}) (*Result, error)

Query executes an Executable statement with the optional arguments using the current transaction. It returns a Result object, that can scan rows in various data types.

func (*TX) QueryAll

func (tx *TX) QueryAll(stmt Executable, i interface{}) error

QueryAll will query the statement using the current transaction and populate the given interface with all results.

func (*TX) QueryOne

func (tx *TX) QueryOne(stmt Executable, i interface{}) error

QueryOne will query the statement using the current transaction and populate the given interface with a single result.

func (*TX) Rollback

func (tx *TX) Rollback() error

Rollback calls the wrapped transactions Rollback method.

func (*TX) String

func (tx *TX) String(stmt Executable) string

String returns parameter-less SQL. If an error occurred during compilation, then the string output of the error will be returned.

type TableElem

type TableElem struct {
	C ColumnSet
	// contains filtered or unexported fields
}

TableElem is underlying struct that holds an SQL TABLE schema. It is returned from the Table constructor function. TODO make this an internal struct?

func Table

func Table(name string, elements ...TableModifier) *TableElem

Table is the constructor function for TableElem. It is provided a name and any number of columns and constraints that implement the TableModifier interface.

func (*TableElem) AddCreatable added in v0.4.0

func (table *TableElem) AddCreatable(c Creatable)

AddCreatable adds a new Creatable to the table

func (*TableElem) Columns

func (table *TableElem) Columns() []ColumnElem

Columns returns the table's columns in proper order.

func (*TableElem) Compile

func (table *TableElem) Compile(d Dialect, params *Parameters) string

Compile implements the Compiles interface allowing its use in statements. TODO Compile might not be the best name for this method, since it is not a target for compilation

func (*TableElem) Create

func (table *TableElem) Create() CreateStmt

Create generates the table's CREATE statement.

func (*TableElem) Delete

func (table *TableElem) Delete() DeleteStmt

Delete is an alias for Delete(table). It will generate a DELETE statement for the entire table. Conditionals can be added with the Where() method or by specifying structs or slices of structs with Values()

func (*TableElem) Drop

func (table *TableElem) Drop() DropStmt

Create generates the table's DROP statement.

func (*TableElem) ForeignKeys

func (table *TableElem) ForeignKeys() []ForeignKeyElem

ForeignKeys returns the table's foreign keys.

func (*TableElem) Insert

func (table *TableElem) Insert() InsertStmt

Insert is an alias for Insert(table). It will create an INSERT statement for the entire table. Specify the insert values with the method Values().

func (*TableElem) Name

func (table *TableElem) Name() string

Name returns the table's name

func (*TableElem) PrimaryKey

func (table *TableElem) PrimaryKey() PrimaryKeyArray

PrimaryKey returns the table's primary key array.

func (*TableElem) Select

func (table *TableElem) Select(selections ...Selectable) SelectStmt

Select is an alias for Select(table). It will generate a SELECT statement for all columns in the table.

func (*TableElem) Selectable

func (table *TableElem) Selectable() []ColumnElem

Selectable allows the table to implement the Selectable interface, which builds SELECT statements.

func (*TableElem) String

func (table *TableElem) String() string

String returns the table name.

func (*TableElem) UniqueConstraints

func (table *TableElem) UniqueConstraints() []UniqueConstraint

UniqueConstraints returns the table's unique constraints.

func (*TableElem) Update

func (table *TableElem) Update() UpdateStmt

Update is an alias for Update(table). It will create an UPDATE statement for the entire table. Specify the update values with the method Values().

type TableModifier

type TableModifier interface {
	Modify(*TableElem) error
}

TableModifer is an interface with a single method Modify, which allows elements declared in a table schema to modify the parent table. In the case of a ColumnElem, it will add the column after checking for a namespace collision. TODO make this an internal interface?

type Text

type Text struct {
	NotNull bool
}

Text represents TEXT column types.

func (Text) Create

func (s Text) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Text) IsPrimaryKey

func (s Text) IsPrimaryKey() bool

func (Text) IsRequired

func (s Text) IsRequired() bool

func (Text) IsUnique

func (s Text) IsUnique() bool

func (Text) Validate

func (s Text) Validate(i interface{}) (interface{}, error)

type Timestamp

type Timestamp struct {
	NotNull         bool
	PrimaryKey      bool
	WithTimezone    bool
	WithoutTimezone bool
	Default         string // TODO Should this be a clause that compiles?
}

Timestamp represents TIMESTAMP column types. TODO take a time.Location for timezone options

func (Timestamp) Create

func (s Timestamp) Create(d Dialect) (string, error)

Create returns the syntax need to create this column in CREATE statements.

func (Timestamp) IsPrimaryKey

func (s Timestamp) IsPrimaryKey() bool

func (Timestamp) IsRequired

func (s Timestamp) IsRequired() bool

func (Timestamp) IsUnique

func (s Timestamp) IsUnique() bool

func (Timestamp) Validate

func (s Timestamp) Validate(i interface{}) (interface{}, error)

type Transaction

type Transaction interface {
	Connection
	Commit() error
	CommitIf(*bool) error
	MustCommitIf(*bool) bool
	Rollback() error
	MustRollbackIf(*bool)
}

type Type

type Type interface {
	Creatable
	IsPrimaryKey() bool
	IsRequired() bool
	IsUnique() bool
	Validate(interface{}) (interface{}, error)
}

Type is the interface that all sql Types must implement

type UnaryClause

type UnaryClause struct {
	Pre Clause
	Sep string
}

func (UnaryClause) Compile

func (c UnaryClause) Compile(d Dialect, params *Parameters) (string, error)

func (UnaryClause) String

func (c UnaryClause) String() string

type UniqueConstraint

type UniqueConstraint []string

UniqueConstraint is the internal representation of a UNIQUE constraint. It implements the TableModifier and Creatable interfaces.

func Unique

func Unique(names ...string) UniqueConstraint

Unique creates a new UniqueConstraint from the given column names.

func (UniqueConstraint) Create

func (uc UniqueConstraint) Create(d Dialect) (string, error)

Create returns the proper syntax for CREATE TABLE commands.

func (UniqueConstraint) Modify

func (uc UniqueConstraint) Modify(table *TableElem) error

Modify implements the TableModifier interface. It confirms that every column given exists in the parent table.

type UpdateStmt

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

UpdateStmt is the internal representation of an SQL UPDATE statement.

func Update

func Update(table *TableElem) (stmt UpdateStmt)

Update creates an UPDATE statement for the given table.

func (UpdateStmt) Compile

func (stmt UpdateStmt) Compile(d Dialect, params *Parameters) (string, error)

Compile outputs the UPDATE statement using the given dialect and parameters. An error may be returned because of a pre-existing error or because an error occurred during compilation.

func (UpdateStmt) String

func (stmt UpdateStmt) String() string

String outputs the parameter-less UPDATE statement in a neutral dialect.

func (UpdateStmt) Values

func (stmt UpdateStmt) Values(values Values) UpdateStmt

Values attaches the given values to the statement. The keys of values must match columns in the table. TODO Allow structs to be used if a primary key is specified in the schema

func (UpdateStmt) Where

func (stmt UpdateStmt) Where(conds ...Clause) UpdateStmt

Where adds a conditional WHERE clause to the UPDATE statement.

type Values

type Values map[string]interface{}

Values is a map of column names to parameters.

func (Values) Compile

func (v Values) Compile(d Dialect, params *Parameters) (string, error)

Compile converts all key value pairs into a binary clauses. Since map iteration is non-deterministic, we'll sort the keys to produce repeatable SQL statements (especially for testing)

func (Values) Diff

func (v Values) Diff(other Values) Values

Diff returns the values in v that differ from the values in other. ISO 31-11: v \ other

func (Values) Keys

func (v Values) Keys() []string

Keys returns the keys of the Values map in alphabetical order.

func (Values) String

func (v Values) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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