database.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. db := &Database{
  43. DB: conn,
  44. log: baseLog.Sub("Database"),
  45. dialect: dbType,
  46. }
  47. db.User = &UserQuery{
  48. db: db,
  49. log: db.log.Sub("User"),
  50. }
  51. db.Portal = &PortalQuery{
  52. db: db,
  53. log: db.log.Sub("Portal"),
  54. }
  55. db.Puppet = &PuppetQuery{
  56. db: db,
  57. log: db.log.Sub("Puppet"),
  58. }
  59. db.Message = &MessageQuery{
  60. db: db,
  61. log: db.log.Sub("Message"),
  62. }
  63. return db, nil
  64. }
  65. func (db *Database) Init() error {
  66. return upgrades.Run(db.log.Sub("Upgrade"), db.dialect, db.DB)
  67. }
  68. type Scannable interface {
  69. Scan(...interface{}) error
  70. }