sql-translation
Assists developers in mapping R logic to specific SQL dialects for database backends.
Install
mkdir -p .claude/skills/sql-translation && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3590" && unzip -o skill.zip -d .claude/skills/sql-translation && rm skill.zipInstalls to .claude/skills/sql-translation
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Guide for adding SQL function translations to dbplyr backends. Use when implementing new database-specific R-to-SQL translations for functions like string manipulation, date/time, aggregates, or window functions.Key capabilities
- →Map R logic to SQL scalar function equivalents
- →Define aggregate SQL translation variants
- →Implement connection-class translation methods
- →Document dialect-specific syntax research
- →Incorporate infix operator translations
How it works
Extends the dbplyr translation layer by defining custom mappings in backend-specific files that convert R syntax into dialect-optimized SQL.
Inputs & outputs
When to use sql-translation
- →Implementing new SQL translations for dbplyr
- →Mapping R functions to database-specific SQL
- →Updating dbplyr backend logic
About this skill
SQL Translation Skill
Use this skill when adding new SQL function translations for a specific database backend.
Overview
This skill guides you through adding SQL translations to dbplyr. SQL translations convert R functions to their SQL equivalents for different database backends.
Workflow
1. Research SQL (CRITICAL - ALWAYS FIRST)
Before implementing any SQL translation, you MUST research the SQL syntax and behavior using the sql-research skill. See that skill for the complete research workflow.
Quick summary:
- Search official documentation for "{dialect} {function}"
- Document findings in
research/{dialect}-{function}.md - Include all source URLs
- Only proceed to implementation after completing research
2. Identify the backend file
SQL translations are defined in backend-specific files:
R/backend-sqlite.R- SQLiteR/backend-postgres.R- PostgreSQLR/backend-mysql.R- MySQLR/backend-mssql.R- MS SQL Server- etc.
3. Add translation
Translations are added to the sql_translation() method for the connection class. This method returns a sql_variant() with three components:
Scalar translations (for mutate/filter):
sql_translator(.parent = base_scalar,
# Simple function name mapping
log10 = \(x) sql_glue("LOG({x}) / LOG(10)"),
# Function with different arguments
round = function(x, digits = 0L) {
digits <- as.integer(digits)
sql_glue("ROUND(CAST({x} AS NUMERIC), {.val digits})")
},
# Infix operators
paste0 = sql_paste_infix("", "||"),
# Complex logic
grepl = function(pattern, x, ignore.case = FALSE) {
if (ignore.case) {
sql_glue("{x} ~* {pattern}")
} else {
sql_glue("{x} ~ {pattern}")
}
}
)
Aggregate translations (for summarise):
sql_translator(.parent = base_agg,
sd = sql_aggregate("STDEV", "sd"),
median = sql_aggregate("MEDIAN"),
quantile = sql_not_supported("quantile")
)
Window translations (for mutate with groups):
sql_translator(.parent = base_win,
sd = win_aggregate("STDEV"),
median = win_absent("median"),
quantile = sql_not_supported("quantile")
)
4. Helper functions
Common translation patterns:
sql_glue()- Build SQL expressions with{x}for interpolation{.val x}- Interpolate literal R values (not SQL expressions)sql_cast(type)- Type casting (e.g.,sql_cast("REAL"))sql_aggregate(sql_name, r_name)- Simple aggregatessql_paste_infix(sep, op)- String concatenation with infix operatorsql_not_supported(name)- Mark unsupported functionswin_aggregate(sql_name)- Window aggregateswin_absent(name)- Window functions not supported
5. Test the translation
Interactive testing:
Rscript -e "devtools::load_all(); library(dplyr, warn.conflicts = FALSE);
translate_sql(your_function(x), con = simulate_yourdb())"
Write tests:
- Tests for
R/{name}.Rgo intests/testthat/test-{name}.R - Place new tests next to similar existing tests
- Keep tests minimal with few comments
Example test:
test_that("backend_name translates function_name correctly", {
lf <- lazy_frame(x = 1, con = simulate_backend())
expect_snapshot(
lf |> mutate(y = your_function(x))
)
})
6. Document the translation
Update backend documentation:
- Edit the
@descriptionsection in the backend file (e.g.,R/backend-postgres.R) - List key translation differences
- Add examples to
@examplesif helpful
Example:
#' Backend: PostgreSQL
#'
#' @description
#' See `vignette("translation-function")` and `vignette("translation-verb")` for
#' details of overall translation technology. Key differences for this backend
#' are:
#'
#' * Many stringr functions
#' * lubridate date-time extraction functions
#' * Your new translation
7. Format and check
# Format code
air format .
# Run relevant tests
Rscript -e "devtools::test(filter = 'backend-name', reporter = 'llm')"
# Check documentation
Rscript -e "devtools::document()"
Key concepts
Parent translators:
base_scalar- Common scalar functions (math, string, logical)base_agg- Common aggregates (sum, mean, min, max)base_win- Common window functions
SQL expression building:
- Use
sql_glue()to build SQL with string interpolation - Use
{x}to interpolate SQL expressions (function arguments) - Use
{.val x}to interpolate literal R values - Use
{sql x}to interpolate raw SQL strings
Argument handling:
- Check arguments with
check_bool(),check_unsupported_arg() - Convert R types appropriately (e.g.,
as.integer()) - Handle optional arguments with defaults
Resources
See also:
vignette("translation-function")- Function translation overviewvignette("new-backend")- Creating new backends- Existing backend files for examples
Checklist
Before completing a SQL translation:
- Researched SQL syntax in official documentation
- Created research file in
research/{dialect}-{function}.md - Added translation to appropriate
sql_translator()section - Tested translation interactively
- Added/updated tests
- Updated backend documentation
- Ran
air format . - Verified tests pass
When not to use it
- →When the database does not support the required functions
- →For simple R queries that do not reach the database backend
Prerequisites
Limitations
- →Requires deep knowledge of the specific SQL dialect
- →Debugging generated SQL can be complex
- →Limited to the dbplyr framework constraints
How it compares
Provides a structured pathway for extending R-to-SQL functionality that ensures dialect-specific research precedes code implementation.
Compared to similar skills
sql-translation side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| sql-translation (this skill) | 1 | 8mo | Review | Advanced |
| drizzle-orm | 32 | 2mo | No flags | Intermediate |
| event-store-design | 5 | 2mo | No flags | Advanced |
| backend-development | 17 | 4mo | No flags | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by tidyverse
View all by tidyverse →You might also like
drizzle-orm
EpicenterHQ
Drizzle ORM patterns for type branding and custom types. Use when working with Drizzle column definitions, branded types, or custom type conversions.
event-store-design
wshobson
Design and implement event stores for event-sourced systems. Use when building event sourcing infrastructure, choosing event store technologies, or implementing event persistence patterns.
backend-development
skillcreatorai
Backend API design, database architecture, microservices patterns, and test-driven development. Use for designing APIs, database schemas, or backend system architecture.
postgresql
sickn33
Design a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features
epic-database
epicweb-dev
Guide on Prisma, SQLite, and LiteFS for Epic Stack
prisma-connection-pool-exhaustion
blader
Fix Prisma "Too many connections" and connection pool exhaustion errors in serverless environments (Vercel, AWS Lambda, Netlify). Use when: (1) Error "P2024: Timed out fetching a new connection from the pool", (2) PostgreSQL "too many connections for role", (3) Database works locally but fails in production serverless, (4) Intermittent database timeouts under load.