micronaut-projects / micronaut-data

Ahead of Time Data Repositories
Apache License 2.0
465 stars 196 forks source link

Override the multi-tenancy behaviour for Micronaut Data MongoDB #1945

Open cosmin-marginean opened 1 year ago

cosmin-marginean commented 1 year ago

Feature description

We have a use case (which we believe to be reasonable) where we want to use multi-tenancy for most of the data, but some of the application core (admin) data doesn't require multi-tenancy. In fact it needs to be stored in a specific MongoDB database.

For example, say we have 2 tenants, we would have 3 MongoDB databases:

Most repositories would need to use app-tenant1/2, but a few core ones would use a fixed database name (app-admin).

Second, resolving a missing/null tenant to app-admin is not possible, as we want to fail an operation without a tenant, and not to default to the app-admin database.

Lastly, we won't be using multiple MongoDB servers, so using that type of configuration (see 'Multiple MongoDB Drivers') would also be unnecessary.

The current multi-tenancy implementation makes the multi-tenancy settings to take precedence when determining which database to read/write: https://github.com/micronaut-projects/micronaut-data/blob/d9a8b295f3f4ddd8dfa58e9902fb7404b280bb33/data-mongodb/src/main/java/io/micronaut/data/mongodb/operations/DefaultMongoDatabaseNameProvider.java#L84 We would like to be able to override the "fixed" database name by simply using things like

@MongoRepository(databaseName = "app-admin")

But this is unattainable because of how this database name resolution behaviour is implemented. It's also quite difficult to override this bean, and we ended up copy-pasting the code, making the required changes and then building this particular class with our app, which is obviously far from ideal.

It would be good if this would be a bean that can be overridden with@Replaces, but happy to hear other suggestions that would address this.

Saumya999 commented 12 months ago

I am also having same kind of requirement

I am not sure how many tenants I will have in future , so my application should be dynamically create mongodb uri on a same server.

Aim is to use same servers but different databases for different customers with same collection schema under every databases.

did you find any solution as I am seeing this is pretty old. ?

I am using Micronaut - Kotlin - Micronaut-data