2022-09-13 13:14:49 +00:00
|
|
|
<?php
|
|
|
|
namespace Misuzu;
|
|
|
|
|
|
|
|
use PDO;
|
2023-07-11 22:45:23 +00:00
|
|
|
use InvalidArgumentException;
|
|
|
|
use Index\Data\IDbConnectionInfo;
|
|
|
|
use Index\Data\MariaDB\MariaDBConnectionInfo;
|
2022-09-13 13:14:49 +00:00
|
|
|
use Misuzu\Database\Database;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @method static int queries()
|
|
|
|
* @method static int exec(string $stmt)
|
|
|
|
* @method static \Misuzu\Database\DatabaseStatement prepare(string $stmt, array $options = [])
|
|
|
|
* @method static \Misuzu\Database\DatabaseStatement query(string $stmt, ?int $fetchMode = null, ...$args)
|
|
|
|
* @method static int lastId()
|
|
|
|
*/
|
|
|
|
final class DB {
|
|
|
|
private static $instance;
|
|
|
|
|
|
|
|
public const ATTRS = [
|
|
|
|
PDO::ATTR_CASE => PDO::CASE_NATURAL,
|
|
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
|
|
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
|
|
|
|
PDO::ATTR_STRINGIFY_FETCHES => false,
|
|
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
|
|
];
|
|
|
|
|
2023-07-11 22:45:23 +00:00
|
|
|
public static function init(IDbConnectionInfo $connInfo) {
|
|
|
|
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);
|
2022-09-13 13:14:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static function __callStatic(string $name, array $args) {
|
|
|
|
return self::$instance->{$name}(...$args);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function getInstance(): Database {
|
|
|
|
return self::$instance;
|
|
|
|
}
|
|
|
|
}
|