Compare commits

...

61 Commits

Author SHA1 Message Date
dtapps 5f70e83104 - update mod
3 weeks ago
dtapps 8dbbff4a27 - update vendor
1 month ago
dtapps 0ed080ee44 - redis增加url连接
1 month ago
dtapps b99cbca10a - update
2 months ago
dtapps 8238616ab5 - update
2 months ago
dtapps b4cf941dd9 - update vendor
2 months ago
dtapps 1f3831a39c - add vendor
2 months ago
dtapps bb1ce11d98 - update gorm sql
3 months ago
dtapps 0799a47c4d - update mongo
3 months ago
dtapps 986c3d81aa update
5 months ago
李光春 ce71070f19 - update
1 year ago
李光春 2480a2f0fb - delete beego
2 years ago
李光春 7bd2d5fea4 - update
2 years ago
李光春 002b617947 - update redis
2 years ago
李光春 093c682a11 - update type
2 years ago
李光春 a92d63c3fa - update mongo
2 years ago
李光春 fbb0a0ef38 - add type
2 years ago
李光春 cda216ae0e - update mongo
2 years ago
李光春 5cf7e80176 - update mongo
2 years ago
李光春 0b0d3b35ad - update
2 years ago
李光春 3b662a2351 - update
2 years ago
李光春 a383dc98c2 - update BsonTime
2 years ago
李光春 dbcb880465 - update mongo
2 years ago
李光春 284e13594a - update mongo
2 years ago
李光春 f1530064e9 - update mongo
2 years ago
李光春 54ca833aa5 - update mongo
2 years ago
李光春 a184e64f15 - update fun
2 years ago
李光春 37f574b436 - add fun
2 years ago
李光春 c65de2d85b - update mongo
2 years ago
李光春 aa56a7a4eb - update mongo
2 years ago
李光春 f420131a37 - update mongo
2 years ago
李光春 7c835284e1 - update vendor
2 years ago
李光春 83ef4742cb - update gorm
2 years ago
李光春 64404d1295 - update config
2 years ago
李光春 3aa6b9c942 - update json
2 years ago
李光春 bbf1a72f89 - update
2 years ago
李光春 c6f0cf2554 - add beego
2 years ago
李光春 184ce91506 - add redis ReadTimeout
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 36cb324abe - update redis keys
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 38bdd453c7 - update redis
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build is failing Details
2 years ago
李光春 e8c2b726bf - update redis lock
continuous-integration/drone/tag Build is failing Details
continuous-integration/drone/push Build was killed Details
2 years ago
李光春 2f71ce5847 - update redis lock
continuous-integration/drone/tag Build is failing Details
continuous-integration/drone/push Build was killed Details
2 years ago
李光春 981bb39993 - add error
continuous-integration/drone/push Build is failing Details
2 years ago
李光春 30eff780b1 - add error
2 years ago
李光春 841f55a29a - update redis lock
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build is failing Details
2 years ago
李光春 389bd8e65c - update redis
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build is failing Details
2 years ago
李光春 8e27344f05 - update redis
continuous-integration/drone/tag Build is failing Details
continuous-integration/drone/push Build was killed Details
2 years ago
李光春 75a6f160b9 - update redis
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build was killed Details
2 years ago
李光春 6a2d8ffdae - update redis cache
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build was killed Details
2 years ago
李光春 26a28acf7b - update
2 years ago
李光春 3035cd19ef - add redis cache
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 981768b7b0 - update redis
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 c58e6fe761 - update redis
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 388310c804 - update redis
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 6559dff6e2 - update
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 bd8d1252d1 - update get db
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 903ce4cbb2 - update zorm
continuous-integration/drone/push Build was killed Details
continuous-integration/drone/tag Build was killed Details
2 years ago
李光春 3186fe56c6 - update bun
continuous-integration/drone/tag Build is passing Details
continuous-integration/drone/push Build is passing Details
2 years ago
李光春 1a428bfa15 - update gorm
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
2 years ago
李光春 82edf1cf60 - update
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/tag Build is failing Details
2 years ago
李光春 59f6113ff8 - update gorm
continuous-integration/drone/push Build is failing Details
2 years ago

2
.gitignore vendored

@ -7,5 +7,5 @@
*_test.go
*.txt
*.text
gomod.sh
go_mod.sh
/vendor/

@ -1,8 +1,8 @@
<h1>
<a href="https://www.dtapp.net/">Golang Dorm</a>
<a href="https://www.dtapp.net/">Golang</a>
</h1>
📦 Golang Dorm
📦 Golang 数据库
[comment]: <> (go)
[![godoc](https://pkg.go.dev/badge/go.dtapp.net/dorm?status.svg)](https://pkg.go.dev/go.dtapp.net/dorm)
@ -13,5 +13,5 @@
#### 安装
```shell
go get -v -u go.dtapp.net/dorm
go get -v -u go.dtapp.net/dorm@v1.0.59
```

@ -1,16 +0,0 @@
package dorm
import (
"github.com/beego/beego/v2/client/orm"
)
type ConfigBeegoClient struct {
Dns string // 地址
}
// BeegoClient
// https://beego.vip/
type BeegoClient struct {
Db *orm.Ormer // 驱动
config *ConfigBeegoClient // 配置
}

@ -1,29 +0,0 @@
package dorm
import (
"database/sql"
"errors"
"fmt"
"github.com/beego/beego/v2/client/orm"
_ "github.com/go-sql-driver/mysql"
)
func NewBeegoMysqlClient(config *ConfigBeegoClient) (*BeegoClient, error) {
var err error
c := &BeegoClient{config: config}
err = orm.RegisterDriver("mysql", orm.DRMySQL)
if err != nil {
return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err))
}
var db *sql.DB
o, err := orm.NewOrmWithDB("mysql", "default", db)
if err != nil {
return nil, err
}
c.Db = &o
return c, nil
}

@ -1,29 +0,0 @@
package dorm
import (
"database/sql"
"errors"
"fmt"
"github.com/beego/beego/v2/client/orm"
_ "github.com/lib/pq"
)
func NewBeegoOracleClient(config *ConfigBeegoClient) (*BeegoClient, error) {
var err error
c := &BeegoClient{config: config}
err = orm.RegisterDriver("oracle", orm.DROracle)
if err != nil {
return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err))
}
var db *sql.DB
o, err := orm.NewOrmWithDB("oracle", "default", db)
if err != nil {
return nil, err
}
c.Db = &o
return c, nil
}

@ -1,29 +0,0 @@
package dorm
import (
"database/sql"
"errors"
"fmt"
"github.com/beego/beego/v2/client/orm"
_ "github.com/lib/pq"
)
func NewBeegoPgsqlClient(config *ConfigBeegoClient) (*BeegoClient, error) {
var err error
c := &BeegoClient{config: config}
err = orm.RegisterDriver("pgsql", orm.DRPostgres)
if err != nil {
return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err))
}
var db *sql.DB
o, err := orm.NewOrmWithDB("pgsql", "default", db)
if err != nil {
return nil, err
}
c.Db = &o
return c, nil
}

@ -1,29 +0,0 @@
package dorm
import (
"database/sql"
"errors"
"fmt"
"github.com/beego/beego/v2/client/orm"
_ "github.com/lib/pq"
)
func NewBeegoTidbClient(config *ConfigBeegoClient) (*BeegoClient, error) {
var err error
c := &BeegoClient{config: config}
err = orm.RegisterDriver("TiDB", orm.DRTiDB)
if err != nil {
return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err))
}
var db *sql.DB
o, err := orm.NewOrmWithDB("TiDB", "default", db)
if err != nil {
return nil, err
}
c.Db = &o
return c, nil
}

@ -1,16 +0,0 @@
package dorm
import (
"github.com/uptrace/bun"
)
type ConfigBunClient struct {
Dns string // 地址
}
// BunClient
// https://bun.uptrace.dev/
type BunClient struct {
Db *bun.DB // 驱动
config *ConfigBunClient // 配置
}

@ -1,25 +0,0 @@
package dorm
import (
"database/sql"
"errors"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/mssqldialect"
)
func NewBunMssqlClient(config *ConfigBunClient) (*BunClient, error) {
var err error
c := &BunClient{config: config}
sqlDb, err := sql.Open("sqlserver", c.config.Dns)
if err != nil {
return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err))
}
c.Db = bun.NewDB(sqlDb, mssqldialect.New())
return c, nil
}

@ -1,25 +0,0 @@
package dorm
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/mysqldialect"
)
func NewBunMysqlClient(config *ConfigBunClient) (*BunClient, error) {
var err error
c := &BunClient{config: config}
sqlDb, err := sql.Open("mysql", c.config.Dns)
if err != nil {
return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err))
}
c.Db = bun.NewDB(sqlDb, mysqldialect.New())
return c, nil
}

@ -1,19 +0,0 @@
package dorm
import (
"database/sql"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
func NewBunPgsqlClient(config *ConfigBunClient) (*BunClient, error) {
c := &BunClient{config: config}
sqlDb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(c.config.Dns)))
c.Db = bun.NewDB(sqlDb, pgdialect.New())
return c, nil
}

149
go.mod

@ -1,126 +1,57 @@
module go.dtapp.net/dorm
go 1.18
go 1.22.1
require (
gitee.com/chunanyong/dm v1.8.5
gitee.com/chunanyong/zorm v1.5.6
github.com/basgys/goxml2json v1.1.0
github.com/beego/beego/v2 v2.0.4
github.com/bmizerany/pq v0.0.0-20131128184720-da2b95e392c1
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d
github.com/denisenkom/go-mssqldb v0.12.2
github.com/dtapps/go-library/utils/gotime v0.0.0-20220321125442-5750f7eb2ca1
github.com/glebarez/sqlite v1.4.6
github.com/go-redis/redis/v8 v8.11.5
github.com/go-redis/redis/v9 v9.0.0-beta.1
github.com/go-sql-driver/mysql v1.6.0
github.com/godror/godror v0.34.0
github.com/gomodule/redigo v2.0.0+incompatible
github.com/kamva/mgm/v3 v3.4.1
github.com/lib/pq v1.10.5
github.com/mailru/go-clickhouse/v2 v2.0.0
github.com/mattn/go-sqlite3 v1.14.14
github.com/qiniu/qmgo v1.1.1
github.com/rs/xid v1.2.1
github.com/sirupsen/logrus v1.8.1
github.com/upper/db/v4 v4.5.4
github.com/uptrace/bun v1.1.6
github.com/uptrace/bun/dialect/mssqldialect v1.1.6
github.com/uptrace/bun/dialect/mysqldialect v1.1.6
github.com/uptrace/bun/dialect/pgdialect v1.1.6
github.com/uptrace/bun/dialect/sqlitedialect v1.1.6
github.com/uptrace/bun/driver/pgdriver v1.1.6
github.com/uptrace/bun/driver/sqliteshim v1.1.6
go.mongodb.org/mongo-driver v1.9.1
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
gorm.io/driver/mysql v1.3.4
gorm.io/driver/postgres v1.3.7
gorm.io/driver/sqlite v1.3.6
gorm.io/driver/sqlserver v1.3.2
gorm.io/gorm v1.23.8
xorm.io/xorm v1.3.1
github.com/redis/go-redis/v9 v9.5.1
github.com/sirupsen/logrus v1.9.3
go.dtapp.net/gojson v1.0.4
go.dtapp.net/gotime v1.0.8
go.mongodb.org/mongo-driver v1.15.0
gorm.io/driver/mysql v1.5.6
gorm.io/driver/postgres v1.5.7
gorm.io/gen v0.3.26
gorm.io/gorm v1.25.10
)
require (
github.com/bitly/go-simplejson v0.5.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/basgys/goxml2json v1.1.0 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/edsrzf/mmap-go v1.0.0 // indirect
github.com/glebarez/go-sqlite v1.17.3 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/goccy/go-json v0.8.1 // indirect
github.com/godror/knownpb v0.1.0 // indirect
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.12.1 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.3.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.11.0 // indirect
github.com/jackc/pgx/v4 v4.16.1 // indirect
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
github.com/jackc/pgx/v5 v5.5.5 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/klauspost/compress v1.15.6 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/klauspost/compress v1.17.8 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect
github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect
github.com/stretchr/testify v1.7.1 // indirect
github.com/syndtr/goleveldb v1.0.0 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.1 // indirect
github.com/xdg-go/stringprep v1.0.3 // indirect
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.11 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
lukechampine.com/uint128 v1.2.0 // indirect
mellium.im/sasl v0.2.1 // indirect
modernc.org/b v1.0.2 // indirect
modernc.org/cc/v3 v3.36.0 // indirect
modernc.org/ccgo/v3 v3.16.7 // indirect
modernc.org/db v1.0.3 // indirect
modernc.org/file v1.0.3 // indirect
modernc.org/fileutil v1.0.0 // indirect
modernc.org/golex v1.0.1 // indirect
modernc.org/internal v1.0.2 // indirect
modernc.org/libc v1.16.14 // indirect
modernc.org/lldb v1.0.2 // indirect
modernc.org/mathutil v1.4.1 // indirect
modernc.org/memory v1.1.1 // indirect
modernc.org/opt v0.1.3 // indirect
modernc.org/ql v1.4.0 // indirect
modernc.org/sortutil v1.1.0 // indirect
modernc.org/sqlite v1.17.3 // indirect
modernc.org/strutil v1.1.2 // indirect
modernc.org/token v1.0.0 // indirect
modernc.org/zappy v1.0.3 // indirect
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240424034433-3c2c7870ae76 // indirect
golang.org/x/arch v0.7.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/tools v0.20.0 // indirect
gorm.io/datatypes v1.2.0 // indirect
gorm.io/hints v1.1.2 // indirect
gorm.io/plugin/dbresolver v1.5.1 // indirect
)

