database.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. if dbType == "sqlite3" {
  38. _, _ = conn.Exec("PRAGMA foreign_keys = ON")
  39. }
  40. db := &Database{
  41. DB: conn,
  42. log: log.Sub("Database"),
  43. }
  44. db.User = &UserQuery{
  45. db: db,
  46. log: db.log.Sub("User"),
  47. }
  48. db.Portal = &PortalQuery{
  49. db: db,
  50. log: db.log.Sub("Portal"),
  51. }
  52. db.Puppet = &PuppetQuery{
  53. db: db,
  54. log: db.log.Sub("Puppet"),
  55. }
  56. db.Message = &MessageQuery{
  57. db: db,
  58. log: db.log.Sub("Message"),
  59. }
  60. return db, nil
  61. }
  62. func (db *Database) Init(dialectName string) error {
  63. return upgrades.Run(db.log.Sub("Upgrade"), dialectName, db.DB)
  64. }
  65. type Scannable interface {
  66. Scan(...interface{}) error
  67. }