drizzle-types 0.3.0

A type-safe SQL query builder 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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! `PostgreSQL` columns: [`ColumnDef`] (const) and [`Column`] (runtime), with
//! their generated-column and identity settings.

use crate::alloc_prelude::*;

#[cfg(feature = "serde")]
use crate::serde_helpers::{cow_from_string, cow_option_from_string};

// =============================================================================
// Generated Column Types
// =============================================================================

/// Whether a generated column is `STORED` or `VIRTUAL` (`VIRTUAL` needs
/// PostgreSQL 18 or later).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum GeneratedType {
    /// Stored generated column
    #[default]
    Stored,
    /// Virtual generated column
    Virtual,
}

/// The `GENERATED ALWAYS AS (...)` part of a [`ColumnDef`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GeneratedDef {
    /// SQL expression for generation
    pub expression: &'static str,
    /// `STORED` or `VIRTUAL`
    pub gen_type: GeneratedType,
}

impl GeneratedDef {
    /// Creates a `STORED` generated column from a SQL expression.
    #[must_use]
    pub const fn stored(expression: &'static str) -> Self {
        Self {
            expression,
            gen_type: GeneratedType::Stored,
        }
    }

    /// Creates a `VIRTUAL` generated column from a SQL expression.
    #[must_use]
    pub const fn virtual_col(expression: &'static str) -> Self {
        Self {
            expression,
            gen_type: GeneratedType::Virtual,
        }
    }

    /// Converts to the runtime [`Generated`].
    #[must_use]
    pub const fn into_generated(self) -> Generated {
        Generated {
            expression: Cow::Borrowed(self.expression),
            gen_type: self.gen_type,
        }
    }
}

/// The `GENERATED ALWAYS AS (...)` part of a [`Column`]. With `serde`, the
/// fields are named `as` and `type`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Generated {
    /// SQL expression for generation
    #[cfg_attr(
        feature = "serde",
        serde(rename = "as", deserialize_with = "cow_from_string")
    )]
    pub expression: Cow<'static, str>,
    /// `STORED` or `VIRTUAL`
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub gen_type: GeneratedType,
}

// =============================================================================
// Identity Column Types
// =============================================================================

/// Whether an identity column is `GENERATED ALWAYS` or `GENERATED BY DEFAULT`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub enum IdentityType {
    /// GENERATED ALWAYS AS IDENTITY
    #[default]
    Always,
    /// GENERATED BY DEFAULT AS IDENTITY
    ByDefault,
}

/// The `GENERATED ... AS IDENTITY` part of a [`ColumnDef`], with the options
/// of its backing sequence. Numeric options are SQL literals stored as
/// strings, so they can hold any `bigint`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IdentityDef {
    /// Name of the backing sequence
    pub name: &'static str,
    /// Schema of the backing sequence
    pub schema: Option<&'static str>,
    /// `ALWAYS` or `BY DEFAULT`
    pub type_: IdentityType,
    /// `INCREMENT BY`
    pub increment: Option<&'static str>,
    /// `MINVALUE`
    pub min_value: Option<&'static str>,
    /// `MAXVALUE`
    pub max_value: Option<&'static str>,
    /// `START WITH`
    pub start_with: Option<&'static str>,
    /// `CACHE`
    pub cache: Option<i32>,
    /// `CYCLE`
    pub cycle: bool,
}

impl IdentityDef {
    /// Creates an identity backed by the sequence `name`, with default options.
    #[must_use]
    pub const fn new(name: &'static str, type_: IdentityType) -> Self {
        Self {
            name,
            schema: None,
            type_,
            increment: None,
            min_value: None,
            max_value: None,
            start_with: None,
            cache: None,
            cycle: false,
        }
    }

    /// Sets the sequence's schema.
    #[must_use]
    pub const fn schema(self, schema: &'static str) -> Self {
        Self {
            schema: Some(schema),
            ..self
        }
    }

    /// Sets `INCREMENT BY`.
    #[must_use]
    pub const fn increment(self, value: &'static str) -> Self {
        Self {
            increment: Some(value),
            ..self
        }
    }

    /// Sets `MINVALUE`.
    #[must_use]
    pub const fn min_value(self, value: &'static str) -> Self {
        Self {
            min_value: Some(value),
            ..self
        }
    }

    /// Sets `MAXVALUE`.
    #[must_use]
    pub const fn max_value(self, value: &'static str) -> Self {
        Self {
            max_value: Some(value),
            ..self
        }
    }

    /// Sets `START WITH`.
    #[must_use]
    pub const fn start_with(self, value: &'static str) -> Self {
        Self {
            start_with: Some(value),
            ..self
        }
    }

