]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Use uppercase SQL throughout code and docs
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 23 Jul 2021 15:47:10 +0000 (17:47 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 23 Jul 2021 15:56:20 +0000 (17:56 +0200)
I personally prefer lowercase, but uppercase is more familiar. There is
also a tiny advantage in greppability, in case someone tries to trace a
generated statement in the code.

The myth that using UPPERCASE the database will sense your urgency and
will run your queries faster has been dispelled.

18 files changed:
docs/advanced/adapt.rst
docs/advanced/async.rst
docs/advanced/cursors.rst
docs/advanced/rows.rst
docs/api/sql.rst
docs/api/types.rst
docs/basic/adapt.rst
docs/basic/from_pg2.rst
docs/basic/usage.rst
psycopg/psycopg/_typeinfo.py
psycopg/psycopg/connection.py
psycopg/psycopg/pool/async_pool.py
psycopg/psycopg/pool/pool.py
psycopg/psycopg/server_cursor.py
psycopg/psycopg/sql.py
psycopg/psycopg/transaction.py
tests/test_transaction.py
tests/test_transaction_async.py

index abb7094cc0de07576f4ebb6eaf01c53178c9a1f0..48fa518c844b26b7db92b44141621a6dcca671bd 100644 (file)
@@ -76,12 +76,12 @@ compatible.
 
     conn = psycopg.connect()
 
-    conn.execute("select 123.45").fetchone()[0]
+    conn.execute("SELECT 123.45").fetchone()[0]
     # Decimal('123.45')
 
     conn.adapters.register_loader("numeric", psycopg.types.numeric.FloatLoader)
 
-    conn.execute("select 123.45").fetchone()[0]
+    conn.execute("SELECT 123.45").fetchone()[0]
     # 123.45
 
 In this example the customised adaptation takes effect only on the connection
@@ -133,7 +133,7 @@ cursor):
 
     cur.execute("SELECT %s::text, %s::text", [date(2020, 12, 31), date.max]).fetchone()
     # ('2020-12-31', 'infinity')
-    cur.execute("select '2020-12-31'::date, 'infinity'::date").fetchone()
+    cur.execute("SELECT '2020-12-31'::date, 'infinity'::date").fetchone()
     # (datetime.date(2020, 12, 31), datetime.date(9999, 12, 31))
 
 
index c2ce6a84fafd36e6efba512ed95a37beef45483f..492584fcaa8259f1e09ed0e7caae6856ee18c2b0 100644 (file)
@@ -161,7 +161,7 @@ received immediately, but only during a connection operation, such as a query.
     # =# notify mychan, 'hey';
     # NOTIFY
 
-    print(conn.cursor().execute("select 1").fetchone())
+    print(conn.cursor().execute("SELECT 1").fetchone())
     # got this: Notify(channel='mychan', payload='hey', pid=961823)
     # (1,)
 
@@ -204,7 +204,7 @@ something else to do too.
 
         # Activity detected. Is the connection still ok?
         try:
-            conn.execute("select 1")
+            conn.execute("SELECT 1")
         except psycopg.OperationalError:
             # You were disconnected: do something useful such as panicking
             logger.error("we lost our database!")
@@ -229,7 +229,7 @@ something similar using `~asyncio.loop.add_reader`:
 
         # Activity detected. Is the connection still ok?
         try:
-            await conn.execute("select 1")
+            await conn.execute("SELECT 1")
         except psycopg.OperationalError:
             # Guess what happened
             ...
index 80b914a9b72786e2288c957864558a2094811837..9d9c18352ab452b0edfebef13d3ffaf5129b9855 100644 (file)
@@ -107,7 +107,7 @@ and create the server cursor:
 
 .. code:: python
 
-    conn.execute("select reffunc('curname')")
+    conn.execute("SELECT reffunc('curname')")
 
 then create a server-side cursor with the same name and call directly the
 fetch methods, omitting to call `~ServerCursor.execute()` before:
index 6790f6d1a6d6c86253fc0cb65a66dbfee6996bc5..2d05e0257df8446c8f2d1aa18049d477a4dffc73 100644 (file)
@@ -170,12 +170,12 @@ any issue. Pydantic will also raise a runtime error in case the
         cur = conn.cursor(row_factory=PersonFactory)
         cur.execute(
             """
-            select id, first_name, last_name, dob
-            from (values
+            SELECT id, first_name, last_name, dob
+            FROM (VALUES
                 (1, 'John', 'Doe', '2000-01-01'::date),
                 (2, 'Jane', 'White', NULL)
-            ) as data (id, first_name, last_name, dob)
-            where id = %(id)s;
+            ) AS data (id, first_name, last_name, dob)
+            WHERE id = %(id)s;
             """,
             {"id": id},
         )
index 122c2c1ff081783f59adb2508b3021b0731b4369..cb1ba20439f0f4a69a966fd6c468b544803189d8 100644 (file)
@@ -13,7 +13,7 @@ arguments::
 
     # This will not work
     table_name = 'my_table'
