# ggrothendieck/sqldf architecture

> Architecture diagram of the GitHub repository ggrothendieck/sqldf, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-16). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/ggrothendieck/sqldf
- Repository: https://github.com/ggrothendieck/sqldf

## Overview

1. **What this repository is**
This is an R package, `sqldf`, whose core purpose is to let R users run SQL against R data frames with minimal setup. The package acts as a translation/orchestration layer rather than a data store itself.

2. **Primary runtime flow**
A call to `sqldf(...)` takes SQL text plus one or more R objects, loads the referenced data into a temporary or persistent database, executes the SQL, reads the result back into R, and then usually tears the database down. That “database behind the scenes” is the main architectural boundary of the package.

3. **Core implementation boundary**
The main package logic lives in `R/sqldf.R`, with `R/zzz.R` likely handling package initialization, global options, and backend selection defaults. The package exports the user-facing `sqldf` and `read.csv.sql` APIs described in the man pages.

4. **Backend abstraction**
`sqldf` is backend-agnostic at the API level but backend-specific underneath. It can target:
- SQLite via `RSQLite`/`DBI` by default
- H2 via `RH2`
- PostgreSQL via `RPostgreSQL`
- MySQL via `RMySQL`
The active driver is chosen from the `drv=` argument, package load state, or the `sqldf.driver` option.

5. **Database lifecycle**
There are two modes:
- **Transient mode**: the package creates an in-memory or temp-file database, runs the query, and deletes it afterward.
- **Persistent mode**: calling `sqldf()` with no query opens/closes a reusable connection, or an explicit `dbname=` keeps an external database around.
This persistence boundary matters because it affects whether intermediate tables remain available across calls.

6. **Data ingestion and export**
Input comes from either:
- R data frames already in memory
- file connections / CSV-like files
- SQL statements against pre-existing tables in a database
After query execution, results are fetched back through DBI and then coerced to reasonable R classes where possible.

7. **Type handling and heuristics**
A notable subsystem is class restoration: the package tries to preserve or infer R types such as `Date`, `POSIXct`, and factors when SQL results map back to original column names. This is important for architecture because it sits at the boundary between relational typing and R’s richer object model.

8. **SQL parsing / interpolation support**
The package relies on `gsubfn` for quasi-string interpolation and parsing conveniences, and that in turn may use `tcltk` unless configured to fall back to the slower pure-R engine. This is a separate parsing layer from SQL execution and can be a portability point of failure.

9. **File-reading subsystem**
`read.csv.sql` is a higher-level ingest/query pipeline built on top of `sqldf`. It reads flat files into a temporary SQLite-backed database, applies SQL filtering/projection, and returns only the selected rows to R. The repo also includes helper scripts such as `inst/csv.awk` and `inst/trcomma2dot.vbs`, indicating support for pre-processing awkward file formats.

10. **Testing and examples**
Behavior is documented and exercised through:
- `demo/` scripts for usage examples
- `inst/unitTests/` and `tests/doSvUnit.R` for automated tests
These are important because much of the package’s complexity is in backend-specific edge cases, not just basic query execution.

11. **Packaging and distribution**
This is a standard CRAN-style R package with `DESCRIPTION`, `NAMESPACE`, `man/` docs, and `inst/NEWS` / `inst/THANKS`. The GitHub workflow under `.github/workflows/rhub.yaml` suggests CI focused on CRAN/R-hub style compatibility across environments and database-driver combinations.

12. **Architectural diagram takeaway**
The diagram should center on `R user code -> sqldf API -> backend selection / DBI layer -> concrete database engine -> result coercion back to R`, with side paths for:
- file ingestion via `read.csv.sql`
- optional parsing/interpolation via `gsubfn`/`tcltk`
- persistent vs temporary connection lifecycle
- tests/demos validating behavior across supported database backends