    /// Sets `CACHE`.
    #[must_use]
    pub const fn cache(self, value: i32) -> Self {
        Self {
            cache: Some(value),
            ..self
        }
    }

    /// Sets `CYCLE`.
    #[must_use]
    pub const fn cycle(self) -> Self {
        Self {
            cycle: true,
            ..self
        }
    }

    /// Converts to the runtime [`Identity`].
    #[must_use]
    pub const fn into_identity(self) -> Identity {
        Identity {
            name: Cow::Borrowed(self.name),
            schema: match self.schema {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            type_: self.type_,
            increment: match self.increment {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            min_value: match self.min_value {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            max_value: match self.max_value {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            start_with: match self.start_with {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            cache: self.cache,
            cycle: if self.cycle { Some(true) } else { None },
        }
    }
}

/// The `GENERATED ... AS IDENTITY` part of a [`Column`]; see [`IdentityDef`].
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Identity {
    /// Name of the backing sequence
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,

    /// Schema of the backing sequence
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub schema: Option<Cow<'static, str>>,

    /// `ALWAYS` or `BY DEFAULT` (serialized as `type`: `"always"` or
    /// `"byDefault"`)
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub type_: IdentityType,

    /// `INCREMENT BY`
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub increment: Option<Cow<'static, str>>,

    /// `MINVALUE`
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub min_value: Option<Cow<'static, str>>,

    /// `MAXVALUE`
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub max_value: Option<Cow<'static, str>>,

    /// `START WITH`
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub start_with: Option<Cow<'static, str>>,

    /// `CACHE`
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub cache: Option<i32>,

    /// `CYCLE`
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub cycle: Option<bool>,
}

impl Identity {
    /// Creates a `GENERATED ALWAYS AS IDENTITY` backed by the sequence `name`.
    #[must_use]
    pub fn always(name: impl Into<Cow<'static, str>>) -> Self {
        Self {
            name: name.into(),
            schema: None,
            type_: IdentityType::Always,
            increment: None,
            min_value: None,
            max_value: None,
            start_with: None,
            cache: None,
            cycle: None,
        }
    }

    /// Creates a `GENERATED BY DEFAULT AS IDENTITY` backed by the sequence
    /// `name`.
    #[must_use]
    pub fn by_default(name: impl Into<Cow<'static, str>>) -> Self {
        Self {
            name: name.into(),
            schema: None,
            type_: IdentityType::ByDefault,
            increment: None,
            min_value: None,
            max_value: None,
            start_with: None,
            cache: None,
            cycle: None,
        }
    }

    /// Sets the sequence's schema.
    #[must_use]
    pub fn schema(mut self, schema: impl Into<Cow<'static, str>>) -> Self {
        self.schema = Some(schema.into());
        self
    }
}

// =============================================================================
// Const-friendly Definition Type
// =============================================================================

/// A column definition that can be built in a `const`.
///
/// Primary keys and unique constraints are separate entities
/// ([`PrimaryKeyDef`](super::PrimaryKeyDef),
/// [`UniqueConstraintDef`](super::UniqueConstraintDef)).
///
/// # Examples
///
/// ```
/// use drizzle_types::postgres::ddl::{ColumnDef, IdentityDef, IdentityType};
///
/// const ID: ColumnDef = ColumnDef::new("public", "users", "id", "integer")
///     .not_null()
///     .identity(IdentityDef::new("users_id_seq", IdentityType::Always));
///
/// let column = ID.into_column();
/// assert!(column.identity.is_some());
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ColumnDef {
    /// Schema name
    pub schema: &'static str,
    /// Parent table name
    pub table: &'static str,
    /// Column name
    pub name: &'static str,
    /// SQL type, such as `"integer"` or `"varchar(255)"`; for an enum, the
    /// enum's type name
    pub sql_type: &'static str,
    /// Schema of a custom or enum type
    pub type_schema: Option<&'static str>,
    /// `NOT NULL`
    pub not_null: bool,
    /// `DEFAULT` value as SQL
    pub default: Option<&'static str>,
    /// Generated column configuration
    pub generated: Option<GeneratedDef>,
    /// Identity column configuration
    pub identity: Option<IdentityDef>,
    /// Number of array dimensions: `Some(1)` renders `type[]`
    pub dimensions: Option<i32>,
    /// Column comment, emitted as `COMMENT ON COLUMN`
    pub comment: Option<&'static str>,
    /// Collation name (e.g. `"en_US"`, `"C"`, `"POSIX"`, or a custom
    /// `CREATE COLLATION` name). `None` uses the type's default collation and
    /// emits no `COLLATE` clause.
    pub collate: Option<&'static str>,
}

impl ColumnDef {
    /// Creates a nullable column with no default.
    #[must_use]
    pub const fn new(
        schema: &'static str,
        table: &'static str,
        name: &'static str,
        sql_type: &'static str,
    ) -> Self {
        Self {
            schema,
            table,
            name,
            sql_type,
            type_schema: None,
            not_null: false,
            default: None,
            generated: None,
            identity: None,
            dimensions: None,
            comment: None,
            collate: None,
        }
    }

    /// Sets the schema of a custom or enum type.
    #[must_use]
    pub const fn type_schema(self, schema: &'static str) -> Self {
        Self {
            type_schema: Some(schema),
            ..self
        }
    }

    /// Adds `NOT NULL`.
    #[must_use]
    pub const fn not_null(self) -> Self {
        Self {
            not_null: true,
            ..self
        }
    }

    /// Sets the `DEFAULT` value, written as SQL.
    #[must_use]
    pub const fn default_value(self, value: &'static str) -> Self {
        Self {
            default: Some(value),
            ..self
        }
    }

    /// Makes the column `GENERATED ALWAYS AS (expression) STORED`.
    #[must_use]
    pub const fn generated_stored(self, expression: &'static str) -> Self {
        Self {
            generated: Some(GeneratedDef::stored(expression)),
            ..self
        }
    }

    /// Makes the column `GENERATED ALWAYS AS (expression) VIRTUAL`.
    #[must_use]
    pub const fn generated_virtual(self, expression: &'static str) -> Self {
        Self {
            generated: Some(GeneratedDef::virtual_col(expression)),
            ..self
        }
    }

    /// Makes the column an identity column.
    #[must_use]
    pub const fn identity(self, identity: IdentityDef) -> Self {
        Self {
            identity: Some(identity),
            ..self
        }
    }

    /// Sets the number of array dimensions.
    #[must_use]
    pub const fn dimensions(self, dims: i32) -> Self {
        Self {
            dimensions: Some(dims),
            ..self
        }
    }

    /// Sets the column comment.
    #[must_use]
    pub const fn comment(self, comment: &'static str) -> Self {
        Self {
            comment: Some(comment),
            ..self
        }
    }

    /// Sets the column's collation.
    ///
    /// Pass the bare name, such as `en_US`; it is rendered quoted, as in
    /// `COLLATE "en_US"`.
    #[must_use]
    pub const fn collate(self, name: &'static str) -> Self {
        Self {
            collate: Some(name),
            ..self
        }
    }

    /// Converts to the runtime [`Column`].
    #[must_use]
    pub const fn into_column(self) -> Column {
        Column {
            schema: Cow::Borrowed(self.schema),
            table: Cow::Borrowed(self.table),
            name: Cow::Borrowed(self.name),
            sql_type: Cow::Borrowed(self.sql_type),
            type_schema: match self.type_schema {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            not_null: self.not_null,
            default: match self.default {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            generated: match self.generated {
                Some(g) => Some(g.into_generated()),
                None => None,
            },
            identity: match self.identity {
                Some(i) => Some(i.into_identity()),
                None => None,
            },
            dimensions: self.dimensions,
            comment: match self.comment {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            collate: match self.collate {
                Some(s) => Some(Cow::Borrowed(s)),
                None => None,
            },
            ordinal_position: None,
        }
    }
}

impl Default for ColumnDef {
    fn default() -> Self {
        Self::new("public", "", "", "")
    }
}

// =============================================================================
// Runtime Type for Serde
// =============================================================================

/// A table column, as stored in migration snapshots.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Column {
    /// Schema name
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub schema: Cow<'static, str>,

    /// Parent table name
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub table: Cow<'static, str>,

    /// Column name
    #[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
    pub name: Cow<'static, str>,

    /// SQL type, such as `"integer"` (serialized as `type`)
    #[cfg_attr(
        feature = "serde",
        serde(rename = "type", deserialize_with = "cow_from_string")
    )]
    pub sql_type: Cow<'static, str>,

    /// Schema of a custom or enum type
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub type_schema: Option<Cow<'static, str>>,

    /// `NOT NULL`
    #[cfg_attr(feature = "serde", serde(default))]
    pub not_null: bool,

    /// `DEFAULT` value as SQL
    #[cfg_attr(
        feature = "serde",
        serde(default, deserialize_with = "cow_option_from_string")
    )]
    pub default: Option<Cow<'static, str>>,

    /// Generated column configuration
    #[cfg_attr(feature = "serde", serde(default))]
    pub generated: Option<Generated>,

    /// Identity column configuration
    #[cfg_attr(feature = "serde", serde(default))]
    pub identity: Option<Identity>,

    /// Number of array dimensions
    #[cfg_attr(feature = "serde", serde(default))]
    pub dimensions: Option<i32>,

    /// Column comment, emitted as `COMMENT ON COLUMN`
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "cow_option_from_string"
        )
    )]
    pub comment: Option<Cow<'static, str>>,

