2017-11-01 20:56:06 +00:00
|
|
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
|
using Npgsql;
|
2018-02-17 07:41:12 +00:00
|
|
|
|
using System;
|
2017-11-01 20:56:06 +00:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Noikoio.RegexBot.ConfigItem
|
|
|
|
|
{
|
|
|
|
|
class DatabaseConfig
|
|
|
|
|
{
|
|
|
|
|
private readonly string _host;
|
|
|
|
|
private readonly string _user;
|
|
|
|
|
private readonly string _pass;
|
|
|
|
|
private readonly string _dbname;
|
|
|
|
|
|
|
|
|
|
public DatabaseConfig(JToken ctok)
|
|
|
|
|
{
|
|
|
|
|
if (ctok == null || ctok.Type != JTokenType.Object)
|
|
|
|
|
{
|
2018-02-17 07:41:12 +00:00
|
|
|
|
throw new DatabaseConfigLoadException("");
|
2017-11-01 20:56:06 +00:00
|
|
|
|
}
|
|
|
|
|
var conf = (JObject)ctok;
|
|
|
|
|
|
|
|
|
|
_host = conf["hostname"]?.Value<string>() ?? "localhost"; // default to localhost
|
2018-02-17 07:41:12 +00:00
|
|
|
|
|
2017-11-01 20:56:06 +00:00
|
|
|
|
_user = conf["username"]?.Value<string>();
|
2018-02-17 07:41:12 +00:00
|
|
|
|
if (string.IsNullOrWhiteSpace(_user))
|
|
|
|
|
throw new DatabaseConfigLoadException("Value for username is not defined.");
|
2017-11-01 20:56:06 +00:00
|
|
|
|
|
2018-02-17 07:41:12 +00:00
|
|
|
|
_pass = conf["password"]?.Value<string>();
|
|
|
|
|
if (string.IsNullOrWhiteSpace(_pass))
|
|
|
|
|
throw new DatabaseConfigLoadException(
|
|
|
|
|
$"Value for password is not defined. {nameof(RegexBot)} only supports password authentication.");
|
2017-11-01 20:56:06 +00:00
|
|
|
|
|
2018-02-17 07:41:12 +00:00
|
|
|
|
_dbname = conf["database"]?.Value<string>();
|
|
|
|
|
if (string.IsNullOrWhiteSpace(_dbname))
|
|
|
|
|
throw new DatabaseConfigLoadException("Value for database name is not defined.");
|
2017-11-01 20:56:06 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-02-17 07:41:12 +00:00
|
|
|
|
internal async Task<NpgsqlConnection> GetOpenConnectionAsync()
|
2017-11-01 20:56:06 +00:00
|
|
|
|
{
|
|
|
|
|
var cs = new NpgsqlConnectionStringBuilder()
|
|
|
|
|
{
|
|
|
|
|
Host = _host,
|
|
|
|
|
Username = _user,
|
|
|
|
|
Password = _pass,
|
|
|
|
|
Database = _dbname
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
var db = new NpgsqlConnection(cs.ToString());
|
|
|
|
|
await db.OpenAsync();
|
|
|
|
|
return db;
|
|
|
|
|
}
|
2018-02-17 07:41:12 +00:00
|
|
|
|
|
|
|
|
|
internal class DatabaseConfigLoadException : Exception
|
|
|
|
|
{
|
|
|
|
|
public DatabaseConfigLoadException(string message) : base(message) { }
|
|
|
|
|
}
|
2017-11-01 20:56:06 +00:00
|
|
|
|
}
|
|
|
|
|
}
|