Calorie counting web application written in the Go language

database.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package controllers
  2. import (
  3. "database/sql"
  4. "github.com/coopernurse/gorp"
  5. _ "github.com/mattn/go-sqlite3"
  6. "github.com/revel/revel"
  7. "github.com/revel/revel/modules/db/app"
  8. "github.com/revolvingcow/grassfed/app/models"
  9. )
  10. var (
  11. DbMap *gorp.DbMap
  12. )
  13. func Initialize() {
  14. db.Init()
  15. DbMap = &gorp.DbMap{ Db: db.Db, Dialect: gorp.SqliteDialect{} }
  16. DbMap.AddTable(models.Account{}).SetKeys(true, "Id")
  17. DbMap.AddTable(models.History{}).SetKeys(true, "Id")
  18. DbMap.AddTable(models.Goal{}).SetKeys(true, "Id")
  19. DbMap.AddTable(models.Weight{}).SetKeys(true, "Id")
  20. DbMap.TraceOn("[db]", revel.INFO)
  21. DbMap.CreateTablesIfNotExists()
  22. }
  23. type DatabaseController struct {
  24. *revel.Controller
  25. Transaction *gorp.Transaction
  26. }
  27. func (c *DatabaseController) Begin() revel.Result {
  28. transaction, err := DbMap.Begin()
  29. if err != nil {
  30. panic(err)
  31. }
  32. c.Transaction = transaction
  33. return nil
  34. }
  35. func (c *DatabaseController) Commit() revel.Result {
  36. if c.Transaction == nil {
  37. return nil
  38. }
  39. if err := c.Transaction.Commit(); err != nil && err != sql.ErrTxDone {
  40. panic(err)
  41. }
  42. c.Transaction = nil
  43. return nil
  44. }
  45. func (c *DatabaseController) Rollback() revel.Result {
  46. if c.Transaction == nil {
  47. return nil
  48. }
  49. if err := c.Transaction.Rollback(); err != nil && err != sql.ErrTxDone {
  50. panic(err)
  51. }
  52. c.Transaction = nil
  53. return nil
  54. }