dbs

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 8, 2019 License: MIT Imports: 16 Imported by: 17

README

DBS

SQL Builder 工具, 不是 ORM。

帮助

在集成的过程中有遇到问题,欢迎加 QQ 群 564704807 讨论。

安装

$ go get github.com/smartwalle/dbs

开始

package main

import (
	"fmt"
	"github.com/smartwalle/dbs"
)

func main() {
	var sb = dbs.NewSelectBuilder()
	sb.Selects("u.id", "u.name", "u.age")
	sb.From("user", "AS u")
	sb.Where("u.id = ?", 1)
	sb.Limit(1)

	sqlStr, args, _ := sb.ToSQL()
	fmt.Println("sqlStr:", sqlStr)
	fmt.Println("args:", args)
}

上述代码会输出如下内容:

sql: SELECT u.id, u.name, u.age FROM user AS u WHERE u.id = ? LIMIT ?
args: [10 1]
执行 SQL

此处使用 MySQL 作为演示,需要准备好一个测试用数据库及 user 表,user 表结构如下:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `human_id_uindex` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/smartwalle/dbs"
)

func main() {
	var sb = dbs.NewSelectBuilder()
	sb.Selects("u.id", "u.name", "u.age")
	sb.From("user", "AS u")
	sb.Where("u.id = ?", 1)
	sb.Limit(1)

	db, err := sql.Open("mysql", "数据库连接信息")
	if err != nil {
		fmt.Println("连接数据库出错:", err)
		return
	}
	defer db.Close()

	var user *User
	if err := sb.Scan(db, &user); err != nil {
		fmt.Println("Query 出错:", err)
		return
	}

	if user != nil {
		fmt.Println(user.Id, user.Name, user.Age)
	}
}

type User struct {
	Id   int64  `sql:"id"`
	Name string `sql:"name"`
	Age  int    `sql:"age"`
}

运行上述代码,如果数据库中存在 id 为 1 的数据,则会正常输出相关的信息。

Select
var sb = dbs.NewSelectBuilder()
sb.Selects("u.id", "u.name AS username", "u.age")
sb.Select(dbs.Alias("b.amount", "user_amount"))
sb.From("user", "AS u")
sb.LeftJoin("bank", "AS b ON b.user_id = u.id")
sb.Where("u.id = ?", 1)
fmt.Println(sb.ToSQL())

执行 Select 语句:

db, err := sql.Open("mysql", "数据库连接信息")
var user *User
sb.Scan(db, &user)
Insert
var ib = dbs.NewInsertBuilder()
ib.Table("user")
ib.Columns("name", "age")
ib.Values("用户1", 18)
ib.Values("用户2", 20)
fmt.Println(ib.ToSQL())

执行 Insert 语句:

db, err := sql.Open("mysql", "数据库连接信息")
ib.Exec(db)
Update
var ub = dbs.NewUpdateBuilder()
ub.Table("user")
ub.SET("name", "新的名字")
ub.Where("id = ? ", 1)
ub.Limit(1)
fmt.Println(ub.ToSQL())

执行 Update 语句:

db, err := sql.Open("mysql", "数据库连接信息")
ub.Exec(db)
Delete
var rb = dbs.NewDeleteBuilder()
rb.Table("user")
rb.Where("id = ?", 1)
rb.Limit(1)
fmt.Println(rb.ToSQL())

执行 Delete 语句:

db, err := sql.Open("mysql", "数据库连接信息")
rb.Exec(db)

更多内容请参考 test 文件。

License

This project is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	MySQL      = &mysql{}
	Default    = MySQL
	PostgreSQL = &postgresql{}
)

Functions

func AND

func AND(stmts ...Statement) *whereStmt

func Alias

func Alias(sql interface{}, alias string) *aliasStmt

func Case

func Case(what ...interface{}) *caseStmt

func Find

func Find(s Executor, table string, dest interface{}, limit, offset int64, w Statement) (err error)

--------------------------------------------------------------------------------

func FindAll

func FindAll(s Executor, table string, dest interface{}, w Statement) (err error)

func FindOne

func FindOne(s Executor, table string, dest interface{}, w Statement) (err error)

func GetFields

func GetFields(dest interface{}) (result []string, err error)

func NewSQL

func NewSQL(driver, url string, maxOpen, maxIdle int) (db *sql.DB, err error)

func NewStatement

func NewStatement(sql interface{}, args ...interface{}) *statement

func OR

