persistence

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2019 License: MIT Imports: 10 Imported by: 6

README

persistence

A dialect agnostic database driver extension to provide simplified query and transaction execution

Created for the sake of learning and memes

Build status Coverage Report Go Report Card GoDoc

Features

  • Off the shelf support for sqlite and postgres
  • Execute raw queries/statements
  • Transactions
  • Primary/Foreign/Composite Primary key support
  • Support for Eagerly loading items which require joins
  • Support for insertion of items joined to the primary item without requiring multiple calls
  • Optionally update items with their current primary keys on insert/update
  • Write only data (more on this later)
  • Support for multiple dialects (requires drivers to be written)
  • Aims to be simple to use

Connecting

Open the connection to your database and specify which driver you will be using. Currently only postgres the postgres driver is written.

Example
import (
	_ "gitlab.com/cosban/persistence/postgres"
	"gitlab.com/cosban/persistence"
)

func main() {
	var connectionTemplate = "postgres://%s:%s@%s:%d/%s?sslmode=%s"
	c, err := persistence.Open(
		"postgres",
		fmt.Sprintf(connectionTemplate, username, password, host, port, database, sslmode),
	)
}

Querying

persistence can perform both raw, and built up queries.

// raw  
var actualText string
query := persistence.Prepare("SELECT value FROM raw_example")
err := c.RawStatement().QueryRow(query, &actualText)

// builder 
type Object struct {
	Value  string 
}
var actual Object
err := c.BuildStatement().Query(&actual)

Prepared Statements

If a query is too complicated to easily build within the query builder, it is very simple to write and execute your own queries within a prepared statement.

// single row
var value1 string
var value2 string
statement := persistence.Prepare("SELECT value1, value2 FROM raw_example LIMIT 1")
err := c.RawStatement().QueryRow(query, &value1, &value2)
if err != nil {
	panic(err)
}
fmt.Println(value1, value2)

// multiple rows
statement := persistence.Prepare("SELECT value1, value2 FROM raw_example LIMIT 1")
rows, err := c.RawStatement().Query(query)
if err != nil {
	panic(err)
}
defer rows.Close()
for rows.Next() {
	var value string
	err = rows.Scan(&value)
	if err != nil {
		panic(err)
	}
	fmt.Println(value)
}

Statement Execution

Either execute your transactions, i.e. your inserts, updates, deletes, Or your queries which return data.
For single statement operations, you may prepare and execute/query in one step using the PrepareAnd... methods available from your connection. You can either query for a single row, or multiple. It's up to you.

// raw
statement := persistence.Prepare("INSERT INTO raw_example (value) VALUES ($1)", "beep boop")
err := persistence.RawStatement().ExecuteStatements(statement)

// builder
type Object struct {
	Value  string 
}
actual := Object{"beep boop"}
err := c.BuildStatement().Insert(actual)

Documentation

Overview

Package persistence is a pure* Go sql dialect agnostic sql interface. It can be used as a raw query executor, query builder, or ORM. Persistence comes packaged with the dialects which can be used to interact with either postgres or sqlite databases. These are both optional to use.

*the sqlite dialect driver, if used, requires cgo and is therefore not "pure". It is not required for persistence to be usable though.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetUsableType

func GetUsableType(i interface{}) reflect.Type

GetUsableType takes in an interface and returns a "usable" `reflect.Type` which represents it. A type is considered "usable" if it is not a pointer. If a pointer is passed to `GetUsableType`, then the method will return a `reflect.Type` of the underlying item.

func GetUsableValue

func GetUsableValue(i interface{}) reflect.Value

GetUsableValue takes in an interface and returns a "usable" `reflect.Value` which represents it. A value is considered "usable" if it is not a pointer. If a pointer is passed to `GetUsableValue`, then the method will return a `reflect.Value` of the underlying item. If that pointer is nil, a zero-value of that type will be returned.

func GetValueFrom

func GetValueFrom(value reflect.Value) interface{}

GetValueFrom takes in a `reflect.Value` and returns an actual implementation of that value

func Prepare

func Prepare(query string, args ...interface{}) statement.Statement

Prepare builds a statement to be executed

func PrepareQuery added in v0.2.0

func PrepareQuery(query string, args ...interface{}) statement.Statement

PrepareQuery builds a statement to be used in a query

func SetDelimiter

func SetDelimiter(replacement string)

