db

package
v0.1.1-beta.2 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2023 License: MIT Imports: 13 Imported by: 1

Documentation

Overview

Author xc, Created on 2019-04-07 20:36 {COPYRIGHTS}

Package db provides database operation and query building api.

Author xc, Created on 2019-04-01 22:00 {COPYRIGHTS}

Index

Examples

Constants

This section is empty.

Variables

View Source
var Operators = []string{">", ">=", "<", "==", "<=", "!=", "=", "in", "like"} // Note: == is for join. todo: make it extendable in loading

Functions

func BindContent

func BindContent(ctx context.Context, entity interface{}, targets string, condition Condition) (int, error)

Bind content with a simple syntax, support innner join todo: might be better in another package since it better involves content model?

Example
content := []struct {
	Title string `boil:"title"`
}{}
//In real case for list, it should be list = contenttype.NewList("folder")
//In real case for content it should be content = contenttype.New("folder")
BindContent(context.Background(), &content, "folder", TrueCond())
Output:

func BindContentWithQuery

func BindContentWithQuery(ctx context.Context, entity interface{}, contentType string, query Query, option ContentOption) (int, error)

Bind content with query

func BindEntity

func BindEntity(ctx context.Context, entity interface{}, targets string, condition Condition) (int, error)

Bind entity

Example
//Fetch all orders into a struct list
orderlist := []struct {
	ID   string `boil:"id"`
	Name string `boil:"name"`
}{}
BindEntity(context.Background(), &orderlist, "demo_order", Cond("author", 5).Limit(0, 10))

//Fetch all orders to a map list
datalist := DatamapList{}
BindEntity(context.Background(), &datalist, "demo_order", TrueCond())
fmt.Print(len(datalist) > 0)

//Fetch one order to a map list
order := DatamapList{}
BindEntity(context.Background(), &order, "demo_order", Cond("id>", 1))
fmt.Print(len(order) > 0)
Output:

truetrue

func BindEntityWithQuery

func BindEntityWithQuery(ctx context.Context, entity interface{}, query Query) (int, error)

Bind entity with Query. The simpest is to use BindContent/BindEntity which is using condition directly. Condition is syntax(use function to create) easier than query(struct creating) If limit is <number>,0 it will ignore entity, and only count If limit is <number larger than 0>(eg. 5), <number> it will ignore count unless AlwaysCount is true

func BuildCondition

func BuildCondition(cond Condition, locationColumns ...[]string) (string, []interface{})

todo: optimize - use pointers & avoid string +

func Count

func Count(targets string, condition Condition, ctx ...context.Context) (int, error)

Count entities

Example
//Count all orders
count, _ := Count("order", TrueCond())
fmt.Println(count > 0)
Output:

true

func CountContent

func CountContent(ctx context.Context, targets string, condition Condition) (int, error)

Count content separately

func CreateTx

func CreateTx(ctx ...context.Context) (*sql.Tx, error)

Create transaction. todo: maybe some pararmeters for options

func DB

func DB() (*sql.DB, error)

Get DB connection cached globally Note: when using it, the related driver should be imported already

func Delete

func Delete(ctx context.Context, tablename string, condition Condition, transation ...*sql.Tx) error

Delete record. It only invokes "<DBHandler>.Delete"

Example
values := map[string]interface{}{
	"name": "Order"}
id, _ := Insert(context.Background(), "demo_order", values)

//Delete the inserted one
Delete(context.Background(), "demo_order", Cond("id", id))

count, _ := Count("demo_order", Cond("id", id))
fmt.Println(count)
Output:

0

func Insert

func Insert(ctx context.Context, tablename string, values map[string]interface{}, transation ...*sql.Tx) (int, error)

Insert record, return id created(if it has). It only invokes "<DBHandler>.Insert"

Example
values := map[string]interface{}{
	"name":        "Test",
	"description": "Test1"}

//Insert without transaction.
result, _ := Insert(context.Background(), "demo_order", values)

