On a regular occasion, my Django webapps produce SQL errors on M2M tables.
Each time it turns out the ID sequence is reset to a value within the range of existing rows.
The app performs normal SQL queries such as:
INSERT INTO "myapp_project" ("name") VALUES ('test1') RETURNING "myapp_project"."id"'
which cause errors such as:
IntegrityError: duplicate key value violates unique constraint "myapp_project_pkey"
DETAIL: Key (id)=(29) already exists.
Then it turns out that the myapp_project_id_seq is pointing to an old ID number:
select currval('myapp_project_id_seq')
29
Which can then be reset by using:
select setval('myapp_project_id_seq', (select max(id) from myapp_project))
However, I can't explain why this is happening. It typically happens on M2M tables in Django. In this case, a normal table with admin-only input. Can someone enlighten me about this?
This typically happens when you (or somebody) sometimes write values to id explicitly, instead of getting values from the sequence (by default or with nextval()).
Your repair code is missing a pair of parentheses.
SELECT setval('myapp_project_id_seq', (SELECT max(id) FROM myapp_project));
This is a tiny bit shorter & cheaper while doing the same, exactly:
SELECT setval('myapp_project_id_seq', max(id)) FROM myapp_project;
Related
I have a problem trying to delete a row from my db...
the DB looks like that:
[The DB picture]
I want do delete a user so I tried:
DELETE FROM USERS WHERE ID = 201;
but obviously it didn't work out at all because it connects with the other TABLES.
And I cant use DROP because its sqlite.
I look up on the internet and got nothing...
the error:
the error
Your table name is Users and You are using USERS in your command. It will give you error as It should be same as name of table.
DELETE FROM Users WHERE ID = 201;
Let me assume that you have another table that defines the user_id as a foreign key:
create table another (
another_id int,
user_id int,
foreign key (user_id) references users(user_id)
);
And you have data in this table, such as:
another_id user_id
1 200
2 201
3 201
Now, you want to delete 201 from users. What happens to rows 2 and 3 in this table? There are several options:
The rows remain with the values as is. But those values no longer refer to a valid user.
The rows that refer to 201 are deleted.
The rows are set to some value, such as NULL or a default value.
The default behavior without a foreign key constraint is (1). And you end up with dangling references. And your database lacks relational integrity. That is considered a bad thing.
SQL supports cascading delete and update foreign key references (although not all databases support these). These respectively implement (2) and (3) on the above list.
You can also manually change the referring rows so the user can be deleted. It is not clear what you really want to do, but this explains why you can't just delete the row and the facilities that SQL offers to get around that.
My report is accessing two MySQL tables of sports matches from two different sources. Let's call them big_table and little_table. Where possible I've matched all the little_table matches to the big table and recorded the little_table IDs in a column in big_table that's joined with a foreign key relationship and enforced with a unique index.
I want to create a one-to-one relationship between the two tables to enable a one-to-many join I need to do from little_table to another table. However, I keep being my chosen cardinality isn't valid.
I'm absolutely positive there are no duplicates in the little_table_id column - MySQL wouldn't allow it. I understand from reading around Null values are treated as unique so they shouldn't be causing a problem. I've also checked the datatypes of the columns and they're 123 which I assume means integer and therefore can't contain blanks.
I can't think of anything else that could be going wrong but clearly something is! Any ideas?
I have two tables, SRC and TGT. I want to populate all my foreign key values in TGT from the target lookups. However, I'm getting nulls into the target. I have used all natural keys for lookup conditions. Can anyone please explain why I am seeing nulls?
For instance, I want to populate foreign key values for MPNG_ID, SESN-ID, WRKFLW-ID from lookup tables based on repository name and version number.
Did you validate if all your Join Conditions are working fine? Probably try to replicate same query in DB and check if its giving you the same result. I assume some Join might have messed up which might result in Null values. Ensure that even the spaces are in sync if you are using Varchar value.
I have a "index" field stores a consequent range of integers, for safety i set it unique.
now I want to increase this field by one, to keep unique I update the value in a descending order:
MyModel.objects.all().order_by('-index').update(index=F('index')+1)
what surprises me is that on some machine an IntegrityError
gets raised and complains for duplicated index value.
is there anything i missed? could I only save records one by one?
thanks in advance!
UPDATE:
I think the root problem is that there is no ORDER BY in an SQL UPDATE command (see UPDATE with ORDER BY, and also SQL Server: UPDATE a table by using ORDER BY)
Obviously django simply translates my statement into a SQL UPDATE with ORDER_BY, which leads to an undefined behavior and creates different result per machine.
You are ordering the queryset ascending. You can make it descending by adding the '-' to the field name in the order by:
MyModel.objects.all().order_by('-index').update(index=F('index')+1)
Django docs for order_by
I am trying to run multiple alter table statements for adding foreign keys on my database
I am using RazorSQL
this are my sql statement
ALTER TABLE SPO999.AVTVRSTEPLACILAPOD
ADD CONSTRAINT SQL100419145030510 FOREIGN KEY
(AVP_VRSTEPLACILA)
REFERENCES SPO999.VRSTEPLACILA
(VP_ID_VP)
ON DELETE NO ACTION
--ON UPDATE NO ACTION
ENFORCED
ENABLE QUERY OPTIMIZATION;
-- DDL Statements for foreign keys on Table SPO999.AVTVRSTEPLACILAVRPL
ALTER TABLE SPO999.AVTVRSTEPLACILAVRPL
ADD CONSTRAINT SQL100419145030630 FOREIGN KEY
(AVV_VRSTEPLACILA)
REFERENCES SPO999.VRSTEPLACILA
(VP_ID_VP)
ON DELETE NO ACTION
--ON UPDATE NO ACTION
ENFORCED
ENABLE QUERY OPTIMIZATION;
If I run one at a time it works, while if trying to run both at I get an SQL Error -104 a token,character or clause is invalid or missing.
I can not find a problem/solution
any suggestions?
thank you
I think it is likely that you can't have these two foreign key definitions referencing the same column within a single transaction.
Try adding commit; between the statements.
(Your SQL editor, depending on its settings, may automatically send a commit after each chunk of statements that you execute. That would explain the difference between the two cases).