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:
@@ -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")
|
||||
|
||||
36
src/models/database/database_migrations.go
Normal file
36
src/models/database/database_migrations.go
Normal 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
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user