parsql_postgres/
traits.rs

1use postgres;
2use postgres::{
3    types::{FromSql, ToSql},
4    Error, Row,
5};
6
7/// SQL sorguları oluşturmak için trait (SELECT işlemleri için).
8/// Bu trait, `Queryable` derive makrosu tarafından uygulanır.
9pub trait SqlQuery<R> {
10    /// SQL sorgu string'ini döndürür.
11    fn query() -> String;
12}
13
14/// SQL komutları oluşturmak için trait (INSERT/UPDATE/DELETE işlemleri için).
15/// Bu trait, `Insertable`, `Updateable` ve `Deletable` derive makroları tarafından uygulanır.
16pub trait SqlCommand {
17    /// SQL komut string'ini döndürür.
18    fn query() -> String;
19}
20
21/// SQL parametreleri sağlamak için trait.
22/// Bu trait, `SqlParams` derive makrosu tarafından uygulanır.
23pub trait SqlParams {
24    /// SQL parametrelerinin referanslarını içeren bir vektör döndürür.
25    fn params(&self) -> Vec<&(dyn ToSql + Sync)>;
26}
27
28/// UPDATE işlemleri için parametre sağlamak üzere trait.
29/// Bu trait, `UpdateParams` derive makrosu tarafından uygulanır.
30pub trait UpdateParams {
31    /// UPDATE işlemleri için SQL parametrelerinin referanslarını içeren bir vektör döndürür.
32    fn params(&self) -> Vec<&(dyn ToSql + Sync)>;
33}
34
35/// Veritabanı satırlarını Rust struct'larına dönüştürmek için trait.
36/// Bu trait, `FromRow` derive makrosu tarafından uygulanır.
37pub trait FromRow {
38    /// Bir veritabanı satırını Rust struct'ına dönüştürür.
39    ///
40    /// # Argümanlar
41    /// * `row` - Veritabanı satırına referans
42    ///
43    /// # Dönüş Değeri
44    /// * `Result<Self, Error>` - Dönüştürülmüş struct veya hata
45    fn from_row(row: &Row) -> Result<Self, Error>
46    where
47        Self: Sized;
48}
49
50/// CrudOps trait defines the CRUD (Create, Read, Update, Delete) operations
51/// that can be performed on a PostgreSQL database.
52///
53/// This trait is implemented for the `postgres::Client` struct, allowing
54/// CRUD operations to be called as extension methods on a client.
55///
56/// # Example
57///
58/// ```rust,no_run
59/// use postgres::{Client, NoTls, Error};
60/// use parsql::postgres::CrudOps;
61/// use parsql::macros::{Insertable, SqlParams, Queryable, FromRow};
62///
63/// #[derive(Insertable, SqlParams)]
64/// #[table("users")]
65/// struct InsertUser {
66///     name: String,
67///     email: String,
68/// }
69///
70/// #[derive(Queryable, FromRow, SqlParams)]
71/// #[table("users")]
72/// #[where_clause("id = $")]
73/// struct GetUser {
74///     id: i32,
75///     name: String,
76///     email: String,
77/// }
78///
79/// fn main() -> Result<(), Error> {
80///     let mut client = Client::connect(
81///         "host=localhost user=postgres dbname=test",
82///         NoTls,
83///     )?;
84///    
85///     // Extension method for insert
86///     let insert_user = InsertUser {
87///         name: "John".to_string(),
88///         email: "john@example.com".to_string(),
89///     };
90///     let rows_affected = client.insert(insert_user)?;
91///    
92///     // Extension method for get
93///     let get_user = GetUser {
94///         id: 1,
95///         name: String::new(),
96///         email: String::new(),
97///     };
98///     let user = client.fetch(&get_user)?;
99///    
100///     println!("User: {:?}", user);
101///     Ok(())
102/// }
103/// ```
104pub trait CrudOps {
105    /// Inserts a new record into the PostgreSQL database.
106    ///
107    /// # Arguments
108    /// * `entity` - Data object to be inserted (must implement SqlCommand and SqlParams traits)
109    ///
110    /// # Returns
111    /// * `Result<P, Error>` - On success, returns the inserted ID or return value; on failure, returns Error
112    fn insert<T: SqlCommand + SqlParams, P: for<'a> FromSql<'a> + Send + Sync>(
113        &mut self,
114        entity: T,
115    ) -> Result<P, Error>;
116
117    /// Updates records in the PostgreSQL database.
118    ///
119    /// # Arguments
120    /// * `entity` - Data object containing the update information (must implement SqlCommand and UpdateParams traits)
121    ///
122    /// # Returns
123    /// * `Result<u64, Error>` - On success, returns the number of updated records; on failure, returns Error
124    fn update<T: SqlCommand + UpdateParams>(&mut self, entity: T) -> Result<u64, Error>;
125
126    /// Deletes records from the PostgreSQL database.
127    ///
128    /// # Arguments
129    /// * `entity` - Data object containing delete conditions (must implement SqlCommand and SqlParams traits)
130    ///
131    /// # Returns
132    /// * `Result<u64, Error>` - On success, returns the number of deleted records; on failure, returns Error
133    fn delete<T: SqlCommand + SqlParams>(&mut self, entity: T) -> Result<u64, Error>;
134
135    /// Retrieves a single record from the PostgreSQL database.
136    ///
137    /// # Arguments
138    /// * `params` - Data object containing query parameters (must implement SqlQuery and SqlParams traits)
139    ///
140    /// # Returns
141    /// * `Result<R, Error>` - On success, returns the retrieved record; on failure, returns Error
142    fn fetch<P, R>(&mut self, params: &P) -> Result<R, Error>
143    where
144        P: SqlQuery<R> + SqlParams,
145        R: FromRow;
146
147    /// Retrieves multiple records from the PostgreSQL database.
148    ///
149    /// # Arguments
150    /// * `params` - Data object containing query parameters (must implement SqlQuery and SqlParams traits)
151    ///
152    /// # Returns
153    /// * `Result<Vec<R>, Error>` - On success, returns a vector of records; on failure, returns Error
154    fn fetch_all<P, R>(&mut self, params: &P) -> Result<Vec<R>, Error>
155    where
156        P: SqlQuery<R> + SqlParams,
157        R: FromRow;
158
159    /// Executes a custom query and transforms the result using the provided function.
160    ///
161    /// # Arguments
162    /// * `entity` - Data object containing query parameters (must implement SqlQuery and SqlParams traits)
163    /// * `to_model` - Function to transform the database row into the desired type
164    ///
165    /// # Returns
166    /// * `Result<R, Error>` - On success, returns the transformed result; on failure, returns Error
167    fn select<T, F, R>(&mut self, entity: &T, to_model: F) -> Result<R, Error>
168    where
169        T: SqlQuery<T> + SqlParams,
170        F: FnOnce(&Row) -> Result<R, Error>;
171
172    /// Executes a custom query and transforms all results using the provided function.
173    ///
174    /// # Arguments
175    /// * `entity` - Data object containing query parameters (must implement SqlQuery and SqlParams traits)
176    /// * `to_model` - Function to transform database rows into the desired type
177    ///
178    /// # Returns
179    /// * `Result<Vec<R>, Error>` - On success, returns a vector of transformed results; on failure, returns Error
180    fn select_all<T, F, R>(&mut self, entity: &T, to_model: F) -> Result<Vec<R>, Error>
181    where
182        T: SqlQuery<T> + SqlParams,
183        F: FnMut(&Row) -> Result<R, Error>;
184}