Abstract

The democratization of data through Text-to-SQL interfaces is one of the most promising applications of Artificial Intelligence. However, connecting an LLM to a relational database introduces critical risks such as Prompt Injection, where a malicious user could trick the AI into executing destructive commands or extracting sensitive information. This article explores how to build a secure query generator using Open Source models from the Hugging Face ecosystem, a Streamlit interface, and, most importantly, an enterprise-grade validation layer based on Abstract Syntax Trees (AST) to guarantee that generated queries are strictly read-only.

The Illusion of "Magical" Text-to-SQL

Building an AI-powered data extractor looks like magic in tutorials: you connect your database schema to an LLM, ask a question in natural language, and get results. Community-documented projects demonstrate how to integrate Streamlit and the Hugging Face API to transform natural language into functional SQL statements almost instantly.

However, in real-world enterprise environments, AI is inherently non-deterministic. What happens if an internal user (or an attacker) inputs the following prompt?