MadelineProto/src/danog/MadelineProto/Db/Driver/Mysql.php

77 lines
2.1 KiB
PHP
Raw Normal View History

2020-04-25 21:57:55 +02:00
<?php
namespace danog\MadelineProto\Db\Driver;
2020-04-25 21:57:55 +02:00
use Amp\Mysql\ConnectionConfig;
use Amp\Mysql\Pool;
2020-05-12 00:41:27 +02:00
use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings\Database\Mysql as DatabaseMysql;
2020-04-25 21:57:55 +02:00
use function Amp\Mysql\Pool;
/**
* MySQL driver wrapper.
*/
2020-04-25 21:57:55 +02:00
class Mysql
{
/** @var Pool[] */
private static array $connections = [];
2020-04-25 21:57:55 +02:00
2020-05-02 19:36:59 +02:00
/**
* @param string $host
* @param int $port
* @param string $user
* @param string $password
* @param string $db
*
2020-05-04 22:09:39 +02:00
* @param int $maxConnections
* @param int $idleTimeout
*
2020-05-02 19:36:59 +02:00
* @throws \Amp\Sql\ConnectionException
* @throws \Amp\Sql\FailureException
* @throws \Throwable
*
* @return \Generator<Pool>
2020-05-02 19:36:59 +02:00
*/
public static function getConnection(DatabaseMysql $settings): \Generator
{
$dbKey = $settings->getKey();
2020-04-25 21:57:55 +02:00
if (empty(static::$connections[$dbKey])) {
$config = ConnectionConfig::fromString("host=".\str_replace("tcp://", "", $settings->getUri()))
->withUser($settings->getUsername())
->withPassword($settings->getPassword())
->withDatabase($settings->getDatabase());
2020-05-02 19:36:59 +02:00
yield from static::createDb($config);
static::$connections[$dbKey] = pool($config, $settings->getMaxConnections(), $settings->getIdleTimeout());
2020-04-25 21:57:55 +02:00
}
return static::$connections[$dbKey];
}
2020-05-02 19:36:59 +02:00
/**
* @param ConnectionConfig $config
*
* @throws \Amp\Sql\ConnectionException
* @throws \Amp\Sql\FailureException
* @throws \Throwable
*
* @return \Generator
2020-05-02 19:36:59 +02:00
*/
private static function createDb(ConnectionConfig $config): \Generator
2020-05-03 03:33:54 +02:00
{
try {
$db = $config->getDatabase();
$connection = pool($config->withDatabase(null));
yield $connection->query("
2020-05-12 00:41:27 +02:00
CREATE DATABASE IF NOT EXISTS `{$db}`
CHARACTER SET 'utf8mb4'
COLLATE 'utf8mb4_general_ci'
");
$connection->close();
} catch (\Throwable $e) {
Logger::log($e->getMessage(), Logger::ERROR);
}
2020-05-02 19:36:59 +02:00
}
2020-06-16 17:52:55 +02:00
}