Skip to main content

toasty_sql/stmt/
column_def.rs

1use super::CheckConstraint;
2
3use toasty_core::{
4    driver::{self, Capability},
5    schema::db::{self, Column},
6    stmt::Expr,
7};
8
9/// A column definition used in `CREATE TABLE` and `ADD COLUMN` statements.
10#[derive(Debug, Clone)]
11pub struct ColumnDef {
12    /// Column name.
13    pub name: String,
14    /// Storage type (e.g. `INTEGER`, `TEXT`).
15    pub ty: db::Type,
16    /// When `true`, the column has a `NOT NULL` constraint.
17    pub not_null: bool,
18    /// When `true`, the column auto-increments.
19    pub auto_increment: bool,
20    /// Optional CHECK constraint on this column.
21    pub check: Option<CheckConstraint>,
22}
23
24impl ColumnDef {
25    pub(crate) fn from_schema(
26        column: &Column,
27        _storage_types: &driver::StorageTypes,
28        capability: &Capability,
29    ) -> Self {
30        // For SQLite enum columns: store as TEXT with a CHECK constraint instead
31        // of db::Type::Enum. The CHECK constraint restricts values to the
32        // declared variants.
33        if let db::Type::Enum(type_enum) = &column.storage_ty
34            && !capability.native_enum
35        {
36            return Self {
37                name: column.name.clone(),
38                ty: db::Type::Text,
39                not_null: !column.nullable,
40                auto_increment: column.auto_increment,
41                check: Some(CheckConstraint {
42                    name: None,
43                    expr: Box::new(Expr::in_list(
44                        Expr::Ident(column.name.clone()),
45                        Expr::list(
46                            type_enum
47                                .variants
48                                .iter()
49                                .map(|v| Expr::from(v.name.clone())),
50                        ),
51                    )),
52                }),
53            };
54        }
55
56        Self {
57            name: column.name.clone(),
58            ty: column.storage_ty.clone(),
59            not_null: !column.nullable,
60            auto_increment: column.auto_increment,
61            check: None,
62        }
63    }
64}