Use the Index DSN to create the PDO based DB instance.

This commit is contained in:
flash 2023-07-11 22:45:23 +00:00
parent 1186b0daeb
commit 29165de457
4 changed files with 25 additions and 21 deletions

@ -1 +1 @@
Subproject commit 31798a6b536069bc47832545b036c0d62422400c Subproject commit 939dcd10fe7f33d567e4bf327b284dcb8a9bdd63

View file

@ -78,8 +78,7 @@ define('MSZ_DB_INIT', 'SET SESSION time_zone = \'+00:00\', sql_mode = \'STRICT_T
$db = DbTools::create($dbConfig['dsn']); $db = DbTools::create($dbConfig['dsn']);
$db->execute(MSZ_DB_INIT); $db->execute(MSZ_DB_INIT);
$dbConfig = $dbConfig['Database'] ?? $dbConfig['Database.mysql-main'] ?? []; DB::init(DbTools::parse($dbConfig['dsn']));
DB::init(DB::buildDSN($dbConfig), $dbConfig['username'] ?? '', $dbConfig['password'] ?? '', DB::ATTRS);
DB::exec(MSZ_DB_INIT); DB::exec(MSZ_DB_INIT);
$cfg = new DbConfig($db); $cfg = new DbConfig($db);

View file

@ -2,6 +2,9 @@
namespace Misuzu; namespace Misuzu;
use PDO; use PDO;
use InvalidArgumentException;
use Index\Data\IDbConnectionInfo;
use Index\Data\MariaDB\MariaDBConnectionInfo;
use Misuzu\Database\Database; use Misuzu\Database\Database;
/** /**
@ -24,8 +27,25 @@ final class DB {
PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_EMULATE_PREPARES => false,
]; ];
public static function init(...$args) { public static function init(IDbConnectionInfo $connInfo) {
self::$instance = new Database(...$args); if(!($connInfo instanceof MariaDBConnectionInfo))
throw new InvalidArgumentException('$connInfo must be an instance of MariaDBConnectionInfo (only mariadb/mysql is supported).');
$dsn = 'mysql:';
if($connInfo->isUnixSocket())
$dsn .= 'unix_socket=' . $connInfo->getSocketPath() . ';';
else {
$dsn .= 'host=' . $connInfo->getHost() . ';';
$dsn .= 'port=' . $connInfo->getPort() . ';';
}
$dsn .= 'dbname=' . $connInfo->getDatabaseName() . ';';
if($connInfo->hasCharacterSet())
$dsn .= 'charset=' . $connInfo->getCharacterSet() . ';';
self::$instance = new Database($dsn, $connInfo->getUserName(), $connInfo->getPassword(), self::ATTRS);
} }
public static function __callStatic(string $name, array $args) { public static function __callStatic(string $name, array $args) {
@ -35,19 +55,4 @@ final class DB {
public static function getInstance(): Database { public static function getInstance(): Database {
return self::$instance; return self::$instance;
} }
public static function buildDSN(array $vars): string {
$dsn = ($vars['driver'] ?? 'mysql') . ':';
foreach($vars as $key => $value) {
if($key === 'driver' || $key === 'username' || $key === 'password')
continue;
if($key === 'database')
$key = 'dbname';
$dsn .= $key . '=' . $value . ';';
}
return $dsn;
}
} }

View file

@ -11,6 +11,6 @@
</head> </head>
<body> <body>
<h1>Error 500</h1> <h1>Error 500</h1>
<p>Something horrendously went wrong. Please report what you were doing to a developer.</p> <p>Something went very wrong. Please report what you were doing to a developer.</p>
</body> </body>
</html> </html>