parsql_postgres/lib.rs
1//! # parsql-postgres
2//!
3//! Synchronous PostgreSQL integration for parsql.
4//! This crate provides synchronous APIs for working with PostgreSQL databases.
5//!
6//! ## Features
7//!
8//! - Synchronous PostgreSQL operations
9//! - Automatic SQL query generation
10//! - Secure parameter management
11//! - Generic CRUD operations
12//! - Transaction support
13//!
14//! ## Usage
15//!
16//! ```rust,no_run
17//! use postgres::{Client, NoTls, Error};
18//! use parsql::postgres::{get, insert};
19//!
20//! #[derive(Insertable, SqlParams)]
21//! #[table("users")]
22//! pub struct InsertUser {
23//! pub name: String,
24//! pub email: String,
25//! }
26//!
27//! #[derive(Queryable, SqlParams, FromRow)]
28//! #[table("users")]
29//! #[where_clause("id = $")]
30//! pub struct GetUser {
31//! pub id: i32,
32//! pub name: String,
33//! pub email: String,
34//! }
35//!
36//! fn main() -> Result<(), Error> {
37//! let mut client = Client::connect(
38//! "host=localhost user=postgres dbname=test",
39//! NoTls,
40//! )?;
41//!
42//! // Insert a new user
43//! let insert_user = InsertUser {
44//! name: "John".to_string(),
45//! email: "john@example.com".to_string(),
46//! };
47//!
48//! let id = insert(&mut client, insert_user)?;
49//!
50//! // Get the user back
51//! let get_user = GetUser::new(id as i32);
52//! let user = get(&mut client, &get_user)?;
53//!
54//! println!("User: {:?}", user);
55//! Ok(())
56//! }
57//! ```
58
59pub mod crud_ops;
60
61pub use postgres::{Client, Error, Row};
62pub use postgres::types::ToSql;
63
64// Re-export crud operations
65pub use crud_ops::{insert, select, select_all, update, delete, get, get_all, get_by_query};
66
67pub use parsql_macros as macros;
68
69/// Trait for generating SQL queries.
70/// This trait is implemented by the derive macro `Queryable`, `Insertable`, `Updateable`, and `Deletable`.
71pub trait SqlQuery {
72 /// Returns the SQL query string.
73 fn query() -> String;
74}
75
76/// Trait for providing SQL parameters.
77/// This trait is implemented by the derive macro `SqlParams`.
78pub trait SqlParams {
79 /// Returns a vector of references to SQL parameters.
80 fn params(&self) -> Vec<&(dyn postgres::types::ToSql + Sync)>;
81}
82
83/// Trait for providing UPDATE parameters.
84/// This trait is implemented by the derive macro `UpdateParams`.
85pub trait UpdateParams {
86 /// Returns a vector of references to SQL parameters for UPDATE operations.
87 fn params(&self) -> Vec<&(dyn postgres::types::ToSql + Sync)>;
88}
89
90/// Trait for converting database rows to Rust structs.
91/// This trait is implemented by the derive macro `FromRow`.
92pub trait FromRow {
93 /// Converts a database row to a Rust struct.
94 ///
95 /// # Arguments
96 /// * `row` - A reference to a database row
97 ///
98 /// # Returns
99 /// * `Result<Self, Error>` - The converted struct or an error
100 fn from_row(row: &postgres::Row) -> Result<Self, postgres::Error>
101 where
102 Self: Sized;
103}