🛠️ SQL Utility
SQL Utility is a lightweight, flexible Rust library designed to simplify the dynamic construction of SQL queries. It provides a robust set of helper functions to programmatically generate SELECT, INSERT, UPDATE, and DELETE statements with ease.
📖 Table of Contents
✨ Features
- Dynamic Query Building: Construct complex SQL queries at runtime.
- Type Safety: Leverages Rust's type system and
serde_jsonfor safe value handling. - Flexible API: Low-level builders and high-level helpers.
- Zero Dependencies: (Well, almost - just
serde_json!).
📦 Installation
Add the following to your Cargo.toml file:
[]
= "0.1.2"
= "1.0"
🚀 Usage
Select Queries
Build SELECT queries using either the granular build_select_sql or the concise make_query helper.
🔹 Using build_select_sql
use build_select_sql;
let sql = build_select_sql;
assert_eq!;
🔹 Using make_query
The make_query function simplifies constructing clauses from arrays of strings.
use make_query;
let sql = make_query;
// Note: make_query joins items with " , " (comma surrounded by spaces)
assert_eq!;
Insert Queries
Generate INSERT statements using build_insert_sql. It accepts a HashMap<String, serde_json::Value> to map column names to values.
use HashMap;
use json;
use build_insert_sql;
let mut data = new;
data.insert;
data.insert;
data.insert;
let sql = build_insert_sql;
// Output: INSERT INTO "users" ("name", "age", "is_admin") VALUES ('John Doe', 30, false)
// Note: The order of columns depends on the HashMap iteration order.
Update Queries
Generate UPDATE statements with build_update_sql.
use HashMap;
use json;
use build_update_sql;
let mut data = new;
data.insert;
data.insert;
let sql = build_update_sql;
// Output: UPDATE "users" SET "name" = 'Jane Doe' , "updated_at" = '2023-01-01' WHERE id = 1
Delete Queries
Generate DELETE statements with build_delete_sql.
use build_delete_sql;
let sql = build_delete_sql;
assert_eq!;
🛠 Helper Functions
The library includes several utility functions to help you manually construct SQL parts:
| Function | Description |
|---|---|
make_column(&[&str]) |
Joins columns with , (comma with spaces). |
make_table(&[&str]) |
Joins tables with , (comma with spaces). |
make_where(&[&str]) |
Joins conditions with AND. |
make_order(&[&str]) |
Joins order clauses with , (comma with spaces). |
quote(&str) |
Escapes single quotes and wraps the string in single quotes. |
quote_identifier(&str) |
Wraps the string in double quotes and escapes internal double quotes. |
Example:
use ;
let where_clause = make_where;
assert_eq!;
let quoted = quote;
assert_eq!;
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
Made with ❤️ in Rust.