From c6ceae52250877c966a3ede6c6e9d2c49bb8ca8a Mon Sep 17 00:00:00 2001 From: Michael Date: Thu, 14 Sep 2017 05:19:05 +0000 Subject: [PATCH] The old database function is now replaced with a wrapper --- include/dba.php | 233 ++++++++++------------------------------ include/dbstructure.php | 18 ++-- mod/directory.php | 6 +- 3 files changed, 66 insertions(+), 191 deletions(-) diff --git a/include/dba.php b/include/dba.php index c945228297..53ee3e9655 100644 --- a/include/dba.php +++ b/include/dba.php @@ -214,171 +214,22 @@ class dba { } } - public function q($sql, $onlyquery = false) { - $a = get_app(); + public function q($sql) { + $ret = self::p($sql); - if (!$this->db || !$this->connected) { - return false; + if (is_bool($ret)) { + return $ret; } - $this->error = ''; + $columns = self::columnCount($ret); - $connstr = ($this->connected() ? "Connected" : "Disonnected"); + $data = self::inArray($ret); - $stamp1 = microtime(true); - - $orig_sql = $sql; - - if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) { - $sql = "/*".System::callstack()." */ ".$sql; - } - - $columns = 0; - - switch ($this->driver) { - case 'pdo': - $result = @$this->db->query($sql); - // Is used to separate between queries that returning data - or not - if (!is_bool($result)) { - $columns = $result->columnCount(); - } - break; - case 'mysqli': - $result = @$this->db->query($sql); - break; - case 'mysql': - $result = @mysql_query($sql,$this->db); - break; - } - $stamp2 = microtime(true); - $duration = (float)($stamp2 - $stamp1); - - $a->save_timestamp($stamp1, "database"); - - if (strtolower(substr($orig_sql, 0, 6)) != "select") { - $a->save_timestamp($stamp1, "database_write"); - } - if (x($a->config,'system') && x($a->config['system'],'db_log')) { - if (($duration > $a->config["system"]["db_loglimit"])) { - $duration = round($duration, 3); - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t". - basename($backtrace[1]["file"])."\t". - $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". - substr($sql, 0, 2000)."\n", FILE_APPEND); - } - } - - switch ($this->driver) { - case 'pdo': - $errorInfo = $this->db->errorInfo(); - if ($errorInfo) { - $this->error = $errorInfo[2]; - $this->errorno = $errorInfo[1]; - } - break; - case 'mysqli': - if ($this->db->errno) { - $this->error = $this->db->error; - $this->errorno = $this->db->errno; - } - break; - case 'mysql': - if (mysql_errno($this->db)) { - $this->error = mysql_error($this->db); - $this->errorno = mysql_errno($this->db); - } - break; - } - if (strlen($this->error)) { - logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error); - } - - if ($this->debug) { - - $mesg = ''; - - if ($result === false) { - $mesg = 'false'; - } elseif ($result === true) { - $mesg = 'true'; - } else { - switch ($this->driver) { - case 'pdo': - $mesg = $result->rowCount().' results'.EOL; - break; - case 'mysqli': - $mesg = $result->num_rows.' results'.EOL; - break; - case 'mysql': - $mesg = mysql_num_rows($result).' results'.EOL; - break; - } - } - - $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg - . (($this->error) ? ' error: ' . $this->error : '') - . EOL; - - logger('dba: ' . $str ); - } - - /** - * If dbfail.out exists, we will write any failed calls directly to it, - * regardless of any logging that may or may nor be in effect. - * These usually indicate SQL syntax errors that need to be resolved. - */ - - if ($result === false) { - logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error); - if (file_exists('dbfail.out')) { - file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND); - } - } - - if (is_bool($result)) { - return $result; - } - if ($onlyquery) { - $this->result = $result; + if ((count($data) == 0) && ($columns == 0)) { return true; } - $r = array(); - switch ($this->driver) { - case 'pdo': - while ($x = $result->fetch(PDO::FETCH_ASSOC)) { - $r[] = $x; - } - $result->closeCursor(); - break; - case 'mysqli': - while ($x = $result->fetch_array(MYSQLI_ASSOC)) { - $r[] = $x; - } - $result->free_result(); - break; - case 'mysql': - while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) { - $r[] = $x; - } - mysql_free_result($result); - break; - } - - // PDO doesn't return "true" on successful operations - like mysqli does - // Emulate this behaviour by checking if the query returned data and had columns - // This should be reliable enough - if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) { - return true; - } - - //$a->save_timestamp($stamp1, "database"); - - if ($this->debug) { - logger('dba: ' . printable(print_r($r, true))); - } - return($r); + return $data; } public function dbg($dbg) { @@ -820,6 +671,26 @@ class dba { return self::$dbo->affected_rows; } + /** + * @brief Returns the number of columns of a statement + * + * @param object Statement object + * @return int Number of columns + */ + public static function columnCount($stmt) { + if (!is_object($stmt)) { + return 0; + } + switch (self::$dbo->driver) { + case 'pdo': + return $stmt->columnCount(); + case 'mysqli': + return $stmt->field_count; + case 'mysql': + return mysql_affected_rows($stmt); + } + return 0; + } /** * @brief Returns the number of rows of a statement * @@ -1415,38 +1286,44 @@ function dbesc($str) { // 'user', 1); function q($sql) { global $db; + $args = func_get_args(); unset($args[0]); - if ($db && $db->connected) { - $sql = $db->clean_query($sql); - $sql = $db->any_value_fallback($sql); - $stmt = @vsprintf($sql,$args); // Disabled warnings - //logger("dba: q: $stmt", LOGGER_ALL); - if ($stmt === false) - logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG); - - $db->log_index($stmt); - - return $db->q($stmt); + if (!$db || !$db->connected) { + return false; } - /** - * - * This will happen occasionally trying to store the - * session data after abnormal program termination - * - */ - logger('dba: no database: ' . print_r($args,true)); - return false; + $sql = $db->clean_query($sql); + $sql = $db->any_value_fallback($sql); + + $stmt = @vsprintf($sql, $args); + + $ret = dba::p($stmt); + + if (is_bool($ret)) { + return $ret; + } + + $columns = dba::columnCount($ret); + + $data = dba::inArray($ret); + + if ((count($data) == 0) && ($columns == 0)) { + return true; + } + + return $data; } /** - * @brief Performs a query with "dirty reads" + * @brief Performs a query with "dirty reads" - deprecated * * By doing dirty reads (reading uncommitted data) no locks are performed * This function can be used to fetch data that doesn't need to be reliable. * + * Hadn't worked like expected and does now the same like the other function. + * * @param $args Query parameters (1 to N parameters of different types) * @return array Query array */ @@ -1465,9 +1342,7 @@ function qu($sql) { $db->log_index($stmt); - $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); $retval = $db->q($stmt); - $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); return $retval; } diff --git a/include/dbstructure.php b/include/dbstructure.php index d87f3948d2..4d615a2f14 100644 --- a/include/dbstructure.php +++ b/include/dbstructure.php @@ -31,7 +31,7 @@ function convert_to_innodb() { $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", dbesc($table['TABLE_NAME'])); echo $sql."\n"; - $result = $db->q($sql); + $result = dba::e($sql); if (!dbm::is_result($result)) { print_update_error($db, $sql); } @@ -442,9 +442,9 @@ function update_structure($verbose, $action, $tables=null, $definition=null) { // Ensure index conversion to unique removes duplicates if ($is_unique) { if ($ignore != "") { - $db->q("SET session old_alter_table=1;"); + dba::e("SET session old_alter_table=1;"); } else { - $r = $db->q("CREATE TABLE `".$temp_name."` LIKE `".$name."`;"); + $r = dba::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;"); if (!dbm::is_result($r)) { $errors .= print_update_error($db, $sql3); return $errors; @@ -452,25 +452,25 @@ function update_structure($verbose, $action, $tables=null, $definition=null) { } } - $r = @$db->q($sql3); + $r = @dba::e($sql3); if (!dbm::is_result($r)) { $errors .= print_update_error($db, $sql3); } if ($is_unique) { if ($ignore != "") { - $db->q("SET session old_alter_table=0;"); + dba::e("SET session old_alter_table=0;"); } else { - $r = $db->q("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";"); + $r = dba::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";"); if (!dbm::is_result($r)) { $errors .= print_update_error($db, $sql3); return $errors; } - $r = $db->q("DROP TABLE `".$name."`;"); + $r = dba::e("DROP TABLE `".$name."`;"); if (!dbm::is_result($r)) { $errors .= print_update_error($db, $sql3); return $errors; } - $r = $db->q("RENAME TABLE `".$temp_name."` TO `".$name."`;"); + $r = dba::e("RENAME TABLE `".$temp_name."` TO `".$name."`;"); if (!dbm::is_result($r)) { $errors .= print_update_error($db, $sql3); return $errors; @@ -551,7 +551,7 @@ function db_create_table($name, $fields, $verbose, $action, $indexes=null) { echo $sql.";\n"; if ($action) - $r = @$db->q($sql); + $r = @dba::e($sql); return $r; } diff --git a/mod/directory.php b/mod/directory.php index cb0b1f4cd1..9e004ab5d8 100644 --- a/mod/directory.php +++ b/mod/directory.php @@ -71,7 +71,7 @@ function directory_content(App $a) { $publish = ((get_config('system','publish_all')) ? '' : " AND `publish` = 1 " ); - $r = $db->q("SELECT COUNT(*) AS `total` FROM `profile` + $r = q("SELECT COUNT(*) AS `total` FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 $sql_extra "); if (dbm::is_result($r)) @@ -81,11 +81,11 @@ function directory_content(App $a) { $limit = intval($a->pager['start']).",".intval($a->pager['itemspage']); - $r = $db->q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`, + $r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`, `contact`.`addr`, `contact`.`url` AS profile_url FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid` - WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 AND `contact`.`self` $sql_extra $order LIMIT ".$limit); + WHERE `is-default` $publish AND `user`.`blocked` = 0 AND `contact`.`self` $sql_extra $order LIMIT ".$limit); if (dbm::is_result($r)) { if (in_array('small', $a->argv)) {