From 515e6ef366b4a71617b01d7f455a68cff502f41f Mon Sep 17 00:00:00 2001 From: Ryan Liu Date: Mon, 16 May 2022 17:46:42 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=BAtests=E5=A2=9E=E5=8A=A0default?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/default/conn.go | 60 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 models/default/conn.go diff --git a/models/default/conn.go b/models/default/conn.go new file mode 100644 index 0000000..ed25d34 --- /dev/null +++ b/models/default/conn.go @@ -0,0 +1,60 @@ +package db + +import ( + "github.com/azhai/xgen/models" + + "github.com/azhai/xgen/dialect" + "github.com/azhai/xgen/xquery" + _ "github.com/go-sql-driver/mysql" + "xorm.io/xorm" +) + +var ( + engine *xorm.Engine +) + +// ConnectXorm 连接数据库 +func ConnectXorm(cfg dialect.ConnConfig) *xorm.Engine { + if d := cfg.LoadDialect(); d == nil || !d.IsXormDriver() { + return nil + } + engine := cfg.QuickConnect(true, true) + if cfg.LogFile != "" { + logger := xquery.NewSqlLogger(cfg.LogFile) + engine.SetLogger(logger) + } + return engine +} + +// Engine 获取当前数据库连接 +func Engine() *xorm.Engine { + if engine == nil { + cfg := models.GetConnConfig("default") + engine = ConnectXorm(cfg) + } + return engine +} + +// Quote 转义表名或字段名 +func Quote(value string) string { + return Engine().Quote(value) +} + +// Table 查询某张数据表 +func Table(args ...interface{}) *xorm.Session { + qr := Engine().NewSession() + if args == nil { + return qr + } + return qr.Table(args[0]) +} + +// InsertBatch 写入多行数据 +func InsertBatch(tableName string, rows []map[string]interface{}) error { + if len(rows) == 0 { + return nil + } + return xquery.ExecTx(Engine(), func(tx *xorm.Session) (int64, error) { + return tx.Table(tableName).Insert(rows) + }) +}