1015
go.sum

File diff suppressed because it is too large Load Diff

@ -0,0 +1,18 @@
package dorm
import "database/sql"
// Ping ping
func (c *GormClient) Ping() error {
return c.sqlDd.Ping()
}
// Close 关闭
func (c *GormClient) Close() error {
return c.sqlDd.Close()
}
// Stats 返回数据库统计信息
func (c *GormClient) Stats() sql.DBStats {
return c.sqlDd.Stats()
}

@ -1,6 +1,7 @@
package dorm
import (
"database/sql"
"fmt"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
@ -9,34 +10,45 @@ import (
"time"
)
type ConfigGormClient struct {
Dns string // 地址
Log bool // 日志
LogUrl string // 日志路径
// GormClientFun *GormClient 驱动
type GormClientFun func() *GormClient
// GormClientTableFun
// *GormClient 驱动
// string 表名
type GormClientTableFun func() (*GormClient, string)
// GormClientConfig 配置
type GormClientConfig struct {
Dns string // 地址
LogStatus bool // 日志 - 状态
LogPath string // 日志 - 路径
LogSlow int64 // 日志 - 慢SQL阈值
LogLevel string // 日志 - 级别
ConnSetMaxIdle int // 连接 - 设置空闲连接池中连接的最大数量
ConnSetMaxOpen int // 连接 - 设置打开数据库连接的最大数量
ConnSetConnMaxLifetime int64 // 连接 - 设置了连接可复用的最大时间
}
// GormClient
// https://gorm.io/
// https://gorm.io/zh_CN/docs/index.html
type GormClient struct {
Db *gorm.DB // 驱动
config *ConfigGormClient // 配置
}
func (c *GormClient) GetDb() *gorm.DB {
return c.Db
db *gorm.DB // 驱动
config *GormClientConfig // 配置
sqlDd *sql.DB
}
type writer struct{}
// 日志路径
var logsUrl = ""
var logsURL = ""
func (w writer) Printf(format string, args ...interface{}) {
now := time.Now()
logFilePath := ""
if dir, err := os.Getwd(); err == nil {
logFilePath = dir + logsUrl
logFilePath = dir + logsURL
}
if err := os.MkdirAll(logFilePath, 0777); err != nil {
fmt.Println(err.Error())

@ -0,0 +1,8 @@
package dorm
import "gorm.io/gorm"
var (
// GormNotFound 没有数据
GormNotFound = gorm.ErrRecordNotFound
)

@ -0,0 +1,29 @@
package dorm
import (
"gorm.io/gen"
"gorm.io/gorm"
)
// GormGenClientFun *GormClient 驱动
type GormGenClientFun func() *GormGenClient
// GormGenClientTableFun
// *GormClient 驱动
// string 表名
type GormGenClientTableFun func() (*GormGenClient, string)
// GormGenClientConfig 配置
type GormGenClientConfig struct {
Dns string // dns地址
Db *gorm.DB // db驱动
Config gen.Config // gen配置
}
// GormGenClient
// https://gorm.io/zh_CN/gen/index.html
type GormGenClient struct {
db *gorm.DB // 驱动
generator *gen.Generator // 驱动
config *GormGenClientConfig // 配置
}

@ -0,0 +1,16 @@
package dorm
import (
"gorm.io/gen"
"gorm.io/gorm"
)
// GetDb 获取驱动
func (c *GormGenClient) GetDb() *gorm.DB {
return c.db
}
// GetGenerator 获取驱动
func (c *GormGenClient) GetGenerator() *gen.Generator {
return c.generator
}

@ -0,0 +1,25 @@
package dorm
import (
"context"
"gorm.io/driver/mysql"
"gorm.io/gen"
"gorm.io/gorm"
)
// NewGormGenMysqlClient 创建GormGenClient实例 mysql
func NewGormGenMysqlClient(ctx context.Context, config *GormGenClientConfig) (*GormGenClient, error) {
c := &GormGenClient{config: config}
c.generator = gen.NewGenerator(config.Config)
if c.config.Dns != "" {
c.db, _ = gorm.Open(mysql.Open(c.config.Dns), &gorm.Config{})
c.generator.UseDB(c.db)
} else {
c.generator.UseDB(c.config.Db)
}
return c, nil
}

@ -0,0 +1,25 @@
package dorm
import (
"context"
"gorm.io/driver/postgres"
"gorm.io/gen"
"gorm.io/gorm"
)
// NewGormGenPostgresClient 创建GormGenClient实例 postgres
func NewGormGenPostgresClient(ctx context.Context, config *GormGenClientConfig) (*GormGenClient, error) {
c := &GormGenClient{config: config}
c.generator = gen.NewGenerator(config.Config)
if c.config.Dns != "" {
c.db, _ = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
c.generator.UseDB(c.db)
} else {
c.generator.UseDB(c.config.Db)
}
return c, nil
}

@ -0,0 +1,25 @@
package dorm
import (
"context"
"gorm.io/driver/postgres"
"gorm.io/gen"
"gorm.io/gorm"
)
// NewGormGenPostgresqlClient 创建GormGenClient实例 postgresql
func NewGormGenPostgresqlClient(ctx context.Context, config *GormGenClientConfig) (*GormGenClient, error) {
c := &GormGenClient{config: config}
c.generator = gen.NewGenerator(config.Config)
if c.config.Dns != "" {
c.db, _ = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
c.generator.UseDB(c.db)
} else {
c.generator.UseDB(c.config.Db)
}
return c, nil
}

@ -0,0 +1,16 @@
package dorm
import (
"database/sql"
"gorm.io/gorm"
)
// GetDb 获取驱动
func (c *GormClient) GetDb() *gorm.DB {
return c.db
}
// GetSqlDb 获取驱动
func (c *GormClient) GetSqlDb() *sql.DB {
return c.sqlDd
}

@ -1,34 +1,52 @@
package dorm
import (
"context"
"errors"
"fmt"
"github.com/dtapps/go-library/utils/gotime"
"go.dtapp.net/gotime"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) {
// NewGormMysqlClient 创建GormClient实例 mysql
func NewGormMysqlClient(ctx context.Context, config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{config: config}
// 判断路径
if c.config.LogUrl == "" {
logsUrl = "/logs/mysql"
if c.config.LogPath == "" {
logsURL = "/logs/mysql"
} else {
logsURL = c.config.LogPath
}
if c.config.Log == true {
c.Db, err = gorm.Open(mysql.Open(c.config.Dns), &gorm.Config{
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
}
c.db, err = gorm.Open(mysql.Open(c.config.Dns), &gorm.Config{
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
@ -36,21 +54,38 @@ func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) {
},
})
} else {
c.Db, err = gorm.Open(mysql.Open(c.config.Dns), &gorm.Config{})
c.db, err = gorm.Open(mysql.Open(c.config.Dns), &gorm.Config{})
}
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
sqlDB, err := c.Db.DB()
c.sqlDd, err = c.db.DB()
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
return nil, errors.New(fmt.Sprintf("获取通用数据库对象失败:%v", err))
}
sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。
sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。
// 设置空闲连接池中连接的最大数量
if c.config.ConnSetMaxIdle == 0 {
c.sqlDd.SetMaxIdleConns(10)
} else {
c.sqlDd.SetMaxIdleConns(c.config.ConnSetMaxIdle)
}
// 设置打开数据库连接的最大数量
if c.config.ConnSetMaxOpen == 0 {
c.sqlDd.SetMaxOpenConns(100)
} else {
c.sqlDd.SetMaxOpenConns(c.config.ConnSetMaxOpen)
}
// 设置了连接可复用的最大时间
if c.config.ConnSetConnMaxLifetime == 0 {
c.sqlDd.SetConnMaxLifetime(time.Second * 600)
} else {
c.sqlDd.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
}
return c, nil
}

@ -0,0 +1,92 @@
package dorm
import (
"context"
"errors"
"fmt"
"go.dtapp.net/gotime"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
// NewGormPostgresClient 创建GormClient实例 postgres
func NewGormPostgresClient(ctx context.Context, config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{}
c.config = config
// 判断路径
if c.config.LogPath == "" {
logsURL = "/logs/postgresql"
} else {
logsURL = c.config.LogPath
}
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
}
c.db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
return gotime.Current().Now().Local()
},
})
} else {
c.db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
}
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
c.sqlDd, err = c.db.DB()
if err != nil {
return nil, errors.New(fmt.Sprintf("获取通用数据库对象失败:%v", err))
}
// 设置空闲连接池中连接的最大数量
if c.config.ConnSetMaxIdle == 0 {
c.sqlDd.SetMaxIdleConns(10)
} else {
c.sqlDd.SetMaxIdleConns(c.config.ConnSetMaxIdle)
}
// 设置打开数据库连接的最大数量
if c.config.ConnSetMaxOpen == 0 {
c.sqlDd.SetMaxOpenConns(100)
} else {
c.sqlDd.SetMaxOpenConns(c.config.ConnSetMaxOpen)
}
// 设置了连接可复用的最大时间
if c.config.ConnSetConnMaxLifetime == 0 {
c.sqlDd.SetConnMaxLifetime(time.Hour)
} else {
c.sqlDd.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
}
return c, nil
}

@ -1,36 +1,53 @@
package dorm
import (
"context"
"errors"
"fmt"
"github.com/dtapps/go-library/utils/gotime"
"go.dtapp.net/gotime"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) {
// NewGormPostgresqlClient 创建GormClient实例 postgresql
func NewGormPostgresqlClient(ctx context.Context, config *GormClientConfig) (*GormClient, error) {
var err error
c := &GormClient{}
c.config = config
// 判断路径
if c.config.LogUrl == "" {
logsUrl = "/logs/postgresql"
if c.config.LogPath == "" {
logsURL = "/logs/postgresql"
} else {
logsURL = c.config.LogPath
}
var err error
if c.config.Log == true {
c.Db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{
if c.config.LogStatus {
var slowThreshold time.Duration
var logLevel logger.LogLevel
if c.config.LogSlow == 0 {
slowThreshold = 100 * time.Millisecond
} else {
slowThreshold = time.Duration(c.config.LogSlow)
}
if c.config.LogLevel == "Error" {
logLevel = logger.Error
} else if c.config.LogLevel == "Warn" {
logLevel = logger.Warn
} else {
logLevel = logger.Info
}
c.db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印
SlowThreshold: slowThreshold, // 慢SQL阈值
LogLevel: logLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: true, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
@ -38,68 +55,38 @@ func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) {
},
})
} else {
c.Db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
c.db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
}
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
sqlDB, err := c.Db.DB()
c.sqlDd, err = c.db.DB()
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
}
sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。
sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。
return c, nil
}
func NewGormPostgresqlClient(config *ConfigGormClient) (*GormClient, error) {
c := &GormClient{}
c.config = config
// 判断路径
if c.config.LogUrl == "" {
logsUrl = "/logs/postgresql"
return nil, errors.New(fmt.Sprintf("获取通用数据库对象失败:%v", err))
}
var err error
if c.config.Log == true {
c.Db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
return gotime.Current().Now().Local()
},
})
// 设置空闲连接池中连接的最大数量
if c.config.ConnSetMaxIdle == 0 {
c.sqlDd.SetMaxIdleConns(10)
} else {
c.Db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{})
c.sqlDd.SetMaxIdleConns(c.config.ConnSetMaxIdle)
}
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
// 设置打开数据库连接的最大数量
if c.config.ConnSetMaxOpen == 0 {
c.sqlDd.SetMaxOpenConns(100)
} else {
c.sqlDd.SetMaxOpenConns(c.config.ConnSetMaxOpen)
}
sqlDB, err := c.Db.DB()
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
// 设置了连接可复用的最大时间
if c.config.ConnSetConnMaxLifetime == 0 {
c.sqlDd.SetConnMaxLifetime(time.Hour)
} else {
c.sqlDd.SetConnMaxLifetime(time.Duration(c.config.ConnSetConnMaxLifetime))
}
sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。
sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。
return c, nil
}