    /// Collation name (e.g. `"en_US"`, `"C"`). `None` means the database
    /// default collation and no `COLLATE` clause is emitted.
    #[cfg_attr(
        feature = "serde",
        serde(default, deserialize_with = "cow_option_from_string")
    )]
    pub collate: Option<Cow<'static, str>>,

    /// Ordinal position within the table (1-based).
    ///
    /// This is primarily populated by introspection and used for stable codegen ordering.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub ordinal_position: Option<i32>,
}

impl Column {
    /// Creates a nullable column with no default.
    #[must_use]
    pub fn new(
        schema: impl Into<Cow<'static, str>>,
        table: impl Into<Cow<'static, str>>,
        name: impl Into<Cow<'static, str>>,
        sql_type: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            schema: schema.into(),
            table: table.into(),
            name: name.into(),
            sql_type: sql_type.into(),
            type_schema: None,
            not_null: false,
            default: None,
            generated: None,
            identity: None,
            dimensions: None,
            comment: None,
            collate: None,
            ordinal_position: None,
        }
    }

    /// Adds `NOT NULL`.
    #[must_use]
    pub const fn not_null(mut self) -> Self {
        self.not_null = true;
        self
    }

    /// Sets the `DEFAULT` value, written as SQL.
    #[must_use]
    pub fn default_value(mut self, value: impl Into<Cow<'static, str>>) -> Self {
        self.default = Some(value.into());
        self
    }

    /// Makes the column an identity column.
    #[must_use]
    pub fn identity(mut self, identity: Identity) -> Self {
        self.identity = Some(identity);
        self
    }

    /// Sets the column comment.
    #[must_use]
    pub fn comment(mut self, comment: impl Into<Cow<'static, str>>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Returns the schema name.
    #[inline]
    #[must_use]
    pub fn schema(&self) -> &str {
        &self.schema
    }

    /// Returns the table name.
    #[inline]
    #[must_use]
    pub fn table(&self) -> &str {
        &self.table
    }

    /// Returns the column name.
    #[inline]
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the SQL type.
    #[inline]
    #[must_use]
    pub fn sql_type(&self) -> &str {
        &self.sql_type
    }
}