SetDelimiter globally sets the delimiter that should be used to separate tags. Only use this if you definitely know what you are doing.

Types

type CommonDriver added in v0.2.0

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

CommonDriver contains a base functionality for many sql driver operations which may be used or overridden by any dialect driver. It is not mandatory that a dialect driver makes use of the common driver even though all drivers must implement the driver interface.

func (*CommonDriver) AddTableColumn added in v0.2.0

func (d *CommonDriver) AddTableColumn(meta TableMeta, field FieldMeta) statement.Statement

AddTableColumn implements the basic functionality to add a column to a table in the database for most dialects

func (*CommonDriver) Bind added in v0.2.0

func (d *CommonDriver) Bind(length int) string

Bind calls the bind function which was previously provided by the dialect driver

func (*CommonDriver) BuildRepeatableSection added in v0.2.0

func (d *CommonDriver) BuildRepeatableSection(
	prefix, joiner string,
	meta TableMeta,
	argsLen int,
	qualifyColumn bool,
	shouldParse func(FieldMeta) bool,
) (string, []interface{})

func (*CommonDriver) ColsToString added in v0.2.0

func (d *CommonDriver) ColsToString(columns *FieldMetas) string

ColsToString implements the basic functionality to provide basic database type information for all fields a table will have for table creation, or gathering metadata about the table for most dialects

func (*CommonDriver) Constraints added in v0.2.0

func (d *CommonDriver) Constraints(constraints []Constraint, currentArgs int) (string, []interface{})

Constraints implements the basic functionality to create a list of constraints which are to be used in queries for most dialects

func (*CommonDriver) CreateTable added in v0.2.0

func (d *CommonDriver) CreateTable(meta TableMeta) statement.Statement

CreateTable implements the basic functionality to create a table in the database for most dialects

func (*CommonDriver) DefaultSchema added in v0.2.0

func (d *CommonDriver) DefaultSchema() string

DefaultSchema returns the default schema which is to be used for all operations unless overridden.

func (*CommonDriver) Delete added in v0.2.0

func (d *CommonDriver) Delete(meta TableMeta, constraints ...Constraint) statement.Statement

Delete implements the basic functionality to delete entries from a table for most dialects

func (*CommonDriver) DeriveConstraints added in v0.2.0

func (d *CommonDriver) DeriveConstraints(columns *FieldMetas) string

DeriveConstraints is used to determine any constraints that a column may have on it during table creation or the addition of columns. This includes uniqueness, primary key, and combined key constraints.

func (*CommonDriver) DropTable added in v0.2.0

func (d *CommonDriver) DropTable(model TableMeta) statement.Statement

DropTable implements the basic functionality to drop a table from the database for most dialects

func (*CommonDriver) GetFullTableName added in v0.2.0

func (d *CommonDriver) GetFullTableName(meta TableMeta) string

GetFullTableName returns the fully qualified name for a table. This means that the schema is included.

func (*CommonDriver) GetSchema added in v0.2.0

func (d *CommonDriver) GetSchema(meta TableMeta) string

GetSchema returns the schema which has been specified by a TableMeta, if none is provided, the default will be used

func (*CommonDriver) Insert added in v0.2.0

func (d *CommonDriver) Insert(meta TableMeta) statement.Statement

Insert implements the basic functionality to insert one or more items of the same type into a table for most dialects

func (*CommonDriver) IsValidType added in v0.2.0

func (d *CommonDriver) IsValidType(t reflect.Type) bool

IsValidType calls the isValidType function which was previously provided by the dialect driver

func (*CommonDriver) Join added in v0.2.0

func (d *CommonDriver) Join(constraint JoinConstraint, currentArgs int) (string, []interface{})

Join implements the basic functionality to join against another table within a query for most dialects.

func (*CommonDriver) JoinConstraints added in v0.2.0

func (d *CommonDriver) JoinConstraints(constraints []JoinConstraint, currentArgs int) (string, []interface{})

func (*CommonDriver) Query added in v0.2.0

func (d *CommonDriver) Query(meta TableMeta, pieces QueryPieces) statement.Statement

Query implements the basic functionality to create a full query in most dialects

func (*CommonDriver) Select added in v0.2.0

func (d *CommonDriver) Select(selects []string) string

Select implements the basic functionality to provide the selected columns portion of a query for most dialects

func (*CommonDriver) SetBindFunc added in v0.2.0

func (d *CommonDriver) SetBindFunc(fn func(int) string)

