We are going to design a multiversion data reader that can handle:
Schema evolution (columns can be added, removed, renamed, and types can change)
Projection (reading only a subset of columns)
Defaulting (if a column is missing in the data, use a default value)
Compatibility tests (check if the data schema is compatible with the reader's expected schema)
We assume that each version of the data has a schema (a set of columns with names and types).
The reader has a target schema (what it expects). We want to read the data and produce records that match the target schema.
Steps:
We have a data schema (the actual schema of the data we are reading) and a target schema (the schema we want to output).
We need to map from the data schema to the target schema. This involves:
For each column in the target schema:
a. If the column exists in the data schema, then we can read it (but note: type might be different, so we may need conversion).
b. If the column does not exist in the data schema, then we use a default value (if provided) or throw an error.
We also allow projection: the target schema might have only a subset of the data schema columns. So we ignore extra columns in the data.
We also have to consider schema evolution in the data: the data schema might have changed over time. So the reader must be able to handle multiple versions of the data.
Compatibility tests: We might want to check if the data schema is compatible with the target schema. This could be done at initialization.
Approach:
Let's define:
DataSchema: a map from column name to data type (and maybe other metadata like whether it's nullable, etc.)
TargetSchema: a map from column name to (target type, default value, maybe required flag)
We want to create a mapping plan:
For each target column (t_name, t_type, t_default, t_required) in TargetSchema:
1. Look for a column in DataSchema with the same name? But note: column might have been renamed.
We might need a mapping from old column names to new column names? Or we assume that the column names are stable?
Alternatively, we can have a mapping strategy: by name, by position, by some ID? The problem says "schema evolution", so we assume that columns can be renamed.
However, the problem does not specify how we handle renames. Let's assume we are given a mapping from data column names to target column names? Or we can try to match by some identifier?
Alternatively, we can think of the data schema and target schema as having a set of columns that are the same "conceptually". But without additional metadata, we can only match by name.
Let's assume for now that we match by name. But note: if a column is renamed, then the old name disappears and a new column appears. So we have two separate columns.
So if the target schema expects a column that was renamed, then we have two cases:
- The old name is in the data schema, but the target expects the new name -> then we don't match.
- The new name is in the data schema, but the target expects the old name -> then we don't match.
Therefore, without a mapping of renames, we cannot automatically match renamed columns.
Since the problem says "multiversion", we might have multiple versions of the data with different schemas. We might need to know the evolution history? Or we might have to define a set of rules for each version?
Alternatively, we can have a "schema mapping" that for each version of the data, we specify how the columns map to the target.
Given the complexity, let's simplify:
We assume that the data schema and target schema are defined in a way that we can match columns by name. If a column is renamed, then we consider it as a new column and the old one as removed.
So:
Steps for mapping:
For each target column:
if the target column name exists in the data schema:
then we can use that column, but we might need to convert the type.
else:
use the default value (if provided) or error if required and no default.
But what if the data schema has a column that the target does not? We ignore it (projection).
However, what if the target column exists in the data schema but with a different type? We need to check type compatibility and possibly convert.
Let's define type compatibility:
We can have a set of rules for type conversion. For example, int to long is safe, int to string is safe, but string to int might fail.
We might want to do:
If the data type is the same as the target type, then no conversion.
If the data type is a subtype of the target type (in a type hierarchy), then we can upcast.
Otherwise, we try to convert (if there's a conversion function) or fail.
But the problem does not specify the type system. Let's assume we have a set of primitive types (int, long, float, double, string, boolean) and maybe complex types (array, struct). We'll ignore complex for now.
We can define a compatibility matrix:
For example:
int -> long, float, double, string (by formatting)
long -> int (if within range), float, double, string
float -> double, string
double -> string
string -> int, long, float, double (by parsing), boolean (by parsing "true"/"false")
boolean -> string
But note: we might lose precision or get errors. So we might want to have a flag that says "strict" or "lossy".
Alternatively, we can have a conversion function for each source type to target type, and if not defined then it's an error.
Given the complexity, let's assume we have a set of allowed conversions and we do them automatically. But we must be cautious.
Alternatively, we can have a configuration for the reader that specifies:
For each target column, the source column name (if different) and the conversion function (if any).
But that would be too much configuration.
Let's stick to:
Match by column name.
If the data type is the same, use it.
If the data type is different, try to convert using a set of built-in conversions (safe ones). If no safe conversion, then error.
We define safe conversions as:
int -> long, float, double, string (without loss of information? Actually, int to string is safe, but int to float might lose precision for very large ints? Let's assume we use 64-bit doubles for float and double, then int to double is safe for 32-bit ints? Actually, double can exactly represent all 32-bit ints? Yes, because double has 52 bits of mantissa, so 32-bit ints are safe.)
But note: the data might be in a format that doesn't support the full range? We assume the data type in the data schema is the actual type of the data.
Alternatively, we can define:
Numeric types: we can convert from a smaller numeric type to a larger one (int to long, int to float, int to double, long to double, float to double) without loss? Not always, but for the sake of simplicity we allow.
String to numeric: might fail, so we can try and if fails, use default? Or error?
We need to decide on the behavior.
Given that this is a reader, we might want to be permissive or strict.
Let's assume we are permissive:
For each target column:
if the column exists in the data:
if the data type is the same as target: read as is.
else if there is a conversion from data type to target type: apply conversion.
else: error (unless there's a default, then use default? But note: we have the data, but it's the wrong type. Maybe we should treat as missing? Or error?)
if the column does not exist in the data:
if there's a default: use default.
else if the target column is required: error.
else: null? But we are building a record for the target schema, so we must have a value. So if required and no default, error.
But note: the target schema might have a required flag? Let's assume every column in the target schema is required unless a default is provided.
So:
Steps for reading a record:
For each target column (t_name, t_type, t_default, t_required):
if t_name in data_schema:
data_value = data_record[t_name]
if type(data_value) matches t_type (or can be converted to t_type safely):
record[t_name] = convert(data_value, t_type) // if conversion needed
else:
if t_default is not None:
record[t_name] = t_default
else:
raise Error("Type mismatch for column {t_name} and no default")
else:
if t_default is not None:
record[t_name] = t_default
else:
raise Error(f"Missing column {t_name} and no default")
However, note that the data might have extra columns that we ignore.
But what if the data schema has a column that is not in the target? We just ignore.
Compatibility test:
We can run the above logic on a sample record? Or we can check the schemas:
For each target column:
if the column is in the data schema:
if the data type is not compatible with the target type (and no conversion) -> not compatible.
else:
if no default and required -> not compatible.
But note: the data schema might have multiple versions? We are given one data schema at a time (for a particular version of the data). So we test against that version.
However, the reader might be used for multiple versions. So we might want to test against all known versions? Or we might have a compatibility matrix?
Alternatively, we can have a list of data schemas (for different versions) and we check that for every version, the mapping is possible.
But the problem says "multiversion data reader", so we might have to handle multiple versions. We can design the reader to accept a data schema (the one of the current data) and then use the above mapping.
def set_data_schema(self, data_schema):
self.data_schema = data_schema
self._build_mapping()
def _build_mapping(self):
# Build a mapping from target columns to either:
# - (source_column, conversion_function) if the column exists and needs conversion or not.
# - (None, default_value) if the column is missing and has a default.
# - (None, None) if the column is missing and required -> error at build time? Or at read time?
# We can build the mapping and if any required column without default and not in data_schema, then we can error at set_data_schema.
self.mapping = {}
for t_col, (t_type, t_default, t_required) in self.target_schema.items():
if t_col in self.data_schema:
d_type = self.data_schema[t_col]
if d_type == t_type:
conv = None
elif (d_type, t_type) in self.allowed_conversions:
conv = self.allowed_conversions[(d_type, t_type)]
else:
# No conversion and types don't match -> error
raise ValueError(f"Column {t_col} has incompatible type {d_type} for target type {t_type}. No conversion defined.")
self.mapping[t_col] = (t_col, conv)
else:
if t_default is not None:
self.mapping[t_col] = (None, lambda: t_default) # We'll create a function that returns the default
else:
if t_required:
raise ValueError(f"Required column {t_col} is missing in data schema and no default provided.")
else:
# If not required and no default, then we can set to None? But the target type might not be nullable.
# We assume that if not required, then we can use None (or the default of the type?).
# But the problem says "defaulting", so if no default and not required, we might set to a null value?
# Let's assume that the target schema has a default for every column that is not required? Or we can set to None.
# We'll set to None and hope the target type is nullable.
self.mapping[t_col] = (None, lambda: None)
def read_record(self, data_record):
# data_record is a dict from data column name to value.
record = {}
for t_col, (source_col, conv) in self.mapping.items():
if source_col is not None:
value = data_record[source_col]
if conv is not None:
value = conv(value)
record[t_col] = value
else:
# source_col is None, so we use the default (or None)
record[t_col] = conv() # conv is a function that returns the default or None
return record
But note: the above mapping is built for one data_schema. If the data schema changes (for a new version), we call set_data_schema again and rebuild the mapping.
However, what if the data schema changes in a way that breaks the mapping? Then set_data_schema will fail. That's the compatibility test.
We can also have a method to check compatibility without building the mapping? Or we build the mapping and if it fails, then it's incompatible.
But note: we might want to allow the reader to be built with a target schema and then used with multiple data schemas (versions). So we can have:
reader = SchemaReader(target_schema)
for each version:
try:
reader.set_data_schema(data_schema_of_version)
# then read records for that version
except ValueError as e:
# incompatible version
Alternatively, we can have a method that returns the mapping for a given data_schema without setting it, and then we can check.
But the above design requires that we set the data schema for the current version we are reading.
We can also have:
class MultiVersionSchemaReader:
def init(self, target_schema, allowed_conversions=None):
self.target_schema = target_schema
self.allowed_conversions = allowed_conversions or default_conversions
self.current_data_schema = None
self.current_mapping = None
code
def set_version(self, data_schema):
# Build mapping for this version and set as current.
# If fails, then this version is not supported.
mapping = {}
for t_col, (t_type, t_default, t_required) in self.target_schema.items():
if t_col in data_schema:
d_type = data_schema[t_col]
if d_type == t_type:
conv = None
elif (d_type, t_type) in self.allowed_conversions:
conv = self.allowed_conversions[(d_type, t_type)]
else:
raise ValueError(f"Version incompatible: column {t_col} has type {d_type} but target type {t_type} and no conversion.")
mapping[t_col] = (t_col, conv)
else:
if t_default is not None:
mapping[t_col] = (None, lambda: t_default)
else:
if t_required:
raise ValueError(f"Version incompatible: required column {t_col} missing and no default.")
else:
mapping[t_col] = (None, lambda: None)
self.current_data_schema = data_schema
self.current_mapping = mapping
def read_record(self, data_record):
if self.current_mapping is None:
raise RuntimeError("No version set. Call set_version first.")
record = {}
for t_col, (source_col, conv) in self.current_mapping.items():
if source_col is not None:
value = data_record[source_col]
if conv is not None:
value = conv(value)
record[t_col] = value
else:
record[t_col] = conv()
return record
This way, we can switch between versions by calling set_version.
But note: the data_record must match the current_data_schema? We assume that the data_record we read for a particular version has the columns as per that version's schema.
Also, note that the data_record might have extra columns (from the data schema) that are not in the target. We ignore them because we only look at the mapping.
However, what if the data_record does not have a column that is in the current_data_schema? That would be an error because we expect the data to conform to the current_data_schema.
We can add a check in read_record that the data_record has at least the columns that are in the current_data_schema? But note: we are only using the columns that are in the mapping (which are the target columns). So if the data_record is missing a column that is in the current_data_schema but not in the target, we don't care. But if it's missing a column that is in the mapping (and source_col is not None) then we get a KeyError.
So we must ensure that the data_record has all the columns that are in the current_data_schema and that are also in the target (with the same name). But note: the mapping uses the data_schema column names. So if the data_record is missing a column that is in the current_data_schema, then we get an error when we try to access it.
Therefore, we assume that the data_record we read for a given version has all the columns of the current_data_schema.
Alternatively, we can relax and allow the data_record to have only the columns that are in the mapping? But then we are not using the full data_schema? We built the mapping based on the data_schema, so if the data_record has fewer columns than the data_schema, then we might have a problem.
So let's assume that the data_record is guaranteed to have at least the columns of the data_schema? Actually, the data_schema is the schema of the data, so the data_record should conform to it.
We can do:
In set_version, we record the set of columns that are in the data_schema and are used in the mapping (i.e., the ones that are in the target). But note: the mapping might use a column that is in the data_schema but not in the target? No, because we only map target columns. So the mapping uses only columns that are in both the target and the data_schema (by name) and also the defaults.
So in read_record, we expect the data_record to have the columns that are in the mapping with source_col not None.
We can check:
code
for t_col, (source_col, conv) in self.current_mapping.items():
if source_col is not None and source_col not in data_record:
raise ValueError(f"Data record missing column {source_col} which is required for target column {t_col}")
But wait: the data_record should have all columns of the data_schema. And the data_schema includes the source_col? Yes, because we built the mapping from the data_schema.
So if the data_record is built from the data_schema, then it should have source_col.
Therefore, we assume that the data_record is a dictionary that has all the keys of the current_data_schema.
Let's code accordingly.
However, what about the case where the data_schema has a column that is not in the target? Then we don't care.
So the data_record must have at least the columns that are in the current_data_schema? Actually, the data_record might be a row from a file that has all the columns of that version. So we assume it has all.
Now, what about the conversion functions?
We need to define a set of allowed conversions. Let's define a default set:
But note: the above might fail for some conversions (e.g., string to int if the string is not numeric). We can wrap in try-except and then use default? But the mapping is built at set_version, so we don't know the actual value.
We have two options:
At set_version, we only check type names and assume the conversion will work. Then at read_record, if the conversion fails, we use the default? Or error?
At set_version, we don't check the conversion, we just record the conversion function. Then at read_record, we try and if fails, then we use the default? But the target column might not have a default.
The problem says "defaulting", so if the column is missing we use default. But if the column exists but conversion fails, should we use default? That might be a good idea.
Let's change the mapping:
For a column that exists in data_schema but with a conversion, we store:
code
(source_col, conv, t_default)
Then in read_record:
code
if source_col in data_record:
value = data_record[source_col]
try:
if conv:
value = conv(value)
except:
if t_default is not None:
value = t_default
else:
raise
else:
# This should not happen because we built the mapping assuming the data_record has the source_col? But what if the data_record is missing a column that is in the data_schema? Then we treat as missing.
if t_default is not None:
value = t_default
else:
raise
But wait, we built the mapping for a given data_schema, and we assume the data_record has all the columns of the data_schema. So the else branch should not happen.
However, if the data_record has the column but the value is None? Then we might want to use default? But that's a separate issue: null handling.
We are not handling nulls. Let's assume that the data might have nulls. Then:
code
if the value is None and the target column is required and no default? Then we might want to use default? Or error?
We can extend:
code
if source_col in data_record:
value = data_record[source_col]
if value is None:
if t_default is not None:
value = t_default
else:
# target column is required? We already checked at set_version that if no default and required, then we error if column missing. But here the column is present but null.
# We can treat null as missing? Or we can allow null if the target type is nullable? We don't have nullable info.
# Let's assume that if the target column has a default, then we use it for null. Otherwise, we keep null? But then the record might have null for a required column.
# We can check at set_version: if the target column is required and there's no default, then we must have a non-null value. But we don't know the data values at set_version.
# So we cannot check that at set_version. We have to check at read_record.
# So we change: at set_version, we don't check for requiredness beyond the presence of the column. At read_record, if the value is None and the target column is required and no default, then error.
# But note: the target column might be of a type that doesn't allow null? We don't have that info.
# Let's simplify: we assume that the target schema has a default for every column that is not required? Actually, the required flag we are using is at the schema level: if the column is required and no default, then we must have a non-null value.
# So we can store the required flag in the mapping.
# Alternatively, we can store the entire target column info.
Given the complexity, let's stick to:
At set_version, we build a mapping that for each target column we have:
code
(source_col, conv, default_value, required)
Then at read_record:
code
if source_col is not None:
if source_col in data_record:
value = data_record[source_col]
if value is None:
if default_value is not None:
value = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has null value and no default.")
else:
value = None # or default_value? But default_value is None? We set default_value to None if not provided.
else:
try:
if conv:
value = conv(value)
except Exception as e:
if default_value is not None:
value = default_value
else:
raise ValueError(f"Conversion failed for column {t_col}: {e}")
else:
# This should not happen because we built the mapping for the data_schema that includes source_col.
if default_value is not None:
value = default_value
else:
raise ValueError(f"Data record missing column {source_col} for target column {t_col}")
else:
value = default_value # which might be None
record[t_col] = value
But note: the required flag: if the target column is required and we have a default, then we can use the default when the value is null or conversion fails. So the required flag only matters when there's no default and the value is missing or null.
So we can change:
code
if source_col is not None and source_col in data_record:
value = data_record[source_col]
if value is None:
if default_value is not None:
value = default_value
else:
if required:
raise ...
else:
value = None
else:
try:
if conv:
value = conv(value)
except:
if default_value is not None:
value = default_value
else:
raise
else:
if default_value is not None:
value = default_value
else:
if required:
raise ...
else:
value = None
This is getting complex.
Alternatively, we can separate the concerns:
Step 1: Extract the value from the data_record for the source column (if exists) or use None if missing.
Step 2: If the value is None, then use default if available, else if required then error, else None.
Step 3: If the value is not None, then try to convert. If conversion fails, then use default if available, else if required then error, else None? But note: the value is not None, but we cannot convert it. We treat it as an invalid value and then use default or error.
But note: the target column might be required and we have a value that is not None but of the wrong type. We try to convert and if fails, then we use default? But if there's no default, then we error.
So:
code
value = None
if source_col is not None and source_col in data_record:
value = data_record[source_col]
if value is None:
if default_value is not None:
value = default_value
else:
if required:
raise ...
else:
value = None
else:
try:
if conv:
value = conv(value)
except:
if default_value is not None:
value = default_value
else:
if required:
raise ...
else:
value = None # or keep the original? But it's of wrong type. We might want to set to None? Or error?
But note: if the value is not None and we fail to convert, and we don't have a default and the column is not required, then we set to None? That might be acceptable.
However, the target schema might have a type that is not nullable? We don't have that information. So we assume that if the column is not required, then we can set to None.
So let's adjust:
We store for each target column:
code
source_col: the column in the data (or None if missing)
conv: conversion function or None
default_value: the default value (or a sentinel for no default)
required: boolean
Then:
code
if source_col is not None and source_col in data_record:
value = data_record[source_col]
else:
value = None
if value is None:
if default_value is not None:
record[t_col] = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has no value and no default.")
else:
record[t_col] = None
else:
try:
if conv:
value = conv(value)
record[t_col] = value
except Exception as e:
if default_value is not None:
record[t_col] = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has incompatible value: {e}")
else:
record[t_col] = None
This seems reasonable.
Now, what about the case where the data_record has the column but the value is None? We treat it as missing.
But note: the data might have nulls. We are treating null as missing. That might be what we want? Or we might want to preserve nulls? But the target schema might not allow nulls.
Since we don't have nullable information in the target schema, we assume that if the column is required, then we cannot have null. So we treat null as missing and then use default or error.
If the column is not required, then we can set to None.
So this design.
Now, let's code accordingly.
We'll define:
class MultiVersionSchemaReader:
def init(self, target_schema, allowed_conversions=None):
"""
target_schema: dict of column_name -> (type, default, required)
type: we'll use strings for simplicity, but could be actual type objects.
default: the default value (can be None, meaning no default)
required: boolean
allowed_conversions: dict of (source_type, target_type) -> conversion function
"""
self.target_schema = target_schema
self.allowed_conversions = allowed_conversions or self.default_conversions()
self.current_data_schema = None
self.current_mapping = None
code
This is a basic design.
However, note: the data_record might have extra columns that are not in the current_data_schema? We don't care because we only look at the columns in the mapping.
But the mapping is built from the current_data_schema, so we only expect the columns that are in the current_data_schema (and in the target). So if the data_record has extra columns, we ignore.
Also, note: the current_data_schema might have columns that are not in the target? We ignore them in the mapping.
So this should work.
But what about the case where the data_schema has a column that is in the target but with a different name? We don't handle that. We only match by exact name.
To handle renames, we would need a mapping from data column names to target column names. We can extend the set_version to take an optional mapping:
for t_col, (t_type, t_default, t_required) in self.target_schema.items():
if column_mapping and t_col in column_mapping:
data_col = column_mapping[t_col]
else:
data_col = t_col
if data_col in data_schema:
... same as before but using data_col as the source column.
This way, we can handle renames.
We can also have a reverse mapping? But we only need to map target to data.
So let's add:
code
def set_version(self, data_schema, column_mapping=None):
mapping = {}
for t_col, (t_type, t_default, t_required) in self.target_schema.items():
data_col = column_mapping.get(t_col, t_col) if column_mapping else t_col
if data_col in data_schema:
d_type = data_schema[data_col]
... then use data_col as source_col.
Then in read_record, we use data_col to look up in data_record.
This allows us to map a renamed column in the data to the target column.
Then we will map the data column 'old_name' to the target column 'new_name'.
So we can handle renames.
Let's update the code accordingly.
Also, note: the column_mapping might map a target column to a data column that is not in the data_schema? Then we treat as missing.
So we adjust:
code
if data_col in data_schema:
...
else:
... missing
Now, what about the case where the data_schema has a column that is not in the target? We ignore.
And if the data_record has a column that is not in the data_schema? That would be an error because the data_record should conform to the data_schema. But we don't check that in read_record. We only check the columns that are in the mapping.
So if the data_record has a column that is in the data_schema but not in the target, we ignore.
But if the data_record is missing a column that is in the data_schema and that column is used in the mapping (i.e., it's a target column) then we get a KeyError? No, because we check if source_col (which is data_col) is in data_record. If not, we treat as missing and use default or error.
But wait: we built the mapping from the data_schema, so if data_col is in data_schema, then we expect the data_record to have that column? Not necessarily: the data_record might not have that column if the data is sparse? But typically, each record should have all the columns of the schema.
We can relax: if the data_record does not have the column, we treat as missing.
So we don't require that the data_record has all the columns of the data_schema. We only use the ones that are in the mapping and that are present in the data_record.
But then, what if the data_schema says a column is present, but in some records it's missing? We treat those records as having a missing value for that column.
That is acceptable.
So we don't need to enforce that the data_record has all the columns of the data_schema.
Therefore, the design is:
We have a target schema with required columns and defaults.
For a given data version (data_schema and optional column_mapping), we build a mapping from target columns to:
Then for each record, we look up the source column in the data_record. If present and not null, we try to convert. If conversion fails, we use default if available, else error if required, else None.
If the source column is missing or null, we use default if available, else error if required, else None.
This handles:
Schema evolution: by changing the data_schema and column_mapping per version.
Projection: we only read the target columns.
Defaulting: using default values when data is missing or invalid.
Compatibility: by building the mapping for a version, we check if the version is compatible (if building fails, then it's not).
We can also have a method to check compatibility without reading:
def build_mapping(self, data_schema, column_mapping=None):
... returns the mapping, but doesn't set it.
def set_version(self, data_schema, column_mapping=None):
self.current_mapping = self.build_mapping(data_schema, column_mapping)
self.current_data_schema = data_schema
Then we can use build_mapping to check compatibility.
Let's do that.
Final design:
class MultiVersionSchemaReader:
def init(self, target_schema, allowed_conversions=None):
self.target_schema = target_schema
self.allowed_conversions = allowed_conversions or self.default_conversions()
code
@staticmethod
def default_conversions():
... as above ...
def build_mapping(self, data_schema, column_mapping=None):
mapping = {}
for t_col, (t_type, t_default, t_required) in self.target_schema.items():
data_col = column_mapping.get(t_col, t_col) if column_mapping else t_col
if data_col in data_schema:
d_type = data_schema[data_col]
if d_type == t_type:
conv = None
elif (d_type, t_type) in self.allowed_conversions:
conv = self.allowed_conversions[(d_type, t_type)]
else:
raise ValueError(f"Column {t_col} (data column: {data_col}) has type {d_type} in data, but target type {t_type} and no conversion defined.")
mapping[t_col] = (data_col, conv, t_default, t_required)
else:
mapping[t_col] = (None, None, t_default, t_required)
return mapping
def set_version(self, data_schema, column_mapping=None):
self.current_mapping = self.build_mapping(data_schema, column_mapping)
self.current_data_schema = data_schema
def read_record(self, data_record):
if self.current_mapping is None:
raise RuntimeError("No data version set. Call set_version first.")
record = {}
for t_col, (data_col, conv, default_value, required) in self.current_mapping.items():
value = None
if data_col is not None and data_col in data_record:
value = data_record[data_col]
if value is None:
if default_value is not None:
record[t_col] = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has no value and no default.")
else:
record[t_col] = None
else:
try:
if conv:
value = conv(value)
record[t_col] = value
except Exception as e:
if default_value is not None:
record[t_col] = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has incompatible value: {e}")
else:
record[t_col] = None
return record
Version 1 data schema:
{'id': 'int', 'name': 'str', 'age': 'int'}
Version 2 data schema (age renamed to years, and age removed):
{'id': 'int', 'name': 'str', 'years': 'int'}
For version 1, we don't need column_mapping. The mapping will be:
id: ('id', None, None, True)
name: ('name', None, 'unknown', False)
age: ('age', None, 0, True)
For version 2, we need column_mapping: {'age': 'years'}.
Then for age in target, we look for 'years' in data_schema.
So mapping for age: ('years', None, 0, True)
Now, what if version 2 has age as string?
data_schema: {'id': 'int', 'name': 'str', 'years': 'str'}
Then for age (target type int), we have data type 'str'. We have a conversion from 'str' to 'int'? Yes, in our default conversions.
So mapping for age: ('years', , 0, True)
What if version 2 has age as string but the conversion fails (e.g., 'abc')? Then we use default 0.
What if version 2 does not have age at all? Then we use default 0.
What if version 2 has age as string and we don't have a conversion? Then set_version will fail.
This seems to work.
We can extend the allowed_conversions to include more types and conversions.
Also, note: the conversion functions might be specific to the data format (e.g., parsing a date string). We can allow the user to pass in allowed_conversions.
This design is flexible.
Let me write the code accordingly.
However, note: the target_schema's type and the data_schema's type are strings. We might want to use actual type objects? But for simplicity, we use strings.
Also, the default value must be of the target type? Not necessarily: we are going to assign it directly. So the default value should be of the target type.
For example, for target type 'int', the default should be an int.
We don't check that at build time, but at read time we assign it. So it's the user's responsibility.
We can also check at build time that the default value is of the target type? But the default might be a string that we want to use as a string, but the target is int? That would be an error.
We can do:
code
if default_value is not None and not isinstance(default_value, self.type_from_string(t_type)):
raise ValueError(f"Default value for {t_col} is not of type {t_type}")
But we don't have a mapping from string to type. We can use:
But note: the user might define their own types. So we leave it to the user to provide correct default values.
Alternatively, we can store the default value as is and hope it's the right type. If not, then when we assign, it might cause an error later? But we are assigning to the record, which is expected to have the target type.
So we can do:
code
record[t_col] = default_value # and if default_value is not of the target type, then the record is invalid.
So we might want to check at build time.
Let's add a type map for the target types? But the target types are given as strings. We can have a parameter for the reader that maps type strings to actual types? Or we can use a function to convert the default value to the target type? But the default value is already in the target type? Not necessarily.
We can do:
code
if default_value is not None:
# Try to convert the default value to the target type? But the default value is supposed to be of the target type.
# We can check by trying to convert to the target type? But the target type might be a string and the default might be an int? Then we can convert int to string? That's safe.
# But the user might have provided a default of the wrong type and expects it to be converted? That's not the intended use.
So let's not convert the default value. We assume the user provided a default of the correct type.
We can add a check:
code
if default_value is not None and type(default_value).__name__ != t_type:
# But note: t_type is a string, and the type of default_value might be a class. We can use a mapping.
Given the complexity, we skip.
Now, what about the conversion functions? They take a value from the data (which is of the data type) and return a value of the target type.
We assume that the conversion functions are correct.
This design should work.
Let's code accordingly.
We'll also add a method to get the current mapping for debugging.
We'll also consider that the data_record might have None for a column that is present? We treat None as missing.
But what if the data has a null and we want to preserve null? Then we should not treat null as missing. But then the target column might be required and we have a null? That would be an error.
So we treat null as missing. If the target column is required and we get null, we use default or error.
If the target column is not required and we get null, we set to None (which might be converted to a default? No, because we only use default when the value is None? Wait:
code
if value is None:
if default_value is not None: use default
else:
if required: error
else: set to None
So if the value is None and the column is not required and no default, we set to None.
That seems correct.
Now, what if the data_record has the column but the value is an empty string? That is not None. So we try to convert. If the conversion fails (e.g., empty string to int), then we use default or error.
So we treat empty string as a value, not as missing.
That is also correct.
We are done.
Let me write the code with some comments.
Note: This is a simplified version. In a real system, we might have more complex types (arrays, structs) and more complex conversion logic.
We assume the data_record is a dictionary.
We also assume that the data_schema is a dictionary of column name to type string.
We also assume that the target_schema is a dictionary of column name to a tuple (type_string, default, required).
We'll code accordingly.
Let's code.
Excellent question. You're describing a core component of modern data systems (like Apache Avro, Protobuf, Parquet, Delta Lake, Iceberg) that must handle schema evolution while maintaining read compatibility. Here's a comprehensive breakdown:
1. Core Concepts
Concept
What it is
Why it matters
Schema Evolution
Rules for changing schemas over time (add/remove/rename fields, change types).
Allows data pipelines to evolve without breaking old consumers.
Projection
Reading only a subset of columns from a dataset.
Reduces I/O, memory, and network costs; enables backward compatibility.
Default Values
Fallback values when a field is missing in the data.
Ensures records still produce valid output after schema changes.
Compatibility Tests
Validation that a consumer's expected schema can read producer's data.
Reader must provide default if field not in old data.
Remove Field
Drop ssn column
✅ Always safe
Reader's extra fields are ignored (projection).
Rename Field
user_id → uid
❌ Breaking
Unless aliased in reader's schema mapping.
Change Type
int → long
✅ Safe (widening)
int → string usually safe; string → int risky.
Change Type
string → int
⚠️ Conditional
Requires conversion; fails on non-numeric strings.
Make Optional
required → optional
✅ Safe
Missing字段可使用默认值。
Make Required
optional → required
❌ Breaking
Old data may miss field.
Compatibility Levels
Backward Compatible: New consumer can read old data.
Forward Compatible: Old consumer can read new data.
Full Compatible: Both directions.
3. Implementation Patterns
A. Schema Resolution Strategies
python
# Pseudocode: resolve field for a record
def resolve_field(record, target_field, source_schema, target_schema):
# 1. Try direct name match
if target_field in record:
return convert_type(record[target_field], target_schema[target_field].type)
# 2. Try field alias (for renames)
if target_field in aliases:
source_name = aliases[target_field]
if source_name in record:
return convert_type(record[source_name], ...)
# 3. Use default if available
if target_field in target_schema and target_schema[target_field].has_default:
return target_schema[target_field].default
# 4. Field missing → error or null (based on required flag)
if target_schema[target_field].required:
raise MissingFieldError(target_field)
return None
B. Type Coercion Rules
yaml
# Safe conversions (lossless or value-preserving):
int → long, float, double, string
long → float, double, string
float → double, string
string → int/long/float (if numeric), bool ("true"/"false")
bool → string
# Unsafe (may fail/lose data):
string → int (non-numeric)
float → int (truncation)
any → enum (value not in set)
C. Projection Pushdown
At storage layer: Parquet/ORC allow column pruning.
At compute layer: Spark/Trino push projections to scan.
At reader layer: Only deserialize needed columns (Avro/Protobuf support this).
4. Design of a Multiversion Data Reader
python
class MultiversionReader:
def __init__(self, target_schema: Schema,
evolution_rules: EvolutionConfig = None):
self.target_schema = target_schema # What application expects
self.evolution_rules = evolution_rules or default_rules()
self.schema_registry = SchemaRegistry() # Stores historical schemas
def read(self, data_bytes: bytes, data_schema_id: int) -> Record:
# 1. Fetch data's schema from registry
data_schema = self.schema_registry.get_schema(data_schema_id)
# 2. Build resolver (cached per schema pair)
resolver = self._build_resolver(data_schema, self.target_schema)
# 3. Decode bytes using data_schema (Avro/Protobuf decoder)
raw_record = decode(data_bytes, data_schema)
# 4. Resolve to target schema
return resolver.resolve(raw_record)
def _build_resolver(self, data_schema: Schema, target_schema: Schema) -> FieldResolver:
resolver = FieldResolver()
for target_field in target_schema.fields:
# Find best matching source field
source_field = self._find_source_field(target_field, data_schema)
resolver.add_mapping(
target_field=target_field,
source_field=source_field,
conversion=self._get_conversion(
source_field.type if source_field else None,
target_field.type
),
default=target_field.default
)
return resolver
5. Compatibility Testing Framework
python
def test_compatibility(writer_schema: Schema, reader_schema: Schema) -> CompatibilityReport:
report = CompatibilityReport()
for field in reader_schema.fields:
# 1. Does writer have this field (or alias)?
source_field = find_field(writer_schema, field.name, field.aliases)
if not source_field:
if field.required and not field.has_default:
report.add_error(f"Required field {field.name} missing in writer schema")
continue
# 2. Type compatibility
if not is_type_compatible(source_field.type, field.type):
report.add_error(f"Type mismatch: {source_field.type} → {field.type}")
# 3. Default value compatibility (if field optional in writer)
if source_field.optional and not field.has_default:
report.add_warning(f"Field {field.name} optional in writer but no default in reader")
# 4. Check for writer-only fields (safe, ignored by reader)
return report
# CI/CD integration:
# - Test all historical writer schemas against current reader schema
# - Test current writer schema against all historical reader schemas
6. Real-World Examples
Apache Avro
json
// Reader schema can have:
// - Extra fields (ignored)
// - Missing fields (use defaults)
// - Different field order
{
"type": "record",
"name": "User",
"fields": [
{"name": "id", "type": "long"},
{"name": "name", "type": ["null", "string"], "default": null},
{"name": "email", "type": ["null", "string"], "default": ""}
]
}
Protobuf
protobuf
message User {
int64 id = 1;
string name = 2; // New field (forward-compatible)
optional string email = 3 [default = ""]; // With default
// Removed field: old data still has it, new reader ignores.
}
Delta Lake / Iceberg
sql
-- ALTER TABLE ADD COLUMN (safe, backward-compatible)
ALTER TABLE users ADD COLUMN email STRING;
-- ALTER TABLE DROP COLUMN (forward-compatible, but old readers break if they need it)
ALTER TABLE users DROP COLUMN ssn;
-- ALTER TABLE RENAME COLUMN (breaking unless using view)
ALTER TABLE users RENAME COLUMN user_id TO uid; -- ❌ breaks old readers
7. Best Practices
Always Add, Never Remove or Rename
Add new fields with defaults (null or sensible defaults).
Never reuse field IDs/names after removal.
Use Explicit Defaults
python
# Good
age: int = 0
status: string = "UNKNOWN"
# Bad (implicit null may break required fields)
email: string # If later made required, old data fails.
Version Schemas Explicitly
json
// Avro schema with version
{"doc": "User v2", "version": 2, ...}
Test Both Directions
Backward: New reader → Old data
Forward: Old reader → New data
Use Field Aliases for Renames (if supported)
protobuf
message User {
int64 uid = 1 [json_name = "user_id"]; // Alias for compatibility
}
Log Schema Mismatches
Monitor compatibility failures in production.
8. Common Pitfalls
Pitfall
Consequence
Solution
Changing field IDs (Protobuf/Avro)
❌ Complete breakage
Never change field IDs/positions.
Making optional → required
❌ Old data missing field
Only make required if all historical data backfilled.
Removing used field
❌ Old readers crash
Deprecate first, then remove after grace period.
No defaults on new required fields
❌ New data readable, old not
Add with default, then make required later (if safe).
Resolve fields across schema versions using name/alias matching.
Apply safe type conversions with clear failure modes.
Inject defaults for missing fields (configurable per field).
Validate compatibility at deployment time, not runtime.
Support projection to minimize data transfer.
The key is explicitness: every field's required/optional status, defaults, and conversion rules must be declared. This turns implicit assumptions into testable contracts.
Final advice: Start with add-only schema changes (most compatible), use deprecation cycles for removals, and never rename without aliases. Automate compatibility testing in CI/CD for every schema change.
@staticmethod
def default_conversions():
# Define a set of safe conversions.
# We'll use Python types for simplicity, but in reality we might have our own type system.
# Let's assume the types are represented by strings: 'int', 'long', 'float', 'double', 'str', 'bool'
# But note: in Python, int and long are the same? In Python3, int is arbitrary precision. So we might not have long.
# Let's use: 'int', 'float', 'str', 'bool'. And we can have 'double' as an alias for float? Or we can have a separate type for double?
# We'll define:
conversions = {
('int', 'int'): lambda x: x,
('int', 'float'): lambda x: float(x),
('int', 'str'): lambda x: str(x),
('int', 'bool'): lambda x: bool(x),
('float', 'int'): lambda x: int(x),
('float', 'float'): lambda x: x,
('float', 'str'): lambda x: str(x),
('float', 'bool'): lambda x: bool(x),
('str', 'int'): lambda x: int(x),
('str', 'float'): lambda x: float(x),
('str', 'str'): lambda x: x,
('str', 'bool'): lambda x: x.lower() in ('true', '1', 'yes'),
('bool', 'int'): lambda x: int(x),
('bool', 'float'): lambda x: float(x),
('bool', 'str'): lambda x: str(x).lower(),
('bool', 'bool'): lambda x: x,
}
return conversions
def set_version(self, data_schema):
"""
data_schema: dict of column_name -> type (string)
"""
mapping = {}
for t_col, (t_type, t_default, t_required) in self.target_schema.items():
if t_col in data_schema:
d_type = data_schema[t_col]
if d_type == t_type:
conv = None
elif (d_type, t_type) in self.allowed_conversions:
conv = self.allowed_conversions[(d_type, t_type)]
else:
raise ValueError(f"Column {t_col} has type {d_type} in data, but target type {t_type} and no conversion defined.")
mapping[t_col] = (t_col, conv, t_default, t_required)
else:
# Column missing in data
mapping[t_col] = (None, None, t_default, t_required)
self.current_data_schema = data_schema
self.current_mapping = mapping
def read_record(self, data_record):
if self.current_mapping is None:
raise RuntimeError("No data version set. Call set_version first.")
record = {}
for t_col, (source_col, conv, default_value, required) in self.current_mapping.items():
# Get the value from data_record if source_col exists and data_record has it.
value = None
if source_col is not None and source_col in data_record:
value = data_record[source_col]
if value is None:
if default_value is not None:
record[t_col] = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has no value and no default.")
else:
record[t_col] = None
else:
try:
if conv:
value = conv(value)
record[t_col] = value
except Exception as e:
if default_value is not None:
record[t_col] = default_value
else:
if required:
raise ValueError(f"Required column {t_col} has incompatible value: {e}")
else:
record[t_col] = None
return record