Search code examples
c#postgresql.net-coremarten

How to create database with Marten on application start?


I would like Marten to create the database if it not exists, while configuring my event store. I've found in the documentation that i need to use the following snippet for such a behavior:

services
    .AddSingleton<IDocumentStore>(DocumentStore.For(options =>
    {
        options.Connection(connectionString);
        options.DatabaseSchemaName = schemaName;
        options.Serializer(GetCustomJsonSerializer());

        options.CreateDatabasesForTenants(databaseConfig =>
        {
            databaseConfig
                .MaintenanceDatabase(connectionString) 
                .ForTenant()
                .CheckAgainstPgDatabase()
                .WithOwner(eventStoreSettings.DatabaseOwner)
                .WithEncoding(eventStoreSettings.Encoding)
                .ConnectionLimit(eventStoreSettings.ConnectionLimit);
        });
    }));

Documentation says "If a connection attempt results in an invalid catalog error (3D000), database creation is triggered.". The attached code really results in the mentioned error (3D000), but instead of triggering the database creation, I get the following unhandled exception: "Npgsql.PostgresException (0x80004005): 3D000: database "UserDatabase1" does not exist at Npgsql.NpgsqlConnector". The privileges of the user used in the connection string are correct. How to use Marten to create database if it not exists? What am i doing wrong?


Solution

  • Your MaintenanceDatabase connection string have to be a different one from your marten datastore connection. Note that MaintenanceDatabase connection must have create database permission for it to work. Just use a root user without any database should work. For example:

    "Host=localhost;Username=sa;Password=Pass@word"