SetBindFunc is to be used by all dialect drivers which use the CommonDriver. It specifies how to bind variables within a query

func (*CommonDriver) SetDefaultSchema added in v0.2.0

func (d *CommonDriver) SetDefaultSchema(schema string)

SetDefaultSchema sets a default schema for all operations to use unless overridden by the operation.

func (*CommonDriver) SetIsValidTypeFunc added in v0.2.0

func (d *CommonDriver) SetIsValidTypeFunc(fn func(reflect.Type) bool)

SetIsValidTypeFunc is to be used by all dialect drivers which use the CommonDriver. It specifies how to determine whether a provided type is valid

func (*CommonDriver) SetToColumnTypeFunc added in v0.2.0

func (d *CommonDriver) SetToColumnTypeFunc(fn func(FieldMeta) string)

SetToColumnTypeFunc is to be used by all dialect drivers which use the CommonDriver. It specifies how to determine the column type to use for any given field to be used in the database.

func (*CommonDriver) ToColumnType added in v0.2.0

func (d *CommonDriver) ToColumnType(column FieldMeta) string

ToColumnType calls the toColumnType function which was previously provided by the dialect driver

func (*CommonDriver) Update added in v0.2.0

func (d *CommonDriver) Update(meta TableMeta, constraints ...Constraint) statement.Statement

Update implements the basic functionality to update currently existing values in the database for most dialects

func (*CommonDriver) Upsert added in v0.2.0

func (d *CommonDriver) Upsert(meta TableMeta) statement.Statement

Upsert implements the basic functionality to insert or update (if already existing) values for most dialects

type Connection

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

Connection represents a connection to a database. Programs should keep hold of this connection because it is how all interaction within the database takesplace, whether through raw, or built up queries.

func Open

func Open(driver, connection string) (*Connection, error)

Open takes in a connection string and opens a wrapped connection from it

connection, err := persistence.Open("postgres", "postgres://user@localhost:5432/database?sslmode=disable")

persistence contains a postgres driver built in, but the user may import any other driver as long as it implements the `Driver` interface while also setting themselves as a driver on init

import _ "gitlab.com/cosban/persistence/postgres"

// driver init example
package driver
func init() {
   persistence.DialectDriver = &postgres{
       schema: "public",
   }
}

func (*Connection) BeginTx

func (c *Connection) BeginTx() error

BeginTx starts a transaction

func (*Connection) BuildStatement

func (c *Connection) BuildStatement() *StatementBuilder

BuildStatement begins creation and execution of a query that is written out with the query builder

func (*Connection) Close

func (c *Connection) Close()

Close closes a database connection. Once a connection is closed, it may no longer be used. A new one must be created.

func (*Connection) CommitTx

func (c *Connection) CommitTx() error

CommitTx commits the last in progress transaction

func (*Connection) ExecuteTx

func (c *Connection) ExecuteTx() error

ExecuteTx determines whether a commit or rollback needs to take place by checking whether any of the components which make up the latest transaction produced an error. A commit occurs on no error, otherwise a rollback takes place. The boolean value returned is an indicator of whether the transaction attempted to commit You may want to defer execution of a transaction

conn.BeginTx()
defer con.ExecuteTx()
// if errors occur during a transaction, they are recorded and `ExecuteTx` will rollback
err := /* perform query or execute statement */
if err != nil {
    return err // `ExecuteTx` rolls back and error is returned
}

func (*Connection) IsConnected

func (c *Connection) IsConnected() bool

IsConnected pings the database and returns true if the connection is still active

func (*Connection) RawStatement

func (c *Connection) RawStatement() *RawStatement

RawStatement begins creation and execution of a query that is written out raw

func (*Connection) RollbackTx

func (c *Connection) RollbackTx() error

RollbackTx rolls back the last in progress transaction

func (*Connection) SetDefaultSchema

func (c *Connection) SetDefaultSchema(schema string)

SetDefaultSchema sets the default schema on the database being used. This is only needed if transactions need to be performed on a non-standard schema. If this is not set by the user, the default schema is set by the driver. This is usually set as `public` or `dbo`.

type Constraint

type Constraint struct {
	Section string
	Kind    string
	Args    []interface{}
}

Constraint is used to modify the results of a query, either by filtering, ordering, or joining

type Driver

