IC Improve Code Recipes

Recipe 1.6 · Python

Bulk Loads with SqlBulkCopy and Table-Valued Parameters

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

A nightly import inserts a supplier's price file, 200,000 rows, one INSERT per row. Each insert is a network round trip and a log flush. The job that should take seconds takes most of an hour. A related problem shows up at the other end of the scale: passing a list of 300 IDs to a query, usually by building a comma-separated string.

The way it's often written

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

On top of the speed problem, this inserts prices formatted with the server's current culture. On a machine set to a European culture, 12.50 becomes 12,50 and the statement fails.

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 One round trip per row, with concatenated values (p031_r1_6_row_by_row_insert_before.py)
"""One round trip per row, with concatenated values

Source: ImproveCode, Chapter 1, Recipe 1.6 "Bulk Loads with SqlBulkCopy and Table-Valued Parameters"
Section: The way it's often written
Book page: 31-32  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlCommand.ExecuteNonQuery -> pyodbc cursor.execute per row.
"""

from typing import Any

import pyodbc


def import_prices(conn: pyodbc.Connection, rows: list[Any]) -> None:
    # Not to copy: one round trip per row.
    for row in rows:
        cmd = conn.cursor()
        cmd.execute(
            "INSERT INTO PriceImport (Sku, Price, EffectiveDate) "
            "VALUES ('" + row.sku + "', " + str(row.price) + ", '"
            + str(row.effective_date) + "')")

The improved recipe

The table-valued parameter type the second class uses:

SQL
CREATE TYPE dbo.IntList AS TABLE
(
    Value INT NOT NULL PRIMARY KEY
);

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 Bulk load staging rows and query by a table-valued parameter (p032_r1_6_bulk_load_and_tvp.py)
"""Bulk load staging rows and query by a table-valued parameter

Source: ImproveCode, Chapter 1, Recipe 1.6 "Bulk Loads with SqlBulkCopy and Table-Valued Parameters"
Section: The improved recipe
Book page: 32-34  -- original C# listing
Converted from C# to Python.
SqlBulkCopy -> pyodbc executemany with fast_executemany=True in 5,000-row batches, run on a worker
thread (asyncio.to_thread); TableLock -> WITH (TABLOCK) hint. SqlDataRecord TVP -> pyodbc's TVP
form [type_name, schema, *rows]. Async reads use aioodbc via the Recipe 1.1/1.2 factory.
"""

import asyncio
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from itertools import islice

import pyodbc

from p020_r1_2_typed_sql_parameters_lookup import DbConnectionFactory


@dataclass(frozen=True)
class PriceImportRow:
    sku: str
    price: Decimal
    effective_date: datetime


class PriceImporter:
    INSERT_SQL = """
        INSERT INTO staging.PriceImport WITH (TABLOCK)
            (Sku, Price, EffectiveDate)
        VALUES (?, ?, ?);
        """
    BATCH_SIZE = 5_000
    BULK_COPY_TIMEOUT = 300

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

    async def load(self, rows: Iterable[PriceImportRow]) -> None:
        table = [(r.sku, r.price, r.effective_date) for r in rows]
        async with asyncio.timeout(self.BULK_COPY_TIMEOUT):
            await asyncio.to_thread(self._write_to_server, table)

    def _write_to_server(self, table: list[tuple[str, Decimal, datetime]]) -> None:
        with pyodbc.connect(self._connection_string, autocommit=True) as connection:
            cursor = connection.cursor()
            cursor.fast_executemany = True
            it = iter(table)
            while batch := list(islice(it, self.BATCH_SIZE)):
                cursor.executemany(self.INSERT_SQL, batch)


@dataclass(frozen=True)
class ProductName:
    product_id: int
    name: str


class ProductQueries:
    BY_IDS_SQL = """
        SELECT p.ProductId, p.Name
        FROM dbo.Product AS p
        JOIN ? AS i ON i.Value = p.ProductId;
        """

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

    async def by_ids(self, ids: Iterable[int]) -> list[ProductName]:
        async with await self._db.open() as connection:
            async with connection.cursor() as command:
                await command.execute(self.BY_IDS_SQL, self.int_list(ids))

                results: list[ProductName] = []
                while (row := await command.fetchone()) is not None:
                    results.append(ProductName(int(row[0]), str(row[1])))
                return results

    @staticmethod
    def int_list(values: Iterable[int]) -> list[object]:
        """TVP of type dbo.IntList (single column Value INT), distinct values."""
        records = [(value,) for value in dict.fromkeys(values)]
        return ["IntList", "dbo", *records]

How it works

SqlBulkCopy streams rows to the server using the same bulk-load protocol as the bcp utility. Rows are minimally logged where the recovery model and table allow it, and the whole load is a handful of round trips. BatchSize commits every 5,000 rows so the log does not grow with one enormous transaction, and TableLock lets the server take a bulk update lock rather than row locks.

Two options matter. By default SqlBulkCopy skips check constraints and does not fire triggers; CheckConstraints turns constraint checking back on. Explicit ColumnMappings match columns by name. Without them, columns are matched by position, and adding a column to the staging table silently shifts data.

The values travel as typed data, not text, so culture-specific decimal separators and date formats stop mattering.

Table-valued parameters solve the smaller problem. The IntList method turns any sequence of integers into a structured parameter of the type dbo.IntList, and the query joins to it like a table. The primary key on the type removes duplicates and gives the optimizer a unique key, which is why the method calls Distinct() first.

Variations and pitfalls

  • Load to staging, then merge. I bulk load into a staging table with no foreign keys, validate with set-based SQL, then move the rows into the real table with one INSERT ... SELECT or an upsert from Chapter 2. A bad file then fails in staging, not halfway through production data.
  • Empty TVPs. An empty list of SqlDataRecord throws. Passing null sends an empty table, which is what the method does when the input is empty.
  • Very large loads. A DataTable holds every row in memory. For millions of rows, pass an IDataReader to WriteToServerAsync instead, either a reader from another database or a small DbDataReader over your file. The FastMember package's ObjectReader is a common shortcut.
  • TVPs and procedures. A TVP parameter in a procedure must be declared READONLY: @Ids dbo.IntList READONLY.
  • Changing a TVP type requires dropping every procedure that uses it first. Name types for what they hold (dbo.IntList, dbo.SkuPriceList) and change them rarely.