From: Daniele Varrazzo Date: Thu, 2 Apr 2020 15:09:51 +0000 (+1300) Subject: Cleanup of the encodings table and lookup X-Git-Tag: 3.0.dev0~623 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=4f40a2388090ffa355b3145403d3d05db460fc28;p=thirdparty%2Fpsycopg.git Cleanup of the encodings table and lookup --- diff --git a/psycopg3/connection.py b/psycopg3/connection.py index 23b4f1a50..ec282b6b0 100644 --- a/psycopg3/connection.py +++ b/psycopg3/connection.py @@ -41,7 +41,7 @@ class BaseConnection: self.adapters: AdaptersMap = {} self.casters: TypecastersMap = {} # name of the postgres encoding (in bytes) - self.pgenc = b"" + self._pgenc = b"" def cursor( self, name: Optional[str] = None, binary: bool = False @@ -54,11 +54,15 @@ class BaseConnection: def codec(self) -> codecs.CodecInfo: # TODO: utf8 fastpath? pgenc = self.pgconn.parameter_status(b"client_encoding") - if self.pgenc != pgenc: - # for unknown encodings and SQL_ASCII be strict and use ascii - pyenc = pq.py_codecs.get(pgenc.decode("ascii")) or "ascii" + if self._pgenc != pgenc: + try: + pyenc = pq.py_codecs[pgenc.decode("ascii")] + except KeyError: + raise e.NotSupportedError( + f"encoding {pgenc.decode('ascii')} not available in Python" + ) self._codec = codecs.lookup(pyenc) - self.pgenc = pgenc + self._pgenc = pgenc return self._codec def encode(self, s: str) -> bytes: diff --git a/psycopg3/pq/encodings.py b/psycopg3/pq/encodings.py index 2a81addff..540b35528 100644 --- a/psycopg3/pq/encodings.py +++ b/psycopg3/pq/encodings.py @@ -33,7 +33,9 @@ py_codecs = { # "MULE_INTERNAL": not available in Python "SHIFT_JIS_2004": "shift_jis_2004", "SJIS": "shift_jis", - "SQL_ASCII": None, # means no encoding, see PostgreSQL docs + # this actually means no encoding, see PostgreSQL docs + # it is special-cased by the text typecaster. + "SQL_ASCII": "ascii", "UHC": "cp949", "UTF8": "utf-8", "WIN1250": "cp1250", diff --git a/tests/test_connection.py b/tests/test_connection.py index c1c4ca6c9..6c963f0d0 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -52,6 +52,12 @@ def test_set_encoding(conn): assert enc == newenc +def test_set_encoding_unsupported(conn): + conn.encoding = "EUC_TW" + with pytest.raises(psycopg3.NotSupportedError): + conn.cursor().execute("select 1") + + def test_set_encoding_bad(conn): with pytest.raises(psycopg3.DatabaseError): conn.encoding = "WAT"