refactor(server/db): Move database connection logic to separate class
Implements a DbBuilder class to streamline the creation of database connections for both SQLite and MySQL storage types. Enhances error handling for database setup and ensures that necessary directories are created dynamically based on configuration settings. This refactor improves code maintainability and readability, consolidating connection logic into a dedicated builder class.
This commit is contained in:
parent
99e37ccba4
commit
0021f9884d
2 changed files with 92 additions and 31 deletions
|
|
@ -314,37 +314,9 @@ namespace TShockAPI
|
|||
// Further exceptions are written to TShock's log from now on.
|
||||
try
|
||||
{
|
||||
if (Config.Settings.StorageType.ToLower() == "sqlite")
|
||||
{
|
||||
string sql = Path.Combine(SavePath, Config.Settings.SqliteDBPath);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sql));
|
||||
DB = new Microsoft.Data.Sqlite.SqliteConnection(string.Format("Data Source={0}", sql));
|
||||
}
|
||||
else if (Config.Settings.StorageType.ToLower() == "mysql")
|
||||
{
|
||||
try
|
||||
{
|
||||
var hostport = Config.Settings.MySqlHost.Split(':');
|
||||
DB = new MySqlConnection();
|
||||
DB.ConnectionString =
|
||||
String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
|
||||
hostport[0],
|
||||
hostport.Length > 1 ? hostport[1] : "3306",
|
||||
Config.Settings.MySqlDbName,
|
||||
Config.Settings.MySqlUsername,
|
||||
Config.Settings.MySqlPassword
|
||||
);
|
||||
}
|
||||
catch (MySqlException ex)
|
||||
{
|
||||
ServerApi.LogWriter.PluginWriteLine(this, ex.ToString(), TraceLevel.Error);
|
||||
throw new Exception("MySql not setup correctly");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Invalid storage type");
|
||||
}
|
||||
// Build database
|
||||
DbBuilder dbBuilder = new(this, Config, SavePath);
|
||||
DB = dbBuilder.BuildDbConnection();
|
||||
|
||||
if (Config.Settings.UseSqlLogs)
|
||||
Log = new SqlLog(DB, logFilename, LogClear);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue