Schema evolution

When working with shelve, we have to address the problem of schema evolution. The class definitions define the schema for the persistent data. The class, however, is not absolutely static. If we change a class definition, the schema evolves. How will we fetch objects from the shelf after this change? A good design often involves some combination of the following techniques.

Changes to methods don't change the persisted object representation. We can classify these changes as minor because the shelved data is still compatible with the changed class definition. A new software release can have a new minor version number and users should be confident that it will work without problems.

Changes to attributes will change the persisted object representation. We can call these major changes, and the shelved data will no longer be compatible with the new class definition. Major changes to the representation should not made by modifying a class definition. These kinds of changes should be made by adding a new subclass and providing an updated factory function to create instances of either version of the class.

We can be flexible about supporting multiple versions, or we can use one-time conversions. To be flexible, we must rely on factory functions to create instances of objects. A flexible application will avoid creating objects directly. By using a factory function, we're assured that all parts of an application can work consistently. We might do something like this to support flexible schema changes:

def make_blog(*args, **kw): 
    version = kw.pop('_version',1) 
    if version == 1: return Blog(*args, **kw) 
    elif version == 2: return Blog2(*args, **kw) 
    else: raise ValueError(f"Unknown Version {version}") 

This kind of factory function requires a _version keyword argument to specify which Blog class definition to use. This allows us to upgrade a schema to use different classes without breaking our application. The Access layer can rely on this kind of function to instantiate correct versions of objects.

An alternative to this level of flexibility is a one-time conversion. This feature of the application will fetch all shelved objects using their old class definition, convert to the new class definition, and store them on a new shelf in the new format.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset