schultek / stormberry

Access your postgres database effortlessly from dart code.
https://pub.dev/packages/stormberry
MIT License
66 stars 16 forks source link

Default value for not null fields in migration? #35

Open ynnob opened 1 year ago

ynnob commented 1 year ago

Hey! Really love this package.

I have a question to the following scenario:

The user table needs to be extended with a new column. This new column must not be null. In my example we add a bool field like that:

@Model()
abstract class User {
  // EXISTING SCHEMA
  @PrimaryKey()
  String get id;
  String get email;
  String get passwordHash;
  int get registerDate;

  // PENDING MIGRATION
  bool get emailConfirmed;
}

The build will succeed but the migration will fail when applying the changes:

Select a database to update: 
Database: connecting to  at 127.0.0.1...
Database: connected
Getting schema changes of 
=========================
++ COLUMN users.email_confirmed
=========================
Do you want to apply these changes? (yes/no): yes
Database schema changed, applying updates now:
---
ALTER TABLE "users"
ADD COLUMN "email_confirmed" bool NOT NULL
Transaction finished with error: PostgreSQLSeverity.unknown 23502: Spalte »email_confirmed« von Relation »users« enthält NULL-Werte Table: users Column: email_confirmed 
========================
---
ALL CHANGES REVERTED, EXITING

This is to be expected because stormberry would need to update every existing entry with a default value. Therefore my question now, would it be possible to define default values for fields so that they:

  1. are optional in the constructor
  2. the migration could automaticly update the database if we add a new not null collumn to a table with existing entries.

Hope i got this right :)

Cheers

schultek commented 1 year ago

Thanks, thats a cool idea.