Quick overview
This workflow lets Slack users ask natural-language questions about a PostgreSQL database, uses Google Sheets metadata plus live schema data to generate and validate a safe read-only SQL query with Google Gemini, executes it, and replies in Slack with a formatted answer.
How it works
- Triggers when the Slack app is mentioned in a channel.
- Extracts the user’s question text, loads table definitions from Google Sheets, and builds a list of allowed tables.
- Queries PostgreSQL system catalogs for the selected tables’ columns and keys, then combines that with the Google Sheets descriptions into a structured schema context.
- Sends the question and schema context to Google Gemini to generate a single read-only SQL query in JSON.
- Validates the generated SQL to ensure it is a single SELECT-only query, and if it fails, asks Google Gemini once to regenerate and revalidates.
- Executes the validated SQL against PostgreSQL and packages the rows into a results object.
- Uses Google Gemini to turn the query results into a Slack-formatted response (or a polite failure message) and posts it back to the originating Slack channel.
Setup
- Create and install a Slack App with a bot user, enable Event Subscriptions for app mentions, add scopes like chat:write and app_mentions:read, then connect the Slack bot token in n8n and set the target channel in the trigger and reply steps.
- Add PostgreSQL credentials in n8n for the database you want to query.
- Create a Google Sheet with table metadata (at minimum “Table Name” and “Description”, plus any optional fields used), connect Google Sheets credentials, and set the document and sheet IDs.
- Add a Google Gemini (PaLM) API credential and select the model for the SQL-generation step.
- Publish the workflow and copy the Slack Trigger webhook URL into your Slack App’s Event Subscriptions settings, then invite the bot to the channel you want to query from.