type Driver interface {

	// SetDefaultSchema overrides the default schema that would normally be set by the driver
	SetDefaultSchema(string)
	// DefaultSchema returns the schema that should be used for statements that do not specify a schema
	DefaultSchema() string
	// HasTable returns a statement that, when executed, specifies whether a table exists in the database
	HasTable(TableMeta) statement.Statement
	// CreateTable returns a statement that creates a table when executed
	CreateTable(TableMeta) statement.Statement
	// DropTable returns a statement that drops a table when executed
	DropTable(TableMeta) statement.Statement
	// GetTableColumns returns a statement that lists all available columns in a specific table when executed
	GetTableColumns(TableMeta) statement.Statement
	// AddTableColumn returns a statement that alters the specified table to include an additional column when executed
	AddTableColumn(TableMeta, FieldMeta) statement.Statement
	// Query returns a statement that can be used to execute a database query
	Query(TableMeta, QueryPieces) statement.Statement
	// Insert returns a statement that can be used to insert data
	Insert(TableMeta) statement.Statement
	// Update returns a statement that can be used to update data
	Update(TableMeta, ...Constraint) statement.Statement
	// Upsert returns a statement that can be used to insert data if it does not exist, or update it in the event that
	// it does
	Upsert(TableMeta) statement.Statement
	// Delete returns a statement that can be used to delete data
	Delete(TableMeta, ...Constraint) statement.Statement
	// GetFullTableName returns the fully qualified name (typically [database].[schema].[table]) of a table
	GetFullTableName(TableMeta) string
	// Select is used to create the select portion of a query from the given fields
	Select([]string) string
	// contains filtered or unexported methods
}

Driver is an implementation of the methods necessary for persistence to fully interact with a dialect of SQL

var (
	DialectDriver Driver
)

DialectDriver is the driver which the user set. Do this by blank importing the driver in your main class.

type ExecutedResult added in v0.2.0

type ExecutedResult struct {
	HasRows   bool
	HasResult bool
	Rows      *sql.Rows
	Result    sql.Result
}

ExecutedResult provides the metadata about the results of a statement that has been executed

type Export

type Export struct {
	Name string
	Meta TableMeta
}

type FieldMeta

type FieldMeta struct {
	Name       string
	Type       reflect.Type
	DataType   string
	Tag        Tag
	Valid      bool
	References *reference
	// contains filtered or unexported fields
}

FieldMeta provides data used to determine the name, type, and constraints belonging to a column

func (FieldMeta) GetName

func (m FieldMeta) GetName() string

GetName returns the column name of a field. Tags may overwrite the default, which is the name of the variable.

func (FieldMeta) GetType

func (m FieldMeta) GetType() reflect.Type

GetType returns the underlying type that a FieldMeta represents

func (*FieldMeta) PopulateForeignKeyReferences added in v0.2.0

func (m *FieldMeta) PopulateForeignKeyReferences(registeredMetas []*TableMeta)

func (FieldMeta) Set added in v0.2.0

func (m FieldMeta) Set() bool

Set returns true if the underlying value of the Fieldmeta has been set

func (*FieldMeta) SetValue added in v0.2.0

func (m *FieldMeta) SetValue(i interface{})

SetValue sets the underlying value of a FieldMeta

func (FieldMeta) Value

func (m FieldMeta) Value() interface{}

Value returns the underlying value of a FieldMeta

func (FieldMeta) Zero added in v0.2.0

func (m FieldMeta) Zero() bool

Zero returns true if the FieldMeta does not represent a value that has been set

type FieldMetas

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

FieldMetas is an ordered map of FieldMeta keyed by each FieldMeta's name as provided by the the item containing it

func NewFieldMetas

func NewFieldMetas() *FieldMetas

NewFieldMetas returns a blank *FieldMetas

func NewFieldMetasFrom

func NewFieldMetasFrom(metas ...FieldMeta) *FieldMetas

NewFieldMetasFrom takes in FieldMetas and returns a pre-populated *FieldMetas

func (*FieldMetas) Copy

func (m *FieldMetas) Copy() *FieldMetas

Copy returns a copy of the FieldMetas which can be used without affecting the original

func (*FieldMetas) Current added in v0.2.0

func (m *FieldMetas) Current() (string, FieldMeta)

Current returns the key and value stored at the position of the internal index

func (*FieldMetas) Get

func (m *FieldMetas) Get(key string) FieldMeta

Get returns the FieldMeta which corresponds to the given key

func (*FieldMetas) Index

