2020-11-09 06:34:17+00:00

Renaming fields in relational SQL databases is handled via straightforward migrations. In NoSQL document databases, renaming a schema attribute is more complex. Because NoSQL databases are schemaless, existing documents retain the old field name until they are explicitly modified, which can break frontend templates. Executing attribute renames on live databases requires implementing a phased data translation wrapper inside the database access layer.

By writing custom Python property descriptors in our database models, we can support reading from both the old and new attribute names during the migration phase.


1. The Dual-Reading Property Wrapper

We update our database models to support reading from *both* the old and new attribute names during the migration phase, ensuring backward compatibility:

# models.py
from google.cloud import ndb

class DeviceConfiguration(ndb.Model):
    new_attribute_name = ndb.StringProperty()
    old_attribute_name = ndb.StringProperty()
    
    def get_value(self):
        # Fallback to old attribute name if new is empty
        return self.new_attribute_name or self.old_attribute_name

2. The Cleanup Phase

Once all application instances are updated to write to the new attribute name, a background batch script rewrites all legacy records, copying the values and dropping the old property.