func OR(stmts ...Statement) *whereStmt

func OnDuplicateKeyUpdate

func OnDuplicateKeyUpdate() *onDuplicateKeyUpdateStmt

func SQL

func SQL(sql string, args ...interface{}) *statement

func Scan

func Scan(rows *sql.Rows, dest interface{}) (err error)

func SetLogger

func SetLogger(l Logger)

func UseDialect

func UseDialect(d dialect)

Types

type Args

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

--------------------------------------------------------------------------------

func (*Args) Append

func (this *Args) Append(args ...interface{})

type Builder

type Builder interface {
	Type() string
	ToSQL() (string, []interface{}, error)
}

--------------------------------------------------------------------------------

type DB

type DB interface {
	Executor
	Preparer

	Ping() error
	PingContext(ctx context.Context) error

	Begin() (*sql.Tx, error)
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

--------------------------------------------------------------------------------

func NewCache

func NewCache(db DB) DB

--------------------------------------------------------------------------------

type DeleteBuilder

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

func NewDeleteBuilder

func NewDeleteBuilder() *DeleteBuilder

--------------------------------------------------------------------------------

func (*DeleteBuilder) Alias

func (this *DeleteBuilder) Alias(alias ...string) *DeleteBuilder

func (*DeleteBuilder) AppendToSQL

func (this *DeleteBuilder) AppendToSQL(w io.Writer, args *Args) error

func (DeleteBuilder) Exec

func (this DeleteBuilder) Exec(s Executor) (sql.Result, error)

func (DeleteBuilder) ExecContext

func (this DeleteBuilder) ExecContext(ctx context.Context, s Executor) (result sql.Result, err error)

func (*DeleteBuilder) Join

func (this *DeleteBuilder) Join(join, table, suffix string, args ...interface{}) *DeleteBuilder

func (*DeleteBuilder) LeftJoin

func (this *DeleteBuilder) LeftJoin(table, suffix string, args ...interface{}) *DeleteBuilder

func (*DeleteBuilder) Limit

func (this *DeleteBuilder) Limit(limit int64) *DeleteBuilder

func (*DeleteBuilder) Offset

func (this *DeleteBuilder) Offset(offset int64) *DeleteBuilder

func (*DeleteBuilder) Options

func (this *DeleteBuilder) Options(options ...string) *DeleteBuilder

func (*DeleteBuilder) OrderBy

func (this *DeleteBuilder) OrderBy(sql ...string) *DeleteBuilder

func (*DeleteBuilder) Prefix

func (this *DeleteBuilder) Prefix(sql string, args ...interface{}) *DeleteBuilder

func (*DeleteBuilder) RightJoin

func (this *DeleteBuilder) RightJoin(table, suffix string, args ...interface{}) *DeleteBuilder

func (*DeleteBuilder) Suffix

func (this *DeleteBuilder) Suffix(sql interface{}, args ...interface{}) *DeleteBuilder

func (*DeleteBuilder) Table

func (this *DeleteBuilder) Table(table string, args ...string) *DeleteBuilder

func (*DeleteBuilder) ToSQL

func (this *DeleteBuilder) ToSQL() (string, []interface{}, error)

func (*DeleteBuilder) Type

func (this *DeleteBuilder) Type() string

func (*DeleteBuilder) USING

func (this *DeleteBuilder) USING(sql string) *DeleteBuilder

func (DeleteBuilder) UseDialect

func (this DeleteBuilder) UseDialect(d dialect)

func (*DeleteBuilder) Where

func (this *DeleteBuilder) Where(sql interface{}, args ...interface{}) *DeleteBuilder

type Eq

type Eq map[string]interface{}

func (Eq) AppendToSQL

func (this Eq) AppendToSQL(w io.Writer, args *Args) error

func (Eq) ToSQL

func (this Eq) ToSQL() (string, []interface{}, error)

type Executor

type Executor interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

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

--------------------------------------------------------------------------------

type InsertBuilder

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

func Insert

func Insert(columns ...string) *InsertBuilder

--------------------------------------------------------------------------------

func NewInsertBuilder

func NewInsertBuilder() *InsertBuilder

--------------------------------------------------------------------------------

func (*InsertBuilder) AppendToSQL

func (this *InsertBuilder) AppendToSQL(w io.Writer, args *Args) error

func (*InsertBuilder) Clone

func (this *InsertBuilder) Clone() *InsertBuilder

func (*InsertBuilder) Column

func (this *InsertBuilder) Column(column string) *InsertBuilder

func (*InsertBuilder) Columns

func (this *InsertBuilder) Columns(columns ...string) *InsertBuilder

func (InsertBuilder) Exec

func (this InsertBuilder) Exec(s Executor) (sql.Result, error)

func (InsertBuilder) ExecContext

func (this InsertBuilder) ExecContext(ctx context.Context, s Executor) (result sql.Result, err error)

func (*InsertBuilder) Options

func (this *InsertBuilder) Options(options ...string) *InsertBuilder

func (*InsertBuilder) Prefix

func (this *InsertBuilder) Prefix(sql string, args ...interface{}) *InsertBuilder

func (*InsertBuilder) SET

func (this *InsertBuilder) SET(column string, value interface{}) *InsertBuilder

func (*InsertBuilder) Select

func (this *InsertBuilder) Select(sb *SelectBuilder) *InsertBuilder

func (*InsertBuilder) Suffix

func (this *InsertBuilder) Suffix(sql interface{}, args ...interface{}) *InsertBuilder

func (*InsertBuilder) Table

func (this *InsertBuilder) Table(table string) *InsertBuilder

func (*InsertBuilder) ToSQL

func (this *InsertBuilder) ToSQL() (string, []interface{}, error)

func (*InsertBuilder) Type

func (this *InsertBuilder) Type() string

func (*InsertBuilder) UseDialect

func (this *InsertBuilder) UseDialect(d dialect)

func (*InsertBuilder) Values

func (this *InsertBuilder) Values(values ...interface{}) *InsertBuilder

type Logger

type Logger interface {
	SetPrefix(prefix string)
	Prefix() string
	Println(args ...interface{})
	Printf(format string, args ...interface{})
	Output(calldepth int, s string) error
}

type NotEq

type NotEq Eq

--------------------------------------------------------------------------------

func (NotEq) AppendToSQL

func (this NotEq) AppendToSQL(w io.Writer, args *Args) error

func (NotEq) ToSQL

func (this NotEq) ToSQL() (string, []interface{}, error)

type Preparer

type Preparer interface {
	Prepare(query string) (*sql.Stmt, error)
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

--------------------------------------------------------------------------------

type RawBuilder

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

--------------------------------------------------------------------------------

func NewBuilder

func NewBuilder(sql string, args ...interface{}) *RawBuilder

--------------------------------------------------------------------------------

func (*RawBuilder) Append

func (this *RawBuilder) Append(sql string, args ...interface{}) *RawBuilder

func (*RawBuilder) AppendToSQL

func (this *RawBuilder) AppendToSQL(w io.Writer, args *Args) error

func (RawBuilder) Exec

func (this RawBuilder) Exec(s Executor) (sql.Result, error)

func (RawBuilder) ExecContext

func (this RawBuilder) ExecContext(ctx context.Context, s Executor) (result sql.Result, err error)

func (*RawBuilder) Format

func (this *RawBuilder) Format(format string, args ...interface{}) *RawBuilder

func (*RawBuilder) Params

func (this *RawBuilder) Params(args ...interface{}) *RawBuilder

func (RawBuilder) Query

func (this RawBuilder) Query(s Executor) (*sql.Rows, error)

func (RawBuilder) QueryContext

func (this RawBuilder) QueryContext(ctx context.Context, s Executor) (*sql.Rows, error)

func (RawBuilder) Scan

func (this RawBuilder) Scan(s Executor, dest interface{}) (err error)

func (RawBuilder) ScanContext

func (this RawBuilder) ScanContext(ctx context.Context, s Executor, dest interface{}) (err error)

func (RawBuilder) ScanRow

func (this RawBuilder) ScanRow(s Executor, dest ...interface{}) (err error)

func (RawBuilder) ScanRowContext

func (this RawBuilder) ScanRowContext(ctx context.Context, s Executor, dest ...interface{}) (err error)

func (*RawBuilder) ToSQL

func (this *RawBuilder) ToSQL() (string, []interface{}, error)

func (*RawBuilder) Type

func (this *RawBuilder) Type() string

func (RawBuilder) UseDialect

func (this RawBuilder) UseDialect(d dialect)

type SQLValue

type SQLValue interface {
	SQLValue() string
}

--------------------------------------------------------------------------------

type SelectBuilder

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

func NewSelectBuilder

func NewSelectBuilder() *SelectBuilder

--------------------------------------------------------------------------------

func Select

func Select(columns ...string) *SelectBuilder

--------------------------------------------------------------------------------

func (*SelectBuilder) AppendToSQL

func (this *SelectBuilder) AppendToSQL(w io.Writer, args *Args) error

func (*SelectBuilder) Clone

func (this *SelectBuilder) Clone() *SelectBuilder

func (*SelectBuilder) Count

func (this *SelectBuilder) Count(args ...string) *SelectBuilder

func (*SelectBuilder) FoundRows

func (this *SelectBuilder) FoundRows(args ...string) *SelectBuilder

func (*SelectBuilder) From

func (this *SelectBuilder) From(table string, args ...string) *SelectBuilder

func (*SelectBuilder) FromStmt

func (this *SelectBuilder) FromStmt(stmt Statement) *SelectBuilder

func (*SelectBuilder) GroupBy

func (this *SelectBuilder) GroupBy(groupBys ...string) *SelectBuilder

func (*SelectBuilder) Having

func (this *SelectBuilder) Having(sql interface{}, args ...interface{}) *SelectBuilder

func (*SelectBuilder) Join

func (this *SelectBuilder) Join(join, table, suffix string, args ...interface{}) *SelectBuilder

func (*SelectBuilder) LeftJoin

func (this *SelectBuilder) LeftJoin(table, suffix string, args ...interface{}) *SelectBuilder

func (*SelectBuilder) Limit

func (this *SelectBuilder) Limit(limit int64) *SelectBuilder

func (*SelectBuilder) Offset

func (this *SelectBuilder) Offset(offset int64) *SelectBuilder

func (*SelectBuilder) Options

func (this *SelectBuilder) Options(options ...string) *SelectBuilder

func (*SelectBuilder) OrderBy

func (this *SelectBuilder) OrderBy(sql ...string) *SelectBuilder

func (*SelectBuilder) Prefix

func (this *SelectBuilder) Prefix(sql string, args ...interface{}) *SelectBuilder

func (SelectBuilder) Query

func (this SelectBuilder) Query(s Executor) (*sql.Rows, error)

func (SelectBuilder) QueryContext

func (this SelectBuilder) QueryContext(ctx context.Context, s Executor) (*sql.Rows, error)

func (*SelectBuilder) RightJoin

func (this *SelectBuilder) RightJoin(table, suffix string, args ...interface{}) *SelectBuilder

func (SelectBuilder) Scan

func (this SelectBuilder) Scan(s Executor, dest interface{}) (err error)

func (SelectBuilder) ScanContext

func (this SelectBuilder) ScanContext(ctx context.Context, s Executor, dest interface{}) (err error)

func (SelectBuilder) ScanRow

func (this SelectBuilder) ScanRow(s Executor, dest ...interface{}) (err error)

func (SelectBuilder) ScanRowContext

func (this SelectBuilder) ScanRowContext(ctx context.Context, s Executor, dest ...interface{}) (err error)

func (*SelectBuilder) Select

func (this *SelectBuilder) Select(column interface{}, args ...interface{}) *SelectBuilder

func (*SelectBuilder) Selects

func (this *SelectBuilder) Selects(columns ...string) *SelectBuilder

func (*SelectBuilder) Suffix

func (this *SelectBuilder) Suffix(sql interface{}, args ...interface{}) *SelectBuilder

func (*SelectBuilder) ToSQL

func (this *SelectBuilder) ToSQL() (string, []interface{}, error)

func (*SelectBuilder) Type

func (this *SelectBuilder) Type() string

func (SelectBuilder) UseDialect

func (this SelectBuilder) UseDialect(d dialect)

func (*SelectBuilder) UseSQLCalcFoundRows

func (this *SelectBuilder) UseSQLCalcFoundRows() *SelectBuilder

--------------------------------------------------------------------------------

func (*SelectBuilder) Where

func (this *SelectBuilder) Where(sql interface{}, args ...interface{}) *SelectBuilder

type Statement

type Statement interface {
	AppendToSQL(w io.Writer, args *Args) error
	ToSQL() (string, []interface{}, error)
}

--------------------------------------------------------------------------------

func IN

func IN(sql string, args interface{}) Statement

--------------------------------------------------------------------------------

func Like

func Like(sql string, args ...interface{}) Statement

func NotIn

func NotIn(sql string, args interface{}) Statement

--------------------------------------------------------------------------------

func NotLike

func NotLike(sql string, args ...interface{}) Statement

type StmtCache

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

func (*StmtCache) Begin

func (this *StmtCache) Begin() (*sql.Tx, error)

func (*StmtCache) BeginTx

func (this *StmtCache) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

func (*StmtCache) Exec

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

func (*StmtCache) ExecContext

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

func (*StmtCache) Ping

func (this *StmtCache) Ping() error

func (*StmtCache) PingContext

func (this *StmtCache) PingContext(ctx context.Context) error

func (*StmtCache) Prepare

func (this *StmtCache) Prepare(query string) (*sql.Stmt, error)

func (*StmtCache) PrepareContext

func (this *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

func (*StmtCache) Query

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

func (*StmtCache) QueryContext

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

type TX

type TX interface {
	Executor
	Preparer

	Stmt(stmt *sql.Stmt) *sql.Stmt
	StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt

	Commit() (err error)
	Rollback() error
}

--------------------------------------------------------------------------------

func MustTx

func MustTx(db DB) TX

func MustTxContext

func MustTxContext(ctx context.Context, db DB, opts *sql.TxOptions) TX

func NewTx

func NewTx(db DB) (TX, error)

--------------------------------------------------------------------------------

func NewTxContext

func NewTxContext(ctx context.Context, db DB, opts *sql.TxOptions) (tx TX, err error)

type UpdateBuilder

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

func NewUpdateBuilder

func NewUpdateBuilder() *UpdateBuilder

--------------------------------------------------------------------------------

func Update

func Update(table string, args ...string) *UpdateBuilder

--------------------------------------------------------------------------------

func (*UpdateBuilder) AppendToSQL

func (this *UpdateBuilder) AppendToSQL(w io.Writer, sep string, args *Args) error

func (UpdateBuilder) Exec

func (this UpdateBuilder) Exec(s Executor) (sql.Result, error)

func (UpdateBuilder) ExecContext

func (this UpdateBuilder) ExecContext(ctx context.Context, s Executor) (result sql.Result, err error)

func (*UpdateBuilder) Join

func (this *UpdateBuilder) Join(join, table, suffix string, args ...interface{}) *UpdateBuilder

func (*UpdateBuilder) LeftJoin

func (this *UpdateBuilder) LeftJoin(table, suffix string, args ...interface{}) *UpdateBuilder

func (*UpdateBuilder) Limit

func (this *UpdateBuilder) Limit(limit int64) *UpdateBuilder

func (*UpdateBuilder) Offset

func (this *UpdateBuilder) Offset(offset int64) *UpdateBuilder

func (*UpdateBuilder) Options

func (this *UpdateBuilder) Options(options ...string) *UpdateBuilder

func (*UpdateBuilder) OrderBy

func (this *UpdateBuilder) OrderBy(sql ...string) *UpdateBuilder

func (*UpdateBuilder) Prefix

func (this *UpdateBuilder) Prefix(sql string, args ...interface{}) *UpdateBuilder

func (*UpdateBuilder) RightJoin

func (this *UpdateBuilder) RightJoin(table, suffix string, args ...interface{}) *UpdateBuilder

func (*UpdateBuilder) SET

func (this *UpdateBuilder) SET(column string, value interface{}) *UpdateBuilder

func (*UpdateBuilder) SETS

func (this *UpdateBuilder) SETS(kvs ...interface{}) *UpdateBuilder

SETS 批量设置需要更新的字段及其值 var name = "my name" SETS("name", name, "age", 10)

func (*UpdateBuilder) SetMap

func (this *UpdateBuilder) SetMap(data map[string]interface{}) *UpdateBuilder

func (*UpdateBuilder) Suffix

func (this *UpdateBuilder) Suffix(sql interface{}, args ...interface{}) *UpdateBuilder

func (*UpdateBuilder) Table

func (this *UpdateBuilder) Table(table string, args ...string) *UpdateBuilder

func (*UpdateBuilder) ToSQL

func (this *UpdateBuilder) ToSQL() (string, []interface{}, error)

func (*UpdateBuilder) Type

func (this *UpdateBuilder) Type() string

func (UpdateBuilder) UseDialect

func (this UpdateBuilder) UseDialect(d dialect)

func (*UpdateBuilder) Where

func (this *UpdateBuilder) Where(sql interface{}, args ...interface{}) *UpdateBuilder

Directories

Path Synopsis
examples module
pq
tools
tx

Jump to

Keyboard shortcuts

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