Main entry points: [`R/sqldf.R`](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R) (sqldf()), [`man/read.csv.sql.Rd`](https://github.com/ggrothendieck/sqldf/blob/master/man/read.csv.sql.Rd) (read.csv.sql()), [`demo/sqldf-groupchoose.R`](https://github.com/ggrothendieck/sqldf/blob/master/demo/sqldf-groupchoose.R) (Demos), [`tests/doSvUnit.R`](https://github.com/ggrothendieck/sqldf/blob/master/tests/doSvUnit.R) (Tests)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_core["Core package"]
  node_r_user(("R user code<br/>caller"))
  node_sqldf_api["sqldf()<br/>API<br/>[sqldf.R]"]
  node_backend_select["Backend select<br/>routing<br/>[sqldf.R]"]
  node_db_lifecycle["DB lifecycle<br/>session mgmt<br/>[sqldf.R]"]
  node_dbi_bridge["DBI bridge<br/>DBI orchestration<br/>[sqldf.R]"]
  node_result_coerce["Type restore<br/>coercion<br/>[sqldf.R]"]
end

subgraph group_backends["Backends"]
  node_sqlite_backend[("SQLite<br/>engine")]
  node_h2_backend[("H2<br/>engine")]
  node_pg_backend[("PostgreSQL<br/>engine")]
  node_mysql_backend[("MySQL<br/>engine")]
end

subgraph group_ingest["Ingest and parsing"]
  node_read_csv_sql["read.csv.sql()<br/>file-query API<br/>[read.csv.sql.Rd]"]
  node_gsubfn_layer["gsubfn parse<br/>interpolation<br/>[sqldf.R]"]
  node_tcltk_engine(("tcltk engine<br/>optional parser"))
  node_file_prep["File prep<br/>preprocess<br/>[csv.awk]"]
end

subgraph group_quality["Validation"]
  node_demo_scripts["Demos<br/>examples"]
  node_unit_tests["Tests<br/>test suite<br/>[doSvUnit.R]"]
  node_pkg_docs["Package docs<br/>documentation<br/>[sqldf-package.Rd]"]
end

node_r_user -->|"calls"| node_sqldf_api
node_sqldf_api -->|"routes"| node_backend_select
node_backend_select -->|"opens"| node_db_lifecycle
node_db_lifecycle -->|"uses"| node_dbi_bridge
node_dbi_bridge -->|"default"| node_sqlite_backend
node_dbi_bridge -->|"optional"| node_h2_backend
node_dbi_bridge -->|"optional"| node_pg_backend
node_dbi_bridge -->|"optional"| node_mysql_backend
node_dbi_bridge -->|"returns"| node_result_coerce
node_sqldf_api -->|"parses"| node_gsubfn_layer
node_gsubfn_layer -.->|"can use"| node_tcltk_engine
node_read_csv_sql -->|"preprocesses"| node_file_prep
node_read_csv_sql -->|"builds on"| node_sqldf_api
node_demo_scripts -.->|"demonstrate"| node_sqldf_api
node_unit_tests -.->|"verify"| node_sqldf_api
node_pkg_docs -.->|"documents"| node_sqldf_api
node_backend_select -->|"prefers"| node_sqlite_backend
node_backend_select -->|"selects"| node_h2_backend
node_backend_select -->|"selects"| node_pg_backend
node_backend_select -->|"selects"| node_mysql_backend

click node_sqldf_api "https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R"
click node_backend_select "https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R"
click node_db_lifecycle "https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R"
click node_dbi_bridge "https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R"
click node_result_coerce "https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R"
click node_read_csv_sql "https://github.com/ggrothendieck/sqldf/blob/master/man/read.csv.sql.Rd"
click node_gsubfn_layer "https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R"
click node_file_prep "https://github.com/ggrothendieck/sqldf/blob/master/inst/csv.awk"
click node_demo_scripts "https://github.com/ggrothendieck/sqldf/blob/master/demo/sqldf-groupchoose.R"
click node_unit_tests "https://github.com/ggrothendieck/sqldf/blob/master/tests/doSvUnit.R"
click node_pkg_docs "https://github.com/ggrothendieck/sqldf/blob/master/man/sqldf-package.Rd"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_r_user,node_sqldf_api,node_backend_select,node_db_lifecycle,node_dbi_bridge,node_result_coerce toneBlue
class node_sqlite_backend,node_h2_backend,node_pg_backend,node_mysql_backend toneAmber
class node_read_csv_sql,node_gsubfn_layer,node_tcltk_engine,node_file_prep toneMint
class node_demo_scripts,node_unit_tests,node_pkg_docs toneRose
```

## Components

### Core package

User-facing API and orchestration logic

- **R user code**: caller · R scripts or sessions invoking sqldf
- [sqldf()](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R): API · Main SQL-over-data-frame entry point · `R/sqldf.R`
- [Backend select](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R): routing · Chooses driver from arguments, package state, or options · `R/sqldf.R`
- [DB lifecycle](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R): session mgmt · Creates transient databases or keeps persistent connections · `R/sqldf.R`
- [DBI bridge](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R): DBI orchestration · Loads tables, runs SQL, and fetches results through DBI-style connections · `R/sqldf.R`
- [Type restore](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R): coercion · Restores or infers R classes such as Date, POSIXct, and factors · `R/sqldf.R`

### Backends

Database engines and selection

- **SQLite**: engine · Default embedded database backend via RSQLite/DBI
- **H2**: engine · Java-based backend via RH2
- **PostgreSQL**: engine · Server-backed relational engine via RPostgreSQL
- **MySQL**: engine · Server-backed relational engine via RMySQL

### Ingest and parsing

File loading and SQL interpolation support

- [read.csv.sql()](https://github.com/ggrothendieck/sqldf/blob/master/man/read.csv.sql.Rd): file-query API · Higher-level file ingest plus SQL filter/projection pipeline · `man/read.csv.sql.Rd`
- [gsubfn parse](https://github.com/ggrothendieck/sqldf/blob/master/R/sqldf.R): interpolation · Quasi-string interpolation and parsing support for SQL text · `R/sqldf.R`
- **tcltk engine**: optional parser · Optional parsing backend used by gsubfn when available
- [File prep](https://github.com/ggrothendieck/sqldf/blob/master/inst/csv.awk): preprocess · Helper scripts for awkward flat-file normalization · `inst/csv.awk`

### Validation

Examples, tests, and package docs

- [Demos](https://github.com/ggrothendieck/sqldf/blob/master/demo/sqldf-groupchoose.R): examples · Usage examples and behavior demonstrations · `demo/sqldf-groupchoose.R`
- [Tests](https://github.com/ggrothendieck/sqldf/blob/master/tests/doSvUnit.R): test suite · Automated checks for backend and edge-case behavior · `tests/doSvUnit.R`
- [Package docs](https://github.com/ggrothendieck/sqldf/blob/master/man/sqldf-package.Rd): documentation · CRAN package manual and reference documentation · `man/sqldf-package.Rd`

## Connections

- R user code → sqldf(): calls · User code enters the main query API
- sqldf() → Backend select: routes · Determines which database driver to use
- Backend select → DB lifecycle: opens · Initializes a transient or persistent connection
- DB lifecycle → DBI bridge: uses · Connection management feeds the query/load bridge
- DBI bridge → SQLite: default · Primary embedded backend
- DBI bridge → H2: optional · Alternative backend when selected
- DBI bridge → PostgreSQL: optional · Alternative backend when selected
- DBI bridge → MySQL: optional · Alternative backend when selected
- DBI bridge → Type restore: returns · Fetched SQL results are coerced back into R-friendly classes
- sqldf() → gsubfn parse: parses · SQL text may be interpolated or massaged before execution
- gsubfn parse → tcltk engine: can use · Optional parser backend for interpolation support
- read.csv.sql() → File prep: preprocesses · Supports flat-file normalization before loading
- read.csv.sql() → sqldf(): builds on · Convenience ingest/query pipeline layered on sqldf
- Demos → sqldf(): demonstrate · Example usage of the primary API
- Tests → sqldf(): verify · Exercises core behaviors and backend-specific cases
- Package docs → sqldf(): documents · Documents exported package behavior
- Backend select → SQLite: prefers · SQLite is the default when available
- Backend select → H2: selects · Chosen when configured for H2
- Backend select → PostgreSQL: selects · Chosen when configured for PostgreSQL
- Backend select → MySQL: selects · Chosen when configured for MySQL
