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