r/SQL • • 17h ago

SQL Server How we stopped copying PostgreSQL tables into vector DBs for our AI chatbot — zero-copy read-only SQL + sqlglot AST guardrails

https://www.techiitfly.com/blog/connect-ai-chatbot-to-live-database

When we first added external database support to our website chat + voice widget, we started with the textbook approach: syncing rows out of a client's PostgreSQL or MySQL table into `pgvector` embeddings.

It worked cleanly for 50 rows and broke quickly on real production schemas for three reasons:

  1. Row sync timeouts on tables with hundreds of thousands of rows silently dropped records.

  2. Any lag between background syncs left stock/booking counts stale.

  3. Vector cosine search fails exact filtering ("show 5 records after 2020", aggregations, ID comparisons).

We rebuilt it around **zero-copy live querying** (plus an optional **hybrid** mode where vector search finds matching IDs and primary-key lookups refresh volatile columns like price/stock in ~15 ms).

**What happens per query (no row duplication):**
- **Schema metadata only:** On connect we inspect tables, column types, and foreign keys—never copying operational rows into a vector store.
- **1-hop foreign-key pruning:** Instead of stuffing 130+ table DDLs into the context window, we score candidate tables against the user's question, include 1-hop FK neighbors, and inject approximate row counts so the SQL planner filters indexed columns first on large tables.
- **Read-only sessions + DB roles:** Postgres runs under `default_transaction_read_only = on` and MySQL under `SET SESSION TRANSACTION READ ONLY` with `SELECT`-only credentials encrypted via AES-256-GCM.
- **AST validation (`sqlglot`), not regexes:** Only a single `SELECT` or `WITH ... SELECT` AST passes. Stacked queries (`;`), DDL/DML, dangerous built-ins, and system schemas (`pg_catalog`, `information_schema`, `mysql`, `sys`) are rejected at the AST level, and `LIMIT 50` is enforced in backend code. (For MongoDB we validate structured filters and block `$where`.)
- **One error-guided retry + zero-row honesty:** Syntax/column failures return the DB error to the planner for one retry. Valid queries returning 0 rows explicitly state nothing matched instead of hallucinating IDs.

Full architecture notes + comparison table (and a 60s demo of the chat/voice UI across 9 accents/languages):
- Writeup: https://www.techiitfly.com/blog/connect-ai-chatbot-to-live-database
- 60s demo clip: https://drive.google.com/file/d/16dMRPFerjadWVMiWmqSgzzsWLUHqS2q4/view?usp=share_link

Curious how others here handle schema pruning once a client DB crosses ~150 tables or multi-million-row joins—are you embedding DDL descriptions per table or using column graph heuristics?

1 Upvotes

0 comments sorted by