From a60c28ce112a00df1a8c15c92706797094468321 Mon Sep 17 00:00:00 2001 From: Sayan Biswas Date: Fri, 8 Oct 2021 21:40:45 +0530 Subject: [PATCH] Database: Init Signed-off-by: Sayan Biswas --- .gitignore | 3 ++- database/chats.go | 33 +++++++++++++++++++++++++++++++++ database/client.go | 29 +++++++++++++++++++++++++++++ main.go | 4 +++- 4 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 database/chats.go create mode 100644 database/client.go diff --git a/.gitignore b/.gitignore index e78acc7..69d2607 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -spb.conf \ No newline at end of file +spb.conf +*.db \ No newline at end of file diff --git a/database/chats.go b/database/chats.go new file mode 100644 index 0000000..577c4ba --- /dev/null +++ b/database/chats.go @@ -0,0 +1,33 @@ +package database + +import "errors" + +type Chat struct { + ChatID int64 `gorm:"primaryKey" gorm:"column:chat_id"` + AutoBan bool `gorm:"column:auto_ban"` + SpamDetect bool `gorm:"column:spam_detect"` + SpamAction string `gorm:"column:spam_action"` +} + +func (c *Chat) DoesAutoBan() bool { + return c.AutoBan +} + +func InsertChat(ChatID int64, AutoBan bool, SpamDetect bool, SpamAction string) { + tx := SESSION.Begin() + chat := &Chat{ChatID: ChatID, AutoBan: AutoBan, SpamDetect: SpamDetect, SpamAction: SpamAction} + tx.Save(chat) + tx.Commit() +} + +func GetChat(ChatID int64) (*Chat, error) { + if SESSION == nil { + return nil, errors.New("cannot access to SESSION " + + "of db, because it's nil") + } + + p := Chat{} + SESSION.Where("chat_id = ?", ChatID).Take(&p) + return &p, nil + +} diff --git a/database/client.go b/database/client.go new file mode 100644 index 0000000..8eb1388 --- /dev/null +++ b/database/client.go @@ -0,0 +1,29 @@ +package database + +import ( + "fmt" + "gitlab.com/Dank-del/SpamProtection-Mirror-Bot/core" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +var SESSION *gorm.DB + +func StartDatabase(name string) { + db, err := gorm.Open(sqlite.Open(fmt.Sprintf("%s.db", name)), &gorm.Config{}) + if err != nil { + core.SUGARED.Error("failed to connect database") + } + + SESSION = db + core.SUGARED.Info("Database connected") + + // Create tables if they don't exist + err = SESSION.AutoMigrate(&Chat{}) + if err != nil { + core.SUGARED.Error(err) + } + + core.SUGARED.Info("Auto-migrated database schema") + +} diff --git a/main.go b/main.go index 708eb55..074617b 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "gitlab.com/Dank-del/SpamProtection-Mirror-Bot/database" "gitlab.com/Dank-del/SpamProtection-Mirror-Bot/handlers" "go.uber.org/zap" "log" @@ -26,9 +27,10 @@ func main() { core.SUGARED = loggerMgr.Sugar() b, up, err := core.BotInit(e) if err != nil { - return + log.Fatal(err) } handlers.LoadHandlers(up.Dispatcher) + database.StartDatabase(e.DatabaseName) logger.Info(b.FirstName, " has started, ID: ", b.Id) up.Idle() }