Skip to main content

sea_orm_sluggable/
model.rs

1use sea_orm::{
2    sea_query::ValueType, ActiveModelTrait, ActiveValue, ColumnTrait, Condition, ConnectionTrait,
3    EntityTrait, Iterable, PrimaryKeyToColumn, Value,
4};
5
6use crate::{config::SlugOptions, db::pick_free, error::SlugError, text::slugify};
7
8type Column<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::Column;
9type Predicate<A> = Box<dyn Fn(&A) -> bool + Send + Sync>;
10type ScopeFn<A> = Box<dyn Fn(&A) -> Condition + Send + Sync>;
11
12/// Gives an `ActiveModel` an automatically generated slug.
13///
14/// ```
15/// # mod categories {
16/// #     use sea_orm::entity::prelude::*;
17/// #     #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
18/// #     #[sea_orm(table_name = "categories")]
19/// #     pub struct Model {
20/// #         #[sea_orm(primary_key)]
21/// #         pub id: i32,
22/// #         pub title: String,
23/// #         pub slug: String,
24/// #     }
25/// #     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
26/// #     pub enum Relation {}
27/// # }
28/// use sea_orm::entity::prelude::*;
29/// use sea_orm_sluggable::{SlugConfig, Sluggable};
30///
31/// impl Sluggable for categories::ActiveModel {
32///     fn slug_config() -> SlugConfig<Self> {
33///         SlugConfig::new([categories::Column::Title], categories::Column::Slug)
34///     }
35/// }
36///
37/// #[async_trait::async_trait]
38/// impl ActiveModelBehavior for categories::ActiveModel {
39///     async fn before_save<C: ConnectionTrait>(self, db: &C, insert: bool) -> Result<Self, DbErr> {
40///         // "Rust for PHP developers" -> "rust-for-php-developers",
41///         // or "rust-for-php-developers-1" when that one is taken.
42///         Ok(sea_orm_sluggable::fill_slug(self, db, insert).await?)
43///     }
44/// }
45/// # fn main() {}
46/// ```
47pub trait Sluggable: ActiveModelTrait + Send {
48    /// Where the slug comes from, where it goes, and how it is built.
49    fn slug_config() -> SlugConfig<Self>;
50}
51
52/// Which columns a slug is built from and stored in, and when it is generated.
53pub struct SlugConfig<A: ActiveModelTrait> {
54    sources: Vec<Column<A>>,
55    target: Column<A>,
56    options: SlugOptions,
57    on_create: bool,
58    on_update: bool,
59    prevent_overwrite: bool,
60    skip_when: Option<Predicate<A>>,
61    scope: Option<ScopeFn<A>>,
62}
63
64impl<A: ActiveModelTrait> SlugConfig<A> {
65    /// Builds the slug from `sources` (joined with a space, in order) into `target`.
66    ///
67    /// Defaults: generated on create, kept on update, unique across the whole table.
68    pub fn new(sources: impl IntoIterator<Item = Column<A>>, target: Column<A>) -> Self {
69        Self {
70            sources: sources.into_iter().collect(),
71            target,
72            options: SlugOptions::default(),
73            on_create: true,
74            on_update: false,
75            prevent_overwrite: false,
76            skip_when: None,
77            scope: None,
78        }
79    }
80
81    /// Separator, length, suffixes and transliteration.
82    #[must_use]
83    pub fn options(mut self, options: SlugOptions) -> Self {
84        self.options = options;
85        self
86    }
87
88    /// Generate the slug when a row is inserted. Default: on.
89    #[must_use]
90    pub const fn on_create(mut self, enabled: bool) -> Self {
91        self.on_create = enabled;
92        self
93    }
94
95    /// Regenerate the slug when a source column changes on update. Default: off,
96    /// because changing a slug breaks every link to the old URL.
97    #[must_use]
98    pub const fn on_update(mut self, enabled: bool) -> Self {
99        self.on_update = enabled;
100        self
101    }
102
103    /// Keep a slug that is already filled in, for example typed by an editor.
104    /// Default: off.
105    #[must_use]
106    pub const fn prevent_overwrite(mut self, enabled: bool) -> Self {
107        self.prevent_overwrite = enabled;
108        self
109    }
110
111    /// Leave the slug alone when `skip` returns `true`, e.g. for drafts.
112    #[must_use]
113    pub fn skip_when(mut self, skip: impl Fn(&A) -> bool + Send + Sync + 'static) -> Self {
114        self.skip_when = Some(Box::new(skip));
115        self
116    }
117
118    /// Makes the slug unique only among rows matching the returned condition,
119    /// e.g. within one category or tenant.
120    ///
121    /// ```
122    /// # mod posts {
123    /// #     use sea_orm::entity::prelude::*;
124    /// #     #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
125    /// #     #[sea_orm(table_name = "posts")]
126    /// #     pub struct Model {
127    /// #         #[sea_orm(primary_key)]
128    /// #         pub id: i32,
129    /// #         pub category_id: i32,
130    /// #         pub title: String,
131    /// #         pub slug: String,
132    /// #     }
133    /// #     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
134    /// #     pub enum Relation {}
135    /// #     impl ActiveModelBehavior for ActiveModel {}
136    /// # }
137    /// use sea_orm::{entity::prelude::*, Condition};
138    /// use sea_orm_sluggable::SlugConfig;
139    ///
140    /// // "hello" can exist once per category.
141    /// let config = SlugConfig::new([posts::Column::Title], posts::Column::Slug).scope(
142    ///     |post: &posts::ActiveModel| {
143    ///         // `try_as_ref` is `None` when the column is not set on this model.
144    ///         match post.category_id.try_as_ref() {
145    ///             Some(category) => Condition::all().add(posts::Column::CategoryId.eq(*category)),
146    ///             None => Condition::all(),
147    ///         }
148    ///     },
149    /// );
150    /// ```
151    #[must_use]
152    pub fn scope(mut self, scope: impl Fn(&A) -> Condition + Send + Sync + 'static) -> Self {
153        self.scope = Some(Box::new(scope));
154        self
155    }
156}
157
158/// Fills the slug column of `model` using [`Sluggable::slug_config`].
159///
160/// Call it from `ActiveModelBehavior::before_save`; `insert` is the flag that
161/// hook receives.
162///
163/// # Errors
164///
165/// [`SlugError::Empty`] when the source columns give no letters or digits,
166/// and [`SlugError::Db`] when the uniqueness check fails.
167pub async fn fill_slug<A, C>(model: A, db: &C, insert: bool) -> Result<A, SlugError>
168where
169    A: Sluggable,
170    C: ConnectionTrait,
171{
172    let config = A::slug_config();
173    fill_slug_with(model, db, insert, &config).await
174}
175
176/// Same as [`fill_slug`], with an explicit configuration.
177///
178/// # Errors
179///
180/// [`SlugError::Empty`] when the source columns give no letters or digits,
181/// and [`SlugError::Db`] when the uniqueness check fails.
182pub async fn fill_slug_with<A, C>(
183    mut model: A,
184    db: &C,
185    insert: bool,
186    config: &SlugConfig<A>,
187) -> Result<A, SlugError>
188where
189    A: ActiveModelTrait + Send,
190    C: ConnectionTrait,
191{
192    if !should_generate(&model, insert, config) {
193        return Ok(model);
194    }
195
196    let base = slugify(&source_text(&model, &config.sources), &config.options);
197    if !insert && still_fits(&model, config, &base) {
198        // Saving the same text again keeps `hello-1` instead of renaming it `hello`.
199        return Ok(model);
200    }
201    let mut scope = config
202        .scope
203        .as_ref()
204        .map_or_else(Condition::all, |scope| scope(&model));
205    if !insert {
206        if let Some(itself) = primary_key_condition(&model) {
207            scope = scope.add(itself.not());
208        }
209    }
210
211    let slug = pick_free::<A::Entity, C>(db, config.target, &base, &config.options, scope).await?;
212    model.set(config.target, slug.into());
213    Ok(model)
214}
215
216fn should_generate<A: ActiveModelTrait>(model: &A, insert: bool, config: &SlugConfig<A>) -> bool {
217    let enabled = if insert {
218        config.on_create
219    } else {
220        // Every source must be known: a partial update with only some sources set
221        // would build the slug from part of the text.
222        let sources = config.sources.iter().map(|column| model.get(*column));
223        config.on_update
224            && config
225                .sources
226                .iter()
227                .any(|column| model.get(*column).is_set())
228            && sources.clone().all(|value| !value.is_not_set())
229    };
230    if !enabled {
231        return false;
232    }
233    if config.skip_when.as_ref().is_some_and(|skip| skip(model)) {
234        return false;
235    }
236    !(config.prevent_overwrite && text_of(model.get(config.target)).is_some_and(|s| !s.is_empty()))
237}
238
239/// Whether the current slug is already `base` or `base` with a numeric suffix.
240fn still_fits<A: ActiveModelTrait>(model: &A, config: &SlugConfig<A>, base: &str) -> bool {
241    let Some(current) = text_of(model.get(config.target)) else {
242        return false;
243    };
244    if current == base {
245        return true;
246    }
247    let prefix = format!("{base}{}", config.options.separator_str());
248    config.options.has_default_suffix()
249        && current
250            .strip_prefix(&prefix)
251            .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
252}
253
254/// The source columns joined with spaces; empty and non-text columns are skipped.
255fn source_text<A: ActiveModelTrait>(model: &A, sources: &[Column<A>]) -> String {
256    sources
257        .iter()
258        .filter_map(|column| text_of(model.get(*column)))
259        .collect::<Vec<_>>()
260        .join(" ")
261}
262
263fn text_of(value: ActiveValue<Value>) -> Option<String> {
264    let value = value.into_value()?;
265    <Option<String> as ValueType>::try_from(value)
266        .ok()
267        .flatten()
268}
269
270/// `WHERE pk = <this row's pk>`, or `None` when the primary key is not loaded.
271fn primary_key_condition<A: ActiveModelTrait>(model: &A) -> Option<Condition> {
272    let mut condition = Condition::all();
273    for key in <<A::Entity as EntityTrait>::PrimaryKey as Iterable>::iter() {
274        let column = key.into_column();
275        let value = model.get(column).into_value()?;
276        condition = condition.add(column.eq(value));
277    }
278    Some(condition)
279}