|
| 1 | +use crate::analysis_route::constants::{LOW_CARDINALITY_WRAPPER, NULLABLE_WRAPPER}; |
| 2 | +use crate::analysis_route::models::TypeMatch; |
| 3 | + |
| 4 | +/// A declared and an inferred ClickHouse type compared without top-level wrappers, nullability apart. |
| 5 | +#[must_use] |
| 6 | +pub fn clickhouse_type_match(declared: &str, inferred: &str, inferred_nullable: bool) -> TypeMatch { |
| 7 | + let (declared_base, declared_nullable) = unwrapped(declared); |
| 8 | + let (inferred_base, wrapped_nullable) = unwrapped(inferred); |
| 9 | + TypeMatch { |
| 10 | + same_type: declared_base == inferred_base, |
| 11 | + nullable_into_non_null: !declared_nullable && (inferred_nullable || wrapped_nullable), |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +/// The type inside its top-level `Nullable` and `LowCardinality` wrappers, and whether it is nullable. |
| 16 | +fn unwrapped(type_sql: &str) -> (&str, bool) { |
| 17 | + let mut current: &str = type_sql.trim(); |
| 18 | + let mut nullable: bool = false; |
| 19 | + loop { |
| 20 | + if let Some(inner) = wrapped(current, NULLABLE_WRAPPER) { |
| 21 | + nullable = true; |
| 22 | + current = inner; |
| 23 | + } else if let Some(inner) = wrapped(current, LOW_CARDINALITY_WRAPPER) { |
| 24 | + current = inner; |
| 25 | + } else { |
| 26 | + return (current, nullable); |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/// The argument of `wrapper(...)` when the whole of `type_sql` is that one call. |
| 32 | +fn wrapped<'a>(type_sql: &'a str, wrapper: &str) -> Option<&'a str> { |
| 33 | + let head: &str = type_sql.get(..wrapper.len())?; |
| 34 | + if !head.eq_ignore_ascii_case(wrapper) { |
| 35 | + return None; |
| 36 | + } |
| 37 | + let inner: &str = type_sql[wrapper.len()..] |
| 38 | + .trim_start() |
| 39 | + .strip_prefix('(')? |
| 40 | + .strip_suffix(')')?; |
| 41 | + let mut depth: usize = 0; |
| 42 | + for character in inner.chars() { |
| 43 | + match character { |
| 44 | + '(' => depth += 1, |
| 45 | + ')' if depth == 0 => return None, |
| 46 | + ')' => depth -= 1, |
| 47 | + _ => {} |
| 48 | + } |
| 49 | + } |
| 50 | + Some(inner.trim()) |
| 51 | +} |
0 commit comments