@ -1,56 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/dtapps/go-library/utils/gotime"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"time"
)
func NewGormSqlServerClient(config *ConfigGormClient) (*GormClient, error) {
var err error
c := &GormClient{config: config}
// 判断路径
if c.config.LogUrl == "" {
logsUrl = "/logs/sqlserver"
}
if c.config.Log == true {
c.Db, err = gorm.Open(sqlserver.Open(c.config.Dns), &gorm.Config{
Logger: logger.New(
writer{},
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印
},
),
NowFunc: func() time.Time {
return gotime.Current().Now().Local()
},
})
} else {
c.Db, err = gorm.Open(sqlserver.Open(c.config.Dns), &gorm.Config{})
}
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
sqlDB, err := c.Db.DB()
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
}
sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。
sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。
return c, nil
}

@ -4,15 +4,15 @@ import "gorm.io/gorm"
// Begin 开始事务,不需要创建 Session 对象
func (c *GormClient) Begin() *gorm.DB {
return c.Db.Begin()
return c.db.Begin()
}
// Rollback 回滚事务
func (c *GormClient) Rollback() *gorm.DB {
return c.Db.Rollback()
return c.db.Rollback()
}
// Commit 提交事务
func (c *GormClient) Commit() *gorm.DB {
return c.Db.Commit()
return c.db.Commit()
}

@ -4,48 +4,56 @@ import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type ConfigMongoClient struct {
// MongoClientFun *MongoClient 驱动
// string 库名
type MongoClientFun func() (*MongoClient, string)
// MongoClientCollectionFun
// *MongoClient 驱动
// string 库名
// string 集合
type MongoClientCollectionFun func() (*MongoClient, string, string)
// MongoClientConfig 实例配置
type MongoClientConfig struct {
Dns string // 地址
Opts *options.ClientOptions
DatabaseName string // 库名
}
// MongoClient 实例
type MongoClient struct {
Db *mongo.Client // 驱动
config *ConfigMongoClient // 配置
databaseName string // 库名
collectionName string // 表名
//filterArr []queryFilter // 查询条件数组
filter bson.D // 查询条件
db *mongo.Client // 驱动
configDatabaseName string // 库名
}
func NewMongoClient(config *ConfigMongoClient) (*MongoClient, error) {
// NewMongoClient 创建实例
func NewMongoClient(ctx context.Context, config *MongoClientConfig) (*MongoClient, error) {
var err error
c := &MongoClient{config: config}
c := &MongoClient{}
c.databaseName = c.config.DatabaseName
c.configDatabaseName = config.DatabaseName
// 连接到MongoDB
if c.config.Dns != "" {
c.Db, err = mongo.Connect(context.Background(), options.Client().ApplyURI(c.config.Dns))
if config.Dns != "" {
c.db, err = mongo.Connect(ctx, options.Client().ApplyURI(config.Dns))
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
} else {
c.Db, err = mongo.Connect(context.Background(), c.config.Opts)
c.db, err = mongo.Connect(ctx, config.Opts)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
}
// 检查连接
err = c.Db.Ping(context.TODO(), nil)
err = c.db.Ping(ctx, nil)
if err != nil {
return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err))
}
@ -54,10 +62,6 @@ func NewMongoClient(config *ConfigMongoClient) (*MongoClient, error) {
}
// Close 关闭
func (c *MongoClient) Close() error {
err := c.Db.Disconnect(context.TODO())
if err != nil {
return errors.New(fmt.Sprintf("关闭失败:%v", err))
}
return nil
func (c *MongoClient) Close(ctx context.Context) error {
return c.db.Disconnect(ctx)
}

@ -1 +0,0 @@
package dorm

@ -0,0 +1,60 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoCollectionOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
dbCollection *mongo.Collection // 集合
}
// Collection 选择集合
func (cd *MongoDatabaseOptions) Collection(name string, opts ...*options.CollectionOptions) *MongoCollectionOptions {
return &MongoCollectionOptions{
db: cd.db, // 驱动
configDatabaseName: cd.configDatabaseName, // 库名
dbCollection: cd.dbDatabase.Collection(name, opts...), // 集合
}
}
// CreateOneIndexes 创建一个索引
func (cc *MongoCollectionOptions) CreateOneIndexes(ctx context.Context, key string, value string) (string, error) {
return cc.dbCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{
Key: key,
Value: value,
}},
})
}
// CreateOneUniqueIndexes 创建一个唯一索引
func (cc *MongoCollectionOptions) CreateOneUniqueIndexes(ctx context.Context, key string, value string) (string, error) {
return cc.dbCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{
Key: key,
Value: value,
}},
Options: options.Index().SetUnique(true),
})
}
// CreateOneUniqueIndexesOpts 创建一个索引
func (cc *MongoCollectionOptions) CreateOneUniqueIndexesOpts(ctx context.Context, key string, value string, opts *options.IndexOptions) (string, error) {
return cc.dbCollection.Indexes().CreateOne(ctx, mongo.IndexModel{
Keys: bson.D{{
Key: key,
Value: value,
}},
Options: opts,
})
}
// CreateManyIndexes 创建多个索引
func (cc *MongoCollectionOptions) CreateManyIndexes(ctx context.Context, models []mongo.IndexModel) ([]string, error) {
return cc.dbCollection.Indexes().CreateMany(ctx, models)
}

@ -0,0 +1,100 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (cc *MongoCollectionOptions) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
return cc.dbCollection.InsertOne(ctx, document, opts...)
}
// InsertMany 插入多个文档
func (cc *MongoCollectionOptions) InsertMany(ctx context.Context, document []interface{}, opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error) {
return cc.dbCollection.InsertMany(ctx, document, opts...)
}
// DeleteOne 删除一个文档
func (cc *MongoCollectionOptions) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return cc.dbCollection.DeleteOne(ctx, filter, opts...)
}
// DeleteMany 删除多个文档
func (cc *MongoCollectionOptions) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return cc.dbCollection.DeleteMany(ctx, filter, opts...)
}
// UpdateByID 按ID更新
func (cc *MongoCollectionOptions) UpdateByID(ctx context.Context, id interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.UpdateByID(ctx, id, update, opts...)
}
// UpdateOne 更新一个文档
func (cc *MongoCollectionOptions) UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.UpdateOne(ctx, filter, update, opts...)
}
// UpdateMany 更新多个文档
func (cc *MongoCollectionOptions) UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.UpdateMany(ctx, filter, update, opts...)
}
// ReplaceOne 替换一个文档
func (cc *MongoCollectionOptions) ReplaceOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error) {
return cc.dbCollection.ReplaceOne(ctx, filter, update, opts...)
}
// Aggregate 统计分析
func (cc *MongoCollectionOptions) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error) {
return cc.dbCollection.Aggregate(ctx, pipeline, opts...)
}
// CountDocuments 计数文档
func (cc *MongoCollectionOptions) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error) {
return cc.dbCollection.CountDocuments(ctx, filter, opts...)
}
// EstimatedDocumentCount 估计文档计数
func (cc *MongoCollectionOptions) EstimatedDocumentCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error) {
return cc.dbCollection.EstimatedDocumentCount(ctx, opts...)
}
func (cc *MongoCollectionOptions) Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error) {
return cc.dbCollection.Distinct(ctx, fieldName, filter, opts...)
}
// Find 查询多个文档
func (cc *MongoCollectionOptions) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error) {
return cc.dbCollection.Find(ctx, filter, opts...)
}
// FindOne 查询一个文档
func (cc *MongoCollectionOptions) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult {
return cc.dbCollection.FindOne(ctx, filter, opts...)
}
func (cc *MongoCollectionOptions) FindOneAndDelete(ctx context.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions) *mongo.SingleResult {
return cc.dbCollection.FindOneAndDelete(ctx, filter, opts...)
}
func (cc *MongoCollectionOptions) FindOneAndReplace(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *mongo.SingleResult {
return cc.dbCollection.FindOneAndReplace(ctx, filter, replacement, opts...)
}
func (cc *MongoCollectionOptions) FindOneAndUpdate(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.FindOneAndUpdateOptions) *mongo.SingleResult {
return cc.dbCollection.FindOneAndUpdate(ctx, filter, replacement, opts...)
}
func (cc *MongoCollectionOptions) Watch(ctx context.Context, pipeline interface{}, opts ...*options.ChangeStreamOptions) (*mongo.ChangeStream, error) {
return cc.dbCollection.Watch(ctx, pipeline, opts...)
}
func (cc *MongoCollectionOptions) Indexes(ctx context.Context) mongo.IndexView {
return cc.dbCollection.Indexes()
}
func (cc *MongoCollectionOptions) Drop(ctx context.Context) error {
return cc.dbCollection.Drop(ctx)
}

@ -1,185 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (c *MongoClient) InsertOne(document interface{}) (result *mongo.InsertOneResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.InsertOne(context.TODO(), document)
return
}
// InsertMany 插入多个文档
func (c *MongoClient) InsertMany(documents []interface{}) (result *mongo.InsertManyResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.InsertMany(context.TODO(), documents)
return
}
// Delete 删除文档
func (c *MongoClient) Delete(filter interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.DeleteOne(context.TODO(), filter)
return
}
// DeleteId 删除文档
func (c *MongoClient) DeleteId(id interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.DeleteOne(context.TODO(), bson.M{"_id": id})
return
}
// DeleteMany 删除多个文档
func (c *MongoClient) DeleteMany(filter interface{}) (result *mongo.DeleteResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.DeleteMany(context.TODO(), filter)
return
}
// UpdateOne 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (c *MongoClient) UpdateOne(filter interface{}, update interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.UpdateOne(context.TODO(), filter, update)
return
}
// UpdateId 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (c *MongoClient) UpdateId(id interface{}, update interface{}) (err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
_, err = collection.UpdateOne(context.TODO(), bson.M{"_id": id}, update)
return
}
// UpdateMany 更新多个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (c *MongoClient) UpdateMany(filter interface{}, update interface{}) (result *mongo.UpdateResult, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.UpdateMany(context.TODO(), filter, update)
return
}
type FindResultI interface {
Many(result interface{}) error
}
// Find 查询
func (c *MongoClient) Find(filter interface{}) (*mongo.Cursor, error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
return collection.Find(context.TODO(), filter)
}
type FindOneResultI interface {
One(result interface{}) error
}
// FindOne 查询单个文档
func (c *MongoClient) FindOne(filter interface{}) *mongo.SingleResult {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
return collection.FindOne(context.TODO(), filter)
}
type FindManyResultI interface {
Many(result interface{}) error
}
// FindMany 查询多个文档
func (c *MongoClient) FindMany(filter interface{}) (*mongo.Cursor, error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
return collection.Find(context.TODO(), filter)
}
// FindManyByFilters 多条件查询
func (c *MongoClient) FindManyByFilters(filter interface{}) (result *mongo.Cursor, err error) {
collection, err := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName).Clone()
result, err = collection.Find(context.TODO(), bson.M{"$and": filter})
return result, err
}
// FindManyByFiltersSort 多条件查询支持排序
func (c *MongoClient) FindManyByFiltersSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection, err := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName).Clone()
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(context.TODO(), filter, findOptions)
return result, err
}
// FindCollection 查询集合文档
func (c *MongoClient) FindCollection(Limit int64) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
findOptions := options.Find()
findOptions.SetLimit(Limit)
result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions)
return result, err
}
// FindCollectionSort 查询集合文档支持排序
func (c *MongoClient) FindCollectionSort(Sort interface{}, Limit int64) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
findOptions.SetLimit(Limit)
result, err = collection.Find(context.TODO(), bson.D{{}}, findOptions)
return result, err
}
// FindManyCollectionSort 查询集合文档支持排序支持条件
func (c *MongoClient) FindManyCollectionSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(context.TODO(), filter, findOptions)
return result, err
}
// CollectionCount 查询集合里有多少数据
func (c *MongoClient) CollectionCount() (name string, size int64) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
name = collection.Name()
size, _ = collection.EstimatedDocumentCount(context.TODO())
return name, size
}
// CollectionDocuments 按选项查询集合
// Skip 跳过
// Limit 读取数量
// sort 1 -1 . 1 为升序 -1 为降序
func (c *MongoClient) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
SORT := bson.D{{"_id", sort}}
filter := bson.D{{key, value}}
findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
result, err = collection.Find(context.TODO(), filter, findOptions)
return result, err
}
// AggregateByFiltersSort 统计分析
func (c *MongoClient) AggregateByFiltersSort(pipeline interface{}) (result *mongo.Cursor, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
result, err = collection.Aggregate(context.TODO(), pipeline)
return result, err
}
// CountDocumentsByFilters 统计数量
func (c *MongoClient) CountDocumentsByFilters(filter interface{}) (count int64, err error) {
collection := c.Db.Database(c.getDatabaseName()).Collection(c.collectionName)
count, err = collection.CountDocuments(context.TODO(), filter)
return count, err
}

