56 lines
1.8 KiB
PHP
56 lines
1.8 KiB
PHP
<?php
|
|
namespace Misuzu;
|
|
|
|
use PDO;
|
|
use InvalidArgumentException;
|
|
use Index\Data\IDbConnectionInfo;
|
|
use Index\Data\MariaDB\MariaDBConnectionInfo;
|
|
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,
|
|
];
|
|
|
|
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);
|
|
}
|
|
|
|
public static function __callStatic(string $name, array $args) {
|
|
return self::$instance->{$name}(...$args);
|
|
}
|
|
|
|
public static function getInstance(): Database {
|
|
return self::$instance;
|
|
}
|
|
}
|