php-vn-lib/package/usr/share/php/vn/db/conn.php

300 lines
6.1 KiB
PHP
Executable File

<?php
namespace Vn\Db;
require_once ('vn/lib/type.php');
require_once ('vn/db/exception.php');
class Conn
{
private $conn = NULL;
private $isOpen = FALSE;
/**
* Opens a new connection to the database.
*
* @param string $host The host name
* @param string $user The user name to authenticate
* @param string $pass The user password
* @param string $name The default schema name
*
* @return boolean %TRUE on success, %FALSE otherwise
**/
function open ($host, $user, $pass, $name)
{
$conn = $this->conn = mysqli_init ();
$conn->options (MYSQLI_READ_DEFAULT_FILE, __DIR__.'/my.cnf');
@$conn->real_connect ($host, $user, $pass, $name);
if (mysqli_connect_errno ())
{
sleep (1);
throw new Exception (mysqli_connect_errno (), mysqli_connect_error ());
return FALSE;
}
$this->isOpen = TRUE;
$this->query ('SET CHARACTER SET utf8');
return TRUE;
}
/**
* Closes the current connection, if it's closed does nothing.
**/
function close ()
{
if ($this->isOpen)
$this->conn->close ();
$this->isOpen = FALSE;
}
/**
* Checks whether the connection is open.
*
* @return boolean %TRUE if connection is open, %FALSE otherwise
**/
function isOpen ()
{
return $this->isOpen;
}
/**
* Executes the query and gets it's first row.
*
* @param string $query The SQL query
* @param mixed[] $params The query parameters
*
* @return mixed[] An associative array with the first row, %NULL if error
**/
function getRow ($query, $params = NULL)
{
$result = $this->query ($query, $params);
if ($result && ($row = $result->fetch_assoc ()))
return $row;
return NULL;
}
/**
* Executes the query and gets the first value of the first row.
*
* @param string $query The SQL query
* @param mixed[] $params The query parameters
*
* @return mixed The value or %NULL if error
**/
function getValue ($query, $params = NULL)
{
$result = $this->query ($query, $params);
if ($result && ($row = $result->fetch_row ()))
return $row[0];
return NULL;
}
/**
* Executes the query stored in the specified file and gets the result.
*
* @param string $query The SQL query
* @param mixed[] $params The query parameters
*
* @return mixed The value or %NULL if error
**/
function queryFromFile ($file, $params = NULL)
{
$query = file_get_contents ($file);
if ($query)
return $this->query ($query, $params);
return NULL;
}
/**
* Executes the query and gets the result.
*
* @param string $query The SQL query
* @param mixed[] $params The query parameters
*
* @return mixed The value or %NULL if error
**/
function query ($query, $params = NULL)
{
$result = $this->conn->query ($this->render ($query, $params));
if (!$result)
$this->checkError ();
else
while ($this->moreResults ())
$this->nextResult ();
return $result;
}
/**
* Execute multiple queries separated by semicolons.
*
* @param string $query The SQL query
* @param mixed[] $params The query parameters
*
* @return mixed The value or %NULL if error
**/
function multiQuery ($query, $params = NULL)
{
$success = $this->conn->multi_query ($this->render ($query, $params));
if (!$success)
$this->checkError ();
return $success;
}
function storeResult ()
{
$result = $this->conn->store_result ();
if (!$result)
$this->checkError ();
return $result;
}
function moreResults ()
{
return $this->conn->more_results ();
}
function nextResult ()
{
return $this->conn->next_result ();
}
function checkError ()
{
if ($this->conn->errno)
{
$code = $this->conn->errno;
$message = $this->conn->error;
$sql = 'SELECT es_es message, 2000 + id AS id '.
'FROM sql_error WHERE code = @err';
if ($code == 1305 && ($row = $this->getRow ($sql)))
throw new Exception ($row['id'], $row['message']);
else
throw new Exception ($code, $message);
}
}
function checkWarnings ()
{
if ($this->conn->warning_count > 0)
if ($result = $this->conn->query ('SHOW WARNINGS'))
{
$warnings = [];
$sql = 'SELECT es_es message, 3000 + id AS id '.
'FROM sql_warning WHERE code = @warn';
while ($row = $result->fetch_assoc ())
{
if ($row['Code'] == 1265
&& ($warning = $this->getRow ($sql)))
{
$row['Code'] = $warning['id'];
$row['Message'] = $warning['message'];
}
$warnings[] = $row;
}
return $warnings;
}
return NULL;
}
/**
* Renders an SQL string using the given parameters.
*
* @param string $query The SQL string
* @param mixed[] $paramsMap The query parameters
*
* @return mixed The rendered SQL string
**/
function render (&$query, &$paramsMap = NULL)
{
if (isset ($paramsMap) && is_array ($paramsMap) && count ($paramsMap) > 0)
{
$i = 0;
$params = [];
foreach ($paramsMap as $key => $value)
$params[$key] = $this->renderValue ($value);
$replaceFunc = function ($matches) use (&$params, &$i)
{
$key = substr ($matches[0], 1);
if (strlen ($key) == 0)
$key = $i++;
if (isset ($params[$key]))
return $params[$key];
return '#'. $key;
};
return preg_replace_callback ('/#\w*/', $replaceFunc, $query);
}
else
return $query;
}
function renderValue ($value)
{
if ($value !== NULL)
switch (get_type ($value))
{
case TYPE_BOOLEAN:
return ($value) ? 'TRUE' : 'FALSE';
case TYPE_STRING:
return '\'' . $this->conn->escape_string ($value) . '\'';
case TYPE_DATE:
return strftime ('\'%Y-%m-%d\'', $value->getTimestamp ());
case TYPE_TIME:
return strftime ('\'%T\'', $value->getTimestamp ());
case TYPE_DATE_TIME:
return strftime ('\'%Y-%m-%d %T\'', $value->getTimestamp ());
default:
return '\'' . $this->conn->escape_string ($value) . '\'';
}
else
return 'NULL';
}
/**
* Renders an SQL string using sprintf like style.
* DEPRECATED
*
* @return mixed The rendered SQL string
**/
static function renderf ($arg)
{
$count = count ($arg);
if ($count > 1)
{
for ($i = 1; $i < $count; $i++)
$arg[$i] = $this->renderValue ($arg[$i]);
return call_user_func_array ('sprintf', $arg);
}
else
return $arg[0];
}
}
?>