laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
use std::panic::Location;

use futures_util::future::BoxFuture;
use serde::de::DeserializeOwned;
use serde_json::Value;

use super::messages::Message;
use super::{DatabaseRule, Field, InputValue, Rule};
use crate::db::identifier::{is_identifier_path, quote};
use crate::db::sqlx::AssertSqlSafe;
use crate::db::{self, Condition, Driver, Expr, IntoCondition, IntoExpr, col};
use crate::http::Request;
use crate::model::Model;
use crate::routing::RouteModel;

/// The builder that [`Rule::unique`](DatabaseRules::unique) and
/// [`Rule::unique_in`](DatabaseRules::unique_in) return. Use it to choose a row to skip and to
/// filter the rows the rule checks. It converts into a [`Rule`](super::Rule).
///
/// ```
/// use laravel::db::col;
/// use laravel::validation::{DatabaseRules, Rule, Rules};
///
/// let rules = Rules::new().field(
///     "email",
///     [Rule::unique_in::<String>("users", "email")
///         .ignore_user()
///         .filter(col("deleted_at").is_null())],
/// );
/// ```
#[derive(Clone, Debug)]
pub struct Unique {
    lookup: Lookup,
    ignore: Option<Ignore>,
    /// The column that holds the skipped row's ID, when the rule names one.
    ignore_column: Option<String>,
}

/// The builder that [`Rule::exists`](DatabaseRules::exists) and
/// [`Rule::exists_in`](DatabaseRules::exists_in) return. Use it to filter the rows the rule
/// accepts. It converts into a [`Rule`](super::Rule).
///
/// ```
/// use laravel::db::col;
/// use laravel::validation::{DatabaseRules, Rule, Rules};
///
/// let rules = Rules::new().field(
///     "category_id",
///     [Rule::exists_in::<i64>("categories", "id").filter(col("active"))],
/// );
/// ```
#[derive(Clone, Debug)]
pub struct Exists(Lookup);

#[derive(Clone, Debug)]
struct Lookup {
    table: String,
    column: String,
    /// The connection to look on, or `None` for the default connection.
    connection: Option<&'static str>,
    /// The conditions a row must also meet, each added by a `filter` call.
    filters: Vec<Condition>,
    /// The conditions that read route parameters, built for each request.
    route_filters: Vec<RouteCondition>,
    bind: fn(&InputValue) -> Option<db::Value<'static>>,
    /// Where the application declared the rule, which its errors point to.
    declared: &'static Location<'static>,
}

/// A `filter = ..` condition that reads the request's route models, as `#[validate]` writes it.
#[doc(hidden)]
pub type RouteCondition = for<'r> fn(&'r Request) -> BoxFuture<'r, crate::Result<Option<Condition>>>;

/// The key of the `P` that the route parameter `parameter` names, which `route::<P>("parameter")` in
/// a `filter = ..` condition reads. It keeps the key's type, so a typed column compares only with
/// a key of its own type. The request finds each record once, as route model binding does.
#[doc(hidden)]
pub async fn route_key<P: Model + RouteModel>(request: &Request, parameter: &str) -> crate::Result<<P as Model>::Key> {
    let model: P = request.model(parameter).await?;

    Ok(P::META.key.get(&model).clone())
}

/// The key column of the `P` that the route parameter names, and its key, for
/// [`Unique::ignore_route`].
type RouteModelKey = for<'r> fn(&'r Request, &'r str) -> BoxFuture<'r, crate::Result<(&'static str, Expr)>>;

fn route_model_key<'r, P: Model + RouteModel>(
    request: &'r Request,
    parameter: &'r str,
) -> BoxFuture<'r, crate::Result<(&'static str, Expr)>> {
    Box::pin(async move {
        Ok((
            P::META.key.name(),
            route_key::<P>(request, parameter).await?.into_expr(),
        ))
    })
}

