Support connect to mysql using socket

This commit is contained in:
sy-records 2024-03-22 09:10:59 +08:00
parent d84e261f7b
commit 20537a0124
No known key found for this signature in database
GPG Key ID: C3BB4FF13CD72ACE
3 changed files with 47 additions and 19 deletions

View File

@ -1065,6 +1065,9 @@ function install_step_2_perform()
// intval port number
if (isset($dbConfig['port'])) {
$dbConfig['port'] = intval($dbConfig['port']);
if (strpos($dbConfig['host'], '/') !== false && $type == 'Mysql') {
$dbConfig['port'] = null;
}
}
// bool ssl verify

View File

@ -5,6 +5,7 @@ namespace Typecho\Db\Adapter;
use Typecho\Config;
use Typecho\Db;
use Typecho\Db\Adapter;
use mysqli_sql_exception;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
@ -49,26 +50,40 @@ class Mysqli implements Adapter
{
$mysqli = mysqli_init();
if ($mysqli) {
if (!empty($config->sslCa)) {
$mysqli->ssl_set(null, null, $config->sslCa, null, null);
try {
if (!empty($config->sslCa)) {
$mysqli->ssl_set(null, null, $config->sslCa, null, null);
if (isset($config->sslVerify)) {
$mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, $config->sslVerify);
if (isset($config->sslVerify)) {
$mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, $config->sslVerify);
}
}
}
$mysqli->real_connect(
$config->host,
$config->user,
$config->password,
$config->database,
(empty($config->port) ? null : $config->port)
);
$host = $config->host;
$port = empty($config->port) ? null : $config->port;
$socket = null;
if (strpos($host, '/') !== false) {
$socket = $host;
$host = 'localhost';
$port = null;
}
$this->dbLink = $mysqli;
$mysqli->real_connect(
$host,
$config->user,
$config->password,
$config->database,
$port,
$socket
);
if ($config->charset) {
$this->dbLink->query("SET NAMES '{$config->charset}'");
$this->dbLink = $mysqli;
if ($config->charset) {
$this->dbLink->query("SET NAMES '{$config->charset}'");
}
} catch (mysqli_sql_exception $e) {
throw new ConnectionException($e->getMessage(), $e->getCode());
}
return $this->dbLink;
@ -106,8 +121,13 @@ class Mysqli implements Adapter
?string $action = null,
?string $table = null
) {
if ($resource = @$this->dbLink->query($query)) {
return $resource;
try {
if ($resource = @$this->dbLink->query($query)) {
return $resource;
}
} catch (mysqli_sql_exception $e) {
/** 数据库异常 */
throw new SQLException($e->getMessage(), $e->getCode());
}
/** 数据库异常 */

View File

@ -61,9 +61,14 @@ class Mysql extends Pdo
}
}
$dsn = !empty($config->dsn)
? $config->dsn
: (strpos($config->host, '/') !== false
? "mysql:dbname={$config->database};unix_socket={$config->host}"
: "mysql:dbname={$config->database};host={$config->host};port={$config->port}");
$pdo = new \PDO(
!empty($config->dsn)
? $config->dsn : "mysql:dbname={$config->database};host={$config->host};port={$config->port}",
$dsn,
$config->user,
$config->password,
$options