polars_core/datatypes/
schema.rs

1use super::*;
2
3pub trait SchemaExtPl {
4    // Answers if this schema matches the given schema.
5    //
6    // Allows (nested) Null types in this schema to match any type in the schema,
7    // but not vice versa. In such a case Ok(true) is returned, because a cast
8    // is necessary. If no cast is necessary Ok(false) is returned, and an
9    // error is returned if the types are incompatible.
10    fn matches_schema(&self, other: &Schema) -> PolarsResult<bool>;
11
12    fn ensure_is_exact_match(&self, other: &Schema) -> PolarsResult<()>;
13}
14
15impl SchemaExtPl for Schema {
16    fn matches_schema(&self, other: &Schema) -> PolarsResult<bool> {
17        polars_ensure!(self.len() == other.len(), SchemaMismatch: "found different number of fields in schema's\n\nLeft schema: {} fields, right schema: {} fields.", self.len(), other.len());
18        let mut cast = false;
19        for (a, b) in self.iter_values().zip(other.iter_values()) {
20            cast |= a.matches_schema_type(b)?;
21        }
22        Ok(cast)
23    }
24
25    fn ensure_is_exact_match(&self, other: &Schema) -> PolarsResult<()> {
26        polars_ensure!(self.len() == other.len(), SchemaMismatch: "found different number of fields in schema's\n\nLeft schema: {} fields, right schema: {} fields.", self.len(), other.len());
27        let mut different_columns = Vec::new();
28        for (a, b) in self.iter_fields().zip(other.iter_fields()) {
29            if a != b {
30                different_columns.push((a, b));
31            }
32        }
33        if !different_columns.is_empty() {
34            use std::fmt::Write;
35            let mut context = String::new();
36            for (a, b) in different_columns {
37                writeln!(
38                    &mut context,
39                    "('{}': {}) != ('{}': {})",
40                    a.name(),
41                    a.dtype(),
42                    b.name(),
43                    b.dtype()
44                )
45                .unwrap();
46            }
47
48            return Err(
49                polars_err!(SchemaMismatch: "mismatching fields in schema's.\n\n{context}"),
50            );
51        }
52
53        Ok(())
54    }
55}