]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Cleanup of the encodings table and lookup
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 2 Apr 2020 15:09:51 +0000 (04:09 +1300)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 2 Apr 2020 15:09:51 +0000 (04:09 +1300)
psycopg3/connection.py
psycopg3/pq/encodings.py
tests/test_connection.py

index 23b4f1a50810fe389b91e118f01d4c7f95adb951..ec282b6b0d72bd9ef3ce2520d059612f452b978d 100644 (file)
@@ -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:
index 2a81addffd15774c1fb723ddcd2582bc655f2087..540b35528cebf9cf85a5f5bcedb83d021097f87e 100644 (file)
@@ -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",
index c1c4ca6c92f20c48ddbd7a5c72ed10cf05d0b025..6c963f0d06093601a53b20ee3b3af997c2885c36 100644 (file)
@@ -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"