| Title: | Grammar of Graphics for SQL |
|---|---|
| Description: | Allows you to write queries that combine SQL (Structured Query Language) data retrieval with visualization specifications in a single, composable syntax. The 'ggsql' package binds directly with the 'ggsql' 'Rust' library and allows you to set up readers and writers and execute queries against it. The package also offers 'knitr' and 'shiny' integration allowing the user to use 'ggsql' in both frameworks. |
| Authors: | Thomas Lin Pedersen [aut, cre] (ORCID: <https://orcid.org/0000-0002-5147-4711>), George Stagg [aut] (ORCID: <https://orcid.org/0009-0006-3173-9846>), Teun van den Brand [aut] (ORCID: <https://orcid.org/0000-0002-9335-7468>), Posit, PBC [cph, fnd] (ROR: <https://ror.org/03wc8by49>) |
| Maintainer: | Thomas Lin Pedersen <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.5.2.9000 |
| Built: | 2026-10-08 17:02:51 UTC |
| Source: | https://github.com/posit-dev/ggsql-r |
Construct a reader whose behavior is defined entirely by R functions you supply. This makes it possible to plug in data sources that aren't provided natively by ggsql (e.g. an in-memory store, a custom HTTP API, a DBI connection, etc.) without touching the Rust side.
custom_reader(execute_sql, register = NULL, unregister = NULL)custom_reader(execute_sql, register = NULL, unregister = NULL)
execute_sql |
A function |
register |
Optional |
unregister |
Optional |
Only execute_sql is required. If register or unregister are
omitted, calling ggsql_register() / ggsql_unregister() on the
returned reader raises an error.
A Reader object, usable anywhere the other *_reader()
constructors are accepted.
Other readers:
duckdb_reader(),
odbc_reader(),
snowflake_reader()
# A trivial reader backed by a list of data frames in an environment, # delegating the actual SQL engine to an in-memory DuckDB. store <- new.env(parent = emptyenv()) backend <- duckdb_reader() reader <- custom_reader( execute_sql = function(sql) ggsql_execute_sql(backend, sql), register = function(name, df, replace) { store[[name]] <- df ggsql_register(backend, df, name, replace = replace) }, unregister = function(name) { rm(list = name, envir = store) ggsql_unregister(backend, name) } ) ggsql_register(reader, mtcars, "cars") ggsql_execute_sql(reader, "SELECT mpg, disp FROM cars LIMIT 3")# A trivial reader backed by a list of data frames in an environment, # delegating the actual SQL engine to an in-memory DuckDB. store <- new.env(parent = emptyenv()) backend <- duckdb_reader() reader <- custom_reader( execute_sql = function(sql) ggsql_execute_sql(backend, sql), register = function(name, df, replace) { store[[name]] <- df ggsql_register(backend, df, name, replace = replace) }, unregister = function(name) { rm(list = name, envir = store) ggsql_unregister(backend, name) } ) ggsql_register(reader, mtcars, "cars") ggsql_execute_sql(reader, "SELECT mpg, disp FROM cars LIMIT 3")
Creates a DuckDB database connection that can execute SQL queries and register data frames as queryable tables. The default creates an empty in-memory database but you can also pass the path to a DuckDB database to directly interact with that.
duckdb_reader(database = NULL)duckdb_reader(database = NULL)
database |
Path to a DuckDB database file, or |
A Reader object.
Other readers:
custom_reader(),
odbc_reader(),
snowflake_reader()
reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") df <- ggsql_execute_sql(reader, "SELECT mpg, disp FROM cars LIMIT 5")reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") df <- ggsql_execute_sql(reader, "SELECT mpg, disp FROM cars LIMIT 5")
Parses the query, and execute it against the reader's database. Returns
either a visualization specification ready for rendering (ggsql_execute) or
a data frame with the query result (ggsql_execute_sql).
ggsql_execute(reader, query) ggsql_execute_sql(reader, query)ggsql_execute(reader, query) ggsql_execute_sql(reader, query)
reader |
A |
query |
A ggsql query string (SQL + VISUALISE clause). |
ggsql_execute() returns Spec object. ggsql_execute_sql()
returns a data frame or NULL
reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x, disp AS y DRAW point" )reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x, disp AS y DRAW point" )
After registration, the data frame can be queried by name in SQL statements.
You can use ggsql_table to extract tables from the reader (both registered
ones and those native to the backend) and ggsql_table_names to get a vector
of all the tables in reader.
ggsql_register(reader, df, name, replace = FALSE) ggsql_unregister(reader, name) ggsql_table(reader, name) ggsql_table_names(reader)ggsql_register(reader, df, name, replace = FALSE) ggsql_unregister(reader, name) ggsql_table(reader, name) ggsql_table_names(reader)
reader |
A |
df |
A data frame to register. |
name |
The name of the table. |
replace |
If |
reader for ggsql_register() and ggsql_unregister().
ggsql_table returns a data.frame if the table exists and NULL if not.
ggsql_table_names return a character vector.
reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") ggsql_table_names(reader) ggsql_table(reader, "cars") ggsql_unregister(reader, "cars") ggsql_table_names(reader)reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") ggsql_table_names(reader) ggsql_table(reader, "cars") ggsql_unregister(reader, "cars") ggsql_table_names(reader)
This function takes a Spec object as returned by ggsql_execute() and
renders it with the provided writer.
ggsql_render(writer, spec)ggsql_render(writer, spec)
writer |
A |
spec |
A |
Writer dependent:
svg_writer(): A string holding the SVG markup of the visualization
pdf_writer(): A raw vector holding the PDF document
hep_writer(): A raw vector holding the .hep plot document
vegalite_writer(): A string holding the Vega-Lite JSON representation
(deprecated)
reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x DRAW histogram" ) ggsql_render(svg_writer(), spec)reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x DRAW histogram" ) ggsql_render(svg_writer(), spec)
This function renders a specification with one of the native ggsql writers
and writes it to disk. The format is derived from the file extension:
.svg, .pdf, and .hep are written directly by the corresponding
writer, .png is converted from the SVG output using the rsvg package, and
.json writes the (deprecated) Vega-Lite representation.
ggsql_save(spec, file, width = 600, height = 400, dpi = 96)ggsql_save(spec, file, width = 600, height = 400, dpi = 96)
spec |
A |
file |
Output file path. Extension determines format: |
width |
Width in pixels. |
height |
Height in pixels. |
dpi |
Resolution in dots per inch. |
file, invisibly.
reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x, disp AS y DRAW point" ) spec_file <- tempfile(fileext = ".svg") ggsql_save(spec, spec_file)reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x, disp AS y DRAW point" ) spec_file <- tempfile(fileext = ".svg") ggsql_save(spec, spec_file)
Registers a duckdb_reader() for use by all renderGgsql() outputs in the
current Shiny session. Must be called from within a Shiny server function
(i.e., while a session is active). The reader is automatically cleaned up
when the session ends.
ggsql_session_reader(reader, session = shiny::getDefaultReactiveDomain())ggsql_session_reader(reader, session = shiny::getDefaultReactiveDomain())
reader |
A |
session |
The Shiny session object. Defaults to the current session. |
The reader, invisibly.
library(shiny) ui <- fluidPage( ggsqlOutput("chart") ) server <- function(input, output, session) { ggsql_session_reader(duckdb_reader()) output$chart <- renderGgsql({ "SELECT * FROM r:mtcars VISUALISE mpg AS x, disp AS y DRAW point" }) } shinyApp(ui, server)library(shiny) ui <- fluidPage( ggsqlOutput("chart") ) server <- function(input, output, session) { ggsql_session_reader(duckdb_reader()) output$chart <- renderGgsql({ "SELECT * FROM r:mtcars VISUALISE mpg AS x, disp AS y DRAW point" }) } shinyApp(ui, server)
Checks query syntax and semantics without executing SQL. Returns a validation result that can be inspected for errors and warnings.
ggsql_validate(query) ggsql_has_visual(x) ggsql_is_valid(x)ggsql_validate(query) ggsql_has_visual(x) ggsql_is_valid(x)
query |
A ggsql query string. |
x |
A |
A ggsql_validated object for ggsql_validate(). A boolean for
ggsql_has_visual() and ggsql_is_valid()
result <- ggsql_validate("SELECT 1 AS x, 2 AS y VISUALISE x, y DRAW point") resultresult <- ggsql_validate("SELECT 1 AS x, 2 AS y VISUALISE x, y DRAW point") result
Create a ggsql_hep htmlwidget from a spec. The spec is rendered to a
.hep plot document server-side and displayed in the browser with the
hephaestus SVG renderer compiled to WebAssembly, which re-lays out the
plot as its container changes size.
ggsql_widget(spec, width = NULL, height = NULL)ggsql_widget(spec, width = NULL, height = NULL)
spec |
A |
width, height
|
Optional widget dimensions passed to
|
An htmlwidget with class ggsql_hep.
Render ggsql visualizations in a Shiny application. renderGgsql() accepts
either a ggsql query string or a Spec object (returned by
ggsql_execute()). When given a string, it validates and executes the query
against reader.
ggsqlOutput(outputId, width = "100%", height = "400px") renderGgsql(expr, reader = NULL, env = parent.frame(), quoted = FALSE)ggsqlOutput(outputId, width = "100%", height = "400px") renderGgsql(expr, reader = NULL, env = parent.frame(), quoted = FALSE)
outputId |
Output variable to read from. |
width, height
|
CSS dimensions for the output container. |
expr |
An expression that returns a ggsql query string or a |
reader |
A |
env |
The environment in which to evaluate |
quoted |
Logical. Is |
ggsqlOutput() returns a Shiny UI element. renderGgsql() returns
a Shiny render function.
library(shiny) ui <- fluidPage( ggsqlOutput("chart") ) server <- function(input, output, session) { ggsql_session_reader(duckdb_reader()) output$chart <- renderGgsql({ "SELECT * FROM r:mtcars VISUALISE mpg AS x, disp AS y DRAW point" }) } shinyApp(ui, server)library(shiny) ui <- fluidPage( ggsqlOutput("chart") ) server <- function(input, output, session) { ggsql_session_reader(duckdb_reader()) output$chart <- renderGgsql({ "SELECT * FROM r:mtcars VISUALISE mpg AS x, disp AS y DRAW point" }) } shinyApp(ui, server)
Creates a connection to a database through an ODBC driver. Can execute SQL queries and, where the backend supports it, register R data frames as temporary tables. Requires an ODBC driver manager (unixODBC/iODBC on Unix, built into Windows) and the appropriate ODBC driver for the target database to be installed.
odbc_reader( dsn = NULL, driver = NULL, server = NULL, database = NULL, uid = NULL, pwd = NULL, ..., connection_string = NULL )odbc_reader( dsn = NULL, driver = NULL, server = NULL, database = NULL, uid = NULL, pwd = NULL, ..., connection_string = NULL )
dsn |
Name of a data source configured in |
driver |
ODBC driver name (e.g. |
server, database, uid, pwd
|
Common ODBC parameters. |
... |
Additional named |
connection_string |
A full ODBC connection string, e.g.
|
Either pass a full ODBC connection string via connection_string, or supply
named components (dsn, driver, server, database, uid, pwd, plus
any extra key = value pairs in ...) and they will be assembled into a
connection string. If connection_string is supplied, the other named
arguments are ignored.
A Reader object.
Connection strings are stored in-memory for the life of the reader. Prefer
configuring credentials through a DSN, ~/.odbc.ini, or environment
variables rather than hard-coding passwords in scripts.
Other readers:
custom_reader(),
duckdb_reader(),
snowflake_reader()
## Not run: # Using a preconfigured DSN reader <- odbc_reader(dsn = "mydsn") # Building a connection string from components reader <- odbc_reader( driver = "{PostgreSQL}", server = "localhost", database = "mydb", uid = "user", pwd = "secret", Port = 5432 ) # Passing a full connection string reader <- odbc_reader("Driver={SQLite3};Database=:memory:") ## End(Not run)## Not run: # Using a preconfigured DSN reader <- odbc_reader(dsn = "mydsn") # Building a connection string from components reader <- odbc_reader( driver = "{PostgreSQL}", server = "localhost", database = "mydb", uid = "user", pwd = "secret", Port = 5432 ) # Passing a full connection string reader <- odbc_reader("Driver={SQLite3};Database=:memory:") ## End(Not run)
Convenience constructor for Snowflake connections. Uses the ODBC reader
under the hood with the Snowflake driver, and takes advantage of the
dedicated Snowflake handling in the ggsql Rust core:
snowflake_reader( account = NULL, warehouse = NULL, database = NULL, schema = NULL, role = NULL, user = NULL, password = NULL, authenticator = NULL, connection_name = NULL, driver = NULL, ..., connection_string = NULL )snowflake_reader( account = NULL, warehouse = NULL, database = NULL, schema = NULL, role = NULL, user = NULL, password = NULL, authenticator = NULL, connection_name = NULL, driver = NULL, ..., connection_string = NULL )
account |
Snowflake account identifier (e.g. |
warehouse, database, schema, role
|
Snowflake session defaults. |
user, password
|
User credentials. Prefer a DSN, |
authenticator |
Snowflake authenticator (e.g. |
connection_name |
Named entry in |
driver |
Override the ODBC driver name (defaults to |
... |
Additional named |
connection_string |
A full raw connection string, bypassing the named
arguments. |
Special handling of Snowflake includes:
If connection_name is supplied (or ConnectionName= appears in the
connection string), it is resolved against ~/.snowflake/connections.toml.
When running inside Posit Workbench, an OAuth token is automatically injected if one is available.
Schema introspection uses Snowflake's SHOW DATABASES / SCHEMAS / TABLES
commands rather than information_schema.
Requires the Snowflake ODBC driver to be installed on the system.
A Reader object.
Other readers:
custom_reader(),
duckdb_reader(),
odbc_reader()
## Not run: # Using a named connection from ~/.snowflake/connections.toml reader <- snowflake_reader(connection_name = "my_workbench") # Browser-based SSO reader <- snowflake_reader( account = "xy12345.us-east-1", user = "[email protected]", authenticator = "externalbrowser", warehouse = "COMPUTE_WH", database = "ANALYTICS", schema = "PUBLIC", role = "ANALYST" ) ## End(Not run)## Not run: # Using a named connection from ~/.snowflake/connections.toml reader <- snowflake_reader(connection_name = "my_workbench") # Browser-based SSO reader <- snowflake_reader( account = "xy12345.us-east-1", user = "[email protected]", authenticator = "externalbrowser", warehouse = "COMPUTE_WH", database = "ANALYTICS", schema = "PUBLIC", role = "ANALYST" ) ## End(Not run)
These functions allow you to extract various information from a Spec object
returned by ggsql_execute().
ggsql_metadata(spec) ggsql_sql(spec) ggsql_visual(spec) ggsql_layer_count(spec) ggsql_layer_data(spec, index = 1L) ggsql_stat_data(spec, index = 1L) ggsql_layer_sql(spec, index = 1L) ggsql_stat_sql(spec, index = 1L) ggsql_warnings(spec)ggsql_metadata(spec) ggsql_sql(spec) ggsql_visual(spec) ggsql_layer_count(spec) ggsql_layer_data(spec, index = 1L) ggsql_stat_data(spec, index = 1L) ggsql_layer_sql(spec, index = 1L) ggsql_stat_sql(spec, index = 1L) ggsql_warnings(spec)
spec |
A |
index |
Layer index |
ggsql_metadata: A list with elements rows, columns, and layer_count
ggsql_sql: A character string with the SQL portion of the query
ggsql_visual: A character string with the visual portion of the query
ggsql_layer_count: An integer giving the number of layers
ggsql_layer_data: A data frame, or NULL if no data is available for
this layer
ggsql_stat_data: A data frame, or NULL if the layer doesn't use a stat
transform
ggsql_layer_sql: A character string with the SQL query used by the layer
to fetch its data, or NULL if the layer doesn't have any data.
ggsql_stat_sql: A character string with the SQL query used by the layers
stat transform, or NULL if the layer doesn't have a stat transform.
ggsql_warnings: A data.frame with columns message, line, and column
giving the validation warnings for the spec
reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x DRAW histogram" ) ggsql_metadata(spec) ggsql_visual(spec)reader <- duckdb_reader() ggsql_register(reader, mtcars, "cars") spec <- ggsql_execute(reader, "SELECT * FROM cars VISUALISE mpg AS x DRAW histogram" ) ggsql_metadata(spec) ggsql_visual(spec)
Writers turn a Spec object (as returned by ggsql_execute()) into an
output artifact. ggsql provides the following writers:
svg_writer(width = 600, height = 400, dpi = 96) pdf_writer(width = 600, height = 400, dpi = 96) hep_writer()svg_writer(width = 600, height = 400, dpi = 96) pdf_writer(width = 600, height = 400, dpi = 96) hep_writer()
width, height
|
Canvas dimensions in pixels. For |
dpi |
Resolution of the canvas in dots per inch. |
svg_writer(): A vector graphic in SVG format
pdf_writer(): A vector graphic in PDF format
hep_writer(): A .hep plot document — a self-contained description of
the resolved plot that a consumer (e.g. the ggsql htmlwidget) can render
and re-layout at any size
vegalite_writer(): A Vega-Lite JSON specification. Deprecated — the
Vega-Lite backend is being phased out of ggsql in favour of the native
writers above
A Writer object.
svg_writer() pdf_writer() hep_writer()svg_writer() pdf_writer() hep_writer()