codegen ColumnDef null() and unique()

This commit is contained in:
Billy Chan 2021-06-22 22:40:43 +08:00
parent cbf16102c0
commit 83e4859776
No known key found for this signature in database
GPG Key ID: A2D690CAC7DF3CC7
2 changed files with 24 additions and 2 deletions

View File

@ -47,7 +47,7 @@ impl ColumnTrait for Column {
match self { match self {
Self::Id => ColumnType::Integer.def(), Self::Id => ColumnType::Integer.def(),
Self::Name => ColumnType::String(Some(255u32)).def(), Self::Name => ColumnType::String(Some(255u32)).def(),
Self::CakeId => ColumnType::Integer.def(), Self::CakeId => ColumnType::Integer.def().null(),
} }
} }
} }

View File

@ -9,6 +9,7 @@ pub struct Column {
pub(crate) col_type: ColumnType, pub(crate) col_type: ColumnType,
pub(crate) auto_increment: bool, pub(crate) auto_increment: bool,
pub(crate) not_null: bool, pub(crate) not_null: bool,
pub(crate) unique: bool,
} }
impl Column { impl Column {
@ -50,7 +51,7 @@ impl Column {
} }
pub fn get_def(&self) -> TokenStream { pub fn get_def(&self) -> TokenStream {
match &self.col_type { let mut col_def = match &self.col_type {
ColumnType::Char(s) => match s { ColumnType::Char(s) => match s {
Some(s) => quote! { ColumnType::Char(Some(#s)).def() }, Some(s) => quote! { ColumnType::Char(Some(#s)).def() },
None => quote! { ColumnType::Char(None).def() }, None => quote! { ColumnType::Char(None).def() },
@ -86,7 +87,18 @@ impl Column {
let s = s.to_string(); let s = s.to_string();
quote! { ColumnType::Custom(#s.to_owned()).def() } quote! { ColumnType::Custom(#s.to_owned()).def() }
} }
};
if !self.not_null {
col_def.extend(quote! {
.null()
});
} }
if self.unique {
col_def.extend(quote! {
.unique()
});
}
col_def
} }
} }
@ -115,11 +127,21 @@ impl From<&ColumnDef> for Column {
}) })
.collect(); .collect();
let not_null = !not_nulls.is_empty(); let not_null = !not_nulls.is_empty();
let uniques: Vec<bool> = col_def
.get_column_spec()
.iter()
.filter_map(|spec| match spec {
ColumnSpec::UniqueKey => Some(true),
_ => None,
})
.collect();
let unique = !uniques.is_empty();
Self { Self {
name, name,
col_type, col_type,
auto_increment, auto_increment,
not_null, not_null,
unique,
} }
} }
} }