qb

package module
v0.0.0-...-cf5e520 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2016 License: GPL-2.0 Imports: 11 Imported by: 0

README

alt text

qb - the database toolkit for go

Build Status Coverage Status License (LGPL version 2.1) Go Report Card GoDoc

This project is currently pre 1.

Currently, it's not feature complete. It can have potential bugs. There are no tests having concurrency race condition tests. It can crash especially in concurrency. Before 1.x releases, each major release could break backwards compatibility.

About qb

qb is a database toolkit for easier db usage in go. It is inspired from python's most favorite orm sqlalchemy. qb is an orm as well as a query builder. It is quite modular in case of using just expression api and query building stuff.

Documentation

The documentation is hosted in readme.io which has great support for markdown docs. Currently, the docs is about 80% - 90% complete. The doc files will be added to this repo soon. Moreover, you can check the godoc from here. Contributions & Feedbacks in docs are welcome.

What's New (0.2)

The new table api design provides functionality for generating table objects like in the sqlalchemy's expression api. Here's a full example to define a table;

    db, err := qb.New("mysql", "root:@tcp(localhost:3306)/qb_test?charset=utf8")
	if err != nil {
		panic(err)
	}

	usersTable := qb.Table(
		"users",
		qb.Column("id", qb.Varchar().Size(40)),
		qb.Column("facebook_id", qb.BigInt()),
		qb.Column("email", qb.Varchar().Size(40).Unique()),
		qb.Column("device_id", qb.Varchar().Size(255).Unique()),
		qb.Column("session_id", qb.Varchar().Size(40)),
		qb.Column("auth_token", qb.Varchar().Size(40)),
		qb.Column("role_id", qb.Varchar().Size(40)),
		qb.PrimaryKey("id"),
		qb.ForeignKey().
			Ref("session_id", "sessions", "id").
			Ref("auth_token", "sessions", "auth_token").
			Ref("role_id", "roles", "id"),
		qb.UniqueKey("email", "device_id"),
	).Index("email", "device_id").Index("facebook_id")

	fmt.Println(usersTable.Create(db.Builder().Adapter()), "\n")

	db.Metadata().AddTable(usersTable)
	err = db.Metadata().CreateAll(db.Engine())
	if err != nil {
		panic(err)
	}
	
	// prints
	//CREATE TABLE users (
    //	session_id VARCHAR(40),
    //	auth_token VARCHAR(40),
    //	role_id VARCHAR(40),
    //	id VARCHAR(40),
    //	facebook_id BIGINT,
    //	email VARCHAR(40) UNIQUE,
    //	device_id VARCHAR(255) UNIQUE,
    //	PRIMARY KEY(id),
    //	FOREIGN KEY(session_id, auth_token) REFERENCES sessions(id, auth_token),
    //	FOREIGN KEY(role_id) REFERENCES roles(id),
    //	CONSTRAINT u_email_device_id UNIQUE(email, device_id)
    //);
    //CREATE INDEX i_email_device_id ON users(email, device_id);
    //CREATE INDEX i_facebook_id ON users(facebook_id);
	

Features

  • Support for postgres(9.5.+), mysql & sqlite3
  • Simplistic query builder with no real magic
  • Struct to table ddl mapper where initial table migrations can happen
  • Expression builder which can be built almost any sql statements
  • Transactional session api that auto map structs to queries
  • Foreign Key definitions of structs using tags
  • Single & composite column indices
  • Relationships (soon..)

Installation

Installation with glide;

glide get github.com/aacanakin/qb

0.1 installation with glide;

glide get github.com/aacanakin/qb#0.1

Installation using go get;

go get -u github.com/aacanakin/qb

If you want to install test dependencies then;

go get -u -t github.com/aacanakin/qb

Quick Start

package main

import (
	"fmt"
	"github.com/aacanakin/qb"
	"github.com/nu7hatch/gouuid"
)

type User struct {
	ID       string `db:"_id" qb:"type:uuid; constraints:primary_key"`
	Email    string `qb:"constraints:unique, notnull"`
	FullName string `qb:"constraints:notnull"`
	Bio      string `qb:"type:text; constraints:null"`
}

func main() {

	db, err := qb.New("postgres", "user=postgres dbname=qb_test sslmode=disable")
	if err != nil {
		panic(err)
	}

	defer db.Close()

	// add table to metadata
	db.AddTable(User{})

	// create all tables registered to metadata
	db.CreateAll()

	userID, _ := uuid.NewV4()
	db.Add(&User{
		ID:       userID.String(),
		Email:    "robert@de-niro.com",
		FullName: "Robert De Niro",
	})

	err = db.Commit() // insert user
	if err != nil {
	    fmt.Println(err)
	    return
	}

	var user User
	db.Find(&User{ID: userID.String()}).One(&user)

	fmt.Println("id", user.ID)
	fmt.Println("email", user.Email)
	fmt.Println("full_name", user.FullName)

	db.DropAll() // drops all tables

}