@ -1,15 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type FindResult struct {
cursor *mongo.Cursor
err error
}
func (f *FindResult) Many(result interface{}) error {
return f.cursor.All(context.TODO(), result)
}

@ -1,15 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type FindManyResult struct {
cursor *mongo.Cursor
err error
}
func (f *FindManyResult) Many(result interface{}) error {
return f.cursor.All(context.TODO(), result)
}

@ -1,11 +0,0 @@
package dorm
import "go.mongodb.org/mongo-driver/mongo"
type FindOneResult struct {
singleResult *mongo.SingleResult
}
func (f *FindOneResult) One(result interface{}) error {
return f.singleResult.Decode(result)
}

@ -0,0 +1,69 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"
)
type MongoDatabaseOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
dbDatabase *mongo.Database // 数据库
}
// Database 选择数据库
func (c *MongoClient) Database(name string, opts ...*options.DatabaseOptions) *MongoDatabaseOptions {
return &MongoDatabaseOptions{
db: c.db, // 驱动
configDatabaseName: c.configDatabaseName, // 库名
dbDatabase: c.db.Database(name, opts...), // 数据库
}
}
// CreateCollection 创建集合
func (cd *MongoDatabaseOptions) CreateCollection(ctx context.Context, name string, opts ...*options.CreateCollectionOptions) error {
return cd.dbDatabase.CreateCollection(ctx, name, opts...)
}
// CreateTimeSeriesCollection 创建时间序列集合
func (cd *MongoDatabaseOptions) CreateTimeSeriesCollection(ctx context.Context, name string, timeField string) error {
return cd.dbDatabase.CreateCollection(ctx, name, options.CreateCollection().SetTimeSeriesOptions(options.TimeSeries().SetTimeField(timeField)))
}
// Model 传入模型自动获取库名和表名
// https://studygolang.com/articles/896
// DatabaseName 库名
// CollectionName 集合名
func (c *MongoClient) Model(value interface{}) *MongoCollectionOptions {
var databaseOptions *MongoDatabaseOptions
var collectionOptions *MongoCollectionOptions
val := reflect.ValueOf(value)
methodDatabaseNameValue := val.MethodByName("DatabaseName")
if methodDatabaseNameValue.IsValid() {
databaseName := methodDatabaseNameValue.Call(nil)[0].String()
databaseOptions = c.Database(databaseName)
} else {
databaseOptions = c.Database(c.configDatabaseName)
}
methodCollectionNameValue := val.MethodByName("CollectionName")
if methodCollectionNameValue.IsValid() {
collectionName := methodCollectionNameValue.Call(nil)[0].String()
collectionOptions = databaseOptions.Collection(collectionName)
} else {
methodTableNameValue := val.MethodByName("TableName")
if methodTableNameValue.IsValid() {
collectionName := methodTableNameValue.Call(nil)[0].String()
collectionOptions = databaseOptions.Collection(collectionName)
} else {
panic(NoConfigCollectionName)
}
}
return collectionOptions
}

@ -0,0 +1,8 @@
package dorm
import "errors"
var (
NoConfigDatabaseName = errors.New("没有配置库名")
NoConfigCollectionName = errors.New("没有配置集合名")
)

@ -4,15 +4,5 @@ import "go.mongodb.org/mongo-driver/mongo"
// GetDb 获取驱动
func (c *MongoClient) GetDb() *mongo.Client {
return c.Db
}
// 获取库名
func (c *MongoClient) getDatabaseName() string {
return c.databaseName
}
// 获取表名
func (c *MongoClient) getCollectionName() string {
return c.collectionName
return c.db
}

@ -1,10 +0,0 @@
package dorm
import "encoding/json"
// JsonDecodeNoError Json解码不报错
func JsonDecodeNoError(b []byte) map[string]interface{} {
var data map[string]interface{}
_ = json.Unmarshal(b, &data)
return data
}

@ -1 +0,0 @@
package dorm

@ -0,0 +1,59 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"log"
)
type MongoSessionOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
session mongo.Session // 会话
sessionContext mongo.SessionContext // 会话上下文
}
// Begin 开始事务,会同时创建开始会话需要在退出时关闭会话
func (c *MongoClient) Begin() *MongoSessionOptions {
var ctx = context.TODO()
var err error
ms := &MongoSessionOptions{}
ms.db = c.GetDb()
ms.configDatabaseName = c.configDatabaseName
// 开始会话
ms.session, err = ms.db.StartSession()
if err != nil {
log.Println("开始会话异常:", err)
}
// 会话上下文
ms.sessionContext = mongo.NewSessionContext(ctx, ms.session)
// 会话开启事务
err = ms.session.StartTransaction()
return ms
}
// Rollback 回滚事务
func (cs *MongoSessionOptions) Rollback() {
var ctx = context.TODO()
err := cs.session.AbortTransaction(ctx)
if err != nil {
log.Println("回滚事务异常:", err)
}
cs.session.EndSession(ctx)
}
// Commit 提交事务
func (cs *MongoSessionOptions) Commit() {
var ctx = context.TODO()
err := cs.session.CommitTransaction(ctx)
if err != nil {
log.Println("提交事务异常:", err)
}
cs.session.EndSession(ctx)
}

@ -0,0 +1,25 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoSessionCollectionOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
session mongo.Session // 会话
sessionContext mongo.SessionContext // 会话上下文
dbCollection *mongo.Collection // 集合
}
// Collection 选择集合
func (csd *MongoSessionDatabaseOptions) Collection(name string, opts ...*options.CollectionOptions) *MongoSessionCollectionOptions {
return &MongoSessionCollectionOptions{
db: csd.db, // 驱动
configDatabaseName: csd.configDatabaseName, // 库名
session: csd.session, // 会话
sessionContext: csd.sessionContext, // 会话上下文
dbCollection: csd.dbDatabase.Collection(name, opts...), // 集合
}
}

@ -0,0 +1,99 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (csc *MongoSessionCollectionOptions) InsertOne(document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
return csc.dbCollection.InsertOne(csc.sessionContext, document, opts...)
}
// InsertMany 插入多个文档
func (csc *MongoSessionCollectionOptions) InsertMany(document []interface{}, opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error) {
return csc.dbCollection.InsertMany(csc.sessionContext, document, opts...)
}
// DeleteOne 删除一个文档
func (csc *MongoSessionCollectionOptions) DeleteOne(filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return csc.dbCollection.DeleteOne(csc.sessionContext, filter, opts...)
}
// DeleteMany 删除多个文档
func (csc *MongoSessionCollectionOptions) DeleteMany(filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error) {
return csc.dbCollection.DeleteMany(csc.sessionContext, filter, opts...)
}
// UpdateByID 按ID更新
func (csc *MongoSessionCollectionOptions) UpdateByID(id interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.UpdateByID(csc.sessionContext, id, update, opts...)
}
// UpdateOne 更新一个文档
func (csc *MongoSessionCollectionOptions) UpdateOne(filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.UpdateOne(csc.sessionContext, filter, update, opts...)
}
// UpdateMany 更新多个文档
func (csc *MongoSessionCollectionOptions) UpdateMany(filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.UpdateMany(csc.sessionContext, filter, update, opts...)
}
// ReplaceOne 替换一个文档
func (csc *MongoSessionCollectionOptions) ReplaceOne(filter interface{}, update interface{}, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error) {
return csc.dbCollection.ReplaceOne(csc.sessionContext, filter, update, opts...)
}
// Aggregate 统计分析
func (csc *MongoSessionCollectionOptions) Aggregate(pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error) {
return csc.dbCollection.Aggregate(csc.sessionContext, pipeline, opts...)
}
// CountDocuments 计数文档
func (csc *MongoSessionCollectionOptions) CountDocuments(filter interface{}, opts ...*options.CountOptions) (int64, error) {
return csc.dbCollection.CountDocuments(csc.sessionContext, filter, opts...)
}
// EstimatedDocumentCount 估计文档计数
func (csc *MongoSessionCollectionOptions) EstimatedDocumentCount(opts ...*options.EstimatedDocumentCountOptions) (int64, error) {
return csc.dbCollection.EstimatedDocumentCount(csc.sessionContext, opts...)
}
func (csc *MongoSessionCollectionOptions) Distinct(fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error) {
return csc.dbCollection.Distinct(csc.sessionContext, fieldName, filter, opts...)
}
// Find 查询多个文档
func (csc *MongoSessionCollectionOptions) Find(filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error) {
return csc.dbCollection.Find(csc.sessionContext, filter, opts...)
}
// FindOne 查询一个文档
func (csc *MongoSessionCollectionOptions) FindOne(filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult {
return csc.dbCollection.FindOne(csc.sessionContext, filter, opts...)
}
func (csc *MongoSessionCollectionOptions) FindOneAndDelete(filter interface{}, opts ...*options.FindOneAndDeleteOptions) *mongo.SingleResult {
return csc.dbCollection.FindOneAndDelete(csc.sessionContext, filter, opts...)
}
func (csc *MongoSessionCollectionOptions) FindOneAndReplace(filter interface{}, replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *mongo.SingleResult {
return csc.dbCollection.FindOneAndReplace(csc.sessionContext, filter, replacement, opts...)
}
func (csc *MongoSessionCollectionOptions) FindOneAndUpdate(filter interface{}, replacement interface{}, opts ...*options.FindOneAndUpdateOptions) *mongo.SingleResult {
return csc.dbCollection.FindOneAndUpdate(csc.sessionContext, filter, replacement, opts...)
}
func (csc *MongoSessionCollectionOptions) Watch(pipeline interface{}, opts ...*options.ChangeStreamOptions) (*mongo.ChangeStream, error) {
return csc.dbCollection.Watch(csc.sessionContext, pipeline, opts...)
}
func (csc *MongoSessionCollectionOptions) Indexes() mongo.IndexView {
return csc.dbCollection.Indexes()
}
func (csc *MongoSessionCollectionOptions) Drop() error {
return csc.dbCollection.Drop(csc.sessionContext)
}

@ -0,0 +1,62 @@
package dorm
import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"reflect"
)
type MongoSessionDatabaseOptions struct {
db *mongo.Client // 驱动
configDatabaseName string // 库名
session mongo.Session // 会话
sessionContext mongo.SessionContext // 会话上下文
dbDatabase *mongo.Database // 数据库
}
// Database 选择数据库
func (cs *MongoSessionOptions) Database(name string, opts ...*options.DatabaseOptions) *MongoSessionDatabaseOptions {
return &MongoSessionDatabaseOptions{
db: cs.db, // 驱动
configDatabaseName: cs.configDatabaseName, // 库名
session: cs.session, // 会话
sessionContext: cs.sessionContext, // 会话上下文
dbDatabase: cs.db.Database(name, opts...), // 数据库
}
}
// Model 传入模型自动获取库名和表名
// https://studygolang.com/articles/896
// DatabaseName 库名
// CollectionName 集合名
func (cs *MongoSessionOptions) Model(value interface{}) *MongoSessionCollectionOptions {
var sessionDatabaseOptions *MongoSessionDatabaseOptions
var sessionCollectionOptions *MongoSessionCollectionOptions
val := reflect.ValueOf(value)
methodDatabaseNameValue := val.MethodByName("DatabaseName")
if methodDatabaseNameValue.IsValid() {
databaseName := methodDatabaseNameValue.Call(nil)[0].String()
sessionDatabaseOptions = cs.Database(databaseName)
} else {
sessionDatabaseOptions = cs.Database(cs.configDatabaseName)
}
methodCollectionNameValue := val.MethodByName("CollectionName")
if methodCollectionNameValue.IsValid() {
collectionName := methodCollectionNameValue.Call(nil)[0].String()
sessionCollectionOptions = sessionDatabaseOptions.Collection(collectionName)
} else {
methodTableNameValue := val.MethodByName("TableName")
if methodTableNameValue.IsValid() {
collectionName := methodTableNameValue.Call(nil)[0].String()
sessionCollectionOptions = sessionDatabaseOptions.Collection(collectionName)
} else {
panic(NoConfigCollectionName)
}
}
return sessionCollectionOptions
}

@ -0,0 +1,18 @@
package dorm
import "go.mongodb.org/mongo-driver/mongo"
// GetDb 获取驱动
func (cs *MongoSessionOptions) GetDb() *mongo.Client {
return cs.db
}
// GetSession 获取会话
func (cs *MongoSessionOptions) GetSession() mongo.Session {
return cs.session
}
// GetSessionContext 获取会话上下文
func (cs *MongoSessionOptions) GetSessionContext() mongo.SessionContext {
return cs.sessionContext
}

@ -1,28 +0,0 @@
package dorm
import "reflect"
// Database 设置库名
func (c *MongoClient) Database(databaseName string) *MongoClient {
c.databaseName = databaseName
return c
}
// Collection 设置表名
func (c *MongoClient) Collection(collectionName string) *MongoClient {
c.collectionName = collectionName
return c
}
// Model 传入模型自动获取库名和表名
func (c *MongoClient) Model(value interface{}) *MongoClient {
// https://studygolang.com/articles/896
val := reflect.ValueOf(value)
if methodValue := val.MethodByName("Database"); methodValue.IsValid() {
c.databaseName = methodValue.Call(nil)[0].String()
}
if methodValue := val.MethodByName("TableName"); methodValue.IsValid() {
c.collectionName = methodValue.Call(nil)[0].String()
}
return c
}

@ -1,50 +1,85 @@
package dorm
import (
"github.com/dtapps/go-library/utils/gotime"
"go.dtapp.net/gotime"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"time"
)
// BsonTime 类型
// BsonTime 时间类型
type BsonTime time.Time
// Value 时间类型
func (t BsonTime) Value() string {
return gotime.SetCurrent(time.Time(t)).Bson()
}
// MarshalJSON 实现json序列化
func (t BsonTime) MarshalJSON() ([]byte, error) {
//log.Println("MarshalJSON")
func (bt BsonTime) MarshalJSON() ([]byte, error) {
b := make([]byte, 0)
b = append(b, gotime.SetCurrent(time.Time(t)).Bson()...)
b = append(b, '"')
b = append(b, gotime.SetCurrent(time.Time(bt)).Bson()...)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON 实现json反序列化
func (t *BsonTime) UnmarshalJSON(data []byte) (err error) {
//log.Println("UnmarshalJSON")
t1 := gotime.SetCurrentParse(string(data))
*t = BsonTime(t1.Time)
return
func (bt *BsonTime) UnmarshalJSON(data []byte) (err error) {
if string(data) == "null" {
return nil
}
bsonTime := gotime.SetCurrentParse(string(data))
*bt = BsonTime(bsonTime.Time)
return nil
}
// Time 转时间
func (bt BsonTime) Time() time.Time {
return gotime.SetCurrent(time.Time(bt)).Time
}
// Format 转时间字符串
func (bt BsonTime) Format() string {
return gotime.SetCurrent(time.Time(bt)).Format()
}
// TimePro 转时间操作
func (bt BsonTime) TimePro() gotime.Pro {
return gotime.SetCurrent(time.Time(bt))
}
// NewBsonTimeCurrent 创建当前时间
func NewBsonTimeCurrent() BsonTime {
return BsonTime(gotime.Current().Time)
}
// NewBsonTimeFromTime 创建某个时间
func NewBsonTimeFromTime(t time.Time) BsonTime {
return BsonTime(t)
}
// NewBsonTimeFromString 创建某个时间 字符串
func NewBsonTimeFromString(t string) BsonTime {
return BsonTime(gotime.SetCurrentParse(t).Time)
}
// Value 时间类型
func (bt BsonTime) Value() string {
return gotime.SetCurrent(time.Time(bt)).Bson()
}
// MarshalBSONValue 实现bson序列化
func (t BsonTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
//log.Println("MarshalBSONValue")
targetTime := gotime.SetCurrent(time.Time(t)).Bson()
return bson.MarshalValue(targetTime)
func (bt BsonTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bson.MarshalValue(gotime.SetCurrent(time.Time(bt)).Bson())
}
// UnmarshalBSONValue 实现bson反序列化
func (t *BsonTime) UnmarshalBSONValue(t2 bsontype.Type, data []byte) error {
//log.Println("UnmarshalBSONValue")
func (bt *BsonTime) UnmarshalBSONValue(t bsontype.Type, data []byte) error {
t1 := gotime.SetCurrentParse(string(data))
//if string(data) == "" {
// return errors.New(fmt.Sprintf("%s, %s, %s", "读取数据失败:", t2, data))
// return errors.New(fmt.Sprintf("%s, %s, %s", "读取数据失败:", t, data))
//}
*t = BsonTime(t1.Time)
*bt = BsonTime(t1.Time)
return nil
}

@ -1,48 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
type MongoTransaction struct {
startSession mongo.Session
Session mongo.SessionContext
db *mongo.Client // 驱动
databaseName string // 库名
collectionName string // 表名
}
// Begin 开始事务,会同时创建开始会话需要在退出时关闭会话
func (c *MongoClient) Begin() (ms MongoTransaction, err error) {
ms.db = c.Db
// 开始会话
ms.startSession, err = ms.db.StartSession()
if err != nil {
panic(err)
}
// 会话上下文
ms.Session = mongo.NewSessionContext(context.Background(), ms.startSession)
// 会话开启事务
err = ms.startSession.StartTransaction()
return ms, err
}
// Close 关闭会话
func (ms *MongoTransaction) Close() {
ms.startSession.EndSession(context.TODO())
}
// Rollback 回滚事务
func (ms *MongoTransaction) Rollback() error {
return ms.startSession.AbortTransaction(context.Background())
}
// Commit 提交事务
func (ms *MongoTransaction) Commit() error {
return ms.startSession.CommitTransaction(context.Background())
}

@ -1,174 +0,0 @@
package dorm
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// InsertOne 插入一个文档
func (ms *MongoTransaction) InsertOne(document interface{}) (result *mongo.InsertOneResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.InsertOne(ms.Session, document)
return
}
// InsertMany 插入多个文档
func (ms *MongoTransaction) InsertMany(documents []interface{}) (result *mongo.InsertManyResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.InsertMany(ms.Session, documents)
return
}
// Delete 删除文档
func (ms *MongoTransaction) Delete(filter interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.DeleteOne(ms.Session, filter)
return
}
// DeleteId 删除文档
func (ms *MongoTransaction) DeleteId(id interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.DeleteOne(ms.Session, bson.M{"_id": id})
return
}
// DeleteMany 删除多个文档
func (ms *MongoTransaction) DeleteMany(key string, value interface{}) (result *mongo.DeleteResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
filter := bson.D{{key, value}}
result, err = collection.DeleteMany(ms.Session, filter)
return
}
// UpdateOne 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (ms *MongoTransaction) UpdateOne(filter interface{}, update interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.UpdateOne(ms.Session, filter, update)
return
}
// UpdateId 更新单个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (ms *MongoTransaction) UpdateId(id interface{}, update interface{}) (err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
_, err = collection.UpdateOne(context.TODO(), bson.M{"_id": id}, update)
return
}
// UpdateMany 更新多个文档
// 修改字段的值($set)
// 字段增加值 inc($inc)
// 从数组中增加一个元素 push($push)
// 从数组中删除一个元素 pull($pull)
func (ms *MongoTransaction) UpdateMany(filter interface{}, update interface{}) (result *mongo.UpdateResult, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.UpdateMany(ms.Session, filter, update)
return
}
// Find 查询
func (ms *MongoTransaction) Find(filter interface{}) (*mongo.Cursor, error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
return collection.Find(ms.Session, filter)
}
// FindOne 查询单个文档
func (ms *MongoTransaction) FindOne(filter interface{}) *mongo.SingleResult {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
return collection.FindOne(ms.Session, filter)
}
// FindMany 查询多个文档
func (ms *MongoTransaction) FindMany(filter interface{}) (*mongo.Cursor, error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
return collection.Find(ms.Session, filter)
}
// FindManyByFilters 多条件查询
func (ms *MongoTransaction) FindManyByFilters(filter interface{}) (result *mongo.Cursor, err error) {
collection, err := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName).Clone()
result, err = collection.Find(ms.Session, bson.M{"$and": filter})
return result, err
}
// FindManyByFiltersSort 多条件查询支持排序
func (ms *MongoTransaction) FindManyByFiltersSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection, err := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName).Clone()
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(ms.Session, filter, findOptions)
return result, err
}
// FindCollection 查询集合文档
func (ms *MongoTransaction) FindCollection(Limit int64) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
findOptions := options.Find()
findOptions.SetLimit(Limit)
result, err = collection.Find(ms.Session, bson.D{{}}, findOptions)
return result, err
}
// FindCollectionSort 查询集合文档支持排序
func (ms *MongoTransaction) FindCollectionSort(Sort interface{}, Limit int64) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
findOptions.SetLimit(Limit)
result, err = collection.Find(ms.Session, bson.D{{}}, findOptions)
return result, err
}
// FindManyCollectionSort 查询集合文档支持排序支持条件
func (ms *MongoTransaction) FindManyCollectionSort(filter interface{}, Sort interface{}) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
findOptions := options.Find()
findOptions.SetSort(Sort)
result, err = collection.Find(ms.Session, filter, findOptions)
return result, err
}
// CollectionCount 查询集合里有多少数据
func (ms *MongoTransaction) CollectionCount(ctx context.Context) (name string, size int64) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
name = collection.Name()
size, _ = collection.EstimatedDocumentCount(ctx)
return name, size
}
// CollectionDocuments 按选项查询集合
// Skip 跳过
// Limit 读取数量
// sort 1 -1 . 1 为升序 -1 为降序
func (ms *MongoTransaction) CollectionDocuments(Skip, Limit int64, sort int, key string, value interface{}) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
SORT := bson.D{{"_id", sort}}
filter := bson.D{{key, value}}
findOptions := options.Find().SetSort(SORT).SetLimit(Limit).SetSkip(Skip)
result, err = collection.Find(ms.Session, filter, findOptions)
return result, err
}
// AggregateByFiltersSort 统计分析
func (ms *MongoTransaction) AggregateByFiltersSort(pipeline interface{}) (result *mongo.Cursor, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
result, err = collection.Aggregate(ms.Session, pipeline)
return result, err
}
// CountDocumentsByFilters 统计数量
func (ms *MongoTransaction) CountDocumentsByFilters(filter interface{}) (count int64, err error) {
collection := ms.db.Database(ms.getDatabaseName()).Collection(ms.collectionName)
count, err = collection.CountDocuments(ms.Session, filter)
return count, err
}

