mysqldb

package module
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2019 License: BSD-2-Clause Imports: 17 Imported by: 0

README

Mysqldb

Mysqldb is a simple ORM for Go.

Installing Mysqldb
go get github.com/go-sql-driver/mysql
go get github.com/kirinlabs/mysqldb
How to use Mysqldb?

Oepn a database connection that supports ConnectionPool

var db *mysqldb.Adapter
var err error

func init(){
    db, err = mysqldb.New(
        &mysqldb.Options{
    	    User:         "root",
    	    Password:     "root",
            Host:         "127.0.0.1",
    	    Port:         3306,
    	    Database:     "test",
    	    Charset:      "utf8",
    	    MaxIdleConns: 5,
    	    MaxOpenConns: 10,
    	    Debug:        true,
        })
    if err != nil {
    	log.Panic("Connect mysql server error: ", err)
    }
}

Open debug log and set the log level

  db.SetLogLevel(mysqldb.LOG_DEBUG)
Crud Operation
type Article struct {
    Id                      int	`json:"id"`
    Title                   string `json:"title"`
    Description             string `json:""`
    CreateDate      string    `json:"create_date"`
}

Fetch a single object

var article1 Article
err := db.Table("article").First(&article1)

var article2 Article
err := db.Table("article").Where("id",">",1).First(&article2)

var article3 Article
err := db.Table("article").Where("id",">",1).Where("create_date","2019-01-01 12:00:01").First(&article2)

Fetch objects list

var articles1 []*Article
err := db.Table("article").Where("id",">=","1").Limit(10).Find(&articles1)

var articles2 []*Article
err := db.Table("article").Where("id",">=","1").Limit(10,20).Find(&articles2)

Fetch result as Map

list,err := db.Table("article").Where("id",">=",1).Where("age",19).Fetch() //return map[string]interface{}

list,err := db.Table("article").Where("id",">=",1).Where("age",19).FetchAll() //return []map[string]interface{}

list,err := db.Table("article").Where("id", ">=", 1).Limit(10).Fields("id", "title").FetchAll()

Insert with Map

data := map[string]interface{}{
		"title":       "test Mysqldb one",
		"cid":         1,
		"Description": "test insert api",
		"create_date": time.Now().Format("2006-01-02 15:04:05"),
	}
num, err := db.Table("article").Insert(data)

Insert with Struct

article := Article{}
article.Title = "test insert two"
article.CreateDate = time.Now().Format("2006-01-02 15:04:05")

num, err := db.Table("article").Insert(&article)

MultiInsert with Map

_, err := m.Table("article").MultiInsert([]map[string]interface{}{
	{"title":"a","desp":"test one","create_date": time.Now().Format("2006-01-02 15:04:05")},
	{"title":"b","desp":"test two","create_date": time.Now().Format("2006-01-02 15:04:05")},
})

MultiInsert with Struct

_, err := m.Table("article").MultiInsert([]*Article{
	{nil,"a","test one",time.Now().Format("2006-01-02 15:04:05")},
	{nil,"b","test two",time.Now().Format("2006-01-02 15:04:05")},
})

Update with Map

data := map[string]interface{}{
		"id":          100,  //Primary keys can be filtered with SetPk(" id ")
		"title":       "test Mysqldb one",
		"cid":         1,
		"Description": "update",
		"create_date": time.Now().Format("2006-01-02 15:04:05"),
}
num, err := db.Table("article").Where("id", 1).SetPk("id").Update(data)  //SetPk("id"), Prevent primary key id from being updated

Delete

num, err := db.Table("article").Where("id", 1).Delete()
num, err := db.Table("article").Delete() //will faild,where condition cannot be empty.
Join Operation

The default alias for the Table is A, default alias of the Join table is B

Left join operation

data, err := db.Table("article").LeftJoin("category", "A.cid=B.id").FetchAll()
data, err := db.Table("article").LeftJoin("category", "A.cid=B.id").WhereRaw("B.id is not null").FetchAll()

Right join operation

data, err := db.Table("article").RightJoin("category", "A.cid=B.id").FetchAll()
Advanced operations

Id

