* For the Direct Message History database, use gorm.io as ORM so that Postgres can be used instead of SQLite for bigger chat room instances. * In settings.toml: the new DatabaseType field defaults to 'sqlite3' but can be set to 'postgres' and use the credentials in the new PostgresDatabase field. * The DirectMessage table schema is also updated to deprecate the Timestamp int field in favor of a proper CreatedAt datetime field. Existing SQLite instances will upgrade their table in the background, converting Timestamp to CreatedAt and blanking out the legacy Timestamp column. * Fix some DB queries so when paginating your DMs history username list, sorting it by timestamp now works reliably. * For existing SQLite instances that want to switch to Postgres, use the scripts/sqlite2psql.py script to transfer your database over.
59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
package models
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"git.kirsle.net/apps/barertc/pkg/log"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var (
|
|
DB *gorm.DB
|
|
ErrNotInitialized = errors.New("database is not initialized")
|
|
)
|
|
|
|
func AutoMigrate() {
|
|
DB.AutoMigrate(
|
|
&DirectMessage{},
|
|
)
|
|
}
|
|
|
|
func Initialize(dbtype, connString string) error {
|
|
|
|
var gormcfg = &gorm.Config{
|
|
// Logger: logger.Default.LogMode(logger.Info),
|
|
}
|
|
|
|
switch dbtype {
|
|
case "sqlite3":
|
|
db, err := gorm.Open(sqlite.Open(connString), gormcfg)
|
|
if err != nil {
|
|
return fmt.Errorf("error opening SQLite DB: %w", err)
|
|
}
|
|
DB = db
|
|
case "postgres":
|
|
db, err := gorm.Open(postgres.Open(connString), gormcfg)
|
|
if err != nil {
|
|
return fmt.Errorf("error opening postgres DB: %w", err)
|
|
}
|
|
DB = db
|
|
default:
|
|
return errors.New("dbtype not supported: must be sqlite3 or postgres")
|
|
}
|
|
|
|
AutoMigrate()
|
|
|
|
// Run initializers.
|
|
go func() {
|
|
if err := (&DirectMessage{}).Init(); err != nil {
|
|
log.Error("DirectMessage.Init: %s", err)
|
|
}
|
|
}()
|
|
|
|
return nil
|
|
}
|