dbCommon.go 2.91 KB
package sdkdb

import (
	"common"
	"io"
	"log"

	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

/**
 *  初始化
 */
func DBInit() {
	// 设置数据库类型
	orm.RegisterDriver("mysql", orm.DRMySQL)

	/*
		// 注册模型
		IceGameTopInit()
		IceGameTopSetInit()
		IceRewardInit()
		IceRewardUserInit()
	*/
}

/**
 *  注册数据库
 */
func DBRegis(dbmysql common.Mysql) (err error) {
	// 正式环境
	/*	dbUser := "icesimba_root"
		dbPasswd := "Icesimba858680668866sdk121"
		dbAddr := "rm-2zenjpu465r1ee1rd.mysql.rds.aliyuncs.com"
		dbPort := "3306"
		dbName := "icesimbasdk_pro"
	*/
	//测试环境

	dbUser := dbmysql.UserName
	dbPasswd := dbmysql.Password
	dbAddr := dbmysql.Address
	dbPort := dbmysql.Port
	dbName := dbmysql.DBName

	//预上线环境
	/*
	   dbUser := "trump"
	   dbPasswd := "Trump123"
	   dbAddr := "rm-2zeia588lj1117u37.mysql.rds.aliyuncs.com"
	   dbPort := "3306"
	   dbName := "icesimbasdk_verification"
	*/
	connStr := dbUser + ":" + dbPasswd + "@tcp(" + dbAddr + ":" + dbPort + ")/" + dbName + "?charset=utf8"
	log.Printf("DB connStr[%s]", connStr)

	err = orm.RegisterDataBase("default", "mysql", connStr)

	return
}

/**
 *  切换数据库
 */
func DBChange(dbName string) {
	o := orm.NewOrm()
	o.Using(dbName)
}

/**
 *  重置已经注册的模型struct
 */
func ResetRegisModel() {
	orm.ResetModelCache()
}

/**
 *  设置debug模式,如果设置debug模式,所有的数据库操作都会产生日志,日志会输出到writer中
 *  @param isPrintLog 是否打印日志
 *  @param writer 日志的输出定向
 */
func SetLogDebug(isPrintLog bool, writer io.Writer) {
	orm.Debug = isPrintLog
	orm.DebugLog = orm.NewLog(writer)
}

/**
 *  事务开始
 */
func DBBegin() (orm.Ormer, error) {
	o := orm.NewOrm()
	err := o.Begin()

	return o, err
}

/**
 *  事务提交
 */
func DBCommit(o orm.Ormer) error {
	err := o.Commit()
	return err
}

/**
 *  事务回滚
 */
func DBRollback(o orm.Ormer) error {
	err := o.Rollback()
	return err
}

/**
 *  查询某个表的数据
 *  @param tableName 表名
 */
func QueryTable(tableName string) orm.QuerySeter {
	o := orm.NewOrm()
	qs := o.QueryTable(tableName)

	return qs
}

/**
 *  执行sql(非查询)
 */
func SqlExec(sqlstr string, args ...interface{}) {
	o, _ := DBBegin()

	rawSeter := o.Raw(sqlstr, args...)
	res, err := rawSeter.Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		log.Println("mysql row affected nums: ", num)
	}

	DBCommit(o)
}

/**
 *  获取当前数据库的信息
 *  @return currDBName 当前数据库的名字
 *  @return currDBType 当前数据库的类型
 */
func CurrDBInfo() (currDBName string, currDBType string) {
	o := orm.NewOrm()
	dr := o.Driver()

	currDBName = dr.Name()

	switch dr.Type() {
	case orm.DRMySQL:
		currDBType = "mysql"
	case orm.DRSqlite:
		currDBType = "sqlite"
	case orm.DROracle:
		currDBType = "oracle"
	case orm.DRPostgres:
		currDBType = "pgsql"
	case orm.DRTiDB:
		currDBType = "TiDB"
	}

	return
}