groupme/database/database.go

113 lines
2.4 KiB
Go
Raw Normal View History

// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package database
import (
2019-03-06 09:59:52 +00:00
_ "github.com/lib/pq"
2019-03-06 21:57:38 +00:00
_ "github.com/mattn/go-sqlite3"
2019-01-11 19:17:31 +00:00
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix-whatsapp/database/upgrades"
2021-02-13 05:53:35 +00:00
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Database struct {
2021-02-13 05:53:35 +00:00
*gorm.DB
log log.Logger
dialect string
User *UserQuery
Portal *PortalQuery
Puppet *PuppetQuery
Message *MessageQuery
}
func New(dbType string, uri string, baseLog log.Logger) (*Database, error) {
2021-02-13 05:53:35 +00:00
var conn gorm.Dialector
2019-07-17 21:06:50 +00:00
if dbType == "sqlite3" {
2021-02-13 05:53:35 +00:00
//_, _ = conn.Exec("PRAGMA foreign_keys = ON")
conn = sqlite.Open(uri)
} else {
conn = postgres.Open(uri)
}
print("no")
gdb, err := gorm.Open(conn, &gorm.Config{
// Logger: baseLog,
})
if err != nil {
panic("failed to connect database")
2019-07-17 21:06:50 +00:00
}
db := &Database{
2021-02-13 05:53:35 +00:00
DB: gdb,
log: baseLog.Sub("Database"),
dialect: dbType,
}
db.User = &UserQuery{
db: db,
2018-08-16 16:20:07 +00:00
log: db.log.Sub("User"),
}
db.Portal = &PortalQuery{
db: db,
2018-08-16 16:20:07 +00:00
log: db.log.Sub("Portal"),
}
db.Puppet = &PuppetQuery{
db: db,
2018-08-16 16:20:07 +00:00
log: db.log.Sub("Puppet"),
}
db.Message = &MessageQuery{
db: db,
log: db.log.Sub("Message"),
}
return db, nil
}
func (db *Database) Init() error {
2021-02-13 05:53:35 +00:00
err := db.AutoMigrate(&Portal{})
if err != nil {
return err
}
err = db.AutoMigrate(&Puppet{})
if err != nil {
return err
}
err = db.AutoMigrate(&Message{})
if err != nil {
return err
}
err = db.AutoMigrate(&mxRegistered{})
if err != nil {
return err
}
err = db.AutoMigrate(&mxUserProfile{})
if err != nil {
return err
}
return upgrades.Run(db.log.Sub("Upgrade"), db.dialect, db.DB)
2018-08-16 16:20:07 +00:00
}
type Scannable interface {
Scan(...interface{}) error
}