I have a question regarding constraints on custom schemas.
My app creates a new/separate schema for each clients corresponding with clients' name (i.e .clienta, clientb,...). Some of the tables have a foreign-key constraints but, they don't work on schemas other than the default public schema. For example, let's say there is schema called clienta and it has projects and tasks tables, model Task has a belongsTo(models.Project) association (i.e projects table primary_key
is a foreign_key
for table tasks. The issue starts here: when trying to create a record in table tasks there comes an error saying foreign key violation error... Key (project_id)=(1) is not present in table "projects...
even though projects table has the respective record with id = 1. I am wording if this is a limitation of sequelize
library itself or am I missing something in the configs?
Sequelize config
"development": {
"database": "my_app",
"host": "127.0.0.1",
"dialect": "postgres",
"operatorsAliases": "Sequelize.Op",
"dialectOptions": {
"prependSearchPath": true
},
"define": {
"underscored": true
}
}
Example of create function:
models.Task.create({...args}, { searchPath: 'clienta' })
N.B Everything works as expected in public schema.
PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships. When Pg creates an implicit index it will emit a NOTICE -level message that you can see in psql and/or the system logs, so you can see when it happens.
Foreign Keys without the constraintsYou don't have to configure a foreign key constraint on a column just because it refers to another column. You could instead configure two tables such that one refers to the other, but without any defined foreign key.
The sync method API lists two options relating to DB-schema:
options.schema - schema the table should be created in
options.searchPath - optional parameter to set searchPath (Postgresql)
When using schemas other than the default and an association between Models has been created (using for instance belongsTo), it is important to set the searchPath to hold the name of the schema of the target table. Following the explanation in search_path in postgresql, not specifying the searchPath will have the constraint referring to a table (if it exists) in the default schema (usually 'public').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With