You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.3 KiB

package sqldb
import (
"database/sql"
"fmt"
"officeHours/config"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
)
// Connect to a database using or throw an error
func Connect(config config.Config) (*sql.DB, error) {
switch config.SQL.Type {
case "SQLite":
return connectSQLite(config.SQL.SQLiteFile)
case "Mysql":
return connectMysql(config.SQL.MysqlUser,
config.SQL.MysqlPassword,
config.SQL.MysqlHost,
config.SQL.MysqlPort,
config.SQL.MysqlDatabase)
default:
return nil, fmt.Errorf("Type of database not recognised: %s", config.SQL.Type)
}
}
// Connect to a SQLite database and check the connection.
func connectSQLite(file string) (*sql.DB, error) {
db, err := sql.Open("sqlite3", file)
if err != nil {
return db, fmt.Errorf("Error opening SQLite database: %w", err)
}
return db, nil
}
// Connect to a Mysql database and check the connection.
func connectMysql(user string, password string, address string, port int, database string) (*sql.DB, error) {
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, address, port, database))
if err != nil {
return db, fmt.Errorf("Error connecting to Mysql database: %w", err)
}
err = db.Ping()
if err != nil {
return db, fmt.Errorf("Error pinging Mysql database: %w", err)
}
return db, nil
}