sea-orm 2.0.1

🐚 An async & dynamic ORM for Rust
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
641
642
use crate::Value;
use sea_query::Nullable;
use std::fmt::Debug;

pub use ActiveValue::{NotSet, Set, Unchanged};

/// The state of a field in an [ActiveModel][crate::ActiveModelTrait].
///
/// There are three possible states represented by three enum variants:
///
/// - [Set] - a value that's explicitly set by the application and sent to the database.
/// - [Unchanged] - an existing, unchanged value from the database.
/// - [NotSet] - an undefined value (nothing is sent to the database).
///
/// The difference between these states is useful
/// when constructing `INSERT` and `UPDATE` SQL statements (see an example below).
/// It's also useful for knowing which fields have changed in a record.
///
/// # Examples
///
/// ```
/// use sea_orm::tests_cfg::{cake, fruit};
/// use sea_orm::{DbBackend, entity::*, query::*};
///
/// // Here, we use `NotSet` to let the database automatically generate an `id`.
/// // This is different from `Set(None)` that explicitly sets `cake_id` to `NULL`.
/// assert_eq!(
///     Insert::one(fruit::ActiveModel {
///         id: ActiveValue::NotSet,
///         name: ActiveValue::Set("Orange".to_owned()),
///         cake_id: ActiveValue::Set(None),
///     })
///     .build(DbBackend::Postgres)
///     .to_string(),
///     r#"INSERT INTO "fruit" ("name", "cake_id") VALUES ('Orange', NULL)"#
/// );
///
/// // Here, we update the record, set `cake_id` to the new value
/// // and use `NotSet` to avoid updating the `name` field.
/// // `id` is the primary key, so it's used in the condition and not updated.
/// assert_eq!(
///     Update::one(fruit::ActiveModel {
///         id: ActiveValue::Unchanged(1),
///         name: ActiveValue::NotSet,
///         cake_id: ActiveValue::Set(Some(2)),
///     })
///     .validate()
///     .unwrap()
///     .build(DbBackend::Postgres)
///     .to_string(),
///     r#"UPDATE "fruit" SET "cake_id" = 2 WHERE "fruit"."id" = 1"#
/// );
/// ```
#[derive(Clone, Debug)]
pub enum ActiveValue<V>
where
    V: Into<Value>,
{
    /// A [Value] that's explicitly set by the application and sent to the database.
    ///
    /// Use this to insert or set a specific value.
    ///
    /// When editing an existing value, you can use [set_ne][ActiveValue::set_ne]
    /// to preserve the [Unchanged] state when the new value is the same as the old one.
    /// Then you can meaningfully use methods like [crate::ActiveModelTrait::is_changed].
    Set(V),
    /// An existing, unchanged [Value] from the database.
    ///
    /// You get these when you query an existing [Model][crate::ModelTrait]
    /// from the database and convert it into an [ActiveModel][crate::ActiveModelTrait].
    ///
    /// When you edit it, you can use [set_ne][ActiveValue::set_ne]
    /// to preserve this "unchanged" state if the new value is the same as the old one.
    /// Then you can meaningfully use methods like [crate::ActiveModelTrait::is_changed].
    Unchanged(V),
    /// An undefined [Value]. Nothing is sent to the database.
    ///
    /// When you create a new [ActiveModel][crate::ActiveModelTrait],
    /// its fields are [NotSet][ActiveValue::NotSet] by default.
    ///
    /// This can be useful when:
    ///
    /// - You insert a new record and want the database to generate a default value (e.g., an id).
    /// - In an `UPDATE` statement, you don't want to update some field.
    NotSet,
}

/// Defines an not set operation on an [ActiveValue]
#[deprecated(
    since = "0.5.0",
    note = "Please use [`ActiveValue::NotSet`] or [`NotSet`]"
)]
#[allow(non_snake_case)]
pub fn Unset<V>(_: Option<bool>) -> ActiveValue<V>
where
    V: Into<Value>,
{
    ActiveValue::not_set()
}

