memos/store/db.go

68 lines
1.2 KiB
Go
Raw Normal View History

2021-12-10 08:41:17 +03:00
package store
import (
"database/sql"
2021-12-12 07:14:40 +03:00
"io/ioutil"
2021-12-10 08:41:17 +03:00
"os"
2021-12-12 07:14:40 +03:00
"path/filepath"
2021-12-10 08:41:17 +03:00
_ "github.com/mattn/go-sqlite3"
)
/*
* Use a global variable to save the db connection: Quick and easy to setup.
* Reference: https://techinscribed.com/different-approaches-to-pass-database-connection-into-controllers-in-golang/
*/
var DB *sql.DB
func InitDBConn() {
2021-12-12 07:52:58 +03:00
// mounting point in docker is "/usr/local/memos/data"
dbFilePath := "./data/memos.db"
2021-12-10 08:41:17 +03:00
if _, err := os.Stat(dbFilePath); err != nil {
dbFilePath = "./resources/memos.db"
println("use the default database")
} else {
println("use the custom database")
}
db, err := sql.Open("sqlite3", dbFilePath)
if err != nil {
2021-12-12 06:43:27 +03:00
panic("db connect failed")
2021-12-10 08:41:17 +03:00
} else {
DB = db
println("connect to sqlite succeed")
}
2021-12-12 07:14:40 +03:00
if dbFilePath == "./resources/memos.db" {
resetDataInDefaultDatabase()
}
2021-12-10 08:41:17 +03:00
}
func FormatDBError(err error) error {
if err == nil {
return nil
}
switch err.Error() {
default:
return err
}
}
func resetDataInDefaultDatabase() {
2021-12-12 07:14:40 +03:00
initialSQLFilePath := filepath.Join("resources", "initial_db.sql")
c, err := ioutil.ReadFile(initialSQLFilePath)
if err != nil {
// do nth
return
}
sql := string(c)
DB.Exec(sql)
println("Initial data succeed")
2021-12-10 08:41:17 +03:00
}