lunes, 12 de marzo de 2012

Mejorando Prestashop: cambio de driver Mysql a Mysqli

La presente es una mejora de Prestashop, se cambia el driver Mysql por Mysqli. Para esto creamos la clase "classes/MySQL2.php" con el siguiente código:

class MySQL2Core extends Db
{
 public function connect()
 {
            
  if (!defined('_PS_DEBUG_SQL_'))
   define('_PS_DEBUG_SQL_', false);
  if ($this->_link = mysqli_connect($this->_server, $this->_user, $this->_password))               
                { 
   if (!$this->set_db($this->_database))
    die(Tools::displayError('The database selection cannot be made.'));
  }
  else
   die(Tools::displayError('Link to database cannot be established.'));
  /* UTF-8 support */
  if (!mysqli_query($this->_link,'SET NAMES \'utf8\''))
   die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
  // removed SET GLOBAL SQL_MODE : we can't do that (see PSCFI-1548)
  return $this->_link;
 }
 
 public function getServerVersion(){
  return mysqli_get_server_info();
 }
 
 /* do not remove, useful for some modules */
 public function set_db($db_name) {
  return mysqli_select_db($this->_link , $db_name );
 }
 
 public function disconnect()
 {
  if ($this->_link)
   @mysqli_close($this->_link);
  $this->_link = false;
 }
 
 public function getRow($query, $use_cache = 1)
 {
  $query .= ' LIMIT 1';
  $this->_result = false;
  $this->_lastQuery = $query;
  if ($use_cache AND _PS_CACHE_ENABLED_){
      $result = Cache::getInstance()->get(md5($query));
      if ( !(gettype($result) === 'boolean' &&  ($result === false) ) )
   {
    $this->_lastCached = true;
    return $result;
   }
  }
  if ($this->_link)
   if ($this->_result = mysqli_query($this->_link, $query))
   {
// echo 'getRow : '. $query ."\n";
    $this->_lastCached = false;
    if (_PS_DEBUG_SQL_)
     $this->displayMySQLError($query);
    $result = mysqli_fetch_assoc($this->_result);
    if ($use_cache = 1 AND _PS_CACHE_ENABLED_){
        Cache::getInstance()->setQuery($query, $result);
    }
    return $result;
   }
  if (_PS_DEBUG_SQL_)
   $this->displayMySQLError($query);
  return false;
 }

 public function getValue($query, $use_cache = 1)
 {
  $query .= ' LIMIT 1';
  $this->_result = false;
  $this->_lastQuery = $query;
  if ($use_cache AND _PS_CACHE_ENABLED_){
      $result = Cache::getInstance()->get(md5($query));
      if ( !(gettype($result) === 'boolean' &&  ($result === false) ))
       {
        $this->_lastCached = true;
        return $result;
       }

  }
  
  if ($this->_link AND $this->_result = mysqli_query($this->_link, $query) AND is_array($tmpArray = mysqli_fetch_assoc($this->_result)))
  {
// echo 'getValue : '. $query ."\n";
      
   $this->_lastCached = false;
   $result =  array_shift($tmpArray);
   if ($use_cache AND _PS_CACHE_ENABLED_){
       Cache::getInstance()->setQuery($query, $result);
   }
   return $result;
  }
  
  return false;
 }
 
 public function Execute($query, $use_cache = 1)
 {
  $this->_result = false;
  if ($this->_link)
  {
   $this->_result = mysqli_query($this->_link, $query);
// echo 'Execute : '. $query ."\n";
   
   if (_PS_DEBUG_SQL_)
    $this->displayMySQLError($query);
   if ($use_cache AND _PS_CACHE_ENABLED_){
       Cache::getInstance()->deleteQuery($query); //VALIDAR POR Q BORRA EL CACHE
   }
   return $this->_result;
  }
  if (_PS_DEBUG_SQL_)
   $this->displayMySQLError($query);
  return false;
 }
 
 /**
  * ExecuteS return the result of $query as array, 
  * or as mysqli_result if $array set to false
  * 
  * @param string $query query to execute
  * @param boolean $array return an array instead of a mysql_result object
  * @param int $use_cache if query has been already executed, use its result
  * @return array or result object 
  */
 public function ExecuteS($query, $array = true, $use_cache = 1)
 {   
  $this->_result = false;
  $this->_lastQuery = $query;
  if ($use_cache AND _PS_CACHE_ENABLED_){
      $result = Cache::getInstance()->get(md5($query));
      if ($array  AND  !(gettype($result) === 'boolean' &&  ($result === false) ) ) 
   {
    $this->_lastCached = true;
    return $result;
    
   } 
  }
                
  if ($this->_link && $this->_result = mysqli_query($this->_link, $query)){
                    
// echo 'ExecuteS ' . $query . ' -- ' . $array . $use_cache. "\n";      
   $this->_lastCached = false;
   if (_PS_DEBUG_SQL_)
    $this->displayMySQLError($query);
   
                        if (!$array)
    return $this->_result;
   $resultArray = array();
   // Only SELECT queries and a few others return a valid resource usable with mysqli_fetch_assoc
   if ($this->_result !== true){                            
    while ($row = mysqli_fetch_assoc($this->_result))
     $resultArray[] = $row;
   }
   if ($use_cache AND _PS_CACHE_ENABLED_){
       Cache::getInstance()->setQuery($query, $resultArray);
   }
   return $resultArray;
  }
  if (_PS_DEBUG_SQL_)
   $this->displayMySQLError($query);
  return false;
 }

