Skip to content

Commit 9f9a3f0

Browse files
authored
Update database migration docs (#11877)
* Update index.mdx * Update index.mdx
1 parent 080a7da commit 9f9a3f0

File tree

1 file changed

+2
-29
lines changed
  • develop-docs/api-server/application-domains/database-migrations

1 file changed

+2
-29
lines changed

develop-docs/api-server/application-domains/database-migrations/index.mdx

+2-29
Original file line numberDiff line numberDiff line change
@@ -313,36 +313,9 @@ creating new columns they should either be:
313313

314314
### Adding Columns With a Default
315315

316-
We run Postgres 14 in production. This means that we can now safely add columns with a default without worrying about rewriting the table. We still need to be careful though.
316+
Since we run Postgres >= 14 in production we are able to add columns with a default. To do so, instead of using `default=<your_default>`, use `db_default=<your_default>`. This tells Django to set a default at the database level and manage it there, rather than managing it in application code.
317317

318-
Django's default behaviour for creating a new not null column with a default is dangerous. When adding a default, in the migrations Django will add the default to backfill all fields, then immediately remove it so that it can handle them in the app layer. This means that during a deploy, the column is sitting in production without a default until all code rolls out. This means that inserts will fail for this table until the deploy completes.
319-
320-
To work around this, you can tell your migration to leave the default in place in Postgres.
321-
322-
```python
323-
operations = [
324-
migrations.SeparateDatabaseAndState(
325-
database_operations=[
326-
migrations.RunSQL(
327-
"""
328-
ALTER TABLE "sentry_groupedmessage" ADD COLUMN "type" integer NOT NULL DEFAULT 1;
329-
""",
330-
reverse_sql="""
331-
ALTER TABLE "sentry_groupedmessage" DROP COLUMN "type";
332-
""",
333-
hints={"tables": ["sentry_groupedmessage"]},
334-
),
335-
],
336-
state_operations=[
337-
migrations.AddField(
338-
model_name="group",
339-
name="type",
340-
field=sentry.db.models.fields.bounded.BoundedPositiveIntegerField(default=1),
341-
),
342-
],
343-
)
344-
]
345-
```
318+
We can't use `default` because Django's default behaviour for creating a new not null column with a default is dangerous. When using default, in the migration Django will add the default to backfill all fields, then immediately remove it so that it can handle them in the app layer. This means that during a deploy, the column is sitting in production without a default until all code rolls out, which means that inserts will fail for this table until the deploy completes.
346319

347320
### Adding Not Null To Columns
348321

0 commit comments

Comments
 (0)