Part III — Advanced Systems · Chapter 17 · Lesson 2 of 7 · 8 min read
Lesson 2: Parameterized Queries, Transactions, Discovery, Batch Inserts, and Upserts
Lesson level: Advanced
Purpose: Execute database work safely, atomically, and observably.
Learning objectives. Separate SQL structure from data; reason about transaction scope; inspect metadata safely; batch writes with bounded failure behavior; and design idempotent synchronization with verified upsert semantics.
Learning objectives
By the end of this lesson, you will be able to:
- write parameterized queries and explain why they prevent injection
- define clear query-result contracts
- group related writes in transactions with commit and rollback
- discover tables and columns through metadata
- perform batch inserts and upserts safely and idempotently
2.1 Parameters separate code from data
A parameterized query sends SQL structure and data values separately. The driver binds values as data, so a name such as O’Brien or a hostile string does not become executable SQL. String concatenation, by contrast, lets external data alter the query.
Unsafe pattern: building a query by joining the text WHERE sku = with a user-supplied value. Safe pattern: writing WHERE sku = ? or the adapter’s documented placeholder, then supplying the SKU in a separate parameter collection.
Parameters protect values, not identifiers. Table names, column names, sort directions, and SQL keywords generally cannot be bound as ordinary parameters. When they must vary, select them from a fixed allowlist owned by the module. Never accept arbitrary identifier text from a request.
Placeholder syntax can vary by driver: positional question marks, numbered placeholders, or named parameters. Hide that difference behind the adapter contract, or document which engines a query supports.
Illustrative safe sort. Accept a requested sort key only from the set name, sku, and updated_at. Map that key to a fixed SQL fragment. Reject any other value before constructing the statement.
Guided practice. Identify which elements can be parameterized in a query that filters by region, date range, and status, then sorts by a user-selected allowed column with an optional limit.
Common mistake. Escaping quotes manually is not a substitute for binding. Engine-specific escaping rules, encodings, and edge cases make manual escaping fragile.
2.2 Query result contracts
Every query should state its expected result: column names, types, nullability, key, ordering, and maximum size. Validate the actual result against that contract. A renamed column or changed type should fail early with an actionable error.
Bound result size. Unbounded queries can exhaust memory or exceed output budgets. Use an explicit limit for previews, pagination for large reads, or a streaming interface when the adapter documents one. Do not rely on a database view staying small.
Prefer explicit column lists to selecting all columns. An explicit list keeps the result schema stable when the table gains new fields and prevents accidental exposure of confidential columns.
Review prompt. Why does selecting all columns weaken both the schema contract and data-minimization policy?
2.3 Transactions define atomic units of work
A transaction groups operations so they commit together or roll back together. Transferring stock between warehouses is a classic example: decrementing one location and incrementing another must not be split by a failure.
Define the transaction boundary around the business invariant, not around a convenient block of code. Keep the boundary small enough to limit lock duration, but large enough to protect every operation that must remain consistent.
Illustrative transfer. Begin a transaction; verify the source location has sufficient quantity; decrement source stock; increment destination stock; write an audit row; commit. If any step fails, roll back and return a classified error. Confirm the adapter’s transaction syntax and context-management behavior before implementation.
Do not perform slow external calls while holding a transaction open. A network request inside the transaction can prolong locks and create failure states that the database cannot roll back. Gather approved external data first or design an explicit outbox pattern.
Isolation levels differ by engine. Concurrent transactions can encounter lost updates, write conflicts, deadlocks, or serialization failures. Verify the engine’s behavior and use conditional updates, constraints, row versioning, or retry policies where appropriate.
Retry only operations designed to be safe on retry, and only for failures classified as transient. A duplicate-key violation or validation failure is not fixed by repetition. Bound retries and record the final outcome.
Guided practice. Write the invariant for a payment allocation: total allocated amount must not exceed the payment amount. Identify the reads and writes that must share one transaction and the database constraint that can add a second safeguard.
Common mistakes. Committing after each statement in a multi-step change; catching an error without rolling back; retrying non-idempotent writes; and leaving a transaction open after an exception.
2.4 Discovery and metadata inspection
Discovery reads metadata such as tables, views, columns, types, keys, and indexes. It is useful for diagnostics, migration planning, and schema-drift checks.
Treat discovery as privileged. Metadata can reveal sensitive table names and system structure. Grant it to administrative or diagnostic workflows that need it, not to every application module.
Do not generate production queries from arbitrary discovered names. Use discovery to compare the live schema with an approved contract. If the schema differs, fail or route the change through review.
Illustrative drift check. Discover the products table columns and compare them with the expected names, types, nullability, and key. Report missing, unexpected, or changed fields. Do not attempt automatic schema correction.
Review prompt. Why can dynamic query generation from discovered metadata conflict with least privilege and stable interfaces?
2.5 Batch inserts
Batching sends many parameter sets for one statement. It can reduce round trips, but it also changes failure behavior. Decide whether a batch is all-or-nothing, partially accepted, or split into chunks with separate outcomes.
Validate rows before the batch begins. The database should remain the final authority for constraints, but basic schema and range validation in PeaLang produces clearer errors and avoids wasted database work.
Illustrative policy. Validate all candidate products; reject the import if more than an approved error threshold fails validation; insert valid rows in bounded chunks; wrap each chunk in a transaction; record chunk identifiers and outcomes; stop on non-transient database errors.
Choose chunk size from measured behavior and resource limits, not from a universal number. Large chunks increase memory use and rollback scope. Small chunks increase overhead and the number of partial outcomes to reconcile.
Report driver-provided row counts carefully. Some drivers report affected rows inconsistently for batches or upserts. If exact accounting is required, reconcile through keys and post-load queries.
2.6 Upsert and merge semantics
An upsert inserts a missing record or updates an existing record identified by a unique key. It is useful for synchronization, but the business rule must define which fields change, which source is authoritative, and how stale updates are rejected.
A safe upsert depends on a real uniqueness constraint. Without one, concurrent writers can create duplicates. Read-then-write emulation is vulnerable to races unless protected by an appropriate transaction and locking strategy.
The project materials record SQLite upsert support. Other adapters are described as contracts and need engine-specific implementation and validation before their merge behavior is treated as available. Syntax and conflict semantics vary across database engines.
Illustrative synchronization rule. Match by SKU; insert unseen products; update name, price, and active flag only when the incoming source version is newer; never overwrite the local creation timestamp; record inserted, updated, unchanged, and rejected outcomes.
Idempotency check. Apply the same batch twice. The second run should create no duplicates and should report no unexpected changes. Then apply an older version and verify that it does not overwrite newer data.
Common mistakes. Updating every field on conflict; losing deletes because upsert cannot represent removal; treating a missing incoming field as null; and ignoring concurrent updates between validation and write.
Common mistakes
- Building SQL by string concatenation: always pass values as parameters.
- Parameterizing identifiers: table and column names cannot be parameters; validate them against an allow-list.
- Long-running transactions: keep transactions short to avoid locks and retries.
- Forgetting rollback on failure: wrap each unit of work so any error rolls it back.
- Non-idempotent loads: use upserts with stable keys so a rerun does not duplicate rows.
- Unbounded batches: size batches so that memory and transaction length stay predictable.
2.7 Hands-on lab: Safe inventory synchronization
Scenario. Synchronize a synthetic supplier product feed into the local SQLite catalog from Lesson 1. The feed may contain new products, changed products, unchanged products, invalid rows, and stale versions.
- Define the feed contract and the catalog key.
- Validate every feed row before database work.
- Use parameters for all values and allowlists for any variable sort or filter field.
- Process valid rows in bounded transactional chunks.
- Use the verified SQLite upsert path or document why the lab is limited to inserts.
- Reject stale versions according to the synchronization rule.
- Run the same feed twice to demonstrate idempotency.
- Run a drift check against the expected catalog schema.
Required tests. Include a SKU containing quotation marks, an attempted SQL fragment in a text field, a duplicate SKU within the feed, a stale update, a missing price, an invalid active flag, a forced failure in the middle of a chunk, and a closed database connection.
Evidence. Record expected and observed outcomes separately. For each chunk, record row keys, transaction outcome, error category, and retry decision. Do not record secrets or unnecessary product attributes in the evidence log.
Acceptance criteria. No input value is concatenated into SQL; failed chunks leave no partial state; repeated feeds are idempotent; stale versions do not overwrite current rows; invalid rows are reported; connections close; and server-engine claims remain absent unless separately tested.
Review, challenge, and summary
Review questions. Why can parameters not protect identifiers? What defines a transaction boundary? When is retrying unsafe? Why is metadata discovery privileged? How does chunk size affect rollback scope? Why must upsert depend on a uniqueness constraint?
Applied challenge. Extend synchronization to deactivate products that disappear from the supplier feed. Define whether absence means discontinued, temporarily missing, or an incomplete extract. Require an explicit completeness signal before applying deactivation.
Lesson summary. Safe SQL integration binds values as parameters, validates result contracts, protects invariants with focused transactions, restricts discovery, batches with clear outcomes, and uses only verified engine-specific upsert behavior.
Lesson status: Ready for review.