pinchbv / floor

The typesafe, reactive, and lightweight SQLite abstraction for your Flutter applications
https://pinchbv.github.io/floor/
Apache License 2.0
951 stars 190 forks source link

Migration use for create new DatabaseView #767

Closed sancho0410 closed 1 year ago

sancho0410 commented 1 year ago

Hi,

I actually have a database on version 1. I've just add a new DatabaseView, visible on .g.dart file one the onCreate method: await database.execute( 'CREATE VIEW IF NOT EXISTS 'CepParcelle' AS SELECT c.*, p.code as parcelle_code From cep c INNER JOIN parcelle p ON p.id = c.parcelle_id'); But i can't see the new view on my database schema, even if i delete install app on emulator and reinstall it.

Need i use 'migration' for add the new databaseView and set 1 to 2 on my database version like this : @Database(version: 1, views[...]) --> @Database(version: 2,views:[...]) ?

Thx a lot

SEGVeenstra commented 1 year ago

Hi @sancho0410,

If I understand correctly, you have first created a database WITHOUT the DatabaseView. Now you've added a DatabaseView but it doesn't appear and you wonder if you need a migration for it to become available?

But i can't see the new view on my database schema, even if i delete install app on emulator and reinstall it.

This almost sounds like the Database is somehow preserved. Which could possibly be, I've seen it before. Have you tried clearing the app's data?

Need i use 'migration' for add the new databaseView and set 1 to 2 on my database version like this : @Database(version: 1, views[...]) --> @Database(version: 2,views:[...]) ?

If you have users already on the first version of the database (version 1) and you want to add a DatabaseView, then YES, you need a migration.

DISCLAIMER: I'm pretty new to the package, but this is what worked for me:

I had to perform the following steps (assuming you've already created your DatabaseView Class):

  1. Bump the version of your database:

    @Database(version: 1, ...) --> @Database(version: 2, ...)
  2. Add the DatabaseView to Database.views:

    @Database(version: 2, views: [CepParcelle], ...)
  3. Create a migration function:

    final migration1to2 = Migration(1, 2, (database) async {
    await database.execute('CREATE VIEW CepParcelle AS SELECT c.*, p.code as parcelle_code From cep c INNER JOIN parcelle p ON p.id = c.parcelle_id');
    });
  4. Add the migration to the databaseBuilder:

    final db = await $FloorMenuDatabase.databaseBuilder('app.db')
    .addMigrations([migration1to2])
    .build();
  5. Run the build-runner again.

I hope this helps!

sancho0410 commented 1 year ago

Thx for the reply =) In fact im not in production yet but i keep my previous instance of database, so i need to use migration if i keep my database and remove the system if i remove my previous app instance =)

Bit the migration system works fine ;-)

SEGVeenstra commented 1 year ago

Glad to hear it!

I assume that answers your question. I will close the issue.