list, err := db.Table("article").Id(1).FetchAll()  //The Id() default operation id field
list, err := db.Table("article").Id([]int{1,2,3}).FetchAll()

list, err := db.Table("article").SetPk("cid").Id([]int{1,2,3}).FetchAll() //Modify the field for the Id() operation

WhereIn

list, err := db.Table("article").WhereIn("id", []int{1, 2, 3}).FetchAll()

WhereNotIn

list, err := db.Table("article").WhereNotIn("id", []int{1, 2, 3}).FetchAll()

WhereRaw

list, err := db.Table("article").Where("id", 2).WhereRaw("cid>=1 and description=''").FetchAll()

OrWhere

list, err := db.Table("article").Where("id", 2).OrWhere("cid>=1 and description=''").FetchAll()

Limit

list, err := db.Table("article").Limit(10).FetchAll()
list, err := db.Table("article").Limit(10,20).FetchAll()

GroupBy

list, err := db.Table("article").Where("id", ">", 1).GroupBy("cid").FetchAll()
list, err := db.Table("article").Where("id", ">", 1).GroupBy("cid,title").FetchAll()

OrderBy

list, err := db.Table("article").Where("id", ">", 1).OrderBy("id").FetchAll()
list, err := db.Table("article").Where("id", ">", 1).OrderBy("id desc").FetchAll()

Distinct

list, err := db.Table("article").Distinct("cid").FetchAll()

Count

list, err := db.Table("article").Count()
list, err := db.Table("article").Where("id",">=",100).Count()
list, err := db.Table("article").Distinct("cid").Count()
Execute native SQL

Query

list, err := db.Query("select * from article")

Exec

num, err := db.Exec("update article set description='execute' where id=2")
Transaction

Need to create a new Model object for transaction operations

m := db.NewModel()

defer m.Close()

m.Begin()
_, err := m.Exec("update article set description='query' where id=3")
if err != nil {
	model.Rollback()
	return
}

_, err = m.Table("category").Where("id", 9).Delete()
if err != nil {
	m.Rollback()
	return
}

m.Commit()
Helper method

Scan()

article := &Article{}

data, _ := db.Table("article").Where("id",1).Where("title","!=","").Fetch()

db.Scan(data,&article)
articles := make([]*Article,0)

list, _ := db.Table("article").Where("id",">",1).Where("title","!=","").FetchAll()

db.Scan(list,&articles)

for _,v:=range articles{
    log.Println(v.Title)
}

Documentation

Index

Constants

View Source
const (
	NODATA_ERROR                    = "no data was queried."
	SLICEPOINTER_ERROR              = "needs a pointer to a slice."
	TABLENAME_ERROR                 = "table name cannot be empty."
	WHERE_ERROR                     = "where condition cannot be empty."
	PARAMETER_ERROR                 = "parameter error."
	PARAMETER_FIRST_REQUIRED        = "first parameter cannot be empty."
	PARAMETER_SECOND_SLICE_REQUIRED = "second parameter needs a slice."
)
View Source
const (
	LOG_PREFIX = "[mysqldb]"
	LOG_FORMAT = log.LstdFlags
	LOG_LEVEL  = LOG_DEBUG
)
View Source
const (
	LOG_DEBUG int = iota
	LOG_INFO
	LOG_WARN
	LOG_ERROR
)

Variables

This section is empty.

Functions

func Export

func Export(v interface{}) string

func FormatUpper

func FormatUpper(str string) string

func Json

func Json(v interface{}) string

func Keys added in v0.1.4

func Keys(src map[string]interface{}) []string

func ReflectFields

func ReflectFields(iface interface{}) []string

func Substr

func Substr(s string, start, length int) string

Types

type Adapter

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

func New

func New(options *Options) (*Adapter, error)

func (*Adapter) Close

func (adapter *Adapter) Close() error

func (*Adapter) DB

func (adapter *Adapter) DB() *sql.DB

func (*Adapter) Debug

func (adapter *Adapter) Debug(flag ...bool)

func (*Adapter) Exec

func (adapter *Adapter) Exec(sql string, args ...interface{}) (int64, error)

