database.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2019 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/lib/pq"
  20. _ "github.com/mattn/go-sqlite3"
  21. log "maunium.net/go/maulogger/v2"
  22. "maunium.net/go/mautrix-whatsapp/database/upgrades"
  23. )
  24. type Database struct {
  25. *sql.DB
  26. log log.Logger
  27. dialect string
  28. User *UserQuery
  29. Portal *PortalQuery
  30. Puppet *PuppetQuery
  31. Message *MessageQuery
  32. }
  33. func New(dbType string, uri string) (*Database, error) {
  34. conn, err := sql.Open(dbType, uri)
  35. if err != nil {
  36. return nil, err
  37. }
  38. if dbType == "sqlite3" {
  39. _, _ = conn.Exec("PRAGMA foreign_keys = ON")
  40. }
  41. db := &Database{
  42. DB: conn,
  43. log: log.Sub("Database"),
  44. dialect: dbType,
  45. }
  46. db.User = &UserQuery{
  47. db: db,
  48. log: db.log.Sub("User"),
  49. }
  50. db.Portal = &PortalQuery{
  51. db: db,
  52. log: db.log.Sub("Portal"),
  53. }
  54. db.Puppet = &PuppetQuery{
  55. db: db,
  56. log: db.log.Sub("Puppet"),
  57. }
  58. db.Message = &MessageQuery{
  59. db: db,
  60. log: db.log.Sub("Message"),
  61. }
  62. return db, nil
  63. }
  64. func (db *Database) Init() error {
  65. return upgrades.Run(db.log.Sub("Upgrade"), db.dialect, db.DB)
  66. }
  67. type Scannable interface {
  68. Scan(...interface{}) error
  69. }