From 111ecbc248913f13b02e4cbeb26528a5c42046a9 Mon Sep 17 00:00:00 2001 From: claustra01 Date: Sun, 7 Apr 2024 12:13:00 +0900 Subject: [PATCH] update: create sql handler --- bot/db/connect.go | 24 ------------------------ bot/db/postgres.go | 22 ++++++++++++++++++++++ bot/db/sql.go | 20 ++++++++++++++++++++ bot/server.go | 2 +- 4 files changed, 43 insertions(+), 25 deletions(-) delete mode 100644 bot/db/connect.go create mode 100644 bot/db/postgres.go create mode 100644 bot/db/sql.go diff --git a/bot/db/connect.go b/bot/db/connect.go deleted file mode 100644 index 16cb70d..0000000 --- a/bot/db/connect.go +++ /dev/null @@ -1,24 +0,0 @@ -package db - -import ( - "database/sql" - "log" - "os" - - _ "github.com/lib/pq" -) - -var Psql *sql.DB - -func Connect() *sql.DB { - db, err := sql.Open("postgres", os.Getenv("DATABASE_URL")) - if err != nil { - panic(err) - } - log.Println("Connected to database!") - return db -} - -func Close(db *sql.DB) { - db.Close() -} diff --git a/bot/db/postgres.go b/bot/db/postgres.go new file mode 100644 index 0000000..246e18a --- /dev/null +++ b/bot/db/postgres.go @@ -0,0 +1,22 @@ +package db + +import ( + "database/sql" + "log" + "os" + + _ "github.com/lib/pq" +) + +func (db SqlHandler) Connect() { + conn, err := sql.Open("postgres", os.Getenv("POSTGRES_DATABASE_URL")) + if err != nil { + panic(err) + } + log.Println("Connected to database!") + db.Conn = conn +} + +func (db SqlHandler) Close() { + db.Conn.Close() +} diff --git a/bot/db/sql.go b/bot/db/sql.go new file mode 100644 index 0000000..da34038 --- /dev/null +++ b/bot/db/sql.go @@ -0,0 +1,20 @@ +package db + +import "database/sql" + +var DB SqlHandler + +type SqlHandlerInterface interface { + Connect() + Close() + Query(string) +} + +type SqlHandler struct { + SqlHandlerInterface + Conn *sql.DB +} + +func (db SqlHandler) Query(query string) { + db.Conn.Query(query) +} diff --git a/bot/server.go b/bot/server.go index e271a6e..367846e 100644 --- a/bot/server.go +++ b/bot/server.go @@ -21,7 +21,7 @@ func main() { } // Connect to database - db.Psql = db.Connect() + db.DB.Connect() // Get channel secret and channel token from environment variables channelSecret := os.Getenv("LINE_CHANNEL_SECRET")