Repository navigation
Expand file tree
/
Copy pathpg_driver_dialect.py
More file actions
373 lines (322 loc) · 18.3 KB
/
Copy pathpg_driver_dialect.py
File metadata and controls
373 lines (322 loc) · 18.3 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import re
import socket
import string
from typing import (TYPE_CHECKING, Any, Callable, ClassVar, FrozenSet, Mapping,
Optional, Sequence, Set, Tuple, cast)
import psycopg
from psycopg import rows
from psycopg import sql as psycopg_sql
if TYPE_CHECKING:
from re import Pattern
from aws_advanced_python_wrapper.hostinfo import HostInfo
from aws_advanced_python_wrapper.pep249 import Connection, Cursor
from contextlib import closing
from inspect import signature
from aws_advanced_python_wrapper.driver_dialect import DriverDialect
from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes
from aws_advanced_python_wrapper.encryption_driver_dialect import \
EncryptionDriverDialect
from aws_advanced_python_wrapper.errors import UnsupportedOperationError
from aws_advanced_python_wrapper.pep249_methods import DbApiMethod
from aws_advanced_python_wrapper.utils.log import Logger
from aws_advanced_python_wrapper.utils.messages import Messages
from aws_advanced_python_wrapper.utils.properties import (Properties,
PropertiesUtils,
WrapperProperties)
logger = Logger(__name__)
_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
class PgDriverDialect(DriverDialect, EncryptionDriverDialect):
_driver_name: str = "Psycopg"
TARGET_DRIVER_CODE: str = "psycopg"
# https://www.psycopg.org/psycopg3/docs/api/pq.html#psycopg.pq.TransactionStatus
PSYCOPG_IDLE_TRANSACTION_STATUS = 0
# metadata_key keeps the base's exact match: catalog names are case-sensitive, so "Users" and users are two tables.
# An unqualified operator resolves through search_path, where a user-defined "=" with a closer type match would
# win. Pin the built-in.
equals_operator: ClassVar[str] = "OPERATOR(pg_catalog.=)"
greater_than_operator: ClassVar[str] = "OPERATOR(pg_catalog.>)"
# The key management utility compares the primary key with the built-in operators, so it needs a built-in type,
# or a domain over one.
key_column_type_sql: ClassVar[Optional[str]] = (
"SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) AS type_name, "
"(CASE WHEN t.typtype OPERATOR(pg_catalog.=) 'd' THEN bt.typnamespace ELSE t.typnamespace END) "
"OPERATOR(pg_catalog.=) 'pg_catalog'::pg_catalog.regnamespace::pg_catalog.oid AS built_in "
"FROM pg_catalog.pg_attribute a "
"JOIN pg_catalog.pg_type t ON t.oid OPERATOR(pg_catalog.=) a.atttypid "
"LEFT JOIN pg_catalog.pg_type bt ON bt.oid OPERATOR(pg_catalog.=) t.typbasetype "
"WHERE a.attrelid OPERATOR(pg_catalog.=) pg_catalog.to_regclass(%s::pg_catalog.text)::pg_catalog.oid "
"AND a.attname OPERATOR(pg_catalog.=) %s::pg_catalog.name AND NOT a.attisdropped")
schema_table_sql: ClassVar[str] = (
"SELECT 1 AS found FROM information_schema.tables "
"WHERE pg_catalog.lower(table_schema) OPERATOR(pg_catalog.=) %s::pg_catalog.text "
"AND pg_catalog.lower(table_name) OPERATOR(pg_catalog.=) %s::pg_catalog.text")
schema_columns_sql: ClassVar[str] = (
"SELECT column_name FROM information_schema.columns "
"WHERE pg_catalog.lower(table_schema) OPERATOR(pg_catalog.=) %s::pg_catalog.text "
"AND pg_catalog.lower(table_name) OPERATOR(pg_catalog.=) %s::pg_catalog.text")
# pg_catalog, not information_schema: its constraint views hide the tables a SELECT-only role can read.
schema_key_constraints_sql: ClassVar[str] = (
"SELECT c.conname AS constraint_name, "
"CASE WHEN c.contype OPERATOR(pg_catalog.=) 'p'::pg_catalog.\"char\" THEN 'PRIMARY KEY' ELSE 'UNIQUE' END "
"AS constraint_type, a.attname AS column_name "
"FROM pg_catalog.pg_constraint c "
"JOIN pg_catalog.pg_class t ON t.oid OPERATOR(pg_catalog.=) c.conrelid "
"JOIN pg_catalog.pg_namespace n ON n.oid OPERATOR(pg_catalog.=) t.relnamespace "
"CROSS JOIN LATERAL pg_catalog.unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord) "
"JOIN pg_catalog.pg_attribute a ON a.attrelid OPERATOR(pg_catalog.=) t.oid "
"AND a.attnum OPERATOR(pg_catalog.=) k.attnum "
"WHERE (c.contype OPERATOR(pg_catalog.=) 'p'::pg_catalog.\"char\" "
"OR c.contype OPERATOR(pg_catalog.=) 'u'::pg_catalog.\"char\") "
"AND pg_catalog.lower(n.nspname) OPERATOR(pg_catalog.=) %s::pg_catalog.text "
"AND pg_catalog.lower(t.relname) OPERATOR(pg_catalog.=) %s::pg_catalog.text "
"ORDER BY c.conname, k.ord")
# ROWS FROM zips the two key arrays: the two-argument unnest shorthand works only unqualified.
schema_foreign_keys_sql: ClassVar[str] = (
"SELECT a.attname AS column_name, rt.relname AS referenced_table, ra.attname AS referenced_column "
"FROM pg_catalog.pg_constraint c "
"JOIN pg_catalog.pg_class t ON t.oid OPERATOR(pg_catalog.=) c.conrelid "
"JOIN pg_catalog.pg_namespace n ON n.oid OPERATOR(pg_catalog.=) t.relnamespace "
"JOIN pg_catalog.pg_class rt ON rt.oid OPERATOR(pg_catalog.=) c.confrelid "
"CROSS JOIN LATERAL ROWS FROM (pg_catalog.unnest(c.conkey), pg_catalog.unnest(c.confkey)) AS k(attnum, refnum) "
"JOIN pg_catalog.pg_attribute a ON a.attrelid OPERATOR(pg_catalog.=) t.oid "
"AND a.attnum OPERATOR(pg_catalog.=) k.attnum "
"JOIN pg_catalog.pg_attribute ra ON ra.attrelid OPERATOR(pg_catalog.=) rt.oid "
"AND ra.attnum OPERATOR(pg_catalog.=) k.refnum "
"WHERE c.contype OPERATOR(pg_catalog.=) 'f'::pg_catalog.\"char\" "
"AND rt.relnamespace OPERATOR(pg_catalog.=) t.relnamespace "
"AND pg_catalog.lower(n.nspname) OPERATOR(pg_catalog.=) %s::pg_catalog.text "
"AND pg_catalog.lower(t.relname) OPERATOR(pg_catalog.=) %s::pg_catalog.text")
analyzed_statements: ClassVar[FrozenSet[str]] = frozenset(
{"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "COPY", "VALUES", "PREPARE"})
sqlglot_dialect: ClassVar[str] = "postgres"
upsert_row_alias: ClassVar[Optional[str]] = "excluded"
sql_token_pattern: ClassVar[Optional[Pattern[str]]] = re.compile(r"""
(?P<line_comment>--[^\n]*)
| (?P<block_comment>/\*)
| (?P<estring>[Ee]'(?:[^'\\]|\\.|'')*(?P<estring_end>'?))
| (?P<string>'(?:[^']|'')*(?P<string_end>'?))
| (?P<ident>"(?:[^"]|"")*(?P<ident_end>"?))
| (?P<param>\$\d+)
| (?P<dollar>\$(?:[^\W\d]\w*)?\$)
| (?P<word>[^\W\d][\w$]*)
| (?P<number>\d[\w.]*)
| (?P<semicolon>;)
| (?P<space>\s+)
| (?P<other>[^\w\s'"$;/\-]+|.)
""", re.VERBOSE | re.DOTALL)
nested_block_comments: ClassVar[bool] = True
strict_placeholders: ClassVar[bool] = True
_dialect_code: str = DriverDialectCodes.PSYCOPG
_network_bound_methods: Set[str] = {
DbApiMethod.CONNECTION_COMMIT.method_name,
DbApiMethod.CONNECTION_AUTOCOMMIT.method_name,
DbApiMethod.CONNECTION_AUTOCOMMIT_SETTER.method_name,
DbApiMethod.CONNECTION_IS_READ_ONLY.method_name,
DbApiMethod.CONNECTION_SET_READ_ONLY.method_name,
DbApiMethod.CONNECTION_ROLLBACK.method_name,
DbApiMethod.CONNECTION_CLOSE.method_name,
DbApiMethod.CONNECTION_CURSOR.method_name,
DbApiMethod.CURSOR_CLOSE.method_name,
DbApiMethod.CURSOR_CALLPROC.method_name,
DbApiMethod.CURSOR_EXECUTE.method_name,
DbApiMethod.CURSOR_FETCHONE.method_name,
DbApiMethod.CURSOR_NEXT.method_name,
DbApiMethod.CURSOR_FETCHMANY.method_name,
DbApiMethod.CURSOR_FETCHALL.method_name
}
def is_dialect(self, connect_func: Callable) -> bool:
if PgDriverDialect.TARGET_DRIVER_CODE not in str(signature(connect_func)):
return PgDriverDialect.TARGET_DRIVER_CODE.lower() in (connect_func.__module__ + connect_func.__qualname__).lower()
return True
def is_closed(self, conn: Connection) -> bool:
if isinstance(conn, psycopg.Connection):
return conn.closed
raise UnsupportedOperationError(
Messages.get_formatted("DriverDialect.UnsupportedOperationError", self._driver_name, "closed"))
def abort_connection(self, conn: Connection):
if isinstance(conn, psycopg.Connection):
# abort_connection is invoked from the host-monitoring (EFM) monitor
# thread to interrupt an in-flight operation when the host becomes
# unreachable, so the owning thread's blocked recv returns promptly.
#
# It must NOT call close(): psycopg close() is PQfinish, which frees
# the libpq connection struct and tears down the SSL session
# (SSL_free) with no lock. Freeing that struct while the owning thread
# is mid-SSL-op on the same connection races a use-after-free in
# libpq/OpenSSL and crashes the whole process with SIGSEGV.
#
# cancel()/cancel_safe() avoids the crash but cannot interrupt a query
# when the host is unreachable (the CancelRequest can't be delivered),
# which defeats the EFM's purpose on exactly the network-failure case
# it exists for.
#
# Shutting the underlying socket down unblocks the owning thread's recv
# immediately (even on a dead host) WITHOUT freeing any struct, so
# there is no SSL_free to race. The owning thread observes the broken
# connection and closes it on its own thread (the only safe place for
# PQfinish).
if conn.closed:
return
try:
fd = conn.fileno()
except Exception:
return
if fd is None or fd < 0:
return
try:
sock = socket.socket(fileno=fd)
except OSError as e:
logger.debug("PgDriverDialect.AbortConnectionShutdownFailed", e)
return
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError as e:
logger.debug("PgDriverDialect.AbortConnectionShutdownFailed", e)
finally:
# release the fd WITHOUT closing it; the connection still owns it
# and will PQfinish on its owning thread.
sock.detach()
return
raise UnsupportedOperationError(
Messages.get_formatted("DriverDialect.UnsupportedOperationError", self._driver_name, "abort_connection"))
def is_in_transaction(self, conn: Connection) -> bool:
if isinstance(conn, psycopg.Connection):
status: int = conn.info.transaction_status
return status != self.PSYCOPG_IDLE_TRANSACTION_STATUS
raise UnsupportedOperationError(Messages.get_formatted(
"DriverDialect.UnsupportedOperationError",
self._driver_name,
"transaction_status"))
def is_read_only(self, conn: Connection) -> bool:
if isinstance(conn, psycopg.Connection):
if conn.read_only is None:
return False
return conn.read_only
raise UnsupportedOperationError(
Messages.get_formatted("DriverDialect.UnsupportedOperationError", self._driver_name, "read_only"))
def set_read_only(self, conn: Connection, read_only: bool):
if isinstance(conn, psycopg.Connection):
conn.read_only = read_only
return
raise UnsupportedOperationError(
Messages.get_formatted("DriverDialect.UnsupportedOperationError", self._driver_name, "read_only"))
def get_autocommit(self, conn: Connection) -> bool:
if isinstance(conn, psycopg.Connection):
return conn.autocommit
raise UnsupportedOperationError(
Messages.get_formatted("DriverDialect.UnsupportedOperationError", self._driver_name, "autocommit"))
def set_autocommit(self, conn: Connection, autocommit: bool):
if isinstance(conn, psycopg.Connection):
conn.autocommit = autocommit
return
raise UnsupportedOperationError(
Messages.get_formatted("DriverDialect.UnsupportedOperationError", self._driver_name, "autocommit"))
def transfer_session_state(self, from_conn: Connection, to_conn: Connection):
if isinstance(from_conn, psycopg.Connection) and isinstance(to_conn, psycopg.Connection):
to_conn.read_only = from_conn.read_only
to_conn.autocommit = from_conn.autocommit
to_conn.isolation_level = from_conn.isolation_level
def get_connection_from_obj(self, obj: object) -> Any:
if isinstance(obj, psycopg.Connection):
return obj
if isinstance(obj, psycopg.Cursor):
return obj.connection
@classmethod
def fold_identifier(cls, name: str, quoted: bool) -> str:
# PostgreSQL folds an unquoted identifier to lower case, ASCII letters only in a multibyte (e.g. UTF-8)
# database; a quoted one keeps its case. The result is the name in the system catalog, apart from PostgreSQL's
# truncation of names longer than 63 bytes.
return name if quoted else name.translate(_ASCII_LOWER)
def upsert_clause(
self, conflict_columns: Sequence[str], update_columns: Sequence[str], extra_assignments: Sequence[str] = ()) -> str:
assignments = ", ".join([f"{c} = EXCLUDED.{c}" for c in update_columns] + list(extra_assignments))
return f"ON CONFLICT ({', '.join(conflict_columns)}) DO UPDATE SET {assignments}"
def insert_returning_id(self, conn: Connection, sql: str, params: Sequence[Any]) -> int:
"""
Runs an ``INSERT`` written without ``RETURNING`` and returns the generated ``id``.
Each cursor call runs through :meth:`execute`, so the ``socket_timeout`` of this dialect's properties applies, and
a timeout raises ``QueryTimeoutError``.
:param conn: the connection to run the statement on.
:param sql: the ``INSERT`` statement.
:param params: the statement's parameters.
:return: the generated ``id``.
"""
returning_sql = f"{sql} RETURNING id"
with closing(conn.cursor()) as cursor:
self.execute(
DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(returning_sql, params), returning_sql, conn=conn)
row = cast("Any", self.execute(DbApiMethod.CURSOR_FETCHONE.method_name, lambda: cursor.fetchone(), conn=conn))
# A connection opened with a dict-like row factory returns a mapping.
if isinstance(row, Mapping):
return int(next(iter(row.values())))
return int(row[0])
def analyzable_sql(self, sql: Any, cursor: Cursor) -> Tuple[Optional[str], Optional[str]]:
"""
Returns the text the encryption plugin analyzes for ``sql``, and the codec of the connection's client encoding
when ``sql`` is ``bytes``.
A psycopg ``Composable`` is analyzed as text and sent as the object.
``bytes`` SQL is analyzed as text in the connection's client encoding when that encoding reads each ASCII byte
as itself and the text encodes back to the same bytes.
psycopg raises ``NotSupportedError`` for an encoding Python has no codec for.
:param sql: the SQL the application passed to the cursor.
:param cursor: the driver cursor the SQL runs on.
:return: the text to analyze, or None when the SQL runs unanalyzed, and the codec ``bytes`` SQL was decoded
with, or None.
"""
if isinstance(sql, psycopg_sql.Composable):
return sql.as_string(cast("Any", cursor)), None
if isinstance(sql, bytes):
conn = self.get_connection_from_obj(cursor)
codec = None if conn is None else conn.info.encoding
return self._decode_sql(sql, codec), codec
return super().analyzable_sql(sql, cursor)
def unsupported_row_factory(self, cursor: Cursor) -> Optional[Any]:
if isinstance(cursor, psycopg.Cursor) and \
cursor.row_factory not in (rows.tuple_row, rows.dict_row, rows.namedtuple_row):
return cursor.row_factory
return None
def prepare_connect_info(self, host_info: HostInfo, original_props: Properties) -> Properties:
driver_props: Properties = Properties(original_props.copy())
PropertiesUtils.remove_wrapper_props(driver_props)
driver_props["host"] = host_info.host
if host_info.is_port_specified():
driver_props["port"] = str(host_info.port)
db = WrapperProperties.DATABASE.get(original_props)
if db is not None:
driver_props["dbname"] = db
connect_timeout = WrapperProperties.CONNECT_TIMEOUT_SEC.get(original_props)
if connect_timeout is not None:
driver_props["connect_timeout"] = connect_timeout
keepalive = WrapperProperties.TCP_KEEPALIVE.get(original_props)
if keepalive is not None:
driver_props["keepalives"] = keepalive
keepalive_time = WrapperProperties.TCP_KEEPALIVE_TIME_SEC.get(original_props)
if keepalive_time is not None:
driver_props["keepalives_idle"] = keepalive_time
keepalive_interval = WrapperProperties.TCP_KEEPALIVE_INTERVAL_SEC.get(original_props)
if keepalive_interval is not None:
driver_props["keepalives_interval"] = keepalive_interval
keepalive_probes = WrapperProperties.TCP_KEEPALIVE_PROBES.get(original_props)
if keepalive_probes is not None:
driver_props["keepalives_count"] = keepalive_probes
return driver_props
def supports_connect_timeout(self) -> bool:
return True
def supports_tcp_keepalive(self) -> bool:
return True
def supports_abort_connection(self) -> bool:
return True