/// Where a [`Unique`] rule finds the ID of the row it skips.
#[derive(Clone, Debug)]
enum Ignore {
    User,
    Route(String, RouteModelKey),
    Id(db::Value<'static>),
}

/// The ID of the row to skip. The rule compares text from the request with the column as text, so
/// it matches integer, UUID, and text keys. It compares a typed ID, and a route model's key, with the
/// column directly.
enum Ignored {
    Text(String),
    Value(db::Value<'static>),
    Key(Expr),
}

impl Unique {
    #[track_caller]
    fn new<T: DeserializeOwned + Into<db::Value<'static>>>(
        table: String,
        column: String,
        connection: Option<&'static str>,
    ) -> Self {
        Self {
            lookup: Lookup::new::<T>(table, column, connection),
            ignore: None,
            ignore_column: None,
        }
    }

    /// Skips the row with this ID, such as the team a handler is updating. A null ID, such as
    /// `None::<i64>`, skips no row.
    ///
    /// ```
    /// use laravel::validation::{DatabaseRules, Rule};
    ///
    /// # let team_id = 7_i64;
    /// let rule = Rule::unique_in::<String>("teams", "name").ignore(team_id);
    /// ```
    #[must_use]
    pub fn ignore<'a>(mut self, id: impl Into<db::Value<'a>>) -> Self {
        let id = id.into().into_owned();
        self.ignore = (!is_null(&id)).then_some(Ignore::Id(id));
        self
    }

    /// Skips the logged-in user's row, so a user can keep their own email address. For a guest,
    /// the rule skips no row.
    ///
    /// When the session guard finds users with [`model::Users`](crate::model::Users), the rule
    /// finds the row by the user model's key column. Otherwise, it finds the row by `id`.
    #[must_use]
    pub fn ignore_user(mut self) -> Self {
        self.ignore = Some(Ignore::User);
        self
    }

    /// Skips the row of the `P` that this route parameter names, such as `team` in
    /// `/teams/{team}`, by `P`'s key column.
    ///
    /// The rule finds the model the same way route model binding does, once per request. So it
    /// works when the route finds the model by another column, such as a slug.
    ///
    /// ```no_run
    /// # use laravel::model::model;
    /// # #[model(route_key = "slug")] pub struct Team { pub id: i64, pub slug: String }
    /// use laravel::validation::{DatabaseRules, Rule};
    ///
    /// let rule = Rule::unique_in::<String>("teams", "name").ignore_route::<Team>("team");
    /// ```
    #[must_use]
    pub fn ignore_route<P: Model + RouteModel>(mut self, parameter: impl Into<String>) -> Self {
        self.ignore = Some(Ignore::Route(parameter.into(), route_model_key::<P>));
        self
    }

    /// [`ignore_route`](Self::ignore_route) for the model that `column` belongs to, which
    /// `unique(Team::name, ignore = route("team"))` writes.
    #[doc(hidden)]
    #[must_use]
    pub fn __ignore_route_of<P: Model + RouteModel, C>(
        self,
        _column: crate::model::Column<P, C>,
        parameter: impl Into<String>,
    ) -> Self {
        self.ignore_route::<P>(parameter)
    }

    /// Finds the skipped row by this column, such as `uuid` or `slug`, instead of `id` or the user
    /// model's key column. The rule compares the column with the ID as given.
    #[must_use]
    pub fn ignore_column(mut self, column: impl Into<String>) -> Self {
        self.ignore_column = Some(column.into());
        self
    }

    /// Checks only the rows that meet `condition`, such as the rows of one team. Like
    /// [`Builder::filter`](crate::db::Builder::filter), each call adds a condition that must also
    /// hold. A `None` condition adds nothing.
    ///
    /// ```
    /// use laravel::db::col;
    /// use laravel::validation::{DatabaseRules, Rule};
    ///
    /// # let team_id = 7_i64;
    /// let rule = Rule::unique_in::<String>("members", "email").filter(col("team_id").eq(team_id));
    /// ```
    #[must_use]
    pub fn filter(mut self, condition: impl IntoCondition) -> Self {
        self.lookup.filters.extend(condition.into_condition());
        self
    }

