FOSSology  4.4.0
Open Source License Compliance by Open Source Software
SolidDbManager.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2014 Siemens AG
4  Authors: Steffen Weber, Andreas Würl
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
8 
9 namespace Fossology\Lib\Db;
10 
11 use Monolog\Logger;
12 
14 {
15  function __construct(Logger $logger)
16  {
17  parent::__construct($logger);
18  }
19 
25  public function prepare($statementName, $sqlStatement)
26  {
27  if (array_key_exists($statementName, $this->preparedStatements)) {
28  if ($this->preparedStatements[$statementName] !== $sqlStatement) {
29  throw new \Exception("Existing Statement mismatch: $statementName");
30  }
31  return;
32  }
33  $this->cumulatedTime[$statementName] = 0;
34  $this->queryCount[$statementName] = 0;
35  $this->preparedStatements[$statementName] = $sqlStatement;
36  }
37 
44  public function execute($statementName, $params = array())
45  {
46  if (! array_key_exists($statementName, $this->preparedStatements)) {
47  throw new \Exception("Unknown Statement");
48  }
49  $startTime = microtime(true);
50  $statement = $this->evaluateStatement($statementName, $params);
51  $res = $this->dbDriver->query($statement);
52  $execTime = microtime(true) - $startTime;
53  $this->collectStatistics($statementName, $execTime);
54  $this->logger->debug("execution of '$statementName' took " . $this->formatMilliseconds($execTime));
55  $this->checkResult($res, "$statementName :: $statement");
56  return $res;
57  }
58 
65  private function evaluateStatement($statementName, $params)
66  {
67  $sql = $this->preparedStatements[$statementName];
68  $cnt = 0;
69  foreach ($params as $var) {
70  $cnt++;
71  if ($var === null) {
72  throw new \Exception('given argument for $' . $cnt . ' is null');
73  }
74  if (is_bool($var)) {
75  $masked = $this->dbDriver->booleanToDb($var);
76  } else if (is_numeric($var)) {
77  $masked = $var;
78  } else {
79  $masked = "'". $this->dbDriver->escapeString($var)."'";
80  }
81  $sqlRep = preg_replace('/(\$'.$cnt.')([^\d]|$)/', "$masked$2", $sql);
82  if ($sqlRep == $sql) {
83  throw new \Exception('$' . $cnt . ' not found in prepared statement');
84  }
85  $sql = $sqlRep;
86  }
87  if (preg_match('/(\$[\d]+)([^\d]|$)/', $sql, $match)) {
88  $this->logger->debug($match[1]." in '$statementName not resolved");
89  }
90  return $sql;
91  }
92 }
checkResult($result, $sqlStatement="")
Check the result for unexpected errors. If found, treat them as fatal.
Definition: DbManager.php:116
collectStatistics($statementName, $execTime)
Definition: DbManager.php:274
evaluateStatement($statementName, $params)
execute($statementName, $params=array())
prepare($statementName, $sqlStatement)