renox_core/db/model.rs
1use std::future::Future;
2
3use super::{
4 DateTime, Db, DbValue, Executor, ModelColumn, ModelIndex, ModelKey, Query, ToDbValue, now,
5 quote, sql,
6};
7use crate::{Error, Result};
8use anyhow::anyhow;
9
10/// A struct stored as a row in a table. Derive it with `#[derive(Model)]`.
11///
12/// ```
13/// # use renox::prelude::*;
14/// # use serde::Serialize;
15/// #[derive(Model, Serialize, Default)]
16/// #[model(table = "products", soft_deletes)]
17/// struct Product {
18/// id: i64,
19/// name: String,
20/// price: i64,
21/// created_at: Option<DateTime>,
22/// updated_at: Option<DateTime>,
23/// deleted_at: Option<DateTime>,
24/// }
25///
26/// # async fn demo(db: Db) -> Result {
27/// let mut coffee = Product { name: "Coffee".into(), price: 18_000, ..Default::default() };
28/// coffee.save(&db).await?; // INSERT, sets id and timestamps
29/// let cheap = Product::query().where_op("price", "<", 20_000).get(&db).await?;
30/// # let _ = cheap; Ok(()) }
31/// ```
32///
33/// Implement it with `#[derive(Model)]`: the hidden items it writes may
34/// change in a minor release.
35///
36/// The primary key is the `id` column. Its type is the `id` field's: `i64`
37/// (numbered by the database; `0` means "not saved yet"), or a
38/// [`Ulid`](super::Ulid), a UUID or a `String` (see [`ModelKey`]).
39pub trait Model: super::FromRow + Sized + Send + Sync + Unpin + 'static {
40 /// The table name (the snake_case struct name unless `#[model(table = …)]`).
41 const TABLE: &'static str;
42 /// Every column, including `id`.
43 const COLUMNS: &'static [&'static str];
44 /// `delete()` sets `deleted_at` instead of removing the row, and queries
45 /// skip deleted rows unless asked with `with_trashed()` / `only_trashed()`.
46 const SOFT_DELETES: bool = false;
47 /// The `Json<CustomValues>` column named by `#[model(custom_fields = "…")]`,
48 /// which holds the values of the run-time custom fields of this model.
49 const CUSTOM_FIELDS: Option<&'static str> = None;
50 /// Select every column (`*`) instead of `COLUMNS`, so `from_row` also
51 /// sees columns the struct doesn't list, and queries may filter on them.
52 /// The built-in `User` does this to keep the app's own columns.
53 const SELECT_ALL: bool = false;
54 /// The text columns full-text search looks in, most important first
55 /// (they weigh more in the ranking); empty: the model can't be
56 /// searched. Set it with `#[model(search = "title, body")]`; see
57 /// [`renox::db::search`](super::search).
58 const SEARCHABLE: &'static [&'static str] = &[];
59 /// The language full-text search stems words for: `english` (the
60 /// default) or a PostgreSQL text search configuration such as `simple`
61 /// (no stemming) or `spanish`. Set it with
62 /// `#[model(search_language = "simple")]`.
63 const SEARCH_LANGUAGE: &'static str = "english";
64 /// How full-text search normalises text before indexing and searching
65 /// it; `None` (the default) indexes text as written. Set it with
66 /// `#[model(search = "name", normalize = "arabic")]`.
67 const SEARCH_NORMALIZE: Option<super::search::Normalize> = None;
68
69 /// The type of the `id` field.
70 type Key: ModelKey;
71
72 /// The primary key.
73 fn id(&self) -> Self::Key;
74 /// Sets the primary key (after an insert, for keys the database numbers).
75 #[doc(hidden)]
76 fn set_id(&mut self, id: Self::Key);
77 /// Values of every column except `id`, in `COLUMNS` order.
78 #[doc(hidden)]
79 fn values(&self) -> Vec<DbValue>;
80 /// Updates `created_at` / `updated_at` if the model has them.
81 #[doc(hidden)]
82 fn touch(&mut self, _now: DateTime, _creating: bool) {}
83 /// Updates `deleted_at` if the model has it.
84 #[doc(hidden)]
85 fn set_deleted_at(&mut self, _at: Option<DateTime>) {}
86 /// Empties `created_at` / `updated_at` when they are `Option`s.
87 #[doc(hidden)]
88 fn forget_timestamps(&mut self) {}
89
90 /// The model's columns with the kind of each field's type. The derive
91 /// fills this in; a hand-written `impl Model` returns none.
92 fn column_info() -> Vec<ModelColumn> {
93 Vec::new()
94 }
95
96 /// The indexes declared with `#[model(index(…))]` and `#[model(unique(…))]`.
97 fn indexes() -> Vec<ModelIndex> {
98 Vec::new()
99 }
100
101 /// A copy of the model that isn't saved yet (Laravel's `replicate`):
102 /// the same values, with an unsaved id, no `deleted_at` and, when they
103 /// are `Option`s, no timestamps, so `save` inserts a new row. Change
104 /// what must differ (a unique SKU, a name) before saving it, or show it
105 /// in the "new" form for someone to finish ("Duplicate").
106 ///
107 /// ```
108 /// # use renox::prelude::*;
109 /// # #[derive(Model, serde::Serialize, Default, Clone)]
110 /// # #[model(table = "products")]
111 /// # struct Product { id: i64, sku: String, name: String, created_at: Option<DateTime> }
112 /// # async fn demo(db: Db) -> Result {
113 /// let original = Product::find_or_404(&db, 1).await?;
114 /// let mut copy = original.replicate();
115 /// copy.sku = format!("{}-COPY", original.sku);
116 /// copy.save(&db).await?; // a new row, with its own id
117 /// # Ok(()) }
118 /// ```
119 fn replicate(&self) -> Self
120 where
121 Self: Clone,
122 {
123 let mut copy = self.clone();
124 copy.set_id(Self::Key::default());
125 copy.set_deleted_at(None);
126 copy.forget_timestamps();
127 copy
128 }
129
130 /// Conditions every query of this model starts with, e.g. the current
131 /// tenant, read from [`renox::context`](mod@crate::context). `query()`,
132 /// `find`, `all`, `where_eq` and the relation loaders apply it;
133 /// [`Model::unscoped`] doesn't. Saving, deleting and restoring a loaded
134 /// model work by its id. Set it with `#[model(default_scope = "…")]`:
135 ///
136 /// ```
137 /// # use renox::prelude::*;
138 /// #[derive(Clone)]
139 /// struct CurrentTeam(i64);
140 ///
141 /// #[derive(Model, serde::Serialize, Default)]
142 /// #[model(table = "projects", default_scope = "team_only")]
143 /// struct Project { id: i64, team_id: i64, name: String }
144 ///
145 /// fn team_only(query: renox::db::Query<Project>) -> renox::db::Query<Project> {
146 /// match renox::context::get::<CurrentTeam>() {
147 /// Some(team) => query.where_eq("team_id", team.0),
148 /// None => query.none(), // no team, no rows: fail closed
149 /// }
150 /// }
151 /// ```
152 fn default_scope(query: Query<Self>) -> Query<Self> {
153 query
154 }
155
156 /// Runs before the row is written; an error stops the save. Implement
157 /// [`ModelHooks`] and add `#[model(hooks)]` rather than overriding it.
158 fn saving(&mut self, _creating: bool) -> Result {
159 Ok(())
160 }
161
162 /// Runs after the row is written (inside the caller's transaction, if
163 /// any); an error is returned by `save`. See [`ModelHooks`].
164 fn saved(&self, _created: bool) -> impl Future<Output = Result> + Send {
165 async { Ok(()) }
166 }
167
168 /// The status column a `#[model(state_machine)]` model guards: `save`,
169 /// `save_only` and `save_changes` refuse to change it, only a transition
170 /// does. `None` for every other model.
171 #[doc(hidden)]
172 fn guarded_column() -> Option<&'static str> {
173 None
174 }
175
176 /// Runs before an insert; an error stops it. For a guarded model it
177 /// applies the machine's `initial` states.
178 #[doc(hidden)]
179 fn check_insert(&self) -> Result {
180 Ok(())
181 }
182
183 /// Runs before `delete`/`force_delete`; an error stops it. See [`ModelHooks`].
184 fn deleting(&self) -> Result {
185 Ok(())
186 }
187
188 /// Runs after `delete`/`force_delete`. See [`ModelHooks`].
189 fn deleted(&self) -> impl Future<Output = Result> + Send {
190 async { Ok(()) }
191 }
192
193 /// A query with the default scope applied (see [`Model::default_scope`]).
194 fn query() -> Query<Self> {
195 Self::default_scope(Query::new())
196 }
197
198 /// A query without the default scope, e.g. for an admin who sees every
199 /// tenant. Soft-deleted rows stay hidden unless asked for.
200 fn unscoped() -> Query<Self> {
201 Query::new()
202 }
203
204 /// Reloads the model's row (e.g. after an `increment` or another request
205 /// changed it); a deleted row is a 404.
206 fn refresh(&mut self, db: &Db) -> impl Future<Output = Result<()>> + Send {
207 async move {
208 let id = self.id();
209 *self = Self::unscoped()
210 .with_trashed()
211 .where_eq("id", id)
212 .first_or_404(db)
213 .await?;
214 Ok(())
215 }
216 }
217
218 /// The rows matching a full-text search, best matches first:
219 /// shorthand for `query().search(words)`. The model needs
220 /// `#[model(search = "…")]` and its index (see
221 /// [`renox::db::search`](super::search)).
222 ///
223 /// ```
224 /// # use renox::prelude::*;
225 /// #[derive(Model, serde::Serialize, Default)]
226 /// #[model(table = "posts", search = "title, body")]
227 /// struct Post { id: i64, title: String, body: String }
228 ///
229 /// # async fn demo(db: Db, q: String) -> Result {
230 /// let posts = Post::search(&q).limit(20).get(&db).await?;
231 /// # let _ = posts; Ok(()) }
232 /// ```
233 fn search(words: &str) -> Query<Self> {
234 Self::query().search(words)
235 }
236
237 /// Shorthand for `query().where_eq(column, value)`.
238 fn where_eq(column: &str, value: impl ToDbValue) -> Query<Self> {
239 Self::query().where_eq(column, value)
240 }
241
242 /// Every row, in id order.
243 fn all<'c, E: Executor<'c>>(db: E) -> impl Future<Output = Result<Vec<Self>>> + Send {
244 Self::query().order_by("id").get(db)
245 }
246
247 /// The row with this id, or `None`.
248 fn find<'c, E: Executor<'c>>(
249 db: E,
250 id: Self::Key,
251 ) -> impl Future<Output = Result<Option<Self>>> + Send {
252 Self::query().where_eq("id", id).first(db)
253 }
254
255 /// The rows with these ids, in id order (missing ids are skipped).
256 fn find_many<'c, E: Executor<'c>>(
257 db: E,
258 ids: impl IntoIterator<Item = Self::Key>,
259 ) -> impl Future<Output = Result<Vec<Self>>> + Send {
260 let ids: Vec<Self::Key> = ids.into_iter().collect();
261 Self::query().where_in("id", ids).order_by("id").get(db)
262 }
263
264 /// Inserts many new models with a few statements (ids aren't returned;
265 /// use `create` when you need them). Timestamps are set; unsaved ULID
266 /// and UUID keys are made, `String` keys must be set, `i64` keys come
267 /// from the database. Returns the number of rows inserted.
268 fn insert_many<'c, E: Executor<'c>>(
269 db: E,
270 models: Vec<Self>,
271 ) -> impl Future<Output = Result<u64>> + Send {
272 async move { write_many::<Self>(db.into_conn(), models, None).await }
273 }
274
275 /// Inserts `models`, or updates the rows they clash with on the
276 /// `unique_by` columns (which need a unique index), setting `update`
277 /// columns (and `updated_at` when the model has it). Returns the rows
278 /// written.
279 ///
280 /// ```
281 /// # use renox::prelude::*;
282 /// # #[derive(Model, serde::Serialize, Default)] struct Stock { id: i64, sku: String, qty: i64 }
283 /// # async fn demo(db: Db) -> Result {
284 /// let feed = vec![Stock { sku: "COFFEE-1".into(), qty: 12, ..Default::default() }];
285 /// Stock::upsert(&db, feed, &["sku"], &["qty"]).await?;
286 /// # Ok(()) }
287 /// ```
288 fn upsert<'c, E: Executor<'c>>(
289 db: E,
290 models: Vec<Self>,
291 unique_by: &[&str],
292 update: &[&str],
293 ) -> impl Future<Output = Result<u64>> + Send {
294 let unique_by: Vec<String> = unique_by.iter().map(|c| (*c).to_owned()).collect();
295 let update: Vec<String> = update.iter().map(|c| (*c).to_owned()).collect();
296 async move {
297 // Keys the app writes (ULID, UUID, String) may be the conflict
298 // target; an `i64` id isn't written, and no key is ever updated.
299 let key_target = !<Self::Key as ModelKey>::AUTO_INCREMENT;
300 for column in unique_by.iter().chain(&update) {
301 let id_allowed =
302 key_target && unique_by.contains(column) && !update.contains(column);
303 if !Self::COLUMNS.contains(&column.as_str()) || (column == "id" && !id_allowed) {
304 return Err(
305 anyhow!("`{}` has no column `{column}` to upsert", Self::TABLE).into(),
306 );
307 }
308 }
309 if unique_by.is_empty() {
310 return Err(anyhow!("upsert needs at least one `unique_by` column").into());
311 }
312 write_many::<Self>(db.into_conn(), models, Some((unique_by, update))).await
313 }
314 }
315
316 /// Like `find`, but a missing row becomes a 404 response.
317 fn find_or_404<'c, E: Executor<'c>>(
318 db: E,
319 id: Self::Key,
320 ) -> impl Future<Output = Result<Self>> + Send {
321 let found = Self::find(db, id);
322 async move { found.await?.ok_or(Error::NotFound) }
323 }
324
325 /// Inserts a new model and returns it with its id and timestamps.
326 fn create<'c, E: Executor<'c>>(
327 db: E,
328 mut model: Self,
329 ) -> impl Future<Output = Result<Self>> + Send {
330 async move {
331 model.insert(db).await?;
332 Ok(model)
333 }
334 }
335
336 /// Inserts the model as a new row, whatever its id: an unsaved id gets a
337 /// new key (from the database for `i64`, a new ULID or UUID v7), a set
338 /// one is written as it is (a `String` key must be set).
339 fn insert<'c, E: Executor<'c>>(&mut self, db: E) -> impl Future<Output = Result> + Send {
340 async move {
341 self.check_insert()?;
342 self.saving(true)?;
343 self.touch(now(), true);
344 if self.id().is_unsaved()
345 && let Some(key) = Self::Key::generate()
346 {
347 self.set_id(key);
348 }
349 let key = self.id();
350 let mut columns: Vec<String> = Self::COLUMNS
351 .iter()
352 .filter(|c| **c != "id")
353 .map(|c| quote(c))
354 .collect();
355 let mut values = self.values();
356 let table = quote(Self::TABLE);
357 if key.is_unsaved() {
358 if !<Self::Key as ModelKey>::AUTO_INCREMENT {
359 return Err(anyhow!(
360 "set the `id` of a new {} row before inserting it",
361 Self::TABLE
362 )
363 .into());
364 }
365 let sql_text = if columns.is_empty() {
366 format!("INSERT INTO {table} DEFAULT VALUES RETURNING id")
367 } else {
368 let marks = vec!["?"; columns.len()].join(", ");
369 format!(
370 "INSERT INTO {table} ({}) VALUES ({marks}) RETURNING id",
371 columns.join(", ")
372 )
373 };
374 let id: Self::Key = sql(sql_text).bind_all(values).scalar(db).await?;
375 self.set_id(id);
376 } else {
377 columns.insert(0, quote("id"));
378 values.insert(0, key.to_db_value());
379 let marks = vec!["?"; columns.len()].join(", ");
380 sql(format!(
381 "INSERT INTO {table} ({}) VALUES ({marks})",
382 columns.join(", ")
383 ))
384 .bind_all(values)
385 .execute(db)
386 .await?;
387 }
388 self.saved(true).await
389 }
390 }
391
392 /// Inserts the model if its id is unsaved (`0`, an empty ULID…),
393 /// otherwise updates its row.
394 fn save<'c, E: Executor<'c>>(&mut self, db: E) -> impl Future<Output = Result> + Send {
395 async move {
396 if self.id().is_unsaved() {
397 return self.insert(db).await;
398 }
399 self.saving(false)?;
400 self.touch(now(), false);
401 let guarded = Self::guarded_column();
402 let mut sets: Vec<String> = Vec::new();
403 let mut values = Vec::new();
404 let mut status = None;
405 for (column, value) in Self::COLUMNS
406 .iter()
407 .filter(|c| **c != "id")
408 .zip(self.values())
409 {
410 if guarded == Some(*column) {
411 status = Some(value);
412 } else {
413 sets.push(format!("{} = ?", quote(column)));
414 values.push(value);
415 }
416 }
417 let table = quote(Self::TABLE);
418 if sets.is_empty() && status.is_none() {
419 return self.saved(false).await;
420 }
421 let mut conn = db.into_conn();
422 if let (Some(column), Some(status)) = (guarded, status) {
423 // The status is not written: the row is matched on it, so a
424 // record whose status was changed (or is stale) is refused.
425 let quoted = quote(column);
426 let matched = if sets.is_empty() {
427 sql(format!(
428 "SELECT COUNT(*) FROM {table} WHERE id = ? AND {quoted} = ?"
429 ))
430 .bind(self.id())
431 .bind_all(vec![status])
432 .scalar::<i64>(conn.reborrow())
433 .await? as u64
434 } else {
435 sql(format!(
436 "UPDATE {table} SET {} WHERE id = ? AND {quoted} = ?",
437 sets.join(", ")
438 ))
439 .bind_all(values)
440 .bind(self.id())
441 .bind_all(vec![status])
442 .execute(conn.reborrow())
443 .await?
444 };
445 if matched == 0 {
446 let exists: i64 = sql(format!("SELECT COUNT(*) FROM {table} WHERE id = ?"))
447 .bind(self.id())
448 .scalar(conn.reborrow())
449 .await?;
450 if exists == 0 {
451 return Err(Error::NotFound);
452 }
453 return Err(status_refused(Self::TABLE, column));
454 }
455 return self.saved(false).await;
456 }
457 let changed = sql(format!(
458 "UPDATE {table} SET {} WHERE id = ?",
459 sets.join(", ")
460 ))
461 .bind_all(values)
462 .bind(self.id())
463 .execute(conn)
464 .await?;
465 if changed == 0 {
466 return Err(Error::NotFound);
467 }
468 self.saved(false).await
469 }
470 }
471
472 /// Updates only `columns` (and `updated_at`, if the model has it) of a
473 /// saved model, so a concurrent change to another column isn't
474 /// overwritten. A column the `saving` hook changes is saved only if
475 /// it's listed.
476 ///
477 /// ```
478 /// # use renox::prelude::*;
479 /// # #[derive(Model, serde::Serialize, Default)]
480 /// # #[model(table = "posts")]
481 /// # struct Post { id: i64, title: String, views: i64 }
482 /// # async fn demo(db: Db, mut post: Post) -> Result {
483 /// post.title = "New title".into();
484 /// post.save_only(&db, &["title"]).await?; // leaves `views` alone
485 /// # Ok(()) }
486 /// ```
487 fn save_only<'c, E: Executor<'c>>(
488 &mut self,
489 db: E,
490 columns: &[&str],
491 ) -> impl Future<Output = Result> + Send {
492 let columns: Vec<String> = columns.iter().map(|c| (*c).to_owned()).collect();
493 async move {
494 self.saving(false)?;
495 update_columns(self, db, columns).await
496 }
497 }
498
499 /// Saves the columns that differ from `original` (the model as it was
500 /// loaded), including those the `saving` hook changes, and returns
501 /// whether anything was written. When nothing changed there's no query
502 /// and no `saved` hook.
503 ///
504 /// ```
505 /// # use renox::prelude::*;
506 /// # #[derive(Model, serde::Serialize, Default, Clone)]
507 /// # #[model(table = "posts")]
508 /// # struct Post { id: i64, title: String, views: i64 }
509 /// # async fn demo(db: Db) -> Result {
510 /// let original = Post::find_or_404(&db, 1).await?;
511 /// let mut post = original.clone();
512 /// post.title = "New title".into();
513 /// post.save_changes(&db, &original).await?; // UPDATE posts SET title = ?
514 /// # Ok(()) }
515 /// ```
516 fn save_changes<'c, E: Executor<'c>>(
517 &mut self,
518 db: E,
519 original: &Self,
520 ) -> impl Future<Output = Result<bool>> + Send {
521 let hooked = self.saving(false);
522 let changed: Vec<String> = Self::COLUMNS
523 .iter()
524 .filter(|c| **c != "id")
525 .zip(self.values().into_iter().zip(original.values()))
526 .filter(|(_, (now, before))| now != before)
527 .map(|(column, _)| (*column).to_owned())
528 .collect();
529 async move {
530 hooked?;
531 if let Some(column) = Self::guarded_column()
532 && changed.iter().any(|c| c == column)
533 {
534 return Err(status_refused(Self::TABLE, column));
535 }
536 if changed.is_empty() {
537 return Ok(false);
538 }
539 update_columns(self, db, changed).await?;
540 Ok(true)
541 }
542 }
543
544 /// Deletes the row, or marks it deleted for models with soft deletes.
545 fn delete<'c, E: Executor<'c>>(&mut self, db: E) -> impl Future<Output = Result> + Send {
546 async move {
547 if !Self::SOFT_DELETES {
548 return self.force_delete(db).await;
549 }
550 self.deleting()?;
551 let at = now();
552 sql(format!(
553 "UPDATE {} SET deleted_at = ? WHERE id = ?",
554 quote(Self::TABLE)
555 ))
556 .bind(at)
557 .bind(self.id())
558 .execute(db)
559 .await?;
560 self.set_deleted_at(Some(at));
561 self.deleted().await
562 }
563 }
564
565 /// Removes the row, even for models with soft deletes.
566 fn force_delete<'c, E: Executor<'c>>(&self, db: E) -> impl Future<Output = Result> + Send {
567 async move {
568 self.deleting()?;
569 sql(format!("DELETE FROM {} WHERE id = ?", quote(Self::TABLE)))
570 .bind(self.id())
571 .execute(db)
572 .await?;
573 self.deleted().await
574 }
575 }
576
577 /// Brings back a soft-deleted row.
578 fn restore<'c, E: Executor<'c>>(&mut self, db: E) -> impl Future<Output = Result> + Send {
579 async move {
580 if !Self::SOFT_DELETES {
581 return Err(anyhow!("{} does not use soft deletes", Self::TABLE).into());
582 }
583 sql(format!(
584 "UPDATE {} SET deleted_at = NULL WHERE id = ?",
585 quote(Self::TABLE)
586 ))
587 .bind(self.id())
588 .execute(db)
589 .await?;
590 self.set_deleted_at(None);
591 Ok(())
592 }
593 }
594}
595
596/// The refusal of a write to a guarded status column.
597fn status_refused(table: &str, column: &str) -> Error {
598 Error::Status(
599 axum::http::StatusCode::UNPROCESSABLE_ENTITY,
600 format!(
601 "the `{column}` of a {table} row moves through its state machine; \
602 run a transition instead of saving it (or reload the record if it is out of date)"
603 ),
604 )
605}
606
607/// `save_only` after the `saving` hook: writes `columns` and `updated_at`,
608/// then runs `saved`.
609async fn update_columns<'c, M: Model, E: Executor<'c>>(
610 model: &mut M,
611 db: E,
612 columns: Vec<String>,
613) -> Result {
614 if model.id().is_unsaved() {
615 return Err(anyhow!("save_only on an unsaved {} row", M::TABLE).into());
616 }
617 for column in &columns {
618 if column == "id" || !M::COLUMNS.contains(&column.as_str()) {
619 return Err(anyhow!("{} has no column `{column}` to save", M::TABLE).into());
620 }
621 if M::guarded_column() == Some(column.as_str()) {
622 return Err(status_refused(M::TABLE, column));
623 }
624 }
625 model.touch(now(), false);
626 let mut sets = Vec::new();
627 let mut binds = Vec::new();
628 for (column, value) in M::COLUMNS
629 .iter()
630 .filter(|c| **c != "id")
631 .zip(model.values())
632 {
633 if columns.iter().any(|c| c == column) || *column == "updated_at" {
634 sets.push(format!("{} = ?", quote(column)));
635 binds.push(value);
636 }
637 }
638 if !sets.is_empty() {
639 let changed = sql(format!(
640 "UPDATE {} SET {} WHERE id = ?",
641 quote(M::TABLE),
642 sets.join(", ")
643 ))
644 .bind_all(binds)
645 .bind(model.id())
646 .execute(db)
647 .await?;
648 if changed == 0 {
649 return Err(Error::NotFound);
650 }
651 }
652 model.saved(false).await
653}
654
655/// Code that runs around a model's writes, like Laravel's model events:
656/// fill a slug, check an invariant, forget a cache key, emit an event. Add
657/// `#[model(hooks)]` and implement the ones you need:
658///
659/// ```
660/// # use renox::prelude::*;
661/// use renox::db::ModelHooks;
662///
663/// #[derive(Model, serde::Serialize, Default)]
664/// #[model(table = "posts", hooks)]
665/// struct Post { id: i64, title: String, slug: String }
666///
667/// impl ModelHooks for Post {
668/// fn saving(&mut self, _creating: bool) -> Result {
669/// self.slug = self.title.to_lowercase().replace(' ', "-");
670/// Ok(())
671/// }
672///
673/// async fn saved(&self, _created: bool) -> Result {
674/// if let Some(state) = renox::context::app() { // the request's or job's app
675/// state.cache.forget("posts.latest").await?;
676/// }
677/// Ok(())
678/// }
679/// }
680/// ```
681///
682/// They run for `save`, `save_only`, `save_changes`, `create`, `insert`, `delete` and
683/// `force_delete`, not for `restore` or bulk `Query::update`/`delete` and
684/// `insert_many`, which write many rows in one statement.
685pub trait ModelHooks {
686 /// Runs before the row is written (`creating` is true for an insert); an error cancels it.
687 fn saving(&mut self, _creating: bool) -> Result {
688 Ok(())
689 }
690
691 /// Runs after the row is written (`created` is true for an insert).
692 fn saved(&self, _created: bool) -> impl Future<Output = Result> + Send {
693 async { Ok(()) }
694 }
695
696 /// Runs before the row is deleted; an error cancels the delete.
697 fn deleting(&self) -> Result {
698 Ok(())
699 }
700
701 /// Runs after the row is deleted.
702 fn deleted(&self) -> impl Future<Output = Result> + Send {
703 async { Ok(()) }
704 }
705}
706
707/// Most parameters one statement binds; both databases allow more
708/// (SQLite 32,766, PostgreSQL 65,535).
709const MAX_BINDS: usize = 30_000;
710
711/// `insert_many` / `upsert`: multi-row INSERTs in chunks under the bind limit.
712async fn write_many<M: Model>(
713 mut conn: super::Conn<'_>,
714 mut models: Vec<M>,
715 upsert: Option<(Vec<String>, Vec<String>)>,
716) -> Result<u64> {
717 for model in &models {
718 model.check_insert()?;
719 }
720 let at = now();
721 // `i64` keys come from the database; other keys are written, made here
722 // (ULID, UUID) when unsaved.
723 let with_keys = !<M::Key as super::ModelKey>::AUTO_INCREMENT;
724 for model in &mut models {
725 model.touch(at, true);
726 if with_keys && model.id().is_unsaved() {
727 match <M::Key as super::ModelKey>::generate() {
728 Some(key) => model.set_id(key),
729 None => {
730 return Err(anyhow!(
731 "set the `id` of every new {} row before inserting them",
732 M::TABLE
733 )
734 .into());
735 }
736 }
737 }
738 }
739 let mut columns: Vec<&str> = M::COLUMNS.iter().copied().filter(|c| *c != "id").collect();
740 if with_keys {
741 columns.insert(0, "id");
742 }
743 if columns.is_empty() || models.is_empty() {
744 return Ok(0);
745 }
746 let quoted: Vec<String> = columns.iter().map(|c| quote(c)).collect();
747 let row_marks = format!("({})", vec!["?"; columns.len()].join(", "));
748 let conflict = upsert.map(|(unique_by, update)| {
749 let targets: Vec<String> = unique_by.iter().map(|c| quote(c)).collect();
750 let mut sets: Vec<String> = update
751 .iter()
752 .map(|c| format!("{0} = excluded.{0}", quote(c)))
753 .collect();
754 if columns.contains(&"updated_at") && !update.iter().any(|c| c == "updated_at") {
755 sets.push(format!("{0} = excluded.{0}", quote("updated_at")));
756 }
757 if sets.is_empty() {
758 format!(" ON CONFLICT ({}) DO NOTHING", targets.join(", "))
759 } else {
760 format!(
761 " ON CONFLICT ({}) DO UPDATE SET {}",
762 targets.join(", "),
763 sets.join(", ")
764 )
765 }
766 });
767 let per_statement = (MAX_BINDS / columns.len()).max(1);
768 let mut written = 0;
769 for chunk in models.chunks(per_statement) {
770 let marks = vec![row_marks.as_str(); chunk.len()].join(", ");
771 let statement = format!(
772 "INSERT INTO {} ({}) VALUES {marks}{}",
773 quote(M::TABLE),
774 quoted.join(", "),
775 conflict.as_deref().unwrap_or_default()
776 );
777 let values = chunk.iter().flat_map(|model| {
778 let key = with_keys.then(|| model.id().to_db_value());
779 key.into_iter().chain(model.values())
780 });
781 written += sql(statement)
782 .bind_all(values)
783 .execute(conn.reborrow())
784 .await?;
785 }
786 Ok(written)
787}