db.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. defaultDB *DB
  20. errNoneConnect = errors.New(`数据库连接错误`)
  21. )
  22. // DB define
  23. type DB struct {
  24. Driver string
  25. conn *sqlx.DB
  26. tx *sqlx.Tx
  27. }
  28. // SetConfig set
  29. func SetConfig(cfg Config) {
  30. config.Driver = cfg.Driver
  31. config.DNS = cfg.DNS
  32. config.MaxOpenConns = cfg.MaxOpenConns
  33. config.MaxIdle = cfg.MaxIdle
  34. config.MaxIdleTime = cfg.MaxIdleTime * time.Second
  35. config.MaxLifeTime = cfg.MaxLifeTime * time.Second
  36. defaultDB = &DB{Driver: config.Driver}
  37. }
  38. // New new DB object
  39. func New() *DB {
  40. return &DB{Driver: config.Driver}
  41. }
  42. // Release free db connect
  43. func Release() {
  44. if db != nil {
  45. db.Close()
  46. }
  47. }
  48. // NewConfig new DB dynamic object
  49. func NewConfig(config Config) (dbx *DB, err error) {
  50. dbx = &DB{}
  51. dbx.Driver = config.Driver
  52. dbx.conn, err = sqlx.Connect(config.Driver, config.DNS)
  53. if err != nil {
  54. return
  55. }
  56. dbx.conn.SetMaxOpenConns(config.MaxOpenConns)
  57. dbx.conn.SetMaxIdleConns(config.MaxIdle)
  58. dbx.conn.SetConnMaxIdleTime(config.MaxIdleTime)
  59. dbx.conn.SetConnMaxLifetime(config.MaxLifeTime)
  60. err = dbx.conn.Ping()
  61. return
  62. }
  63. // ReleaseConfig free db connect
  64. func ReleaseConfig(dbx *DB) {
  65. if dbx.conn != nil {
  66. dbx.conn.Close()
  67. }
  68. }
  69. func connect() (dbx *sqlx.DB, err error) {
  70. once.Do(func() {
  71. db, err = sqlx.Connect(config.Driver, config.DNS)
  72. if err != nil {
  73. fmt.Println("Connect ERR", err)
  74. return
  75. }
  76. db.DB.SetMaxOpenConns(config.MaxOpenConns)
  77. db.DB.SetMaxIdleConns(config.MaxIdle)
  78. db.DB.SetConnMaxIdleTime(config.MaxIdleTime)
  79. db.DB.SetConnMaxLifetime(config.MaxLifeTime)
  80. err = db.Ping()
  81. if err != nil {
  82. fmt.Println("Connect Ping", err)
  83. return
  84. }
  85. })
  86. if db == nil {
  87. err = errNoneConnect
  88. return
  89. }
  90. dbx = db
  91. return
  92. }
  93. // Stats Stats returns database statistics.
  94. func (d *DB) Stats() (s sql.DBStats) {
  95. s = d.conn.DB.Stats()
  96. return
  97. }
  98. // Connect connect to database
  99. func (d *DB) Connect() (err error) {
  100. if d.conn != nil {
  101. return
  102. }
  103. d.conn, err = connect()
  104. return
  105. }
  106. // Close close database connect
  107. func (d *DB) Close() {
  108. // use pool
  109. //d.conn.Close()
  110. }
  111. // Ping Ping connect
  112. func (d *DB) Ping() (err error) {
  113. d.conn, err = connect()
  114. if err != nil {
  115. return
  116. }
  117. return d.conn.Ping()
  118. }
  119. // BeginTrans begin trans
  120. func (d *DB) BeginTrans() (err error) {
  121. d.conn, err = connect()
  122. if err != nil {
  123. return
  124. }
  125. d.tx, err = d.conn.Beginx()
  126. return
  127. }
  128. // Commit commit
  129. func (d *DB) Commit() (err error) {
  130. return d.tx.Commit()
  131. }
  132. // Rollback rollback
  133. func (d *DB) Rollback() (err error) {
  134. return d.tx.Rollback()
  135. }
  136. // TransExec trans execute
  137. func (d *DB) TransExec(query string, args interface{}) (LastInsertId, RowsAffected int64, err error) {
  138. if rs, err := d.tx.NamedExec(query, args); err == nil {
  139. RowsAffected, _ = rs.RowsAffected()
  140. LastInsertId, _ = rs.LastInsertId()
  141. }
  142. return
  143. }
  144. // TransUpdate trans update
  145. func (d *DB) TransUpdate(query string, args interface{}) (reply Reply) {
  146. var (
  147. err error
  148. rs sql.Result
  149. )
  150. if rs, err = d.tx.NamedExec(query, args); err == nil {
  151. a, _ := rs.RowsAffected()
  152. reply = ReplyOk(a, 0)
  153. } else {
  154. reply = ReplyFaild(ErrException, err, errors.New(`数据执行错误`))
  155. }
  156. return
  157. }
  158. // TransRow trans get row
  159. func (d *DB) TransRow(dest interface{}, query string, args interface{}) (err error) {
  160. nstmt, err := d.tx.PrepareNamed(query)
  161. if err != nil {
  162. return err
  163. }
  164. defer nstmt.Close()
  165. err = nstmt.Get(dest, args)
  166. //err = d.tx.Get(dest, query, args)
  167. return err
  168. }
  169. // Select select
  170. func (d *DB) Select(dest interface{}, query string, args ...interface{}) error {
  171. err := d.Connect()
  172. if err != nil {
  173. return err
  174. }
  175. defer d.Close()
  176. err = d.conn.Select(dest, query, args...)
  177. return err
  178. }
  179. // Rows get rows
  180. func (d *DB) Rows(dest interface{}, query string, args interface{}) error {
  181. err := d.Connect()
  182. if err != nil {
  183. return err
  184. }
  185. defer d.Close()
  186. nstmt, err := d.conn.PrepareNamed(query)
  187. if err != nil {
  188. return err
  189. }
  190. defer nstmt.Close()
  191. err = nstmt.Select(dest, args)
  192. return err
  193. }
  194. // Get get
  195. func (d *DB) Get(dest interface{}, query string, args ...interface{}) error {
  196. err := d.Connect()
  197. if err != nil {
  198. return err
  199. }
  200. defer d.Close()
  201. err = d.conn.Get(dest, query, args...)
  202. return err
  203. }
  204. // Row get row
  205. func (d *DB) Row(dest interface{}, query string, args interface{}) error {
  206. err := d.Connect()
  207. if err != nil {
  208. return err
  209. }
  210. defer d.Close()
  211. nstmt, err := d.conn.PrepareNamed(query)
  212. if err != nil {
  213. return err
  214. }
  215. defer nstmt.Close()
  216. err = nstmt.Get(dest, args)
  217. return err
  218. }
  219. // InsertReply insert and return DbReply
  220. func (d *DB) InsertReply(query string, args interface{}) (reply Reply) {
  221. var (
  222. err error
  223. rs sql.Result
  224. )
  225. err = d.Connect()
  226. if err != nil {
  227. reply = ReplyFaild(ErrNotConnect, err, errors.New(`数据库连接错误`))
  228. return
  229. }
  230. defer d.Close()
  231. if rs, err = d.conn.NamedExec(query, args); err == nil {
  232. a, _ := rs.RowsAffected()
  233. n, _ := rs.LastInsertId()
  234. reply = ReplyOk(a, n)
  235. } else {
  236. reply = ReplyFaild(ErrException, err, errors.New(`数据执行错误`))
  237. }
  238. return
  239. }
  240. // UpdateReply update/delete and return DbReply
  241. func (d *DB) UpdateReply(query string, args interface{}) (reply Reply) {
  242. var (
  243. err error
  244. rs sql.Result
  245. )
  246. err = d.Connect()
  247. if err != nil {
  248. reply = ReplyFaild(ErrNotConnect, err, errors.New(`数据库连接错误`))
  249. return
  250. }
  251. defer d.Close()
  252. if rs, err = d.conn.NamedExec(query, args); err == nil {
  253. a, _ := rs.RowsAffected()
  254. reply = ReplyOk(a, 0)
  255. } else {
  256. reply = ReplyFaild(ErrException, err, errors.New(`数据执行错误`))
  257. }
  258. return
  259. }
  260. // Insert insert into
  261. func (d *DB) Insert(query string, args interface{}) (LastInsertId, RowsAffected int64, err error) {
  262. err = d.Connect()
  263. if err != nil {
  264. return
  265. }
  266. defer d.Close()
  267. var rs sql.Result
  268. if rs, err = d.conn.NamedExec(query, args); err == nil {
  269. LastInsertId, _ = rs.LastInsertId()
  270. RowsAffected, _ = rs.RowsAffected()
  271. }
  272. return
  273. }
  274. // Update update/delete
  275. func (d *DB) Update(query string, args interface{}) (RowsAffected int64, err error) {
  276. err = d.Connect()
  277. if err != nil {
  278. return
  279. }
  280. defer d.Close()
  281. var rs sql.Result
  282. if rs, err = d.conn.NamedExec(query, args); err == nil {
  283. RowsAffected, _ = rs.RowsAffected()
  284. }
  285. return
  286. }
  287. // Exec exec
  288. func (d *DB) Exec(query string, args ...interface{}) (LastInsertId, RowsAffected int64, err error) {
  289. err = d.Connect()
  290. if err != nil {
  291. return
  292. }
  293. defer d.Close()
  294. var rs sql.Result
  295. if rs, err = d.conn.Exec(query, args...); err == nil {
  296. LastInsertId, _ = rs.LastInsertId()
  297. RowsAffected, _ = rs.RowsAffected()
  298. }
  299. return
  300. }
  301. // Limit MySQL limit
  302. func (d *DB) Limit(page, pagesize int) string {
  303. // MySQL limit 0, size
  304. if d.Driver == `mysql` {
  305. return fmt.Sprintf(" limit %d, %d", (page-1)*pagesize, pagesize)
  306. }
  307. // // PostgreSQL limit size offset 0
  308. return fmt.Sprintf(" limit %d offset %d", pagesize, (page-1)*pagesize)
  309. }
  310. // Ping ping connect
  311. func Ping() (err error) {
  312. defaultDB.conn, err = connect()
  313. if err != nil {
  314. return
  315. }
  316. err = defaultDB.Ping()
  317. return
  318. }
  319. // Select select
  320. func Select(dest interface{}, query string, args ...interface{}) (err error) {
  321. defaultDB.conn, err = connect()
  322. if err != nil {
  323. return err
  324. }
  325. err = defaultDB.conn.Select(dest, query, args...)
  326. return
  327. }
  328. // Rows get rows
  329. func Rows(dest interface{}, query string, args interface{}) (err error) {
  330. defaultDB.conn, err = connect()
  331. if err != nil {
  332. return err
  333. }
  334. nstmt, err := defaultDB.conn.PrepareNamed(query)
  335. if err != nil {
  336. return
  337. }
  338. defer nstmt.Close()
  339. err = nstmt.Select(dest, args)
  340. return
  341. }
  342. // Get get
  343. func Get(dest interface{}, query string, args ...interface{}) (err error) {
  344. defaultDB.conn, err = connect()
  345. if err != nil {
  346. return
  347. }
  348. err = defaultDB.conn.Get(dest, query, args...)
  349. return
  350. }
  351. // Row get row
  352. func Row(dest interface{}, query string, args interface{}) (err error) {
  353. defaultDB.conn, err = connect()
  354. if err != nil {
  355. return
  356. }
  357. nstmt, err := defaultDB.conn.PrepareNamed(query)
  358. if err != nil {
  359. return err
  360. }
  361. defer nstmt.Close()
  362. err = nstmt.Get(dest, args)
  363. return
  364. }
  365. func Exec(query string, args ...interface{}) (LastInsertId, RowsAffected int64, err error) {
  366. defaultDB.conn, err = connect()
  367. if err != nil {
  368. return
  369. }
  370. LastInsertId, RowsAffected, err = defaultDB.Exec(query, args...)
  371. return
  372. }