Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add log system 🚀 #55

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions cmd/bro-backend/commands/spin.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package commands

import (
"io"
"log"
"os"

"github.com/spf13/cobra"
backendUtils "github.com/threeal/bro/cmd/bro-backend/utils"
"github.com/threeal/bro/pkg/db/sqlite/log_system"
"github.com/threeal/bro/pkg/schema"
"github.com/threeal/bro/pkg/service"
)
Expand All @@ -15,6 +18,19 @@ func getSpinCommand() *cobra.Command {
Short: "Spin command",
Long: `A command to run Bro backend process..`,
Args: cobra.NoArgs,
PreRun: func(cmd *cobra.Command, args []string) {
db := log_system.InitDB()
log_system.QueryDB(db, log_system.InsertToSessionsTableSQL)
sessionID, err := log_system.QueryLastID(db)
if err != nil {
log.Fatalf("cannot get session id, %v", err)
}
dbWriter := &log_system.DBWriter{}
dbWriter.SetDB(db)
dbWriter.SetSessionID(sessionID)
mw := io.MultiWriter(dbWriter, os.Stdout)
log.SetOutput(mw)
},
Run: func(cmd *cobra.Command, args []string) {
server, err := backendUtils.CreateServer()
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.19

require (
github.com/fatih/color v1.14.1
github.com/mattn/go-sqlite3 v1.14.16
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5
github.com/spf13/cobra v1.6.1
github.com/stretchr/testify v1.8.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5 h1:Ii+DKncOVM8Cu1Hc+ETb5K+23HdAMvESYE3ZJ5b5cMI=
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
14 changes: 14 additions & 0 deletions pkg/db/sqlite/log_system/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package log_system

import (
"database/sql"
"time"
)

type Log struct {
LogID int `db:"log_id" json:"log_id"`
Time time.Time `db:"time" json:"time"`
SessionID int `db:"session_id" json:"session_id"`
Topic sql.NullString `db:"topic" json:"topic"`
Content string `db:"content" json:"content"`
}
82 changes: 82 additions & 0 deletions pkg/db/sqlite/log_system/repo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package log_system

import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"path/filepath"

"github.com/threeal/bro/pkg/utils"
)

func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}

func GetLogPath() (string, error) {
configDir, err := utils.GetConfigDir()
if err != nil {
return "", err
}
configPath := filepath.Join(configDir, "log.db")
return configPath, nil
}

func CreateDatabaseFile() string {
logPath, err := GetLogPath()
if err != nil {
log.Fatal(err)
}
if fileExists(logPath) {
return logPath
}
file, err := os.Create(logPath)
defer file.Close()
if err != nil {
log.Fatal(err)
}
return logPath
}

func InitDB() *sql.DB {
logPath := CreateDatabaseFile()
db, err := sql.Open("sqlite3", logPath)
if err != nil {
fmt.Println(err)
}
QueryDB(db, EnableForeignKey)
QueryDB(db, CreateSessionsTableSQL)
QueryDB(db, CreateLogsTableSQL)
return db
}

func QueryDB(db *sql.DB, sqlString string, sqlQuery ...interface{}) {
log_table := sqlString
query, err := db.Prepare(log_table)
if err != nil {
log.Fatal(err)
}
_, err = query.Exec(sqlQuery...)
if err != nil {
fmt.Println(err)
}
fmt.Println("Query ran successfully!")
}

func QueryLastID(db *sql.DB) (int, error) {
var lastID int
// Query for a value based on a single row.
if err := db.QueryRow("SELECT last_insert_rowid()").Scan(&lastID); err != nil {
if err == sql.ErrNoRows {
return 0, fmt.Errorf("unknown row")
}
return 0, fmt.Errorf("Error: %v", err)
}
return lastID, nil
}
10 changes: 10 additions & 0 deletions pkg/db/sqlite/log_system/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package log_system

import (
"time"
)

type Session struct {
SessionID int `db:"session_id" json:"session_id"`
StartTime time.Time `db:"start_time" json:"start_time"`
}
44 changes: 44 additions & 0 deletions pkg/db/sqlite/log_system/sql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package log_system

const (
CreateLogsTableSQL = `
CREATE TABLE IF NOT EXISTS logs (
log_id INTEGER PRIMARY KEY,
topic VARCHAR(64),
content TEXT NOT NULL,
time DATETIME DEFAULT CURRENT_TIMESTAMP,
session_id INTEGER NOT NULL,
FOREIGN KEY (session_id)
REFERENCES sessions (session_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
`
)

const (
EnableForeignKey = `
PRAGMA foreign_keys = ON;
`
)

const (
CreateSessionsTableSQL = `
CREATE TABLE IF NOT EXISTS sessions (
session_id INTEGER PRIMARY KEY,
start_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
`
)

const (
InsertToLogsTableSQL = `
INSERT INTO logs(topic,content,session_id) VALUES(?,?,?);
`
)

const (
InsertToSessionsTableSQL = `
INSERT INTO sessions DEFAULT VALUES;
`
)
24 changes: 24 additions & 0 deletions pkg/db/sqlite/log_system/writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package log_system

import "database/sql"

type DBWriter struct {
db *sql.DB
sessionID int
}

func (w *DBWriter) Write(p []byte) (n int, err error) {
QueryDB(w.db, InsertToLogsTableSQL, nil, string(p), w.sessionID)
if err != nil {
return
}
return len(p), nil
}

func (w *DBWriter) SetDB(db *sql.DB) {
w.db = db
}

func (w *DBWriter) SetSessionID(sessionID int) {
w.sessionID = sessionID
}
8 changes: 4 additions & 4 deletions pkg/utils/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func Prompt(q string, def string, rd io.Reader) (string, error) {
return strings.TrimSpace(text), err
}

func getConfigDir() (string, error) {
func GetConfigDir() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
logError("failed to determine home directory", err)
Expand Down Expand Up @@ -66,7 +66,7 @@ func WriteConfigToFile(c Config, configName string) error {
if err != nil {
logError("failed to marshal json", err)
}
configDir, err := getConfigDir()
configDir, err := GetConfigDir()
if err != nil {
return err
}
Expand All @@ -78,7 +78,7 @@ func WriteConfigToFile(c Config, configName string) error {
}

func ReadConfigFromFile(c Config, configName string) error {
configDir, err := getConfigDir()
configDir, err := GetConfigDir()
if err != nil {
return err
}
Expand All @@ -91,7 +91,7 @@ func ReadConfigFromFile(c Config, configName string) error {
}

func DeleteConfig(configName string) error {
configDir, err := getConfigDir()
configDir, err := GetConfigDir()
if err != nil {
return err
}
Expand Down