    #[doc(hidden)]
    #[must_use]
    pub fn __filter_route(mut self, condition: RouteCondition) -> Self {
        self.lookup.route_filters.push(condition);
        self
    }

    async fn check(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
        self.taken(field).await.map_err(|error| error.at(self.lookup.declared))
    }

    async fn taken(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
        let Some(value) = self.lookup.value(field) else {
            return Ok(None);
        };
        let named = self.ignore_column.as_deref();
        let ignored = match &self.ignore {
            None => None,
            Some(Ignore::Id(id)) => Some((named.unwrap_or("id"), Ignored::Value(id.clone()))),
            Some(Ignore::User) => crate::auth::user_id(field.request("unique")?)
                .await?
                .map(|(id, column)| id_text(&id).map(|id| (named.unwrap_or(column), Ignored::Text(id))))
                .transpose()?,
            Some(Ignore::Route(parameter, key)) => {
                let (column, key) = key(field.request("unique")?, parameter).await?;
                Some((named.unwrap_or(column), Ignored::Key(key)))
            }
        };

        let filters = self.lookup.route_filters(field, "unique").await?;
        let taken = self.lookup.find(value, filters, ignored).await?;

        Ok(taken.then(|| Message::rule("unique")))
    }
}

impl Exists {
    #[track_caller]
    fn new<T: DeserializeOwned + Into<db::Value<'static>>>(
        table: String,
        column: String,
        connection: Option<&'static str>,
    ) -> Self {
        Self(Lookup::new::<T>(table, column, connection))
    }

    /// Accepts only the rows that meet `condition`, such as categories that aren't archived. Like
    /// [`Builder::filter`](crate::db::Builder::filter), each call adds a condition that must also
    /// hold. A `None` condition adds nothing.
    ///
    /// ```
    /// use laravel::db::col;
    /// use laravel::validation::{DatabaseRules, Rule};
    ///
    /// let rule = Rule::exists_in::<i64>("categories", "id").filter(col("archived_at").is_null());
    /// ```
    #[must_use]
    pub fn filter(mut self, condition: impl IntoCondition) -> Self {
        self.0.filters.extend(condition.into_condition());
        self
    }

    #[doc(hidden)]
    #[must_use]
    pub fn __filter_route(mut self, condition: RouteCondition) -> Self {
        self.0.route_filters.push(condition);
        self
    }

    async fn check(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
        self.missing(field).await.map_err(|error| error.at(self.0.declared))
    }

    async fn missing(&self, field: &Field<'_>) -> crate::Result<Option<Message>> {
        let Some(value) = self.0.value(field) else {
            return Ok(None);
        };

        let filters = self.0.route_filters(field, "exists").await?;
        let found = self.0.find(value, filters, None).await?;

        Ok((!found).then(|| Message::rule("exists")))
    }
}

