peewee_migrations icon indicating copy to clipboard operation
peewee_migrations copied to clipboard

Renaming fields

Open henryh9n opened this issue 4 months ago • 0 comments

Renaming an attribute on the model results in dropping the column and creating a new one with empty values.

 class Student(BaseModel):
     id = AutoField(primary_key=True)
-    name = CharField(max_length=50)
-    surname = CharField(max_length=50)
+    first_name = CharField(max_length=50)
+    last_name = CharField(max_length=50)
     email = CharField(max_length=255, unique=True)

For instance the change above generates the following migration:

# auto-generated snapshot
from peewee import *
import datetime
import peewee


snapshot = Snapshot()


@snapshot.append
class Student(peewee.Model):
    first_name = CharField(max_length=50)
    last_name = CharField(max_length=50)
    email = CharField(max_length=255, unique=True)
    class Meta:
        table_name = "student"


def forward(old_orm, new_orm):
    student = new_orm['student']
    return [
        # Apply default value '' to the field student.first_name,
        student.update({student.first_name: ''}).where(student.first_name.is_null(True)),
        # Apply default value '' to the field student.last_name,
        student.update({student.last_name: ''}).where(student.last_name.is_null(True)),
    ]


def backward(old_orm, new_orm):
    student = new_orm['student']
    return [
        # Apply default value '' to the field student.name,
        student.update({student.name: ''}).where(student.name.is_null(True)),
        # Apply default value '' to the field student.surname,
        student.update({student.surname: ''}).where(student.surname.is_null(True)),
    ]

What is supposed to be a renaming of the column, causes the column to be dropped and hence a data loss.

In this case it would make sense to detect when the new fields have the same type and suggest to rename the column instead of dropping those. Similar behavior is implemented in Alembic for SQLAlchemy.

henryh9n avatar Mar 24 '24 20:03 henryh9n