I've discovered a Foreign key column in a table that wasn't matched by an entry in the Models file for that entity.
First tried to remove it like this (because its not referenced in the code, as it isn't in the Models file)
migrationBuilder.Sql("alter table mytable drop constraint if exists myfk");
migrationBuilder.Sql("drop index if exists myindex");
migrationBuilder.Sql("alter table mytable drop column if exists myunusedFKcolumn");
This removed it, but then the code began to error, as it seemed to need that relation in one specific place where that relation isn't relevant.
So I re-added it (along with FK relation and index), and in a next migration, tried to remove it cleanly, like this (thinking that doing it the EF way would be more clean than directly in the database):
migrationBuilder.DropForeignKey(
name: "myfk,
schema: "myschema",
table: "mytable");
migrationBuilder.DropIndex(
name: "myindex",
schema: "myschema",
table: "mytable");
migrationBuilder.DropColumn(
name: "myunusedFKcolumn",
schema: "myschema",
table: "mytable");
But whatever I do, the migrations continue to automatically add myfk and myindex back in the next migration.
How to get rid of this happening?
Related
To preface, I am trying to replace an entire table with a new table with same columns, but with updated values.
I have the following SQL code:
BEGIN;
ALTER TABLE "original" RENAME TO "original_old";
ALTER TABLE "original_new" RENAME TO "original";
ALTER TABLE "original" RENAME CONSTRAINT "temp_original_id" to "original_id";
DROP TABLE "original_old";
COMMIT;
Output:
ERROR: constraint "temp_original_id" for table "original" does not exist
However, if I do the following before the last ALTER statement:
SELECT * from original;
I see temp_original_id present in the table.
I can't seem to find any other sources that lead me to updating primary key (at least that worked)
The table I am replacing also has dependencies with other tables.. So I was wondering if this would be a viable solution to even begin with
Did you mean ALTER TABLE "original" RENAME COLUMN "temp_original_id" to "original_id"; ?
I have a requirement of deleting records from the Postgres database tables.
We have a Customer table which is the main table, this table contains a primary key which is used in so many other tables as a FOREIGN KEY, I want to delete one of the customers as well as its reference used in other tables. Is there any way to delete the customer from main table as well as from other tables which contains foreign key.
Thanks in Advance.
In the other tables, you want a cascading delete foreign key reference. You can create one in the database using:
alter table othertable add constraint fk_othertable_customerid
foreign key (customerid) references customers(customerid)
on delete cascade;
Note: This assumes that customerid is the name of the column in both tables and that it is already defined in the other tables.
A cascading foreign key constraint does exactly what you specify. When a row is deleted in the reference table, then all related rows are deleted.
If you already have foreign key constraints on customerid, then drop the existing constraint and add the cascading version.
I have an issue where Postgres is complaining of a duplicate ID following an import of some initial data and I am trying to see how to increment the id column counter?
Details:
I have recently uploaded some initial data into a Postgres table, where the id is set to autoincrement in my Sequelize model definition. For example:
sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.STRING
}
The data insert looks like:
INSERT INTO "users" ("id","name") VALUES(1, "bob");
INSERT INTO "users" ("id","name") VALUES(2, "brooke");
INSERT INTO "users" ("id","name") VALUES(3, "nico");
Now from my node.js application when I try to insert a new record it complains that Key (id)=(1) already exists. The SQL Sequelize is using is of the form:
INSERT INTO "users" ("id","name") VALUES(DEFAULT, "nico");
If I am empty the table of records and try this again or retry the operations enough times, then I see the counter does increment. The issue seems Postgres is not able to tell what the current max id is, based on the records?
What would be the right way to tell Postgres to update the counters, following uploading initial data into the database?
BTW using Postgres 9.6
After a bit more searching it turns out this will do what I need to do.
SELECT setval('users_id_seq', max(id)) FROM users;
This code will set the id to the current maximum id in the table, here it being my users table. Note, to check if a sequence is associated with a column, this will work:
SELECT pg_get_serial_sequence('patients', 'id')
The only thing to note is that you ignore the 'public.' part in the returned value.
I'll add the setval() to my initial data script.
Try dropping the table before you initially insert data, it may be persisting from a previous run in which case (1, "bob") would already be in your table before you tried adding it again.
This happened to me because I inserted records using literal, numeric values (instead of DEFAULT or undefined) as arguments for the auto-incremented column. Doing so circumvents the column's underlying sequence object's increment call, hence making the sequence's value out of sync with the values in the column in the table.
SELECT setval('users_id_seq', (SELECT MAX(id) from users));
The name of the sequence is auto generated and is always tablename_columnname_seq.
I searched for this problem. But my postgres user has enough grant and I do not think I have misspelling error. However I am newbie.
I have this error message:
21:38:03 set search_path='public'
21:38:03 ALTER TABLE public.tbl_user DROP CONSTRAINT "fk-user-access-user-id"
21:38:03 ERROR: constraint "fk-user-access-user-id" of relation "tbl_user" does not exist
I use the PhpStorm. I just open the database view, expanded the tbl_user table, right click and select "drop". And I got this error in the console.
So the above SQL command generated by the PhpStorm.
Then I tried with these commands manually on Ubuntu:
ALTER TABLE tbl_user DROP CONSTRAINT "fk-user-access-user-id"
ALTER TABLE "tbl_user" DROP CONSTRAINT "fk-user-access-user-id"
But I get the same error.
In the PhpStorm I see this definition:
"fk-user-access-user-id" FOREIGN KEY (access_id) REFERENCES tbl_access (id)
The tbl_access table exists with the primary id key.
I do not understand this error message, because the "fk-user-access-user-id" foreign key is at the tbl_user and so for me the 'relation "tbl_user" does not exist' strange. I do not understand.
I tried to find similar problem on StackOverflow, but I gave up after 20x question reading.
By the way, the postgres code was generated by the Yii framework.
$this->addColumn('{{%user}}', 'access_id', $this->integer()->notNull()->defaultValue(1)->after('status'));
$this->addForeignKey('fk-user-access-user-id', '{{%user}}', 'access_id', '{{%access}}', 'id');
first row mean add access_id column to the user table.
second row: create foreign key with 'fk-user...' name on tbl_user table's access_id column references to tbl_access table's id column.
So I used this PHP code to generate this SQL commands. I prefer this way because for me the migration files are very useful.
Most likely the definition and actual implementation in your underlying DB has changed from what the app has recorded. Depending on what the history is, either a change in the app for that foreign key relationship was not migrated to persist the change at the database level, or someone has executed some operation directly at the DB level to remove the relationship. You will need to sync up the app layer to the DB at this point I would think.
I have two tables
Users
Users_Role
I decided to try to add a foreign key as to my understanding it will let me cascade the delete procedure when removing a user from Users (as well as enforce integrity).
So via Management Studio I right clicked my Users_Role table, Design, then went into Relationships. I added a new relationship between the two tables as such:
Foreign Key Base Table: Users_Role
Foreign Key Columns: UserID
Primary/Unique Key Base: Users
Primary/Unique Key columns: ID
When I then try to save, I get the following error:
'Users' table saved successfully
'Users_Role' table
- Unable to create relationship 'FK_Users_Role_Users'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Users_Role_Users". The conflict occurred in database "db", table "dbo.Users", column 'ID'.
I'm not sure what's going on. Adds the relationship to Users, but not Users_Role? The only thing special about Users_Role is that my primary key consists of two columns, UserID and Role (the only two columns in the table, if that matters). Otherwise, nothing special.
This error means that in your current database, you have entries in the "Users_Role" table which have a "UserID" value that is not present in the Users table as ID.
You first need to find those "rogue" rows and either update or delete them, before you can create the foreign key to enforce referential integrity and avoid such problems in the future.
You can find those by issuing this command:
SELECT * FROM Users_Role
WHERE UserID NOT IN
(SELECT DISTINCT ID FROM Users)