2 minutes
HugSQLx - SQL queries turned into Rust functions
The Clojure community is fortunate to have HugSQL - a brilliant library that simplifies working with SQL. HugSQL separates queries from the code, preventing them from cluttering .clj files and transforming them into plain Clojure functions within a namespace. These functions are quite intelligent; the underlying magic connects to PostgreSQL, SQLite, or any supported database via JDBC, executing defined queries with the provided function arguments.
Simple, yet remarkably effective…
Can we achieve something similar in Rust?
It appears we can.

Motivation
HugSqlx truly excels in three key areas when working with SQL:
- Separation of queries from code: this feature enhances formatting, syntax highlighting, and documentation, allowing for clear comments. Your IDE is far more suited to editing .sql files than to handling SQL embedded within Rust source code.
- Named queries: queries become easier to identify, both within the code and in logs when tracking down issues that may have impacted production.
- Queries as documented functions: this approach clarifies the author’s intention, providing insight into what the query does and what results to expect.
Lastly, turning queries into functions enables out-of-the-box auto-completion and quick documentation views, provided your Language Server Protocol (LSP) is up to the task.
Solution (PoC)
HugSqlx is still kind of proof-of-concept, doing its best to materialize these ideas. Although crate is at its newborn stage, it should be quite functional. Standing on the shoulders of awesome SQLx it implements query-as-a-function concept for 3 major databases: postgres, sqlite and mysql. From a technical point of view, entire logic comes down to a simple (more or less..) code transformation which generates a static trait functions for your struct.
First results seem to be promising. I de-cluttered my sources, enjoy LSP happily providing me queries names via auto-completion. And, most importantly, I learned a lot about procedural macros.