use serde::Serialize;
use super::RivetType;
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SourceColumn {
pub name: String,
pub native_type: String,
pub nullable: bool,
pub precision: Option<u8>,
pub scale: Option<i8>,
pub length: Option<u64>,
pub datetime_precision: Option<u8>,
}
impl SourceColumn {
pub fn simple(name: impl Into<String>, native_type: impl Into<String>, nullable: bool) -> Self {
Self {
name: name.into(),
native_type: native_type.into(),
nullable,
precision: None,
scale: None,
length: None,
datetime_precision: None,
}
}
#[allow(dead_code)]
pub fn decimal(
name: impl Into<String>,
native_type: impl Into<String>,
nullable: bool,
precision: u8,
scale: i8,
) -> Self {
Self {
name: name.into(),
native_type: native_type.into(),
nullable,
precision: Some(precision),
scale: Some(scale),
length: None,
datetime_precision: None,
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ColumnOverride {
pub name: String,
pub rivet_type: RivetType,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn simple_constructor_leaves_optional_metadata_blank() {
let c = SourceColumn::simple("id", "int8", false);
assert_eq!(c.name, "id");
assert_eq!(c.native_type, "int8");
assert!(!c.nullable);
assert_eq!(c.precision, None);
assert_eq!(c.scale, None);
assert_eq!(c.length, None);
assert_eq!(c.datetime_precision, None);
}
#[test]
fn decimal_constructor_sets_precision_scale() {
let c = SourceColumn::decimal("amount", "numeric", true, 18, 2);
assert_eq!(c.precision, Some(18));
assert_eq!(c.scale, Some(2));
assert!(c.nullable);
}
#[test]
fn negative_scale_is_supported_for_postgres_numeric() {
let c = SourceColumn::decimal("rough", "numeric", false, 5, -2);
assert_eq!(c.scale, Some(-2));
}
#[test]
fn source_column_serializes_nullable_optional_fields() {
let c = SourceColumn::decimal("amount", "numeric", true, 18, 2);
let json: serde_json::Value =
serde_json::from_str(&serde_json::to_string(&c).expect("serialize")).expect("parse");
assert_eq!(json["name"], "amount");
assert_eq!(json["native_type"], "numeric");
assert_eq!(json["nullable"], true);
assert_eq!(json["precision"], 18);
assert_eq!(json["scale"], 2);
assert!(json["length"].is_null());
assert!(json["datetime_precision"].is_null());
}
}