<?php
namespace Bitrix\Main\DB;

class MysqlDbConnection
	extends DbConnection
{
	public function __construct($dbHost, $dbName, $dbLogin, $dbPassword, $dbInitCommand, $dbOptions = -1)
	{
		parent::__construct($dbHost, $dbName, $dbLogin, $dbPassword, $dbInitCommand, $dbOptions);
	}

	/**********************************************************
	 * SqlHelper
	 **********************************************************/

	/**
	 * @return SqlHelper
	 */
	protected function createSqlHelper()
	{
		return new MysqlSqlHelper($this);
	}


	/***********************************************************
	 * Connection and disconnection
	 ***********************************************************/

	public function disconnectInternal()
	{
		if (!$this->isConnected)
			return;

		mysql_close($this->connectionResource);
	}

	protected function connectInternal()
	{
		if ($this->isConnected)
			return;

		if (($this->dbOptions & self::PERSISTENT) != 0)
			$connection = @mysql_pconnect($this->dbHost, $this->dbLogin, $this->dbPassword);
		else
			$connection = @mysql_connect($this->dbHost, $this->dbLogin, $this->dbPassword, true);

		if (!$connection)
			throw new ConnectionException('Mysql connect error', mysql_error());

		if (!mysql_select_db($this->dbName, $connection))
			throw new ConnectionException('Mysql select db error', mysql_error($connection));

		$this->connectionResource = $connection;
		$this->isConnected = true;

		global $DB, $USER, $APPLICATION;
		if ($fn = \Bitrix\Main\Loader::getPersonal("php_interface/after_connect.php"))
			include($fn);
	}


	/*********************************************************
	 * Query
	 *********************************************************/

	/**
	 * @param $sql
	 * @param array|null $arBinds
	 * @param $offset
	 * @param $limit
	 * @param \Bitrix\Main\Diag\SqlTrackerQuery|null $trackerQuery
	 * @return resource
	 * @throws SqlException
	 */
	protected function queryInternal($sql, array $arBinds, $offset, $limit, \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery = null)
	{
		$this->connectInternal();

		$offset = intval($offset);
		$limit = intval($limit);

		if ($offset > 0 && $limit <= 0)
			throw new \Bitrix\Main\ArgumentException("Limit should be set if offset is set");

		if ($limit > 0)
		{
			if (preg_match("#\slimit\s+\d#i", $sql))
				throw new \Bitrix\Main\ArgumentException("Duplicate limit settings");

			$sql .= "\nLIMIT ".intval($offset).", ".intval($limit)."\n";
		}

		if ($trackerQuery != null)
			$trackerQuery->startQuery($sql, $arBinds);

		$result = @mysql_query($sql, $this->connectionResource);

		if ($trackerQuery != null)
			$trackerQuery->finishQuery();

		if (!$result)
			throw new SqlException('Mysql query error', mysql_error($this->connectionResource));

		return $result;
	}

	/**
	 * @param $result
	 * @param \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery
	 * @return DbResult
	 */
	protected function createDbResult($result, \Bitrix\Main\Diag\SqlTrackerQuery $trackerQuery = null)
	{
		return new MysqlDbResult($this, $result, $trackerQuery);
	}

	public function getInsertedId($name = "")
	{
		$this->connectInternal();
		return mysql_insert_id($this->connectionResource);
	}


	/*********************************************************
	 * DDL
	 *********************************************************/

	public function isTableExists($tableName)
	{
		$tableName = preg_replace("/[^A-Za-z0-9%_]+/i", "", $tableName);
		$tableName = trim($tableName);

		if (strlen($tableName) <= 0)
			return false;

		$dbResult = $this->query("SHOW TABLES LIKE '".$this->getSqlHelper()->forSql($tableName)."'");
		if ($arResult = $dbResult->Fetch())
			return true;
		else
			return false;
	}

	public function isIndexExists($tableName, array $arColumns)
	{
		return $this->getIndexName($tableName, $arColumns) !== null;
	}

	public function getIndexName($tableName, array $arColumns, $strict = false)
	{
		if (!is_array($arColumns) || count($arColumns) <= 0)
			return null;

		$rs = $this->query("SHOW INDEX FROM `".$this->getSqlHelper()->forSql($tableName)."`");
		if (!$rs)
			return null;

		$arIndexes = array();
		while ($ar = $rs->fetch())
			$arIndexes[$ar["Key_name"]][$ar["Seq_in_index"] - 1] = $ar["Column_name"];

		$strColumns = implode(",", $arColumns);
		foreach ($arIndexes as $Key_name => $arKeyColumns)
		{
			ksort($arKeyColumns);
			$strKeyColumns = implode(",", $arKeyColumns);
			if ($strict)
			{
				if ($strKeyColumns === $strColumns)
					return $Key_name;
			}
			else
			{
				if (substr($strKeyColumns, 0, strlen($strColumns)) === $strColumns)
					return $Key_name;
			}
		}

		return null;
	}

	public function getTableFields($tableName)
	{
		if (!array_key_exists($tableName, $this->tableColumnsCache))
		{
			$this->tableColumnsCache[$tableName] = array();
			$this->connectInternal();
			$rs = mysql_list_fields($this->dbName, $tableName, $this->connectionResource);
			if ($rs > 0)
			{
				$intNumFields = mysql_num_fields($rs);
				while (--$intNumFields >= 0)
				{
					$name = mysql_field_name($rs, $intNumFields);
					$type = mysql_field_type($rs, $intNumFields);
					$this->tableColumnsCache[$tableName][$name] = array(
						"NAME" => $name,
						"TYPE" => $type,
					);
				}
			}
		}
		return $this->tableColumnsCache[$tableName];
	}


	/*********************************************************
	 * Transaction
	 *********************************************************/

	public function startTransaction()
	{
		$this->query("START TRANSACTION");
	}

	public function commitTransaction()
	{
		$this->query("COMMIT");
	}

	public function rollbackTransaction()
	{
		$this->query("ROLLBACK");
	}


	/*********************************************************
	 * Type, version, cache, etc.
	 *********************************************************/

	public function getVersion()
	{
		if ($this->version == null)
		{
			$version = $this->queryScalar("SELECT VERSION()");
			if ($version != null)
			{
				$version = trim($version);
				preg_match("#[0-9]+\.[0-9]+\.[0-9]+#", $version, $ar);
				$this->version = $ar[0];
			}
		}

		return array($this->version, null);
	}

	public function getType()
	{
		return "mysql";
	}

	protected function getErrorMessage()
	{
		return sprintf("[%s] %s", mysql_errno($this->connectionResource), mysql_error($this->connectionResource));
	}
}
