sqlutil 0.1.4

A utility library for building SQL queries
Documentation

🛠️ SQL Utility

Crates.io Documentation License

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_json for 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:

[dependencies]
sqlutil = "0.1.4"
serde_json = "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 sqlutil::build_select_sql;

let sql = build_select_sql(
    "users",                 // table
    Some("id, name, email"), // columns
    Some("active = 1"),      // where clause
    Some("created_at DESC"), // order by
    Some(0),                 // offset
    Some(10),                // limit
);

assert_eq!(sql, "SELECT id, name, email FROM \"users\" WHERE active = 1 ORDER BY created_at DESC OFFSET 0 LIMIT 10");

🔹 Using make_query

The make_query function simplifies constructing clauses from arrays of strings. All parameters except tables are Option.

use sqlutil::make_query;

// Full example with all parameters
let sql = make_query(
    &["users"],                            // tables
    Some(&["id", "name"]),                 // columns (None = select *)
    Some(&["age > 18", "active = 1"]),     // where conditions (None = no WHERE)
    Some(&["name ASC"]),                   // order by (None = no ORDER BY)
    Some(0),                               // offset (None = no OFFSET)
    Some(20),                              // limit (None = no LIMIT)
);

// Note: make_query joins items with " , " (comma surrounded by spaces)
assert_eq!(sql, "SELECT id , name FROM \"users\" WHERE age > 18 AND active = 1 ORDER BY name ASC OFFSET 0 LIMIT 20");

// Minimal example — select all from a table
let sql = make_query(&["users"], None, None, None, None, None);
assert_eq!(sql, "SELECT * FROM \"users\"");

Insert Queries

Generate INSERT statements using build_insert_sql. It accepts a HashMap<K, serde_json::Value> where K can be String or &str.

use std::collections::HashMap;
use serde_json::json;
use sqlutil::build_insert_sql;

// Using &str keys
let mut data = HashMap::new();
data.insert("name", json!("John Doe"));
data.insert("age", json!(30));
data.insert("is_admin", json!(false));
data.insert("deleted_at", json!(null));

let sql = build_insert_sql("users", data);

// Output: INSERT INTO "users" ("name", "age", "is_admin", "deleted_at") VALUES ('John Doe', 30, false, NULL)
// Note: The order of columns depends on the HashMap iteration order.

Update Queries

Generate UPDATE statements with build_update_sql. It also accepts a HashMap<K, serde_json::Value> where K can be String or &str.

use std::collections::HashMap;
use serde_json::json;
use sqlutil::build_update_sql;

let mut data = HashMap::new();
data.insert("name", json!("Jane Doe"));
data.insert("updated_at", json!("2023-01-01"));

let sql = build_update_sql(
    "users",
    data,
    Some("id = 1"), // where clause
);

// 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 sqlutil::build_delete_sql;

let sql = build_delete_sql(
    "users", 
    Some("id = 1") // where clause
);

assert_eq!(sql, "DELETE FROM \"users\" WHERE id = 1");

🛠 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 sqlutil::{make_where, quote};

let where_clause = make_where(&["status = 'active'", "count > 0"]);
assert_eq!(where_clause, "status = 'active' AND count > 0");

let quoted = quote("O'Reilly");
assert_eq!(quoted, "'O''Reilly'");

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Made with ❤️ in Rust.