@ -1,11 +0,0 @@
package dorm
// 获取库名
func (ms *MongoTransaction) getDatabaseName() string {
return ms.databaseName
}
// 获取表名
func (ms *MongoTransaction) getCollectionName() string {
return ms.collectionName
}

@ -1,28 +0,0 @@
package dorm
import "reflect"
// Database 设置库名
func (ms *MongoTransaction) Database(databaseName string) *MongoTransaction {
ms.databaseName = databaseName
return ms
}
// Collection 设置表名
func (ms *MongoTransaction) Collection(collectionName string) *MongoTransaction {
ms.collectionName = collectionName
return ms
}
// Model 传入模型自动获取库名和表名
func (ms *MongoTransaction) Model(value interface{}) *MongoTransaction {
// https://studygolang.com/articles/896
val := reflect.ValueOf(value)
if methodValue := val.MethodByName("Database"); methodValue.IsValid() {
ms.databaseName = methodValue.Call(nil)[0].String()
}
if methodValue := val.MethodByName("TableName"); methodValue.IsValid() {
ms.collectionName = methodValue.Call(nil)[0].String()
}
return ms
}

@ -1,16 +0,0 @@
package dorm
import (
"encoding/json"
"github.com/basgys/goxml2json"
"strings"
)
// XmlDecodeNoError Xml解码不报错
func XmlDecodeNoError(b []byte) map[string]interface{} {
xtj := strings.NewReader(string(b))
jtx, _ := xml2json.Convert(xtj)
var data map[string]interface{}
_ = json.Unmarshal(jtx.Bytes(), &data)
return data
}

