6 releases

0.0.6 Jan 24, 2024
0.0.5 Jan 24, 2024
0.0.4 Dec 31, 2023

#1234 in Database interfaces

23 downloads per month

LGPL-3.0-or-later

78KB
873 lines

squeal

A Rust Query Builder.

Create a (safe, correct) Rust structure representing a SQL query and then render it into SQL itself.

Escape hatches in appropriate places are designed in.

The targeted SQL dialect is PostgreSQL. The Postgres library is https://docs.rs/postgres/latest/postgres/

A similar library for Go is https://github.com/leporo/sqlf.

readiness

This code is not ready for use.

Built against Rust 1.75.x.

license

License: LGPL 3.0 or later.


lib.rs:

Simple Query Builder for Rust

Provides a straightforward way to build SQL queries in Rust. Conceptually, you build a list of properly termed objects in a "Query" object, and then call the sql() method on the Query object to get the SQL string.

Escape hatches are built in to allow you to use any SQL you want and have it integrated properly.

Part of the design goal is not to use attributes, macros, or other "magic" to make this work.

"Keep it simple & stupid."

Examples

use squeal::*;

let result = Query {
     select: Some(Select::new(Columns::Star)),
     from: Some("table"),
     where_clause: Some(Term::Condition(
       Box::new(Term::Atom("a")),
     Op::O("<>"),
     Box::new(Term::Atom("b")))),
     group_by: None,
    having: None,
    order_by: None,
    limit: None,
    offset: None,
    for_update: false,
}.sql();

assert_eq!(result, "SELECT * FROM table WHERE a <> b");

Note the verbosity of the Enum scoping. This is not intentional and an artifact of this still being in early development.

Example using Q() fluent interface:

use squeal::*;
let mut qb = Q();
let result = qb.select(vec!["a", "sum(b)"])
  .from("the_table")
  .where_(Term::Condition(
     Box::new(Term::Atom("a")),
     Op::O(">"),
     Box::new(Term::Atom("10"))))
  .group_by(vec!["b"])
  .having(Term::Condition(
     Box::new(Term::Atom("a")),
     Op::O(">"),
     Box::new(Term::Atom("1000"))))
  .limit(19)
  .offset(10);
let q = result.build();
assert_eq!(q.sql(), "SELECT a, sum(b) FROM the_table WHERE a > 10 GROUP BY b HAVING a > 1000 LIMIT 19 OFFSET 10");


Dependencies

~7–16MB
~223K SLoC