Calorie counting web application written in the Go language

database.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.TraceOn("[db]", revel.INFO)
  19. DbMap.CreateTables()
  20. }
  21. type DatabaseController struct {
  22. *revel.Controller
  23. Transaction *gorp.Transaction
  24. }
  25. func (c *DatabaseController) Begin() revel.Result {
  26. transaction, err := DbMap.Begin()
  27. if err != nil {
  28. panic(err)
  29. }
  30. c.Transaction = transaction
  31. return nil
  32. }
  33. func (c *DatabaseController) Commit() revel.Result {
  34. if c.Transaction == nil {
  35. return nil
  36. }
  37. if err := c.Transaction.Commit(); err != nil && err != sql.ErrTxDone {
  38. panic(err)
  39. }
  40. c.Transaction = nil
  41. return nil
  42. }
  43. func (c *DatabaseController) Rollback() revel.Result {
  44. if c.Transaction == nil {
  45. return nil
  46. }
  47. if err := c.Transaction.Rollback(); err != nil && err != sql.ErrTxDone {
  48. panic(err)
  49. }
  50. c.Transaction = nil
  51. return nil
  52. }