storage.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. The "storage" package in Kurz provides the data model.
  3. In its current implementation:
  4. - it is specific to MySQL/MariaDB and compatibles SQL engines.
  5. - data model and data access are not isolated
  6. - it assumes the DB has been initialized by importing the data/db-schema.sql file
  7. - it initializes the connection info based on the "dsn" CLI flag
  8. */
  9. package storage
  10. /**
  11. TODO use a CLI flag to clear the database on init
  12. TODO use a CLI flag to install the database schema
  13. */
  14. import (
  15. "database/sql"
  16. "flag"
  17. _ "github.com/go-sql-driver/mysql"
  18. )
  19. type Storage struct {
  20. DB *sql.DB
  21. DSN string
  22. }
  23. var Service Storage = Storage{}
  24. /*
  25. Open() established the database connection, making sure it is actually available instead of just preparing the connection info.
  26. */
  27. func (s *Storage) Open() error {
  28. var err error
  29. s.DB, err = sql.Open("mysql", s.DSN)
  30. if err == nil {
  31. err = s.DB.Ping()
  32. }
  33. return err
  34. }
  35. /*
  36. Close() closes the database connection and releases its information.
  37. */
  38. func (s *Storage) Close() {
  39. if s.DB != nil {
  40. s.DB.Close()
  41. }
  42. s.DB = nil
  43. }
  44. /*
  45. SetDSN() sets the DSN information for the storage.
  46. */
  47. func (s *Storage) SetDSN(dsn string) {
  48. s.DSN = dsn
  49. }
  50. /*
  51. init() initializes the storage information from the command-line flag "dsn".
  52. */
  53. func init() {
  54. var dsn = flag.String("dsn", "root:@tcp(localhost:3306)/go_kurz", "some_user:some_pass@tcp(some_host:some_port)/some_db")
  55. flag.Parse()
  56. Service.SetDSN(*dsn)
  57. }