db.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. // Stats Stats returns database statistics.
  78. func (d *DB) Stats() (s sql.DBStats) {
  79. s = d.conn.DB.Stats()
  80. return
  81. }
  82. // Connect connect to database
  83. func (d *DB) Connect() (err error) {
  84. if d.conn != nil {
  85. return
  86. }
  87. d.conn, err = connect()
  88. return
  89. }
  90. // Close close database connect
  91. func (d *DB) Close() {
  92. // use pool
  93. //d.conn.Close()
  94. }
  95. // BeginTrans begin trans
  96. func (d *DB) BeginTrans() (err error) {
  97. d.conn, err = connect()
  98. if err != nil {
  99. return
  100. }
  101. d.tx = d.conn.MustBegin()
  102. return
  103. }
  104. // Commit commit
  105. func (d *DB) Commit() error {
  106. return d.tx.Commit()
  107. }
  108. // Rollback rollback
  109. func (d *DB) Rollback() error {
  110. return d.tx.Rollback()
  111. }
  112. // TransExec trans execute
  113. func (d *DB) TransExec(query string, args interface{}) (LastInsertId, RowsAffected int64, err error) {
  114. if rs, err := d.tx.NamedExec(query, args); err == nil {
  115. RowsAffected, _ = rs.RowsAffected()
  116. LastInsertId, _ = rs.LastInsertId()
  117. }
  118. return
  119. }
  120. // TransUpdate trans update
  121. func (d *DB) TransUpdate(query string, args interface{}) (reply Reply) {
  122. var (
  123. err error
  124. rs sql.Result
  125. )
  126. if rs, err = d.tx.NamedExec(query, args); err == nil {
  127. a, _ := rs.RowsAffected()
  128. reply = ReplyOk(a, 0)
  129. } else {
  130. reply = ReplyFaild(ErrException, err, errors.New(`数据执行错误`))
  131. }
  132. return
  133. }
  134. // TransRow trans get row
  135. func (d *DB) TransRow(dest interface{}, query string, args interface{}) error {
  136. nstmt, err := d.tx.PrepareNamed(query)
  137. if err != nil {
  138. return err
  139. }
  140. defer nstmt.Close()
  141. err = nstmt.Get(dest, args)
  142. //err = d.tx.Get(dest, query, args)
  143. return err
  144. }
  145. // Select select
  146. func (d *DB) Select(dest interface{}, query string, args ...interface{}) error {
  147. err := d.Connect()
  148. if err != nil {
  149. return err
  150. }
  151. defer d.Close()
  152. err = d.conn.Select(dest, query, args...)
  153. return err
  154. }
  155. // Rows get rows
  156. func (d *DB) Rows(dest interface{}, query string, args interface{}) error {
  157. err := d.Connect()
  158. if err != nil {
  159. return err
  160. }
  161. defer d.Close()
  162. nstmt, err := d.conn.PrepareNamed(query)
  163. if err != nil {
  164. return err
  165. }
  166. defer nstmt.Close()
  167. err = nstmt.Select(dest, args)
  168. return err
  169. }
  170. // Get get
  171. func (d *DB) Get(dest interface{}, query string, args ...interface{}) error {
  172. err := d.Connect()
  173. if err != nil {
  174. return err
  175. }
  176. defer d.Close()
  177. err = d.conn.Get(dest, query, args...)
  178. return err
  179. }
  180. // Row get row
  181. func (d *DB) Row(dest interface{}, query string, args interface{}) error {
  182. err := d.Connect()
  183. if err != nil {
  184. return err
  185. }
  186. defer d.Close()
  187. nstmt, err := d.conn.PrepareNamed(query)
  188. if err != nil {
  189. return err
  190. }
  191. defer nstmt.Close()
  192. err = nstmt.Get(dest, args)
  193. return err
  194. }
  195. // InsertReply insert and return DbReply
  196. func (d *DB) InsertReply(query string, args interface{}) (reply Reply) {
  197. var (
  198. err error
  199. rs sql.Result
  200. )
  201. err = d.Connect()
  202. if err != nil {
  203. reply = ReplyFaild(ErrNotConnect, err, errors.New(`数据库连接错误`))
  204. return
  205. }
  206. defer d.Close()
  207. if rs, err = d.conn.NamedExec(query, args); err == nil {
  208. a, _ := rs.RowsAffected()
  209. n, _ := rs.LastInsertId()
  210. reply = ReplyOk(a, n)
  211. } else {
  212. reply = ReplyFaild(ErrException, err, errors.New(`数据执行错误`))
  213. }
  214. return
  215. }
  216. // UpdateReply update/delete and return DbReply
  217. func (d *DB) UpdateReply(query string, args interface{}) (reply Reply) {
  218. var (
  219. err error
  220. rs sql.Result
  221. )
  222. err = d.Connect()
  223. if err != nil {
  224. reply = ReplyFaild(ErrNotConnect, err, errors.New(`数据库连接错误`))
  225. return
  226. }
  227. defer d.Close()
  228. if rs, err = d.conn.NamedExec(query, args); err == nil {
  229. a, _ := rs.RowsAffected()
  230. reply = ReplyOk(a, 0)
  231. } else {
  232. reply = ReplyFaild(ErrException, err, errors.New(`数据执行错误`))
  233. }
  234. return
  235. }
  236. // Insert insert into
  237. func (d *DB) Insert(query string, args interface{}) (LastInsertId, RowsAffected int64, err error) {
  238. err = d.Connect()
  239. if err != nil {
  240. return
  241. }
  242. defer d.Close()
  243. var rs sql.Result
  244. if rs, err = d.conn.NamedExec(query, args); err == nil {
  245. LastInsertId, _ = rs.LastInsertId()
  246. RowsAffected, _ = rs.RowsAffected()
  247. }
  248. return
  249. }
  250. // Update update/delete
  251. func (d *DB) Update(query string, args interface{}) (RowsAffected int64, err error) {
  252. err = d.Connect()
  253. if err != nil {
  254. return
  255. }
  256. defer d.Close()
  257. var rs sql.Result
  258. if rs, err = d.conn.NamedExec(query, args); err == nil {
  259. RowsAffected, _ = rs.RowsAffected()
  260. }
  261. return
  262. }
  263. // Exec exec
  264. func (d *DB) Exec(query string, args ...interface{}) (LastInsertId, RowsAffected int64, err error) {
  265. err = d.Connect()
  266. if err != nil {
  267. return
  268. }
  269. defer d.Close()
  270. var rs sql.Result
  271. if rs, err = d.conn.Exec(query, args...); err == nil {
  272. LastInsertId, _ = rs.LastInsertId()
  273. RowsAffected, _ = rs.RowsAffected()
  274. }
  275. return
  276. }
  277. // Limit MySQL limit
  278. func (d *DB) Limit(page, pagesize int) string {
  279. // MySQL limit 0, size
  280. if d.Driver == `mysql` {
  281. return fmt.Sprintf(" limit %d, %d", (page-1)*pagesize, pagesize)
  282. }
  283. // // PostgreSQL limit size offset 0
  284. return fmt.Sprintf(" limit %d offset %d", pagesize, (page-1)*pagesize)
  285. }