IC Improve Code Recipes

Recipe 17.1 · Python

Replacing String-Built Queries in SQLManager

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

SQLManager has one public method for nearly every query the product runs: GetIncidentFromID, GetDrillFromID, GetAudit, GetAuditRBPS1 through GetAuditRBPS18, and more than 300 others. Most build a SQL string with string.Format, hand it to a generic GetData, and return an untyped DataSet. Mapping to a model happens later, in SQLUtility, with column names typed a second time.

The way it's often written

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

This is from CFATS Manager, abridged and re-wrapped. The column list is shortened.

With an int parameter this particular query can't be injected. The habit is the problem. The same pattern is used with string parameters all through the class, including for lookups by name, and GetData accepts any string at all. When the query fails, HandleException records the error in the manager's State and returns an empty DataSet. The caller has to remember to look.

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 Incident lookup built with string formatting and a data helper that swallows errors (p382_r17_1_string_formatted_incident_query_before.py)
"""Incident lookup built with string formatting and a data helper that swallows errors

Source: ImproveCode, Chapter 17, Recipe 17.1 "Replacing String-Built Queries in SQLManager"
Section: The way it's often written
Book page: 382-383  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlConnection/SQLHelper.ExecuteDataset become pyodbc and fetchall(); DataSet becomes a
list of rows (empty on failure, as the original returned an empty DataSet).
"""

from typing import Any

import pyodbc


# From CFATS Manager: CFATSLibrary\Data\SQLServer\SQLManager.cs
# lines 246-267 and 1587-1595 (abridged, re-wrapped)
class SQLManager:
    def __init__(self, connection_string: str) -> None:
        self._connection_string = connection_string

    def get_incident_from_id(self, IncidentID: int) -> list[Any]:
        SQL = ""
        SQL = (
            "select FacilityID,IncidentID,IncidentTypeNo, ... "
            + "FileGUID from vwFacilityIncidentView "
            + "where IncidentID = {0}"
        )

        Query = SQL.format(IncidentID)
        dsData = self.get_data(Query)
        return dsData

    def get_data(self, SQL: str) -> list[Any]:
        DBConnection = None
        DS: list[Any] = []
        try:
            DBConnection = self.get_connection(self._connection_string)
            Query = self.set_query(SQL)
            DS = DBConnection.cursor().execute(Query).fetchall()
        except Exception as ex:
            self.handle_exception(ex, "Get data failed")
        finally:
            self.dispose_connection(DBConnection)
        return DS

    def get_connection(self, cs: str) -> pyodbc.Connection:
        return pyodbc.connect(cs)

    def set_query(self, sql: str) -> str:
        return sql

    def dispose_connection(self, conn: pyodbc.Connection | None) -> None:
        if conn is not None:
            conn.close()

    def handle_exception(self, ex: Exception, message: str) -> None:
        ...

The improved recipe

Packages: Microsoft.Data.SqlClient (6.x).

Requirements: Python 3.12+. Install: pip install aioodbc · 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 Parameterized async incident lookup mapped to a typed record (p383_r17_1_parameterized_incident_repository.py)
"""Parameterized async incident lookup mapped to a typed record

Source: ImproveCode, Chapter 17, Recipe 17.1 "Replacing String-Built Queries in SQLManager"
Section: The improved recipe
Book page: 383-384  -- original C# listing
Converted from C# to Python.
Microsoft.Data.SqlClient becomes aioodbc (async pyodbc) with a ? parameter; the record
becomes a frozen dataclass and GUID strings are converted to uuid.UUID.
"""

import uuid
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Protocol

import aioodbc


@dataclass(frozen=True)
class IncidentRecord:
    incident_id: int
    facility_id: int
    incident_type: str
    name: str
    occurred_on: datetime
    location: str | None
    reported_to: str | None
    description: str | None
    file_id: uuid.UUID | None


class SqlConnectionFactory(Protocol):
    async def create(self) -> aioodbc.Connection: ...


