db.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "database/sql"
  4. "log"
  5. )
  6. type DBData struct {
  7. DB *sql.DB
  8. User string
  9. }
  10. func (db *DBData) Open(filename string) {
  11. var err error
  12. db.DB, err = sql.Open("sqlite3", filename)
  13. if err != nil {
  14. log.Panicln("Error Opening Sqlite3:", err)
  15. }
  16. }
  17. func (db *DBData) Close() {
  18. db.DB.Close()
  19. }
  20. func (db *DBData) Create() {
  21. _, err := db.DB.Exec(
  22. "CREATE TABLE IF NOT EXISTS settings(username TEXT, setting TEXT, value TEXT, PRIMARY KEY(username, setting));")
  23. if err != nil {
  24. log.Panicln(err)
  25. }
  26. _, err = db.DB.Exec(
  27. "CREATE TABLE IF NOT EXISTS scores ( \"username\" TEXT, \"when\" INTEGER, \"date\" INTEGER, \"hand\" INTEGER, \"won\" INTEGER, \"score\" INTEGER, PRIMARY KEY(\"username\", \"date\", \"hand\"));")
  28. if err != nil {
  29. log.Panicln(err)
  30. }
  31. _, err = db.DB.Exec(
  32. "CREATE TABLE IF NOT EXISTS \"monthly\" ( \"month\" INTEGER, \"username\" TEXT, \"days\" INTEGER, \"hands_won\" INTEGER, \"score\" INTEGER, PRIMARY KEY(\"month\",\"username\") );")
  33. if err != nil {
  34. log.Panicln(err)
  35. }
  36. }
  37. func (db *DBData) GetSetting(setting string, ifMissing string) string {
  38. rows, err := db.DB.Query("SELECT value FROM settings WHERE username=? AND setting=?", db.User, setting)
  39. if err != nil {
  40. log.Panicln("Query GetSetting", err)
  41. }
  42. defer rows.Close()
  43. for rows.Next() {
  44. var value string
  45. err = rows.Scan(&value)
  46. if err != nil {
  47. log.Panicln("Scan GetSetting", err)
  48. }
  49. return value
  50. }
  51. return ifMissing
  52. }
  53. func (db *DBData) SetSetting(setting string, value string) {
  54. _, err := db.DB.Query("REPLACE INTO settings(username, setting, value) VALUES(?,?,?)", db.User, setting, value)
  55. if err != nil {
  56. log.Panicln("Query SetSetting", err)
  57. }
  58. }