#!/usr/bin/env python3 """Timing benchmarks for Chapter 9 (Connections, transactions, and migrations) on Django 6.1.3. Measures: 1. Transaction boundary cost on a file-backed SQLite database (7 trials, 100 Correction inserts per trial): - autocommit (100 separate COMMITs with fsync) - 1 atomic() block (1 COMMIT, 0 savepoints) - 1 atomic() + 100 nested atomic() savepoints (100 SAVEPOINT/RELEASE pairs) - 1 atomic() + bulk_create(100) (1 multi-row INSERT, 1 COMMIT) 2. SQLite SchemaEditor DDL cost as `newsroom_story` grows (0, 1000, 5000, 10000 rows, 5 trials): - add_field(nullable CharField) -> O(1) ALTER TABLE ADD COLUMN - alter_field(headline max_length 160 -> 200) -> O(N) _remake_table """ from __future__ import annotations import copy import statistics import sys import tempfile import time from datetime import datetime, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk UTC = timezone.utc def main() -> None: boot_desk() from django.core.management import call_command from django.db import connection, connections, models, transaction from django.db.backends.sqlite3.base import DatabaseWrapper from newsroom.models import Correction, Desk, Edition, Reporter, Story rec = Recorder("ch09-bench") # Part 1: File-backed SQLite transaction & savepoint benchmark (100 inserts, 7 trials) with tempfile.TemporaryDirectory() as tmpdir: db_path = str(Path(tmpdir) / "bench_tx.sqlite3") file_settings = copy.deepcopy(connection.settings_dict) file_settings["NAME"] = db_path file_conn = DatabaseWrapper(file_settings, alias="bench_file") connections["bench_file"] = file_conn try: call_command("migrate", database="bench_file", verbosity=0, interactive=False) metro = Desk.objects.using("bench_file").create( name="Metro", slug="metro", section_code="MTR" ) ada = Reporter.objects.using("bench_file").create( name="Ada", email="ada@desk.example", desk=metro ) ed = Edition.objects.using("bench_file").create( issue_date=datetime(2026, 11, 25, tzinfo=UTC).date(), slug="2026-11-25", title="Wednesday", status=Edition.Status.PUBLISHED, published_at=datetime(2026, 11, 25, 11, 0, tzinfo=UTC), ) story = Story.objects.using("bench_file").create( headline="Lead", slug="lead", body="Body", priority=1, status=Story.Status.PUBLISHED, published_at=datetime(2026, 11, 25, 10, 0, tzinfo=UTC), desk=metro, reporter=ada, edition=ed, ) ts = datetime(2026, 11, 25, 12, 0, tzinfo=UTC) def bench_file_mode(run_fn, trials: int = 7) -> float: Correction.objects.using("bench_file").all().delete() run_fn() # warm up samples: list[float] = [] for _ in range(trials): Correction.objects.using("bench_file").all().delete() t0 = time.perf_counter() run_fn() samples.append((time.perf_counter() - t0) * 1e3) return statistics.median(samples) def mode_autocommit(): for i in range(100): Correction.objects.using("bench_file").create( story=story, note=f"n{i}", issued_at=ts ) def mode_single_atomic(): with transaction.atomic(using="bench_file"): for i in range(100): Correction.objects.using("bench_file").create( story=story, note=f"n{i}", issued_at=ts ) def mode_nested_savepoints(): with transaction.atomic(using="bench_file"): for i in range(100): with transaction.atomic(using="bench_file"): Correction.objects.using("bench_file").create( story=story, note=f"n{i}", issued_at=ts ) def mode_atomic_bulk(): with transaction.atomic(using="bench_file"): Correction.objects.using("bench_file").bulk_create( [Correction(story=story, note=f"n{i}", issued_at=ts) for i in range(100)] ) results_tx = [ ("autocommit (100 commits)", 100, bench_file_mode(mode_autocommit)), ("1 atomic() + 100 savepoints", 1, bench_file_mode(mode_nested_savepoints)), ("1 atomic() (0 savepoints)", 1, bench_file_mode(mode_single_atomic)), ("1 atomic() + bulk_create(100)", 1, bench_file_mode(mode_atomic_bulk)), ] base_ms = results_tx[0][2] with rec.block("1. 100 Correction inserts on file-backed SQLite (7 trials, median ms)"): rec.emit(f"{'mode':<32} {'commits':>8} {'median_ms':>10} {'speedup':>9}") for label, commits, med in results_tx: rec.emit(f"{label:<32} {commits:8d} {med:10.3f} {base_ms / med:8.2f}x") finally: file_conn.close() del connections["bench_file"] # Part 2: SQLite ADD COLUMN (O(1)) vs _remake_table (O(N)) on in-memory SQLite with rec.block("2. SQLite SchemaEditor: ADD COLUMN vs _remake_table by table size (5 trials, ms)"): rec.emit(f"{'rows':>6} {'add_col_ms':>12} {'remake_ms':>12} {'ratio':>9}") metro = Desk.objects.get(slug="metro") ada = Reporter.objects.get(name="Ada") ed = Edition.objects.get(slug="2026-11-25") ts = datetime(2026, 11, 25, 10, 0, tzinfo=UTC) old_headline = Story._meta.get_field("headline") new_headline = copy.deepcopy(old_headline) new_headline.max_length = 200 for n_rows in (0, 1000, 5000, 10000): Story.objects.all().delete() if n_rows: Story.objects.bulk_create( [ Story( headline=f"Story {i}", slug=f"bench-ddl-{n_rows}-{i}", body="Standard newsroom body paragraph for schema rebuild timing.", priority=(i % 3) + 1, status=Story.Status.PUBLISHED, published_at=ts, desk=metro, reporter=ada, edition=ed, ) for i in range(n_rows) ], batch_size=1000, ) # Time O(1) nullable ADD COLUMN (then drop it each trial) add_samples: list[float] = [] for trial in range(5): f_tmp = models.CharField(max_length=80, null=True) f_tmp.set_attributes_from_name(f"tmp_kicker_{n_rows}_{trial}") t0 = time.perf_counter() with connection.schema_editor() as ed_ddl: ed_ddl.add_field(Story, f_tmp) add_samples.append((time.perf_counter() - t0) * 1e3) with connection.schema_editor() as ed_drop: ed_drop.remove_field(Story, f_tmp) # Time O(N) _remake_table via alter_field (headline max_length 160 -> 200 -> 160) remake_samples: list[float] = [] for trial in range(5): src = old_headline if trial % 2 == 0 else new_headline dst = new_headline if trial % 2 == 0 else old_headline t0 = time.perf_counter() with connection.schema_editor() as ed_ddl: ed_ddl.alter_field(Story, src, dst) remake_samples.append((time.perf_counter() - t0) * 1e3) # Ensure back to original max_length=160 if odd number of trials with connection.schema_editor() as ed_restore: ed_restore.alter_field(Story, new_headline, old_headline) add_med = statistics.median(add_samples) rem_med = statistics.median(remake_samples) rec.emit( f"{n_rows:6d} {add_med:12.3f} {rem_med:12.3f} {rem_med / add_med:8.1f}x" ) rec.write() if __name__ == "__main__": main()