class OdbcConnectionFactory:
    def __init__(self, connection_string: str) -> None:
        self._connection_string = connection_string

    async def create(self) -> aioodbc.Connection:
        return await aioodbc.connect(dsn=self._connection_string)


class IncidentRepository:
    _SELECT_BY_ID = """
        SELECT IncidentID, FacilityID, IncidentTypeName,
               IncidentName, OccurenceDate, Location,
               ReportedToPersonName, Description, FileGUID
        FROM dbo.vwFacilityIncidentView
        WHERE IncidentID = ?;
        """

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

    async def get_by_id(self, incident_id: int) -> IncidentRecord | None:
        conn = await self._db.create()
        try:
            async with conn.cursor() as cur:
                await cur.execute(self._SELECT_BY_ID, (incident_id,))
                row = await cur.fetchone()
        finally:
            await conn.close()

        return self._map(row) if row is not None else None

    @staticmethod
    def _map(r: Any) -> IncidentRecord:
        return IncidentRecord(
            incident_id=r[0],
            facility_id=r[1],
            incident_type=r[2],
            name=r[3],
            occurred_on=r[4],
            location=r[5],
            reported_to=r[6],
            description=r[7],
            file_id=uuid.UUID(str(r[8])) if r[8] is not None else None,
        )

How it works

The query and its mapping live side by side in one small class per aggregate, instead of the query in SQLManager and the mapping in SQLUtility, 2,000 lines apart. The SQL is a raw string literal with a named parameter. The value travels separately, typed as SqlDbType.Int, so there is no string to inject into, and SQL Server can reuse one plan for every ID.

await using closes and disposes the connection, the command and the reader on every path. The original needed a finally block and a PersistConnection flag to do the same. Connection pooling already gives you cheap connections, so there is nothing to gain by holding one open.

The method returns IncidentRecord?. A missing row is null, which the compiler forces the caller to handle. A failed query throws SqlException and goes up to whatever handles errors for the request. It does not vanish into a state object. The record's nullable members match the nullable columns, so a reader can tell from the type alone which values may be missing.

ISqlConnectionFactory is the only seam. In a test you point it at a LocalDB or container database. The original read ServerInfo.GetConnectionString(), a static call to ConfigurationManager, inside every Usage method, which made that impossible.

Variations and pitfalls

  • Dapper. If you have dozens of these, Dapper removes the mapper: conn.QuerySingleOrDefaultAsync<IncidentRecord>(sql, new { IncidentId = id }). Alias the columns to match the record's property names. Chapter 1 compares the two.
  • Don't keep the one-method-per-query god class. Splitting SQLManager by aggregate (incidents, drills, audits) is what makes the change reviewable. Move one aggregate at a time and delete the old methods as callers move.
  • Watch the old null handling. The legacy mappers turned NULL into something else. This one is from CFATS Manager, SQLUtility.cs lines 212-217, re-wrapped:

A missing date became now. Other overloads used a sentinel of 1/1/1901 (Constants.NO_DATE). When you port a screen, check which one it relied on. Use DateTime? and decide at the UI what "no date" should look like.

  • Views are still fine. The product reads through views such as vwFacilityIncidentView. Keep them. They are a stable contract between the schema and the code, and they let you rename columns without a release.

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

Python Legacy date helper that silently turns a NULL column into "now" (p385_r17_1_dbnull_date_defaults_to_now.py)
"""Legacy date helper that silently turns a NULL column into "now"

Source: ImproveCode, Chapter 17, Recipe 17.1 "Replacing String-Built Queries in SQLManager"
Section: Variations and pitfalls
Book page: 385  -- original C# listing
Converted from C# to Python.
Shown as the pitfall the recipe warns about (missing dates become the current time).
DBNull.Value becomes None; DateTime.Now becomes naive datetime.now().
"""

from datetime import datetime
from typing import cast


def get_date_value(db_object: object) -> datetime:
    date_value: datetime
    date_value = datetime.now() if db_object is None else cast(datetime, db_object)
    return date_value