Skip to content

Support lossless JSON <-> JSONB column type migration #4985

Closed

Description

@developerjamiu

Problem to Solve

When a developer changes an existing serializable field from json to jsonb (or vice versa), the migration engine treats it as a destructive change; dropping and recreating the table, losing all data in it.. Both PostgreSQL and SQLite support lossless type casting, so this data loss is unnecessary.

Proposal

The migration engine should detect json ↔ jsonb as a compatible type change and generate cast-based migrations:

PostgreSQL:

ALTER TABLE my_table ALTER COLUMN data SET DATA TYPE jsonb USING data::jsonb;
-- Reverse:
ALTER TABLE my_table ALTER COLUMN data SET DATA TYPE json USING data::json;

SQLite (during table recreation):

INSERT INTO new_table (..., json_col)
SELECT ..., jsonb(json_col) FROM old_table;
-- Reverse:
INSERT INTO new_table (..., json_col)
SELECT ..., json(json_col) FROM old_table;

Use Case

A developer has an existing Serverpod project with serializable fields stored as json. They want to switch to jsonb for better query performance and GIN indexing. Currently, serverpod create-migration generates a destructive migration that drops and recreates the entire table, losing all data. The developer must either accept the data loss with --force or write manual SQL. With this feature, the migration engine would generate the correct cast-based SQL automatically.

Alternatives

  • Users manually write ALTER COLUMN TYPE SQL (error-prone, defeats the purpose of managed migrations)
  • Users run --force and accept data loss (unacceptable for production)
  • Do nothing and document it as a limitation (current state)

Additional context

This was split from PR #4960 (JSONB column support, refs #3919) per reviewer suggestion to keep scope manageable. The JSONB feature itself lands in #4960; this issue covers only the migration path for existing columns.

How experienced are you with this library?

Intermediate - Familiar with the basics or have used it in a few projects

Are you interested in working on a PR for this?

  • I want to work on this

Metadata

Metadata

Labels

enhancement

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions