orm

package module
v0.0.0-...-f41d1a7 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2015 License: MIT Imports: 13 Imported by: 0

README

##About

server-nado/orm

一个数据库ORM.

How to use?

Insert

go get github.com/server-nado/orm

Super database

sqlite3 "github.com/mattn/go-sqlite3" mysql "github.com/go-sql-driver/mysql" postgree "github.com/lib/pq"

##数据库DBHook 建立方法

//引用模块
import "github.com/server-nado/orm"

//mysql 驱动
import _ "github.com/go-sql-driver/mysql"

//建立连接 
// 参数分别为 名称 , 驱动, 连接字符串
// 注:必须包含一个default 连接, 作为默认连接。
orm.NewDatabase("default" , "mysql" , "user:passwd@ip/database?charset=utf8&parseTime=true")



//建立一个数据模型。 
type UserInfo struct**** {
	orm.DBHook
	Id int64 `field:"id" auto:"true" index:"pk"`
	Name string `field:"username"`
	Passwd string `field:"password"`
}



//读写分离:
orm.NewDatabase("write-conname" , "mysql" , "user:passwd@tcp(ip:port)/database?charset=utf8&parseTime=true")
orm.NewDatabase("read-conname" , "mysql" , "user:passwd@tcp(ip:port)/database?charset=utf8&parseTime=true")
orm.SetWriteConnectName("write-conname")
orm.SetReadConnectName("read-conname")



//Cache  (Redis)

orm.AddCacheAddress("127.0.0.1:6379","PASSWD") //缓存服务器地址 

更多信息>>

##新增 CacheHook 模型, 支持分布式redis作为数据库缓存。

import "github.com/server-nado/orm"
import _ "github.com/go-sql-driver/mysql"

type userB struct {
	orm.CacheHook
	Uid     int64  `field:"Id" index:"pk" cache:"user" `
	Alias   string `field:"Alias"`
	Money int64  `field:"money"	`
}

func main(){
	orm.AddCacheAddress("127.0.0.1:6379",PASSWD)  //添加多个redis服务器
	orm.SetCachePrefix("nado") //默认nado .  将作为redis key 的前缀
	orm.NewDatabase("default", "mysql", "happy:passwd@tcp(127.0.0.1:3306)/mydatabase?charset=utf8&parseTime=true")
	
	orm.SetCachePrefix("nado")  //cache 前缀。 
	orm.SetDebug(false)   //true 是否开启调试模式



	b := new(userB)
	b.Uid = 10000
	err:=b.Objects(b).One()
	if err!= nil {
		panic(err)
	}
	fmt.Println(b.Uid ,b.Alias ,b.Money)

	b.Incrby("Money" , 100)
	fmt.Println(b.Money)
	b.Save() //不执行不会保存到数据库 只会修改redis数据。 

    //查询id小于10的所有数据
    user := new(userB)
    users := []*userB{}
    if err := user.Objects(user).Filter("Uid__lt",10).All(&users); err == nil{
        for _,u:= range users{
            fmt.Println(u.Uid , u.Alias)
        }
    }
}

##一些说明, 这个ORM的目的:

  1. 简化数据库操作方式
  2. 降低数据库的操作压力

比较适合出现频繁,高性能要求的数据库读写操作。 使用CacheHook 模式操作数据时, 大多数情况下,热数据会被导入到缓存,这样的情况下, mysql的度频率会降低,读速度会提高很多,同时, 使用Set或者Incry等方式修改数据, 写速度会大大提升。

Documentation

Overview

Package consistent provides a consistent hashing function.

Consistent hashing is often used to distribute requests to a changing set of servers. For example, say you have some cache servers cacheA, cacheB, and cacheC. You want to decide which cache server to use to look up information on a user.

You could use a typical hash table and hash the user id to one of cacheA, cacheB, or cacheC. But with a typical hash table, if you add or remove a server, almost all keys will get remapped to different results, which basically could bring your service to a grinding halt while the caches get rebuilt.

With a consistent hash, adding or removing a server drastically reduces the number of keys that get remapped.

Read more about consistent hashing on wikipedia: http://en.wikipedia.org/wiki/Consistent_hashing

Index

Constants

This section is empty.

Variables

View Source
var (
	CacheServer = map[string]Cache{}
)
View Source
var Debug = log.New(os.Stdout, "ORM-DEBUG ", log.Lshortfile|log.LstdFlags)
View Source
var ErrDoesNotExist = errors.New("DoesNotExist")
View Source
var ErrEmptyCircle = errors.New("empty circle")

ErrEmptyCircle is the error returned when trying to get an element when nothing has been added to hash.

View Source
var (
	ErrKeyNotExist = errors.New("keys not exists")
)
View Source
var Error = log.New(os.Stdout, "ORM-ERROR ", log.Lshortfile|log.LstdFlags)
View Source
var NULL_LIMIT = [2]int{0, 0}
View Source
var OpenSyncDelete = false
View Source
var OpenSyncUpdate = false
View Source
var Pool *redis.Pool = nil
View Source
var SqlSyncHook = make(chan string, 1000)

Functions

func AddCacheAddress

func AddCacheAddress(address, password string)

设置 cache 地址

func DelCacheAddress

func DelCacheAddress(key string)

func GetCachePrefix

func GetCachePrefix() []byte

func NewMarsharlDriverSql

func NewMarsharlDriverSql(driverName string, fun driversqlType)

func SetCacheAddress

func SetCacheAddress(keys []string, password string)

func SetCachePrefix

func SetCachePrefix(str string)

func SetCacheWithPool

func SetCacheWithPool(pool *redis.Pool)

func SetDebug

func SetDebug(b bool)

func SetDefaultCacheDb

func SetDefaultCacheDb(db int)

func SetReadConnectName

func SetReadConnectName(name string)

读数据库名称 默认default

func SetWriteConnectName

func SetWriteConnectName(name string)

写数据库名称 默认default

func UseHashCache

func UseHashCache(b bool)

Types

type Cache

type Cache interface {
	Set(key string, b []byte) error
	Get(key string) ([]byte, error)
	Keys(key string) ([]string, error)
	//Incy(key string) (int64, error)
	Incrby(key string, n int64) (int64, error)
	Hset(key, field string, b []byte) (bool, error)
	Hmset(key string, maping interface{}) error
	Hget(key, field string) ([]byte, error)
	Hincrby(key, filed string, n int64) (int64, error)
	Exists(key string) (bool, error)
	Del(key string) (bool, error)
	// contains filtered or unexported methods
}

func GetCacheClient

func GetCacheClient(key string) Cache

func GetCacheConn

func GetCacheConn(key interface{}) (address string, c Cache)

func GetCachePool

func GetCachePool() Cache

type CacheHook

type CacheHook struct {
	Cache
	DBHook
	Object *DBHook

	CacheFileds []string
	CacheNames  []string
	// contains filtered or unexported fields
}

func (*CacheHook) All

func (self *CacheHook) All(out interface{}) error

func (*CacheHook) AllOnCache

func (self *CacheHook) AllOnCache(out interface{}) error

func (*CacheHook) Ca

func (self *CacheHook) Ca(key interface{}) *CacheHook

func (*CacheHook) Count

func (self *CacheHook) Count() (int64, error)

func (*CacheHook) CountOnCache

func (self *CacheHook) CountOnCache() (int64, error)

func (*CacheHook) Db

func (self *CacheHook) Db(name string) *CacheHook

func (*CacheHook) Delete

func (self *CacheHook) Delete() (err error)

func (*CacheHook) DeleteOnCache

func (self *CacheHook) DeleteOnCache() error

func (*CacheHook) Filter

func (self *CacheHook) Filter(name string, val interface{}) *CacheHook

func (*CacheHook) GetCacheKey

func (self *CacheHook) GetCacheKey() string

func (*CacheHook) Incrby

func (self *CacheHook) Incrby(key string, val int64) (ret int64, err error)

func (*CacheHook) Incry

func (self *CacheHook) Incry(key string) (val int64, err error)

func (*CacheHook) Limit

func (self *CacheHook) Limit(page, step int) *CacheHook

func (*CacheHook) Objects

func (self *CacheHook) Objects(mode Module, param ...string) *CacheHook

func (*CacheHook) One

func (self *CacheHook) One() error

func (*CacheHook) OneOnCache

func (self *CacheHook) OneOnCache() error

func (*CacheHook) Orderby

func (self *CacheHook) Orderby(order ...string) *CacheHook

func (*CacheHook) Query

func (self *CacheHook) Query() (Rows, error)

func (*CacheHook) Save

func (self *CacheHook) Save() (isnew bool, id int64, err error)

func (CacheHook) SaveToCache

func (self CacheHook) SaveToCache() error

func (*CacheHook) Set

func (self *CacheHook) Set(key string, value interface{}) (err error)

type CacheModule

type CacheModule struct{ CacheHook }

type CacheRows

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

func (*CacheRows) Close

func (self *CacheRows) Close() error

func (*CacheRows) Next

func (self *CacheRows) Next() bool

func (*CacheRows) Scan

func (self *CacheRows) Scan(mode Module) error

type Consistent

type Consistent struct {
	NumberOfReplicas int

	sync.RWMutex
	// contains filtered or unexported fields
}

Consistent holds the information about the members of the consistent hash circle.

func NewConsistent

func NewConsistent() *Consistent

New creates a new Consistent object with a default setting of 20 replicas for each entry.

To change the number of replicas, set NumberOfReplicas before adding entries.

func (*Consistent) Add

func (c *Consistent) Add(elt string)

Add inserts a string element in the consistent hash.

func (*Consistent) Get

func (c *Consistent) Get(name string) (string, error)

Get returns an element close to where name hashes to in the circle.

func (Consistent) GetCircle

func (c Consistent) GetCircle() map[uint32]string

func (*Consistent) GetN

func (c *Consistent) GetN(name string, n int) ([]string, error)

GetN returns the N closest distinct elements to the name input in the circle.

func (*Consistent) GetTwo

func (c *Consistent) GetTwo(name string) (string, string, error)

GetTwo returns the two closest distinct elements to the name input in the circle.

func (*Consistent) Members

func (c *Consistent) Members() []string

func (*Consistent) Remove

func (c *Consistent) Remove(elt string)

Remove removes an element from the hash.

func (*Consistent) Set

func (c *Consistent) Set(elts []string)

Set sets all the elements in the hash. If there are existing elements not present in elts, they will be removed.

type DBHook

type DBHook struct {
	sync.RWMutex
	Params
	// contains filtered or unexported fields
}

func (*DBHook) All

func (self *DBHook) All(out interface{}) error

查找数据

func (*DBHook) Change

func (self *DBHook) Change(name string, val interface{}) *DBHook

func (*DBHook) Count

func (self *DBHook) Count() (int64, error)

计算数量

func (*DBHook) Db

func (self *DBHook) Db(name string) *DBHook

选择数据库

func (*DBHook) Delete

func (self *DBHook) Delete() (int64, error)

删除数据

func (*DBHook) DoesNotExist

func (self *DBHook) DoesNotExist() error

func (*DBHook) Existed

func (self *DBHook) Existed() *DBHook

func (*DBHook) Field

func (self *DBHook) Field(name string) reflect.Value

func (*DBHook) Filter

func (self *DBHook) Filter(name string, val interface{}) *DBHook

条件筛选 name 结构字段名称 val 需要过滤的数据值

func (*DBHook) FilterOr

func (self *DBHook) FilterOr(name string, val interface{}) *DBHook