impl Lookup {
    #[track_caller]
    fn new<T: DeserializeOwned + Into<db::Value<'static>>>(
        table: String,
        column: String,
        connection: Option<&'static str>,
    ) -> Self {
        Self {
            table,
            column,
            connection,
            filters: Vec::new(),
            route_filters: Vec::new(),
            bind: |value| crate::validation::typed::deserialize::<T>(value).ok().map(Into::into),
            declared: Location::caller(),
        }
    }

    fn value(&self, field: &Field<'_>) -> Option<db::Value<'static>> {
        field.value.and_then(self.bind)
    }

    /// The conditions of the filters that read route parameters, for this request.
    async fn route_filters(&self, field: &Field<'_>, rule: &str) -> crate::Result<Vec<Condition>> {
        let mut conditions = Vec::new();
        for filter in &self.route_filters {
            conditions.extend(filter(field.request(rule)?).await?);
        }

        Ok(conditions)
    }

    /// Whether a row that meets the filters, and `route_filters`, has the value, other than the one
    /// whose `column` holds the ignored ID. The comparison is null-safe, so rows with a null key
    /// still count.
    async fn find(
        &self,
        value: db::Value<'static>,
        route_filters: Vec<Condition>,
        ignored: Option<(&str, Ignored)>,
    ) -> crate::Result<bool> {
        let ignore_column = ignored.as_ref().map(|(column, _)| *column);
        for identifier in [self.table.as_str(), &self.column].into_iter().chain(ignore_column) {
            if !is_identifier_path(identifier) {
                return Err(crate::error::fail(format!(
                    "`{identifier}` isn't a table or column name for a database validation rule"
                )));
            }
        }

        let connection = match self.connection {
            Some(name) => db::connection(name)?,
            None => db::default_connection()?,
        };
        let driver = connection.driver();
        if !holds(driver, &value) {
            return Ok(false);
        }
        let skipped = ignored.and_then(|(column, ignored)| match ignored {
            Ignored::Text(id) => {
                let id = db::Value::Text(Some(id.into()));
                holds(driver, &id).then(|| text(driver, column).is_distinct_from(id))
            }
            Ignored::Value(id) => holds(driver, &id).then(|| col(column).is_distinct_from(id)),
            Ignored::Key(key) => Some(col(column).is_distinct_from(key)),
        });

        let query = connection
            .table(self.table.as_str())
            .filter(col(&self.column).eq(value))
            .filter(skipped);

        self.filters
            .iter()
            .cloned()
            .chain(route_filters)
            .fold(query, db::Builder::filter)
            .exists()
            .await
    }
}

/// A column cast to text, so an ID from the request matches integer, UUID, and text keys...
fn text(driver: Driver, column: &str) -> Expr {
    let text = match driver {
        Driver::MySql | Driver::MariaDb => "char",
        _ => "text",
    };

    db::expr(db::raw!(AssertSqlSafe(format!(
        "cast({} as {text})",
        quote(driver, column)
    ))))
}

/// Whether the driver can bind the value. One it can't, such as an unsigned integer above
/// `i64::MAX` on PostgreSQL, isn't in any column, so the lookup skips the query instead of failing,
/// and an ignored ID it can't bind skips no row.
fn holds(driver: Driver, value: &db::Value<'_>) -> bool {
    match (value, driver) {
        (db::Value::UnsignedInteger(Some(value)), Driver::Postgres | Driver::Sqlite) => i64::try_from(*value).is_ok(),
        (db::Value::Text(Some(text)), Driver::Postgres) => !text.contains('\0'),
        _ => true,
    }
}

fn is_null(value: &db::Value<'_>) -> bool {
    matches!(
        value,
        db::Value::Boolean(None)
            | db::Value::SmallInteger(None)
            | db::Value::Integer(None)
            | db::Value::BigInteger(None)
            | db::Value::UnsignedInteger(None)
            | db::Value::Real(None)
            | db::Value::Double(None)
            | db::Value::Text(None)
            | db::Value::Binary(None)
            | db::Value::Date(None)
            | db::Value::Time(None)
            | db::Value::DateTime(None)
            | db::Value::Timestamp(None)
            | db::Value::Decimal(None)
            | db::Value::Json(None)
            | db::Value::Uuid(None)
            | db::Value::Ulid(None)
            | db::Value::Vector(None)
    )
}

fn id_text(id: &Value) -> crate::Result<String> {
    match id {
        Value::String(id) => Ok(id.clone()),
        Value::Number(id) => Ok(id.to_string()),
        _ => Err(crate::error::fail(
            "the `unique` rule ignores the user's row by ID, so the ID must serialize as a number or string",
        )),
    }
}

