database.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. )
  23. type Database struct {
  24. *sql.DB
  25. log log.Logger
  26. User *UserQuery
  27. Portal *PortalQuery
  28. Puppet *PuppetQuery
  29. Message *MessageQuery
  30. }
  31. func New(dbType string, uri string) (*Database, error) {
  32. conn, err := sql.Open(dbType, uri)
  33. if err != nil {
  34. return nil, err
  35. }
  36. db := &Database{
  37. DB: conn,
  38. log: log.Sub("Database"),
  39. }
  40. db.User = &UserQuery{
  41. db: db,
  42. log: db.log.Sub("User"),
  43. }
  44. db.Portal = &PortalQuery{
  45. db: db,
  46. log: db.log.Sub("Portal"),
  47. }
  48. db.Puppet = &PuppetQuery{
  49. db: db,
  50. log: db.log.Sub("Puppet"),
  51. }
  52. db.Message = &MessageQuery{
  53. db: db,
  54. log: db.log.Sub("Message"),
  55. }
  56. return db, nil
  57. }
  58. func (db *Database) CreateTables(dbType string) error {
  59. err := db.User.CreateTable(dbType)
  60. if err != nil {
  61. return err
  62. }
  63. err = db.Portal.CreateTable(dbType)
  64. if err != nil {
  65. return err
  66. }
  67. err = db.Puppet.CreateTable(dbType)
  68. if err != nil {
  69. return err
  70. }
  71. err = db.Message.CreateTable(dbType)
  72. if err != nil {
  73. return err
  74. }
  75. return nil
  76. }
  77. type Scannable interface {
  78. Scan(...interface{}) error
  79. }