gorose

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2019 License: MIT Imports: 13 Imported by: 43

README

GoRose ORM

GoDoc Go Report Card Gitter gorose-orm

  _______   ______   .______        ______        _______. _______ 
 /  _____| /  __  \  |   _  \      /  __  \      /       ||   ____|
|  |  __  |  |  |  | |  |_)  |    |  |  |  |    |   (----`|  |__   
|  | |_ | |  |  |  | |      /     |  |  |  |     \   \    |   __|  
|  |__| | |  `--'  | |  |\  \----.|  `--'  | .----)   |   |  |____ 
 \______|  \______/  | _| `._____| \______/  |_______/    |_______|
中文-readme | english-readme
What is GoRose?

GoRose, a mini database ORM for golang, which inspired by the famous php framwork laravel's eloquent. It will be friendly for php developers and python or ruby developers.
Currently provides five major database drivers:

1.0.0 update notes
  • struct support
  • seperation of write & read cluster
  • New architecture
Documentation

latest document | 最新中文文档
0.x version english document | 0.x版本中文文档
github

Quick Preview
type users struct {
	Name string
	Age int `orm:"age"`
}

// select * from users where id=1 limit 1
var user users      // a row data
var users []users   // several rows
// use struct
db.Table(&user).Select()
db.Table(&users).Where("id",1).Limit(10).Select()
// use string instead of struct
db.Table("users").Where("id",1).First()

// select id as uid,name,age from users where id=1 order by id desc limit 10
db.Table(&user).Where("id",1).Fields("id as uid,name,age").Order("id desc").Limit(10).Get()

// query string
db.Query("select * from user limit 10")
db.Execute("update users set name='fizzday' where id=?", 1)
Features
  • Chain Operation
  • Connection Pool
  • struct/string compatible
  • read/write separation cluster
  • process a lot of data into slices
  • transaction easily
  • friendly for extended (extend more builders or config parsers)
Installation
  • standard:
go get -u github.com/gohouse/gorose
Base Usage
package main

import (
	"github.com/gohouse/gorose"
	_ "github.com/gohouse/gorose/driver/mysql"
	"fmt"
)

type Users struct {
	Name string
	Age  int `orm:"age"`
}

// DB Config.(Recommend to use configuration file to import)
var dbConfig = &gorose.DbConfigSingle{
    Driver:          "mysql", // driver: mysql/sqlite/oracle/mssql/postgres
    EnableQueryLog:  true,    // if enable sql logs
    SetMaxOpenConns: 0,       // connection pool of max Open connections, default zero
    SetMaxIdleConns: 0,       // connection pool of max sleep connections
    Prefix:          "",      // prefix of table
    Dsn:             "root:root@tcp(localhost:3306)/test?charset=utf8", // db dsn
}

func main() {
	connection, err := gorose.Open(dbConfig)
	if err != nil {
		fmt.Println(err)
		return
	}
	// start a new session
	session := connection.NewSession()
	// get a row of data
	var user Users
	err2 := session.Table(&user).Select()
	if err2 != nil {
		fmt.Println(err2)
		return
	}
	fmt.Println(session.LastSql)
	fmt.Println(user)
	
	// get several rows of data
	var users []Users
	// use connection derictly instead of NewSession()
	err3 := connection.Table(&users).Limit(3).Select()
	if err3 != nil {
		fmt.Println(err3)
		return
	}
	fmt.Println(users)
}

For more usage, please read the Documentation.

Contribution
Contributors
  • fizzday : Initiator
  • wuyumin : pursuing the open source standard
  • holdno : official website builder
  • LazyNeo : bug fix and improve source code
  • dmhome : improve source code
release notes

v1.0.4

  • add middleware support, add logger cors

v1.0.3

  • add version get by const: gorose.VERSION

v1.0.2

  • improve go mod's bug

1.0.0

  • New architecture, struct support, seperation of write & read cluster

0.9.2

  • new connection pack for supporting multi connection

0.9.1

  • replace the insert result lastInsertId with rowsAffected as default

0.9.0

  • new seperate db instance

0.8.2

  • improve config format, new config format support file config like json/toml etc.

0.8.1

  • improve multi connection and nulti transation

0.8.0

  • add connection pool
  • adjust dir for open source standard
  • add glide version control
  • translate for english and chinese docment
License

MIT

Documentation

Index

Constants

View Source
const (
	VERSION_TEXT = "\ngolang orm of gorose's version : "
	VERSION_NO   = "1.0.4"
	VERSION      = VERSION_TEXT + VERSION_NO + GOROSE_IMG
)
View Source
const GOROSE_IMG = `` /* 772-byte string literal not displayed */

Variables

This section is empty.

Functions

func BootLogger added in v1.0.4

func BootLogger() func(*Connection)

func NewBuilder

func NewBuilder(ormApi across.OrmApi, operType ...string) (string, error)

NewBuilder : sql构造器

func NewLogger added in v1.0.4

func NewLogger() func(*Connection)

func NewTableToStruct added in v1.0.5

func NewTableToStruct(c *Connection) *converter.Table2Struct

Types

type Connection

type Connection struct {
	DbConfig *DbConfigCluster
	Db       sqlDb
	Logger   cors.LoggerHandler // 持久化sql日志,如果为空则不持久化
}

func NewConnection

func NewConnection() *Connection

func Open

func Open(args ...interface{}) (*Connection, error)

Open 链接数据库入口, 传入配置 args 接收一个或2个参数, 一个参数时:struct配置文件(across.DbConfigCluster{})

两个参数时: 第一个是驱动或文件类型, 第二个是dsn或文件路径

func (*Connection) Close

func (conn *Connection) Close() error

Close database

func (*Connection) Execute

func (c *Connection) Execute(arg string, params ...interface{}) (int64, error)

func (*Connection) GetExecuteDb

func (c *Connection) GetExecuteDb() *sql.DB

func (*Connection) GetQueryDb

func (c *Connection) GetQueryDb() (db *sql.DB)

func (*Connection) NewSession

func (c *Connection) NewSession() *Session

func (*Connection) Query

func (c *Connection) Query(arg string, params ...interface{}) ([]map[string]interface{}, error)

func (*Connection) Table

func (c *Connection) Table(arg interface{}) *Session

func (*Connection) Use added in v1.0.4

func (conn *Connection) Use(options ...func(*Connection)) *Connection

Use : cors

type DbConfigCluster

type DbConfigCluster struct {
	Slave  []*DbConfigSingle // 多台读服务器, 如果启用则需要放入对应的多台从服务器配置
	Master *DbConfigSingle   // 一台主服务器负责写数据
}

数据库集群配置 如果不启用集群, 则直接使用 DbConfig 即可 如果仍然使用此配置为非集群, 则 Slave 配置置空即可, 等同于使用 DbConfig

func NewDbConfigCluster

func NewDbConfigCluster() *DbConfigCluster

func NewFileParser

func NewFileParser(fileOrDriverType, dsnOrFile string) (*DbConfigCluster, error)

NewFileParser : 配置解析器

type DbConfigSingle

type DbConfigSingle struct {
	Driver          string // 驱动: mysql/sqlite3/oracle/mssql/postgres
	EnableQueryLog  bool   // 是否开启sql日志
	SetMaxOpenConns int    // (连接池)最大打开的连接数,默认值为0表示不限制
	SetMaxIdleConns int    // (连接池)闲置的连接数
	Prefix          string // 表前缀
	Dsn             string // 数据库链接
}

单一数据库配置

type Session

type Session struct {
	across.OrmApi
	Connection *Connection
}

func NewOrm

func NewOrm() *Session

func (*Session) AddFields

func (dba *Session) AddFields(fields ...string) *Session

AddFields : If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the AddFields method:

func (*Session) Avg

func (dba *Session) Avg(avg string) (interface{}, error)

Avg : select avg field

func (*Session) Begin

func (dba *Session) Begin()

func (*Session) BuildSql

func (dba *Session) BuildSql(operType ...string) (string, error)

// BuildSql : build sql string , but not execute sql really // operType : select/insert/update/delete

func (*Session) Chunk

func (dba *Session) Chunk(limit int, callback func([]map[string]interface{}))

Chunk : select chunk more data to piceses block

func (*Session) Commit

func (dba *Session) Commit()

func (*Session) Count

func (dba *Session) Count(args ...string) (int64, error)

Count : select count rows

func (*Session) CrossJoin

func (dba *Session) CrossJoin(args ...interface{}) *Session

CrossJoin : like join , the relation is cross

func (*Session) Data

func (dba *Session) Data(data interface{}) *Session

Data : insert or update data

func (*Session) Decrement

func (dba *Session) Decrement(args ...interface{}) (int64, error)

Decrement : auto Decrement -1 default we can define step (such as 2, 3, 6 ...) if give the second params

func (*Session) Delete

func (dba *Session) Delete() (int64, error)

Delete : delete data

func (*Session) Distinct

func (dba *Session) Distinct() *Session

Distinct : select distinct

func (*Session) Execute

func (dba *Session) Execute(sqlstring string, params ...interface{}) (int64, error)

Execute : query instance of sql.DB.Execute

func (*Session) ExecuteAct

func (dba *Session) ExecuteAct(operType string) (int64, error)

func (*Session) Fields

func (dba *Session) Fields(fields ...string) *Session

Fields : select fields

func (*Session) First

func (dba *Session) First() (result map[string]interface{}, err error)

func (*Session) Force

func (dba *Session) Force(arg ...bool) *Session

Force : delete or update without where condition

func (*Session) Get

func (dba *Session) Get() (result []map[string]interface{}, err error)

func (*Session) Group

func (dba *Session) Group(group string) *Session

Group : select group by

func (*Session) GroupBy

func (dba *Session) GroupBy(group string) *Session

GroupBy : equals Group()

func (*Session) Having

func (dba *Session) Having(having string) *Session

Having : select having

func (*Session) Increment

func (dba *Session) Increment(args ...interface{}) (int64, error)

Increment : auto Increment +1 default we can define step (such as 2, 3, 6 ...) if give the second params we can use this method as decrement with the third param as "-"

func (*Session) InnerJoin

func (dba *Session) InnerJoin(args ...interface{}) *Session

InnerJoin : equals join

func (*Session) Insert

func (dba *Session) Insert() (int64, error)

Insert : insert data and get affected rows

func (*Session) InsertGetId

func (dba *Session) InsertGetId() (int64, error)

insertGetId : insert data and get id

func (*Session) Join

func (dba *Session) Join(args ...interface{}) *Session

Join : select join query

func (*Session) JsonEncode

func (dba *Session) JsonEncode(data interface{}) string

JsonEncode : parse json

func (*Session) LeftJoin

func (dba *Session) LeftJoin(args ...interface{}) *Session

LeftJoin : like join , the relation is left

func (*Session) Limit

func (dba *Session) Limit(limit int) *Session

Limit : select limit

func (*Session) Loop

func (dba *Session) Loop(limit int, callback func([]map[string]interface{}))

Loop : select more data to piceses block from begin

func (*Session) Max

func (dba *Session) Max(max string) (interface{}, error)

Max : select max field

func (*Session) Min

func (dba *Session) Min(min string) (interface{}, error)

Min : select min field

func (*Session) Offset

func (dba *Session) Offset(offset int) *Session

Offset : select offset

func (*Session) OrWhere

func (dba *Session) OrWhere(args ...interface{}) *Session

OrWhere : like where , but the relation is or,

func (*Session) OrWhereBetween

func (dba *Session) OrWhereBetween(field string, arr interface{}) *Session

OrWhereBetween : like WhereNull , the relation is or,

func (*Session) OrWhereIn

func (dba *Session) OrWhereIn(field string, arr interface{}) *Session

OrWhereIn : as WhereIn, the relation is or

func (*Session) OrWhereNotBetween

func (dba *Session) OrWhereNotBetween(field string, arr interface{}) *Session

OrWhereNotBetween : like WhereNotNull , the relation is or,

func (*Session) OrWhereNotIn

func (dba *Session) OrWhereNotIn(field string, arr interface{}) *Session

OrWhereNotIn : as WhereNotIn, the relation is or

func (*Session) OrWhereNotNull

func (dba *Session) OrWhereNotNull(arg string) *Session

OrWhereNotNull : like WhereNotNull , the relation is or,

func (*Session) OrWhereNull

func (dba *Session) OrWhereNull(arg string) *Session

OrWhereNull : like WhereNull , the relation is or,

func (*Session) Order

func (dba *Session) Order(order string) *Session

Order : select order by

func (*Session) OrderBy

func (dba *Session) OrderBy(order string) *Session

OrderBy : equal order

func (*Session) Page

func (dba *Session) Page(page int) *Session

Page : select page

func (*Session) ParseTable

func (dba *Session) ParseTable() error

func (*Session) Pluck

func (dba *Session) Pluck(args ...string) (interface{}, error)

Pluck : Retrieving A List Of Column Values

func (*Session) Query

func (dba *Session) Query(sqlstring string, params ...interface{}) (result []map[string]interface{}, errs error)

Query : query instance of sql.DB.Query

func (*Session) Reset

func (dba *Session) Reset(source string)

Reset : reset union select

func (*Session) ResetWhere

func (dba *Session) ResetWhere()

ResetWhere : in transaction, when you need update several tables in difference condition

func (*Session) RightJoin

func (dba *Session) RightJoin(args ...interface{}) *Session

RightJoin : like join , the relation is right

func (*Session) Rollback

func (dba *Session) Rollback()

func (*Session) Scan

func (dba *Session) Scan(rows *sql.Rows) (result []map[string]interface{}, err error)

func (*Session) ScanAll

func (dba *Session) ScanAll(rows *sql.Rows, dst interface{}) error

ScanAll scans all sql result rows into a slice of structs. It reads all rows and closes rows when finished. dst should be a pointer to a slice of the appropriate type. The new results will be appended to any existing data in dst.

func (*Session) ScanMap

func (dba *Session) ScanMap(rows *sql.Rows) (result []map[string]interface{}, err error)

func (*Session) ScanRow

func (dba *Session) ScanRow(rows *sql.Rows, dst interface{}) error

scan a single row of data into a struct.

func (*Session) Select

func (dba *Session) Select() (err error)

func (*Session) Skip

func (dba *Session) Skip(offset int) *Session

Skip : select offset

func (*Session) Sum

func (dba *Session) Sum(sum string) (interface{}, error)

Sum : select sum field

func (*Session) Table

func (dba *Session) Table(arg interface{}) *Session

func (*Session) Take

func (dba *Session) Take(limit int) *Session

Take : select limit

func (*Session) Transaction

func (dba *Session) Transaction(closure func() error) error

Transaction : is a simple usage of trans

func (*Session) UnionAct

func (dba *Session) UnionAct(union, field string) (interface{}, error)

UnionAct : build union select real

func (*Session) UnionJoin

func (dba *Session) UnionJoin(args ...interface{}) *Session

UnionJoin : like join , the relation is union

func (*Session) Update

func (dba *Session) Update() (int64, error)

Update : update data

func (*Session) Value

func (dba *Session) Value(arg string) (interface{}, error)

Value : If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:

func (*Session) Where

func (dba *Session) Where(args ...interface{}) *Session

Where : query or execute where condition, the relation is and

func (*Session) WhereBetween

func (dba *Session) WhereBetween(field string, arr interface{}) *Session

WhereBetween : a column's value is between two values:

func (*Session) WhereIn

func (dba *Session) WhereIn(field string, arr interface{}) *Session

WhereIn : a given column's value is contained within the given array

func (*Session) WhereNotBetween

func (dba *Session) WhereNotBetween(field string, arr interface{}) *Session

WhereNotBetween : a column's value lies outside of two values:

func (*Session) WhereNotIn

func (dba *Session) WhereNotIn(field string, arr interface{}) *Session

WhereNotIn : the given column's value is not contained in the given array

func (*Session) WhereNotNull

func (dba *Session) WhereNotNull(arg string) *Session

WhereNotNull : like where , where filed is not null,

func (*Session) WhereNull

func (dba *Session) WhereNull(arg string) *Session

WhereNull : like where , where filed is null,

Directories

Path Synopsis
driver

Jump to

Keyboard shortcuts

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