/// The rules that query the database: [`Rule::unique`](DatabaseRules::unique) and
/// [`Rule::exists`](DatabaseRules::exists) for a model's column, and
/// [`Rule::unique_in`](DatabaseRules::unique_in) and [`Rule::exists_in`](DatabaseRules::exists_in)
/// for a table without a model. The prelude imports this trait.
///
/// ```
/// use laravel::validation::{DatabaseRules, Rule};
///
/// let rule = Rule::unique_in::<String>("users", "email");
/// ```
pub trait DatabaseRules {
    /// Requires a value that no row of the model's table has in `column`, such as an email address
    /// that no other user has. The rule queries the model's connection.
    ///
    /// The rule decodes the submitted value as the column's type and binds it, so form text such as
    /// `"42"` matches an integer column. In a derive attribute, the rule decodes the value as the
    /// field's type instead, and a field whose type doesn't compare with the column's type doesn't
    /// compile. If the value doesn't decode, the rule passes, and the field reports its type error.
    /// A value the database can't store, such as a `u64` above `i64::MAX` on PostgreSQL, matches no
    /// row, so `unique` passes and `exists` fails without a query. Text comparisons follow the
    /// column's collation.
    ///
    /// In a derive attribute, `unique(User::email, ignore = user)` calls
    /// [`ignore_user`](Unique::ignore_user), and `unique(Team::name, ignore = route("team"))`
    /// calls [`ignore_route`](Unique::ignore_route) for the column's model. `ignore = user("uuid")`
    /// also calls [`ignore_column`](Unique::ignore_column).
    ///
    /// The constructor returns the [`Unique`] builder, which can skip a row and filter the rows
    /// the rule checks. To list the rule with other rules, pass the rules as a tuple.
    ///
    /// ```no_run
    /// # use laravel::model::model;
    /// # #[model] pub struct User { pub id: i64, pub email: String }
    /// use laravel::validation::{DatabaseRules, Rule, Rules};
    ///
    /// let rules = Rules::new().field(
    ///     "email",
    ///     (Rule::required(), Rule::email(), Rule::unique(User::email).ignore_user()),
    /// );
    /// ```
    #[track_caller]
    fn unique<M, C>(column: crate::model::Column<M, C>) -> Unique
    where
        M: Model,
        C: DeserializeOwned + Into<db::Value<'static>>;

    /// Requires a value that some row of the model's table has in `column`, such as the ID of a
    /// category that exists. The rule queries the model's connection and decodes the value as the
    /// column's type, as for [`Rule::unique`](DatabaseRules::unique).
    ///
    /// The constructor returns the [`Exists`] builder, which can filter the rows the rule accepts.
    /// To list the rule with other rules, pass the rules as a tuple.
    ///
    /// ```no_run
    /// # use laravel::model::model;
    /// # #[model] pub struct Category { pub id: i64 }
    /// use laravel::validation::{DatabaseRules, Rule, Rules};
    ///
    /// let rules = Rules::new().field("category_id", (Rule::required(), Rule::exists(Category::id)));
    /// ```
    ///
    /// In a derive attribute, a field whose type differs from the column's type doesn't compile:
    ///
    /// ```compile_fail
    /// # use laravel::model::model;
    /// # #[model] pub struct Category { pub id: i64 }
    /// #[derive(serde::Deserialize, laravel::validation::Validate)]
    /// struct StorePost {
    ///     #[validate(exists(Category::id))]
    ///     category_id: String,
    /// }
    /// ```
    #[track_caller]
    fn exists<M, C>(column: crate::model::Column<M, C>) -> Exists
    where
        M: Model,
        C: DeserializeOwned + Into<db::Value<'static>>;