func (*Adapter) Id

func (adapter *Adapter) Id(args interface{}) *Model

func (*Adapter) In

func (adapter *Adapter) In(field string, values interface{}) *Model

func (*Adapter) NewModel

func (adapter *Adapter) NewModel() *Model

func (*Adapter) NotIn

func (adapter *Adapter) NotIn(field string, values interface{}) *Model

func (*Adapter) Query

func (adapter *Adapter) Query(sql string, args ...interface{}) ([]map[string]interface{}, error)

func (*Adapter) Scan

func (adapter *Adapter) Scan(sour interface{}, dest interface{}) error

func (*Adapter) SetLogLevel

func (adapter *Adapter) SetLogLevel(level int)

func (*Adapter) SetLogger

func (adapter *Adapter) SetLogger(logger iLogger)

func (*Adapter) SetMaxIdleConns

func (adapter *Adapter) SetMaxIdleConns(n int)

func (*Adapter) SetMaxOpenConns

func (adapter *Adapter) SetMaxOpenConns(n int)

func (*Adapter) T

func (adapter *Adapter) T(args string) *Model

func (*Adapter) Table

func (adapter *Adapter) Table(args string) *Model

func (*Adapter) Where

func (adapter *Adapter) Where(args ...interface{}) *Model

func (*Adapter) WhereIn

func (adapter *Adapter) WhereIn(field string, values interface{}) *Model

func (*Adapter) WhereNotIn

func (adapter *Adapter) WhereNotIn(field string, values interface{}) *Model

func (*Adapter) WhereRaw

func (adapter *Adapter) WhereRaw(args string) *Model

type LogEntry

type LogEntry struct {
	LogInfo  *log.Logger
	LogWarn  *log.Logger
	LogDebug *log.Logger
	LogError *log.Logger
	// contains filtered or unexported fields
}

func InitLogger

func InitLogger(o io.Writer) *LogEntry

func (*LogEntry) Debug

func (l *LogEntry) Debug(v ...interface{})

func (*LogEntry) Debugf

func (l *LogEntry) Debugf(f string, v ...interface{})

func (*LogEntry) Error

func (l *LogEntry) Error(v ...interface{})

func (*LogEntry) Errorf

func (l *LogEntry) Errorf(f string, v ...interface{})

func (*LogEntry) Flag

func (l *LogEntry) Flag() int

func (*LogEntry) Info

func (l *LogEntry) Info(v ...interface{})

func (*LogEntry) Infof

func (l *LogEntry) Infof(f string, v ...interface{})

func (*LogEntry) Init

func (l *LogEntry) Init()

func (*LogEntry) Level

func (l *LogEntry) Level() int

func (*LogEntry) Prefix

func (l *LogEntry) Prefix() string

func (*LogEntry) SetFlag

func (l *LogEntry) SetFlag(flag int)

func (*LogEntry) SetLevel

func (l *LogEntry) SetLevel(level int)

func (*LogEntry) SetPrefix

func (l *LogEntry) SetPrefix(prefix string)

func (*LogEntry) Warn

func (l *LogEntry) Warn(v ...interface{})

func (*LogEntry) Warnf

func (l *LogEntry) Warnf(f string, v ...interface{})

type Model

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

func (*Model) As

func (model *Model) As(args string) *Model

func (*Model) Begin

func (model *Model) Begin() error

func (*Model) Close

func (model *Model) Close()

func (*Model) Commit

func (model *Model) Commit() error

func (*Model) Count

func (model *Model) Count() (int64, error)

func (*Model) Delete

func (model *Model) Delete() (num int64, err error)

func (*Model) Distinct

func (model *Model) Distinct(args string) *Model

func (*Model) Exec

func (model *Model) Exec(sql string, args ...interface{}) (sql.Result, error)

func (*Model) Fetch

func (model *Model) Fetch() (map[string]interface{}, error)

func (*Model) FetchAll

func (model *Model) FetchAll() ([]map[string]interface{}, error)

func (*Model) Fields

func (model *Model) Fields(args ...string) *Model

func (*Model) Find

func (model *Model) Find(s interface{}) error

