database.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. User *UserQuery
  28. Portal *PortalQuery
  29. Puppet *PuppetQuery
  30. Message *MessageQuery
  31. }
  32. func New(dbType string, uri string) (*Database, error) {
  33. conn, err := sql.Open(dbType, uri)
  34. if err != nil {
  35. return nil, err
  36. }
  37. db := &Database{
  38. DB: conn,
  39. log: log.Sub("Database"),
  40. }
  41. db.User = &UserQuery{
  42. db: db,
  43. log: db.log.Sub("User"),
  44. }
  45. db.Portal = &PortalQuery{
  46. db: db,
  47. log: db.log.Sub("Portal"),
  48. }
  49. db.Puppet = &PuppetQuery{
  50. db: db,
  51. log: db.log.Sub("Puppet"),
  52. }
  53. db.Message = &MessageQuery{
  54. db: db,
  55. log: db.log.Sub("Message"),
  56. }
  57. return db, nil
  58. }
  59. func (db *Database) Init(dialectName string) error {
  60. return upgrades.Run(db.log.Sub("Upgrade"), dialectName, db.DB)
  61. }
  62. type Scannable interface {
  63. Scan(...interface{}) error
  64. }