xql
An SQL query builder for sqlx. Work in progress
Table of Contents
Basic Query Building
Suppose you have a table like this:
INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT,
lang TEXT,
year SMALLINT
);
(
id
The CRUD (or ISUD with sql acronym) will be look like this:
INSERT
statement.
let book1 = "The Fellowship of the Rings".to_string;
let auth1 = "J. R. R. Tolkien".to_string;
let book2 = "Dune".to_string;
let auth2 = "Frank Herbret".to_string;
let english = "English".to_string;
let values = ;
let insert = insert
.values
.returning;
assert_eq!;
SELECT
statement.
let select = select
.from
.filter
.order_by;
assert_eq!;
UPDATE
statement.
let author = &"Frank Herbert".to_string;
let update = update
.set
.filter
.returning;
assert_eq!;
DELETE
statement.
let delete = delete
.filter
.returning;
assert_eq!;
Blanket
There are some blanket implementation for traits that defined
in xql::blanket
to assist query building.
Blanket on Expression
Most of expr's function defined in xql::ops
have method of blanket
implementation of xql::blanket::ExprExt
.
use ExprExt;
let cond = "year".greater_than.and;
assert_eq!;
let query = select.from.filter;
assert_eq!;
Well, that looks verbose. It can't be helped, because using gt
or le
will
clash with PartialOrd
(which can't be disabled even with
no_implicit_prelude
). This one below will not compile.
use ExprExt;
let cond = "year".gt.and;
A work around is to turn the left hand side into Expr
first or using a table qualified
column reference.
use Expr;
use ExprExt;
let year = from;
let qualified = ;
let cond = year.gt.and;
assert_eq!;
Blanket on Table Expression
join
family functions have some blanket implementations.
use ExprExt;
use TableExprExt;
let table = "book".join;
assert_eq!;
Blanket on SELECT
and VALUES
statement
SELECT
and VALUES
are the only statements that can use UNION
family functions.
use ResultExt;
let query = select.union;
assert_eq!;
In case you're wondering, ResultExt
's name came from
xql::stmt::result::Result
which is an enum of only Select
and Values
. Why
Result
? Well, because naming is hard and it looks good in Stmt
enum definition:
Derive
You can enable derive
feature to make query building looks shorter or nicer.
use Schema;
let shorter = select.from;
assert_eq!;
let nicer = select.from;
assert_eq!;
assert_eq!;
The table qualified column will turn to unqualified in INSERT
's columns or
UPDATE
's SET
.
use Schema;
use ExprExt;
let values = ;
let insert = insert.values;
assert_eq!;
let author = "Frank Herbert".to_string;
let update = update.set.filter;
assert_eq!;
Execution
To execute those queries, enable sqlx
feature and one of postgres
, mysql
or sqlite
feature.
async
Available variants are: fetch_one
, fetch_all
, fetch_optional
with _as
,
_scalar
or no suffix respectively.
Notes on str
and String
You may notice serveral use of &"text".to_string()
in the examples above.
That's because &str
will turn into an identifier while &String
will turn
into a literal text.