/// Any type that can be converted into an [ActiveValue]
pub trait IntoActiveValue<V>
where
    V: Into<Value>,
{
    /// Method to perform the conversion
    fn into_active_value(self) -> ActiveValue<V>;
}

impl<V> IntoActiveValue<V> for Option<V>
where
    V: IntoActiveValue<V> + Into<Value> + Nullable,
{
    fn into_active_value(self) -> ActiveValue<V> {
        match self {
            Some(value) => Set(value),
            None => NotSet,
        }
    }
}

impl<V> IntoActiveValue<Option<V>> for Option<Option<V>>
where
    V: IntoActiveValue<V> + Into<Value> + Nullable,
{
    fn into_active_value(self) -> ActiveValue<Option<V>> {
        match self {
            Some(value) => Set(value),
            None => NotSet,
        }
    }
}

macro_rules! impl_into_active_value {
    ($ty: ty) => {
        impl IntoActiveValue<$ty> for $ty {
            fn into_active_value(self) -> ActiveValue<$ty> {
                Set(self)
            }
        }
    };
}

impl_into_active_value!(bool);
impl_into_active_value!(i8);
impl_into_active_value!(i16);
impl_into_active_value!(i32);
impl_into_active_value!(i64);
impl_into_active_value!(u8);
impl_into_active_value!(u16);
impl_into_active_value!(u32);
impl_into_active_value!(u64);
impl_into_active_value!(f32);
impl_into_active_value!(f64);
impl_into_active_value!(&'static str);
impl_into_active_value!(String);
impl_into_active_value!(Vec<u8>);

#[cfg(feature = "with-json")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-json")))]
impl_into_active_value!(crate::prelude::Json);

#[cfg(feature = "with-chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
impl_into_active_value!(crate::prelude::Date);

#[cfg(feature = "with-chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
impl_into_active_value!(crate::prelude::Time);

#[cfg(feature = "with-chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
impl_into_active_value!(crate::prelude::DateTime);

#[cfg(feature = "with-chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
impl_into_active_value!(crate::prelude::DateTimeWithTimeZone);

#[cfg(feature = "with-chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
impl_into_active_value!(crate::prelude::DateTimeUtc);

#[cfg(feature = "with-chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-chrono")))]
impl_into_active_value!(crate::prelude::DateTimeLocal);

#[cfg(feature = "with-rust_decimal")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-rust_decimal")))]
impl_into_active_value!(crate::prelude::Decimal);

#[cfg(feature = "with-bigdecimal")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-bigdecimal")))]
impl_into_active_value!(crate::prelude::BigDecimal);

#[cfg(feature = "with-uuid")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-uuid")))]
impl_into_active_value!(crate::prelude::Uuid);

#[cfg(feature = "with-time")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
impl_into_active_value!(crate::prelude::TimeDate);

#[cfg(feature = "with-time")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
impl_into_active_value!(crate::prelude::TimeTime);

#[cfg(feature = "with-time")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
impl_into_active_value!(crate::prelude::TimeDateTime);

#[cfg(feature = "with-time")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-time")))]
impl_into_active_value!(crate::prelude::TimeDateTimeWithTimeZone);

#[cfg(feature = "with-ipnetwork")]
#[cfg_attr(docsrs, doc(cfg(feature = "with-ipnetwork")))]
impl_into_active_value!(crate::prelude::IpNetwork);

impl<V> Default for ActiveValue<V>
where
    V: Into<Value>,
{
    /// Create an [ActiveValue::NotSet]
    fn default() -> Self {
        Self::NotSet
    }
}

impl<V> ActiveValue<V>
where
    V: Into<Value>,
{
    /// Create an [ActiveValue::Set]
    pub fn set(value: V) -> Self {
        Self::Set(value)
    }

    /// Check if the [ActiveValue] is [ActiveValue::Set]
    pub fn is_set(&self) -> bool {
        matches!(self, Self::Set(_))
    }

    /// Check if the [ActiveValue] is [ActiveValue::Set] and that the inner value
    /// matches a given predicate.
    pub fn is_set_and(&self, f: impl FnOnce(&V) -> bool) -> bool {
        matches!(self, Self::Set(v) if f(v))
    }

    /// Create an [ActiveValue::Unchanged]
    pub fn unchanged(value: V) -> Self {
        Self::Unchanged(value)
    }

    /// Check if the [ActiveValue] is [ActiveValue::Unchanged]
    pub fn is_unchanged(&self) -> bool {
        matches!(self, Self::Unchanged(_))
    }

    /// Check if the [ActiveValue] is [ActiveValue::Unchanged] and that the inner
    /// value matches a given predicate.
    pub fn is_unchanged_and(&self, f: impl FnOnce(&V) -> bool) -> bool {
        matches!(self, Self::Unchanged(v) if f(v))
    }

    /// Create an [ActiveValue::NotSet]
    pub fn not_set() -> Self {
        Self::default()
    }

    /// Check if the [ActiveValue] is [ActiveValue::NotSet]
    pub fn is_not_set(&self) -> bool {
        matches!(self, Self::NotSet)
    }

    /// Take ownership of the inner value, also setting self to `NotSet`
    pub fn take(&mut self) -> Option<V> {
        match std::mem::take(self) {
            ActiveValue::Set(value) | ActiveValue::Unchanged(value) => Some(value),
            ActiveValue::NotSet => None,
        }
    }

    /// Get an owned value of the [ActiveValue]
    ///
    /// # Panics
    ///
    /// Panics if it is [ActiveValue::NotSet]
    pub fn unwrap(self) -> V {
        match self {
            ActiveValue::Set(value) | ActiveValue::Unchanged(value) => value,
            ActiveValue::NotSet => panic!("Cannot unwrap ActiveValue::NotSet"),
        }
    }

    /// Take ownership of the inner value, consuming self
    pub fn into_value(self) -> Option<Value> {
        match self {
            ActiveValue::Set(value) | ActiveValue::Unchanged(value) => Some(value.into()),
            ActiveValue::NotSet => None,
        }
    }

    /// Wrap the [Value] into a `ActiveValue<Value>`
    pub fn into_wrapped_value(self) -> ActiveValue<Value> {
        match self {
            Self::Set(value) => ActiveValue::set(value.into()),
            Self::Unchanged(value) => ActiveValue::unchanged(value.into()),
            Self::NotSet => ActiveValue::not_set(),
        }
    }

    /// Reset the value from [ActiveValue::Unchanged] to [ActiveValue::Set],
    /// leaving [ActiveValue::NotSet] untouched.
    pub fn reset(&mut self) {
        *self = match self.take() {
            Some(value) => ActiveValue::Set(value),
            None => ActiveValue::NotSet,
        };
    }

    /// `Set(value)`, except when [`self.is_unchanged()`][ActiveValue#method.is_unchanged]
    /// and `value` equals the current [Unchanged][ActiveValue::Unchanged] value.
    ///
    /// This is useful when you have an [Unchanged][ActiveValue::Unchanged] value from the database,
    /// then update it using this method,
    /// and then use [`.is_unchanged()`][ActiveValue#method.is_unchanged] to see whether it has *actually* changed.
    ///
    /// The same nice effect applies to the entire `ActiveModel`.
    /// You can now meaningfully use [crate::ActiveModelTrait::is_changed][crate::ActiveModelTrait#method.is_changed]
    /// to see whether are any changes that need to be saved to the database.
    ///
    /// ## Examples
    ///
    /// ```
    /// # use sea_orm::ActiveValue;
    /// #
    /// let mut value = ActiveValue::Unchanged("old");
    ///
    /// // This wouldn't be the case if we used plain `value = Set("old");`
    /// value.set_ne("old");
    /// assert!(value.is_unchanged());
    ///
    /// // Only when we change the actual `&str` value, it becomes `Set`
    /// value.set_ne("new");
    /// assert_eq!(value.is_unchanged(), false);
    /// assert_eq!(value, ActiveValue::Set("new"));
    /// ```
    pub fn set_ne(&mut self, value: V)
    where
        V: PartialEq,
    {
        match self {
            ActiveValue::Unchanged(current) if &value == current => {}
            _ => *self = ActiveValue::Set(value),
        }
    }

    /// Alias for [`ActiveValue::set_ne`]. Kept for compatibility.
    pub fn set_if_not_equals(&mut self, value: V)
    where
        V: PartialEq,
    {
        self.set_ne(value);
    }

    /// `Set(value)`, except when [`self.is_unchanged()`][ActiveValue#method.is_unchanged],
    /// `value` equals the current [Unchanged][ActiveValue::Unchanged] value, and `value`
    /// does not match a given predicate.
    ///
    /// This is useful in the same situations as [`ActiveValue::set_ne`] as
    /// well as when you want to leave an existing [Set][ActiveValue::Set] value alone
    /// depending on a condition, such as ensuring a `None` value never replaced an
    /// existing `Some` value. This can come up when trying to merge two [ActiveValue]s.
    ///
    /// ## Examples
    ///
    /// ```
    /// # use sea_orm::ActiveValue;
    /// #
    /// let mut value = ActiveValue::Set(Some("old"));
    ///
    /// // since Option::is_some(None) == false, we leave the existing set value alone
    /// value.set_ne_and(None, Option::is_some);
    /// assert_eq!(value, ActiveValue::Set(Some("old")));
    ///
    /// // since Option::is_some(Some("new")) == true, we replace the set value
    /// value.set_ne_and(Some("new"), Option::is_some);
    /// assert_eq!(value, ActiveValue::Set(Some("new")));
    /// ```
    pub fn set_ne_and(&mut self, value: V, f: impl FnOnce(&V) -> bool)
    where
        V: PartialEq,
    {
        match self {
            ActiveValue::Unchanged(current) if &value == current => {}
            ActiveValue::Set(_) if !f(&value) => {}
            _ => *self = ActiveValue::Set(value),
        }
    }

    /// Alias for [`ActiveValue::set_ne_and`]. Kept for compatibility.
    pub fn set_if_not_equals_and(&mut self, value: V, f: impl FnOnce(&V) -> bool)
    where
        V: PartialEq,
    {
        self.set_ne_and(value, f);
    }

    /// `Set(value)` if [`self.is_not_set()`][ActiveValue#method.is_not_set], no-op otherwise.
    /// Similar to "null coalescing" or [Option#method.get_or_insert], but without
    /// returning the inner value if it is set/unchanged.
    ///
    /// ## Examples
    ///
    /// ```
    /// # use sea_orm::ActiveValue;
    /// #
    /// let mut set_value = ActiveValue::Set(true);
    /// let mut unchanged_value = ActiveValue::Unchanged(true);
    /// let mut notset_value = ActiveValue::NotSet;
    ///
    /// // since `set_value.is_not_set == false`, we leave the existing set value alone
    /// set_value.set_if_unset(false);
    /// assert_eq!(set_value, ActiveValue::Set(true));
    ///
    /// // since `set_value.is_not_set == false`, we leave the existing set value alone
    /// unchanged_value.set_if_unset(false);
    /// assert_eq!(unchanged_value, ActiveValue::Unchanged(true));
    ///
    /// // since `set_value.is_not_set == true`, we fill with the provided value
    /// notset_value.set_if_unset(false);
    /// assert_eq!(notset_value, ActiveValue::Set(false));
    /// ```
    pub fn set_if_unset(&mut self, value: V) {
        if let ActiveValue::NotSet = self {
            *self = ActiveValue::Set(value);
        }
    }

    /// `Set(f())` if [`self.is_not_set()`][ActiveValue#method.is_not_set], no-op otherwise.
    /// Similar to "null coalescing" or [Option#method.get_or_insert_with], but without
    /// returning the inner value if it is set/unchanged.
    ///
    /// This can be useful if the value you want to replace it with is expensive to compute,
    /// or has side-effects which need to be ran (like logging).
    ///
    /// ## Examples
    ///
    /// ```
    /// # use sea_orm::ActiveValue;
    /// #
    /// let mut set_value = ActiveValue::Set(true);
    /// let mut unchanged_value = ActiveValue::Unchanged(true);
    /// let mut notset_value = ActiveValue::NotSet;
    ///
    /// let mut count = 0;
    /// // since `set_value.is_not_set == false`, we leave the existing set value alone
    /// set_value.set_if_unset_with(|| {
    ///     count += 1;
    ///     false
    /// });
    /// assert_eq!(set_value, ActiveValue::Set(true));
    ///
    /// // since `set_value.is_not_set == false`, we leave the existing set value alone
    /// unchanged_value.set_if_unset_with(|| {
    ///     count += 1;
    ///     false
    /// });
    /// assert_eq!(unchanged_value, ActiveValue::Unchanged(true));
    ///
    /// // since `set_value.is_not_set == true`, we fill with the result of the provided computation.
    /// notset_value.set_if_unset_with(|| {
    ///     count += 1;
    ///     false
    /// });
    /// assert_eq!(notset_value, ActiveValue::Set(false));
    ///
    /// // Only the last closure actually executed.
    /// assert_eq!(count, 1);
    /// ```
    pub fn set_if_unset_with(&mut self, f: impl FnOnce() -> V) {
        if let ActiveValue::NotSet = self {
            *self = ActiveValue::Set(f());
        }
    }

    /// `Set(V::default())` if [`self.is_not_set()`][ActiveValue#method.is_not_set], no-op otherwise.
    /// Similar to "null coalescing" or [Option#method.get_or_insert_default], but without
    /// returning the inner value if it is set/unchanged.
    ///
    /// Convenient shorthand for `set_if_unset(Default::default())`.
    ///
    /// ## Examples
    ///
    /// ```
    /// # use sea_orm::ActiveValue;
    /// #
    /// let mut set_value = ActiveValue::Set(100);
    /// let mut unchanged_value = ActiveValue::Unchanged(100);
    /// let mut notset_value = ActiveValue::NotSet;
    ///
    /// // since `set_value.is_not_set == false`, we leave the existing set value alone
    /// set_value.set_if_unset_default();
    /// assert_eq!(set_value, ActiveValue::Set(100));
    ///
    /// // since `set_value.is_not_set == false`, we leave the existing set value alone
    /// unchanged_value.set_if_unset_default();
    /// assert_eq!(unchanged_value, ActiveValue::Unchanged(100));
    ///
    /// // since `set_value.is_not_set == true`, we fill with the default int (0)
    /// notset_value.set_if_unset_default();
    /// assert_eq!(notset_value, ActiveValue::Set(0));
    /// ```
    pub fn set_if_unset_default(&mut self)
    where
        V: Default,
    {
        if let ActiveValue::NotSet = self {
            *self = ActiveValue::Set(V::default());
        }
    }

    /// Get the inner value, unless `self` is [NotSet][ActiveValue::NotSet].
    ///
    /// There's also a panicking version: [ActiveValue::as_ref].
    ///
    /// ## Examples
    ///
    /// ```
    /// # use sea_orm::ActiveValue;
    /// #
    /// assert_eq!(ActiveValue::Unchanged(42).try_as_ref(), Some(&42));
    /// assert_eq!(ActiveValue::Set(42).try_as_ref(), Some(&42));
    /// assert_eq!(ActiveValue::NotSet.try_as_ref(), None::<&i32>);
    /// ```
    pub fn try_as_ref(&self) -> Option<&V> {
        match self {
            ActiveValue::Set(value) | ActiveValue::Unchanged(value) => Some(value),
            ActiveValue::NotSet => None,
        }
    }
}

impl<V> ActiveValue<Option<V>>
where
    V: Into<Value> + Nullable,
{
    /// Flatten an `&ActiveValue<Option<V>>` into an `Option<&V>`, folding
    /// [NotSet][ActiveValue::NotSet] together with the inner [None][Option::None],
    /// and [Set][ActiveValue::Set] / [Unchanged][ActiveValue::Unchanged] together
    /// with the inner [Some][Option::Some].
    ///
    /// Shorthand for `self.try_as_ref().and_then(Option::as_ref)`. For the owned
    /// version, see [ActiveValue::into_option].
    ///
    /// ```
    /// use sea_orm::ActiveValue;
    ///
    /// let x: ActiveValue<Option<i32>> = ActiveValue::Set(Some(1));
    /// let y: ActiveValue<Option<i32>> = ActiveValue::Set(None);
    /// let z: ActiveValue<Option<i32>> = ActiveValue::NotSet;
    ///
    /// assert_eq!(x.as_option(), Some(&1));
    /// assert_eq!(y.as_option(), None);
    /// assert_eq!(z.as_option(), None);
    ///
    /// // composes cleanly with a predicate, on a single line
    /// assert!(x.as_option().is_some_and(|v| *v == 1));
    /// ```
    pub fn as_option(&self) -> Option<&V> {
        self.try_as_ref().and_then(Option::as_ref)
    }

    /// Flatten an `ActiveValue<Option<V>>` into an `Option<V>`, folding
    /// [NotSet][ActiveValue::NotSet] together with the inner [None][Option::None],
    /// and [Set][ActiveValue::Set] / [Unchanged][ActiveValue::Unchanged] together
    /// with the inner [Some][Option::Some].
    ///
    /// For a borrowing version, see [ActiveValue::as_option].
    ///
    /// ```
    /// use sea_orm::ActiveValue;
    ///
    /// let x: ActiveValue<Option<i32>> = ActiveValue::Set(Some(1));
    /// let y: ActiveValue<Option<i32>> = ActiveValue::Set(None);
    /// let z: ActiveValue<Option<i32>> = ActiveValue::NotSet;
    ///
    /// assert_eq!(x.into_option(), Some(1));
    /// assert_eq!(y.into_option(), None);
    /// assert_eq!(z.into_option(), None);
    /// ```
    pub fn into_option(self) -> Option<V> {
        match self {
            ActiveValue::Set(value) | ActiveValue::Unchanged(value) => value,
            ActiveValue::NotSet => None,
        }
    }
}

impl<V> std::convert::AsRef<V> for ActiveValue<V>
where
    V: Into<Value>,
{
    /// # Panics
    ///
    /// Panics if it is [ActiveValue::NotSet].
    ///
    /// See [ActiveValue::try_as_ref] for a fallible non-panicking version.
    fn as_ref(&self) -> &V {
        match self {
            ActiveValue::Set(value) | ActiveValue::Unchanged(value) => value,
            ActiveValue::NotSet => panic!("Cannot borrow ActiveValue::NotSet"),
        }
    }
}

impl<V> PartialEq for ActiveValue<V>
where
    V: Into<Value> + std::cmp::PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ActiveValue::Set(l), ActiveValue::Set(r)) => l == r,
            (ActiveValue::Unchanged(l), ActiveValue::Unchanged(r)) => l == r,
            (ActiveValue::NotSet, ActiveValue::NotSet) => true,
            _ => false,
        }
    }
}

impl<V> From<ActiveValue<V>> for ActiveValue<Option<V>>
where
    V: Into<Value> + Nullable,
{
    fn from(value: ActiveValue<V>) -> Self {
        match value {
            ActiveValue::Set(value) => ActiveValue::set(Some(value)),
            ActiveValue::Unchanged(value) => ActiveValue::unchanged(Some(value)),
            ActiveValue::NotSet => ActiveValue::not_set(),
        }
    }
}