v1.0

v1.0

/

/

How to secure text-to-SQL agents with governed query execution

How to secure text-to-SQL agents with governed query execution

How to secure text-to-SQL agents with governed query execution

The security boundary in text-to-SQL is not the prompt. A model can produce syntactically valid SQL and still query sensitive rows, run a costly scan or invent a misleading business calculation. Reliable enterprise analytics requires a governed path between natural-language intent and database execution.

How to secure text-to-SQL agents with governed query execution
Image

Connect your data, tools, and AI agents.

Automate complex workflows effortlessly.

Turn insights into intelligent actions.

  • Trello logo
  • Notion logo
  • Slack logo
  • Google logo
  • Salesforce logo
  • Zapier logo
  • Linear logo
  • Intercom logo
  • Dropbox logo
  • Jira logo
  • Google Drive logo
  • HubSpot logo
  • Google Sheets logo
  • HubSpot logo
  • Google Sheets logo
  • HubSpot logo
  • GitHub logo
  • Dropbox logo

Adil Harcha

The security boundary in text-to-SQL is not the prompt. A model can produce syntactically valid SQL and still query sensitive rows, run a costly scan or invent a misleading business calculation. Reliable enterprise analytics requires a governed path between natural-language intent and database execution.

How a governed text-to-SQL request should work

The user asks: “What changed in gross margin for our French enterprise accounts last quarter?” The system resolves identity and tenant, maps business vocabulary to approved metrics, generates a read-only query plan, validates it against policy and only then executes it on approved data. It returns an explanation with metric definitions and query provenance.

The trust boundary stays outside the model: identity, permissions and query execution limits are enforced by infrastructure. A good answer is insufficient if the execution path bypasses row-level security or crosses tenants.

Governed text-to-SQL pipeline from natural-language question to validated read-only SQL and traceable business answer.

Seven controls to implement in order

Control

Why it matters

Verification

1. Identity binding

Tie every request to the actual person and tenant

Attempt cross-role and cross-tenant access

2. Semantic definitions

Standardize approved metrics and joins

Compare identical KPI questions across teams

3. Schema minimization

Hide tables and columns outside the task

Try to request forbidden columns

4. SQL parsing and allowlists

Reject mutations, risky functions and unsupported statements

AST tests with nested queries and injections

5. Database enforcement

Apply least privilege, RLS, timeouts and quotas

Prove denied queries fail in database

6. Result validation

Check types, totals, units and result cardinality

Inject nulls and edge cases

7. Audit and evaluation

Trace question, policy, SQL, result and feedback

Replay incident with sensitive data redacted

The semantic layer is a correctness contract

A semantic layer provides shared business definitions such as “net revenue,” “active customer” or “on-time delivery.” It is more than a schema dictionary: it documents calculation logic, approved joins, filters, grain and metric ownership. Without it, two plausible SQL statements can give contradictory answers to the same question.

The semantic layer should be versioned and tied to data lineage. For a definition, see enterprise search for the broader retrieval boundary and the new related definition proposed below, what is a semantic layer for AI agents?

Treat prompt injection as an input threat, not an instruction

An attacker may place instructions inside a database value, a retrieved document or a user question. That text must never rewrite authorization. Use a deterministic validator that understands the parsed query, enforce tenant and role restrictions at the database, and disallow arbitrary DDL/DML and unrestricted functions. OWASP recommends backend permissions, least privilege and explicit authorization on tool calls.

Example of a query approval trace

request_id = "req-2026-014"
identity = "tenant-fr / finance-viewer"
metric = "gross_margin_pct@v3"
allowed_tables = ["sales_metrics_readonly"]
sql_validation = "pass"
database_role = "analytics_reader"
execution_status = "success"
review_required = false
request_id = "req-2026-014"
identity = "tenant-fr / finance-viewer"
metric = "gross_margin_pct@v3"
allowed_tables = ["sales_metrics_readonly"]
sql_validation = "pass"
database_role = "analytics_reader"
execution_status = "success"
review_required = false

This is a synthetic illustration. Actual production logs should avoid storing sensitive raw SQL parameters, user secrets or personal data without a lawful basis and protection controls.

Evidence chain showing identity, metric contract, SQL validation, database authorization and traceable analytical result.

