IC Improve Code Recipes

Recipe 1.2 · Python

Parameterized Queries, Typed Properly

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

SQL built by string concatenation is the oldest security hole in the business-application world, and it is still being written. Even teams that know to use parameters often use them loosely, with AddWithValue, and pay for it in slow queries and a bloated plan cache.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The first version breaks on the first customer named O'Brien and hands the database to anyone who types ' OR 1=1 --. The second version is safe from injection, but AddWithValue infers an nvarchar parameter with a length equal to the string. A 12-character e-mail gets nvarchar(12), a 13-character one gets nvarchar(13), and each produces its own cached plan. If the column is varchar, SQL Server must convert every row of the column to compare against an nvarchar value, which can turn an index seek into a scan.

Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.

Python Query built by string concatenation, then loosely parameterized (p020_r1_2_string_concatenated_sql_before.py)
"""Query built by string concatenation, then loosely parameterized

Source: ImproveCode, Chapter 1, Recipe 1.2 "Parameterized Queries, Typed Properly"
Section: The way it's often written
Book page: 20  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlCommand -> pyodbc cursor; AddWithValue -> passing a value with no setinputsizes(),
so pyodbc guesses the SQL type and length just as AddWithValue does.
"""

import pyodbc


def find_by_email(conn: pyodbc.Connection, txt_email: str) -> list[pyodbc.Row]:
    # Not to copy: injection, quoting bugs and no plan reuse.
    sql = ("SELECT CustomerId, Name, Email FROM Customer "
           "WHERE Email = '" + txt_email + "'")
    cmd = conn.cursor()
    cmd.execute(sql)
    rows = cmd.fetchall()

    # Better, but still loose: type and length are guessed.
    cmd.execute("SELECT CustomerId, Name, Email FROM Customer WHERE Email = ?",
                txt_email)
    rows += cmd.fetchall()
    return rows

The improved recipe

Requirements: Python 3.12+. Install: pip install aioodbc pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.

Python Typed, sized SQL parameters and a customer lookup by email (p020_r1_2_typed_sql_parameters_lookup.py)
"""Typed, sized SQL parameters and a customer lookup by email

Source: ImproveCode, Chapter 1, Recipe 1.2 "Parameterized Queries, Typed Properly"
Section: The improved recipe
Book page: 20-21  -- original C# listing
Converted from C# to Python.
SqlParameterCollection extension methods -> a small TypedParams builder that records values and
pyodbc setinputsizes() entries (SQL type, size, scale); named @params -> positional ? markers.
SqlClient async -> aioodbc; record -> frozen dataclass; None maps to SQL NULL (DBNull).
"""

from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal
from typing import Any, Protocol

import aioodbc
import pyodbc


class DbConnectionFactory(Protocol):
    async def open(self) -> aioodbc.Connection: ...


@dataclass
class TypedParams:
    """Ordered parameter values plus their declared SQL types for setinputsizes()."""

    names: list[str] = field(default_factory=list)
    values: list[Any] = field(default_factory=list)
    sizes: list[tuple[int, int, int]] = field(default_factory=list)

    def _add(self, name: str, sql_type: int, size: int, scale: int, value: Any) -> "TypedParams":
        self.names.append(name)
        self.values.append(value)  # None is sent as NULL
        self.sizes.append((sql_type, size, scale))
        return self

    def add_int(self, name: str, value: int | None) -> "TypedParams":
        return self._add(name, pyodbc.SQL_INTEGER, 0, 0, value)

    def add_varchar(self, name: str, size: int, value: str | None) -> "TypedParams":
        return self._add(name, pyodbc.SQL_VARCHAR, size, 0, value)

    def add_nvarchar(self, name: str, size: int, value: str | None) -> "TypedParams":
        return self._add(name, pyodbc.SQL_WVARCHAR, size, 0, value)

    def add_decimal(self, name: str, precision: int, scale: int,
                    value: Decimal | None) -> "TypedParams":
        return self._add(name, pyodbc.SQL_DECIMAL, precision, scale, value)

    def add_datetime2(self, name: str, value: datetime | None) -> "TypedParams":
        # datetime2(7): column size 27, 7 fractional digits
        return self._add(name, pyodbc.SQL_TYPE_TIMESTAMP, 27, 7, value)

    async def apply(self, cursor: aioodbc.Cursor) -> None:
        await cursor.setinputsizes(self.sizes)


@dataclass(frozen=True)
class CustomerSummary:
    id: int
    name: str
    email: str


class CustomerLookup:
    FIND_BY_EMAIL_SQL = """
        SELECT CustomerId, Name, Email
        FROM dbo.Customer
        WHERE Email = ? AND IsActive = 1;
        """

    def __init__(self, db: DbConnectionFactory) -> None:
        self._db = db

    async def find_by_email(self, email: str) -> CustomerSummary | None:
        async with await self._db.open() as connection:
            async with connection.cursor() as command:
                params = TypedParams().add_varchar("@Email", 254, email)
                await params.apply(command)
                await command.execute(self.FIND_BY_EMAIL_SQL, *params.values)

                row = await command.fetchone()
                if row is None:
                    return None

                return CustomerSummary(int(row[0]), str(row[1]), str(row[2]))

How it works

Each extension method creates a parameter with an explicit SqlDbType, and a size, precision or scale where the type needs one. Declare the parameter exactly like the column it is compared against. A varchar(254) column gets a varchar(254) parameter, so SQL Server sees the same parameter signature on every call and reuses one plan.

The private WithValue helper converts a C# null into DBNull.Value. Forgetting that conversion is a classic bug: a parameter whose Value is null is treated as not supplied, and the call fails with an error about a missing parameter.

The query text is a constant, written as a raw string literal so it reads like SQL. Nothing from the user ever touches it.

Variations and pitfalls

  • Identifiers cannot be parameters. You cannot pass a column name for ORDER BY or a table name as a parameter. Map user choices to known names through a whitelist and reject anything else:

  • IN lists. Do not build IN (1, 2, 3) by joining strings. Pass a table-valued parameter (Recipe 1.6), or let Dapper expand a list parameter for you.

  • LIKE searches. Parameterize the pattern and add the wildcards in C#: "%" + term + "%". If the term itself can contain %, _ or [, escape those characters first.
  • Stored procedures. Set CommandType.StoredProcedure and pass the procedure name as the command text. The same typed parameters apply.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Whitelist a user-supplied sort column (p022_r1_2_sort_column_whitelist.py)
"""Whitelist a user-supplied sort column

Source: ImproveCode, Chapter 1, Recipe 1.2 "Parameterized Queries, Typed Properly"
Section: Variations and pitfalls
Book page: 22  -- original C# listing
Converted from C# to Python.
Case-insensitive Dictionary (OrdinalIgnoreCase) -> dict with lowercase keys and str.casefold().
"""

# Usage snippet: sort column whitelist.
SORT_COLUMNS: dict[str, str] = {
    "name": "Name",
    "created": "CreatedUtc",
}


def resolve_sort_column(sort: str) -> str:
    return SORT_COLUMNS.get(sort.casefold(), "Name")