db.go 6.2 KB

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