database.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2018 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package database
  17. import (
  18. "database/sql"
  19. _ "github.com/mattn/go-sqlite3"
  20. log "maunium.net/go/maulogger/v2"
  21. )
  22. type Database struct {
  23. *sql.DB
  24. log log.Logger
  25. User *UserQuery
  26. Portal *PortalQuery
  27. Puppet *PuppetQuery
  28. Message *MessageQuery
  29. }
  30. func New(file string) (*Database, error) {
  31. conn, err := sql.Open("sqlite3", file)
  32. if err != nil {
  33. return nil, err
  34. }
  35. db := &Database{
  36. DB: conn,
  37. log: log.Sub("Database"),
  38. }
  39. db.User = &UserQuery{
  40. db: db,
  41. log: db.log.Sub("User"),
  42. }
  43. db.Portal = &PortalQuery{
  44. db: db,
  45. log: db.log.Sub("Portal"),
  46. }
  47. db.Puppet = &PuppetQuery{
  48. db: db,
  49. log: db.log.Sub("Puppet"),
  50. }
  51. db.Message = &MessageQuery{
  52. db: db,
  53. log: db.log.Sub("Message"),
  54. }
  55. return db, nil
  56. }
  57. func (db *Database) CreateTables() error {
  58. err := db.User.CreateTable()
  59. if err != nil {
  60. return err
  61. }
  62. err = db.Portal.CreateTable()
  63. if err != nil {
  64. return err
  65. }
  66. err = db.Puppet.CreateTable()
  67. if err != nil {
  68. return err
  69. }
  70. err = db.Message.CreateTable()
  71. if err != nil {
  72. return err
  73. }
  74. return nil
  75. }
  76. type Scannable interface {
  77. Scan(...interface{}) error
  78. }