-    cur.execute("insert into %s values (%s, %s)", [table_name, 10, 20])
+    cur.execute("INSERT INTO %s VALUES (%s, %s)", [table_name, 10, 20])
 
 The SQL query should be composed before the arguments are merged, for
 instance::
@@ -21,7 +21,7 @@ instance::
     # This works, but it is not optimal
     table_name = 'my_table'
     cur.execute(
-        "insert into %s values (%%s, %%s)" % table_name,
+        "INSERT INTO %s VALUES (%%s, %%s)" % table_name,
         [10, 20])
 
 This sort of works, but it is an accident waiting to happen: the table name
@@ -34,7 +34,7 @@ name should be escaped using `~psycopg.pq.Escaping.escape_identifier()`::
     # This works, but it is not optimal
     table_name = 'my_table'
     cur.execute(
-        "insert into %s values (%%s, %%s)" % Escaping.escape_identifier(table_name),
+        "INSERT INTO %s VALUES (%%s, %%s)" % Escaping.escape_identifier(table_name),
         [10, 20])
 
 This is now safe, but it somewhat ad-hoc. In case, for some reason, it is
@@ -52,7 +52,7 @@ from the query parameters::
     from psycopg import sql
 
     cur.execute(
-        sql.SQL("insert into {} values (%s, %s)")
+        sql.SQL("INSERT INTO {} VALUES (%s, %s)")
             .format(sql.Identifier('my_table')),
         [10, 20])
 
@@ -67,7 +67,7 @@ have ``%s``\-style placeholders in your query and pass values to
 `~psycopg.Cursor.execute()`: such value placeholders will be untouched by
 `!format()`::
 
