2022-08-29 20:58:19 +00:00
|
|
|
package sqldb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2022-09-19 12:46:16 +00:00
|
|
|
"fmt"
|
2022-09-20 10:21:01 +00:00
|
|
|
"officeHours/config"
|
2022-08-29 20:58:19 +00:00
|
|
|
|
2022-09-12 17:42:45 +00:00
|
|
|
_ "github.com/go-sql-driver/mysql"
|
2022-08-29 20:58:19 +00:00
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
)
|
|
|
|
|
2022-09-21 20:24:08 +00:00
|
|
|
func Connect(config config.Config) (*sql.DB, error) {
|
2022-09-19 12:46:16 +00:00
|
|
|
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:
|
2022-09-21 20:24:08 +00:00
|
|
|
return nil, fmt.Errorf("Type of database not recognised: %s", config.SQL.Type)
|
2022-09-19 12:46:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-21 20:24:08 +00:00
|
|
|
func connectSQLite(file string) (*sql.DB, error) {
|
2022-09-12 17:42:45 +00:00
|
|
|
db, err := sql.Open("sqlite3", file)
|
2022-08-29 20:58:19 +00:00
|
|
|
if err != nil {
|
2022-09-21 20:24:08 +00:00
|
|
|
return db, fmt.Errorf("Error opening SQLite database: %w", err)
|
2022-08-29 20:58:19 +00:00
|
|
|
}
|
2022-09-21 20:24:08 +00:00
|
|
|
return db, nil
|
2022-08-29 20:58:19 +00:00
|
|
|
}
|
2022-09-12 17:42:45 +00:00
|
|
|
|
2022-09-21 20:24:08 +00:00
|
|
|
func connectMysql(user string, password string, address string, port int, database string) (*sql.DB, error) {
|
2022-09-19 12:46:16 +00:00
|
|
|
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, address, port, database))
|
2022-09-12 17:42:45 +00:00
|
|
|
if err != nil {
|
2022-09-21 20:24:08 +00:00
|
|
|
return db, fmt.Errorf("Error connecting to Mysql database: %w", err)
|
2022-09-12 17:42:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err = db.Ping()
|
|
|
|
// handle error
|
|
|
|
if err != nil {
|
2022-09-21 20:24:08 +00:00
|
|
|
return db, fmt.Errorf("Error pinging Mysql database: %w", err)
|
2022-09-12 17:42:45 +00:00
|
|
|
}
|
2022-09-21 20:24:08 +00:00
|
|
|
return db, nil
|
2022-09-12 17:42:45 +00:00
|
|
|
}
|