func (m *FieldMetas) Index(i int) (string, FieldMeta)

Index returns the key and value stored at the requested index

func (*FieldMetas) Iter added in v0.2.0

func (m *FieldMetas) Iter() *FieldMetas

Iter returns a copy of the FieldMetas that is able to be cleanly iterated over

func (*FieldMetas) Next added in v0.2.0

func (m *FieldMetas) Next() bool

Next moves moves the internal index forward and returns true if there is a value available to be read

func (*FieldMetas) PopulateForeignKeyReferences added in v0.2.0

func (m *FieldMetas) PopulateForeignKeyReferences(registeredMetas []*TableMeta, template FieldMeta)

func (*FieldMetas) Set

func (m *FieldMetas) Set(key string, value FieldMeta)

Set puts the key and value into the map ordered map. If the key already exists, its order is maintained.

func (*FieldMetas) Size

func (m *FieldMetas) Size() int

Size returns the number of items that are contained within the FieldMetas

type JoinConstraint

type JoinConstraint struct {
	Constraint
	Export
	Kind    JoinKind
	From    TableMeta
	Against TableMeta
}

type JoinKind

type JoinKind uint32

JoinKind specifies which type of join is to be used

const (
	// InnerJoin represents a full inner join on the database
	InnerJoin JoinKind = iota + 1
	// FullOuterJoin represents a full outer join on the database
	FullOuterJoin
	// LeftOuterJoin represents a left outer join on the database
	LeftOuterJoin
	// RightOuterJoin represents a right outer join on the database
	RightOuterJoin
)

type Meta

type Meta interface {
	GetName() string
	GetType() reflect.Type
}

Meta is a representation of a struct or value which has a name and a type

type QueryPieces

type QueryPieces struct {
	Table   string
	Schema  string
	Selects []string
	Filters []Constraint
	Joins   []JoinConstraint
	Limit   int
	Offset  int
	Order   []string
	Groups  []string
	Having  []Constraint
	Args    []interface{}
}

QueryPieces is the structured representation of a query

type RawStatement

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

RawStatement is used to create raw queries or statements

func (*RawStatement) BlindlyExecuteStatements added in v0.2.0

func (r *RawStatement) BlindlyExecuteStatements(stmts ...statement.Statement) error

BlindlyExecuteStatements allows the user to execute or query >= 1 statement in a single sql transaction but only returns error info

func (*RawStatement) Execute added in v0.2.0

func (r *RawStatement) Execute(stmt statement.Statement) (sql.Result, error)

Execute allows the user to execute a statement it returns the result of the execution

func (*RawStatement) ExecuteStatements

func (r *RawStatement) ExecuteStatements(stmts ...statement.Statement) ([]ExecutedResult, error)

ExecuteStatements allows the user to execute or query >= 1 statement in a single sql transaction

func (*RawStatement) PrepareAndExecute

func (r *RawStatement) PrepareAndExecute(query string, args ...interface{}) (sql.Result, error)

PrepareAndExecute performs the actions of Prepare and Execute a single statement in one step rather than forcing the user to manually Prepare a statement.

func (*RawStatement) PrepareAndQuery

func (r *RawStatement) PrepareAndQuery(query string, args ...interface{}) (*sql.Rows, error)

PrepareAndQuery performs the actions of Prepare and Query a single statement in one step rather than forcing the user to manually Prepare a statement.

func (*RawStatement) Query

func (r *RawStatement) Query(stmt statement.Statement) (*sql.Rows, error)

Query allows the user to perform a query where >= 1 rows are expected back It simply returns the rows so that the user may manipulate the data as they please

func (*RawStatement) QueryRow

func (r *RawStatement) QueryRow(stmt statement.Statement, data ...interface{}) error

QueryRow allows the user to perform an sql query where only one row is expected The results of the query are put into the passed in data interfaces

type StatementBuilder

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

StatementBuilder is used to build and execute a query

func (*StatementBuilder) And

func (query *StatementBuilder) And(section string, args ...interface{}) *StatementBuilder

And adds an additional AND constraint to the query. Constraints are not yet grouped, so this only allows for simple constraints to be used.

func (*StatementBuilder) Count added in v0.2.0

func (query *StatementBuilder) Count() (int, error)

Count causes a statement to actually execute and returns the number of rows that were returned as a result of the query

func (*StatementBuilder) CreateFromModel

func (query *StatementBuilder) CreateFromModel(models ...interface{}) error