 public function nextRow($result = false)
 {
  return mysqli_fetch_assoc($result ? $result : $this->_result);
 }
 
 public function delete($table, $where = false, $limit = false, $use_cache = 1)
 {
     $this->_result = false;
  if ($this->_link)
  {
   $query  = 'DELETE FROM `'.pSQL($table).'`'.($where ? ' WHERE '.$where : '').($limit ? ' LIMIT '.(int)($limit) : '');
   $res =  mysqli_query($this->_link, $query);
// echo 'delete : '. $query ."\n";
   
   if ($use_cache AND _PS_CACHE_ENABLED_){
       Cache::getInstance()->deleteQuery($query);
   }
   return $res;
  }
   
  return false;
 }
 
 public function NumRows()
 {
  if (!$this->_lastCached AND $this->_link AND $this->_result)
  {
   $nrows = mysqli_num_rows($this->_result);
   if (_PS_CACHE_ENABLED_){
    Cache::getInstance()->setNumRows(md5($this->_lastQuery), $nrows);
   }
   return $nrows;
  }
  elseif (_PS_CACHE_ENABLED_ AND $this->_lastCached)
  {
   return Cache::getInstance()->getNumRows(md5($this->_lastQuery));
  }
 }
 
 public function Insert_ID()
 {
  if ($this->_link)
   return mysqli_insert_id($this->_link);
  return false;
 }
 
 public function Affected_Rows()
 {
  if ($this->_link)
   return mysqli_affected_rows($this->_link);
  return false;
 }

 protected function q($query, $use_cache = 1)
 {
  global $webservice_call;
  $this->_result = false;
  if ($this->_link)
  {
   $result =  mysqli_query($this->_link, $query);
// echo 'q : '. $query ."\n";
   
   $this->_lastQuery = $query;
   if ($webservice_call)
    $this->displayMySQLError($query);
   if ($use_cache AND _PS_CACHE_ENABLED_){
       Cache::getInstance()->deleteQuery($query);
   }
   return $result;
  }
  return false;
 }
 
 /**
  * Returns the text of the error message from previous MySQL operation
  *
  * @acces public
  * @return string error
  */
 public function getMsgError($query = false)
 {
  return mysqli_error($this->_link);
 }

 public function getNumberError()
 {
  return mysqli_errno($this->_link);
 }

 public function displayMySQLError($query = false)
 {
  global $webservice_call;
  if ($webservice_call && mysqli_errno($this->_link))
  {
   WebserviceRequest::getInstance()->setError(500, '[SQL Error] '.mysqli_error($this->_link).'. Query was : '.$query, 97);

  }
  elseif (_PS_DEBUG_SQL_ AND mysqli_errno($this->_link) AND !defined('PS_INSTALLATION_IN_PROGRESS'))
  {
   if ($query)
    die(Tools::displayError(mysqli_error($this->_link).'

'.$query.'
')); die(Tools::displayError((mysqli_error($this->_link)))); } } /** * tryToConnect return 0 if the connection succeed and the database can be selected. * @since 1.4.4.0, the parameter $newDbLink (default true) has been added. * * @param string $server mysql server name * @param string $user mysql user * @param string $pwd mysql user password * @param string $db mysql database name * @param boolean $newDbLink if set to true, the function will not create a new link if one already exists. * @return integer */ public static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true) { if (!$link = @mysqli_connect($server, $user, $pwd)) return 1; if (!@mysqli_select_db($link,$db)) return 2; @mysqli_close($link); return 0; } public static function tryUTF8($server, $user, $pwd) { $link = @mysqli_connect($server, $user, $pwd); if (!mysqli_query($link,'SET NAMES \'utf8\'')) $ret = false; else $ret = true; @mysqli_close($link); return $ret; } }

Y en el archivo "classes/Db.php" cambiamos:

self::$_instance[(int)($idServer)] = new MySQL(self::$_servers[(int)($idServer)]['server'], self::$_servers[(int)($idServer)]['user'], self::$_servers[(int)($idServer)]['password'], self::$_servers[(int)($idServer)]['database']);

Por

self::$_instance[(int)($idServer)] = new MySQL2(self::$_servers[(int)($idServer)]['server'], self::$_servers[(int)($idServer)]['user'], self::$_servers[(int)($idServer)]['password'], self::$_servers[(int)($idServer)]['database']);

Suerte en la implementación !!
Enhanced by Zemanta

1 comentario:

franco dijo...

Hola, esto no es suficiente...porque devuelve un Fatal Error. Tambièn el Db.php tiene una función mysql_real_escape_string que debe ser convertida...mejor si se utiliza esto https://github.com/philip/MySQLConverterTool en ambos archivos MYSQL.php y Db.php.. y entonces funciona bien... Feliz Año Nuevo

Configure Grafana and Slack

To configure Grafana to send alerts to Slack, you need to set up a notification channel in Grafana and configure it to use the Slack integra...