gosql

package module
v0.0.0-...-9eeaa5e Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2020 License: MIT Imports: 13 Imported by: 0

README

本仓库不在更新,请使用新仓库: https://github.com/rushteam/gosql

gosql

A golang ORM

gosql 是一个数据库的golang库

Why build this wheels

几乎是翻遍github上所有开源的使用golang实现的操作数据库类)使用起来总有不顺手的地方,例如:

gorm不支持读写分离,关联表使用频率少

gendry 是didi开源的一款,比较简洁但部分语法怪异 如group by 和 limit 依赖字段的约定

sqlx 相比起来不错,但语法不够简洁,不支持读写分离,

gosql 目前仅支持mysql (关键是`符号的处理,以及一些特殊语法,后期可能会考虑兼容pgsql等

本数据库参阅了大量现有数据库架构,参阅各种文献,自定义语法习惯,从零实现

其中灵感来自:分模块的灵感来自gendry,标签读取部分参考gorm,拼装sql的语法来自于我之前写的php的操作db库

Structure 结构

  • db.go: defined base struct define 基本结构定义
  • pool.go: db manger 管理db
  • session.go: session and maping to model 会话和模型
  • builder.go: for building SQL 构建sql
  • scanner/*: mapping struct and scan 映射模型

Feature 功能

  • Versatile 功能多样的
  • Unlimited nesting query 查询条件无限嵌套
  • Reading and Writing Separation 读写分离

Builder of DEMO 例子

为了展示gosql的能力,先展示个例子: Let's look a demo:

SELECT DISTINCT * FROM `tbl1`.`t1` JOIN `tbl3` ON `a` = `b`
WHERE (`t1`.`status` = ?
  AND `type` = ?
  AND `sts` IN (?, ?, ?, ?)
  AND `sts2` IN (?)
  AND (`a` = ? AND `b` = ?)
  AND aaa = 999
  AND ccc = ?
  AND `a` LIKE ? AND EXISTS (SELECT 1)
  AND EXISTS (SELECT * FROM `tbl2`.`t2` WHERE `xx` = ?)
) GROUP BY `id` HAVING `ss` = ? ORDER BY `id desc`, `id asc` LIMIT 10, 30
FOR UPDATE
    s := builder.New()
    s.Flag("DISTINCT")
    s.Field("*")
    s.Table("tbl1.t1")
    s.Where("t1.status", "0")
    s.Where("type", "A")
    s.Where("[in]sts", []string{"1", "2", "3", "4"})
    s.Where("[in]sts2", 1)
    s.Where(func(s *builder.Clause) {
        s.Where("a", "200")
        s.Where("b", "100")
    })
    s.Where("aaa = 999")
    s.Where("[#]ccc = ?", 888)
    s.Join("tbl3", "a", "=", "b")
    s.Having("ss", "1")
    s.Where("[~]a", "AA")
    s.Where("[exists]", "select 1")
    s.Where("[exists]", func(s *builder.SQLSegments) {
        s.Table("tbl2.t2")
        s.Where("xx", 10000)
    })
    s.GroupBy("id")
    s.OrderBy("id desc", "id asc")
    s.Limit(30)
    s.Offset(10)
    s.ForUpdate()
    fmt.Println(s.BuildSelect())

How to use 如何使用

  1. Init db
db,err := gosql.NewCluster(
    gosql.AddDb("mysql","user:pasword@tcp(127.0.0.1:3306)/test?parseTime=true&readTimeout=3s&writeTimeout=3s&timeout=3s"),
)
if err != nil {
    fmt.Println(err)
}

Doc 文档

Auto

Exec

INSERT: db.Insert(dst interface{}, opts ...Option) (Result, error)
type UserModel struct{
    ID int `db:"id"`
    Name string ``
}
func (u *UserModel) TableName() {
    return "my_world"
}
user := &WorldModel{}
user.Name = "jack"
ret,err := db.Insert(&user)

REPALCE: db.Replace(dst interface{}, opts ...Option) (Result, error)
type UserModel struct{
    ID int `db:"id"`
    Name string ``
}
func (u *UserModel) TableName() {
    return "my_world"
}
user := &WorldModel{}
user.Name = "jack"
ret,err := db.Replace(&user,gosql.Where("id",1))

UPDATE: Update(dst interface{}, opts ...Option) (Result, error)
type UserModel struct{
    ID int `db:"id"`
    Name string ``
}
func (u *UserModel) TableName() {
    return "my_world"
}
user := &WorldModel{}
user.Name = "jack Ma"
ret,err := db.Update(&user,gosql.Where("id",1))

DELETE: db.Delete(dst interface{}, opts ...Option) (Result, error)
type UserModel struct{
    ID int `db:"id"`
    Name string ``
}
func (u *UserModel) TableName() {
    return "my_world"
}
user := &WorldModel{}
ret,err := db.Delete(&user,gosql.Where("id",1))
//sql: delete from my_world where id = 1

QUERY

Get a record: db.Fetch(dst interface{}, opts ...Option) error
Get multiple records: db.FetchAll(dst interface{}, opts ...Option) error

OPTION

WHERE
gosql.Where("id",1)

eq sql:

id = 1
gosql.Where("age[>]",18)

eq sql:

age > 18
gosql.Where("id[in]",[]int{1,2})

eq sql:

id in (1,2)
gosql.Where("id[!in]",[]int{1,2})

eq sql:

id not in (1,2)
gosql.Where("name[~]","ja%")

eq sql:

name like 'ja%'
gosql.Where("name[!~]","ja%")

eq sql:

name not like 'ja%'
条件表达式 [?]
[=] equal
gosql.Where("[=]id",1)
//sql: id = 1
[!=] not equal
gosql.Where("[!=]id",1)
//sql: id != 1
[>] greater than
gosql.Where("[>]id",1)
//sql: id > 1
[>=] greater or equal
gosql.Where("[>=]id",1)
//sql: id >= 1
[<] less
gosql.Where("[<]id",1)
//sql: id < 1
[<=] less or equal
gosql.Where("[<=]id",1)
//sql: id <= 1
[in] in
gosql.Where("[in]id",[]int{1,2})
//sql: id in (1,2)
[!in] not in
gosql.Where("[!in]id",[]int{1,2})
//sql: id not in (1,2)
[is] is
gosql.Where("[is]name",nil)
//sql: name is null
[!is] not is
gosql.Where("[!is]name","")
//sql: id is not ""
[exists] exists
gosql.Where("[exists]name","select 1")
//sql: name exists(select 1)
[!exists] not exists
gosql.Where("[!exists]name","select 1")
//sql: name not exists(select 1)
[#] sql
gosql.Where("[#]age=age-1")
//sql: age = age-1 

Raw SQL: db.Query()

rows,err := db.Query("select * from world where id = ?",1)
//sql: select * from world where id = 1

select master or slave

change to master: db.Master()
db := db.Master()
db.Fetch(...)
change to slave: db.Slave()
db := db.Slave()
db.Fetch(...)

builder of API

创建语句

用法 builder.New()

例子 s := builder.New()

设置Flag builder.Flag(f string)

设置一个falg,非必须

用法 s.Flag(string)

例子 s := builder.New().Flag("")

指定字段 builder.Field(fields string)

指定查询字段 不指定 默认为 *

用法 s.Field("*")

指定表名 builder.Table(tbl string)

用法 s.Table("tbl1.t1")

查询条件
  • 普通查询 s.Where(key string, val inferface{})

  • 等于查询

用法 s.Where("t1.status", "0")

等效SQL t1.status = 0

  • 不等于查询

用法 s.Where("[!=]t1.status", "0")

等效SQL t1.status != 0

  • IN查询

用法 s.Where("[in]sts", []string{"a", "b", "c"})

等效SQL t1.type in (a,b,c)

  • NOT IN查询

用法 s.Where("[!in]sts", []string{"a", "b", "c"})

等效SQL t1.type not in (a,b,c)

  • 复杂条件查询

用法 .Where(func(s *builder.Clause){}

s.Where("[!]t1.a",1).Where(func(s *builder.Clause){
    s.Where("t1.b",1)
    s.OrWhere("t1.c",1)
})

等效SQL t1.a != 1 and (t1.b = 1 or t1.c = 1)

  • GROUP BY 分类

用法 s.GroupBy("id")

等效SQL group by id

  • ORDER BY 排序

用法 s.OrderBy("id desc", "age asc")

等效SQL order by id desc

  • 限制条数

用法 s.Limit(30)

等效SQL limit 30

  • 偏移条数

用法 s.Offset(10)

等效SQL offset 30

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteSQL

func DeleteSQL(opts ...Option) (string, []interface{})

DeleteSQL ..

func InsertSQL

func InsertSQL(opts ...Option) (string, []interface{})

InsertSQL ..

func ReplaceSQL

func ReplaceSQL(opts ...Option) (string, []interface{})

ReplaceSQL ..

func Select

func Select(opts ...Option) (string, []interface{})

Select ..

func UpdateSQL

func UpdateSQL(opts ...Option) (string, []interface{})

UpdateSQL ..

Types

type Add

type Add int

Add ..

type Clause

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

Clause ...

func (*Clause) Build

func (p *Clause) Build(i int) (string, []interface{})

Build ...

func (*Clause) OrWhere

func (p *Clause) OrWhere(key interface{}, vals ...interface{}) *Clause

OrWhere ..

func (*Clause) Where

func (p *Clause) Where(key interface{}, vals ...interface{}) *Clause

Where ..

type Cluster

type Cluster interface {
	Master() (Executor, error)
	Slave(v uint64) (Executor, error)
	Session() (*Session, error)
	SessionContext(ctx context.Context) (*Session, error)
	Begin() (*Session, error)
	Fetch(dst interface{}, opts ...Option) error
	FetchAll(dst interface{}, opts ...Option) error
	Update(dst interface{}, opts ...Option) (Result, error)
	Insert(dst interface{}, opts ...Option) (Result, error)
	Replace(dst interface{}, opts ...Option) (Result, error)
	Delete(dst interface{}, opts ...Option) (Result, error)
}

Cluster ..

type DB

type DB interface {
	SetMaxIdleConns(n int)
	SetMaxOpenConns(n int)
	SetConnMaxLifetime(d time.Duration)
	Stats() sql.DBStats
	PingContext(ctx context.Context) error
	Ping() error
	Close() error
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
	Begin() (*sql.Tx, error)
	Driver() driver.Driver
	Conn(ctx context.Context) (*sql.Conn, error)
}

DB ..

type Error

type Error struct {
	Number  uint16
	Message string
}

Error ..

func (*Error) Error

func (e *Error) Error() string

type Executor

type Executor interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	Prepare(query string) (*sql.Stmt, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	Exec(query string, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
	QueryRow(query string, args ...interface{}) *sql.Row
}

Executor is a Executor

type Option

type Option func(q SQLSegments) SQLSegments

Option ..

func Columns

func Columns(fields ...string) Option

Columns ..

func CorssJoin

func CorssJoin(table string, conditionA, logic, conditionB string) Option

CorssJoin ..

func Flag

func Flag(flags ...string) Option

Flag ..

func ForUpdate

func ForUpdate(n int) Option

ForUpdate ..

func GroupBy

func GroupBy(fields ...string) Option

GroupBy ..

func InnerJoin

func InnerJoin(table string, conditionA, logic, conditionB string) Option

InnerJoin ..

func Join

func Join(table string, conditionA, logic, conditionB string) Option

Join ..

func LeftJoin

func LeftJoin(table string, conditionA, logic, conditionB string) Option

LeftJoin ..

func Limit

func Limit(n int) Option

Limit ..

func Offset

func Offset(n int) Option

Offset ..

func OrWhere

func OrWhere(key interface{}, vals ...interface{}) Option

OrWhere ..

func OrderBy

func OrderBy(fields ...string) Option

OrderBy ..

func RightJoin

func RightJoin(table string, conditionA, logic, conditionB string) Option

RightJoin ..

func Set

func Set(key string, val interface{}) Option

Set ..

func Table

func Table(name interface{}) Option

Table ..

func Where

func Where(key interface{}, vals ...interface{}) Option

Where ..

type PoolCluster

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

PoolCluster ..

func NewCluster

func NewCluster(opts ...PoolClusterOpts) *PoolCluster

NewCluster start

func (*PoolCluster) Begin

func (c *PoolCluster) Begin() (*Session, error)

Begin a transaction

func (*PoolCluster) Delete

func (c *PoolCluster) Delete(dst interface{}, opts ...Option) (Result, error)

Delete delete record

func (*PoolCluster) Fetch

func (c *PoolCluster) Fetch(dst interface{}, opts ...Option) error

Fetch fetch record to model

func (*PoolCluster) FetchAll

func (c *PoolCluster) FetchAll(dst interface{}, opts ...Option) error

FetchAll fetch records to models

func (*PoolCluster) Insert

func (c *PoolCluster) Insert(dst interface{}, opts ...Option) (Result, error)

Insert insert from model

func (*PoolCluster) Master

func (c *PoolCluster) Master() (Executor, error)

Master select db to master

func (*PoolCluster) Replace

func (c *PoolCluster) Replace(dst interface{}, opts ...Option) (Result, error)

Replace replace from model

func (*PoolCluster) Session

func (c *PoolCluster) Session() (*Session, error)

Session ..

func (*PoolCluster) SessionContext

func (c *PoolCluster) SessionContext(ctx context.Context) (*Session, error)

SessionContext ..

func (*PoolCluster) Slave

func (c *PoolCluster) Slave(v uint64) (Executor, error)

Slave select db to slave

func (*PoolCluster) Update

func (c *PoolCluster) Update(dst interface{}, opts ...Option) (Result, error)

Update update from model

type PoolClusterOpts

type PoolClusterOpts func(p *PoolCluster) *PoolCluster

PoolClusterOpts ..

func AddDb

func AddDb(driver, dsn string) PoolClusterOpts

AddDb add a db

type Result

type Result sql.Result

Result ..

type SQLSegments

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

SQLSegments ...

func New

func New() *SQLSegments

New ..

func NewSQLSegment

func NewSQLSegment() *SQLSegments

NewSQLSegment ..

func (*SQLSegments) Args

func (s *SQLSegments) Args() []interface{}

Args ..

func (*SQLSegments) Build

func (s *SQLSegments) Build() (string, []interface{})

Build ..

func (*SQLSegments) BuildDelete

func (s *SQLSegments) BuildDelete() string

BuildDelete ...

func (*SQLSegments) BuildInsert

func (s *SQLSegments) BuildInsert() string

BuildInsert ...

func (*SQLSegments) BuildReplace

func (s *SQLSegments) BuildReplace() string

BuildReplace ...

func (*SQLSegments) BuildSelect

func (s *SQLSegments) BuildSelect() string

BuildSelect ...

func (*SQLSegments) BuildUpdate

func (s *SQLSegments) BuildUpdate() string

BuildUpdate ...

func (*SQLSegments) CorssJoin

func (s *SQLSegments) CorssJoin(table string, conditionA, logic, conditionB string) *SQLSegments

CorssJoin SQLSegments

func (*SQLSegments) Delete

func (s *SQLSegments) Delete() *SQLSegments

Delete ...

func (*SQLSegments) Field

func (s *SQLSegments) Field(fields ...string) *SQLSegments

Field SQLSegments

func (*SQLSegments) Flag

func (s *SQLSegments) Flag(flags ...string) *SQLSegments

Flag SQLSegments

func (*SQLSegments) ForUpdate

func (s *SQLSegments) ForUpdate() *SQLSegments

ForUpdate SQLSegments

func (*SQLSegments) GroupBy

func (s *SQLSegments) GroupBy(fields ...string) *SQLSegments

GroupBy SQLSegments

func (*SQLSegments) Having

func (s *SQLSegments) Having(key interface{}, vals ...interface{}) *SQLSegments

Having ...

func (*SQLSegments) InnerJoin

func (s *SQLSegments) InnerJoin(table string, conditionA, logic, conditionB string) *SQLSegments

InnerJoin SQLSegments

func (*SQLSegments) Insert

func (s *SQLSegments) Insert(vals ...map[string]interface{}) *SQLSegments

Insert ...

func (*SQLSegments) IsEmptyWhereClause

func (s *SQLSegments) IsEmptyWhereClause() bool

IsEmptyWhereClause ...

func (*SQLSegments) Join

func (s *SQLSegments) Join(table string, conditionA, logic, conditionB string) *SQLSegments

Join SQLSegments

func (*SQLSegments) LeftJoin

func (s *SQLSegments) LeftJoin(table string, conditionA, logic, conditionB string) *SQLSegments

LeftJoin SQLSegments

func (*SQLSegments) Limit

func (s *SQLSegments) Limit(n int) *SQLSegments

Limit SQLSegments

func (*SQLSegments) Offset

func (s *SQLSegments) Offset(n int) *SQLSegments

Offset SQLSegments

func (*SQLSegments) OrWhere

func (s *SQLSegments) OrWhere(key interface{}, vals ...interface{}) *SQLSegments

OrWhere ..

func (*SQLSegments) OrderBy

func (s *SQLSegments) OrderBy(fields ...string) *SQLSegments

OrderBy SQLSegments

func (*SQLSegments) RightJoin

func (s *SQLSegments) RightJoin(table string, conditionA, logic, conditionB string) *SQLSegments

RightJoin SQLSegments

func (*SQLSegments) Table

func (s *SQLSegments) Table(name interface{}) *SQLSegments

Table SQLSegments

func (*SQLSegments) Union

func (s *SQLSegments) Union(f func(*SQLSegments)) *SQLSegments

Union ...

func (*SQLSegments) UnsafeUpdate

func (s *SQLSegments) UnsafeUpdate(vals map[string]interface{}) *SQLSegments

UnsafeUpdate 可以没有where条件更新 ,Update 更新必须指定where条件才能更新否则panic

func (*SQLSegments) Update

func (s *SQLSegments) Update(vals map[string]interface{}) *SQLSegments

Update ..

func (*SQLSegments) UpdateField

func (s *SQLSegments) UpdateField(key string, val interface{}) *SQLSegments

UpdateField 更新字段

func (*SQLSegments) Where

func (s *SQLSegments) Where(key interface{}, vals ...interface{}) *SQLSegments

Where ..

type Session

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

Session ..

func (*Session) Commit

func (s *Session) Commit() error

Commit ..

func (*Session) Delete

func (s *Session) Delete(dst interface{}, opts ...Option) (Result, error)

Delete ..

func (*Session) Exec

func (s *Session) Exec(query string, args ...interface{}) (sql.Result, error)

Exec ..

func (*Session) ExecContext

func (s *Session) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

ExecContext ..

func (*Session) Executor

func (s *Session) Executor(master bool) (Executor, error)

Executor ..

func (*Session) Fetch

func (s *Session) Fetch(dst interface{}, opts ...Option) error

Fetch ..

func (*Session) FetchAll

func (s *Session) FetchAll(dst interface{}, opts ...Option) error

FetchAll ..

func (*Session) Insert

func (s *Session) Insert(dst interface{}, opts ...Option) (Result, error)

Insert ..

func (*Session) Master

func (s *Session) Master() *Session

Master 强制master

func (*Session) Query

func (s *Session) Query(query string, args ...interface{}) (*sql.Rows, error)

Query ..

func (*Session) QueryContext

func (s *Session) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

QueryContext ..

func (*Session) QueryRow

func (s *Session) QueryRow(query string, args ...interface{}) *sql.Row

QueryRow ..

func (*Session) QueryRowContext

func (s *Session) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRowContext ..

func (*Session) Replace

func (s *Session) Replace(dst interface{}, opts ...Option) (Result, error)

Replace ..

func (*Session) Rollback

func (s *Session) Rollback() error

Rollback ..

func (*Session) Update

func (s *Session) Update(dst interface{}, opts ...Option) (Result, error)

Update ..

type SessionOpts

type SessionOpts func(s *Session) *Session

SessionOpts ..

type Sub

type Sub int

Sub ..

type TbName

type TbName struct {
	Name  string
	Alias string
}

TbName ..

type Tx

type Tx interface {
	StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt
	Stmt(stmt *sql.Stmt) *sql.Stmt
	Commit() error
	Rollback() error
}

Tx ..

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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