Tables, PDFs, Scanned Docs & Text-to-SQL
Query structured tables and document excerpts safely with read-only SQL enforcement, schema-checked result validation, OCR/PDF provenance tracking, and pytest + GitHub Actions CI.
Enterprise data rarely arrives as clean markdown paragraphs. Facts often live inside relational tables, multi-column PDFs, invoices, and OCR-scanned documents where layout and scan quality affect accuracy.
This module assumes PDF text, table data, and OCR output have already been extracted. It focuses on provenance-aware retrieval over those extracted excerpts and structured rows, paired with defense-in-depth read-only SQL execution verified with pytest and GitHub Actions.
Enterprise Scenario: Northwind Freight
Northwind’s operations team needs to answer questions such as:
- What was the total freight cost for a customer during a given quarter?
- Which invoice contains the disputed surcharge?
- Which page of the scanned contract defines the surcharge policy?
- Does the invoice total agree with the corresponding relational database record?
A reliable assistant must combine structured SQL queries with provenance-aware document retrieval, preserve source references, and avoid inventing answers when extracted data is incomplete or unreliable.
What You Will Build
- Document excerpt, table row, and SQL result schemas: Represent pre-extracted PDF/OCR excerpts with source, page, and OCR confidence metadata, structured
TableRowrecords with JSON-compatible scalar values, and read-only SQL results with strict Pydantic v2 validation and column/row consistency. - Provenance-aware excerpt lookup: Search pre-extracted document and OCR excerpts while surfacing low-confidence OCR warnings (a warning signal for noisy scans, not proof that extracted text is accurate).
- Defense-in-depth read-only SQL guardrails: Combine string-literal/comment-aware SQL checks with a required non-empty table allow-list,
PRAGMA query_only = ON,sqlite3.Connection.set_authorizer()strictmain-database, table, and function allow-lists, parameterized bindings, duplicate-column detection, and row-cap truncation detection. - Safe read-only SQL execution assignment + CI: Implement
execute_safe_read_only_queryin the practice assignment and verify withpytestand GitHub Actions.
1. Pre-Extracted Docs/OCR, Table Rows, and Defense-in-Depth SQL
- Working with pre-extracted PDFs, OCR output, and table rows: Full PDF parsing and OCR engines are heavy pipelines outside a 1-2h lab. Here we start from already-extracted excerpts and
TableRowrecords (wherevaluesmaps non-blank column names to JSON-compatible scalar values such as strings, numbers, booleans, orNone), keepingsource_name,page_number, andocr_confidenceattached. Nested dictionaries, lists, and non-finite floats are rejected. Treatocr_confidenceas a warning signal, not proof that extracted text is correct. - Why naive regex/keyword checks alone are not enough for SQL: Scanning raw text with regexes treats words and semicolons inside string literals (such as
SELECT 'update' AS description;) or comments like SQL tokens, while missing quoted identifiers, CTEs, and subqueries. Keep preliminary checks aware of string literals, quoted identifiers (double quotes, backticks, and brackets), and comments, reject multiple statements or trailing content after a semicolon, and let SQLite enforce read-only execution and table access. - Enforcing strict main-database, table, and function allow-lists in SQLite: Require an explicit non-empty
allowed_tablesset by default (unrestricted access, if ever enabled intentionally, is a less restrictive mode and not a safe default). CombinePRAGMA query_only = ON(which remains enabled on the supplied connection after the function returns) andsqlite3.Connection.set_authorizer()to restrict reads strictly toschema_name == "main"and approved tables (blocking attached databases such asarchive_dbeven if they share an allowed table name) and allow only approved SQL functions rather than blanketSQLITE_FUNCTIONapproval, because custom registered SQL functions could have side effects even inside aSELECT. These controls are complementary safeguards, not substitutes for a genuinely read-only database connection.
Retrieval Versus SQL Decision Guide
| User question | Preferred approach |
|---|---|
| Calculate total freight cost | SQL |
| Find a clause in a contract | Document retrieval |
| Identify an invoice’s page number | Document retrieval |
| Compare invoice amount with database total | SQL + document retrieval |
| Answer using unreliable OCR | Warn or abstain |
2. Step-by-Step Build Walkthrough
- Set up the
fde-02-3repository and virtual environment: Create the package layout, configure.env.example,.gitignore, andpyproject.toml, and install editable dev dependencies.macOS / Linux:
mkdir -p fde-02-3/src/fde_02_3 fde-02-3/tests cd fde-02-3 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .envWindows (PowerShell):
mkdir fde-02-3 cd fde-02-3 py -m venv .venv .\.venv\Scripts\Activate.ps1 py -m pip install --upgrade pip py -m pip install -e ".[dev]" Copy-Item .env.example .envWindows (CMD):
mkdir fde-02-3 cd fde-02-3 py -m venv .venv .venv\Scripts\activate.bat python -m pip install --upgrade pip python -m pip install -e ".[dev]" copy .env.example .env - Define strict schemas for document excerpts, table rows, and SQL results: Enforce
extra="forbid",strict=True, non-blank strings, finite floats, JSON-compatible scalar table values,row_count == len(rows), uniquecolumns, and matching row keys vs.columns.import math from typing import Any from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator def _require_finite(value: float, field_name: str) -> float: if not math.isfinite(value): raise ValueError(f"{field_name} must be finite") return value def _require_non_blank(value: str, field_name: str) -> str: if not value.strip(): raise ValueError(f"{field_name} must not be blank") return value class DocumentExcerpt(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) excerpt_id: str = Field(min_length=1) source_name: str = Field(min_length=1) page_number: int = Field(ge=1) text: str = Field(min_length=1) ocr_confidence: float = Field(default=1.0, ge=0.0, le=1.0) @field_validator("excerpt_id", "source_name", "text") @classmethod def _validate_non_blank_str(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) @field_validator("ocr_confidence") @classmethod def _validate_finite_ocr(cls, value: float) -> float: return _require_finite(value, "ocr_confidence") class TableRow(BaseModel): """Represents one row from a pre-extracted or relational table.""" model_config = ConfigDict(extra="forbid", strict=True) table_name: str = Field(min_length=1) row_index: int = Field(ge=0) values: dict[str, Any] @field_validator("table_name") @classmethod def _validate_table_name(cls, value: str) -> str: return _require_non_blank(value, "table_name") @field_validator("values") @classmethod def _validate_scalar_values(cls, values: dict[str, Any]) -> dict[str, Any]: for column, value in values.items(): _require_non_blank(column, "column name") if value is None or isinstance(value, bool): continue if isinstance(value, int): continue if isinstance(value, float): _require_finite(value, f"Column '{column}'") continue if isinstance(value, str): continue raise ValueError( f"Column '{column}' must contain a JSON-compatible scalar value" ) return values class ExcerptMatch(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) excerpt_id: str = Field(min_length=1) source_name: str = Field(min_length=1) page_number: int = Field(ge=1) score: float ocr_confidence: float = Field(ge=0.0, le=1.0) low_ocr_warning: bool text: str = Field(min_length=1) @field_validator("score", "ocr_confidence") @classmethod def _validate_finite_floats(cls, value: float, info) -> float: return _require_finite(value, info.field_name) class QueryExecutionResult(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) sql: str = Field(min_length=1) row_count: int = Field(ge=0) columns: list[str] rows: list[dict[str, Any]] truncated: bool @field_validator("sql") @classmethod def _validate_sql_non_blank(cls, value: str) -> str: return _require_non_blank(value, "sql") @model_validator(mode="after") def _validate_result_consistency(self) -> "QueryExecutionResult": if self.row_count != len(self.rows): raise ValueError("row_count must match len(rows)") if len(self.columns) != len(set(self.columns)): raise ValueError("columns must contain unique names") expected_cols = set(self.columns) for row in self.rows: if set(row.keys()) != expected_cols: raise ValueError( "Each row must contain the exact declared columns" ) return self - Implement pre-extracted document/OCR excerpt search: Score excerpts using a simple heuristic overlap score while flagging
low_ocr_warningwheneverocr_confidence < min_ocr_confidence.import re def _tokens(text: str) -> set[str]: return set(re.findall(r"[a-z0-9_]+", text.lower())) def search_document_excerpts( query: str, excerpts: list[DocumentExcerpt], top_k: int = 5, min_ocr_confidence: float = 0.75, ) -> list[ExcerptMatch]: _require_non_blank(query, "query") if top_k < 1: raise ValueError("top_k must be at least 1") if not math.isfinite(min_ocr_confidence) or not ( 0.0 <= min_ocr_confidence <= 1.0 ): raise ValueError( "min_ocr_confidence must be finite and within [0.0, 1.0]" ) q_toks = _tokens(query) if not q_toks or not excerpts: return [] matches: list[ExcerptMatch] = [] for exc in excerpts: e_toks = _tokens(exc.text) overlap = len(q_toks.intersection(e_toks)) if overlap == 0: continue score = overlap / math.sqrt(len(e_toks) if e_toks else 1) matches.append( ExcerptMatch( excerpt_id=exc.excerpt_id, source_name=exc.source_name, page_number=exc.page_number, score=score, ocr_confidence=exc.ocr_confidence, low_ocr_warning=( exc.ocr_confidence < min_ocr_confidence ), text=exc.text, ) ) matches.sort(key=lambda item: (-item.score, item.excerpt_id)) return matches[:top_k] - Implement literal/comment-aware SQL pre-check, required non-empty table allow-list,
PRAGMA query_only = ON, and main-db + function-restricted authorizer: Reject multiple statements or trailing content after a semicolon, require a non-emptyallowed_tablesset by default, and enforce strictmain-database reads, allowed tables, and approved SQL functions in_authorizer.import sqlite3 _FORBIDDEN_KEYWORDS = { "insert", "update", "delete", "drop", "alter", "create", "attach", "detach", "replace", "truncate", "pragma", "vacuum", "reindex", "savepoint", "release", } _ALLOWED_SQL_FUNCTIONS = { "count", "sum", "avg", "min", "max", "total", "coalesce", "ifnull", "nullif", "abs", "round", "lower", "upper", "trim", "ltrim", "rtrim", "length", "substr", "substring", } def _scan_sql_outside_literals_and_comments( sql: str, ) -> tuple[list[str], int, bool]: """Return SQL keywords outside strings/identifiers, semicolon count, and whether significant content follows a semicolon. """ tokens: list[str] = [] semicolons = 0 saw_semicolon = False trailing_after_semicolon = False i = 0 n = len(sql) word_buf: list[str] = [] def _flush_word() -> None: if word_buf: tokens.append("".join(word_buf).lower()) word_buf.clear() while i < n: ch = sql[i] if ch.isspace(): _flush_word() i += 1 continue if ch == "-" and i + 1 < n and sql[i + 1] == "-": _flush_word() if saw_semicolon: trailing_after_semicolon = True nl = sql.find("\n", i + 2) i = n if nl == -1 else nl + 1 continue if ch == "/" and i + 1 < n and sql[i + 1] == "*": _flush_word() if saw_semicolon: trailing_after_semicolon = True close = sql.find("*/", i + 2) if close == -1: raise ValueError("Unterminated SQL block comment") i = close + 2 continue if ch in {"'", '"', "`", "["}: _flush_word() if saw_semicolon: trailing_after_semicolon = True closing = "]" if ch == "[" else ch i += 1 while i < n: if sql[i] == closing: if ( closing != "]" and i + 1 < n and sql[i + 1] == closing ): i += 2 continue i += 1 break i += 1 else: raise ValueError( "Unterminated SQL string or quoted identifier" ) continue if ch == ";": _flush_word() semicolons += 1 saw_semicolon = True i += 1 continue if ch.isalnum() or ch == "_": if saw_semicolon: trailing_after_semicolon = True word_buf.append(ch) else: if saw_semicolon: trailing_after_semicolon = True _flush_word() i += 1 _flush_word() return tokens, semicolons, trailing_after_semicolon def validate_read_only_sql(sql: str) -> str: _require_non_blank(sql, "sql") stripped = sql.strip() tokens, semicolons, trailing_after_semicolon = ( _scan_sql_outside_literals_and_comments(stripped) ) if semicolons > 1 or trailing_after_semicolon: raise ValueError( "Multiple SQL statements or trailing content after semicolon " "are not allowed" ) without_trailing_semi = ( stripped[:-1].strip() if stripped.endswith(";") else stripped ) if not tokens: raise ValueError("SQL query must contain keywords") if tokens[0] not in {"select", "with"}: raise ValueError( f"Only read-only SELECT or WITH queries are allowed, got: {tokens[0]}" ) for kw in _FORBIDDEN_KEYWORDS: if kw in tokens: raise ValueError(f"Forbidden SQL keyword detected: {kw}") return without_trailing_semi def execute_safe_read_only_query( conn: sqlite3.Connection, sql: str, params: tuple[Any, ...] = (), allowed_tables: set[str] | None = None, max_rows: int = 100, ) -> QueryExecutionResult: if max_rows < 1: raise ValueError("max_rows must be at least 1") if allowed_tables is None or len(allowed_tables) == 0: raise ValueError( "allowed_tables must be a non-empty set of table names" ) normalized_allowed: set[str] = set() for tbl in allowed_tables: _require_non_blank(tbl, "allowed_tables entry") normalized_allowed.add(tbl.strip().lower()) validated_sql = validate_read_only_sql(sql) blocked_tables: list[str] = [] blocked_functions: list[str] = [] def _authorizer( action_code: int, arg1: str | None, arg2: str | None, db_name: str | None, _trigger_name: str | None, ) -> int: if action_code == sqlite3.SQLITE_READ: table_name = (arg1 or "").lower() schema_name = (db_name or "").lower() disallowed_db = schema_name != "main" if disallowed_db or table_name not in normalized_allowed: label = ( f"{schema_name}.{table_name}" if (disallowed_db and table_name) else table_name ) if label and label not in blocked_tables: blocked_tables.append(label) return sqlite3.SQLITE_DENY return sqlite3.SQLITE_OK if action_code == sqlite3.SQLITE_FUNCTION: fn_name = (arg2 or "").lower() if not fn_name or fn_name not in _ALLOWED_SQL_FUNCTIONS: if fn_name not in blocked_functions: blocked_functions.append(fn_name) return sqlite3.SQLITE_DENY return sqlite3.SQLITE_OK if action_code == sqlite3.SQLITE_SELECT: return sqlite3.SQLITE_OK return sqlite3.SQLITE_DENY conn.execute("PRAGMA query_only = ON") conn.set_authorizer(_authorizer) try: cursor = conn.cursor() cursor.execute(validated_sql, params) raw_columns = [ col[0] for col in (cursor.description or ()) ] fetched = cursor.fetchmany(max_rows + 1) except sqlite3.DatabaseError as exc: if blocked_tables: raise ValueError( f"Query references disallowed tables: " f"{', '.join(sorted(blocked_tables))}" ) from exc if blocked_functions: raise ValueError( f"Query references disallowed SQL functions: " f"{', '.join(sorted(blocked_functions))}" ) from exc raise ValueError( f"Blocked or invalid read-only SQL query: {exc}" ) from exc finally: conn.set_authorizer(None) if len(raw_columns) != len(set(raw_columns)): raise ValueError( "Query returned duplicate column names. Use unique SQL aliases." ) truncated = len(fetched) > max_rows kept = fetched[:max_rows] rows = [ dict(zip(raw_columns, row)) for row in kept ] return QueryExecutionResult( sql=validated_sql, row_count=len(rows), columns=raw_columns, rows=rows, truncated=truncated, ) - Run tests and commit to Git: Verify deterministic unit tests with
pytest, add.github/workflows/pytest.yml, and commit to Git.python -m pytest -v git status git add . git commit -m "Complete FDE module 02.3"
Production Engineering Note
The SQL guardrails in this lab demonstrate defense-in-depth controls for SQLite. They are not a complete SQL sandbox or a substitute for database-level access controls. Production systems should additionally use least-privilege database credentials, read-only roles or connections, query timeouts, resource limits, audit logging, and carefully controlled schema access.
3. Common Pitfalls and Operational Hygiene
- Treating
PRAGMA query_only = ONorset_authorizer()as a full replacement for a read-only database connection: Both are complementary safeguards, andPRAGMA query_only = ONstays active on the supplied connection after the call returns; in production also use a genuinely read-only connection/role and keep custom functions off untrusted query paths. - Omitting
allowed_tables, ignoring attached databases, or allowing arbitrary SQL functions: Require a non-emptyallowed_tablesset by default, enforceschema_name == "main"on reads, and restrictSQLITE_FUNCTIONto approved read-only functions. - Accepting nested table values or duplicate SQL result column names: Keep
TableRow.valueslimited to JSON-compatible scalar values and reject blank column names, nested dictionaries, lists, and non-finite floats. Require unique SQL result column names or explicit aliases because duplicate names can silently overwrite values when rows are converted into dictionaries. - Treating
ocr_confidenceas proof of accuracy or ignoringmax_rows + 1truncation checks: OCR confidence warns of noisy scan text rather than proving correctness, and fetchingmax_rows + 1rows detects truncation accurately.
4. Completion Criteria
DocumentExcerpt,TableRow,ExcerptMatch, andQueryExecutionResultenforce strict validation, non-blank strings, finite floats, JSON-compatible scalar table values, and row/column consistency.TableRowrejects nested values, blank column names, and non-finite floats.search_document_excerptsreturns ranked matches with source, page, and OCR confidence warning flags.validate_read_only_sqlandexecute_safe_read_only_queryrequire non-emptyallowed_tables, enforce read-only execution viaPRAGMA query_only = ONandset_authorizer()with strictmain-database, table, and SQL function allow-lists, block unsafe SQL and disallowed tables, reject duplicate result column names, and track row-cap truncation.- All
pytesttests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Build this
In fde-02-3, implement execute_safe_read_only_query(conn: sqlite3.Connection, sql: str, params: tuple[Any, ...] = (), allowed_tables: set[str] | None = None, max_rows: int = 100) -> QueryExecutionResult in src/fde_02_3/sql_guard.py that validates max_rows >= 1, requires a non-empty allowed_tables set by default (validating non-blank table names), runs preliminary SQL checks plus PRAGMA query_only = ON and a sqlite3.Connection.set_authorizer() hook restricting reads strictly to schema_name == "main" and allowed tables, and approved SQL functions, and returns a QueryExecutionResult containing:
sql(str): single read-only query string.row_count(int): number of returned rows (matchinglen(rows)).columns(list[str]): ordered, unique column names from the cursor description.rows(list[dict[str, Any]]): up tomax_rowsrows mapped to column names (matchingcolumns).truncated(bool):Trueiffetchmany(max_rows + 1)returns more thanmax_rowsrows, elseFalse.
Add unit tests in tests/test_sql_guard.py and tests/test_docs_tables.py covering pre-extracted PDF/OCR excerpt lookup and TableRow validation (including accepted scalar values and rejection of nested dictionaries, lists, blank column names, and non-finite floats), quoted/bracketed/backtick identifiers containing reserved words or semicolons, schema-qualified names, CTEs and subqueries, comments and string literals containing reserved words or semicolons, trailing content or comments after a semicolon, unterminated strings/comments, attached databases even when sharing an allowed table name, missing or empty allowed_tables, disallowed tables, custom/disallowed SQL functions, missing or empty authorizer function names, missing or non-main schema names, write/DDL/multi-statement rejection, duplicate SQL result column names and acceptance of unique aliases, max_rows < 1 validation, and row-cap truncation. Then run python -m pytest -v and push fde-02-3 (including .github/workflows/pytest.yml) to GitHub.
Stretch Challenge - Build a Northwind Evidence Response
Implement a function that accepts a business question, retrieves relevant document excerpts, executes an approved read-only SQL query when structured data is required, and returns:
- The answer
- SQL result evidence, where applicable
- Document source and page references
- OCR confidence warnings
- An explicit abstention when the available evidence is insufficient
Do not allow the assistant to present unsupported values as verified facts.
Test your understanding
- What specific guardrails are required before executing model-generated SQL against a database?
- Why do PDFs, tables, and OCR-scanned documents break naive plain-text chunking?
- How do you combine structured SQL table queries with unstructured document/OCR excerpts in an enterprise assistant?
- Why should you enforce an explicit row cap and parameterized bindings on text-to-SQL outputs?
- How does tracking document source, page, and OCR confidence protect downstream answers?
Reveal self-review answers (attempt the questions first)
- SQL execution guardrails: Enforce read-only statements (
SELECT/WITH ... SELECTonly), scan outside string literals, quoted identifiers, and comments, block stacked statements and trailing content after a semicolon, and block mutating/DDL/administrative keywords. Require an explicit non-empty table allow-list enforced viaset_authorizer()(strictmaindatabase and SQL function checks) andPRAGMA query_only = ONalongside a genuinely read-only connection. Use parameterized inputs and apply a row limit. - PDFs, tables, and OCR quirks: Flattening multi-column layouts, tables, or low-confidence OCR text into raw word streams destroys row-column relationships, splits headers from values, and mixes noisy scan artifacts into embeddings.
- Combining tables and document excerpts: Route exact counts, totals, and structured filters to validated read-only SQL against relational tables, and retrieve narrative policy or exception excerpts from chunked documents with provenance metadata.
- Row caps and parameterized bindings: Unbounded queries can return huge result sets that blow context windows or slow down endpoints, while string-interpolating untrusted values risks injection or syntax errors from quotes and special characters.
- Provenance and OCR confidence: Recording document ID, page number, and OCR confidence lets callers surface low-confidence scan warnings or abstain when OCR text is too noisy to trust.
Questions or notes on this module?