fmt.Println(result > 0)
Output:

true
Example (WithTransaction)
values := map[string]interface{}{
	"name":        "Test",
	"description": "Test2"}

database, _ := DB()
tx, _ := database.Begin()

//Insert with transation
result, err := Insert(context.Background(), "demo_order", values)
tx.Commit()

if err != nil {
	tx.Rollback()
}
fmt.Println(result > 0)
Output:

true

func IsEmptyCond

func IsEmptyCond(cond Condition) bool

func RegisterHandler

func RegisterHandler(dbHandler DBHandler)

func Update

func Update(ctx context.Context, tablename string, values map[string]interface{}, condition Condition, transation ...*sql.Tx) error

Update record. It only invokes "<DBHandler>.Update"

Example
//Update only name
values := map[string]interface{}{
	"name": "Order updated"}
Update(context.Background(), "demo_order", values, Cond("id", 1))

//fetch updated
order := struct {
	Name string `boil:"name"`
}{}
BindEntity(context.Background(), &order, "demo_order", Cond("id", 1))
fmt.Println(order.Name)
Output:

Order updated

Types

type Condition

type Condition struct {
	Logic    string
	Children interface{}     //can be []Condition or Expression(when it's the leaf) (eg. and( and( A, B ), C )
	Option   ConditionOption //Only used by top condition for building condition, then pass to Query
}

Condition is a self contained query condition

func Cond

func Cond(field string, value interface{}) Condition

Cond creates condition like Cond("id", 1), or Cond("id", []int{1,2}) or Cond("id>", 10)

Example
//cond
cond := Cond("id>", 10)

output, _ := BuildCondition(cond)
fmt.Println(output)
Output:

id > ?
Example (AndCondition)
cond := Cond(" modified  > ", 22222222)
cond2 := Cond("published >", 3333333)

//and
andCond := cond.And(cond2)

output, _ := BuildCondition(andCond)
fmt.Println(output)
Output:

(modified > ? AND published > ?)
Example (AndExpression)
cond := Cond("modified >", 22222)

//and
andCond := cond.And("published >", 3333333) //Here is the same as cond.And( db.Cond( "published >", 3333333 ) )

output, _ := BuildCondition(andCond)
fmt.Println(output)
Output:

(modified > ? AND published > ?)
Example (MulitiCond)
cond := Cond("modified >", 22222)

//Here Cond() is the same as And()
andCond := cond.Cond("published >", 3333333)

output, _ := BuildCondition(andCond)
fmt.Println(output)
Output:

(modified > ? AND published > ?)
Example (Or)
cond := Cond(" modified  > ", 22222222)
cond2 := Cond("published >", 3333333)

//or
orCond := cond.Or(cond2)

output, _ := BuildCondition(orCond)
fmt.Println(output)
Output:

(modified > ? OR published > ?)
Example (OrAnd)
cond := Cond(" modified  > ", 22222222)
cond2 := Cond("published >", 3333333)

//or then and
orCond := cond.Or(cond2).And("id>", 1)

output, _ := BuildCondition(orCond)
fmt.Println(output)
Output:

((modified > ? OR published > ?) AND id > ?)

func EmptyCond

func EmptyCond() Condition

EmptyCond creates a empty condition without expression or value

Example
cond := EmptyCond().Cond("author", "1")
built, _ := BuildCondition(cond)
fmt.Println(built)
Output:

author = ?

func FalseCond

func FalseCond() Condition

func TrueCond

func TrueCond() Condition

func (Condition) And

func (c Condition) And(input interface{}, more ...interface{}) Condition

And accepts <cond>.And( <cond1>, <cond2> ), also <cond>.And( "id<", 2200 ) (same as <cond>.And( Cond( "id<", 2200 ) ))

func (Condition) Cond

func (c Condition) Cond(field string, value interface{}) Condition

Cond is same as And(<field>, <value>) or And( Cond( <field>, <value> ) )

