CodeToQuery
Rails-native gem

Natural language to SQL for Rails applications.

Give your team self-serve data access without compromising security. CodeToQuery converts plain English questions into safe, parameterized SQL queries with built-in guardrails for Ruby on Rails applications.

app/services/code_to_query.rb
# Ask a question in plain English
query = CodeToQuery.ask(
  prompt: "Show me top customers by revenue this month",
  allow_tables: %w[customers orders],
  current_user: current_user
)

# Check if it's safe to run
if query.safe?
  results = query.run
  puts "Found #{results.rows.length} results"
end

# Or inspect the generated SQL
puts query.sql    #=> SELECT customers.* FROM customers...
puts query.params #=> { start_date: "2024-01-01", ... }
Ruby
PostgreSQL
AI

Key Features

Everything you need to enable self-serve data access while maintaining security and performance.

AI-Powered

Works with OpenAI or local models to understand natural language questions and convert them to SQL.

Built-in Safety

SQL linting, table allowlists, EXPLAIN plan checks, and readonly execution keep your data secure.

Schema Awareness

Understands your Rails models, associations, and scopes to generate accurate, context-aware queries.

Policy Enforcement

Automatically injects tenant filters and access rules based on your application's security policies.

How it works

Step 1

Install

Add the library to your app and provide a DB schema snapshot.

Step 2

Prompt

Send a natural‑language request like 'top 10 invoices by amount this month'.

Step 3

Review

Receive proposed SQL + parameters, optionally show a diff/approval UI.

Step 4

Run

Execute against read replicas or behind a guard—return results to users.

Quickstart (Rails)

  1. 1. Add the gem: gem 'code_to_query'
  2. 2. Configure your OpenAI API key and security settings in an initializer.
  3. 3. Run rails code_to_query:bootstrap to generate your schema context.
  4. 4. Call CodeToQuery.ask with your natural language prompt.
See more examples in the repository README.
config/initializers/code_to_query.rb
CodeToQuery.configure do |config|
  config.openai_api_key = ENV['OPENAI_API_KEY']
  config.openai_model = 'gpt-4'
  
  # Security settings
  config.enable_explain_gate = true
  config.allow_seq_scans = false
  config.max_query_cost = 10000
  config.require_limit_by_default = true
end

FAQ

Does CodeToQuery run queries automatically?

No—by default it returns SQL + parameters. You decide when/where to execute (and can require approval).

Will it mutate my data?

Use read‑only roles and allow‑lists to keep generated SQL scoped to SELECTs unless you explicitly allow writes.

Which databases are supported?

PostgreSQL first; MySQL and SQLite are on the roadmap. Since it outputs SQL, it can work wherever your adapter does.

Do I need to send production data to an LLM?

No. Provide a schema snapshot so models can reason without touching PII.