    /// Requires a value that no row of a table has in a column, like
    /// [`Rule::unique`](DatabaseRules::unique), for a table without a model.
    ///
    /// Either name may include a schema, as in `"app.users"`. The rule queries the default
    /// connection. `T` is the field's Rust type, and the rule decodes the submitted value as `T`.
    /// Nothing checks `T` against the column's type. A table or column name that isn't a plain
    /// identifier fails validation with a `500`.
    ///
    /// In a derive attribute without a column, as in `unique("posts")`, the column is the field's
    /// Rust name. A serde rename changes only the input name. With a table name, `ignore` names the
    /// route's model, as in `ignore = route::<Team>("team")`.
    ///
    /// ```
    /// use laravel::validation::{DatabaseRules, Rule, Rules};
    ///
    /// let rules = Rules::new().field(
    ///     "email",
    ///     [Rule::unique_in::<String>("users", "email").ignore_user()],
    /// );
    /// ```
    #[track_caller]
    fn unique_in<T>(table: impl Into<String>, column: impl Into<String>) -> Unique
    where
        T: DeserializeOwned + Into<db::Value<'static>>;

    /// Requires a value that some row of a table has in a column, like
    /// [`Rule::exists`](DatabaseRules::exists), for a table without a model.
    ///
    /// Either name may include a schema, as in `"app.categories"`. As for
    /// [`Rule::unique_in`](DatabaseRules::unique_in), the rule queries the default connection and
    /// decodes the submitted value as `T`.
    ///
    /// ```
    /// use laravel::validation::{DatabaseRules, Rule, Rules};
    ///
    /// let rules = Rules::new().field("category_id", [Rule::exists_in::<i64>("categories", "id")]);
    /// ```
    #[track_caller]
    fn exists_in<T>(table: impl Into<String>, column: impl Into<String>) -> Exists
    where
        T: DeserializeOwned + Into<db::Value<'static>>;
}

impl DatabaseRules for Rule {
    #[track_caller]
    fn unique<M, C>(column: crate::model::Column<M, C>) -> Unique
    where
        M: Model,
        C: DeserializeOwned + Into<db::Value<'static>>,
    {
        Unique::new::<C>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
    }

    #[track_caller]
    fn exists<M, C>(column: crate::model::Column<M, C>) -> Exists
    where
        M: Model,
        C: DeserializeOwned + Into<db::Value<'static>>,
    {
        Exists::new::<C>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
    }

    #[track_caller]
    fn unique_in<T>(table: impl Into<String>, column: impl Into<String>) -> Unique
    where
        T: DeserializeOwned + Into<db::Value<'static>>,
    {
        Unique::new::<T>(table.into(), column.into(), None)
    }

    #[track_caller]
    fn exists_in<T>(table: impl Into<String>, column: impl Into<String>) -> Exists
    where
        T: DeserializeOwned + Into<db::Value<'static>>,
    {
        Exists::new::<T>(table.into(), column.into(), None)
    }
}

/// The `unique` rule a derive gives a field of type `T` for a column.
#[doc(hidden)]
#[track_caller]
pub fn __unique_field<T, M, C>(column: crate::model::Column<M, C>) -> Unique
where
    M: Model,
    T: crate::model::ComparableTo<C> + DeserializeOwned + Into<db::Value<'static>>,
{
    Unique::new::<T>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
}

/// The `exists` rule a derive gives a field of type `T` for a column.
#[doc(hidden)]
#[track_caller]
pub fn __exists_field<T, M, C>(column: crate::model::Column<M, C>) -> Exists
where
    M: Model,
    T: crate::model::ComparableTo<C> + DeserializeOwned + Into<db::Value<'static>>,
{
    Exists::new::<T>(M::META.table.to_owned(), column.name().to_owned(), M::META.connection)
}

impl DatabaseRule for Unique {
    fn check<'a>(&'a self, field: &'a Field<'a>) -> BoxFuture<'a, crate::Result<Option<Message>>> {
        Box::pin(self.check(field))
    }
}

impl DatabaseRule for Exists {
    fn check<'a>(&'a self, field: &'a Field<'a>) -> BoxFuture<'a, crate::Result<Option<Message>>> {
        Box::pin(self.check(field))
    }
}

impl From<Unique> for Rule {
    fn from(rule: Unique) -> Self {
        Self::__database(rule)
    }
}

impl From<Exists> for Rule {
    fn from(rule: Exists) -> Self {
        Self::__database(rule)
    }
}