Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Create query and dialect options for prepending schema search_path in Postgres #4534
When you have a multi-tenant application that has the same database models across multiple schemas the current sequelize model paradigm forces you to create a separate model for each schema that is identical except for the schema property of the tableName object. This change adds a dialect option called prependSearchPath that will allow you to pass a searchPath option to any query that will be prepend the query with "SET search_path to ". If the prependSearchPath options is enabled and no searchPath query option is provided it will use DEFAULT which should be the same behavior as before. By supporting a searchPath option I can now define a common set of models and use them across tenant schemas by passing the correct searchPath. If the prependSearchPath dialect option is not explicitly passed as true than the code works exactly as it did before.
On the surface this functionality would appear to be possible by using model.schema() but this does not work well when the same model needs to be used against multiple schemas concurrently in the same application as it changes the schema option on the model itself which can lead to inconsistent results. Specifically the following use cases do no work well.
referenced this pull request
Sep 17, 2015
I agree that this is an issue with the .schema() functionality. The issue with cloning the model to set the schema is that you introduce a large memory problem. If you have a model that needs to be used across 1000s of schemas concurrently you are having to store than object in memory 1000s of times with that solution. This does not scale and is the reason we used the search_path approach which allows you to use one copy of the model across all schemas.
@mickhansen Sorry I didn't call this out better. I made the functionality opt-in in this versions by only prepending if the dialectOption 'prependSearchPath' is set to true. See https://github.com/mliszewski/sequelize/blob/wrap_search_path/lib/sequelize.js#L744