1
0
mirror of https://github.com/JustKato/FreePad.git synced 2026-02-24 00:00:46 +02:00

+ Started work on Sqlite

+ Started work on moving migrations into code instead of Dockerfile
This commit is contained in:
2022-05-17 03:20:31 +03:00
parent af6a4676e3
commit c8dde83c05
10 changed files with 1815 additions and 4 deletions

View File

@@ -9,7 +9,63 @@ import (
_ "github.com/go-sql-driver/mysql"
)
// Declare the default database driver
const defaultDatabaseDriver string = "sqlite"
// Declare the valid database drivers
var validDatabaseDrivers []string = []string{"sqlite", "mysql"}
// Get the database type to use
func getDbType() string {
// Grab the environment variable
db, test := os.LookupEnv(`DATABASE_DRIVER`)
// Check if the test has failed
if !test {
return defaultDatabaseDriver
}
for _, v := range validDatabaseDrivers {
// Check if the provided database corresponds to this entry
if v == db {
// This is a valid database type
return db
}
}
// No matches
return defaultDatabaseDriver
}
func GetConn() (*sql.DB, error) {
// Check what kind of database we are looking for
dbConnType := getDbType()
if dbConnType == `mysql` {
return GetMysqlConn()
} else {
return GetLiteConn()
}
}
func GetSqliteDatabasePath() string {
return "main.db"
}
func GetLiteConn() (*sql.DB, error) {
// Declare the database file name
dbFile := GetSqliteDatabasePath()
db, err := sql.Open("sqlite3", dbFile)
if err != nil {
return nil, err
}
return db, nil
}
func GetMysqlConn() (*sql.DB, error) {
user := os.Getenv("MYSQL_USER")
password := os.Getenv("MYSQL_PASSWORD")

View File

@@ -0,0 +1,36 @@
package database
import (
"fmt"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/sqlite"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
// Run migrations to ensure tables exist
func MigrationUpdate() *migrate.Logger {
// Get the path to the sqlite database
databasePath := fmt.Sprintf("sqlite://%s", GetSqliteDatabasePath())
// Try and create a new migration
m, err := migrate.New(
"file://../db/migrations_sqlite",
databasePath,
)
if err != nil {
// End the whole thing if migrations fail
panic(err)
}
// Run the update
err = m.Up()
m.Run()
m.Force(1)
return &m.Log
}