Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Foreign-key constraints in non public schema

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.

like image 327
bir_ham Avatar asked Jul 14 '18 11:07

bir_ham


People also ask

Are foreign keys automatically indexed Postgres?

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.

Can you have a foreign key without a constraint?

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.


1 Answers

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').

like image 153
Koen Avatar answered Sep 21 '22 17:09

Koen