Skip to content
Youssef Ben edited this page Oct 25, 2023 · 8 revisions

Cassandra Fluent Migrator

Cassandra Fluent library

Cassandra Fluent Migrator is a library that offers a set of fluent code and extensions to facilitate the creation and management of the migrations using code instead of CQL commands.

Stack

Installation

PM> Install-Package Cassandra.Fluent.Migrator

Future Improvements

  • Add support for more complex types.
  • Add support for the Materialized views.

Documentations

Basic Usage

  • Migration class
public class InitialMigration : IMigrator
{
    private readonly ICassandraFluentMigrator cfm;
    private readonly ILogger<InitialMigration> logger;

    public InitialMigration(ILogger<InitialMigration> logger, ICassandraFluentMigrator cfm)
    {
        this.cfm = cfm;
        this.logger = logger;
    }

    public string Name => this.GetType().Name;
    public Version Version => new Version(1, 0, 0);
    public string Description => "First migration to initialize the Schema";

    public async Task ApplyMigrationAsync()
    {
        this.logger.LogDebug($"Creating the Address User-Defined type...");
        await this.cfm.CreateUserDefinedTypeAsync<Address>();

        // Should not be here in real-world application.
        // Used only for example purposes.
        this.cfm
            .GetCassandraSession()
                .UserDefinedTypes.Define(
                UdtMap.For<Address>()
                    .Map(a => a.Number, "Number".ToLower())
                    .Map(a => a.Street, "Street".ToLower())
                    .Map(a => a.City, "City".ToLower())
                    .Map(a => a.Contry, "Contry".ToLower())
                    .Map(a => a.Province, "Province".ToLower())
                    .Map(a => a.PostalCode, "PostalCode".ToLower()));

        this.logger.LogDebug($"Creating the User table...");
        await this.cfm.GetTable<Users>().CreateIfNotExistsAsync();
    }
}
  • Startup class
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    // Custom method that you can create to initialize the Cassandra {ISession}.
    services.AddCassandraSession(this.Configuration);

    // Register the migrations
    services.AddTransient<IMigrator, InitialMigration>();

    // Required by the library to register the needed classes.
    services.AddCassandraFluentMigratorServices();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...

    // Start the migration process.
    app.UseCassandraMigration();

    ...
}