Skip to content

Commit 92d5585

Browse files
committed
Add structured table profiling
1 parent 3120ae1 commit 92d5585

16 files changed

Lines changed: 391 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# Changelog
22

3+
## 0.1.15 - 2026-05-16
4+
5+
### Added
6+
- Add table profiling APIs with structured `ProfilingQueries` outputs.
7+
- Add prompt support for rendering target-table columns in profiler instructions.
8+
- Add unit and integration coverage for profiling prompt construction and output shape.
9+
10+
### Changed
11+
- Limit profiler policy context to generic critical rules and add single-table query guidance.
12+
313
## 0.1.11 - 2026-04-18
414

515
### Added

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "piglets"
3-
version = "0.1.14"
3+
version = "0.1.15"
44
description = "A modular text-to-SQL toolkit."
55
readme = "README.md"
66
requires-python = ">=3.10"

‎src/piglets/__init__.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .planning import LogicalPlanner as LogicalPlanner
99
from .policies import RuleMode as RuleMode
1010
from .policies import SemanticRules as SemanticRules
11+
from .profiling import Profiler as Profiler
1112
from .pruning import Pruner as Pruner
1213
from .semantic_linking import SemanticLinker as SemanticLinker
1314
from .types import (
@@ -20,6 +21,8 @@
2021
LogicalSteps as LogicalSteps,
2122
PreservationColumns as PreservationColumns,
2223
PreservationSet as PreservationSet,
24+
ProfilingQuery as ProfilingQuery,
25+
ProfilingQueries as ProfilingQueries,
2326
PruningColumns as PruningColumns,
2427
SemanticLinkingResult as SemanticLinkingResult,
2528
Table as Table,
@@ -55,7 +58,11 @@
5558
"SemanticLinkingResult",
5659
"Table",
5760
# Pruning
58-
"Pruner"
61+
"Pruner",
62+
# Profiling
63+
"Profiler",
64+
"ProfilingQuery",
65+
"ProfilingQueries",
5966
]
6067

6168

‎src/piglets/database/database_connector.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ def get_database_schema(self) -> Database:
6969
for table_name in self.inspector.get_table_names():
7070
columns = []
7171
for column_info in self.inspector.get_columns(table_name):
72+
# TODO: Populate column descriptions when metadata retrieval supports them.
7273
column = Column(name=column_info["name"], data_type=str(column_info["type"]))
7374
columns.append(column)
7475
table = Table(name=table_name, columns=columns)

‎src/piglets/policies/semantic_rules.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,15 @@ class SemanticRules(BaseModel):
2323
metrics: RuleMode = RuleMode.STANDARD
2424
ambiguity: RuleMode = RuleMode.WARN
2525

26-
def to_string(self) -> str:
26+
def critical_rules_to_string(self) -> str:
2727
prompts_dir = Path(__file__).resolve().parent / "prompts"
28+
return read_markdown_file(prompts_dir / "critical_rules.md").strip()
29+
30+
def to_string(self) -> str:
2831
sections = [
29-
read_markdown_file(prompts_dir / "critical_rules.md").strip(),
32+
self.critical_rules_to_string(),
3033
]
34+
prompts_dir = Path(__file__).resolve().parent / "prompts"
3135

