/web/database/database.go

https://github.com/bojand/ghz · Go · 71 lines · 50 code · 15 blank · 6 comment · 11 complexity · faaa7e4093f967648d7e97c88dac3684 MD5 · raw file

  1. package database
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/bojand/ghz/web/model"
  6. "github.com/jinzhu/gorm"
  7. _ "github.com/jinzhu/gorm/dialects/mysql" // enable the mysql dialect
  8. _ "github.com/jinzhu/gorm/dialects/postgres" // enable the postgres dialect
  9. _ "github.com/jinzhu/gorm/dialects/sqlite" // enable the sqlite3 dialect
  10. )
  11. const dbName = "../test/test.db"
  12. // New creates a new wrapper for the gorm database framework.
  13. func New(dialect, connection string, log bool) (*Database, error) {
  14. if err := createDirectoryIfSqlite(dialect, connection); err != nil {
  15. return nil, err
  16. }
  17. db, err := gorm.Open(dialect, connection)
  18. if err != nil {
  19. return nil, err
  20. }
  21. db.LogMode(log)
  22. // We normally don't need that much connections, so we limit them.
  23. db.DB().SetMaxOpenConns(10)
  24. if dialect == "sqlite3" {
  25. // Sqlite cannot handle concurrent operations well so limit to one connection.
  26. db.DB().SetMaxOpenConns(1)
  27. // Turn on foreign keys.
  28. db.Exec("PRAGMA foreign_keys = ON;")
  29. }
  30. db.AutoMigrate(
  31. new(model.Project),
  32. new(model.Report),
  33. new(model.Options),
  34. new(model.Detail),
  35. new(model.Histogram),
  36. )
  37. return &Database{DB: db}, nil
  38. }
  39. func createDirectoryIfSqlite(dialect string, connection string) error {
  40. if dialect == "sqlite3" {
  41. if _, err := os.Stat(filepath.Dir(connection)); os.IsNotExist(err) {
  42. if err := os.MkdirAll(filepath.Dir(connection), 0777); err != nil {
  43. return err
  44. }
  45. }
  46. }
  47. return nil
  48. }
  49. // Database is a wrapper for the gorm framework.
  50. type Database struct {
  51. DB *gorm.DB
  52. }
  53. // Close closes the gorm database connection.
  54. func (d *Database) Close() error {
  55. return d.DB.Close()
  56. }