db.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // Create the tables (if needed)
  17. db.Create()
  18. }
  19. func (db *DBData) Close() {
  20. db.DB.Close()
  21. }
  22. func (db *DBData) Create() {
  23. _, err := db.DB.Exec(
  24. "CREATE TABLE IF NOT EXISTS settings(username TEXT, setting TEXT, value TEXT, PRIMARY KEY(username, setting));")
  25. if err != nil {
  26. log.Panicln(err)
  27. }
  28. _, err = db.DB.Exec(
  29. "CREATE TABLE IF NOT EXISTS scores ( \"username\" TEXT, \"when\" INTEGER, \"date\" INTEGER, \"hand\" INTEGER, \"won\" INTEGER, \"score\" INTEGER, PRIMARY KEY(\"username\", \"date\", \"hand\"));")
  30. if err != nil {
  31. log.Panicln(err)
  32. }
  33. _, err = db.DB.Exec(
  34. "CREATE TABLE IF NOT EXISTS \"monthly\" ( \"month\" INTEGER, \"username\" TEXT, \"days\" INTEGER, \"hands_won\" INTEGER, \"score\" INTEGER, PRIMARY KEY(\"month\",\"username\") );")
  35. if err != nil {
  36. log.Panicln(err)
  37. }
  38. }
  39. func (db *DBData) GetSetting(setting string, ifMissing string) string {
  40. row := db.DB.QueryRow("SELECT value FROM settings WHERE username=? AND setting=?;", db.User, setting)
  41. var value string
  42. // log.Printf("row: %#v\n", row)
  43. err := row.Scan(&value)
  44. if err != nil {
  45. return ifMissing
  46. }
  47. return value
  48. }
  49. func (db *DBData) SetSetting(setting string, value string) {
  50. _, err := db.DB.Exec("REPLACE INTO settings(username, setting, value) VALUES(?,?,?);", db.User, setting, value)
  51. if err != nil {
  52. log.Panicln("Query SetSetting", err)
  53. }
  54. // log.Printf("SetSetting %s %s = %s\n", db.User, setting, value)
  55. }