Skip to main content

laravel/validation/
database.rs

1use std::panic::Location;
2
3use futures_util::future::BoxFuture;
4use serde::de::DeserializeOwned;
5use serde_json::Value;
6
7use super::messages::Message;
8use super::{DatabaseRule, Field, InputValue, Rule};
9use crate::db::identifier::{is_identifier_path, quote};
10use crate::db::sqlx::AssertSqlSafe;
11use crate::db::{self, Condition, Driver, Expr, IntoCondition, IntoExpr, col};
12use crate::http::Request;
13use crate::model::Model;
14use crate::routing::RouteModel;
15
16/// The builder that [`Rule::unique`](DatabaseRules::unique) and
17/// [`Rule::unique_in`](DatabaseRules::unique_in) return. Use it to choose a row to skip and to
18/// filter the rows the rule checks. It converts into a [`Rule`](super::Rule).
19///
20/// ```
21/// use laravel::db::col;
22/// use laravel::validation::{DatabaseRules, Rule, Rules};
23///
24/// let rules = Rules::new().field(
25///     "email",
26///     [Rule::unique_in::<String>("users", "email")
27///         .ignore_user()
28///         .filter(col("deleted_at").is_null())],
29/// );
30/// ```
31#[derive(Clone, Debug)]
32pub struct Unique {
33    lookup: Lookup,
34    ignore: Option<Ignore>,
35    /// The column that holds the skipped row's ID, when the rule names one.
36    ignore_column: Option<String>,
37}
38
39/// The builder that [`Rule::exists`](DatabaseRules::exists) and
40/// [`Rule::exists_in`](DatabaseRules::exists_in) return. Use it to filter the rows the rule
41/// accepts. It converts into a [`Rule`](super::Rule).
42///
43/// ```
44/// use laravel::db::col;
45/// use laravel::validation::{DatabaseRules, Rule, Rules};
46///
47/// let rules = Rules::new().field(
48///     "category_id",
49///     [Rule::exists_in::<i64>("categories", "id").filter(col("active"))],
50/// );
51/// ```
52#[derive(Clone, Debug)]
53pub struct Exists(Lookup);
54
55#[derive(Clone, Debug)]
56struct Lookup {
57    table: String,
58    column: String,
59    /// The connection to look on, or `None` for the default connection.
60    connection: Option<&'static str>,
61    /// The conditions a row must also meet, each added by a `filter` call.
62    filters: Vec<Condition>,
63    /// The conditions that read route parameters, built for each request.
64    route_filters: Vec<RouteCondition>,
65    bind: fn(&InputValue) -> Option<db::Value<'static>>,
66    /// Where the application declared the rule, which its errors point to.
67    declared: &'static Location<'static>,
68}
69
70/// A `filter = ..` condition that reads the request's route models, as `#[validate]` writes it.
71#[doc(hidden)]
72pub type RouteCondition = for<'r> fn(&'r Request) -> BoxFuture<'r, crate::Result<Option<Condition>>>;
73
74/// The key of the `P` that the route parameter `parameter` names, which `route::<P>("parameter")` in
75/// a `filter = ..` condition reads. It keeps the key's type, so a typed column compares only with
76/// a key of its own type. The request finds each record once, as route model binding does.
77#[doc(hidden)]
78pub async fn route_key<P: Model + RouteModel>(request: &Request, parameter: &str) -> crate::Result<<P as Model>::Key> {
79    let model: P = request.model(parameter).await?;
80
81    Ok(P::META.key.get(&model).clone())
82}
83
84/// The key column of the `P` that the route parameter names, and its key, for
85/// [`Unique::ignore_route`].
86type RouteModelKey = for<'r> fn(&'r Request, &'r str) -> BoxFuture<'r, crate::Result<(&'static str, Expr)>>;
87
88fn route_model_key<'r, P: Model + RouteModel>(
89    request: &'r Request,
90    parameter: &'r str,
91) -> BoxFuture<'r, crate::Result<(&'static str, Expr)>> {
92    Box::pin(async move {
93        Ok((
94            P::META.key.name(),
95            route_key::<P>(request, parameter).await?.into_expr(),
96        ))
97    })
98}
99
100/// Where a [`Unique`] rule finds the ID of the row it skips.
101#[derive(Clone, Debug)]
102enum Ignore {
103    User,
104    Route(String, RouteModelKey),
105    Id(db::Value<'static>),
106}
107
108/// The ID of the row to skip. The rule compares text from the request with the column as text, so
109/// it matches integer, UUID, and text keys. It compares a typed ID, and a route model's key, with the
110/// column directly.
111enum Ignored {
112    Text(String),
113    Value(db::Value<'static>),
114    Key(Expr),
115}
116
117impl Unique {
118    #[track_caller]
119    fn new<T: DeserializeOwned + Into<db::Value<'static>>>(
120        table: String,
121        column: String,
122        connection: Option<&'static str>,
123    ) -> Self {
124        Self {
125            lookup: Lookup::new::<T>(table, column, connection),
126            ignore: None,
127            ignore_column: None,
128        }
129    }
130
131    /// Skips the row with this ID, such as the team a handler is updating. A null ID, such as
132    /// `None::<i64>`, skips no row.
133    ///
134    /// ```
135    /// use laravel::validation::{DatabaseRules, Rule};
136    ///
137    /// # let team_id = 7_i64;
138    /// let rule = Rule::unique_in::<String>("teams", "name").ignore(team_id);
139    /// ```
140    #[must_use]
141    pub fn ignore<'a>(mut self, id: impl Into<db::Value<'a>>) -> Self {
142        let id = id.into().into_owned();
143        self.ignore = (!is_null(&id)).then_some(Ignore::Id(id));
144        self
145    }
146
147    /// Skips the logged-in user's row, so a user can keep their own email address. For a guest,
148    /// the rule skips no row.
149    ///
150    /// When the session guard finds users with [`model::Users`](crate::model::Users), the rule
151    /// finds the row by the user model's key column. Otherwise, it finds the row by `id`.
152    #[must_use]
153    pub fn ignore_user(mut self) -> Self {
154        self.ignore = Some(Ignore::User);
155        self
156    }
157
158    /// Skips the row of the `P` that this route parameter names, such as `team` in
159    /// `/teams/{team}`, by `P`'s key column.
160    ///
161    /// The rule finds the model the same way route model binding does, once per request. So it
162    /// works when the route finds the model by another column, such as a slug.
163    ///
164    /// ```no_run
165    /// # use laravel::model::model;
166    /// # #[model(route_key = "slug")] pub struct Team { pub id: i64, pub slug: String }
167    /// use laravel::validation::{DatabaseRules, Rule};
168    ///
169    /// let rule = Rule::unique_in::<String>("teams", "name").ignore_route::<Team>("team");
170    /// ```
171    #[must_use]
172    pub fn ignore_route<P: Model + RouteModel>(mut self, parameter: impl Into<String>) -> Self {
173        self.ignore = Some(Ignore::Route(parameter.into(), route_model_key::<P>));
174        self
175    }
176
177    /// [`ignore_route`](Self::ignore_route) for the model that `column` belongs to, which
178    /// `unique(Team::name, ignore = route("team"))` writes.
179    #[doc(hidden)]
180    #[must_use]
181    pub fn __ignore_route_of<P: Model + RouteModel, C>(
182        self,
183        _column: crate::model::Column<P, C>,
184        parameter: impl Into<String>,
185    ) -> Self {
186        self.ignore_route::<P>(parameter)
187    }
188
189    /// Finds the skipped row by this column, such as `uuid` or `slug`, instead of `id` or the user
190    /// model's key column. The rule compares the column with the ID as given.
191    #[must_use]
192    pub fn ignore_column(mut self, column: impl Into<String>) -> Self {
193        self.ignore_column = Some(column.into());
194        self
195    }
196
197    /// Checks only the rows that meet `condition`, such as the rows of one team. Like
198    /// [`Builder::filter`](crate::db::Builder::filter), each call adds a condition that must also
199    /// hold. A `None` condition adds nothing.
200    ///
201    /// ```
202    /// use laravel::db::col;
203    /// use laravel::validation::{DatabaseRules, Rule};
204    ///
205    /// # let team_id = 7_i64;
206    /// let rule = Rule::unique_in::<String>("members", "email").filter(col("team_id").eq(team_id));
207    /// ```
208    #[must_use]
209    pub fn filter(mut self, condition: impl IntoCondition) -> Self {
210        self.lookup.filters.extend(condition.into_condition());
211        self
212    }
213
214    #[doc(hidden)]
215    #[must_use]
216    pub fn __filter_route(mut self, condition: RouteCondition) -> Self {
217        self.lookup.route_filters.push(condition);
218        self
219    }
220
221    async fn check(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
222        self.taken(field).await.map_err(|error| error.at(self.lookup.declared))
223    }
224
225    async fn taken(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
226        let Some(value) = self.lookup.value(field) else {
227            return Ok(None);
228        };
229        let named = self.ignore_column.as_deref();
230        let ignored = match &self.ignore {
231            None => None,
232            Some(Ignore::Id(id)) => Some((named.unwrap_or("id"), Ignored::Value(id.clone()))),
233            Some(Ignore::User) => crate::auth::user_id(field.request("unique")?)
234                .await?
235                .map(|(id, column)| id_text(&id).map(|id| (named.unwrap_or(column), Ignored::Text(id))))
236                .transpose()?,
237            Some(Ignore::Route(parameter, key)) => {
238                let (column, key) = key(field.request("unique")?, parameter).await?;
239                Some((named.unwrap_or(column), Ignored::Key(key)))
240            }
241        };
242
243        let filters = self.lookup.route_filters(field, "unique").await?;
244        let taken = self.lookup.find(value, filters, ignored).await?;
245
246        Ok(taken.then(|| Message::rule("unique")))
247    }
248}
249
250impl Exists {
251    #[track_caller]
252    fn new<T: DeserializeOwned + Into<db::Value<'static>>>(
253        table: String,
254        column: String,
255        connection: Option<&'static str>,
256    ) -> Self {
257        Self(Lookup::new::<T>(table, column, connection))
258    }
259
260    /// Accepts only the rows that meet `condition`, such as categories that aren't archived. Like
261    /// [`Builder::filter`](crate::db::Builder::filter), each call adds a condition that must also
262    /// hold. A `None` condition adds nothing.
263    ///
264    /// ```
265    /// use laravel::db::col;
266    /// use laravel::validation::{DatabaseRules, Rule};
267    ///
268    /// let rule = Rule::exists_in::<i64>("categories", "id").filter(col("archived_at").is_null());
269    /// ```
270    #[must_use]
271    pub fn filter(mut self, condition: impl IntoCondition) -> Self {
272        self.0.filters.extend(condition.into_condition());
273        self
274    }
275
276    #[doc(hidden)]
277    #[must_use]
278    pub fn __filter_route(mut self, condition: RouteCondition) -> Self {
279        self.0.route_filters.push(condition);
280        self
281    }
282
283    async fn check(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
284        self.missing(field).await.map_err(|error| error.at(self.0.declared))
285    }
286
287    async fn missing(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
288        let Some(value) = self.0.value(field) else {
289            return Ok(None);
290        };
291
292        let filters = self.0.route_filters(field, "exists").await?;
293        let found = self.0.find(value, filters, None).await?;
294
295        Ok((!found).then(|| Message::rule("exists")))
296    }
297}
298
299impl Lookup {
300    #[track_caller]
301    fn new<T: DeserializeOwned + Into<db::Value<'static>>>(
302        table: String,
303        column: String,
304        connection: Option<&'static str>,
305    ) -> Self {
306        Self {
307            table,
308            column,
309            connection,
310            filters: Vec::new(),
311            route_filters: Vec::new(),
312            bind: |value| crate::validation::typed::deserialize::<T>(value).ok().map(Into::into),
313            declared: Location::caller(),
314        }
315    }
316
317    fn value(&self, field: &Field<'_>) -> Option<db::Value<'static>> {
318        field.value.and_then(self.bind)
319    }
320
321    /// The conditions of the filters that read route parameters, for this request.
322    async fn route_filters(&self, field: &Field<'_>, rule: &str) -> crate::Result<Vec<Condition>> {
323        let mut conditions = Vec::new();
324        for filter in &self.route_filters {
325            conditions.extend(filter(field.request(rule)?).await?);
326        }
327
328        Ok(conditions)
329    }
330
331    /// Whether a row that meets the filters, and `route_filters`, has the value, other than the one
332    /// whose `column` holds the ignored ID. The comparison is null-safe, so rows with a null key
333    /// still count.
334    async fn find(
335        &self,
336        value: db::Value<'static>,
337        route_filters: Vec<Condition>,
338        ignored: Option<(&str, Ignored)>,
339    ) -> crate::Result<bool> {
340        let ignore_column = ignored.as_ref().map(|(column, _)| *column);
341        for identifier in [self.table.as_str(), &self.column].into_iter().chain(ignore_column) {
342            if !is_identifier_path(identifier) {
343                return Err(crate::error::fail(format!(
344                    "`{identifier}` isn't a table or column name for a database validation rule"
345                )));
346            }
347        }
348
349        let connection = match self.connection {
350            Some(name) => db::connection(name)?,
351            None => db::default_connection()?,
352        };
353        let driver = connection.driver();
354        if !holds(driver, &value) {
355            return Ok(false);
356        }
357        let skipped = ignored.and_then(|(column, ignored)| match ignored {
358            Ignored::Text(id) => {
359                let id = db::Value::Text(Some(id.into()));
360                holds(driver, &id).then(|| text(driver, column).is_distinct_from(id))
361            }
362            Ignored::Value(id) => holds(driver, &id).then(|| col(column).is_distinct_from(id)),
363            Ignored::Key(key) => Some(col(column).is_distinct_from(key)),
364        });
365
366        let query = connection
367            .table(self.table.as_str())
368            .filter(col(&self.column).eq(value))
369            .filter(skipped);
370
371        self.filters
372            .iter()
373            .cloned()
374            .chain(route_filters)
375            .fold(query, db::Builder::filter)
376            .exists()
377            .await
378    }
379}
380
381/// A column cast to text, so an ID from the request matches integer, UUID, and text keys...
382fn text(driver: Driver, column: &str) -> Expr {
383    let text = match driver {
384        Driver::MySql | Driver::MariaDb => "char",
385        _ => "text",
386    };
387
388    db::expr(db::raw!(AssertSqlSafe(format!(
389        "cast({} as {text})",
390        quote(driver, column)
391    ))))
392}
393
394/// Whether the driver can bind the value. One it can't, such as an unsigned integer above
395/// `i64::MAX` on PostgreSQL, isn't in any column, so the lookup skips the query instead of failing,
396/// and an ignored ID it can't bind skips no row.
397fn holds(driver: Driver, value: &db::Value<'_>) -> bool {
398    match (value, driver) {
399        (db::Value::UnsignedInteger(Some(value)), Driver::Postgres | Driver::Sqlite) => i64::try_from(*value).is_ok(),
400        (db::Value::Text(Some(text)), Driver::Postgres) => !text.contains('\0'),
401        _ => true,
402    }
403}
404
405fn is_null(value: &db::Value<'_>) -> bool {
406    matches!(
407        value,
408        db::Value::Boolean(None)
409            | db::Value::SmallInteger(None)
410            | db::Value::Integer(None)
411            | db::Value::BigInteger(None)
412            | db::Value::UnsignedInteger(None)
413            | db::Value::Real(None)
414            | db::Value::Double(None)
415            | db::Value::Text(None)
416            | db::Value::Binary(None)
417            | db::Value::Date(None)
418            | db::Value::Time(None)
419            | db::Value::DateTime(None)
420            | db::Value::Timestamp(None)
421            | db::Value::Decimal(None)
422            | db::Value::Json(None)
423            | db::Value::Uuid(None)
424            | db::Value::Ulid(None)
425            | db::Value::Vector(None)
426    )
427}
428
429fn id_text(id: &Value) -> crate::Result<String> {
430    match id {
431        Value::String(id) => Ok(id.clone()),
432        Value::Number(id) => Ok(id.to_string()),
433        _ => Err(crate::error::fail(
434            "the `unique` rule ignores the user's row by ID, so the ID must serialize as a number or string",
435        )),
436    }
437}
438
439/// The rules that query the database: [`Rule::unique`](DatabaseRules::unique) and
440/// [`Rule::exists`](DatabaseRules::exists) for a model's column, and
441/// [`Rule::unique_in`](DatabaseRules::unique_in) and [`Rule::exists_in`](DatabaseRules::exists_in)
442/// for a table without a model. The prelude imports this trait.
443///
444/// ```
445/// use laravel::validation::{DatabaseRules, Rule};
446///
447/// let rule = Rule::unique_in::<String>("users", "email");
448/// ```
449pub trait DatabaseRules {
450    /// Requires a value that no row of the model's table has in `column`, such as an email address
451    /// that no other user has. The rule queries the model's connection.
452    ///
453    /// The rule decodes the submitted value as the column's type and binds it, so form text such as
454    /// `"42"` matches an integer column. In a derive attribute, the rule decodes the value as the
455    /// field's type instead, and a field whose type doesn't compare with the column's type doesn't
456    /// compile. If the value doesn't decode, the rule passes, and the field reports its type error.
457    /// A value the database can't store, such as a `u64` above `i64::MAX` on PostgreSQL, matches no
458    /// row, so `unique` passes and `exists` fails without a query. Text comparisons follow the
459    /// column's collation.
460    ///
461    /// In a derive attribute, `unique(User::email, ignore = user)` calls
462    /// [`ignore_user`](Unique::ignore_user), and `unique(Team::name, ignore = route("team"))`
463    /// calls [`ignore_route`](Unique::ignore_route) for the column's model. `ignore = user("uuid")`
464    /// also calls [`ignore_column`](Unique::ignore_column).
465    ///
466    /// The constructor returns the [`Unique`] builder, which can skip a row and filter the rows
467    /// the rule checks. To list the rule with other rules, pass the rules as a tuple.
468    ///
469    /// ```no_run
470    /// # use laravel::model::model;
471    /// # #[model] pub struct User { pub id: i64, pub email: String }
472    /// use laravel::validation::{DatabaseRules, Rule, Rules};
473    ///
474    /// let rules = Rules::new().field(
475    ///     "email",
476    ///     (Rule::required(), Rule::email(), Rule::unique(User::email).ignore_user()),
477    /// );
478    /// ```
479    #[track_caller]
480    fn unique<M, C>(column: crate::model::Column<M, C>) -> Unique
481    where
482        M: Model,
483        C: DeserializeOwned + Into<db::Value<'static>>;
484
485    /// Requires a value that some row of the model's table has in `column`, such as the ID of a
486    /// category that exists. The rule queries the model's connection and decodes the value as the
487    /// column's type, as for [`Rule::unique`](DatabaseRules::unique).
488    ///
489    /// The constructor returns the [`Exists`] builder, which can filter the rows the rule accepts.
490    /// To list the rule with other rules, pass the rules as a tuple.
491    ///
492    /// ```no_run
493    /// # use laravel::model::model;
494    /// # #[model] pub struct Category { pub id: i64 }
495    /// use laravel::validation::{DatabaseRules, Rule, Rules};
496    ///
497    /// let rules = Rules::new().field("category_id", (Rule::required(), Rule::exists(Category::id)));
498    /// ```
499    ///
500    /// In a derive attribute, a field whose type differs from the column's type doesn't compile:
501    ///
502    /// ```compile_fail
503    /// # use laravel::model::model;
504    /// # #[model] pub struct Category { pub id: i64 }
505    /// #[derive(serde::Deserialize, laravel::validation::Validate)]
506    /// struct StorePost {
507    ///     #[validate(exists(Category::id))]
508    ///     category_id: String,
509    /// }
510    /// ```
511    #[track_caller]
512    fn exists<M, C>(column: crate::model::Column<M, C>) -> Exists
513    where
514        M: Model,
515        C: DeserializeOwned + Into<db::Value<'static>>;
516
517    /// Requires a value that no row of a table has in a column, like
518    /// [`Rule::unique`](DatabaseRules::unique), for a table without a model.
519    ///
520    /// Either name may include a schema, as in `"app.users"`. The rule queries the default
521    /// connection. `T` is the field's Rust type, and the rule decodes the submitted value as `T`.
522    /// Nothing checks `T` against the column's type. A table or column name that isn't a plain
523    /// identifier fails validation with a `500`.
524    ///
525    /// In a derive attribute without a column, as in `unique("posts")`, the column is the field's
526    /// Rust name. A serde rename changes only the input name. With a table name, `ignore` names the
527    /// route's model, as in `ignore = route::<Team>("team")`.
528    ///
529    /// ```
530    /// use laravel::validation::{DatabaseRules, Rule, Rules};
531    ///
532    /// let rules = Rules::new().field(
533    ///     "email",
534    ///     [Rule::unique_in::<String>("users", "email").ignore_user()],
535    /// );
536    /// ```
537    #[track_caller]
538    fn unique_in<T>(table: impl Into<String>, column: impl Into<String>) -> Unique
539    where
540        T: DeserializeOwned + Into<db::Value<'static>>;
541
542    /// Requires a value that some row of a table has in a column, like
543    /// [`Rule::exists`](DatabaseRules::exists), for a table without a model.
544    ///
545    /// Either name may include a schema, as in `"app.categories"`. As for
546    /// [`Rule::unique_in`](DatabaseRules::unique_in), the rule queries the default connection and
547    /// decodes the submitted value as `T`.
548    ///
549    /// ```
550    /// use laravel::validation::{DatabaseRules, Rule, Rules};
551    ///
552    /// let rules = Rules::new().field("category_id", [Rule::exists_in::<i64>("categories", "id")]);
553    /// ```
554    #[track_caller]
555    fn exists_in<T>(table: impl Into<String>, column: impl Into<String>) -> Exists
556    where
557        T: DeserializeOwned + Into<db::Value<'static>>;
558}
559
560impl DatabaseRules for Rule {
561    #[track_caller]
562    fn unique<M, C>(column: crate::model::Column<M, C>) -> Unique
563    where
564        M: Model,
565        C: DeserializeOwned + Into<db::Value<'static>>,
566    {
567        Unique::new::<C>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
568    }
569
570    #[track_caller]
571    fn exists<M, C>(column: crate::model::Column<M, C>) -> Exists
572    where
573        M: Model,
574        C: DeserializeOwned + Into<db::Value<'static>>,
575    {
576        Exists::new::<C>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
577    }
578
579    #[track_caller]
580    fn unique_in<T>(table: impl Into<String>, column: impl Into<String>) -> Unique
581    where
582        T: DeserializeOwned + Into<db::Value<'static>>,
583    {
584        Unique::new::<T>(table.into(), column.into(), None)
585    }
586
587    #[track_caller]
588    fn exists_in<T>(table: impl Into<String>, column: impl Into<String>) -> Exists
589    where
590        T: DeserializeOwned + Into<db::Value<'static>>,
591    {
592        Exists::new::<T>(table.into(), column.into(), None)
593    }
594}
595
596/// The `unique` rule a derive gives a field of type `T` for a column.
597#[doc(hidden)]
598#[track_caller]
599pub fn __unique_field<T, M, C>(column: crate::model::Column<M, C>) -> Unique
600where
601    M: Model,
602    T: crate::model::ComparableTo<C> + DeserializeOwned + Into<db::Value<'static>>,
603{
604    Unique::new::<T>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
605}
606
607/// The `exists` rule a derive gives a field of type `T` for a column.
608#[doc(hidden)]
609#[track_caller]
610pub fn __exists_field<T, M, C>(column: crate::model::Column<M, C>) -> Exists
611where
612    M: Model,
613    T: crate::model::ComparableTo<C> + DeserializeOwned + Into<db::Value<'static>>,
614{
615    Exists::new::<T>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
616}
617
618impl DatabaseRule for Unique {
619    fn check<'a>(&'a self, field: &'a Field<'a>) -> BoxFuture<'a, crate::Result<Option<Message>>> {
620        Box::pin(self.check(field))
621    }
622}
623
624impl DatabaseRule for Exists {
625    fn check<'a>(&'a self, field: &'a Field<'a>) -> BoxFuture<'a, crate::Result<Option<Message>>> {
626        Box::pin(self.check(field))
627    }
628}
629
630impl From<Unique> for Rule {
631    fn from(rule: Unique) -> Self {
632        Self::__database(rule)
633    }
634}
635
636impl From<Exists> for Rule {
637    fn from(rule: Exists) -> Self {
638        Self::__database(rule)
639    }
640}