Support cursor.execute(psycopg2.sql.Composable) (#1029)

In addition to str, PostgreSQL cursors accept the
psycopg2.sql.Composable type, which is useful for guarding against SQL
injections when building raw queries that can’t be parameterized in
the normal way (e.g. interpolating identifiers).

In order to avoid reintroducing a dependency on psycopg2, we define a
Protocol that matches psycopg2.sql.Composable.

Documentation: https://www.psycopg.org/docs/sql.html
Related: https://github.com/python/typeshed/pull/7494

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
This commit is contained in:
Anders Kaseorg authored and GitHub committed 2022-06-28 23:44:20 +03:00
1 parent 33d4dc7dae
commit 214b0c7439
3 files changed
+37 -4

No files matched your search

+10
View File
@@ -4,6 +4,16 @@
with connection.cursor() as cursor:
reveal_type(cursor) # N: Revealed type is "django.db.backends.utils.CursorWrapper"
cursor.execute("SELECT %s", [123])
- case: raw_connection_psycopg2_composable
main: |
from django.db import connection
from psycopg2.sql import SQL, Identifier
with connection.cursor() as cursor:
cursor.execute(SQL("INSERT INTO {} VALUES (%s)").format(Identifier("my_table")), [123])
- case: raw_connections
main: |
from django.db import connections