/databases/connection.go

https://github.com/bigfile/bigfile · Go · 60 lines · 40 code · 10 blank · 10 comment · 10 complexity · 7015d35ffc6e2a4633d7beb4dbcc7cb2 MD5 · raw file

  1. // Copyright 2019 The bigfile Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package databases provides capacity to interact with database
  5. package databases
  6. import (
  7. "time"
  8. "github.com/bigfile/bigfile/config"
  9. "github.com/jinzhu/gorm"
  10. // import mysql database driver
  11. _ "github.com/jinzhu/gorm/dialects/mysql"
  12. // import sqlite database driver
  13. _ "github.com/jinzhu/gorm/dialects/sqlite"
  14. )
  15. var connection *gorm.DB
  16. // NewConnection will initialize a connection to database. But, if connection
  17. // has already existed, it will be used.
  18. func NewConnection(dbConfig *config.Database) (*gorm.DB, error) {
  19. var (
  20. err error
  21. dsn string
  22. )
  23. if dbConfig == nil {
  24. dbConfig = &config.DefaultConfig.Database
  25. }
  26. if connection == nil {
  27. if dsn, err = dbConfig.DSN(); err != nil {
  28. return nil, err
  29. }
  30. if connection, err = gorm.Open(dbConfig.Driver, dsn); err != nil {
  31. return nil, err
  32. }
  33. connection.DB().SetConnMaxLifetime(time.Hour)
  34. connection.DB().SetMaxOpenConns(500)
  35. connection.DB().SetMaxIdleConns(0)
  36. }
  37. return connection, err
  38. }
  39. // MustNewConnection just call NewConnection, but, when something goes wrong, it will
  40. // raise a panic
  41. func MustNewConnection(dbConfig *config.Database) *gorm.DB {
  42. var (
  43. conn *gorm.DB
  44. err error
  45. )
  46. if conn, err = NewConnection(dbConfig); err != nil {
  47. panic(err)
  48. }
  49. return conn
  50. }