Test the system with questions that are designed to fail

  • Ask for a competitor tenant’s customer-level data. Expected: deny.

  • Request an unsupported metric with ambiguous grain. Expected: clarify, not fabricate.

  • Inject SQL instructions inside a source document. Expected: treat as data.

  • Generate a query that times out. Expected: graceful bounded failure.

  • Change access between planning and execution. Expected: recheck permission.

  • Submit the same write-like intent repeatedly. Expected: no execution through a read-only agent.

What to measure during a pilot

Track task success under authorized roles, policy-denial correctness, SQL syntax validity, semantic correctness, p95 query time, error rate, cost per successful question and user escalation. Compare against a stable baseline of analyst-authored queries and business-owned metric definitions.

Deployment checklist

  • Bind identity and tenant before planning.

  • Expose only authorized semantic entities and database scopes.

  • Validate SQL as an AST and enforce limits at the database.

  • Run read-only credentials and track resource usage.

  • Persist a redacted evidence chain for every execution.

  • Block rollout if any high-severity authorization test fails.

A reference deployment boundary for engineering teams

Expose a text-to-SQL agent through a dedicated API that receives authenticated user context from the application, not a role copied out of a chat message. The agent can request a governed semantic query plan, but a separate validator verifies allowed business entities, joins, filters and output grain. The database connection uses a narrowly scoped read-only role, with row-level access policies, statement timeouts and a maximum result size. Return aggregate results with the semantic metric version and a trace identifier. Reject attempts to execute multiple statements or to request resources outside the approved contract.

Why SQL syntax validation is necessary but insufficient

A parser can catch a forbidden UPDATE statement or an unsupported function. It does not necessarily know that “revenue” should exclude refunded orders, that a contract cannot cross regions, or that a customer identifier is personal data. That is why three different controls must cooperate: syntactic query policy, business semantic validation and enforcement of permissions by the database itself. Each failure mode needs a dedicated adversarial test.

Treat derived SQL as an untrusted proposal. Even when it has been produced by a trusted model, validate placeholders, identifier resolution, expanded views, table functions and data volume. Prefer parameterized filters, deny-by-default table access, and policy-aware query compilation. Require the system to explain when a metric definition is missing rather than inventing a plausible calculation.

Operational ownership: who updates what?

Responsibility

Accountable team

Metric definitions and reporting grain

Business data owner

Identity, authorization and data classification

Security and platform engineering

Query planner, validators and agent evaluation

AI engineering

Database roles, RLS, limits and performance

Data platform operations

Release approval and incident response

Cross-functional service owner

This separation makes text-to-SQL a maintained business capability, not an uncontrolled chatbot attached to a database. The technical win is not only more questions answered; it is that answers and attempted actions can be explained, reproduced and challenged safely.

Frequently asked questions

Can prompts alone secure a SQL agent?

No. Access control and query constraints must be enforced independently by backend and database systems.

Why does text-to-SQL need a semantic layer?

It provides shared metric definitions, joins and grain so a syntactically correct query can also be business-correct.

Should a SQL agent have write access?

Read-only access is the safest default for analytics; any write operation requires separate design, authorization and approvals.

What is the safest database permission for an analytics SQL agent?

Start with a narrowly scoped read-only database role, enforce tenant and row-level permissions in the database, and apply statement timeouts and result-size limits.

What should a SQL agent do when a business metric is ambiguous?

Ask for clarification or decline the calculation until an approved semantic definition exists; do not invent metric formulas, joins or reporting grain.

Related Resources

Related Resources

Related definition

Framer is a no-code tool for building and publishing responsive websites—perfect for anyone creating modern, high-performance pages without coding.

An open-source foundation for building your own agents.

ApowerB is the open-source agentic framework developed by thaink² to build, orchestrate, and operate AI agents on your own stack, using your models, tools, and data.

What if your next analysis were ready before your next meeting?

Show us your environment and a use case. See how thaink² can query, monitor, and act on your data.

Our mission
Our vision

Move from data you look at to data that works continuously for your business.

We believe the next generation of Data platforms will do more than show what happened. They will monitor, explain, anticipate, and prepare decisions before some questions even need to be asked.

Image

What is an Agentic Data Platform?

An Agentic Data Platform uses specialized AI agents to work with enterprise data. Unlike a static dashboard or a simple chatbot, agents can explore multiple sources, run analyses, generate visualizations, produce deliverables, and execute recurring missions.

What’s the difference between Proactive Mode and Exploratory Mode?