Credits

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseDBTag

func ParseDBTag(rawTag string) string

ParseDBTag parses the "db" tag that can be used in custom column name mapping

Types

type AggregateClause

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

AggregateClause is the base struct for building aggregate functions

func Aggregate

func Aggregate(fn string, column ColumnElem) AggregateClause

Aggregate generates a new aggregate clause given function & column

func Avg

func Avg(column ColumnElem) AggregateClause

Avg function generates "avg(%s)" statement for column

func Count

func Count(column ColumnElem) AggregateClause

Count function generates "count(%s)" statement for column

func Max

func Max(column ColumnElem) AggregateClause

Max function generates "max(%s)" statement for column

func Min

func Min(column ColumnElem) AggregateClause

Min function generates "min(%s)" statement for column

func Sum

func Sum(column ColumnElem) AggregateClause

Sum function generates "sum(%s)" statement for column

func (AggregateClause) Build

func (c AggregateClause) Build(dialect Dialect) (string, []interface{})

Build compiles the aggregate clause and returns the sql and bindings

type AndClause

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

AndClause is the base struct to keep and within the where clause It satisfies the Clause interface

func And

func And(conditions ...Conditional) AndClause

And generates an AndClause given conditional clauses

func (AndClause) Build

func (c AndClause) Build(dialect Dialect) (string, []interface{})

Build compiles the and clause, joins the sql, returns sql and bindings

type Builder

type Builder interface {
	// Build takes a dialect and returns a stmt
	Build(dialect Dialect) *Stmt
}

Builder is the common interface for any statement builder in qb such as Insert(), Update(), Delete(), Select() query starters

type Clause

type Clause interface {
	Compiles
}

Clause is the key interface for any sql clause

type ColumnElem

type ColumnElem struct {
	Name  string
	Type  TypeElem
	Table string // This field should be lazily set by Table() function
}

ColumnElem is the definition of any columns defined in a table

func Column

func Column(name string, t TypeElem) ColumnElem

Column generates a ColumnElem given name and type

func (ColumnElem) Build

func (c ColumnElem) Build(dialect Dialect) (string, []interface{})

Build compiles the column element and returns sql, bindings It satisfies the Clause interface

func (ColumnElem) Eq

func (c ColumnElem) Eq(value interface{}) Conditional

Eq wraps the Eq(col ColumnElem, value interface{})

func (ColumnElem) Gt

func (c ColumnElem) Gt(value interface{}) Conditional

Gt wraps the Gt(col ColumnElem, value interface{})

func (ColumnElem) Gte

func (c ColumnElem) Gte(value interface{}) Conditional

Gte wraps the Gte(col ColumnElem, value interface{})

func (ColumnElem) In

func (c ColumnElem) In(values ...interface{}) Conditional

In wraps the In(col ColumnElem, values ...interface{})

func (ColumnElem) Like

func (c ColumnElem) Like(pattern string) Conditional

Like wraps the Like(col ColumnElem, pattern string)

func (ColumnElem) NotEq

func (c ColumnElem) NotEq(value interface{}) Conditional

NotEq wraps the NotEq(col ColumnElem, value interface{})

func (ColumnElem) NotIn

func (c ColumnElem) NotIn(values ...interface{}) Conditional

NotIn wraps the NotIn(col ColumnElem, values ...interface{})

func (ColumnElem) St

func (c ColumnElem) St(value interface{}) Conditional

St wraps the St(col ColumnElem, value interface{})

func (ColumnElem) Ste

func (c ColumnElem) Ste(value interface{}) Conditional

Ste wraps the Ste(col ColumnElem, value interface{})

func (ColumnElem) String

func (c ColumnElem) String(dialect Dialect) string

String returns the column element as an sql clause It satisfies the TableClause interface

type Compiles

type Compiles interface {
	// Build is the key function of any sql clause
	// It returns sql as string and bindings as []interface{}
	Build(dialect Dialect) (string, []interface{})
}

Compiles is the standard interface for any compilable sql clause Compiling means to post process any sql clauses if needed such as escaping, putting placeholders, etc.

type CompositeIndex

type CompositeIndex string

CompositeIndex is the struct definition when building composite indices for any struct that will be mapped into a table

type Conditional

type Conditional struct {
	Col    ColumnElem
	Values []interface{}
	Op     string
}

Conditional is the base struct for any conditional statements in sql clauses

func Condition

func Condition(col ColumnElem, op string, values ...interface{}) Conditional

Condition generates a condition object to use in update, delete & select statements

func Eq

func Eq(col ColumnElem, value interface{}) Conditional

Eq generates a equals conditional sql clause

func Gt

func Gt(col ColumnElem, value interface{}) Conditional

Gt generates a greater than conditional sql clause

func Gte

func Gte(col ColumnElem, value interface{}) Conditional

Gte generates a greater than or equal to conditional sql clause

func In

