database.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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"
  21. )
  22. type Database struct {
  23. *sql.DB
  24. log log.Logger
  25. User *UserQuery
  26. Portal *PortalQuery
  27. Puppet *PuppetQuery
  28. }
  29. func New(file string) (*Database, error) {
  30. conn, err := sql.Open("sqlite3", file)
  31. if err != nil {
  32. return nil, err
  33. }
  34. db := &Database{
  35. DB: conn,
  36. log: log.Sub("Database"),
  37. }
  38. db.User = &UserQuery{
  39. db: db,
  40. log: db.log.Sub("User"),
  41. }
  42. db.Portal = &PortalQuery{
  43. db: db,
  44. log: db.log.Sub("Portal"),
  45. }
  46. db.Puppet = &PuppetQuery{
  47. db: db,
  48. log: db.log.Sub("Puppet"),
  49. }
  50. return db, nil
  51. }
  52. func (db *Database) CreateTables() error {
  53. err := db.User.CreateTable()
  54. if err != nil {
  55. return err
  56. }
  57. err = db.Portal.CreateTable()
  58. if err != nil {
  59. return err
  60. }
  61. err = db.Puppet.CreateTable()
  62. if err != nil {
  63. return err
  64. }
  65. return nil
  66. }
  67. type Scannable interface {
  68. Scan(...interface{}) error
  69. }