Large Language Models (LLMs) can translate plain-English questions into SQL, which makes institutional databases usable by people who cannot write queries. In a shared system such as a college ERP, however, the generated SQL must be treated as untrusted code: it may modify data, read rows that belong to another user, or quietly answer the wrong question. This paper reports the design, deployment, and security testing of SafeSQL, a natural-language query system over a 25-table, 174-column PostgreSQL ERP schema holding about 200,000 records. SafeSQL places the LLM behind four independent layers: model-level refusal, syntax-tree (AST) blocking with sqlglot, a read-only non-owner database role, and Row-Level Security (RLS). We show that the widely used RLS pattern based on current_setting() can be defeated by generated SQL that calls set_config() from a subquery, CTE, LATERAL join, or window function, and we replace it with a session map keyed on the PostgreSQL backend process, which adds about 2.14 ms per query. We also describe five cases in which our own test infrastructure reported success for the wrong reason, and the checks we added to catch them. The system is deployed as a web application and is covered by 248 automated tests.
Introduction
The text describes the development of a secure AI-powered Text-to-SQL system for a College Enterprise Resource Planning (ERP) platform. The system allows students, faculty and administrators to interact with a college database using natural language instead of writing SQL queries manually.
The main focus is not only generating accurate SQL queries but also ensuring database security, user authentication and restricted access to personal information.
1. Introduction
Text-to-SQL technology converts natural language questions into SQL queries using Large Language Models (LLMs).
For example, a student can ask, "Show my semester marks," and the AI generates an SQL query to retrieve the required information.
Existing systems such as DIN-SQL, DAIL-SQL, MAC-SQL and CHESS have improved SQL generation accuracy. However, they mainly focus on query correctness rather than database security.
In a college ERP system, different users have different access permissions. Students should only access their own records, while faculty and administrators have different levels of access.
The study addresses this security challenge by developing a multi-layer protection system that prevents unauthorized database access, SQL injection and unsafe queries.
2. Review of Related Work
Previous research has explored several areas:
LLM-based Text-to-SQL: Models such as ChatGPT and other language models convert natural language into SQL queries.
Guardrails and security attacks: Tools such as NeMo Guardrails and Llama Guard filter unsafe inputs and outputs, but do not fully analyse SQL execution behaviour.
Database authorization: PostgreSQL Row-Level Security (RLS) restricts access to individual database records based on user permissions.
Hallucination detection: Techniques such as self-evaluation, sampling consistency, semantic entropy and isotonic regression help estimate the reliability of AI-generated responses.
The research gap is that existing Text-to-SQL systems focus mainly on accuracy, while secure execution and user-specific database access require additional protection.
3. System Architecture
The proposed system follows a four-layer architecture with an additional model-refusal mechanism.
Its workflow includes:
Frontend: React and TypeScript provide the user interface for entering natural language questions.
Backend: FastAPI authenticates users, retrieves database schema information and communicates with the LLM.
SQL generation: Claude Sonnet is used as the primary AI model, while Gemini Flash-Lite is used for cross-model testing.
Security verification: Generated SQL queries pass through multiple security layers before execution.
Database: PostgreSQL stores college information and applies access restrictions.
The system provides five response statuses:
SUCCESS – Query executed successfully.
REFUSED – AI refuses an unsafe request.
CLARIFICATION_NEEDED – Additional information is required.
The most important contribution of this project is its defence-in-depth security architecture.
Layer 1: Model Refusal
The AI model is instructed to reject requests involving unauthorized access to other users' data or database modifications.
This provides an initial security check, but the system does not depend entirely on the AI model for protection.
Layer 2: AST Guardrails
The generated SQL is analysed using sqlglot, which converts SQL statements into an Abstract Syntax Tree (AST).
The system blocks:
INSERT, UPDATE and DELETE operations.
CREATE, DROP and other database modification commands.
Multiple SQL statements.
Unauthorized or dangerous functions such as set_config, pg_sleep and pg_read_file.
Queries that do not follow the permitted SELECT structure.
A LIMIT clause is also automatically added when missing.
Layer 3: Read-Only Non-Owner Database Role
The system executes approved queries using a restricted PostgreSQL database role.
This role:
Has only SELECT permissions on permitted tables and columns.
Cannot modify database records.
Cannot access sensitive columns that have been excluded from its permissions.
Does not own database tables.
This provides additional protection even if an unsafe query passes the earlier security layers.
Layer 4: Process-Bound Row-Level Security (RLS)
This layer ensures that each user can access only their authorized records.
The researchers identified a weakness in conventional PostgreSQL RLS policies that use the current_setting() function to identify users.
Since SQL can potentially modify this session setting using set_config(), an attacker could attempt to change the identity associated with a query.
To address this issue, the researchers developed a process-bound session mapping mechanism.
It uses a session_map table containing:
Database process ID.
Backend start time.
User ID.
User role.
The database identifies the authenticated user using the database backend process rather than a session variable that generated SQL could modify.
Conclusion
SafeSQL treats the LLM as an untrusted SQL author and places it behind four layers that do not depend on its behaviour. Our main practical finding is that the textbook current_setting() form of PostgreSQL RLS is not safe when queries are model-written, and that binding identity to the backend process closes the gap at small cost. We also found that test infrastructure needs the same scrutiny as the system it tests. Future work includes per-user column policies, more database schemas, and broader attack generation.
References
[1] V. Zhong, C. Xiong, and R. Socher, \"Seq2SQL: Generating structured queries from natural language using reinforcement learning,\" arXiv:1709.00103, 2017.
[2] T. Yu et al., \"Spider: A large-scale human-labeled dataset for complex and cross-domain semantic parsing and text-to-SQL task,\" in Proc. EMNLP, 2018.
[3] J. Li et al., \"Can LLM already serve as a database interface? A big bench for large-scale database grounded text-to-SQLs,\" in Proc. NeurIPS Datasets and Benchmarks, 2023.
[4] M. Pourreza and D. Rafiei, \"DIN-SQL: Decomposed in-context learning of text-to-SQL with self-correction,\" in Proc. NeurIPS, 2023.
[5] D. Gao et al., \"Text-to-SQL empowered by large language models: A benchmark evaluation,\" Proc. VLDB Endow., vol. 17, no. 5, 2024.
[6] B. Wang et al., \"MAC-SQL: A multi-agent collaborative framework for text-to-SQL,\" in Proc. COLING, 2025.
[7] S. Talaei et al., \"CHESS: Contextual harnessing for efficient SQL synthesis,\" arXiv:2405.16755, 2024.
[8] L. Shi et al., \"A survey on employing large language models for text-to-SQL tasks,\" arXiv:2407.15186, 2024.
[9] G. Qu et al., \"Before generation, align it! A novel and effective strategy for mitigating hallucinations in text-to-SQL generation,\" in Findings of ACL, 2024.
[10] K. Maamari et al., \"The death of schema linking? Text-to-SQL in the age of well-reasoned language models,\" arXiv:2408.07702, 2024.
[11] H. Li et al., \"CodeS: Towards building open-source language models for text-to-SQL,\" Proc. ACM Manag. Data (SIGMOD), 2024.
[12] T. Rebedea et al., \"NeMo Guardrails: A toolkit for controllable and safe LLM applications with programmable rails,\" in Proc. EMNLP: System Demonstrations, 2023.
[13] H. Inan et al., \"Llama Guard: LLM-based input-output safeguard for human-AI conversations,\" arXiv:2312.06674, 2023.
[14] R. Pedro et al., \"From prompt injections to SQL injection attacks: How protected is your LLM-integrated web application?\" arXiv:2308.01990, 2023.
[15] M. Lin et al., \"Are your LLM-based text-to-SQL models secure? Exploring SQL injection via backdoor attacks,\" Proc. ACM Manag. Data (SIGMOD), 2025.
[16] D. Klisura and A. Rios, \"Unmasking database vulnerabilities: Zero-knowledge schema inference attacks in text-to-SQL systems,\" arXiv, 2025.
[17] PostgreSQL Global Development Group, \"Row security policies,\" PostgreSQL Documentation. [Online]. Available: https://www.postgresql.org/docs/current/ddl-rowsecurity.html
[18] PostgreSQL Global Development Group, \"System administration functions: set_config,\" PostgreSQL Documentation. [Online]. Available: https://www.postgresql.org/docs/current/functions-admin.html
[19] T. Mao et al., \"sqlglot: Python SQL parser and transpiler.\" [Online]. Available: https://github.com/tobymao/sqlglot
[20] S. Kadavath et al., \"Language models (mostly) know what they know,\" arXiv:2207.05221, 2022.
[21] P. Manakul, A. Liusie, and M. J. F. Gales, \"SelfCheckGPT: Zero-resource black-box hallucination detection for generative large language models,\" in Proc. EMNLP, 2023.
[22] L. Kuhn, Y. Gal, and S. Farquhar, \"Semantic uncertainty: Linguistic invariances for uncertainty estimation in natural language generation,\" in Proc. ICLR, 2023.
[23] S. Farquhar, J. Kossen, L. Kuhn, and Y. Gal, \"Detecting hallucinations in large language models using semantic entropy,\" Nature, vol. 630, pp. 625–630, 2024.
[24] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger, \"On calibration of modern neural networks,\" in Proc. ICML, 2017.
[25] B. Zadrozny and C. Elkan, \"Transforming classifier scores into accurate multiclass probability estimates,\" in Proc. KDD, 2002.
[26] M. P. Naeini, G. F. Cooper, and M. Hauskrecht, \"Obtaining well calibrated probabilities using Bayesian binning,\" in Proc. AAAI, 2015.