Skip to main content

tank_core/
entity.rs

1use crate::{
2    AnyQuery, ColumnDef, Context, Driver, Executor, Expression, Fragment, Query, RawQuery, Result,
3    Row, RowOwned, RowsAffected, Sql, TableRef, Value, future::Either, stream::Stream,
4    truncate_long, writer::SqlWriter,
5};
6use anyhow::anyhow;
7use futures::{FutureExt, StreamExt};
8use log::Level;
9use std::{
10    future::{self, Future},
11    pin::pin,
12};
13
14pub trait AsEntity {
15    type Entity: Entity;
16    fn as_entity(&self) -> &Self::Entity;
17}
18
19/// Database entity mapping.
20///
21/// Use `#[derive(Entity)]` to implement this trait.
22pub trait Entity: AsEntity + Expression {
23    /// Primary key type. A tuple of field types (or single type) forming the PK.
24    type PrimaryKey<'a>
25    where
26        Self: 'a;
27
28    /// Table reference matching the `#[tank(...)]` attributes.
29    fn table() -> &'static TableRef;
30
31    /// All column definitions in declaration order.
32    fn columns() -> &'static [ColumnDef] {
33        &Self::table().columns
34    }
35
36    /// Extract PK value(s) from `self`.
37    fn primary_key(&self) -> Self::PrimaryKey<'_>;
38
39    /// Build an expression matching the PK of `self`.
40    fn primary_key_expr(&self) -> impl Expression;
41
42    /// Values of all persisted columns in declaration order, borrowing from `self` where possible.
43    fn row_values(&self) -> impl ExactSizeIterator<Item = Value<'_>>;
44
45    /// Full row representation with column labels.
46    fn row(&self) -> RowOwned {
47        RowOwned::new(
48            Self::columns()
49                .iter()
50                .map(|v| v.name().to_string())
51                .collect(),
52            self.row_values().map(Value::into_owned).collect(),
53        )
54    }
55
56    /// Reconstruct `Self` from a labeled row.
57    ///
58    /// Fails if columns are missing or type conversion fails.
59    fn from_row(row: impl Row) -> Result<Self>
60    where
61        Self: Sized;
62
63    /// Create table (and optional schema).
64    ///
65    /// - `if_not_exists`: Emits `IF NOT EXISTS` if supported.
66    /// - `create_schema`: Attempts schema creation first.
67    fn create_table(
68        executor: &mut impl Executor,
69        if_not_exists: bool,
70        create_schema: bool,
71    ) -> impl Future<Output = Result<()>> + Send
72    where
73        Self: Sized,
74    {
75        async move {
76            let mut query = AnyQuery::with_capacity(2048);
77            let writer = executor.driver().sql_writer();
78            if create_schema && !Self::table().schema.is_empty() {
79                writer.write_create_schema(&mut query, Self::table(), true);
80            }
81            if !executor.accepts_multiple_statements() && !query.is_empty() {
82                let mut q = query.into_query(executor.driver());
83                executor.execute(&mut q).await?;
84                query = q.into();
85                query.clear(); // Reuse the buffer
86            }
87            writer.write_create_table(&mut query, Self::table(), if_not_exists);
88            for column in Self::columns().iter().filter(|c| !c.comment.is_empty()) {
89                if !executor.accepts_multiple_statements() && !query.is_empty() {
90                    let mut q = query.into_query(executor.driver());
91                    executor.execute(&mut q).await?;
92                    query = q.into();
93                    query.clear(); // Reuse the buffer
94                }
95                writer.write_column_comment(
96                    &mut Context::new(Fragment::SqlCommentOnColumn, true),
97                    &mut query,
98                    column,
99                );
100            }
101            if !query.is_empty() {
102                executor.execute(query).await?;
103            }
104            Ok(())
105        }
106    }
107
108    /// Drop the table (and optional schema).
109    ///
110    /// - `if_exists`: Emits `IF EXISTS` if supported.
111    /// - `drop_schema`: Drops schema *after* table removal (if empty).
112    fn drop_table(
113        executor: &mut impl Executor,
114        if_exists: bool,
115        drop_schema: bool,
116    ) -> impl Future<Output = Result<()>> + Send
117    where
118        Self: Sized,
119    {
120        async move {
121            let mut query = AnyQuery::with_capacity(256);
122            let writer = executor.driver().sql_writer();
123            writer.write_drop_table(&mut query, Self::table(), if_exists);
124            if drop_schema && !Self::table().schema.is_empty() {
125                if !executor.accepts_multiple_statements() {
126                    let mut q = query.into_query(executor.driver());
127                    executor.execute(&mut q).await?;
128                    // To reuse the allocated buffer
129                    query = q.into();
130                    query.clear();
131                }
132                writer.write_drop_schema(&mut query, Self::table(), true);
133            }
134            executor.execute(query).await.map(|_| ())
135        }
136    }
137
138    /// Insert a single entity.
139    fn insert_one<E: AsEntity>(
140        executor: &mut impl Executor,
141        entity: E,
142    ) -> impl Future<Output = Result<RowsAffected>> + Send {
143        let mut query = AnyQuery::default();
144        executor.driver().sql_writer().write_insert(
145            &mut query,
146            Sql()
147                .insert_into(E::Entity::table())
148                .values([entity.as_entity()]),
149        );
150        executor.execute(query)
151    }
152
153    /// Bulk insert entities.
154    fn insert_many<It>(
155        executor: &mut impl Executor,
156        items: It,
157    ) -> impl Future<Output = Result<RowsAffected>> + Send
158    where
159        Self: Sized,
160        It: IntoIterator + Send,
161        It::IntoIter: Send,
162        It::Item: AsEntity,
163    {
164        executor.append(items)
165    }
166
167    /// Prepare (but do not yet run) a SQL select query.
168    ///
169    /// Returns the prepared statement.
170    fn prepare_find<Exec: Executor>(
171        executor: &mut Exec,
172        condition: impl Expression,
173        limit: Option<u32>,
174    ) -> impl Future<Output = Result<Query<Exec::Driver>>> + Send {
175        let builder = Sql()
176            .select(Self::columns())
177            .from(Self::table())
178            .where_expr(condition)
179            .limit(limit);
180        let writer = executor.driver().sql_writer();
181        let mut query = AnyQuery::default();
182        writer.write_select(&mut query, &builder);
183        async {
184            if let AnyQuery::Raw(RawQuery(sql)) = query {
185                executor.prepare(sql).await
186            } else {
187                Ok(query.into())
188            }
189        }
190    }
191
192    /// Finds the first entity matching a condition expression.
193    ///
194    /// Returns `Ok(None)` if no row matches.
195    fn find_one(
196        executor: &mut impl Executor,
197        condition: impl Expression,
198    ) -> impl Future<Output = Result<Option<Self>>> + Send
199    where
200        Self: Sized,
201    {
202        let stream = Self::find_many(executor, condition, Some(1));
203        async move { pin!(stream).into_future().map(|(v, _)| v).await.transpose() }
204    }
205
206    /// Streams entities matching a condition.
207    ///
208    /// `limit` restricts the maximum number of rows returned at a database level if `Some`
209    /// (if supported by the driver, unlimited otherwise).
210    fn find_many(
211        executor: &mut impl Executor,
212        condition: impl Expression,
213        limit: Option<u32>,
214    ) -> impl Stream<Item = Result<Self>> + Send
215    where
216        Self: Sized,
217    {
218        let builder = Sql()
219            .select(Self::columns())
220            .from(Self::table())
221            .where_expr(condition)
222            .limit(limit);
223        executor
224            .fetch(builder.build(&executor.driver()))
225            .map(|result| result.and_then(Self::from_row))
226    }
227
228    /// Deletes all entities matching a condition.
229    ///
230    /// Returns the number of deleted rows.
231    fn delete_many(
232        executor: &mut impl Executor,
233        condition: impl Expression,
234    ) -> impl Future<Output = Result<RowsAffected>> + Send
235    where
236        Self: Sized,
237    {
238        let mut query = AnyQuery::with_capacity(128);
239        executor
240            .driver()
241            .sql_writer()
242            .write_delete(&mut query, Self::table(), condition);
243        executor.execute(query)
244    }
245
246    /// Saves the entity (insert or update if available) based on primary key presence.
247    ///
248    /// Errors:
249    /// - Missing PK in the table.
250    /// - Execution failures from underlying driver.
251    fn save(&self, executor: &mut impl Executor) -> impl Future<Output = Result<()>> + Send
252    where
253        Self: Sized,
254        for<'s> &'s Self: AsEntity,
255    {
256        if Self::table().primary_key().next().is_none() {
257            return Either::Left(future::ready(
258                Err(anyhow!(
259                    "Cannot save an entity without a primary key, it would always result in an insert",
260                ))
261                .inspect_err(|e| log::error!("{e:#}")),
262            ));
263        }
264        let mut query = AnyQuery::default();
265        executor.driver().sql_writer().write_insert(
266            &mut query,
267            Sql().insert_into(Self::table()).values([self]).update(),
268        );
269        let context = format!(
270            "While saving using the query {}",
271            truncate_long(&query.as_str())
272        );
273        Either::Right(executor.execute(query).map(|mut v| {
274            if let Ok(result) = v
275                && let Some(affected) = result.rows_affected
276                && affected > 2
277            {
278                v = Err(anyhow!(
279                    "The driver returned affected rows: {affected} (expected <= 2)"
280                ));
281            }
282            match v {
283                Ok(_) => Ok(()),
284                Err(e) => Err(e.context(context)),
285            }
286        }))
287    }
288
289    /// Deletes this entity instance via its primary key.
290    ///
291    /// Errors:
292    /// - Missing PK in the table.
293    /// - If not exactly one row was deleted.
294    /// - Execution failures from underlying driver.
295    fn delete(&self, executor: &mut impl Executor) -> impl Future<Output = Result<()>> + Send
296    where
297        Self: Sized,
298    {
299        if Self::table().primary_key().next().is_none() {
300            return Either::Left(future::ready(
301                Err(anyhow!(
302                    "Cannot delete an entity without a primary key, it would delete nothing",
303                ))
304                .inspect_err(|e| log::error!("{e:#}")),
305            ));
306        }
307        Either::Right(
308            Self::delete_many(executor, self.primary_key_expr()).map(|v| {
309                v.and_then(|v| {
310                    if let Some(affected) = v.rows_affected {
311                        if affected != 1 {
312                            let error = anyhow!(
313                                "The query deleted {affected} rows instead of the expected 1"
314                            );
315                            log::log!(
316                                if affected == 0 {
317                                    Level::Info
318                                } else {
319                                    Level::Error
320                                },
321                                "{error}",
322                            );
323                            return Err(error);
324                        }
325                    }
326                    Ok(())
327                })
328            }),
329        )
330    }
331}