-    query = sql.SQL("select {field} from {table} where {pkey} = %s").format(
+    query = sql.SQL("SELECT {field} FROM {table} WHERE {pkey} = %s").format(
         field=sql.Identifier('my_name'),
         table=sql.Identifier('some_table'),
         pkey=sql.Identifier('id'))
@@ -84,7 +84,7 @@ If part of your query is a variable sequence of arguments, such as a
 comma-separated list of field names, you can use the `SQL.join()` method to
 pass them to the query::
 
-    query = sql.SQL("select {fields} from {table}").format(
+    query = sql.SQL("SELECT {fields} FROM {table}").format(
         fields=sql.SQL(',').join([
             sql.Identifier('field1'),
             sql.Identifier('field2'),
index eaf6c8a828abf4973cab49df5f3dc046276171d6..b38dc4e046235c935d061fef669af50d0b8f709d 100644 (file)
@@ -37,7 +37,7 @@ can extend the behaviour of the adapters: if you create a loader for
     t = TypeInfo.fetch(conn, "mytype")
     t.register(conn)
 
-    for record in conn.execute("select mytypearray from mytable"):
+    for record in conn.execute("SELECT mytypearray FROM mytable"):
         # records will return lists of "mytype" as string
 
     class MyTypeLoader(Loader):
@@ -46,7 +46,7 @@ can extend the behaviour of the adapters: if you create a loader for
 
     conn.adapters.register_loader("mytype", MyTypeLoader)
 
-    for record in conn.execute("select mytypearray from mytable"):
+    for record in conn.execute("SELECT mytypearray FROM mytable"):
         # records will return lists of MyType instances
 
 
index 9d8a4c57c4b0f12bbb3267c67f4873eb517b9b83..39d7368e8e754b156c88a8ee540e8f1b5097fc9f 100644 (file)
@@ -114,15 +114,15 @@ Python `int` values are converted to PostgreSQL :sql:`bigint` (a.k.a.
   expect an :sql:`integer` (aka :sql:`int4`): passing them a :sql:`bigint`
   may cause an error::
 
-      cur.execute("select current_date + %s", [1])
+      cur.execute("SELECT current_date + %s", [1])
       # UndefinedFunction: operator does not exist: date + bigint
 
   In this case you should add an :sql:`::int` cast to your query or use the
   `~psycopg.types.numeric.Int4` wrapper::
 
-      cur.execute("select current_date + %s::int", [1])
+      cur.execute("SELECT current_date + %s::int", [1])
 
-      cur.execute("select current_date + %s", [Int4(1)])
+      cur.execute("SELECT current_date + %s", [Int4(1)])
 
   .. admonition:: TODO
 
@@ -167,9 +167,9 @@ such as :sql:`text` and :sql:`varchar` are converted back to Python `!str`:
 
     conn = psycopg.connect()
     conn.execute(
-        "insert into strtest (id, data) values (%s, %s)",
+        "INSERT INTO strtest (id, data) VALUES (%s, %s)",
         (1, "Crème Brûlée at 4.99€"))
-    conn.execute("select data from strtest where id = 1").fetchone()[0]
+    conn.execute("SELECT data FROM strtest WHERE id = 1").fetchone()[0]
     'Crème Brûlée at 4.99€'
 
 PostgreSQL databases `have an encoding`__, and `the session has an encoding`__
@@ -191,12 +191,12 @@ encoding/decoding errors:
     # The Latin-9 encoding can manage some European accented letters
     # and the Euro symbol
     conn.client_encoding = 'latin9'
-    conn.execute("select data from strtest where id = 1").fetchone()[0]
+    conn.execute("SELECT data FROM strtest WHERE id = 1").fetchone()[0]
     'Crème Brûlée at 4.99€'
 
     # The Latin-1 encoding doesn't have a representation for the Euro symbol
     conn.client_encoding = 'latin1'
-    conn.execute("select data from strtest where id = 1").fetchone()[0]
+    conn.execute("SELECT data FROM strtest WHERE id = 1").fetchone()[0]
     # Traceback (most recent call last)
     # ...
     # UntranslatableCharacter: character with byte sequence 0xe2 0x82 0xac
@@ -210,7 +210,7 @@ coming from the database, which will be returned as `bytes`:
 .. code:: python
 
     conn.client_encoding = "ascii"
-    conn.execute("select data from strtest where id = 1").fetchone()[0]
+    conn.execute("SELECT data FROM strtest WHERE id = 1").fetchone()[0]
     b'Cr\xc3\xa8me Br\xc3\xbbl\xc3\xa9e at 4.99\xe2\x82\xac'
 
 Alternatively you can cast the unknown encoding data to :sql:`bytea` to
@@ -270,7 +270,7 @@ either `psycopg.types.json.Json` or `~psycopg.types.json.Jsonb`.
     from psycopg.types.json import Jsonb
 
     thing = {"foo": ["bar", 42]}
-    conn.execute("insert into mytable values (%s)", [Jsonb(thing)])
+    conn.execute("INSERT INTO mytable VALUES (%s)", [Jsonb(thing)])
 
 By default Psycopg uses the standard library `json.dumps` and `json.loads`
 functions to serialize and de-serialize Python objects to JSON. If you want to
@@ -292,7 +292,7 @@ to a specific context (connection or cursor).
     # Return floating point values as Decimal, just in one connection
     set_json_loads(partial(json.loads, parse_float=Decimal), conn)
 
-    conn.execute("select %s", [Jsonb({"value": 123.45})]).fetchone()[0]
+    conn.execute("SELECT %s", [Jsonb({"value": 123.45})]).fetchone()[0]
     # {'value': Decimal('123.45')}
 
 If you need an even more specific dump customisation only for certain objects
@@ -314,7 +314,7 @@ take precedence over what specified by `!set_json_dumps()`.
 
     uuid_dumps = partial(json.dumps, cls=UUIDEncoder)
     obj = {"uuid": uuid4()}
-    cnn.execute("insert into objs values %s", [Json(obj, dumps=uuid_dumps)])
+    cnn.execute("INSERT INTO objs VALUES %s", [Json(obj, dumps=uuid_dumps)])
     # will insert: {'uuid': '0a40799d-3980-4c65-8315-2956b18ab0e1'}
 
 
index 6e569061ac641a681f697ac044e57d645b54883d..706acf01386169de76ba01392e9d7bfc50716a62 100644 (file)
@@ -24,14 +24,14 @@ explicit cast.
 
 .. code:: python
 
-    cur.execute("select '[10,20,30]'::jsonb -> 1").fetchone()
+    cur.execute("SELECT '[10,20,30]'::jsonb -> 1").fetchone()
     # returns (20,)
 
-    cur.execute("select '[10,20,30]'::jsonb -> %s", [1]).fetchone()
+    cur.execute("SELECT '[10,20,30]'::jsonb -> %s", [1]).fetchone()
     # raises an exception:
     # UndefinedFunction: operator does not exist: jsonb -> numeric
 
-    cur.execute("select '[10,20,30]'::jsonb -> %s::int", [1]).fetchone()
+    cur.execute("SELECT '[10,20,30]'::jsonb -> %s::int", [1]).fetchone()
     # returns (20,)
 
 PostgreSQL will also reject the execution of several queries at once
index edbc7c925351425318818389da34b54f221bf1ce..83bfa600f81b6b0d680cd71b438c377452ce8c55 100644 (file)
@@ -140,7 +140,7 @@ using a result in a single expression:
 
 .. code::
 
-    print(psycopg.connect(DSN).execute("select now()").fetchone()[0])
+    print(psycopg.connect(DSN).execute("SELECT now()").fetchone()[0])
     # 2042-07-12 18:15:10.706497+01:00
 
 
index 87faf61190c3513b63216163acf881d9565bec17..fa91032299f0218a391077d72e6296aade6939af 100644 (file)
@@ -140,12 +140,12 @@ class TypeInfo:
             register_adapters(self, context)
 
     _info_query = """\
-select
-    typname as name, oid, typarray as array_oid,
-    oid::regtype as alt_name, typdelim as delimiter
-from pg_type t
-where t.oid = %(name)s::regtype
-order by t.oid
+SELECT
+    typname AS name, oid, typarray AS array_oid,
+    oid::regtype AS alt_name, typdelim AS delimiter
+FROM pg_type t
+WHERE t.oid = %(name)s::regtype
+ORDER BY t.oid
 """
 
 
@@ -166,11 +166,11 @@ class RangeInfo(TypeInfo):
         register_adapters(self, context)
 
     _info_query = """\
-select t.typname as name, t.oid as oid, t.typarray as array_oid,
-    r.rngsubtype as subtype_oid
-from pg_type t
-join pg_range r on t.oid = r.rngtypid
-where t.oid = %(name)s::regtype
+SELECT t.typname AS name, t.oid AS oid, t.typarray AS array_oid,
+    r.rngsubtype AS subtype_oid
+FROM pg_type t
+JOIN pg_range r ON t.oid = r.rngtypid
+WHERE t.oid = %(name)s::regtype
 """
 
 
@@ -203,28 +203,28 @@ class CompositeInfo(TypeInfo):
         register_adapters(self, context, factory)
 
     _info_query = """\
-select
-    t.typname as name, t.oid as oid, t.typarray as array_oid,
-    coalesce(a.fnames, '{}') as field_names,
-    coalesce(a.ftypes, '{}') as field_types
-from pg_type t
-left join (
-    select
+SELECT
+    t.typname AS name, t.oid AS oid, t.typarray AS array_oid,
+    coalesce(a.fnames, '{}') AS field_names,
+    coalesce(a.ftypes, '{}') AS field_types
+FROM pg_type t
+LEFT JOIN (
+    SELECT
         attrelid,
-        array_agg(attname) as fnames,
-        array_agg(atttypid) as ftypes
-    from (
-        select a.attrelid, a.attname, a.atttypid
-        from pg_attribute a
-        join pg_type t on t.typrelid = a.attrelid
-        where t.oid = %(name)s::regtype
-        and a.attnum > 0
-        and not a.attisdropped
-        order by a.attnum
+        array_agg(attname) AS fnames,
+        array_agg(atttypid) AS ftypes
+    FROM (
+        SELECT a.attrelid, a.attname, a.atttypid
+        FROM pg_attribute a
+        JOIN pg_type t ON t.typrelid = a.attrelid
+        WHERE t.oid = %(name)s::regtype
+        AND a.attnum > 0
+        AND NOT a.attisdropped
+        ORDER BY a.attnum
     ) x
-    group by attrelid
-) a on a.attrelid = t.typrelid
-where t.oid = %(name)s::regtype
+    GROUP BY attrelid
+) a ON a.attrelid = t.typrelid
+WHERE t.oid = %(name)s::regtype
 """
 
 
index c1a5d5c75c0ab95da4c0e2501bb2dea250afae56..f8e6fba26a95ffd61b9e04d4db2c5b254667cfc3 100644 (file)
@@ -276,7 +276,7 @@ class BaseConnection(Generic[Row]):
 
     def _set_client_encoding_gen(self, name: str) -> PQGen[None]:
         self.pgconn.send_query_params(
-            b"select set_config('client_encoding', $1, false)",
+            b"SELECT set_config('client_encoding', $1, false)",
             [encodings.py2pg(name)],
         )
         (result,) = yield from execute(self.pgconn)
@@ -479,19 +479,19 @@ class BaseConnection(Generic[Row]):
         if self._begin_statement:
             return self._begin_statement
 
-        parts = [b"begin"]
+        parts = [b"BEGIN"]
 
         if self.isolation_level is not None:
             val = IsolationLevel(self.isolation_level)
-            parts.append(b"isolation level")
-            parts.append(val.name.lower().replace("_", " ").encode("utf8"))
+            parts.append(b"ISOLATION LEVEL")
+            parts.append(val.name.replace("_", " ").encode("utf8"))
 
         if self.read_only is not None:
-            parts.append(b"read only" if self.read_only else b"read write")
+            parts.append(b"READ ONLY" if self.read_only else b"READ WRITE")
 
         if self.deferrable is not None:
             parts.append(
-                b"deferrable" if self.deferrable else b"not deferrable"
+                b"DEFERRABLE" if self.deferrable else b"NOT DEFERRABLE"
             )
 
         self._begin_statement = b" ".join(parts)
@@ -508,7 +508,7 @@ class BaseConnection(Generic[Row]):
         if self.pgconn.transaction_status == TransactionStatus.IDLE:
             return
 
-        yield from self._exec_command(b"commit")
+        yield from self._exec_command(b"COMMIT")
 
     def _rollback_gen(self) -> PQGen[None]:
         """Generator implementing `Connection.rollback()`."""
@@ -521,7 +521,7 @@ class BaseConnection(Generic[Row]):
         if self.pgconn.transaction_status == TransactionStatus.IDLE:
             return
 
-        yield from self._exec_command(b"rollback")
+        yield from self._exec_command(b"ROLLBACK")
 
 
 class Connection(BaseConnection[Row]):
index 947f2f86e02eb1fcb632290d18159f3d546da9c9..a3c42b1a8a4e88b2251f340b3d3226c574aadb2a 100644 (file)
@@ -294,7 +294,7 @@ class AsyncConnectionPool(BasePool[AsyncConnection[Any]]):
         while conns:
             conn = conns.pop()
             try:
-                await conn.execute("select 1")
+                await conn.execute("SELECT 1")
             except Exception:
                 self._stats[self._CONNECTIONS_LOST] += 1
                 logger.warning("discarding broken connection: %s", conn)
index 8a2868236d6af85b4d7bba614b4081861f99d602..2de6918ead16e0d0ce63c4d8740525ff0121bee3 100644 (file)
@@ -357,7 +357,7 @@ class ConnectionPool(BasePool[Connection[Any]]):
         while conns:
             conn = conns.pop()
             try:
-                conn.execute("select 1")
+                conn.execute("SELECT 1")
             except Exception:
                 self._stats[self._CONNECTIONS_LOST] += 1
                 logger.warning("discarding broken connection: %s", conn)
index 2739c0878b6ff1304c8dc903daa4ddef9b171ead..201278f78651a89ed76d11f2ef30890250220e47 100644 (file)
@@ -104,13 +104,13 @@ class ServerCursorHelper(Generic[ConnectionType, Row]):
         # but we must make sure it exists.
         if not self.described:
             query = sql.SQL(
-                "select 1 from pg_catalog.pg_cursors where name = {}"
+                "SELECT 1 FROM pg_catalog.pg_cursors WHERE name = {}"
             ).format(sql.Literal(self.name))
             res = yield from cur._conn._exec_command(query)
             if res.ntuples == 0:
                 return
 
-        query = sql.SQL("close {}").format(sql.Identifier(self.name))
+        query = sql.SQL("CLOSE {}").format(sql.Identifier(self.name))
         yield from cur._conn._exec_command(query)
 
     def _fetch_gen(
@@ -124,9 +124,9 @@ class ServerCursorHelper(Generic[ConnectionType, Row]):
         if num is not None:
             howmuch: sql.Composable = sql.Literal(num)
         else:
-            howmuch = sql.SQL("all")
+            howmuch = sql.SQL("ALL")
 
-        query = sql.SQL("fetch forward {} from {}").format(
+        query = sql.SQL("FETCH FORWARD {} FROM {}").format(
             howmuch, sql.Identifier(self.name)
         )
         res = yield from cur._conn._exec_command(query)
@@ -142,8 +142,8 @@ class ServerCursorHelper(Generic[ConnectionType, Row]):
             raise ValueError(
                 f"bad mode: {mode}. It should be 'relative' or 'absolute'"
             )
-        query = sql.SQL("move{} {} from {}").format(
-            sql.SQL(" absolute" if mode == "absolute" else ""),
+        query = sql.SQL("MOVE{} {} FROM {}").format(
+            sql.SQL(" ABSOLUTE" if mode == "absolute" else ""),
             sql.Literal(value),
             sql.Identifier(self.name),
         )
@@ -161,15 +161,15 @@ class ServerCursorHelper(Generic[ConnectionType, Row]):
             query = sql.SQL(query)
 
         parts = [
-            sql.SQL("declare"),
+            sql.SQL("DECLARE"),
             sql.Identifier(self.name),
         ]
         if self.scrollable is not None:
-            parts.append(sql.SQL("scroll" if self.scrollable else "no scroll"))
-        parts.append(sql.SQL("cursor"))
+            parts.append(sql.SQL("SCROLL" if self.scrollable else "NO SCROLL"))
+        parts.append(sql.SQL("CURSOR"))
         if self.withhold:
-            parts.append(sql.SQL("with hold"))
-        parts.append(sql.SQL("for"))
+            parts.append(sql.SQL("WITH HOLD"))
+        parts.append(sql.SQL("FOR"))
         parts.append(query)
 
         return sql.SQL(" ").join(parts)
index abc5bc4bb177ce593ae7978f107f7a0c0117e223..caf903025265104388185ccb43b1c58736fba671 100644 (file)
@@ -114,9 +114,9 @@ class Composed(Composable):
     Example::
 
         >>> comp = sql.Composed(
-        ...     [sql.SQL("insert into "), sql.Identifier("table")])
+        ...     [sql.SQL("INSERT INTO "), sql.Identifier("table")])
         >>> print(comp.as_string(conn))
-        insert into "table"
+        INSERT INTO "table"
 
     `!Composed` objects are iterable (so they can be used in `SQL.join` for
     instance).
@@ -185,11 +185,11 @@ class SQL(Composable):
 
     Example::
 
-        >>> query = sql.SQL("select {0} from {1}").format(
+        >>> query = sql.SQL("SELECT {0} FROM {1}").format(
         ...    sql.SQL(', ').join([sql.Identifier('foo'), sql.Identifier('bar')]),
         ...    sql.Identifier('table'))
         >>> print(query.as_string(conn))
-        select "foo", "bar" from "table"
+        SELECT "foo", "bar" FROM "table"
     """
 
     _obj: str
@@ -235,15 +235,15 @@ class SQL(Composable):
 
         Example::
 
-            >>> print(sql.SQL("select * from {} where {} = %s")
+            >>> print(sql.SQL("SELECT * FROM {} WHERE {} = %s")
             ...     .format(sql.Identifier('people'), sql.Identifier('id'))
             ...     .as_string(conn))
-            select * from "people" where "id" = %s
+            SELECT * FROM "people" WHERE "id" = %s
 
-            >>> print(sql.SQL("select * from {tbl} where name = {name}")
+            >>> print(sql.SQL("SELECT * FROM {tbl} WHERE name = {name}")
             ...     .format(tbl=sql.Identifier('people'), name="O'Rourke"))
             ...     .as_string(conn))
-            select * from "people" where name = 'O''Rourke'
+            SELECT * FROM "people" WHERE name = 'O''Rourke'
 
         """
         rv: List[Composable] = []
@@ -336,11 +336,11 @@ class Identifier(Composable):
 
     Example::
 
-        >>> query = sql.SQL("select {} from {}").format(
+        >>> query = sql.SQL("SELECT {} FROM {}").format(
         ...     sql.Identifier("table", "field"),
         ...     sql.Identifier("schema", "table"))
         >>> print(query.as_string(conn))
-        select "table"."field" from "schema"."table"
+        SELECT "table"."field" FROM "schema"."table"
 
     """
 
@@ -413,17 +413,17 @@ class Placeholder(Composable):
 
         >>> names = ['foo', 'bar', 'baz']
 
-        >>> q1 = sql.SQL("insert into table ({}) values ({})").format(
+        >>> q1 = sql.SQL("INSERT INTO my_table ({}) VALUES ({})").format(
         ...     sql.SQL(', ').join(map(sql.Identifier, names)),
         ...     sql.SQL(', ').join(sql.Placeholder() * len(names)))
         >>> print(q1.as_string(conn))
-        insert into table ("foo", "bar", "baz") values (%s, %s, %s)
+        INSERT INTO my_table ("foo", "bar", "baz") VALUES (%s, %s, %s)
 
-        >>> q2 = sql.SQL("insert into table ({}) values ({})").format(
+        >>> q2 = sql.SQL("INSERT INTO my_table ({}) VALUES ({})").format(
         ...     sql.SQL(', ').join(map(sql.Identifier, names)),
         ...     sql.SQL(', ').join(map(sql.Placeholder, names)))
         >>> print(q2.as_string(conn))
-        insert into table ("foo", "bar", "baz") values (%(foo)s, %(bar)s, %(baz)s)
+        INSERT INTO my_table ("foo", "bar", "baz") VALUES (%(foo)s, %(bar)s, %(baz)s)
 
     """
 
index 85a5c3a17ffa95ee5b8982fbc6f5e0016672f484..abde9e54c7587dd1805ef90d86f45ca4dad36bbb 100644 (file)
@@ -103,7 +103,7 @@ class BaseTransaction(Generic[ConnectionType]):
 
         if self._savepoint_name:
             commands.append(
-                sql.SQL("savepoint {}")
+                sql.SQL("SAVEPOINT {}")
                 .format(sql.Identifier(self._savepoint_name))
                 .as_bytes(self._conn)
             )
@@ -131,14 +131,14 @@ class BaseTransaction(Generic[ConnectionType]):
         commands = []
         if self._savepoint_name and not self._outer_transaction:
             commands.append(
-                sql.SQL("release {}")
+                sql.SQL("RELEASE {}")
                 .format(sql.Identifier(self._savepoint_name))
                 .as_bytes(self._conn)
             )
 
         if self._outer_transaction:
             assert not self._conn._savepoints
-            commands.append(b"commit")
+            commands.append(b"COMMIT")
 
         return self._conn._exec_command(b"; ".join(commands))
 
@@ -154,14 +154,14 @@ class BaseTransaction(Generic[ConnectionType]):
         commands = []
         if self._savepoint_name and not self._outer_transaction:
             commands.append(
-                sql.SQL("rollback to {n}; release {n}")
+                sql.SQL("ROLLBACK TO {n}; RELEASE {n}")
                 .format(n=sql.Identifier(self._savepoint_name))
                 .as_bytes(self._conn)
             )
 
         if self._outer_transaction:
             assert not self._conn._savepoints
-            commands.append(b"rollback")
+            commands.append(b"ROLLBACK")
 
         yield from self._conn._exec_command(b"; ".join(commands))
 
index 00860dcae8f5f26d975bf0f745b965566a5e621f..ba54549c8b1e5184e4f5bac5a44e9953d81da839 100644 (file)
@@ -357,43 +357,43 @@ def test_named_savepoints_successful_exit(conn, commands):
     # Using Transaction explicitly becase conn.transaction() enters the contetx
     assert not commands
     with conn.transaction() as tx:
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         assert not tx.savepoint_name
-    assert commands.popall() == ["commit"]
+    assert commands.popall() == ["COMMIT"]
 
     # Case 1 (with a transaction already started)
     conn.cursor().execute("select 1")
-    assert commands.popall() == ["begin"]
+    assert commands.popall() == ["BEGIN"]
     with conn.transaction() as tx:
-        assert commands.popall() == ['savepoint "_pg3_1"']
+        assert commands.popall() == ['SAVEPOINT "_pg3_1"']
         assert tx.savepoint_name == "_pg3_1"
-    assert commands.popall() == ['release "_pg3_1"']
+    assert commands.popall() == ['RELEASE "_pg3_1"']
     conn.rollback()
-    assert commands.popall() == ["rollback"]
+    assert commands.popall() == ["ROLLBACK"]
 
     # Case 2
     with conn.transaction(savepoint_name="foo") as tx:
-        assert commands.popall() == ['begin; savepoint "foo"']
+        assert commands.popall() == ['BEGIN; SAVEPOINT "foo"']
         assert tx.savepoint_name == "foo"
-    assert commands.popall() == ["commit"]
+    assert commands.popall() == ["COMMIT"]
 
     # Case 3 (with savepoint name provided)
     with conn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         with conn.transaction(savepoint_name="bar") as tx:
-            assert commands.popall() == ['savepoint "bar"']
+            assert commands.popall() == ['SAVEPOINT "bar"']
             assert tx.savepoint_name == "bar"
-        assert commands.popall() == ['release "bar"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['RELEASE "bar"']
+    assert commands.popall() == ["COMMIT"]
 
     # Case 3 (with savepoint name auto-generated)
     with conn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         with conn.transaction() as tx:
-            assert commands.popall() == ['savepoint "_pg3_2"']
+            assert commands.popall() == ['SAVEPOINT "_pg3_2"']
             assert tx.savepoint_name == "_pg3_2"
-        assert commands.popall() == ['release "_pg3_2"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['RELEASE "_pg3_2"']
+    assert commands.popall() == ["COMMIT"]
 
 
 def test_named_savepoints_exception_exit(conn, commands):
@@ -405,40 +405,40 @@ def test_named_savepoints_exception_exit(conn, commands):
     # Case 1
     with pytest.raises(ExpectedException):
         with conn.transaction() as tx:
-            assert commands.popall() == ["begin"]
+            assert commands.popall() == ["BEGIN"]
             assert not tx.savepoint_name
             raise ExpectedException
-    assert commands.popall() == ["rollback"]
+    assert commands.popall() == ["ROLLBACK"]
 
     # Case 2
     with pytest.raises(ExpectedException):
         with conn.transaction(savepoint_name="foo") as tx:
-            assert commands.popall() == ['begin; savepoint "foo"']
+            assert commands.popall() == ['BEGIN; SAVEPOINT "foo"']
             assert tx.savepoint_name == "foo"
             raise ExpectedException
-    assert commands.popall() == ["rollback"]
+    assert commands.popall() == ["ROLLBACK"]
 
     # Case 3 (with savepoint name provided)
     with conn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         with pytest.raises(ExpectedException):
             with conn.transaction(savepoint_name="bar") as tx:
-                assert commands.popall() == ['savepoint "bar"']
+                assert commands.popall() == ['SAVEPOINT "bar"']
                 assert tx.savepoint_name == "bar"
                 raise ExpectedException
-        assert commands.popall() == ['rollback to "bar"; release "bar"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['ROLLBACK TO "bar"; RELEASE "bar"']
+    assert commands.popall() == ["COMMIT"]
 
     # Case 3 (with savepoint name auto-generated)
     with conn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         with pytest.raises(ExpectedException):
             with conn.transaction() as tx:
-                assert commands.popall() == ['savepoint "_pg3_2"']
+                assert commands.popall() == ['SAVEPOINT "_pg3_2"']
                 assert tx.savepoint_name == "_pg3_2"
                 raise ExpectedException
-        assert commands.popall() == ['rollback to "_pg3_2"; release "_pg3_2"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['ROLLBACK TO "_pg3_2"; RELEASE "_pg3_2"']
+    assert commands.popall() == ["COMMIT"]
 
 
 def test_named_savepoints_with_repeated_names_works(conn):
index 25dfb64920d62e4bc30acda073f039c25988364c..c1d767b6f1bd0e98c93160b98c9c133620f27ca9 100644 (file)
@@ -319,44 +319,44 @@ async def test_named_savepoints_successful_exit(aconn, acommands):
     # Case 1
     # Using Transaction explicitly becase conn.transaction() enters the contetx
     async with aconn.transaction() as tx:
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         assert not tx.savepoint_name
-    assert commands.popall() == ["commit"]
+    assert commands.popall() == ["COMMIT"]
 
     # Case 1 (with a transaction already started)
     await aconn.cursor().execute("select 1")
-    assert commands.popall() == ["begin"]
+    assert commands.popall() == ["BEGIN"]
     async with aconn.transaction() as tx:
-        assert commands.popall() == ['savepoint "_pg3_1"']
+        assert commands.popall() == ['SAVEPOINT "_pg3_1"']
         assert tx.savepoint_name == "_pg3_1"
 
-    assert commands.popall() == ['release "_pg3_1"']
+    assert commands.popall() == ['RELEASE "_pg3_1"']
     await aconn.rollback()
-    assert commands.popall() == ["rollback"]
+    assert commands.popall() == ["ROLLBACK"]
 
     # Case 2
     async with aconn.transaction(savepoint_name="foo") as tx:
-        assert commands.popall() == ['begin; savepoint "foo"']
+        assert commands.popall() == ['BEGIN; SAVEPOINT "foo"']
         assert tx.savepoint_name == "foo"
-    assert commands.popall() == ["commit"]
+    assert commands.popall() == ["COMMIT"]
 
     # Case 3 (with savepoint name provided)
     async with aconn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         async with aconn.transaction(savepoint_name="bar") as tx:
-            assert commands.popall() == ['savepoint "bar"']
+            assert commands.popall() == ['SAVEPOINT "bar"']
             assert tx.savepoint_name == "bar"
-        assert commands.popall() == ['release "bar"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['RELEASE "bar"']
+    assert commands.popall() == ["COMMIT"]
 
     # Case 3 (with savepoint name auto-generated)
     async with aconn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         async with aconn.transaction() as tx:
-            assert commands.popall() == ['savepoint "_pg3_2"']
+            assert commands.popall() == ['SAVEPOINT "_pg3_2"']
             assert tx.savepoint_name == "_pg3_2"
-        assert commands.popall() == ['release "_pg3_2"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['RELEASE "_pg3_2"']
+    assert commands.popall() == ["COMMIT"]
 
 
 async def test_named_savepoints_exception_exit(aconn, acommands):
@@ -370,40 +370,40 @@ async def test_named_savepoints_exception_exit(aconn, acommands):
     # Case 1
     with pytest.raises(ExpectedException):
         async with aconn.transaction() as tx:
-            assert commands.popall() == ["begin"]
+            assert commands.popall() == ["BEGIN"]
             assert not tx.savepoint_name
             raise ExpectedException
-    assert commands.popall() == ["rollback"]
+    assert commands.popall() == ["ROLLBACK"]
 
     # Case 2
     with pytest.raises(ExpectedException):
         async with aconn.transaction(savepoint_name="foo") as tx:
-            assert commands.popall() == ['begin; savepoint "foo"']
+            assert commands.popall() == ['BEGIN; SAVEPOINT "foo"']
             assert tx.savepoint_name == "foo"
             raise ExpectedException
-    assert commands.popall() == ["rollback"]
+    assert commands.popall() == ["ROLLBACK"]
 
     # Case 3 (with savepoint name provided)
     async with aconn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         with pytest.raises(ExpectedException):
             async with aconn.transaction(savepoint_name="bar") as tx:
-                assert commands.popall() == ['savepoint "bar"']
+                assert commands.popall() == ['SAVEPOINT "bar"']
                 assert tx.savepoint_name == "bar"
                 raise ExpectedException
-        assert commands.popall() == ['rollback to "bar"; release "bar"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['ROLLBACK TO "bar"; RELEASE "bar"']
+    assert commands.popall() == ["COMMIT"]
 
     # Case 3 (with savepoint name auto-generated)
     async with aconn.transaction():
-        assert commands.popall() == ["begin"]
+        assert commands.popall() == ["BEGIN"]
         with pytest.raises(ExpectedException):
             async with aconn.transaction() as tx:
-                assert commands.popall() == ['savepoint "_pg3_2"']
+                assert commands.popall() == ['SAVEPOINT "_pg3_2"']
                 assert tx.savepoint_name == "_pg3_2"
                 raise ExpectedException
-        assert commands.popall() == ['rollback to "_pg3_2"; release "_pg3_2"']
-    assert commands.popall() == ["commit"]
+        assert commands.popall() == ['ROLLBACK TO "_pg3_2"; RELEASE "_pg3_2"']
+    assert commands.popall() == ["COMMIT"]
 
 
 async def test_named_savepoints_with_repeated_names_works(aconn):