func In(col ColumnElem, values ...interface{}) Conditional

In generates an in conditional sql clause

func Like

func Like(col ColumnElem, pattern string) Conditional

Like generates a like conditional sql clause

func NotEq

func NotEq(col ColumnElem, value interface{}) Conditional

NotEq generates a not equal conditional sql clause

func NotIn

func NotIn(col ColumnElem, values ...interface{}) Conditional

NotIn generates a not in conditional sql clause

func St

func St(col ColumnElem, value interface{}) Conditional

St generates a smaller than conditional sql clause

func Ste

func Ste(col ColumnElem, value interface{}) Conditional

Ste generates a smaller than or equal to conditional sql clause

func (Conditional) Build

func (c Conditional) Build(dialect Dialect) (string, []interface{})

Build compiles the conditional element

type ConstraintElem

type ConstraintElem struct {
	Name string
}

ConstraintElem is the definition of column & table constraints

func Constraint

func Constraint(name string) ConstraintElem

Constraint generates a custom constraint due to variation of adapters

func Default

func Default(value interface{}) ConstraintElem

Default generates generic default constraint

func NotNull

func NotNull() ConstraintElem

NotNull generates generic not null constraint

func Null

func Null() ConstraintElem

Null generates generic null constraint

func Unique

func Unique() ConstraintElem

Unique generates generic unique constraint if cols are given, then composite unique constraint will be built

func (ConstraintElem) String

func (c ConstraintElem) String() string

String returns the constraint as an sql clause

type DefaultDialect

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

DefaultDialect is a type of dialect that can be used with unsupported sql drivers

func (*DefaultDialect) AutoIncrement

func (d *DefaultDialect) AutoIncrement() string

AutoIncrement generates auto increment sql of current dialect

func (*DefaultDialect) Driver

func (d *DefaultDialect) Driver() string

Driver returns the current driver of dialect

func (*DefaultDialect) Escape

func (d *DefaultDialect) Escape(str string) string

Escape wraps the string with escape characters of the dialect

func (*DefaultDialect) EscapeAll

func (d *DefaultDialect) EscapeAll(strings []string) []string

EscapeAll wraps all elements of string array

func (*DefaultDialect) Escaping

func (d *DefaultDialect) Escaping() bool

Escaping gets the escaping parameter of dialect

func (*DefaultDialect) Placeholder

func (d *DefaultDialect) Placeholder() string

Placeholder returns the placeholder for bindings in the sql

func (*DefaultDialect) Placeholders

func (d *DefaultDialect) Placeholders(values ...interface{}) []string

Placeholders returns the placeholders for bindings in the sql

func (*DefaultDialect) Reset

func (d *DefaultDialect) Reset()

Reset does nothing for the default driver

func (*DefaultDialect) SetEscaping

func (d *DefaultDialect) SetEscaping(escaping bool)

SetEscaping sets the escaping parameter of dialect

func (*DefaultDialect) SupportsUnsigned

func (d *DefaultDialect) SupportsUnsigned() bool

SupportsUnsigned returns whether driver supports unsigned type mappings or not

type DeleteStmt

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

DeleteStmt is the base struct for building delete queries

func Delete

func Delete(table TableElem) DeleteStmt

Delete generates a delete statement and returns it for chaining qb.Delete(usersTable).Where(qb.Eq("id", 5))

func (DeleteStmt) Build

