|
11 | 11 |
|
12 | 12 | use Nette; |
13 | 13 | use Nette\Database\Connection; |
| 14 | +use Nette\Database\DriverException; |
14 | 15 | use PDO; |
15 | 16 | use PDOException; |
16 | 17 |
|
@@ -48,4 +49,79 @@ public function getPdo(): ?PDO |
48 | 49 | { |
49 | 50 | return $this->pdo; |
50 | 51 | } |
| 52 | + |
| 53 | + |
| 54 | + public function query(string $queryString, array $params) |
| 55 | + { |
| 56 | + try { |
| 57 | + static $types = ['boolean' => PDO::PARAM_BOOL, 'integer' => PDO::PARAM_INT, |
| 58 | + 'resource' => PDO::PARAM_LOB, 'NULL' => PDO::PARAM_NULL, ]; |
| 59 | + |
| 60 | + $statement = $this->pdo->prepare($queryString); |
| 61 | + foreach ($params as $key => $value) { |
| 62 | + $type = gettype($value); |
| 63 | + $statement->bindValue(is_int($key) ? $key + 1 : $key, $value, $types[$type] ?? PDO::PARAM_STR); |
| 64 | + } |
| 65 | + $statement->setFetchMode(PDO::FETCH_ASSOC); |
| 66 | + @$statement->execute(); // @ PHP generates warning when ATTR_ERRMODE = ERRMODE_EXCEPTION bug #73878 |
| 67 | + return $statement; |
| 68 | + |
| 69 | + } catch (PDOException $e) { |
| 70 | + $e = $this->convertException($e); |
| 71 | + $e->queryString = $queryString; |
| 72 | + $e->params = $params; |
| 73 | + throw $e; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | + public function beginTransaction(): void |
| 79 | + { |
| 80 | + try { |
| 81 | + $this->pdo->beginTransaction(); |
| 82 | + } catch (PDOException $e) { |
| 83 | + throw $this->convertException($e); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + |
| 88 | + public function commit(): void |
| 89 | + { |
| 90 | + try { |
| 91 | + $this->pdo->commit(); |
| 92 | + } catch (PDOException $e) { |
| 93 | + throw $this->convertException($e); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | + public function rollBack(): void |
| 99 | + { |
| 100 | + try { |
| 101 | + $this->pdo->rollBack(); |
| 102 | + } catch (PDOException $e) { |
| 103 | + throw $this->convertException($e); |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + |
| 108 | + public function getInsertId(string $sequence = null): string |
| 109 | + { |
| 110 | + try { |
| 111 | + $res = $this->pdo->lastInsertId($sequence); |
| 112 | + return $res === false ? '0' : $res; |
| 113 | + } catch (PDOException $e) { |
| 114 | + throw $this->convertException($e); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + |
| 119 | + public function quote(string $string, int $type = PDO::PARAM_STR): string |
| 120 | + { |
| 121 | + try { |
| 122 | + return $this->pdo->quote($string, $type); |
| 123 | + } catch (PDOException $e) { |
| 124 | + throw DriverException::from($e); |
| 125 | + } |
| 126 | + } |
51 | 127 | } |
0 commit comments