1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Brouzie\Sphinxy\Connection; |
4
|
|
|
|
5
|
|
|
use Brouzie\Sphinxy\Exception\ConnectionException; |
6
|
|
|
|
7
|
|
|
class PdoConnection implements ConnectionInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var \PDO |
11
|
|
|
*/ |
12
|
|
|
private $pdo; |
13
|
|
|
|
14
|
|
|
private $dsn; |
15
|
|
|
|
16
|
9 |
|
public function __construct($dsn) |
17
|
|
|
{ |
18
|
9 |
|
$this->dsn = $dsn; |
19
|
9 |
|
} |
20
|
|
|
|
21
|
9 |
|
public function query($query) |
22
|
|
|
{ |
23
|
9 |
|
$this->initialize(); |
24
|
|
|
|
25
|
|
|
try { |
26
|
6 |
|
$stmt = $this->pdo->query($query); |
27
|
6 |
|
} catch (\PDOException $e) { |
28
|
|
|
throw new ConnectionException($e->getMessage(), 0, $e); |
29
|
|
|
} |
30
|
|
|
|
31
|
6 |
|
return $stmt->fetchAll(\PDO::FETCH_ASSOC); |
32
|
|
|
} |
33
|
|
|
|
34
|
3 |
|
public function multiQuery($query, array $resultSetNames = array()) |
35
|
|
|
{ |
36
|
3 |
|
$this->initialize(); |
37
|
|
|
|
38
|
|
|
try { |
39
|
3 |
|
$stmt = $this->pdo->query($query); |
40
|
3 |
|
} catch (\PDOException $e) { |
41
|
|
|
throw new ConnectionException($e->getMessage(), 0, $e); |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
$results = array(); |
45
|
3 |
|
$i = 0; |
46
|
|
|
do { |
47
|
3 |
|
$key = isset($resultSetNames[$i]) ? $resultSetNames[$i] : $i; |
48
|
3 |
|
$results[$key] = $stmt->fetchAll(\PDO::FETCH_ASSOC); |
49
|
3 |
|
++$i; |
50
|
3 |
|
} while ($stmt->nextRowset()); |
51
|
|
|
|
52
|
3 |
|
return $results; |
53
|
|
|
} |
54
|
|
|
|
55
|
3 |
|
public function exec($query) |
56
|
|
|
{ |
57
|
3 |
|
$this->initialize(); |
58
|
|
|
|
59
|
|
|
try { |
60
|
3 |
|
return $this->pdo->exec($query); |
61
|
|
|
} catch (\PDOException $e) { |
62
|
|
|
throw new ConnectionException($e->getMessage(), 0, $e); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function quote($value) |
67
|
|
|
{ |
68
|
|
|
$this->initialize(); |
69
|
|
|
|
70
|
|
|
if (false === $value = $this->pdo->quote((string) $value)) { |
71
|
|
|
throw new ConnectionException($this->pdo->errorInfo(), $this->pdo->errorCode()); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $value; |
75
|
|
|
} |
76
|
|
|
|
77
|
9 |
|
protected function initialize() |
78
|
|
|
{ |
79
|
9 |
|
if (null === $this->pdo) { |
80
|
|
|
try { |
81
|
9 |
|
$this->pdo = new \PDO($this->dsn, null, null, array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION)); |
82
|
9 |
|
} catch (\PDOException $e) { |
83
|
3 |
|
throw new ConnectionException($e->getMessage(), 0, $e); |
84
|
|
|
} |
85
|
6 |
|
} |
86
|
6 |
|
} |
87
|
|
|
|
88
|
|
|
public function checkConnection() |
89
|
|
|
{ |
90
|
|
|
try { |
91
|
|
|
$this->query('SELECT 1'); |
92
|
|
|
} catch (\ConnectionException $e) { |
|
|
|
|
93
|
|
|
$this->pdo = null; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|