use crate::schema::{DataType, LengthUnit};
use crate::value::Value;
const COUNTS_CHARACTERS: u16 = 1;
#[derive(Clone, Debug, PartialEq)]
pub struct Column {
pub(crate) id: u32,
pub(crate) name: String,
pub(crate) domain: u16,
pub(crate) width: u32,
pub(crate) scale: u16,
pub(crate) nullable: bool,
pub(crate) default: Option<String>,
pub(crate) first_schema: u32,
pub(crate) absent: Option<Value>,
}
impl Column {
#[must_use]
pub fn id(&self) -> u32 {
self.id
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn data_type(&self) -> DataType {
DataType::from_domain(self.domain)
}
#[must_use]
pub fn domain(&self) -> u16 {
self.domain
}
#[must_use]
pub fn width(&self) -> u32 {
self.width
}
#[must_use]
pub fn length_unit(&self) -> Option<LengthUnit> {
match self.data_type() {
DataType::Char | DataType::VarChar if self.scale == COUNTS_CHARACTERS => {
Some(LengthUnit::Characters)
}
DataType::Char | DataType::VarChar | DataType::Binary | DataType::VarBinary => {
Some(LengthUnit::Bytes)
}
_ => None,
}
}
#[must_use]
pub fn scale(&self) -> u16 {
self.scale
}
#[must_use]
pub fn is_nullable(&self) -> bool {
self.nullable
}
#[must_use]
pub fn default(&self) -> Option<&str> {
self.default.as_deref()
}
#[must_use]
pub fn first_schema(&self) -> u32 {
self.first_schema
}
#[must_use]
pub fn absent_value(&self) -> Option<&Value> {
self.absent.as_ref()
}
#[must_use]
pub fn sql_type(&self) -> String {
let name = self.data_type().name();
match self.data_type() {
DataType::Numeric | DataType::Decimal => {
format!("{name}({},{})", self.width, self.scale)
}
DataType::Char | DataType::VarChar | DataType::Binary | DataType::VarBinary => {
format!("{name}({})", self.width)
}
DataType::Unknown(domain) => format!("{name}({domain})"),
_ => name.to_owned(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_scale_of_a_character_column_says_what_its_width_counts() {
let unit = |domain, scale| {
let column = Column {
id: 1,
name: "name".to_owned(),
domain,
width: 20,
scale,
nullable: false,
default: None,
first_schema: 0,
absent: Some(Value::Null),
};
column.length_unit()
};
assert_eq!(unit(9, 0), Some(LengthUnit::Bytes));
assert_eq!(unit(9, 1), Some(LengthUnit::Characters));
assert_eq!(unit(8, 1), Some(LengthUnit::Characters));
assert_eq!(unit(28, 1), Some(LengthUnit::Bytes));
assert_eq!((unit(10, 1), unit(2, 0)), (None, None));
}
}