/vendor/github.com/gohouse/gorose/gorose.go

https://github.com/yxhsea/SecKill · Go · 263 lines · 176 code · 30 blank · 57 comment · 36 complexity · 1f5437826362f8799b758ea42137a1e6 MD5 · raw file

  1. package gorose
  2. import (
  3. "database/sql"
  4. "errors"
  5. "github.com/gohouse/gorose/drivers"
  6. )
  7. var (
  8. // DB is origin DB
  9. DB *sql.DB
  10. // Tx is transaction DB
  11. Tx *sql.Tx
  12. // Connect is the Connection Object
  13. Connect Connection
  14. //conn.SetMaxOpenConns int = 0
  15. //conn.SetMaxIdleConns int = -1
  16. )
  17. func init() {
  18. Connect.SetMaxOpenConns = 0
  19. Connect.SetMaxIdleConns = -1
  20. }
  21. // Open instance of sql.DB.Oper
  22. // if args has 1 param , it will be derect connection or with default config set
  23. // if args has 2 params , the second param will be the default dirver key
  24. func Open(args ...interface{}) (Connection, error) {
  25. //fmt.Println(args)
  26. //return Connect, errors.New("dsf")
  27. if len(args) == 1 {
  28. // continue
  29. } else if len(args) == 2 {
  30. if confReal, ok := args[1].(string); ok {
  31. Connect.Default = confReal
  32. } else {
  33. // 指定默认数据库只能为字符串!
  34. return Connect, errors.New("only str allowed of default database name")
  35. }
  36. } else {
  37. // Open方法只接收1个或2个参数!
  38. return Connect, errors.New("1 or 2 params need in Open() method")
  39. }
  40. // 解析config
  41. err := Connect.parseConfig(args[0])
  42. if err != nil {
  43. return Connect, err
  44. }
  45. // 驱动数据库
  46. errs := Connect.boot()
  47. return Connect, errs
  48. }
  49. // Connection is the database pre handle
  50. type Connection struct {
  51. // all config sets
  52. DbConfig map[string]interface{}
  53. // default database
  54. Default string
  55. // current config on use
  56. CurrentConfig map[string]string
  57. // all sql logs
  58. SqlLog []string
  59. // if in transaction, the code auto change
  60. Trans bool
  61. // max open connections
  62. SetMaxOpenConns int
  63. // max freedom connections leave
  64. SetMaxIdleConns int
  65. }
  66. // Parse input config
  67. func (conn *Connection) parseConfig(args interface{}) error {
  68. if confReal, ok := args.(map[string]string); ok { // direct connection
  69. Connect.CurrentConfig = confReal
  70. } else if confReal, ok := args.(map[string]interface{}); ok {
  71. // store the full connection
  72. Connect.DbConfig = confReal
  73. // if set the Default conf, store it
  74. if defaultDb, ok := confReal["Default"]; ok {
  75. // judge if seted
  76. if Connect.Default == "" {
  77. Connect.Default = defaultDb.(string)
  78. }
  79. }
  80. if Connect.Default == "" {
  81. // 配置文件默认数据库链接未设置
  82. return errors.New("the default database is missing in config!")
  83. }
  84. // 获取指定的默认数据库链接信息
  85. var connections map[string]map[string]string
  86. if connectionsInterface, ok := confReal["Connections"]; ok {
  87. switch connectionsInterface.(type) {
  88. case map[string]map[string]string:
  89. connections = connectionsInterface.(map[string]map[string]string)
  90. default:
  91. return errors.New("the database connections format error !")
  92. }
  93. } else {
  94. return errors.New("the database connections missing !")
  95. }
  96. if defaultDbConnection, ok := connections[Connect.Default]; ok {
  97. Connect.CurrentConfig = defaultDbConnection
  98. } else {
  99. // 指定的数据库链接不存在!
  100. return errors.New("the database for using is missing!")
  101. }
  102. // 设置连接池信息
  103. if mo, ok := confReal["SetMaxOpenConns"]; ok {
  104. if moInt, ok := mo.(int); ok {
  105. conn.SetMaxOpenConns = moInt
  106. } else {
  107. // 连接池信息配置的值只能是数字
  108. return errors.New("the value of connection pool config need int")
  109. }
  110. }
  111. if mi, ok := confReal["SetMaxIdleConns"]; ok {
  112. if miInt, ok := mi.(int); ok {
  113. conn.SetMaxIdleConns = miInt
  114. } else {
  115. return errors.New("the value of connection pool config need int")
  116. }
  117. }
  118. } else {
  119. return errors.New("format error in database config!")
  120. }
  121. return nil
  122. }
  123. // Boot sql driver
  124. func (conn *Connection) boot() error {
  125. dbObj := Connect.CurrentConfig
  126. var driver, dsn string
  127. var err error
  128. //DB, err = sql.Open("mysql", "root:@tcp(localhost:3306)/test?charset=utf8")
  129. switch dbObj["driver"] {
  130. case "mysql":
  131. driver, dsn = drivers.MySQL(dbObj)
  132. case "sqlite3":
  133. driver, dsn = drivers.Sqlite3(dbObj)
  134. case "postgres":
  135. driver, dsn = drivers.Postgres(dbObj)
  136. case "oracle":
  137. driver, dsn = drivers.Oracle(dbObj)
  138. case "mssql":
  139. driver, dsn = drivers.MsSQL(dbObj)
  140. }
  141. // 开始驱动
  142. DB, err = sql.Open(driver, dsn)
  143. DB.SetMaxOpenConns(conn.SetMaxOpenConns)
  144. DB.SetMaxIdleConns(conn.SetMaxIdleConns)
  145. if err != nil {
  146. return err
  147. }
  148. // 检查是否可以ping通
  149. err2 := DB.Ping()
  150. return err2
  151. }
  152. // Close database
  153. func (conn *Connection) Close() error {
  154. Connect.SqlLog = []string{}
  155. return DB.Close()
  156. }
  157. // Ping db
  158. func (conn *Connection) Ping() error {
  159. return DB.Ping()
  160. }
  161. // Table is set table from database
  162. func (conn *Connection) Table(table string) *Database {
  163. //conn.table = table
  164. var database Database
  165. return database.Table(table)
  166. }
  167. // Begin transaction begin
  168. func (conn *Connection) Begin() {
  169. Tx, _ = DB.Begin()
  170. Connect.Trans = true
  171. }
  172. // Commit is transaction commit
  173. func (conn *Connection) Commit() {
  174. Tx.Commit()
  175. Connect.Trans = false
  176. }
  177. // Rollback is transaction rollback
  178. func (conn *Connection) Rollback() {
  179. Tx.Rollback()
  180. Connect.Trans = false
  181. }
  182. // Transaction is simple transaction
  183. func (conn *Connection) Transaction(closure func() error) bool {
  184. //defer func() {
  185. // if err := recover(); err != nil {
  186. // conn.Rollback()
  187. // panic(err)
  188. // }
  189. //}()
  190. conn.Begin()
  191. err := closure()
  192. if err != nil {
  193. conn.Rollback()
  194. return false
  195. }
  196. conn.Commit()
  197. return true
  198. }
  199. // Query str
  200. func (conn *Connection) Query(args ...interface{}) ([]map[string]interface{}, error) {
  201. var database Database
  202. return database.Query(args...)
  203. }
  204. // Execute str
  205. func (conn *Connection) Execute(args ...interface{}) (int64, error) {
  206. var database Database
  207. return database.Execute(args...)
  208. }
  209. // GetInstance , get the database object
  210. func (conn *Connection) GetInstance() Database {
  211. var database Database
  212. return database
  213. }
  214. // JsonEncode : parse json
  215. func (dba *Connection) JsonEncode(arg interface{}) string {
  216. var database Database
  217. return database.JsonEncode(arg)
  218. }
  219. // LastSql is get last query sql
  220. func (conn *Connection) LastSql() string {
  221. if len(Connect.SqlLog) > 0 {
  222. return Connect.SqlLog[len(Connect.SqlLog)-1:][0]
  223. }
  224. return ""
  225. }
  226. // SqlLogs is all sql query logs in this request
  227. func (conn *Connection) SqlLogs() []string {
  228. return Connect.SqlLog
  229. }
  230. // GetDB is get origin *sql.DB
  231. func GetDB() *sql.DB {
  232. return DB
  233. }