CreateFromModel takes in one or more models and attmepts to create tables based on their properties and tags. For a field to become a column, it must be of a valid type (as specified by the driver), or a valid type within an anonymous member

func (*StatementBuilder) CreateOrUpdateTable

func (query *StatementBuilder) CreateOrUpdateTable(models ...interface{}) error

CreateOrUpdateTable is a feature incomplete method which aims to create new tables for the supplied models if the tables do not exist, or to supplement the existing tables with any additional columns or joins if they do exist. The method does not fully migrate tables yet so should be used with great care.

func (*StatementBuilder) Delete

func (query *StatementBuilder) Delete(deletes ...interface{}) error

Delete will attempt to delete any rows represented by the supplied models. This cascades for joins as well.

func (*StatementBuilder) DropFromModel

func (query *StatementBuilder) DropFromModel(models ...interface{}) error

DropFromModel will attempt to drop the tables represented by the given models. It will return the first encountered error if any are seen during this process.

func (*StatementBuilder) Eager

func (query *StatementBuilder) Eager(name string, model interface{}) *StatementBuilder

Eager sets the query to join against the tables required in order to fill all of the items that make up the provided field within the primary model. When the query is executed, the slice of all of these items will be exported into the primary model without requiring additional calls.

func (*StatementBuilder) From

func (query *StatementBuilder) From(i interface{}) *StatementBuilder

From is used to determine which table is queried from

func (*StatementBuilder) FullJoin

func (query *StatementBuilder) FullJoin(name string, model interface{}) *StatementBuilder

FullJoin performs a full outer join against another table in the database while also allowing the user to specify constraints for how the join should be performed.

func (*StatementBuilder) GetSchema added in v0.2.0

func (query *StatementBuilder) GetSchema() string

GetSchema returns the schema to be used within the query being built

func (*StatementBuilder) HasTable

func (query *StatementBuilder) HasTable(model interface{}) (bool, error)

HasTable queries the database to check the existence of any table with the name that the supplied model would use if any error occurs, `HasTable` will return false and that error regardless of whether the table actually exists.

func (*StatementBuilder) Including

func (query *StatementBuilder) Including(name string, model interface{}) *StatementBuilder

Including appends the meta of the included interface to the StatementBuilder in such a way that if the provided field, which must be a slice, is not empty, those items contained within that field will also be upserted. This will also fill in any applicable join tables in the event that the field is a multi-join field FIXME: changes are additive only. Deletes are not performed on joins or multi-joins

func (*StatementBuilder) Insert

func (query *StatementBuilder) Insert(inserts ...interface{}) error

Insert attempts to insert all of the provided models. If a join or multi-join are present within a model. If Include was called before insert, then persistence will try to insert each value found within the include as well.

func (*StatementBuilder) IsValidType added in v0.2.0

func (query *StatementBuilder) IsValidType(t reflect.Type) bool

IsValidType requests for the dialect driver to determine whether the provided type is valid

func (*StatementBuilder) Join

func (query *StatementBuilder) Join(name string, model interface{}) *StatementBuilder

Join performs an inner join against another table in the database while also allowing the user to specify constraints for how the join should be performed.

func (*StatementBuilder) LeftJoin

func (query *StatementBuilder) LeftJoin(name string, model interface{}) *StatementBuilder

LeftJoin performs a left join against another table in the database while also allowing the user to specify constraints for how the join should be performed.

func (*StatementBuilder) Limit

func (query *StatementBuilder) Limit(limit int) *StatementBuilder

Limit ensures that no more than the provided number of results will be returned when the query is executed

func (*StatementBuilder) Offset

func (query *StatementBuilder) Offset(offset int) *StatementBuilder

Offset skips over the first N results in the query where N is the number provided

func (*StatementBuilder) On added in v0.2.0

func (query *StatementBuilder) On(section string, args ...interface{}) *StatementBuilder

On specifies the constraints to be used on the last created join

func (*StatementBuilder) Or

func (query *StatementBuilder) Or(section string, args ...interface{}) *StatementBuilder

Or adds an additional OR constraint to the query. Constraints are not yet grouped, so this only allows for simple constraints to be used.

func (*StatementBuilder) Order

func (query *StatementBuilder) Order(order ...string) *StatementBuilder

Order specifies the order in which results from the query should be returned

func (*StatementBuilder) Query

func (query *StatementBuilder) Query(i interface{}) error