@ -4,43 +4,48 @@ import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"github.com/redis/go-redis/v9"
"time"
)
type ConfigRedisClient struct {
Addr string // 地址
Password string // 密码
DB int // 数据库
PoolSize int // 连接池大小
// RedisClientFun *RedisClient 驱动
type RedisClientFun func() *RedisClient
type RedisClientConfig struct {
Addr string // 地址
Password string // 密码
DB int // 数据库
PoolSize int // 连接池大小
ReadTimeout time.Duration // 读取超时
}
// RedisClient
// https://redis.uptrace.dev/
type RedisClient struct {
Db *redis.Client // 驱动
config *ConfigRedisClient // 配置
db *redis.Client // 驱动
}
func NewRedisClient(config *ConfigRedisClient) (*RedisClient, error) {
// NewRedisClient 创建实例
func NewRedisClient(config *RedisClientConfig) (*RedisClient, error) {
c := &RedisClient{}
c.config = config
if c.config.PoolSize == 0 {
c.config.PoolSize = 100
if config.PoolSize == 0 {
config.PoolSize = 100
}
c.Db = redis.NewClient(&redis.Options{
Addr: c.config.Addr, // 地址
Password: c.config.Password, // 密码
DB: c.config.DB, // 数据库
PoolSize: c.config.PoolSize, // 连接池大小
c.db = redis.NewClient(&redis.Options{
Addr: config.Addr, // 地址
Password: config.Password, // 密码
DB: config.DB, // 数据库
PoolSize: config.PoolSize, // 连接池大小
ReadTimeout: config.ReadTimeout, // 读取超时
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := c.Db.Ping(ctx).Result()
// 检测 Redis 连接是否正常连接
_, err := c.db.Ping(ctx).Result()
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
@ -48,6 +53,27 @@ func NewRedisClient(config *ConfigRedisClient) (*RedisClient, error) {
return c, nil
}
func (c *RedisClient) GetDb() *redis.Client {
return c.Db
// NewRedisClientURL 创建实例
func NewRedisClientURL(redisURL string) (*RedisClient, error) {
c := &RedisClient{}
opt, err := redis.ParseURL(redisURL)
if err != nil {
return c, nil
}
// 创建 Redis 客户端
c.db = redis.NewClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 检测 Redis 连接是否正常连接
_, err = c.db.Ping(ctx).Result()
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}

@ -1,47 +0,0 @@
package dorm
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"time"
)
// RedisClient6
// https://redis.uptrace.dev/
type RedisClient6 struct {
Db *redis.Client // 驱动
config *ConfigRedisClient // 配置
}
// NewRedisClient6 Redis 6
func NewRedisClient6(config *ConfigRedisClient) (*RedisClient6, error) {
c := &RedisClient6{}
c.config = config
if c.config.PoolSize == 0 {
c.config.PoolSize = 100
}
c.Db = redis.NewClient(&redis.Options{
Addr: c.config.Addr, // 地址
Password: c.config.Password, // 密码
DB: c.config.DB, // 数据库
PoolSize: c.config.PoolSize, // 连接池大小
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := c.Db.Ping(ctx).Result()
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}
func (c *RedisClient6) GetDb() *redis.Client {
return c.Db
}

@ -1,47 +0,0 @@
package dorm
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis/v9"
"time"
)
// RedisClient7
// https://redis.uptrace.dev/
type RedisClient7 struct {
Db *redis.Client // 驱动
config *ConfigRedisClient // 配置
}
// NewRedisClient7 Redis 7
func NewRedisClient7(config *ConfigRedisClient) (*RedisClient7, error) {
c := &RedisClient7{}
c.config = config
if c.config.PoolSize == 0 {
c.config.PoolSize = 100
}
c.Db = redis.NewClient(&redis.Options{
Addr: c.config.Addr, // 地址
Password: c.config.Password, // 密码
DB: c.config.DB, // 数据库
PoolSize: c.config.PoolSize, // 连接池大小
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := c.Db.Ping(ctx).Result()
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}
func (c *RedisClient7) GetDb() *redis.Client {
return c.Db
}

@ -0,0 +1,96 @@
package dorm
import (
"context"
"go.dtapp.net/gojson"
"time"
)
// GttStringFunc String缓存结构
type GttStringFunc func() string
// GttInterfaceFunc Interface缓存结构
type GttInterfaceFunc func() interface{}
// RedisCacheConfig 配置
type RedisCacheConfig struct {
Expiration time.Duration // 过期时间
}
// RedisClientCache https://github.com/go-redis/redis
type RedisClientCache struct {
defaultExpiration time.Duration // 过期时间
operation *RedisClient // 操作
GetterString GttStringFunc // 不存在的操作
GetterInterface GttInterfaceFunc // 不存在的操作
}
// NewCache 实例化
func (r *RedisClient) NewCache(config *RedisCacheConfig) *RedisClientCache {
return &RedisClientCache{
defaultExpiration: config.Expiration,
operation: r,
}
}
// NewCacheDefaultExpiration 实例化
func (r *RedisClient) NewCacheDefaultExpiration() *RedisClientCache {
return &RedisClientCache{
defaultExpiration: time.Minute * 30,
operation: r,
}
}
// GetString 缓存操作
func (rc *RedisClientCache) GetString(ctx context.Context, key string) (ret string) {
f := func() string {
return rc.GetterString()
}
// 如果不存在则调用GetterString
ret, err := rc.operation.Get(ctx, key).Result()
if err != nil {
rc.operation.Set(ctx, key, f(), rc.defaultExpiration)
ret, _ = rc.operation.Get(ctx, key).Result()
}
return
}
// GetInterface 缓存操作
func (rc *RedisClientCache) GetInterface(ctx context.Context, key string, result interface{}) {
f := func() string {
marshal, _ := gojson.Marshal(rc.GetterInterface())
return string(marshal)
}
// 如果不存在则调用GetterInterface
ret, err := rc.operation.Get(ctx, key).Result()
if err != nil {
rc.operation.Set(ctx, key, f(), rc.defaultExpiration)
ret, _ = rc.operation.Get(ctx, key).Result()
}
err = gojson.Unmarshal([]byte(ret), result)
return
}
// GetInterfaceKey 获取key值
func (rc *RedisClientCache) GetInterfaceKey(ctx context.Context, key string, result interface{}) error {
ret, err := rc.operation.Get(ctx, key).Result()
if err != nil {
return err
}
err = gojson.Unmarshal([]byte(ret), result)
return nil
}
// SetInterfaceKey 设置key值
func (rc *RedisClientCache) SetInterfaceKey(ctx context.Context, key string, value interface{}) (string, error) {
marshal, _ := gojson.Marshal(value)
return rc.operation.Set(ctx, key, marshal, rc.defaultExpiration).Result()
}

@ -0,0 +1,158 @@
package dorm
import (
"context"
"github.com/redis/go-redis/v9"
"time"
)
// Set 设置一个key的值
func (r *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd {
return r.db.Set(ctx, key, value, expiration)
}
// Get 查询key的值
func (r *RedisClient) Get(ctx context.Context, key string) *redis.StringCmd {
return r.db.Get(ctx, key)
}
// GetSet 设置一个key的值并返回这个key的旧值
func (r *RedisClient) GetSet(ctx context.Context, key string, value interface{}) *redis.StringCmd {
return r.db.GetSet(ctx, key, value)
}
// SetNX 如果key不存在则设置这个key的值
func (r *RedisClient) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd {
return r.db.SetNX(ctx, key, value, expiration)
}
// MGet 批量查询key的值
func (r *RedisClient) MGet(ctx context.Context, keys ...string) *redis.SliceCmd {
return r.db.MGet(ctx, keys...)
}
// MSet 批量设置key的值
// MSet(map[string]interface{}{"key1": "value1", "key2": "value2"})
func (r *RedisClient) MSet(ctx context.Context, values map[string]interface{}) *redis.StatusCmd {
return r.db.MSet(ctx, values)
}
// Incr 针对一个key的数值进行递增操作
func (r *RedisClient) Incr(ctx context.Context, key string) *redis.IntCmd {
return r.db.Incr(ctx, key)
}
// IncrBy 针对一个key的数值进行递增操作指定每次递增多少
func (r *RedisClient) IncrBy(ctx context.Context, key string, value int64) *redis.IntCmd {
return r.db.IncrBy(ctx, key, value)
}
// Decr 针对一个key的数值进行递减操作
func (r *RedisClient) Decr(ctx context.Context, key string) *redis.IntCmd {
return r.db.Decr(ctx, key)
}
// DecrBy 针对一个key的数值进行递减操作指定每次递减多少
func (r *RedisClient) DecrBy(ctx context.Context, key string, value int64) *redis.IntCmd {
return r.db.DecrBy(ctx, key, value)
}
// Del 删除key操作支持批量删除
func (r *RedisClient) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return r.db.Del(ctx, keys...)
}
// Keys 按前缀获取所有key名
func (r *RedisClient) Keys(ctx context.Context, prefix string) []string {
values, _ := r.db.Keys(ctx, prefix).Result()
keys := make([]string, 0, len(values))
if len(values) <= 0 {
return keys
}
for _, value := range values {
keys = append(keys, value)
}
return keys
}
// KeysValue 按前缀获取所有key值
func (r *RedisClient) KeysValue(ctx context.Context, prefix string) *redis.SliceCmd {
values, _ := r.db.Keys(ctx, prefix).Result()
if len(values) <= 0 {
return &redis.SliceCmd{}
}
keys := make([]string, 0, len(values))
for _, value := range values {
keys = append(keys, value)
}
return r.MGet(ctx, keys...)
}
// AddKeyToSet 将值添加到集合
func (r *RedisClient) AddKeyToSet(ctx context.Context, setKey string, value interface{}) error {
return r.db.SAdd(ctx, setKey, value).Err()
}
// GetAllKeysInSet 获取集合的所有元素
func (r *RedisClient) GetAllKeysInSet(ctx context.Context, setKey string) ([]string, error) {
return r.db.SMembers(ctx, setKey).Result()
}
// DoesKeyExistInSet 检查值是否存在于集合中
func (r *RedisClient) DoesKeyExistInSet(ctx context.Context, setKey string, targetKey interface{}) (bool, error) {
return r.db.SIsMember(ctx, setKey, targetKey).Result()
}
// RemoveKeyFromSet 从集合中删除指定的元素
func (r *RedisClient) RemoveKeyFromSet(ctx context.Context, setKey string, targetKey interface{}) error {
return r.db.SRem(ctx, setKey, targetKey).Err()
}
// DeleteKeysWithPrefix 根据前缀删除key
func (r *RedisClient) DeleteKeysWithPrefix(ctx context.Context, prefix string) error {
// 获取所有符合给定模式的键
keys, err := r.db.Keys(ctx, prefix+"*").Result()
if err != nil {
return err
}
// 删除所有匹配的键
if len(keys) > 0 {
_, err := r.db.Del(ctx, keys...).Result()
if err != nil {
return err
}
}
return nil
}
// DeleteScanWithPrefix 根据前缀删除key
func (r *RedisClient) DeleteScanWithPrefix(ctx context.Context, prefix string) error {
var cursor uint64
for {
// 使用 SCAN 迭代获取匹配模式的键
keys, nextCursor, err := r.db.Scan(ctx, cursor, prefix+"*", 10).Result()
if err != nil {
return err
}
// 删除当前迭代返回的键
if len(keys) > 0 {
_, err := r.db.Del(ctx, keys...).Result()
if err != nil {
return err
}
}
// 更新游标,继续迭代
cursor = nextCursor
// 如果迭代结束,退出循环
if cursor == 0 {
break
}
}
return nil
}

@ -0,0 +1,31 @@
package dorm
import (
"context"
"github.com/redis/go-redis/v9"
)
// Subscribe 订阅channel
func (r *RedisClient) Subscribe(ctx context.Context, channels ...string) *redis.PubSub {
return r.db.Subscribe(ctx, channels...)
}
// PSubscribe 订阅channel支持通配符匹配
func (r *RedisClient) PSubscribe(ctx context.Context, channels ...string) *redis.PubSub {
return r.db.PSubscribe(ctx, channels...)
}
// Publish 将信息发送到指定的channel
func (r *RedisClient) Publish(ctx context.Context, channel string, message interface{}) *redis.IntCmd {
return r.db.Publish(ctx, channel, message)
}
// PubSubChannels 查询活跃的channel
func (r *RedisClient) PubSubChannels(ctx context.Context, pattern string) *redis.StringSliceCmd {
return r.db.PubSubChannels(ctx, pattern)
}
// PubSubNumSub 查询指定的channel有多少个订阅者
func (r *RedisClient) PubSubNumSub(ctx context.Context, channels ...string) *redis.MapStringIntCmd {
return r.db.PubSubNumSub(ctx, channels...)
}

@ -0,0 +1,8 @@
package dorm
import "errors"
var (
// RedisKeysNotFound keys没有数据
RedisKeysNotFound = errors.New("ERR wrong number of arguments for 'mget' command")
)

@ -0,0 +1,8 @@
package dorm
import "github.com/redis/go-redis/v9"
// GetDb 获取驱动
func (r *RedisClient) GetDb() *redis.Client {
return r.db
}

@ -2,25 +2,25 @@ package dorm
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/redis/go-redis/v9"
)
// HashOperation Hash类型数据操作
type HashOperation struct {
db *redis.Client
ctx context.Context
db *redis.Client
}
// NewHashOperation hash类型数据操作 https://www.tizi365.com/archives/296.html
func NewHashOperation(db *redis.Client, ctx context.Context) *HashOperation {
return &HashOperation{db: db, ctx: ctx}
func NewHashOperation(db *redis.Client) *HashOperation {
return &HashOperation{db: db}
}
// Set 根据key和field字段设置field字段的值
func (cl *HashOperation) Set(key string, value interface{}) *redis.IntCmd {
return cl.db.HSet(cl.ctx, key, value)
func (cl *HashOperation) Set(ctx context.Context, key string, value interface{}) *redis.IntCmd {
return cl.db.HSet(ctx, key, value)
}
// Get 根据key和field字段设置field字段的值
func (cl *HashOperation) Get(key, field string) *redis.StringCmd {
return cl.db.HGet(cl.ctx, key, field)
func (cl *HashOperation) Get(ctx context.Context, key, field string) *redis.StringCmd {
return cl.db.HGet(ctx, key, field)
}

@ -2,17 +2,18 @@ package dorm
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/redis/go-redis/v9"
)
// ListOperation 列表(list)类型数据操作
type ListOperation struct {
db *redis.Client
ctx context.Context
}
// NewListOperation 列表(list)类型数据操作 https://www.tizi365.com/archives/299.html
func (c *RedisClient) NewListOperation() *ListOperation {
return &ListOperation{db: c.Db, ctx: context.Background()}
func (r *RedisClient) NewListOperation() *ListOperation {
return &ListOperation{db: r.db, ctx: context.Background()}
}
// LPush 从列表左边插入数据

@ -0,0 +1,73 @@
package dorm
import (
"context"
"errors"
"fmt"
"github.com/redis/go-redis/v9"
"time"
)
// RedisClientLock https://github.com/go-redis/redis
type RedisClientLock struct {
operation *RedisClient // 操作
}
// NewLock 实例化锁
func (r *RedisClient) NewLock() *RedisClientLock {
return &RedisClientLock{r}
}
// Lock 上锁
// key 锁名
// val 锁内容
// ttl 锁过期时间
func (rl *RedisClientLock) Lock(ctx context.Context, key string, val string, ttl time.Duration) (resp string, err error) {
if ttl <= 0 {
return resp, errors.New("长期请使用 LockForever 方法")
}
// 获取
get, err := rl.operation.Get(ctx, key).Result()
if errors.Is(err, redis.Nil) {
// 设置
err = rl.operation.Set(ctx, key, val, ttl).Err()
if err != nil {
return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error()))
}
return val, nil
}
if get != "" {
return resp, errors.New("上锁失败,已存在")
}
return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error()))
}
// Unlock 解锁
// key 锁名
func (rl *RedisClientLock) Unlock(ctx context.Context, key string) error {
_, err := rl.operation.Del(ctx, key).Result()
if err != nil {
return errors.New(fmt.Sprintf("解锁失败:%s", err.Error()))
}
return err
}
// LockForever 永远上锁
// key 锁名
// val 锁内容
func (rl *RedisClientLock) LockForever(ctx context.Context, key string, val string) (resp string, err error) {
// 获取
get, err := rl.operation.Get(ctx, key).Result()
if errors.Is(err, redis.Nil) {
// 设置
err = rl.operation.Set(ctx, key, val, 0).Err()
if err != nil {
return resp, errors.New(fmt.Sprintf("上锁失败:%s", err.Error()))
}
return val, nil
}
if get != "" {
return resp, errors.New("上锁失败,已存在")
}
return resp, errors.New(fmt.Sprintf("获取异常:%s", err.Error()))
}

@ -1,7 +1,8 @@
package dorm
import (
"encoding/json"
"context"
"go.dtapp.net/gojson"
"time"
)
@ -24,7 +25,7 @@ type SimpleCache struct {
}
// NewSimpleCache 构造函数
func (c *RedisClient) NewSimpleCache(operation *StringOperation, expire time.Duration, serializer string) *SimpleCache {
func (r *RedisClient) NewSimpleCache(operation *StringOperation, expire time.Duration, serializer string) *SimpleCache {
return &SimpleCache{
Operation: operation, // 操作类
Expire: expire, // 过去时间
@ -33,29 +34,29 @@ func (c *RedisClient) NewSimpleCache(operation *StringOperation, expire time.Dur
}
// SetCache 设置缓存
func (c *SimpleCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleCache) SetCache(ctx context.Context, key string, value interface{}) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleCache) GetCache(key string) (ret interface{}) {
func (c *SimpleCache) GetCache(ctx context.Context, key string) (ret interface{}) {
if c.Serializer == SerializerJson {
f := func() string {
obj := c.JsonGetter()
b, err := json.Marshal(obj)
b, err := gojson.Marshal(obj)
if err != nil {
return ""
}
return string(b)
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
} else if c.Serializer == SerializerString {
f := func() string {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
}
return
}

@ -1,7 +1,7 @@
package dorm
import (
"log"
"context"
"time"
)
@ -15,7 +15,7 @@ type SimpleInterfaceCache struct {
}
// NewSimpleInterfaceCache 构造函数
func (c *RedisClient) NewSimpleInterfaceCache(operation *SimpleOperation, expire time.Duration) *SimpleInterfaceCache {
func (r *RedisClient) NewSimpleInterfaceCache(operation *SimpleOperation, expire time.Duration) *SimpleInterfaceCache {
return &SimpleInterfaceCache{
Operation: operation, // 操作类
Expire: expire, // 过期时间
@ -23,17 +23,16 @@ func (c *RedisClient) NewSimpleInterfaceCache(operation *SimpleOperation, expire
}
// SetCache 设置缓存
func (c *SimpleInterfaceCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleInterfaceCache) SetCache(ctx context.Context, key string, value interface{}) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleInterfaceCache) GetCache(key string) (ret interface{}) {
func (c *SimpleInterfaceCache) GetCache(ctx context.Context, key string) (ret interface{}) {
f := func() interface{} {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
log.Println(ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
return ret
}

@ -1,7 +1,8 @@
package dorm
import (
"encoding/json"
"context"
"go.dtapp.net/gojson"
"time"
)
@ -15,7 +16,7 @@ type SimpleJsonCache struct {
}
// NewSimpleJsonCache 构造函数
func (c *RedisClient) NewSimpleJsonCache(operation *StringOperation, expire time.Duration) *SimpleJsonCache {
func (r *RedisClient) NewSimpleJsonCache(operation *StringOperation, expire time.Duration) *SimpleJsonCache {
return &SimpleJsonCache{
Operation: operation, // 操作类
Expire: expire, // 过期时间
@ -23,21 +24,21 @@ func (c *RedisClient) NewSimpleJsonCache(operation *StringOperation, expire time
}
// SetCache 设置缓存
func (c *SimpleJsonCache) SetCache(key string, value interface{}) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleJsonCache) SetCache(ctx context.Context, key string, value interface{}) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleJsonCache) GetCache(key string) (ret interface{}) {
func (c *SimpleJsonCache) GetCache(ctx context.Context, key string) (ret interface{}) {
f := func() string {
obj := c.DBGetter()
b, err := json.Marshal(obj)
b, err := gojson.Marshal(obj)
if err != nil {
return ""
}
return string(b)
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
return
}

@ -2,37 +2,33 @@ package dorm
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/redis/go-redis/v9"
"time"
)
type SimpleOperation struct {
db *redis.Client
ctx context.Context
db *redis.Client
}
func (c *RedisClient) NewSimpleOperation() *SimpleOperation {
return &SimpleOperation{
db: c.Db,
ctx: context.Background(),
}
func (r *RedisClient) NewSimpleOperation() *SimpleOperation {
return &SimpleOperation{db: r.db}
}
// Set 设置
func (o *SimpleOperation) Set(key string, value interface{}, attrs ...*OperationAttr) *SimpleResult {
func (o *SimpleOperation) Set(ctx context.Context, key string, value interface{}, attrs ...*OperationAttr) *SimpleResult {
exp := OperationAttrs(attrs).Find(AttrExpr)
if exp == nil {
exp = time.Second * 0
}
return NewSimpleResult(o.db.Set(o.ctx, key, value, exp.(time.Duration)).Result())
return NewSimpleResult(o.db.Set(ctx, key, value, exp.(time.Duration)).Result())
}
// Get 获取单个
func (o *SimpleOperation) Get(key string) *SimpleResult {
return NewSimpleResult(o.db.Get(o.ctx, key).Result())
func (o *SimpleOperation) Get(ctx context.Context, key string) *SimpleResult {
return NewSimpleResult(o.db.Get(ctx, key).Result())
}
// Del 删除key操作支持批量删除
func (o *SimpleOperation) Del(keys ...string) *redis.IntCmd {
return o.db.Del(o.ctx, keys...)
func (o *SimpleOperation) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return o.db.Del(ctx, keys...)
}

@ -1,6 +1,7 @@
package dorm
import (
"context"
"time"
)
@ -14,7 +15,7 @@ type SimpleStringCache struct {
}
// NewSimpleStringCache 构造函数
func (c *RedisClient) NewSimpleStringCache(operation *StringOperation, expire time.Duration) *SimpleStringCache {
func (r *RedisClient) NewSimpleStringCache(operation *StringOperation, expire time.Duration) *SimpleStringCache {
return &SimpleStringCache{
Operation: operation, // 操作类
Expire: expire, // 过期时间
@ -22,16 +23,16 @@ func (c *RedisClient) NewSimpleStringCache(operation *StringOperation, expire ti
}
// SetCache 设置缓存
func (c *SimpleStringCache) SetCache(key string, value string) {
c.Operation.Set(key, value, WithExpire(c.Expire)).Unwrap()
func (c *SimpleStringCache) SetCache(ctx context.Context, key string, value string) {
c.Operation.Set(ctx, key, value, WithExpire(c.Expire)).Unwrap()
}
// GetCache 获取缓存
func (c *SimpleStringCache) GetCache(key string) (ret string) {
func (c *SimpleStringCache) GetCache(ctx context.Context, key string) (ret string) {
f := func() string {
return c.DBGetter()
}
ret = c.Operation.Get(key).UnwrapOrElse(f)
c.SetCache(key, ret)
ret = c.Operation.Get(ctx, key).UnwrapOrElse(f)
c.SetCache(ctx, key, ret)
return
}

@ -2,42 +2,38 @@ package dorm
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/redis/go-redis/v9"
"time"
)
type StringOperation struct {
db *redis.Client
ctx context.Context
db *redis.Client
}
func (c *RedisClient) NewStringOperation() *StringOperation {
return &StringOperation{
db: c.Db,
ctx: context.Background(),
}
func (r *RedisClient) NewStringOperation() *StringOperation {
return &StringOperation{db: r.db}
}
// Set 设置
func (o *StringOperation) Set(key string, value interface{}, attrs ...*OperationAttr) *StringResult {
func (o *StringOperation) Set(ctx context.Context, key string, value interface{}, attrs ...*OperationAttr) *StringResult {
exp := OperationAttrs(attrs).Find(AttrExpr)
if exp == nil {
exp = time.Second * 0
}
return NewStringResult(o.db.Set(o.ctx, key, value, exp.(time.Duration)).Result())
return NewStringResult(o.db.Set(ctx, key, value, exp.(time.Duration)).Result())
}
// Get 获取单个
func (o *StringOperation) Get(key string) *StringResult {
return NewStringResult(o.db.Get(o.ctx, key).Result())
func (o *StringOperation) Get(ctx context.Context, key string) *StringResult {
return NewStringResult(o.db.Get(ctx, key).Result())
}
// MGet 获取多个
func (o *StringOperation) MGet(keys ...string) *SliceResult {
return NewSliceResult(o.db.MGet(o.ctx, keys...).Result())
func (o *StringOperation) MGet(ctx context.Context, keys ...string) *SliceResult {
return NewSliceResult(o.db.MGet(ctx, keys...).Result())
}
// Del 删除key操作支持批量删除
func (o *StringOperation) Del(keys ...string) *redis.IntCmd {
return o.db.Del(o.ctx, keys...)
func (o *StringOperation) Del(ctx context.Context, keys ...string) *redis.IntCmd {
return o.db.Del(ctx, keys...)
}

@ -0,0 +1,76 @@
package dorm
// Bool 复制 bool 对象,并返回复制体
func Bool(b bool) bool {
return b
}
// Uint8 复制 int8 对象,并返回复制体
func Uint8(ui uint8) uint8 {
return ui
}
// Uint16 复制 uint16 对象,并返回复制体
func Uint16(ui uint16) uint16 {
return ui
}
// Uint32 复制 uint32 对象,并返回复制体
func Uint32(ui uint32) uint32 {
return ui
}
// Uint64 复制 uint64 对象,并返回复制体
func Uint64(ui uint64) uint64 {
return ui
}
// Int8 复制 int8 对象,并返回复制体
func Int8(i int8) int8 {
return i
}
// Int16 复制 int16 对象,并返回复制体
func Int16(i int16) int16 {
return i
}
// Int32 复制 int64 对象,并返回复制体
func Int32(i int32) int32 {
return i
}
// Int64 复制 int64 对象,并返回复制体
func Int64(i int64) int64 {
return i
}
// Float32 复制 float32 对象,并返回复制体
func Float32(f float32) float32 {
return f
}
// Float64 复制 float64 对象,并返回复制体
func Float64(f float64) float64 {
return f
}
// String 复制 string 对象,并返回复制体
func String(s string) string {
return s
}
// Int 复制 int 对象,并返回复制体
func Int(i int) int {
return i
}
// Uint 复制 uint 对象,并返回复制体
func Uint(ui uint) uint {
return ui
}
// Any 复制 any 对象,并返回复制体
func Any(a any) any {
return a
}

@ -1,9 +0,0 @@
package dorm
import "github.com/upper/db/v4"
// UpperClient
// https://upper.io/
type UpperClient struct {
Db *db.Session // 驱动
}

@ -1,23 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/upper/db/v4/adapter/cockroachdb"
)
func NewUpperCockroachdbClient(settings cockroachdb.ConnectionURL) (*UpperClient, error) {
var err error
c := &UpperClient{}
sess, err := cockroachdb.Open(settings)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
defer sess.Close()
c.Db = &sess
return c, nil
}

@ -1,23 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/upper/db/v4/adapter/mongo"
)
func NewUpperMongodbClient(settings mongo.ConnectionURL) (*UpperClient, error) {
var err error
c := &UpperClient{}
sess, err := mongo.Open(settings)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
defer sess.Close()
c.Db = &sess
return c, nil
}

@ -1,23 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/upper/db/v4/adapter/mssql"
)
func NewUpperMssqlClient(settings mssql.ConnectionURL) (*UpperClient, error) {
var err error
c := &UpperClient{}
sess, err := mssql.Open(settings)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
defer sess.Close()
c.Db = &sess
return c, nil
}

@ -1,23 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/upper/db/v4/adapter/mysql"
)
func NewUpperMysqlClient(settings mysql.ConnectionURL) (*UpperClient, error) {
var err error
c := &UpperClient{}
sess, err := mysql.Open(settings)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
defer sess.Close()
c.Db = &sess
return c, nil
}

@ -1,23 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/upper/db/v4/adapter/postgresql"
)
func NewUpperPostgresqlClient(settings postgresql.ConnectionURL) (*UpperClient, error) {
var err error
c := &UpperClient{}
sess, err := postgresql.Open(settings)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
defer sess.Close()
c.Db = &sess
return c, nil
}

@ -1,23 +0,0 @@
package dorm
import (
"errors"
"fmt"
"github.com/upper/db/v4/adapter/ql"
)
func NewUpperQlClient(settings ql.ConnectionURL) (*UpperClient, error) {
var err error
c := &UpperClient{}
sess, err := ql.Open(settings)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
defer sess.Close()
c.Db = &sess
return c, nil
}

@ -1,3 +1,4 @@
package dorm
const Version = "1.0.7"
// Version 版本
const Version = "1.0.59"

@ -1,16 +0,0 @@
package dorm
import (
"xorm.io/xorm"
)
type ConfigXormClient struct {
Dns string // 地址
}
// XormClient
// https://xorm.io/
type XormClient struct {
Db *xorm.Engine // 驱动
config *ConfigXormClient // 配置
}

@ -1,21 +0,0 @@
package dorm
import (
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"xorm.io/xorm"
)
func NewXormMysqlClient(config *ConfigXormClient) (*XormClient, error) {
var err error
c := &XormClient{config: config}
c.Db, err = xorm.NewEngine("mysql", c.config.Dns)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}

@ -1,21 +0,0 @@
package dorm
import (
"errors"
"fmt"
_ "github.com/lib/pq"
"xorm.io/xorm"
)
func NewXormPostgresClient(config *ConfigXormClient) (*XormClient, error) {
var err error
c := &XormClient{config: config}
c.Db, err = xorm.NewEngine("postgres", c.config.Dns)
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}

@ -1,27 +0,0 @@
package dorm
import (
"xorm.io/xorm"
)
// XormClientSession https://xorm.io/zh/docs/chapter-10/readme/
type XormClientSession struct {
*xorm.Session
}
// Begin 开始事务,需要创建 Session 对象
//func (c *XormClient) Begin() (*XormClientSession, error) {
// session := c.Db.NewSession()
// defer session.Close()
// return &session, session.Begin()
//}
// Rollback 回滚事务
//func (c *XormClientSession) Rollback() error {
// return c.Rollback()
//}
// Commit 提交事务
//func (c *XormClientSession) Commit() error {
// return c.Commit()
//}

@ -1,17 +0,0 @@
package dorm
import (
"gitee.com/chunanyong/zorm"
)
type ConfigZormClient struct {
Dns string // 地址
}
// ZormClient
// https://zorm.cn/
// https://www.yuque.com/u27016943/nrgi00
type ZormClient struct {
Db *zorm.DBDao // 驱动
config *ConfigZormClient // 配置
}

@ -1,31 +0,0 @@
package dorm
import (
"errors"
"fmt"
"gitee.com/chunanyong/zorm"
_ "github.com/mailru/go-clickhouse/v2"
)
func NewZormClickhouseClient(config *ConfigZormClient) (*ZormClient, error) {
var err error
c := &ZormClient{config: config}
c.Db, err = zorm.NewDBDao(&zorm.DataSourceConfig{
DSN: c.config.Dns,
DriverName: "chhttp", // 数据库驱动名称
DBType: "clickhouse", // 数据库类型
PrintSQL: true, // 是否打印sql
MaxOpenConns: 0, // 数据库最大连接数,默认50
MaxIdleConns: 0, // 数据库最大空闲连接数,默认50
ConnMaxLifetimeSecond: 0, // 连接存活秒时间. 默认600(10分钟)后连接被销毁重建.
// 避免数据库主动断开连接,造成死连接.MySQL默认wait_timeout 28800秒(8小时)
DefaultTxOptions: nil, // 事务隔离级别的默认配置,默认为nil
})
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}

@ -1,31 +0,0 @@
package dorm
import (
"errors"
"fmt"
_ "gitee.com/chunanyong/dm"
"gitee.com/chunanyong/zorm"
)
func NewZormDmClient(config *ConfigZormClient) (*ZormClient, error) {
var err error
c := &ZormClient{config: config}
c.Db, err = zorm.NewDBDao(&zorm.DataSourceConfig{
DSN: c.config.Dns,
DriverName: "dm", // 数据库驱动名称
DBType: "dm", // 数据库类型
PrintSQL: true, // 是否打印sql
MaxOpenConns: 0, // 数据库最大连接数,默认50
MaxIdleConns: 0, // 数据库最大空闲连接数,默认50
ConnMaxLifetimeSecond: 0, // 连接存活秒时间. 默认600(10分钟)后连接被销毁重建.
// 避免数据库主动断开连接,造成死连接.MySQL默认wait_timeout 28800秒(8小时)
DefaultTxOptions: nil, // 事务隔离级别的默认配置,默认为nil
})
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}

@ -1 +0,0 @@
package dorm

@ -1 +0,0 @@
package dorm

@ -1,31 +0,0 @@
package dorm
import (
"errors"
"fmt"
"gitee.com/chunanyong/zorm"
_ "github.com/go-sql-driver/mysql"
)
func NewZormMysqlClient(config *ConfigZormClient) (*ZormClient, error) {
var err error
c := &ZormClient{config: config}
c.Db, err = zorm.NewDBDao(&zorm.DataSourceConfig{
DSN: c.config.Dns,
DriverName: "mysql", // 数据库驱动名称
DBType: "mysql", // 数据库类型
PrintSQL: true, // 是否打印sql
MaxOpenConns: 0, // 数据库最大连接数,默认50
MaxIdleConns: 0, // 数据库最大空闲连接数,默认50
ConnMaxLifetimeSecond: 0, // 连接存活秒时间. 默认600(10分钟)后连接被销毁重建.
// 避免数据库主动断开连接,造成死连接.MySQL默认wait_timeout 28800秒(8小时)
DefaultTxOptions: nil, // 事务隔离级别的默认配置,默认为nil
})
if err != nil {
return nil, errors.New(fmt.Sprintf("连接失败:%v", err))
}
return c, nil
}

@ -1 +0,0 @@
package dorm
Loading…
Cancel
Save