question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add support for schema in queryInterface.addConstraint method inside references attribute

See original GitHub issue

Issue Description

queryInterface.addConstraint method does not have support for schema specification inside references attribute

What are you doing?

Trying to add a foreign key to a table that does not belong to ‘public’ schema in postgres

await queryInterface.addConstraint({
    schema: 'something',
    tableName: 'person'
}, ['company_id'], {
    type: 'foreign key',
    name: 'fk_name',
    references: {
        schema: 'something', // <--- This
        table: 'company',
        field: 'id'
    },
    onUpdate: 'cascade',
    onDelete: 'cascade'
});

What do you expect to happen?

That resulting query outputs:

ALTER TABLE "something"."person"
ADD CONSTRAINT "fk_name"
FOREIGN KEY ("company_id")
REFERENCES "something"."company" ("id")
ON UPDATE CASCADE
ON DELETE CASCADE

What is actually happening?

The output was Bar!

Due to there is no an option to specify the schema inside references attribute I’m getting the following sql output

ALTER TABLE "something"."person"
ADD CONSTRAINT "fk_name"
FOREIGN KEY ("company_id")
REFERENCES "company" ("id")
ON UPDATE CASCADE
ON DELETE CASCADE

And then an error: Error relation "company" does not exist

Additional context

What am I doing wrong, is there another way to achive this?

I also tried something like this:

await queryInterface.addConstraint({
    schema: 'something',
    tableName: 'person'
}, ['company_id'], {
    type: 'foreign key',
    name: 'fk_name',
    references: {
        table: 'something.company', // '"something"."company"'
        field: 'id'
    },
    onUpdate: 'cascade',
    onDelete: 'cascade'
});

And none worked succesfully

To solve my problem temporarily I wrote this code

import { QueryInterface } from 'sequelize';

interface AddForeignKeyOptions {
	name: string;
	references: {
		schema: string;
		table: string;
		field: string;
	};
	onUpdate: string;
	onDelete: string;
	logging?: boolean | ((sql: string) => void);
}

export const addForeignKey = (queryInterface: QueryInterface, table: { tableName: string, schema: string }, attributes: string[], options: AddForeignKeyOptions) => {
	const sql = `ALTER TABLE "${table.schema}"."${table.tableName}"
		ADD CONSTRAINT "${options.name}"
		FOREIGN KEY (${attributes.map(a => '"' + a + '"').join(', ')})
		REFERENCES "${options.references.schema}"."${options.references.table}" ("${options.references.field}")
		ON UPDATE ${options.onUpdate.toUpperCase()}
		ON DELETE ${options.onDelete.toUpperCase()}`;

	if (typeof options.logging === 'function') {
		options.logging(`Executing (default): ${sql}`);
	}

	return queryInterface.sequelize.query(sql);
};

Environment

  • Sequelize version: 5.21.2
  • Node.js version: 10.16.0
  • Operating System: XXX
  • If TypeScript related: TypeScript version: 3.5.1

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s): postgres
  • I don’t know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don’t know how to start, I would need guidance.
  • No, I don’t have the time, although I believe I could do it if I had the time…
  • No, I don’t have the time and I wouldn’t even know how to start.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:9
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
ephyscommented, Nov 4, 2022

I tried something like this, and it works for me:

That is the actual officially supported solution. Should be clearer once we’re done strictly typing queryInterface. 😃

2reactions
lyridwancommented, Sep 8, 2021

I tried something like this, and it works for me: tested on: v6.6.5

queryInterface.addConstraint("Posts", {
    fields: ["username"],
    type: "foreign key",
    name: "custom_fkey_constraint_name",
    references: {
        table: {
            tableName: target_table_name,
            // define schema here
            schema: target_table_schema,
        },
        field: "target_column_name",
    },
    onDelete: "cascade",
    onUpdate: "cascade",
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

QueryInterface - Sequelize
An easy-to-use multi SQL dialect ORM for Node.js.
Read more >
Writing Migrations with Foreign Keys Using SequelizeJS
How do I create tables with foreign key relationships with one another through the Sequelize QueryInterface? The .createTable() method takes in a dictionary ......
Read more >
migrations · Sequelize-docs - RYAN S CHATTERTON
addConstraint (tableName, attributes, options). This method adds a new constraint of the specified type. tableName - Name of the table to add the...
Read more >
lib/query-interface.js | Sequelize
* This method returns an array of hashes containing information about all attributes in the table. *; * ```js; * {; * name:...
Read more >
How to use ADD CONSTRAINT in SQL (with examples)
SQL databases work the same way. You can set up constraints – rules for entry into your table – and the database will...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found