1: | <?php
|
2: | namespace Opencart\System\Library\DB;
|
3: | |
4: | |
5: | |
6: | |
7: |
|
8: | class PgSQL {
|
9: | |
10: | |
11: |
|
12: | private $connection;
|
13: |
|
14: | |
15: | |
16: | |
17: | |
18: | |
19: | |
20: | |
21: | |
22: |
|
23: | public function __construct(string $hostname, string $username, string $password, string $database, string $port = '') {
|
24: | if (!$port) {
|
25: | $port = '5432';
|
26: | }
|
27: |
|
28: | try {
|
29: | $pg = @pg_connect('host=' . $hostname . ' port=' . $port . ' user=' . $username . ' password=' . $password . ' dbname=' . $database . ' options=\'--client_encoding=UTF8\' ');
|
30: | } catch (\Exception $e) {
|
31: | throw new \Exception('Error: Could not make a database link using ' . $username . '@' . $hostname);
|
32: | }
|
33: |
|
34: | if ($pg) {
|
35: | $this->connection = $pg;
|
36: | pg_query($this->connection, "SET CLIENT_ENCODING TO 'UTF8'");
|
37: |
|
38: |
|
39: | pg_query($this->connection, "SET TIMEZONE = '" . $this->escape(date('P')) . "'");
|
40: | }
|
41: | }
|
42: |
|
43: | |
44: | |
45: | |
46: | |
47: | |
48: | |
49: |
|
50: | public function query(string $sql): \stdClass {
|
51: | $resource = pg_query($this->connection, $sql);
|
52: |
|
53: | if ($resource === false) {
|
54: | throw new \Exception('Error: ' . pg_last_error($this->connection) . '<br/>' . $sql);
|
55: | }
|
56: |
|
57: | $data = [];
|
58: |
|
59: | while ($result = pg_fetch_assoc($resource)) {
|
60: | $data[] = $result;
|
61: | }
|
62: |
|
63: | pg_free_result($resource);
|
64: |
|
65: | $query = new \stdClass();
|
66: | $query->row = $data[0] ?? [];
|
67: | $query->rows = $data;
|
68: | $query->num_rows = count($data);
|
69: |
|
70: | return $query;
|
71: | }
|
72: |
|
73: | |
74: | |
75: | |
76: | |
77: | |
78: | |
79: |
|
80: | public function escape(string $value): string {
|
81: | return pg_escape_string($this->connection, $value);
|
82: | }
|
83: |
|
84: | |
85: | |
86: | |
87: | |
88: |
|
89: | public function countAffected(): int {
|
90: | return pg_affected_rows($this->connection);
|
91: | }
|
92: |
|
93: | |
94: | |
95: | |
96: | |
97: |
|
98: | public function getLastId(): int {
|
99: | $query = $this->query("SELECT LASTVAL() AS `id`");
|
100: |
|
101: | return $query->row['id'];
|
102: | }
|
103: |
|
104: | |
105: | |
106: | |
107: | |
108: |
|
109: | public function isConnected(): bool {
|
110: | return pg_connection_status($this->connection) == PGSQL_CONNECTION_OK;
|
111: | }
|
112: |
|
113: | |
114: | |
115: | |
116: | |
117: |
|
118: | public function __destruct() {
|
119: | if ($this->connection) {
|
120: | pg_close($this->connection);
|
121: |
|
122: | $this->connection = null;
|
123: | }
|
124: | }
|
125: | }
|
126: | |