database.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. "go.mau.fi/whatsmeow/store/sqlstore"
  23. "maunium.net/go/mautrix-whatsapp/database/upgrades"
  24. )
  25. func init() {
  26. sqlstore.PostgresArrayWrapper = pq.Array
  27. }
  28. type Database struct {
  29. *sql.DB
  30. log log.Logger
  31. dialect string
  32. User *UserQuery
  33. Portal *PortalQuery
  34. Puppet *PuppetQuery
  35. Message *MessageQuery
  36. }
  37. func New(dbType string, uri string, baseLog log.Logger) (*Database, error) {
  38. conn, err := sql.Open(dbType, uri)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if dbType == "sqlite3" {
  43. _, _ = conn.Exec("PRAGMA foreign_keys = ON")
  44. }
  45. db := &Database{
  46. DB: conn,
  47. log: baseLog.Sub("Database"),
  48. dialect: dbType,
  49. }
  50. db.User = &UserQuery{
  51. db: db,
  52. log: db.log.Sub("User"),
  53. }
  54. db.Portal = &PortalQuery{
  55. db: db,
  56. log: db.log.Sub("Portal"),
  57. }
  58. db.Puppet = &PuppetQuery{
  59. db: db,
  60. log: db.log.Sub("Puppet"),
  61. }
  62. db.Message = &MessageQuery{
  63. db: db,
  64. log: db.log.Sub("Message"),
  65. }
  66. return db, nil
  67. }
  68. func (db *Database) Init() error {
  69. return upgrades.Run(db.log.Sub("Upgrade"), db.dialect, db.DB)
  70. }
  71. type Scannable interface {
  72. Scan(...interface{}) error
  73. }