impl Default for Column {
    fn default() -> Self {
        Self::new("public", "", "", "")
    }
}

impl From<ColumnDef> for Column {
    fn from(def: ColumnDef) -> Self {
        def.into_column()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_const_column_def() {
        const COLDEF: ColumnDef = ColumnDef::new("public", "users", "id", "INTEGER").not_null();

        assert_eq!(COLDEF.schema, "public");
        assert_eq!(COLDEF.name, "id");
        assert_eq!(COLDEF.table, "users");
        assert_eq!(COLDEF.sql_type, "INTEGER");
        const {
            assert!(COLDEF.not_null);
        }

        let col: Column = COLDEF.into_column();

        assert_eq!(col.schema, Cow::Borrowed("public"));
        assert_eq!(col.name, Cow::Borrowed("id"));
        assert_eq!(col.table, Cow::Borrowed("users"));
        assert_eq!(col.sql_type, Cow::Borrowed("INTEGER"));
        assert!(col.not_null);
    }

    #[test]
    fn test_identity_column() {
        const IDENTITY_DEF: IdentityDef = IdentityDef::new("users_id_seq", IdentityType::Always)
            .increment("1")
            .start_with("1");

        const COL: ColumnDef =
            ColumnDef::new("public", "users", "id", "INTEGER").identity(IDENTITY_DEF);

        assert!(COL.identity.is_some());
    }

    #[test]
    fn test_generated_virtual_column() {
        const COL: ColumnDef = ColumnDef::new("public", "users", "name_len", "INTEGER")
            .generated_virtual("length(name)");

        assert_eq!(
            COL.generated.expect("generated column").gen_type,
            GeneratedType::Virtual
        );

        let col = COL.into_column();
        assert_eq!(
            col.generated.expect("generated column").gen_type,
            GeneratedType::Virtual
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_roundtrip() {
        let col = Column::new("public", "users", "id", "INTEGER");
        let json = serde_json::to_string(&col).unwrap();
        let parsed: Column = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name(), "id");
    }
}