-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
PgSqlDriver.php
228 lines (184 loc) 路 6.67 KB
/
PgSqlDriver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Database\Drivers;
use Nette;
/**
* Supplemental PostgreSQL database driver.
*/
class PgSqlDriver extends PdoDriver
{
public function detectExceptionClass(\PDOException $e): ?string
{
$code = $e->errorInfo[0] ?? null;
if ($code === '0A000' && str_contains($e->getMessage(), 'truncate')) {
return Nette\Database\ForeignKeyConstraintViolationException::class;
} elseif ($code === '23502') {
return Nette\Database\NotNullConstraintViolationException::class;
} elseif ($code === '23503') {
return Nette\Database\ForeignKeyConstraintViolationException::class;
} elseif ($code === '23505') {
return Nette\Database\UniqueConstraintViolationException::class;
} elseif ($code === '08006') {
return Nette\Database\ConnectionException::class;
} else {
return null;
}
}
/********************* SQL ****************d*g**/
public function delimite(string $name): string
{
// @see http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
return '"' . str_replace('"', '""', $name) . '"';
}
public function formatDateTime(\DateTimeInterface $value): string
{
return $value->format("'Y-m-d H:i:s'");
}
public function formatDateInterval(\DateInterval $value): string
{
throw new Nette\NotSupportedException;
}
public function formatLike(string $value, int $pos): string
{
$bs = substr($this->pdo->quote('\\'), 1, -1); // standard_conforming_strings = on/off
$value = substr($this->pdo->quote($value), 1, -1);
$value = strtr($value, ['%' => $bs . '%', '_' => $bs . '_', '\\' => '\\\\']);
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
}
public function applyLimit(string &$sql, ?int $limit, ?int $offset): void
{
if ($limit < 0 || $offset < 0) {
throw new Nette\InvalidArgumentException('Negative offset or limit.');
}
if ($limit !== null) {
$sql .= ' LIMIT ' . $limit;
}
if ($offset) {
$sql .= ' OFFSET ' . $offset;
}
}
/********************* reflection ****************d*g**/
public function getTables(): array
{
return $this->pdo->query(<<<'X'
SELECT DISTINCT ON (c.relname)
c.relname::varchar AS name,
c.relkind IN ('v', 'm') AS view,
n.nspname::varchar || '.' || c.relname::varchar AS "fullName"
FROM
pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
WHERE
c.relkind IN ('r', 'v', 'm', 'p')
AND n.nspname = ANY (pg_catalog.current_schemas(FALSE))
ORDER BY
c.relname
X)->fetchAll(\PDO::FETCH_ASSOC);
}
public function getColumns(string $table): array
{
$columns = [];
foreach ($this->pdo->query(<<<X
SELECT
a.attname::varchar AS name,
c.relname::varchar AS table,
t.typname AS nativetype,
CASE WHEN a.atttypmod = -1 THEN NULL ELSE a.atttypmod -4 END AS size,
NOT (a.attnotnull OR t.typtype = 'd' AND t.typnotnull) AS nullable,
pg_catalog.pg_get_expr(ad.adbin, 'pg_catalog.pg_attrdef'::regclass)::varchar AS default,
coalesce(co.contype = 'p' AND (seq.relname IS NOT NULL OR strpos(pg_catalog.pg_get_expr(ad.adbin, ad.adrelid), 'nextval') = 1), FALSE) AS autoincrement,
coalesce(co.contype = 'p', FALSE) AS primary,
coalesce(seq.relname, substring(pg_catalog.pg_get_expr(ad.adbin, 'pg_catalog.pg_attrdef'::regclass) from 'nextval[(]''"?([^''"]+)')) AS sequence
FROM
pg_catalog.pg_attribute AS a
JOIN pg_catalog.pg_class AS c ON a.attrelid = c.oid
JOIN pg_catalog.pg_type AS t ON a.atttypid = t.oid
LEFT JOIN pg_catalog.pg_depend AS d ON d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.deptype = 'i'
LEFT JOIN pg_catalog.pg_class AS seq ON seq.oid = d.objid AND seq.relkind = 'S'
LEFT JOIN pg_catalog.pg_attrdef AS ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum
LEFT JOIN pg_catalog.pg_constraint AS co ON co.connamespace = c.relnamespace AND contype = 'p' AND co.conrelid = c.oid AND a.attnum = ANY(co.conkey)
WHERE
c.relkind IN ('r', 'v', 'm', 'p')
AND c.oid = {$this->pdo->quote($this->delimiteFQN($table))}::regclass
AND a.attnum > 0
AND NOT a.attisdropped
ORDER BY
a.attnum
X, \PDO::FETCH_ASSOC) as $column) {
$column['vendor'] = $column;
unset($column['sequence']);
$columns[] = $column;
}
return $columns;
}
public function getIndexes(string $table): array
{
$indexes = [];
foreach ($this->pdo->query(<<<X
SELECT
c2.relname::varchar AS name,
i.indisunique AS unique,
i.indisprimary AS primary,
a.attname::varchar AS column
FROM
pg_catalog.pg_class AS c1
JOIN pg_catalog.pg_index AS i ON c1.oid = i.indrelid
JOIN pg_catalog.pg_class AS c2 ON i.indexrelid = c2.oid
LEFT JOIN pg_catalog.pg_attribute AS a ON c1.oid = a.attrelid AND a.attnum = ANY(i.indkey)
WHERE
c1.relkind IN ('r', 'p')
AND c1.oid = {$this->pdo->quote($this->delimiteFQN($table))}::regclass
X) as $row) {
$id = $row['name'];
$indexes[$id]['name'] = $id;
$indexes[$id]['unique'] = $row['unique'];
$indexes[$id]['primary'] = $row['primary'];
$indexes[$id]['columns'][] = $row['column'];
}
return array_values($indexes);
}
public function getForeignKeys(string $table): array
{
/* Doesn't work with multi-column foreign keys */
return $this->pdo->query(<<<X
SELECT
co.conname::varchar AS name,
al.attname::varchar AS local,
nf.nspname || '.' || cf.relname::varchar AS table,
af.attname::varchar AS foreign
FROM
pg_catalog.pg_constraint AS co
JOIN pg_catalog.pg_class AS cl ON co.conrelid = cl.oid
JOIN pg_catalog.pg_class AS cf ON co.confrelid = cf.oid
JOIN pg_catalog.pg_namespace AS nf ON nf.oid = cf.relnamespace
JOIN pg_catalog.pg_attribute AS al ON al.attrelid = cl.oid AND al.attnum = co.conkey[1]
JOIN pg_catalog.pg_attribute AS af ON af.attrelid = cf.oid AND af.attnum = co.confkey[1]
WHERE
co.contype = 'f'
AND cl.oid = {$this->pdo->quote($this->delimiteFQN($table))}::regclass
AND nf.nspname = ANY (pg_catalog.current_schemas(FALSE))
X)->fetchAll(\PDO::FETCH_ASSOC);
}
public function getColumnTypes(\PDOStatement $statement): array
{
static $cache;
$item = &$cache[$statement->queryString];
$item ??= Nette\Database\Helpers::detectTypes($statement);
return $item;
}
public function isSupported(string $item): bool
{
return $item === self::SupportSequence || $item === self::SupportSubselect || $item === self::SupportSchema;
}
/**
* Converts: schema.name => "schema"."name"
*/
private function delimiteFQN(string $name): string
{
return implode('.', array_map([$this, 'delimite'], explode('.', $name)));
}
}