/database/database.go

https://github.com/traggo/server · Go · 57 lines · 40 code · 10 blank · 7 comment · 9 complexity · f322ab1183f1b4fafd47bf47a1db44f3 MD5 · raw file

  1. package database
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/jinzhu/gorm"
  6. _ "github.com/jinzhu/gorm/dialects/mysql" // enable the mysql dialect
  7. _ "github.com/jinzhu/gorm/dialects/postgres" // enable the postgres dialect
  8. _ "github.com/jinzhu/gorm/dialects/sqlite" // enable the sqlite3 dialect
  9. "github.com/rs/zerolog/log"
  10. "github.com/traggo/server/logger"
  11. "github.com/traggo/server/model"
  12. )
  13. var mkdirAll = os.MkdirAll
  14. // New creates a gorm instance.
  15. func New(dialect, connection string) (*gorm.DB, error) {
  16. createDirectoryIfSqlite(dialect, connection)
  17. db, err := gorm.Open(dialect, connection)
  18. if err != nil {
  19. return nil, err
  20. }
  21. db.LogMode(true)
  22. db.SetLogger(&logger.DatabaseLogger{})
  23. // We normally don't need that much connections, so we limit them. F.ex. mysql complains about
  24. // "too many connections".
  25. db.DB().SetMaxOpenConns(10)
  26. if dialect == "sqlite3" {
  27. // We use the database connection inside the handlers from the http
  28. // framework, therefore concurrent access occurs. Sqlite cannot handle
  29. // concurrent writes, so we limit sqlite to one connection.
  30. // see https://github.com/mattn/go-sqlite3/issues/274
  31. db.DB().SetMaxOpenConns(1)
  32. db.Exec("PRAGMA foreign_keys = ON")
  33. }
  34. log.Debug().Msg("Auto migrating schema's")
  35. db.AutoMigrate(model.All()...)
  36. log.Debug().Msg("Database initialized")
  37. return db, nil
  38. }
  39. func createDirectoryIfSqlite(dialect string, connection string) {
  40. if dialect == "sqlite3" {
  41. if _, err := os.Stat(filepath.Dir(connection)); os.IsNotExist(err) {
  42. if err := mkdirAll(filepath.Dir(connection), 0777); err != nil {
  43. panic(err)
  44. }
  45. }
  46. }
  47. }