Skip to content

Commit a40945c

Browse files
committed
add query execution and profiling results
1 parent 92d5585 commit a40945c

20 files changed

Lines changed: 968 additions & 72 deletions

‎CHANGELOG.md‎

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

3+
## 0.1.16 - 2026-05-17
4+
5+
### Added
6+
- Add typed SQL query and query result models, including prompt-readable result rendering.
7+
- Add query execution support to `DatabaseConnector`.
8+
- Add database type metadata to `Database` schemas.
9+
- Add table profile result models and end-to-end table profiling from generated queries through executed evidence.
10+
11+
### Changed
12+
- Move profiling query outputs onto the shared SQL query model shape.
13+
- Make semantic linking optional for profiling while preserving the unknown-role fallback.
14+
- Require `Profiler` to be initialized with a `Database` so profiling prompts can use the database type.
15+
316
## 0.1.15 - 2026-05-16
417

518
### 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.15"
3+
version = "0.1.16"
44
description = "A modular text-to-SQL toolkit."
55
readme = "README.md"
66
requires-python = ">=3.10"

‎src/piglets/__init__.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
URL as URL,
55
database_name_from_connection as database_name_from_connection,
66
database_name_from_connection_string as database_name_from_connection_string,
7+
database_type_from_connection as database_type_from_connection,
78
)
89
from .planning import LogicalPlanner as LogicalPlanner
910
from .policies import RuleMode as RuleMode
@@ -23,8 +24,14 @@
2324
PreservationSet as PreservationSet,
2425
ProfilingQuery as ProfilingQuery,
2526
ProfilingQueries as ProfilingQueries,
27+
QueryResult as QueryResult,
28+
QueryResults as QueryResults,
2629
PruningColumns as PruningColumns,
2730
SemanticLinkingResult as SemanticLinkingResult,
31+
SQLQueries as SQLQueries,
32+
SQLQuery as SQLQuery,
33+
TableProfileColumnResult as TableProfileColumnResult,
34+
TableProfileResult as TableProfileResult,
2835
Table as Table,
2936
)
3037

@@ -38,6 +45,7 @@
3845
"URL",
3946
"database_name_from_connection",
4047
"database_name_from_connection_string",
48+
"database_type_from_connection",
4149
"create_tpch_example_duckdb_db",
4250
# Planning
4351
"LogicalPlanner",
@@ -55,7 +63,13 @@
5563
"PreservationColumns",
5664
"PreservationSet",
5765
"PruningColumns",
66+
"QueryResult",
67+
"QueryResults",
5868
"SemanticLinkingResult",
69+
"SQLQueries",
70+
"SQLQuery",
71+
"TableProfileColumnResult",
72+
"TableProfileResult",
5973
"Table",
6074
# Pruning
6175
"Pruner",

‎src/piglets/database/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
DatabaseConnector as DatabaseConnector,
33
database_name_from_connection as database_name_from_connection,
44
database_name_from_connection_string as database_name_from_connection_string,
5+
database_type_from_connection as database_type_from_connection,
56
)
67
from .url import BigQueryURL as BigQueryURL, URL as URL
78

@@ -14,6 +15,7 @@
1415
"URL",
1516
"database_name_from_connection",
1617
"database_name_from_connection_string",
18+
"database_type_from_connection",
1719
]
1820

1921

‎src/piglets/database/database_connector.py‎

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import logging
22
from typing import Any
33

4-
from sqlalchemy import create_engine, inspect
4+
from sqlalchemy import create_engine, inspect, text
55
from sqlalchemy.engine.url import make_url
66

7-
from piglets.types import Column, Database, Table
7+
from piglets.types import Column, Database, QueryResult, SQLQuery, Table
88

99
logger = logging.getLogger(__name__)
1010

@@ -49,6 +49,30 @@ def database_name_from_connection_string(connection_string: str) -> str:
4949
return database_name_from_connection(connection_string)
5050

5151