func (*Model) First

func (model *Model) First(i interface{}) error

func (*Model) FullJoin

func (model *Model) FullJoin(table, condition string) *Model

func (*Model) GroupBy

func (model *Model) GroupBy(args string) *Model

func (*Model) Id

func (model *Model) Id(args interface{}) *Model

func (*Model) Init

func (model *Model) Init()

func (*Model) Insert

func (model *Model) Insert(args interface{}) (id int64, err error)

func (*Model) Join

func (model *Model) Join(table, condition string) *Model

func (*Model) LeftJoin

func (model *Model) LeftJoin(table, condition string) *Model

func (*Model) Limit

func (model *Model) Limit(args ...int) *Model

func (*Model) MultiInsert added in v0.1.4

func (model *Model) MultiInsert(args interface{}) (int64, error)

func (*Model) OrWhere

func (model *Model) OrWhere(args ...interface{}) *Model

func (*Model) OrderBy

func (model *Model) OrderBy(args string) *Model

func (*Model) Query

func (model *Model) Query(sql string, args ...interface{}) ([]map[string]interface{}, error)

func (*Model) RightJoin

func (model *Model) RightJoin(table, condition string) *Model

func (*Model) Rollback

func (model *Model) Rollback() error

func (*Model) SetPk

func (model *Model) SetPk(pk string) *Model

func (*Model) Table

func (model *Model) Table(args string) *Model

func (*Model) Update

func (model *Model) Update(args interface{}) (n int64, err error)

func (*Model) Where

func (model *Model) Where(args ...interface{}) *Model

func (*Model) WhereIn

func (model *Model) WhereIn(field string, values interface{}) *Model

func (*Model) WhereNotIn

func (model *Model) WhereNotIn(field string, values interface{}) *Model

func (*Model) WhereRaw

func (model *Model) WhereRaw(args string) *Model

type Options

type Options struct {
	User         string
	Password     string
	Host         string
	Port         int
	Database     string
	Charset      string
	MaxIdleConns int
	MaxOpenConns int
	Debug        bool
}

type Statement

type Statement struct {
	TableName string
	// contains filtered or unexported fields
}

func (*Statement) As

func (statement *Statement) As(args string) *Statement

func (*Statement) CustomError

func (statement *Statement) CustomError(msg string, f, c int, flag ...bool)

func (*Statement) Distinct

func (statement *Statement) Distinct(args string) *Statement

func (*Statement) Error

func (statement *Statement) Error(msg string, flag ...bool)

func (*Statement) Fileds

func (statement *Statement) Fileds(args ...string) *Statement

func (*Statement) FullJoin

func (statement *Statement) FullJoin(table, condition string) *Statement

func (*Statement) GroupBy

func (statement *Statement) GroupBy(args string) *Statement

func (*Statement) Init

func (statement *Statement) Init()

func (*Statement) Join

func (statement *Statement) Join(table, condition string) *Statement

func (*Statement) LeftJoin

func (statement *Statement) LeftJoin(table, condition string) *Statement

func (*Statement) Limit

func (statement *Statement) Limit(args ...int) *Statement

func (*Statement) OrWhere

func (statement *Statement) OrWhere(args ...interface{}) *Statement

func (*Statement) OrderBy

func (statement *Statement) OrderBy(args string) *Statement

func (*Statement) RightJoin

func (statement *Statement) RightJoin(table, condition string) *Statement

func (*Statement) SetPk

func (statement *Statement) SetPk(pk string) *Statement

func (*Statement) Table

func (statement *Statement) Table(table string) *Statement

func (*Statement) Trace

func (statement *Statement) Trace() (file string, line int, function string)

func (*Statement) Where

func (statement *Statement) Where(args ...interface{}) *Statement

func (*Statement) WhereIn

func (statement *Statement) WhereIn(field string, values interface{}) *Statement

func (*Statement) WhereNotIn

func (statement *Statement) WhereNotIn(field string, values interface{}) *Statement

func (*Statement) WhereRaw

func (statement *Statement) WhereRaw(args string) *Statement

Jump to

Keyboard shortcuts

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