func (*DBHook) Filters

func (self *DBHook) Filters(filters map[string]interface{}) *DBHook

Filter 的一次传入版本 , 不建议使用 , 因为map 循序不可控

func (*DBHook) Limit

func (self *DBHook) Limit(page, steq int) *DBHook

分页支持

func (*DBHook) Objects

func (self *DBHook) Objects(mode Module, params ...string) *DBHook

func (*DBHook) One

func (self *DBHook) One() error

提取一个数据

func (*DBHook) Orderby

func (self *DBHook) Orderby(names ...string) *DBHook

Order by 排序 , Field__asc Field__desc

func (*DBHook) Query

func (self *DBHook) Query() (Rows, error)

func (*DBHook) Save

func (self *DBHook) Save() (bool, int64, error)

更新活添加

func (*DBHook) Set

func (self *DBHook) Set(name string, val interface{}) *DBHook

修改数据 name 结构字段名称 val 结构数据

type Database

type Database struct {
	*sql.DB
	Name           string
	DriverName     string
	DataSourceName string
}

func NewDatabase

func NewDatabase(name, driverName, dataSourceName string) (database *Database, err error)

func (*Database) Conn

func (self *Database) Conn() (err error)

type FuncParam

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

type ModeRows

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

func (*ModeRows) Close

func (self *ModeRows) Close() error

func (*ModeRows) Next

func (self *ModeRows) Next() bool

func (*ModeRows) Scan

func (self *ModeRows) Scan(mode Module) (err error)

type Module

type Module interface {
	GetTableName() string
}

type ModuleToSql

type ModuleToSql interface {
	Select() (sql string, val []interface{})
	Delete() (sql string, val []interface{})
	Update() (sql string, val []interface{})
	Insert() (sql string, val []interface{})
	Count() (sql string, val []interface{})
	Instance(ParamsInterface)
}

type MysqlModeToSql

type MysqlModeToSql struct {
	Params ParamsInterface
}

func (MysqlModeToSql) Count

func (self MysqlModeToSql) Count() (sql string, val []interface{})

func (MysqlModeToSql) Delete

func (self MysqlModeToSql) Delete() (sql string, val []interface{})

func (MysqlModeToSql) Insert

func (self MysqlModeToSql) Insert() (sql string, val []interface{})

func (MysqlModeToSql) Instance

func (self MysqlModeToSql) Instance(param ParamsInterface)

func (MysqlModeToSql) Select

func (self MysqlModeToSql) Select() (sql string, val []interface{})

func (MysqlModeToSql) Update

func (self MysqlModeToSql) Update() (sql string, val []interface{})

type Object

type Object struct{ DBHook }

type Params

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

*

传参解析

*

func (*Params) All

func (self *Params) All() (rows *sql.Rows, err error)

func (*Params) Change

func (self *Params) Change(name string, val interface{})

添加修改

func (*Params) Count

func (self *Params) Count() (int64, error)

func (*Params) Db

func (self *Params) Db(name string) *Params

func (*Params) Delete

func (self *Params) Delete() (res sql.Result, err error)

func (*Params) Filter

func (self *Params) Filter(name string, val interface{}) *Params

func (*Params) FilterOr

func (self *Params) FilterOr(name string, val interface{}) *Params

func (Params) GetFields

func (self Params) GetFields() []string

func (Params) GetLimit

func (self Params) GetLimit() [2]int

func (Params) GetOr

func (self Params) GetOr() []ParmaField

func (Params) GetOrLen

func (self Params) GetOrLen() int

func (Params) GetOrder

func (self Params) GetOrder() []string

func (Params) GetSet

func (self Params) GetSet() []ParmaField

func (Params) GetSetLen

func (self Params) GetSetLen() int

func (Params) GetTableName

func (self Params) GetTableName() string

func (Params) GetWhere

func (self Params) GetWhere() []ParmaField

func (Params) GetWhereLen

