migrate method

Future<void> migrate({
  1. DatabaseDisk disk = Model.defaultDisk,
})

Migrates the pivot table schema for the selected disk.

For SQLite, this method:

  • merges defaultColumnDefinitions with columnDefinitions
  • creates the pivot table if it does not exist
  • creates a standard composite index on the relationship columns
  • creates a unique composite index to prevent duplicate relationships

At present, pivot table migration is implemented for sqlite only.

Parameters:

Example:

final pivot = UserRolePivot();
await pivot.migrate(disk: DatabaseDisk.sqlite);

Implementation

Future<void> migrate({DatabaseDisk disk = Model.defaultDisk}) async {
  switch (disk) {
    case DatabaseDisk.sqlite:
      try {
        final database = App().make<SQLiteDatabase>();
        final allColumns = {...defaultColumnDefinitions, ...columnDefinitions};

        final col1 = columnDefinitions.keys.toList()[0].toString();
        final col2 = columnDefinitions.keys.toList()[1].toString();

        final columnsDef = allColumns.entries.map((e) => '${e.key} ${e.value}').join(', ');

        await database.execute('''
              CREATE TABLE IF NOT EXISTS $name (
                $columnsDef
              )
              ''');
        await database.execute('''
              CREATE INDEX IF NOT EXISTS idx_$name ON $name ($col1, $col2)
              ''');
        await database.execute('''
             CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_$name ON $name ($col1, $col2)
              ''');
      } catch (e, stack) {
        App().archeryLogger.error("Error migrating pivot table: $name", {"origin": "PivotTable.migrate() case:sqlite", "error": e.toString(), "stack": stack.toString()});
      }

    case DatabaseDisk.file:
      // TODO: Handle this case.
      App().archeryLogger.error("Error migrating pivot table: $name", {"origin": "PivotTable.migrate() case:file", "error": "file disk not configured",});
      throw UnimplementedError();
    case DatabaseDisk.pgsql:
      App().archeryLogger.error("Error migrating pivot table: $name", {"origin": "PivotTable.migrate() case:pgsql", "error": "pgsql disk not configured",});
      throw UnimplementedError();
    case DatabaseDisk.s3:
      App().archeryLogger.error("Error migrating pivot table: $name", {"origin": "PivotTable.migrate() case:s3", "error": "s3 disk not configured",});
      throw UnimplementedError();
  }
}