In Exploratory Mode, the user asks a question and thaink² runs the analysis on demand. In Proactive Mode, a mission is defined in advance: agents monitor the data based on a set schedule or specific conditions and automatically deliver the relevant results.

Do I need to know SQL to use thaink²?

Not for business use cases. Users can ask questions in natural language and get analyses, tables, charts, and dashboards without writing SQL queries themselves.

What data sources can thaink² connect to?

The platform is designed to work with the systems already in place across your organization: databases, data warehouses, ERP, CRM, APIs, files, and document repositories. Available connectors depend on your environment and use case.

What types of outputs can the agents produce?

Depending on the agent and use case, outputs can include analyses, tables, charts, dashboards, forecasts, alerts, summaries, and reports. The goal is to deliver an actionable result, not just a text response.

Can thaink² be deployed on our own infrastructure?

thaink² supports deployment options designed around enterprise requirements, including organizations that need greater control over their infrastructure, models, and data. Our teams help define the architecture that best fits the project.

Which part of the thaink² ecosystem is open source?

ApowerB is the open-source agentic framework developed by thaink². It enables technical teams to build and operate their own agents, with support for RAG, Text-to-SQL, multi-LLM setups, and APIs.

How do I get started with thaink²?

The easiest way to start is with a concrete use case: reporting, analysis, forecasting, document search, or monitoring. An initial session helps define the available data, expected outcomes, and the most suitable deployment approach.

Join our Discord community

Connect with builders, Data teams, and AI practitioners. Share ideas, get technical help, discuss agentic architectures, and follow the latest developments around ApowerB.

Our newsletter (Soon)

Data that takes action, straight to your inbox.

Field insights, agentic architectures, benchmarks, use cases, and the latest from ApowerB. Only what’s worth reading.

© 2026 thaink² SAS — All rights reserved

An open-source foundation for building your own agents.

ApowerB is the open-source agentic framework developed by thaink² to build, orchestrate, and operate AI agents on your own stack, using your models, tools, and data.

What if your next analysis were ready before your next meeting?

Show us your environment and a use case. See how thaink² can query, monitor, and act on your data.

Our mission
Our vision

Put the power of data in the hands of decision-makers.

Today, too many business questions still depend on an export, a dashboard, or the availability of a Data team. thaink² changes that by letting teams query their data directly, while agents handle the analysis and recurring work.

Image

What is an Agentic Data Platform?

An Agentic Data Platform uses specialized AI agents to work with enterprise data. Unlike a static dashboard or a simple chatbot, agents can explore multiple sources, run analyses, generate visualizations, produce deliverables, and execute recurring missions.

What’s the difference between Proactive Mode and Exploratory Mode?

In Exploratory Mode, the user asks a question and thaink² runs the analysis on demand. In Proactive Mode, a mission is defined in advance: agents monitor the data based on a set schedule or specific conditions and automatically deliver the relevant results.

Do I need to know SQL to use thaink²?

Not for business use cases. Users can ask questions in natural language and get analyses, tables, charts, and dashboards without writing SQL queries themselves.

What data sources can thaink² connect to?

The platform is designed to work with the systems already in place across your organization: databases, data warehouses, ERP, CRM, APIs, files, and document repositories. Available connectors depend on your environment and use case.

What types of outputs can the agents produce?

Depending on the agent and use case, outputs can include analyses, tables, charts, dashboards, forecasts, alerts, summaries, and reports. The goal is to deliver an actionable result, not just a text response.

Can thaink² be deployed on our own infrastructure?

thaink² supports deployment options designed around enterprise requirements, including organizations that need greater control over their infrastructure, models, and data. Our teams help define the architecture that best fits the project.

Which part of the thaink² ecosystem is open source?

ApowerB is the open-source agentic framework developed by thaink². It enables technical teams to build and operate their own agents, with support for RAG, Text-to-SQL, multi-LLM setups, and APIs.

How do I get started with thaink²?

The easiest way to start is with a concrete use case: reporting, analysis, forecasting, document search, or monitoring. An initial session helps define the available data, expected outcomes, and the most suitable deployment approach.

Join our Discord community

Connect with builders, Data teams, and AI practitioners. Share ideas, get technical help, discuss agentic architectures, and follow the latest developments around aPowerB.

Our newsletter (Soon)

Data that takes action, straight to your inbox.

Field insights, agentic architectures, benchmarks, use cases, and the latest from ApowerB. Only what’s worth reading.

© 2026 thaink² SAS — All rights reserved