Query causes a statement to actually execute and sets the underlying data on to the provided interface

func (*StatementBuilder) RightJoin

func (query *StatementBuilder) RightJoin(name string, model interface{}) *StatementBuilder

RightJoin performs a right join against another table in the database while also allowing the user to specify constraints for how the join should be performed.

func (*StatementBuilder) Schema

func (query *StatementBuilder) Schema(schema string) *StatementBuilder

Schema sets the schema to be used in this query for times when usage of the default schema is not desired

func (*StatementBuilder) Select

func (query *StatementBuilder) Select(selects ...string) *StatementBuilder

Select will limit the fields which are populated in the event that the user does not want the entire model to be populated

func (*StatementBuilder) Update

func (query *StatementBuilder) Update(updates ...interface{}) error

Update attempts to update all of the provided models. If a join or multi-join are present within a model, Update will attempt to insert the joined items as well if they do not already exist.

func (*StatementBuilder) Upsert

func (query *StatementBuilder) Upsert(upserts ...interface{}) error

Upsert attempts to insert the provided items if they do not exist in the table yet, otherwise updating those existing items. Like `Insert` and `Update`, if joins are present, it will attempt to insert them should they not exist.

func (*StatementBuilder) Where

func (query *StatementBuilder) Where(section string, args ...interface{}) *StatementBuilder

Where will set a constraint on the query that is being built. Where must be called before `And`/`Or` are used. Constraints are not yet grouped, so this only allows for simple constraints to be used.

type TableMeta

type TableMeta struct {
	Name            string
	Pointer         bool
	JoinTable       bool
	Type            reflect.Type
	Schema          string
	Columns         *FieldMetas
	Primary         *FieldMetas
	Joins           map[string][]TableMeta
	ManyToManyJoins map[string][]TableMeta
	Zero            bool
}

TableMeta contains all of the information needed to construct a new table

func DeriveTableMetaFromExport added in v0.2.0

func DeriveTableMetaFromExport(export interface{}, validator TypeValidator) TableMeta

DeriveTableMetaFromExport attempts to ObtainTableMeta with the provided export, it will search for the first underlying type of any slice/pointer/etc that is provided to it.

func ObtainTableMeta

func ObtainTableMeta(model interface{}, validator TypeValidator) TableMeta

ObtainTableMeta constructs a TableMeta that represents the given interface. It also includes additional information that is necessary for writing/modifying/deleting the data in the database.

func (TableMeta) AreAllColumnsPrimary

func (meta TableMeta) AreAllColumnsPrimary() bool

AreAllColumnsPrimary returns true if every column within a table is also a primary key

func (TableMeta) Copy

func (meta TableMeta) Copy() TableMeta

Copy returns an equivalent copy of the receiver. This copy is able to be modified without changing the original.

func (TableMeta) Export

func (meta TableMeta) Export(i interface{}, exports ...Export)

Export takes in an interface, and if that interface a pointer to the type that the TableMeta represents, then the TableMeta will copy its values into the interface.

func (TableMeta) GetName

func (meta TableMeta) GetName() string

GetName returns the name of the item represented by the TableMeta

func (TableMeta) GetRowIDField added in v0.2.0

func (meta TableMeta) GetRowIDField() FieldMeta

GetRowIDField returns a field which should represent the rowid for any row within a table. This function is not supported by every dialect of sql.

func (TableMeta) GetType

func (meta TableMeta) GetType() reflect.Type

GetType returns the type of data that is represented by the TableMeta

func (TableMeta) IsEmpty

func (meta TableMeta) IsEmpty() bool

IsEmpty returns true if a tableMeta does not represent anything

func (TableMeta) ToMap

func (meta TableMeta) ToMap() map[string]interface{}

ToMap returns a map representation of a TableMeta where the key is the name of each FieldMeta and the value is the value that each FieldMeta represents

type Tag

type Tag struct {
	Valid          bool
	Name           string
	NotNullable    bool
	Unique         bool
	PrimaryKey     bool
	CombinedKey    string
	DefaultValue   string
	References     string
	Type           string
	Join           bool
	ManyToManyJoin bool
	Generated      bool
}

Tag is the representation of a persistence struct tag

type TypeValidator added in v0.2.0

type TypeValidator interface {
	IsValidType(reflect.Type) bool
	GetSchema() string
}

TypeValidator is used to determine whether a provided type is supported by the database

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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