func (s DeleteStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of DeleteStmt object

func (DeleteStmt) Returning

func (s DeleteStmt) Returning(cols ...ColumnElem) DeleteStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (DeleteStmt) Where

func (s DeleteStmt) Where(clause Clause) DeleteStmt

Where adds a where clause to the current delete statement

type Dialect

type Dialect interface {
	Escape(str string) string
	EscapeAll([]string) []string
	SetEscaping(escaping bool)
	Escaping() bool
	Placeholder() string
	Placeholders(values ...interface{}) []string
	AutoIncrement() string
	Reset()
	SupportsUnsigned() bool
	Driver() string
}

Dialect is the common adapter for driver changes It is for fixing compatibility issues of different drivers

func NewDialect

func NewDialect(driver string) Dialect

NewDialect returns a dialect pointer given driver

type Engine

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

Engine is the generic struct for handling db connections

func NewEngine

func NewEngine(driver string, dsn string) (*Engine, error)

NewEngine generates a new engine and returns it as an engine pointer

func (*Engine) DB

func (e *Engine) DB() *sqlx.DB

DB returns sql.DB of wrapped engine connection

func (*Engine) Driver

func (e *Engine) Driver() string

Driver returns the driver as string

func (*Engine) Dsn

func (e *Engine) Dsn() string

Dsn returns the connection dsn

func (*Engine) Exec

func (e *Engine) Exec(statement *Stmt) (sql.Result, error)

Exec executes insert & update type queries and returns sql.Result and error

func (*Engine) Get

func (e *Engine) Get(statement *Stmt, model interface{}) error

Get maps the single row to a model

func (*Engine) Ping

func (e *Engine) Ping() error

Ping pings the db using connection and returns error if connectivity is not present

func (*Engine) Query

func (e *Engine) Query(statement *Stmt) (*sql.Rows, error)

Query wraps *sql.DB.Query()

func (*Engine) QueryRow

func (e *Engine) QueryRow(statement *Stmt) *sql.Row

QueryRow wraps *sql.DB.QueryRow()

func (*Engine) Select

func (e *Engine) Select(statement *Stmt, model interface{}) error

Select maps multiple rows to a model array

type ForeignKeyConstraints

type ForeignKeyConstraints struct {
	Refs []Reference
}

ForeignKeyConstraints is the definition of foreign keys in any table

func ForeignKey

func ForeignKey() ForeignKeyConstraints

ForeignKey generates a foreign key for table constraint definitions

func (ForeignKeyConstraints) Ref

func (c ForeignKeyConstraints) Ref(col string, refTable string, refCol string) ForeignKeyConstraints

Ref generates a reference after the definition of foreign key by chaining

func (ForeignKeyConstraints) String

func (c ForeignKeyConstraints) String(adapter Dialect) string

type HavingClause

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

HavingClause is the base struct for generating having clauses when using select It satisfies Clause interface

func (HavingClause) Build

func (c HavingClause) Build(dialect Dialect) (string, []interface{})

Build generates having sql & bindings out of HavingClause struct

type IndexElem

type IndexElem struct {
	Table   string
	Name    string
	Columns []string
}

IndexElem is the definition of any index elements for a table

func Index

func Index(table string, cols ...string) IndexElem

Index generates an index clause given table and columns as params

func (IndexElem) String

func (i IndexElem) String(adapter Dialect) string

String returns the index element as an sql clause

type InsertStmt

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

InsertStmt is the base struct for any insert statements

func Insert

func Insert(table TableElem) InsertStmt

Insert generates an insert statement and returns it Insert(usersTable).Values(map[string]interface{}{"id": 1})

func (InsertStmt) Build

func (s InsertStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of InsertStmt object

func (InsertStmt) Returning

func (s InsertStmt) Returning(cols ...string) InsertStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (InsertStmt) Values

func (s InsertStmt) Values(vals map[string]interface{}) InsertStmt

Values accepts map[string]interface{} and forms the values map of insert statement

type JoinClause

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

JoinClause is the base struct for generating join clauses when using select It satisfies Clause interface

func (JoinClause) Build

func (c JoinClause) Build(dialect Dialect) (string, []interface{})

Build generates join sql & bindings out of JoinClause struct

type MapperElem

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

MapperElem is the generic struct for struct to table mapping

func Mapper

func Mapper(adapter Dialect) MapperElem

Mapper creates a new mapper struct and returns it as a mapper pointer

func (MapperElem) ModelName

func (m MapperElem) ModelName(model interface{}) string

ModelName returns the sql table name of model

func (MapperElem) ToMap

func (m MapperElem) ToMap(model interface{}, includeZeroFields bool) map[string]interface{}

ToMap converts a model struct to a map. Uninitialized fields are optionally ignored if includeZeroFields is true. Fields are renamed using qb conventions. db tag overrides column names

func (*MapperElem) ToTable

func (m *MapperElem) ToTable(model interface{}) (TableElem, error)

ToTable parses struct and converts it to a new table

func (*MapperElem) ToType

func (m *MapperElem) ToType(colType string, tagType string) TypeElem

ToType returns the type mapping of column. If tagType is, then colType would automatically be resolved. If tagType is not "", then automatic type resolving would be overridden by tagType

type MetaDataElem

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

MetaDataElem is the container for database structs and tables

func MetaData

func MetaData(dialect Dialect) *MetaDataElem

MetaData creates a new MetaData object and returns it as a pointer TODO: Metadata should not use builder, it should only use dialect

func (*MetaDataElem) Add

func (m *MetaDataElem) Add(model interface{})

Add retrieves the struct and converts it using mapper and appends to tables slice

func (*MetaDataElem) AddTable

func (m *MetaDataElem) AddTable(table TableElem)

AddTable appends table to tables slice

func (*MetaDataElem) CreateAll

func (m *MetaDataElem) CreateAll(engine *Engine) error

CreateAll creates all the tables added to metadata

func (*MetaDataElem) DropAll

func (m *MetaDataElem) DropAll(engine *Engine) error

DropAll drops all the tables which is added to metadata

func (*MetaDataElem) Table

func (m *MetaDataElem) Table(name string) TableElem

Table returns the metadata registered table object. It returns nil if table is not found

func (*MetaDataElem) Tables

func (m *MetaDataElem) Tables() []TableElem

Tables returns the current tables slice

type MysqlDialect

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

MysqlDialect is a type of dialect that can be used with mysql driver

func (*MysqlDialect) AutoIncrement

func (d *MysqlDialect) AutoIncrement() string

AutoIncrement generates auto increment sql of current dialect

func (*MysqlDialect) Driver

func (d *MysqlDialect) Driver() string

Driver returns the current driver of dialect

func (*MysqlDialect) Escape

func (d *MysqlDialect) Escape(str string) string

Escape wraps the string with escape characters of the dialect

func (*MysqlDialect) EscapeAll

func (d *MysqlDialect) EscapeAll(strings []string) []string

EscapeAll wraps all elements of string array

func (*MysqlDialect) Escaping

func (d *MysqlDialect) Escaping() bool

Escaping gets the escaping parameter of dialect

func (*MysqlDialect) Placeholder

func (d *MysqlDialect) Placeholder() string

Placeholder returns the placeholder for bindings in the sql

func (*MysqlDialect) Placeholders

func (d *MysqlDialect) Placeholders(values ...interface{}) []string

Placeholders returns the placeholders for bindings in the sql

func (*MysqlDialect) Reset

func (d *MysqlDialect) Reset()

Reset does nothing for the default driver

func (*MysqlDialect) SetEscaping

func (d *MysqlDialect) SetEscaping(escaping bool)

SetEscaping sets the escaping parameter of dialect

func (*MysqlDialect) SupportsUnsigned

func (d *MysqlDialect) SupportsUnsigned() bool

SupportsUnsigned returns whether driver supports unsigned type mappings or not

type OrClause

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

OrClause is the base struct to keep or within the where clause It satisfies the Clause interface

func Or

func Or(conditions ...Conditional) OrClause

Or generates an OrClause given conditional clauses

func (OrClause) Build

func (c OrClause) Build(dialect Dialect) (string, []interface{})

Build compiles the or clause, joins the sql, returns sql and bindings

type OrderByClause

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

OrderByClause is the base struct for generating order by clauses when using select It satisfies Clause interface

func (OrderByClause) Build

func (c OrderByClause) Build(dialect Dialect) (string, []interface{})

Build generates an order by clause

type PostgresDialect

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

PostgresDialect is a type of dialect that can be used with postgres driver

func (*PostgresDialect) AutoIncrement

func (d *PostgresDialect) AutoIncrement() string

AutoIncrement generates auto increment sql of current dialect

func (*PostgresDialect) Driver

func (d *PostgresDialect) Driver() string

Driver returns the current driver of dialect

func (*PostgresDialect) Escape

func (d *PostgresDialect) Escape(str string) string

Escape wraps the string with escape characters of the dialect

func (*PostgresDialect) EscapeAll

func (d *PostgresDialect) EscapeAll(strings []string) []string

EscapeAll wraps all elements of string array

func (*PostgresDialect) Escaping

func (d *PostgresDialect) Escaping() bool

Escaping gets the escaping parameter of dialect

func (*PostgresDialect) Placeholder

func (d *PostgresDialect) Placeholder() string

Placeholder returns the placeholder for bindings in the sql

func (*PostgresDialect) Placeholders

func (d *PostgresDialect) Placeholders(values ...interface{}) []string

Placeholders returns the placeholders for bindings in the sql

func (*PostgresDialect) Reset

func (d *PostgresDialect) Reset()

Reset clears the binding index for postgres driver

func (*PostgresDialect) SetEscaping

func (d *PostgresDialect) SetEscaping(escaping bool)

SetEscaping sets the escaping parameter of dialect

func (*PostgresDialect) SupportsUnsigned

func (d *PostgresDialect) SupportsUnsigned() bool

SupportsUnsigned returns whether driver supports unsigned type mappings or not

type PrimaryKeyConstraint

type PrimaryKeyConstraint struct {
	Columns []string
}

PrimaryKeyConstraint is the definition of primary key constraints of any table

func PrimaryKey

func PrimaryKey(cols ...string) PrimaryKeyConstraint

PrimaryKey generates a primary key constraint of any table

func (PrimaryKeyConstraint) String

func (c PrimaryKeyConstraint) String(dialect Dialect) string

String returns the primary key constraints as an sql clause

type Reference

type Reference struct {
	Cols     []string
	RefTable string
	RefCols  []string
}

Reference is the main struct for defining foreign key references

type SelectStmt

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

SelectStmt is the base struct for building select statements

func Select

func Select(clauses ...Clause) SelectStmt

Select generates a select statement and returns it

func (SelectStmt) Asc

func (s SelectStmt) Asc() SelectStmt

Asc sets the t type of current order by clause NOTE: Please use it after calling OrderBy()

func (SelectStmt) Build

func (s SelectStmt) Build(dialect Dialect) *Stmt

Build compiles the select statement and returns the Stmt

func (SelectStmt) CrossJoin

func (s SelectStmt) CrossJoin(table TableElem) SelectStmt

CrossJoin appends an cross join clause to the select statement

func (SelectStmt) Desc

func (s SelectStmt) Desc() SelectStmt

Desc sets the t type of current order by clause NOTE: Please use it after calling OrderBy()

func (SelectStmt) From

func (s SelectStmt) From(table TableElem) SelectStmt

From sets the from table of select statement

func (SelectStmt) GroupBy

func (s SelectStmt) GroupBy(cols ...ColumnElem) SelectStmt

GroupBy appends columns to group by clause of the select statement

func (SelectStmt) Having

func (s SelectStmt) Having(aggregate AggregateClause, op string, value interface{}) SelectStmt

Having appends a having clause to select statement

func (SelectStmt) InnerJoin

func (s SelectStmt) InnerJoin(table TableElem, fromCol ColumnElem, col ColumnElem) SelectStmt

InnerJoin appends an inner join clause to the select statement

func (SelectStmt) LeftJoin

func (s SelectStmt) LeftJoin(table TableElem, fromCol ColumnElem, col ColumnElem) SelectStmt

LeftJoin appends an left outer join clause to the select statement

func (SelectStmt) Limit

func (s SelectStmt) Limit(offset int, count int) SelectStmt

Limit sets the offset & count values of the select statement

func (SelectStmt) OrderBy

func (s SelectStmt) OrderBy(columns ...ColumnElem) SelectStmt

OrderBy generates an OrderByClause and sets select statement's orderbyclause OrderBy(usersTable.C("id")).Asc() OrderBy(usersTable.C("email")).Desc()

func (SelectStmt) RightJoin

func (s SelectStmt) RightJoin(table TableElem, fromCol ColumnElem, col ColumnElem) SelectStmt

RightJoin appends a right outer join clause to select statement

func (SelectStmt) Where

func (s SelectStmt) Where(clause Clause) SelectStmt

Where sets the where clause of select statement

type Session

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

Session is the composition of engine connection & orm mappings

func New

func New(driver string, dsn string) (*Session, error)

New generates a new Session given engine and returns session pointer

func (*Session) Add

func (s *Session) Add(model interface{})

Add adds a single model to the session. The query must be insert or update

func (*Session) AddAll

func (s *Session) AddAll(models ...interface{})

AddAll adds multiple models an adds an insert statement to current queries

func (*Session) AddStatement

func (s *Session) AddStatement(statement *Stmt)

AddStatement adds a statement given the query pointer retrieved from Build() function

func (*Session) AddTable

func (s *Session) AddTable(model interface{})

AddTable adds a model to metadata that is mapped into table object

func (*Session) All

func (s *Session) All(models interface{}) error

All returns all the records mapped as a model slice The interface should be struct pointer instead of struct

func (*Session) Asc

func (s *Session) Asc() *Session

Asc wraps the select's Asc

func (*Session) Close

func (s *Session) Close()

Close closes engine db (sqlx) connection

func (*Session) Commit

func (s *Session) Commit() error

Commit commits the current transaction with queries

func (*Session) CreateAll

func (s *Session) CreateAll() error

CreateAll creates all tables that are registered to metadata

func (*Session) CrossJoin

func (s *Session) CrossJoin(table TableElem) *Session

CrossJoin wraps select's CrossJoin

func (*Session) Delete

func (s *Session) Delete(model interface{})

Delete adds a single delete statement to the session

func (*Session) Desc

func (s *Session) Desc() *Session

Desc wraps the select's Desc

func (*Session) Dialect

func (s *Session) Dialect() Dialect

Dialect returns the current dialect of session

func (*Session) DropAll

func (s *Session) DropAll() error

DropAll drops all tables that are registered to metadata

func (*Session) Engine

func (s *Session) Engine() *Engine

Engine returns the current sqlx wrapped engine

func (*Session) Filter

func (s *Session) Filter(conditional Conditional) *Session

Filter appends a filter to the current select statement NOTE: It currently only builds AndClause within the filters TODO: Add OR able filters

func (*Session) Find

func (s *Session) Find(model interface{}) *Session

Find returns a row given model properties

func (*Session) From

func (s *Session) From(table TableElem) *Session

From wraps select's From NOTE: You only need to set if Query() parameters are not columns No columns are in aggregate clauses

func (*Session) GroupBy

func (s *Session) GroupBy(cols ...ColumnElem) *Session

GroupBy wraps the select's GroupBy

func (*Session) Having

func (s *Session) Having(aggregate AggregateClause, op string, value interface{}) *Session

Having wraps the select's Having

func (*Session) InnerJoin

func (s *Session) InnerJoin(table TableElem, fromCol ColumnElem, col ColumnElem) *Session

InnerJoin wraps select's InnerJoin

func (*Session) LeftJoin

func (s *Session) LeftJoin(table TableElem, fromCol ColumnElem, col ColumnElem) *Session

LeftJoin wraps select's LeftJoin

func (*Session) Limit

func (s *Session) Limit(offset int, count int) *Session

Limit wraps the select's Limit

func (*Session) Metadata

func (s *Session) Metadata() *MetaDataElem

Metadata returns the metadata of session

func (*Session) One

func (s *Session) One(model interface{}) error

One returns the first record mapped as a model The interface should be struct pointer instead of struct

func (*Session) OrderBy

func (s *Session) OrderBy(cols ...ColumnElem) *Session

OrderBy wraps the select's OrderBy

func (*Session) Query

func (s *Session) Query(clauses ...Clause) *Session

Query starts a select statement given columns

func (*Session) RightJoin

func (s *Session) RightJoin(table TableElem, fromCol ColumnElem, col ColumnElem) *Session

RightJoin wraps select's RightJoin

func (*Session) Rollback

func (s *Session) Rollback() error

Rollback rollbacks the current transaction

func (*Session) Statement

func (s *Session) Statement() *Stmt

Statement builds the active query and returns it as a Stmt

func (*Session) T

func (s *Session) T(name string) TableElem

T returns the table given name as string It is for Query() function parameter generation

type SqliteDialect

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

SqliteDialect is a type of dialect that can be used with sqlite driver

func (*SqliteDialect) AutoIncrement

func (d *SqliteDialect) AutoIncrement() string

AutoIncrement generates auto increment sql of current dialect

func (*SqliteDialect) Driver

func (d *SqliteDialect) Driver() string

Driver returns the current driver of dialect

func (*SqliteDialect) Escape

func (d *SqliteDialect) Escape(str string) string

Escape wraps the string with escape characters of the dialect

func (*SqliteDialect) EscapeAll

func (d *SqliteDialect) EscapeAll(strings []string) []string

EscapeAll wraps all elements of string array

func (*SqliteDialect) Escaping

func (d *SqliteDialect) Escaping() bool

Escaping gets the escaping parameter of dialect

func (*SqliteDialect) Placeholder

func (d *SqliteDialect) Placeholder() string

Placeholder returns the placeholder for bindings in the sql

func (*SqliteDialect) Placeholders

func (d *SqliteDialect) Placeholders(values ...interface{}) []string

Placeholders returns the placeholders for bindings in the sql

func (*SqliteDialect) Reset

func (d *SqliteDialect) Reset()

Reset does nothing for the default driver

func (*SqliteDialect) SetEscaping

func (d *SqliteDialect) SetEscaping(escaping bool)

SetEscaping sets the escaping parameter of dialect

func (*SqliteDialect) SupportsUnsigned

func (d *SqliteDialect) SupportsUnsigned() bool

SupportsUnsigned returns whether driver supports unsigned type mappings or not

type Stmt

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

Stmt is the base abstraction for all sql queries

func Statement

func Statement() *Stmt

Statement creates a new query and returns its pointer

func (*Stmt) AddBinding

func (s *Stmt) AddBinding(bindings ...interface{})

AddBinding appends a new binding to current query

func (*Stmt) AddClause

func (s *Stmt) AddClause(clause string)

AddClause appends a new clause to current query

func (*Stmt) Bindings

func (s *Stmt) Bindings() []interface{}

Bindings returns all bindings of current query

func (*Stmt) Clauses

func (s *Stmt) Clauses() []string

Clauses returns all clauses of current query

func (*Stmt) SQL

func (s *Stmt) SQL() string

SQL returns the query struct sql statement

func (*Stmt) SetDelimiter

func (s *Stmt) SetDelimiter(delimiter string)

SetDelimiter sets the delimiter of query

type TableClause

type TableClause interface {
	// String takes the dialect and returns the ddl as an sql string
	String(dialect Dialect) string
}

TableClause is the common interface for ddl generators such as Column(), PrimaryKey(), ForeignKey().Ref(), etc.

type TableElem

type TableElem struct {
	Name                  string
	Columns               map[string]ColumnElem
	PrimaryKeyConstraint  PrimaryKeyConstraint
	ForeignKeyConstraints ForeignKeyConstraints
	UniqueKeyConstraint   UniqueKeyConstraint
	Indices               []IndexElem
}

TableElem is the definition of any sql table

func Table

func Table(name string, clauses ...TableClause) TableElem

Table generates table struct given name and clauses

func (TableElem) All

func (t TableElem) All() []Clause

All returns all columns of table as a column slice

func (TableElem) C

func (t TableElem) C(name string) ColumnElem

C returns the column name given col

func (TableElem) Create

func (t TableElem) Create(adapter Dialect) string

Create generates create table syntax and returns it as a query struct

func (TableElem) Drop

func (t TableElem) Drop(adapter Dialect) string

Drop generates drop table syntax and returns it as a query struct

func (TableElem) Index

func (t TableElem) Index(cols ...string) TableElem

Index appends an IndexElem to current table without giving table name

func (TableElem) PrimaryCols

func (t TableElem) PrimaryCols() []ColumnElem

PrimaryCols returns the columns that are primary key to the table

type Tag

type Tag struct {
	// contains default, null, notnull, unique, primary_key, foreign_key(table.column), check(condition > 0)
	Constraints []string

	// contains type(size) or type parameters
	Type string

	// true if it is ignored
	Ignore bool
}

Tag is the base abstraction of qb tag

func ParseTag

func ParseTag(rawTag string) (Tag, error)

ParseTag parses raw qb tag and builds a Tag object

type TypeElem

type TypeElem struct {
	Name string
	// contains filtered or unexported fields
}

TypeElem is the struct for defining column types

func BigInt

func BigInt() TypeElem

BigInt creates bigint type

func Boolean

func Boolean() TypeElem

Boolean creates boolean type

func Char

func Char() TypeElem

Char creates char type

func Decimal

func Decimal() TypeElem

Decimal creates a decimal type

func Float

func Float() TypeElem

Float creates float type

func Int

func Int() TypeElem

Int creates int type

func Numeric

func Numeric() TypeElem

Numeric creates a numeric type

func SmallInt

func SmallInt() TypeElem

SmallInt creates smallint type

func Text

func Text() TypeElem

Text creates text type

func Timestamp

func Timestamp() TypeElem

Timestamp creates timestamp type

func Type

func Type(name string) TypeElem

Type returns a new TypeElem while defining columns in table

func Varchar

func Varchar() TypeElem

Varchar creates varchar type

func (TypeElem) Constraint

func (t TypeElem) Constraint(name string) TypeElem

Constraint adds a custom constraint to column type

func (TypeElem) Default

func (t TypeElem) Default(def interface{}) TypeElem

Default adds a default constraint to column type

func (TypeElem) NotNull

func (t TypeElem) NotNull() TypeElem

NotNull adds not null constraint to column type

func (TypeElem) Null

func (t TypeElem) Null() TypeElem

Null adds null constraint to column type

func (TypeElem) Precision

func (t TypeElem) Precision(p int, s int) TypeElem

Precision sets the precision of column type Note: Use it in Float, Decimal and Numeric types

func (TypeElem) Size

func (t TypeElem) Size(size int) TypeElem

Size adds size constraint to column type

func (TypeElem) String

func (t TypeElem) String() string

String returns the clause as string

func (TypeElem) Unique

func (t TypeElem) Unique() TypeElem

Unique adds a unique constraint to column type

type UniqueKeyConstraint

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

UniqueKeyConstraint is the base struct to define composite unique indexes of tables

func UniqueKey

func UniqueKey(cols ...string) UniqueKeyConstraint

UniqueKey generates UniqueKeyConstraint given columns as strings

func (UniqueKeyConstraint) String

func (c UniqueKeyConstraint) String(dialect Dialect) string

String generates composite unique indices as sql clause

type UpdateStmt

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

UpdateStmt is the base struct for any update statements

func Update

func Update(table TableElem) UpdateStmt

Update generates an update statement and returns it qb.Update(usersTable). Values(map[string]interface{}{"id": 1}). Where(qb.Eq("id", 5))

func (UpdateStmt) Build

func (s UpdateStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of UpdateStmt object

func (UpdateStmt) Returning

func (s UpdateStmt) Returning(cols ...string) UpdateStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (UpdateStmt) Values

func (s UpdateStmt) Values(values map[string]interface{}) UpdateStmt

Values accepts map[string]interface{} and forms the values map of insert statement

func (UpdateStmt) Where

func (s UpdateStmt) Where(clause Clause) UpdateStmt

Where adds a where clause to update statement and returns the update statement

type UpsertStmt

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

UpsertStmt is the base struct for any insert ... on conflict/duplicate key ... update ... statements

func Upsert

func Upsert(table TableElem) UpsertStmt

Upsert generates an insert ... on (duplicate key/conflict) update statement

func (UpsertStmt) Build

func (s UpsertStmt) Build(dialect Dialect) *Stmt

Build generates a statement out of UpdateStmt object NOTE: It generates different statements for each driver For sqlite, it generates REPLACE INTO ... VALUES ... For mysql, it generates INSERT INTO ... VALUES ... ON DUPLICATE KEY UPDATE ... For postgres, it generates INSERT INTO ... VALUES ... ON CONFLICT(...) DO UPDATE SET ...

func (UpsertStmt) Returning

func (s UpsertStmt) Returning(cols ...string) UpsertStmt

Returning accepts the column names as strings and forms the returning array of insert statement NOTE: Please use it in only postgres dialect, otherwise it'll crash

func (UpsertStmt) Values

func (s UpsertStmt) Values(vals map[string]interface{}) UpsertStmt

Values accepts map[string]interface{} and forms the values map of insert statement

type WhereClause

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

WhereClause is the base of any where clause when using expression api

func Where

func Where(clause Clause) WhereClause

Where generates a compilable where clause

func (WhereClause) Build

func (c WhereClause) Build(dialect Dialect) (string, []interface{})

Build compiles the where clause, returns sql and bindings

Jump to

Keyboard shortcuts

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