db.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. package db
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "sync"
  7. "time"
  8. "git.chuangxin1.com/cx/tyr"
  9. // mysql
  10. _ "github.com/go-sql-driver/mysql"
  11. "github.com/jmoiron/sqlx"
  12. )
  13. // DB error code
  14. const (
  15. DBErrCodeOK = 0 // DBErrCodeOK ok
  16. DBErrCodeException = 1 // DBErrCodeException exception
  17. DBErrCodeExists = 2 // DBErrCodeExists exists
  18. DBErrCodeNotFound = 3 // DBErrCodeNotFound not found
  19. DBErrCodeAuthorized = 4 // DBErrCodeAuthorized authorized
  20. DBErrCodeNotConnect = 5 // DBErrCodeNotConnect connect error
  21. )
  22. // Config config
  23. type Config struct {
  24. Driver string
  25. DNS string
  26. MaxOpenConns int
  27. MaxIdle int
  28. MaxLifetime time.Duration
  29. }
  30. // Reply db exec return insert/update/delete
  31. type Reply struct {
  32. OK bool
  33. Err error
  34. LastErr error
  35. ErrCode int
  36. LastID int64
  37. RowsAffected int64
  38. }
  39. // ReplyToReplyData db reply to response
  40. func ReplyToReplyData(reply Reply) *tyr.ReplyData {
  41. status := tyr.ErrOk
  42. if !reply.OK {
  43. switch reply.ErrCode {
  44. case DBErrCodeException:
  45. status = tyr.ErrException
  46. case DBErrCodeExists:
  47. status = tyr.ErrDataExists
  48. case DBErrCodeNotFound:
  49. status = tyr.ErrDataNotFound
  50. case DBErrCodeAuthorized:
  51. status = tyr.ErrUnAuthorized
  52. case DBErrCodeNotConnect:
  53. status = tyr.ErrNotFound
  54. }
  55. return tyr.ErrReplyData(status, reply.LastErr.Error())
  56. }
  57. return tyr.OkReplyData()
  58. }
  59. var (
  60. config Config
  61. db *sqlx.DB
  62. err error
  63. once sync.Once
  64. )
  65. // DB define
  66. type DB struct {
  67. conn *sqlx.DB
  68. tx *sqlx.Tx
  69. }
  70. // SetDbConfig set
  71. func SetDbConfig(cfg Config) {
  72. config.Driver = cfg.Driver
  73. config.DNS = cfg.DNS
  74. config.MaxOpenConns = cfg.MaxOpenConns
  75. config.MaxIdle = cfg.MaxIdle
  76. config.MaxLifetime = cfg.MaxLifetime * time.Second
  77. }
  78. // ErrSQLNoRows check norows error
  79. func ErrSQLNoRows(err error) bool {
  80. if err == sql.ErrNoRows {
  81. return true
  82. }
  83. return false
  84. }
  85. // ReplyOk exec ok
  86. func ReplyOk(rowsAffected, lastID int64) Reply {
  87. var reply Reply
  88. reply.OK = true
  89. reply.ErrCode = 0
  90. reply.LastID = lastID
  91. reply.RowsAffected = rowsAffected
  92. return reply
  93. }
  94. // ReplyFaild exec faild
  95. func ReplyFaild(errCode int, err, errText error) (reply Reply) {
  96. reply.OK = false
  97. reply.ErrCode = errCode
  98. reply.LastID = -1
  99. reply.RowsAffected = -1
  100. reply.Err = err
  101. reply.LastErr = errText
  102. return
  103. }
  104. // NewDB new DB object
  105. func NewDB() *DB {
  106. return &DB{}
  107. }
  108. // ReleaseDB free db connect
  109. func ReleaseDB() {
  110. if db != nil {
  111. db.Close()
  112. }
  113. }
  114. // NewConfigDB new DB dynamic object
  115. func NewConfigDB(config Config) (dbx *DB, err error) {
  116. dbx = &DB{}
  117. dbx.conn, err = sqlx.Connect(config.Driver, config.DNS)
  118. if err == nil {
  119. dbx.conn.SetMaxOpenConns(config.MaxOpenConns)
  120. dbx.conn.SetMaxIdleConns(config.MaxIdle)
  121. dbx.conn.SetConnMaxLifetime(config.MaxLifetime)
  122. dbx.conn.Ping()
  123. }
  124. return
  125. }
  126. // ReleaseConfigDB free db connect
  127. func ReleaseConfigDB(dbx *DB) {
  128. if dbx.conn != nil {
  129. dbx.conn.Close()
  130. }
  131. }
  132. func connect() (dbx *sqlx.DB, err error) {
  133. once.Do(func() {
  134. db, err = sqlx.Connect(config.Driver, config.DNS)
  135. if err == nil {
  136. db.DB.SetMaxOpenConns(config.MaxOpenConns)
  137. db.DB.SetMaxIdleConns(config.MaxIdle)
  138. db.DB.SetConnMaxLifetime(config.MaxLifetime)
  139. db.Ping()
  140. }
  141. })
  142. dbx = db
  143. return
  144. }
  145. // Connect connect to database
  146. func (d *DB) Connect() (err error) {
  147. if d.conn != nil {
  148. return
  149. }
  150. d.conn, err = connect()
  151. return
  152. }
  153. // Close close database connect
  154. func (d *DB) Close() {
  155. //d.conn.Close()
  156. }
  157. // BeginTrans begin trans
  158. func (d *DB) BeginTrans() (err error) {
  159. d.conn, err = connect()
  160. if err != nil {
  161. return
  162. }
  163. d.tx = d.conn.MustBegin()
  164. return
  165. }
  166. // Commit commit
  167. func (d *DB) Commit() error {
  168. return d.tx.Commit()
  169. }
  170. // Rollback rollback
  171. func (d *DB) Rollback() error {
  172. return d.tx.Rollback()
  173. }
  174. // TransExec trans execute
  175. func (d *DB) TransExec(query string, args interface{}) (LastInsertId, RowsAffected int64, err error) {
  176. if rs, err := d.tx.NamedExec(query, args); err == nil {
  177. RowsAffected, _ = rs.RowsAffected()
  178. LastInsertId, _ = rs.LastInsertId()
  179. }
  180. return
  181. }
  182. // TransUpdate trans update
  183. func (d *DB) TransUpdate(query string, args interface{}) (reply Reply) {
  184. var (
  185. err error
  186. rs sql.Result
  187. )
  188. if rs, err = d.tx.NamedExec(query, args); err == nil {
  189. a, _ := rs.RowsAffected()
  190. reply = ReplyOk(a, 0)
  191. } else {
  192. reply = ReplyFaild(DBErrCodeException, err, errors.New(`数据执行错误`))
  193. }
  194. return
  195. }
  196. // Rows get rows
  197. func (d *DB) Rows(dest interface{}, query string, args interface{}) error {
  198. err := d.Connect()
  199. if err != nil {
  200. return err
  201. }
  202. defer d.Close()
  203. nstmt, err := d.conn.PrepareNamed(query)
  204. if err != nil {
  205. return err
  206. }
  207. defer nstmt.Close()
  208. err = nstmt.Select(dest, args)
  209. return err
  210. }
  211. // Row get row
  212. func (d *DB) Row(dest interface{}, query string, args interface{}) error {
  213. err := d.Connect()
  214. if err != nil {
  215. return err
  216. }
  217. defer d.Close()
  218. nstmt, err := d.conn.PrepareNamed(query)
  219. if err != nil {
  220. return err
  221. }
  222. defer nstmt.Close()
  223. err = nstmt.Get(dest, args)
  224. return err
  225. }
  226. // InsertReply insert and return DbReply
  227. func (d *DB) InsertReply(query string, args interface{}) (reply Reply) {
  228. var (
  229. err error
  230. rs sql.Result
  231. )
  232. err = d.Connect()
  233. if err != nil {
  234. reply = ReplyFaild(DBErrCodeNotConnect, err, errors.New(`数据库连接错误`))
  235. return
  236. }
  237. defer d.Close()
  238. if rs, err = d.conn.NamedExec(query, args); err == nil {
  239. a, _ := rs.RowsAffected()
  240. n, _ := rs.LastInsertId()
  241. reply = ReplyOk(a, n)
  242. } else {
  243. reply = ReplyFaild(DBErrCodeException, err, errors.New(`数据执行错误`))
  244. }
  245. return
  246. }
  247. // UpdateReply update/delete and return DbReply
  248. func (d *DB) UpdateReply(query string, args interface{}) (reply Reply) {
  249. var (
  250. err error
  251. rs sql.Result
  252. )
  253. err = d.Connect()
  254. if err != nil {
  255. reply = ReplyFaild(DBErrCodeNotConnect, err, errors.New(`数据库连接错误`))
  256. return
  257. }
  258. defer d.Close()
  259. if rs, err = d.conn.NamedExec(query, args); err == nil {
  260. a, _ := rs.RowsAffected()
  261. reply = ReplyOk(a, 0)
  262. } else {
  263. reply = ReplyFaild(DBErrCodeException, err, errors.New(`数据执行错误`))
  264. }
  265. return
  266. }
  267. // Insert insert into
  268. func (d *DB) Insert(query string, args interface{}) (LastInsertId, RowsAffected int64, err error) {
  269. err = d.Connect()
  270. if err != nil {
  271. return
  272. }
  273. defer d.Close()
  274. if rs, err := d.conn.NamedExec(query, args); err == nil {
  275. LastInsertId, _ = rs.LastInsertId()
  276. RowsAffected, _ = rs.RowsAffected()
  277. }
  278. return
  279. }
  280. // Update update/delete
  281. func (d *DB) Update(query string, args interface{}) (RowsAffected int64, err error) {
  282. err = d.Connect()
  283. if err != nil {
  284. return
  285. }
  286. defer d.Close()
  287. if rs, err := d.conn.NamedExec(query, args); err == nil {
  288. RowsAffected, _ = rs.RowsAffected()
  289. }
  290. return
  291. }
  292. // Limit MySQL limit
  293. func (d *DB) Limit(page, pagesize int) string {
  294. return fmt.Sprintf(" limit %d, %d", (page-1)*pagesize, pagesize)
  295. }