3236
for domain, mode in (
3337
("joins", self.joins),

‎src/piglets/profiling/__init__.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from .profiler import Profiler as Profiler
2+
3+
__all__ = [
4+
"Profiler",
5+
]

‎src/piglets/profiling/profiler.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
from langchain.chat_models import init_chat_model
2+
3+
from piglets.policies import SemanticRules
4+
from piglets.types import (
5+
ProfilingQueries,
6+
SemanticLinkingResult,
7+
Table,
8+
)
9+
10+
11+
class Profiler():
12+
def __init__(
13+
self,
14+
model_name: str,
15+
model_provider: str = None,
16+
rules: SemanticRules | None = None,
17+
):
18+
self.model_name = model_name
19+
self.model_provider = model_provider
20+
self.rules = rules or SemanticRules()
21+
22+
def profile_table(
23+
self,
24+
natural_language_query: str,
25+
database_type: str | None,
26+
table: Table,
27+
semantic_linking_result: SemanticLinkingResult,
28+
) -> ProfilingQueries:
29+
30+
llm = init_chat_model(model=self.model_name, model_provider=self.model_provider)
31+
llm = llm.with_structured_output(ProfilingQueries)
32+
critical_rules = self.rules.critical_rules_to_string()
33+
sql_type = f"{database_type.upper()} SQL" if database_type else "SQL"
34+
semantic_table_functions_lower = {k.lower(): v for k, v in semantic_linking_result.table_functions.items()}
35+
semantic_table_function = semantic_table_functions_lower.get(table.name.lower(), "Unknown Role")
36+
37+
# TODO: Include column descriptions here once Column supports them.
38+
DATA_PROFILE_QUERY_GENERATION_PROMPT = f"""
39+
*** TASK CONTEXT ***
40+
You are an agent exploring a database table to verify its
41+
relevance to a user question.
42+
You must not explore randomly. You must verify if this
43+
table fits its anticipated role.
44+
{critical_rules}
45+
46+
*** TARGET TABLE: {table.name} ***
47+
Columns:
48+
{table.columns_to_string()}
49+
50+
*** USER QUESTION ***
51+
{natural_language_query}
52+
53+
*** ANTICIPATED ROLE ***
54+
This table was identified as: {semantic_table_function}. Use this to
55+
guide your exploration.
56+
57+
*** YOUR MISSION ***
58+
Generate 3-8 {sql_type} queries to investigate. **Focus on
59+
understanding the table’s semantics and utility.**
60+
Each query must profile only the target table, {table.name}.
61+
Do not join to, reference, or infer data from any other table.
62+
63+
**Motivation for Exploration**:
64+
1. **Semantic Alignment**: Check distinct values to understand what the column *means* versus what the query
65+
*needs*. (e.g., If column is ’type’, does it contain the specific
66+
categories? If ’status’, does it contain values like ’Active’
67+
or code ’1’?)
68+
2. **Granularity & Scope**: Verify the table’s grain (e.g., is
69+
it one row per Order or per Item?). This determines if it
70+
supports the required aggregations.
71+
3. **Bridge/Connectivity**: If this looks like a linking table,
72+
verify the Foreign Keys are populated (not all NULL) to
73+
ensure it can actually serve as a bridge.
74+
4. **Data Quality**: Are critical columns (targets for filters
75+
or answers) usable, or are they mostly NULL?
76+
77+
*** OUTPUT FORMAT ***
78+
Return structured data matching the ProfilingQueries schema:
79+
- exploratory_queries: a list of 3-8 objects.
80+
- Each object must contain:
81+
- motivation: a concise reason for running the profiling query.
82+
- query: the {sql_type} query string.
83+
84+
Do not wrap queries in markdown fences. Put the reason for each
85+
query in the motivation field, not in SQL comments.
86+
Generate your exploration queries:
87+
"""
88+
89+
profiling_queries = llm.invoke(DATA_PROFILE_QUERY_GENERATION_PROMPT)
90+
91+
return profiling_queries

‎src/piglets/types/__init__.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212
Database as Database,
1313
Table as Table,
1414
)
15+
from .profiling import (
16+
ProfilingQuery as ProfilingQuery,
17+
ProfilingQueries as ProfilingQueries,
18+
)
1519
from .pruning import (
1620
DeletionColumns as DeletionColumns,
1721
DeletionSet as DeletionSet,
@@ -31,10 +35,13 @@
3135
"Column",
3236
"Database",
3337
"Table",
38+
# profiling types
39+
"ProfilingQuery",
40+
"ProfilingQueries",
3441
# pruning types
3542
"DeletionColumns",
3643
"DeletionSet",
3744
"PreservationColumns",
3845
"PreservationSet",
39-
"PruningColumns"
46+
"PruningColumns",
4047
]

‎src/piglets/types/database.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ class Table(BaseModel):
1313
name: str = Field(description="The name of the table.")
1414
columns: list[Column] = Field(description="The list of columns in the table.")
1515

16+
def columns_to_string(self) -> str:
17+
"""Export the table columns as one prompt-readable line per column."""
18+
return "\n".join(
19+
f"{column.name} ({column.data_type}):"
20+
for column in self.columns
21+
)
22+
1623
class Database(BaseModel):
1724
"""The schema of a database, including its name and tables."""
1825

‎src/piglets/types/profiling.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from pydantic import BaseModel
2+
3+
class ProfilingQuery(BaseModel):
4+
"""A single query generated for profiling the database."""
5+
6+
motivation: str = ""
7+
query: str = ""
8+
9+
class ProfilingQueries(BaseModel):
10+
"""A list of queries generated for profiling the database."""
11+
12+
exploratory_queries: list[ProfilingQuery] = []

0 commit comments

Comments
 (0)