52+
def database_type_from_connection(connection: Any) -> str:
53+
connection_url = connection_to_sqlalchemy_url(connection)
54+
url = make_url(connection_url)
55+
driver_name = url.drivername.split("+", 1)[0]
56+
57+
if driver_name == "bigquery":
58+
return "BigQuery"
59+
if driver_name == "snowflake":
60+
return "Snowflake"
61+
if driver_name == "duckdb":
62+
database = url.database or ""
63+
if database.startswith(("md:", "motherduck:")):
64+
return "MotherDuck"
65+
return "DuckDB"
66+
if driver_name == "sqlite":
67+
return "SQLite"
68+
if driver_name in {"postgres", "postgresql"}:
69+
return "PostgreSQL"
70+
if driver_name == "mysql":
71+
return "MySQL"
72+
73+
return driver_name.replace("_", " ").title().replace(" ", "")
74+
75+
5276
class DatabaseConnector():
5377
"""Base class for database connectors."""
5478
def __init__(
@@ -58,6 +82,7 @@ def __init__(
5882
connection_url = connection_to_sqlalchemy_url(connection)
5983
engine_kwargs = connection_to_create_engine_kwargs(connection)
6084
self.database_name = database_name_from_connection(connection_url)
85+
self.database_type = database_type_from_connection(connection_url)
6186

6287
logger.info("Connecting to database %s", self.database_name)
6388
self.engine = create_engine(connection_url, **engine_kwargs)
@@ -74,6 +99,26 @@ def get_database_schema(self) -> Database:
7499
columns.append(column)
75100
table = Table(name=table_name, columns=columns)
76101
tables.append(table)
77-
return Database(name=self.database_name, tables=tables)
102+
return Database(
103+
name=self.database_name,
104+
database_type=self.database_type,
105+
tables=tables,
106+
)
78107

79-
# TODO: Implement database querying methods using connector-x or similar libraries for efficient querying and data retrieval.
108+
def execute_query(self, query: SQLQuery | str) -> QueryResult:
109+
"""Execute a SQL query and return a typed result."""
110+
sql = query if isinstance(query, str) else query.query
111+
if not sql.strip():
112+
raise ValueError("query must not be empty")
113+
114+
with self.engine.connect() as connection:
115+
result = connection.execute(text(sql))
116+
columns = list(result.keys())
117+
rows = [tuple(row) for row in result.fetchall()]
118+
119+
return QueryResult(
120+
query=sql,
121+
columns=columns,
122+
rows=rows,
123+
row_count=len(rows),
124+
)

‎src/piglets/profiling/profiler.py‎

Lines changed: 125 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,50 @@
11
from langchain.chat_models import init_chat_model
22

3+
from piglets.database import DatabaseConnector
34
from piglets.policies import SemanticRules
45
from piglets.types import (
6+
Database,
57
ProfilingQueries,
8+
QueryResult,
9+
QueryResults,
610
SemanticLinkingResult,
711
Table,
12+
TableProfileResult,
813
)
914

10-
1115
class Profiler():
1216
def __init__(
1317
self,
1418
model_name: str,
19+
database: Database,
1520
model_provider: str = None,
1621
rules: SemanticRules | None = None,
1722
):
1823
self.model_name = model_name
24+
self.database = database
1925
self.model_provider = model_provider
2026
self.rules = rules or SemanticRules()
2127

22-
def profile_table(
28+
def _generate_table_profiler_queries(
2329
self,
2430
natural_language_query: str,
25-
database_type: str | None,
2631
table: Table,
27-
semantic_linking_result: SemanticLinkingResult,
32+
semantic_linking_result: SemanticLinkingResult | None = None,
2833
) -> ProfilingQueries:
2934

3035
llm = init_chat_model(model=self.model_name, model_provider=self.model_provider)
3136
llm = llm.with_structured_output(ProfilingQueries)
3237
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")
38+
sql_type = f"{self.database.database_type.upper()} SQL"
39+
semantic_table_functions_lower = (
40+
{k.lower(): v for k, v in semantic_linking_result.table_functions.items()}
41+
if semantic_linking_result
42+
else {}
43+
)
44+
semantic_table_function = semantic_table_functions_lower.get(
45+
table.name.lower(),
46+
"Unknown Role",
47+
)
3648

3749
# TODO: Include column descriptions here once Column supports them.
3850
DATA_PROFILE_QUERY_GENERATION_PROMPT = f"""
@@ -76,7 +88,7 @@ def profile_table(
7688
7789
*** OUTPUT FORMAT ***
7890
Return structured data matching the ProfilingQueries schema:
79-
- exploratory_queries: a list of 3-8 objects.
91+
- query: a list of 3-8 objects.
8092
- Each object must contain:
8193
- motivation: a concise reason for running the profiling query.
8294
- query: the {sql_type} query string.
@@ -89,3 +101,108 @@ def profile_table(
89101
profiling_queries = llm.invoke(DATA_PROFILE_QUERY_GENERATION_PROMPT)
90102

91103
return profiling_queries
104+
105+
# TODO: Parallel query execution
106+
def _execute_table_profiling_queries(
107+
self,
108+
database_connector: DatabaseConnector,
109+
profiling_queries: ProfilingQueries,
110+
) -> QueryResults:
111+
query_results = QueryResults()
112+
for profiling_query in profiling_queries.query:
113+
query_result: QueryResult = database_connector.execute_query(profiling_query)
114+
query_results.query_results.append(query_result)
115+
return query_results
116+
117+
def _profile_table_from_query_results(
118+
self,
119+
natural_language_query: str,
120+
query_results: QueryResults,
121+
table: Table,
122+
) -> TableProfileResult:
123+
llm = init_chat_model(model=self.model_name, model_provider=self.model_provider)
124+
llm = llm.with_structured_output(TableProfileResult)
125+
126+
TABLE_PROFILE_PROMPT = f"""
127+
*** TASK ***
128+
Based on the exploration history and results above,
129+
determine if table {table.name} is RELEVANT to the User
130+
Question.
131+
*** EXPLORATION EVIDENCE ***
132+
{query_results.to_string()}
133+
*** USER QUESTION ***
134+
{natural_language_query}
135+
*** DECISION GUIDELINES ***
136+
- **Direct Match**: Contains the specific answer data.
137+
- **Bridge Table**: Contains IDs needed to join other relevant tables (CRITICAL: Keep even if no other useful data).
138+
- **Filter Source**: Contains columns needed to restrict the
139+
result.
140+
- **Calculation Support**: Contains numerical columns
141+
needed for aggregation (e.g., score for AVG, price for
142+
SUM).
143+
*** OUTPUT GUIDELINES ***
144+
- relevant: Whether this table is relevant to the user question.
145+
- relevant_columns: Columns relevant to the user question.
146+
- column_name: The relevant column name.
147+
- relevance_reason: Explain the column's logical role.
148+
- observations: Summarize factual findings from exploration.
149+
- table_summary: A concise summary of what this table
150+
represents in the context of the query.
151+
*** OUTPUT FORMAT ***
152+
Return structured data matching the TableProfileResult schema:
153+
- relevant: boolean.
154+
- relevant_columns: list of TableProfileColumnResult objects.
155+
- Each relevant_columns item must contain:
156+
- column_name: string.
157+
- relevance_reason: string.
158+
- observations: string.
159+
- table_summary: string.
160+
161+
Example shape:
162+
```json
163+
{{
164+
"relevant": true,
165+
"relevant_columns": [
166+
{{
167+
"column_name": "name",
168+
"relevance_reason": "...",
169+
"observations": "..."
170+
}}
171+
],
172+
"table_summary": "..."
173+
}}
174+
```
175+
Provide your analysis:
176+
"""
177+
178+
table_profile_result = llm.invoke(TABLE_PROFILE_PROMPT)
179+
180+
return table_profile_result
181+
182+
def profile_table(
183+
self,
184+
natural_language_query: str,
185+
table: Table,
186+
database_connector: DatabaseConnector,
187+
semantic_linking_result: SemanticLinkingResult | None = None,
188+
) -> TableProfileResult:
189+
profiling_queries = self._generate_table_profiler_queries(
190+
natural_language_query=natural_language_query,
191+
table=table,
192+
semantic_linking_result=semantic_linking_result,
193+
)
194+
query_results = self._execute_table_profiling_queries(
195+
database_connector=database_connector,
196+
profiling_queries=profiling_queries,
197+
)
198+
table_profile_result = self._profile_table_from_query_results(
199+
natural_language_query=natural_language_query,
200+
query_results=query_results,
201+
table=table,
202+
)
203+
return table_profile_result
204+
205+
#TODO profile self.database by profiling all of it's tables in parallel
206+
# returning a list of TableProfileResults
207+
#def profile_database(self) -> DatabaseProfileResult:
208+

‎src/piglets/types/__init__.py‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,24 @@
1212
Database as Database,
1313
Table as Table,
1414
)
15-
from .profiling import (
16-
ProfilingQuery as ProfilingQuery,
17-
ProfilingQueries as ProfilingQueries,
18-
)
1915
from .pruning import (
2016
DeletionColumns as DeletionColumns,
2117
DeletionSet as DeletionSet,
2218
PreservationColumns as PreservationColumns,
2319
PreservationSet as PreservationSet,
24-
PruningColumns as PruningColumns
20+
PruningColumns as PruningColumns,
21+
)
22+
from .profiling import (
23+
TableProfileColumnResult as TableProfileColumnResult,
24+
TableProfileResult as TableProfileResult,
25+
)
26+
from .queries import (
27+
ProfilingQuery as ProfilingQuery,
28+
ProfilingQueries as ProfilingQueries,
29+
QueryResult as QueryResult,
30+
QueryResults as QueryResults,
31+
SQLQueries as SQLQueries,
32+
SQLQuery as SQLQuery,
2533
)
2634

2735
__all__ = [
@@ -35,13 +43,20 @@
3543
"Column",
3644
"Database",
3745
"Table",
38-
# profiling types
39-
"ProfilingQuery",
40-
"ProfilingQueries",
4146
# pruning types
4247
"DeletionColumns",
4348
"DeletionSet",
4449
"PreservationColumns",
4550
"PreservationSet",
4651
"PruningColumns",
52+
# query types
53+
"ProfilingQuery",
54+
"ProfilingQueries",
55+
"QueryResult",
56+
"QueryResults",
57+
"SQLQueries",
58+
"SQLQuery",
59+
# profiling types
60+
"TableProfileColumnResult",
61+
"TableProfileResult",
4762
]

0 commit comments

Comments
 (0)