Skip to content

Commit

Permalink
Save database connection to sqlite
Browse files Browse the repository at this point in the history
  • Loading branch information
lewissteele committed Oct 5, 2024
1 parent dee8f37 commit 7321b69
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cmd
import (
"errors"

"github.com/gookit/goutil/dump"
db "github.com/lewissteele/dbat/internal"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -40,7 +40,9 @@ func run(cmd *cobra.Command, args []string) {
results = append(results, result)
}

dump.P(results)
host, username, password := results[0], results[1], results[2]

db.SaveConnection(host, username, password)
}

func isNotBlank(val string) error {
Expand Down
38 changes: 38 additions & 0 deletions internal/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package db

import (
"os"
"path/filepath"

"github.com/lewissteele/dbat/internal/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

var localDB *gorm.DB

func SaveConnection(host string, username string, password string) {
localDB.Create(&model.Database{Host: "localhost", Username: "root", Password: ""})
}

func init() {
configHome := os.Getenv("XDG_CONFIG_HOME")

if len(configHome) == 0 {
configHome = filepath.Join(os.Getenv("HOME"), ".config")
}

path := filepath.Join(configHome, "dbat/dbat.db")
conn, err := gorm.Open(sqlite.Open(path), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})

if err != nil {
panic("could not connect to sqlite db")
}

conn.AutoMigrate(&model.Database{})

localDB = conn
}
10 changes: 10 additions & 0 deletions internal/model/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package model

import "gorm.io/gorm"

type Database struct {
gorm.Model
Host string
Username string
Password string
}

0 comments on commit 7321b69

Please sign in to comment.