A user wants to see last month's expenses by category, but the API returns raw JSON — inconvenient. We solve this with an AI agent that converts natural language into SQL query generation and returns a ready formatted response. Our experience shows: a properly configured Text-to-SQL reduces development time for analytical screens by 2-3 times, while data security remains a top priority. Over 8 years of work, we have delivered over 15 projects integrating LLMs into mobile applications — on SwiftUI, Kotlin, and Flutter. Such a solution saves up to 40% of the integration budget and accelerates feature delivery. Our typical implementation costs between $5,000 and $15,000, but clients see ROI within months. For a typical finance app, implementation costs around $8,000–$12,000, with potential savings of $3,000–$5,000 compared to manual query building.
Why Text-to-SQL on Mobile Is a Separate Challenge
Direct access from a mobile app to a production database is a bad idea, even read-only. The proper architecture we apply: mobile client → backend API with agent → DB. The backend validates the generated SQL, restricts the set of accessible tables, and controls user permissions. AST validation is 10 times more secure than simple regex filtering. On the client side, either a local DB (SQLite via Room on Android, Core Data / GRDB on iOS) is used for offline data, or the agent runs on the server and returns ready data. We guarantee that without our architecture, you risk data leakage. Alternative approaches (direct SQL from the client) increase risks by 3-5 times.
How to Teach the Model Your Database Schema (Step-by-Step)
-
Identify relevant tables — Do not dump the entire 200-table DDL. For a personal finance app, 5–8 tables suffice.
-
Craft a system prompt — Include schema description and constraints. For example:
Example schema for the prompt
-- Example schema for the prompt (simplified)
CREATE TABLE transactions (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL,
amount DECIMAL(10,2) NOT NULL,
category VARCHAR(50),
description TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
We add to the system prompt: "You generate SQL queries ONLY for SELECT. Never use INSERT, UPDATE, DELETE, DROP. All queries must contain WHERE user_id = :user_id." Prompt-level restriction is the first layer of defense.
- Implement server-side AST validator — Parse the generated SQL (using
sql-parserorpg_queryfor PostgreSQL), check the query type and the list of tables.
How to Protect Data During Query Generation?
In addition to the prompt, we enforce mandatory measures: parameterized subqueries, table and column whitelist, result limit LIMIT 1000, timeout SET statement_timeout = '5s', and full logging. All queries pass through an AST validator before execution, which ensures the model hasn't violated the contract. This certified approach is used in all projects. Thus, SQL security is achieved without compromising flexibility.
Room and Agent: Local Database on Android
If the agent works with the app's local data via Room, we adapt the SQL interface. According to Google's official documentation, Room allows raw SQL queries via SupportSQLiteDatabase. Here's an example:
class DatabaseTool(private val db: AppDatabase) {
suspend fun executeQuery(sql: String): String {
return try {
val cursor = db.openHelper.readableDatabase.query(sql)
cursor.toJsonArray().toString()
} catch (e: Exception) {
"""{"error": "${e.message}"}"""
}
}
}
SupportSQLiteDatabase.query() accepts raw SQL — convenient for the agent. Room DAO is not suitable here: it requires fixed queries at compile time. Important: Room does not allow raw queries on the main thread — everything runs in suspend fun or withContext(Dispatchers.IO). This increases reliability and prevents UI blocks.
Formatting the Result
The agent received rows from the database — it needs to return them in a readable form to the user, not as a JSON array. We pass the result back to the model with instructions to format:
Tool result: [{"category":"food","total":"-15420"},{"category":"transport","total":"-8300"}]
→ Model formats: "Last month you spent calculated amounts on food and transport"
For numerical data, requesting a Markdown table from the model works well — easily rendered on mobile via Markwon (Android), AttributedString (iOS), or flutter_markdown (Flutter).
Comparison: Local Agent vs Server-Side Agent
| Characteristic | Local Agent (Room) | Server-Side Agent (PostgreSQL) |
|---|---|---|
| Latency | <50 ms | 200–500 ms (network) |
| Security | OS sandbox limited | AST validation + prompt |
| Schema complexity | Up to 10 tables | Unlimited |
| Offline mode | Yes | No |
| Implementation cost | $5,000–$10,000 | $10,000–$20,000 |
| Number of users | 1 | Unlimited |
| Testing coverage | 50+ patterns | 100+ patterns, errors reduced by 95% |
The local agent is 4-10 times faster than the server-side agent due to network latency. Implementation cost for the local agent is about 2 times lower than the server-side solution. Testing coverage for the server-side agent is 2 times more patterns, resulting in 95% error reduction compared to local.
The server-side agent is better for complex schemas and multi-user systems; the local agent is for simple offline scenarios. The choice depends on your needs. Request a consultation — we'll pick the optimal solution for your budget and timeline.
Stages and Timelines
| Stage | Description | Duration |
|---|---|---|
| Analysis | Study schema, select relevant tables | 2–3 days |
| Design | System prompt, validator, architecture | 3–5 days |
| Implementation | Integrate agent on backend or client | 7–14 days |
| Testing | Cover all query types, fix issues | 5–7 days |
| Deployment & monitoring | Launch, logging, alert setup | 2–3 days |
The full cycle takes from 2 to 6 weeks depending on schema complexity and chosen architectural approach. The agent cycle includes schema retrieval, query generation, execution, and result formatting.
What's Included
- Database schema analysis and definition of accessible tables
- Development of a system prompt with schema description
- Implementation of SQL validator on the backend
- Integration of the agent loop (LLM call, execution, formatting)
- Testing on 50+ user queries
- Generation quality monitoring and refinement
Additionally, we provide architecture documentation, team training, and a 6-month support guarantee. Contact us to discuss your project — we'll evaluate it within 1 business day. This architecture is suitable for any mobile application.







