/common/db/db.go

https://github.com/labulaka521/crocodile · Go · 92 lines · 70 code · 14 blank · 8 comment · 3 complexity · 044bba4ff1236654e10c0180be8c2b70 MD5 · raw file

  1. package db
  2. import (
  3. "context"
  4. "database/sql"
  5. "time"
  6. _ "github.com/go-sql-driver/mysql" // registry sqlite3 deive
  7. _ "github.com/mattn/go-sqlite3" // registry mysql drive
  8. )
  9. var (
  10. _db *sql.DB
  11. )
  12. type dbCfg struct {
  13. DriveName string
  14. Dsn string
  15. MaxIdleConnection int
  16. MaxOpenConnection int
  17. MaxQueryTime time.Duration
  18. }
  19. // GetConn from db conn pool
  20. func GetConn(ctx context.Context) (*sql.Conn, error) {
  21. return _db.Conn(ctx)
  22. }
  23. // Option is function option
  24. type Option func(*dbCfg)
  25. // Drivename Set mysql or sqlite
  26. func Drivename(drivename string) Option {
  27. return func(dbcfg *dbCfg) {
  28. dbcfg.DriveName = drivename
  29. }
  30. }
  31. // Dsn set dbCfg conn addr
  32. func Dsn(dsn string) func(*dbCfg) {
  33. return func(dbcfg *dbCfg) {
  34. dbcfg.Dsn = dsn
  35. }
  36. }
  37. // MaxIdleConnection set sql db max idle conn
  38. func MaxIdleConnection(idle int) Option {
  39. return func(dbcfg *dbCfg) {
  40. dbcfg.MaxIdleConnection = idle
  41. }
  42. }
  43. // MaxOpenConnection set sql db max open conn
  44. func MaxOpenConnection(open int) Option {
  45. return func(dbcfg *dbCfg) {
  46. dbcfg.MaxOpenConnection = open
  47. }
  48. }
  49. // MaxQueryTime set sql conn exec max timeout
  50. func MaxQueryTime(query time.Duration) Option {
  51. return func(dbcfg *dbCfg) {
  52. dbcfg.MaxQueryTime = query
  53. }
  54. }
  55. func defaultdbOption() *dbCfg {
  56. return &dbCfg{
  57. DriveName: "sqlite3",
  58. Dsn: "sqlite3.db",
  59. MaxIdleConnection: 10,
  60. MaxOpenConnection: 5,
  61. MaxQueryTime: 3,
  62. }
  63. }
  64. // NewDb create new db
  65. func NewDb(opts ...Option) (err error) {
  66. dbcfg := defaultdbOption()
  67. for _, opt := range opts {
  68. opt(dbcfg)
  69. }
  70. _db, err = sql.Open(dbcfg.DriveName, dbcfg.Dsn)
  71. if err != nil {
  72. return err
  73. }
  74. _db.SetMaxOpenConns(dbcfg.MaxOpenConnection)
  75. _db.SetMaxIdleConns(dbcfg.MaxIdleConnection)
  76. err = _db.Ping()
  77. return err
  78. }