func (Condition) Limit

func (c Condition) Limit(offset int, number int) Condition

Limit sets limit rule. Note: Limit(<x>, 0) has special meaning: count only.

func (Condition) Or

func (c Condition) Or(input interface{}, more ...interface{}) Condition

Or accepts <cond>.Or( <cond1>, <cond2> ), also <cond>.Or( "id=", 2 ). Similar to And

func (Condition) Sortby

func (c Condition) Sortby(sortby ...string) Condition

Sortby sets sort rules where each string is a rule separated by space. eg. Sortby( "author asc", "modified desc" )

func (Condition) WithCount

func (c Condition) WithCount() Condition

type ConditionOption

type ConditionOption struct {
	Sortby      []string
	LimitArr    []int
	AlwaysCount bool
}

type ContentOption

type ContentOption struct {
	WithAuthor       bool
	WithRelation     []string //relation field
	WithRelationlist []string //relationlist field
}

type DBEntitier

type DBEntitier interface {
	GetByID(contentType string, id int) interface{}
}

type DBHandler

type DBHandler interface {
	WithContent(query Query, contentType string, option ContentOption) (Query, error)

	BuildQuery(querier Query, count bool) (string, []interface{}, error)

	GetColumns(table string) []string

	Insert(ctx context.Context, tablename string, values map[string]interface{}, transation ...*sql.Tx) (int, error)
	Update(ctx context.Context, tablename string, values map[string]interface{}, condition Condition, transation ...*sql.Tx) error
	Delete(ctx context.Context, tableName string, condition Condition, transation ...*sql.Tx) error
}

type Datamap

type Datamap map[string]interface{}

type DatamapList

type DatamapList []Datamap

type Expression

type Expression struct {
	Field    string
	Operator string
	Value    interface{}
}

Expression is a 'leaf' condition

type MysqlHandler

type MysqlHandler struct {
}

Implement DBEntitier

func (MysqlHandler) BuildQuery

func (handler MysqlHandler) BuildQuery(query Query, count bool) (string, []interface{}, error)

Implement BuildQuery

func (MysqlHandler) Delete

func (MysqlHandler) Delete(ctx context.Context, tableName string, condition Condition, transation ...*sql.Tx) error

Delete based on condition

func (MysqlHandler) GetColumns

func (handler MysqlHandler) GetColumns(table string) []string

get table columns with Cache

func (MysqlHandler) Insert

func (MysqlHandler) Insert(ctx context.Context, tablename string, values map[string]interface{}, transation ...*sql.Tx) (int, error)

func (MysqlHandler) Update

func (MysqlHandler) Update(ctx context.Context, tablename string, values map[string]interface{}, condition Condition, transation ...*sql.Tx) error

Generic update an entity

func (MysqlHandler) WithContent

func (handler MysqlHandler) WithContent(query Query, contentType string, option ContentOption) (Query, error)

type Query

type Query struct {
	Queries     []SingleQuery
	Groupby     []string //group by
	LimitArr    []int
	LeftQueries []SingleQuery
	SortArr     []string
	AlwaysCount bool
}

func CreateQuery

func CreateQuery(targets string, condition Condition) (string, Query)

Build query from a condition. Returns the first target and a Query instance

func (*Query) Add

func (q *Query) Add(added SingleQuery)

Add a query

func (*Query) AddLeft

func (q *Query) AddLeft(query SingleQuery)

func (*Query) Join

func (q *Query) Join(name string, condition Condition, joinCondition Condition) Query

Join a content or table

func (*Query) Limit

func (q *Query) Limit(offset int, limit int) Query

Limit

func (*Query) Sortby

func (q *Query) Sortby(sortby ...string) Query

sort by

type SingleQuery

type SingleQuery struct {
	Table     string
	Alias     string
	Select    []string
	Condition Condition
	Relation  Condition
}

Jump to

Keyboard shortcuts

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