func (self Params) GetWhereLen() int

func (*Params) Init

func (self *Params) Init()

func (*Params) Limit

func (self *Params) Limit(page, step int) *Params

func (*Params) One

func (self *Params) One(vals ...interface{}) error

func (*Params) Save

func (self *Params) Save() (bool, int64, error)

func (*Params) SetField

func (self *Params) SetField(fields ...string)

func (*Params) SetTable

func (self *Params) SetTable(tbname string)

type ParamsInterface

type ParamsInterface interface {
	GetOrLen() int
	GetWhereLen() int
	GetSetLen() int
	GetOr() []ParmaField
	GetWhere() []ParmaField
	GetSet() []ParmaField
	GetFields() []string
	GetOrder() []string
	GetLimit() [2]int
	GetTableName() string
}

type ParmaField

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

type PostgressModeToSql

type PostgressModeToSql struct {
	Params ParamsInterface
}

func (PostgressModeToSql) Count

func (self PostgressModeToSql) Count() (sql string, val []interface{})

func (PostgressModeToSql) Delete

func (self PostgressModeToSql) Delete() (sql string, val []interface{})

func (PostgressModeToSql) Insert

func (self PostgressModeToSql) Insert() (sql string, val []interface{})

func (PostgressModeToSql) Instance

func (self PostgressModeToSql) Instance(param ParamsInterface)

func (PostgressModeToSql) Select

func (self PostgressModeToSql) Select() (sql string, val []interface{})

func (PostgressModeToSql) Update

func (self PostgressModeToSql) Update() (sql string, val []interface{})

type RedisCache

type RedisCache struct {
	*redis.Pool
}

func NewRedisCache

func NewRedisCache(REDIS_HOST, PASSWD string) *RedisCache

新建 Redis 连接

func NewRedisCacheWithRedisPool

func NewRedisCacheWithRedisPool(pool *redis.Pool) *RedisCache

func (*RedisCache) ConnGet

func (c *RedisCache) ConnGet() redis.Conn

func (*RedisCache) Del

func (c *RedisCache) Del(key string) (bool, error)

func (*RedisCache) Exists

func (c *RedisCache) Exists(key string) (bool, error)

func (*RedisCache) Get

func (c *RedisCache) Get(key string) ([]byte, error)

func (*RedisCache) Hget

func (c *RedisCache) Hget(key, field string) ([]byte, error)

func (*RedisCache) Hincrby

func (c *RedisCache) Hincrby(key, field string, n int64) (int64, error)

func (*RedisCache) Hmset

func (c *RedisCache) Hmset(key string, maping interface{}) (err error)

func (*RedisCache) Hset

func (c *RedisCache) Hset(key, field string, b []byte) (bool, error)

func (*RedisCache) Incrby

func (c *RedisCache) Incrby(key string, n int64) (int64, error)

func (*RedisCache) Keys

func (c *RedisCache) Keys(key string) (keys []string, err error)

func (*RedisCache) Set

func (c *RedisCache) Set(key string, b []byte) (err error)

type Rows

type Rows interface {
	Next() bool
	Scan(Module) error
	Close() error
}

type SqliteModeToSql

type SqliteModeToSql struct {
	Params ParamsInterface
}

func (SqliteModeToSql) Count

func (self SqliteModeToSql) Count() (sql string, val []interface{})

func (SqliteModeToSql) Delete

func (self SqliteModeToSql) Delete() (sql string, val []interface{})

func (SqliteModeToSql) Insert

func (self SqliteModeToSql) Insert() (sql string, val []interface{})

func (SqliteModeToSql) Instance

func (self SqliteModeToSql) Instance(param ParamsInterface)

func (SqliteModeToSql) Select

func (self SqliteModeToSql) Select() (sql string, val []interface{})

func (SqliteModeToSql) Update

func (self SqliteModeToSql) Update() (sql string, val []interface{})

Jump to

Keyboard shortcuts

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