how can I delete a row in Sqlite with foreign key? - c++

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.

Related

Create table without checking foreign key on unexisting table

I'm adapting a really big query (MySQL to SQL) that creates lots of tables and relationships. The problem is that it always check if a table exists prior to adding a foreign key referencing to that table.
So I have to reorder the queries to avoid this problem, and my question is if there's a instruction that can turn that check off, so it'll create the tables and add references without stopping the query with every error it encounters.
I'm working with SQL in an Azure DB.
Thank you.
Easiest way is to create all tables first and then add constraints using ALTER TABLE.
For example:
CREATE TABLE a(id INT PRIMARY KEY IDENTITY(1,1), b_id INT, c CHAR(10));
CREATE TABLE b(id INT PRIMARY KEY IDENTITY(1,1), z INT);
ALTER TABLE a ADD CONSTRAINT FK_a_b_id_b FOREIGN KEY (b_id) REFERENCES b(id);
Rextester Demo

ID value is not continuous in django admin interface

When I delete an existing record from database and recreated a exactly same record through Django admin interface, the id value shows in Django admin interface is not continuous. For instance, the record with id value is 6 and the previous one is 5, then I delete the one with id 6. When I recreate it, the id value becomes 7 instead of 6. I think it supposes to be 6. It this a error and how can I fix this issue?
That is the correct behaviour. Primary keys should not get re-used, especially to avoid conflicts when it has been referenced in other tables.
See this SO question for more info about it: How to restore a continuous sequence of IDs as primary keys in a SQL database?
If you really want to reset the Auto Increment of PK, you can do ALTER TABLE tablename AUTO_INCREMENT = 1 (for MySQL). Other DBs may have different limitations like not being able to reset to any value lower than the highest used, even if there are gaps (MySQL:InnoDB).

PostgreSQL sequence being reset?

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;

C++: How to set GUID to NULL instead of GUID_NULL?

I have a database which uses GUIDs instead of, say, an ordinary counter for the ID fields. But I can't seem to put NULL (instead of GUID_NULL) into such fields in DB even though. Yes, the field in the database does take NULL.
Let's say there is a parent-child relationship between two tables. So there is a parent and a child GUID references from one table to another. But the "root" parent does not have any parent and there I would like to be able to put NULL into its ParentUID database field. If I put GUID_NULL there then I will need a corresponding default row in the referenced table which has a GUID-value of GUID_NULL so that the foreign key constraint won't break.
Also, using GUID_NULL with default-rows at referenced tables will give me a resultset back when doing a standard join operation...which is not desirable.
They way it's done in code when inserting values into database is using a CCommand which takes structure that contains the values of the row fields to be inserted. One of these is a GUID type variable.
So it creates an SQL statement string looking like
INSERT INTO [tablename] (field1, field2, field3,...) VALUES(?,?,?,...)
and then in a loop there is something like:
command.field1 = 1;
command.field2 = 2;
command.GUIDField = ?????? //I want to put NULL here instead of GUID_NULL
command.Open(...);
I hope it is understandable what I wish to do and what the conditions in code are.
Thankful for help!
UPDATE:
Ok, it was very hard to exaplin correctly, but this is exactly what I want to do http://support.microsoft.com/kb/260900
Just that when I follow that example, it makes no difference...still I get FK constraint violation on insert so I suspect it is trying to insert GUID_NULL instead of NULL. :(
The link I had in my Update-section does work, my bad: http://support.microsoft.com/kb/260900
It is the answer to my problems, perhaps it will help someone else as well! :3

Django and sqlite email authentication

I wanted to create an email authenticated django user model, and I basically followed the steps in this website:
http://www.micahcarrick.com/django-email-authentication.html
And also included the table alteration code in a post_syncdb function in a managmenet module, to make the email a unique identifier. This should work ok with MySql. BUT, it wont work for sqlite. This is because sqlite's table alteration is limited and wont allow you to change that attribute OR even add a column with a unique identifier.
If there is no elegant way of doing this, then I might have to switch to MySql.
http://www.sqlite.org/faq.html#q26
So, it UNIQUE is fully supported, but you cannot alter a table using UNIQUE. So dump the table to a new table that has the UNIQUE constraint then alter and rename the tables. Or just dump it, modify the dump and reimport it.
I think, in your post_syncdb hook, you can add:
cursor.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_user_email_unique "
"ON auth_user (email COLLATE NOCASE);"
)
you may have to break out different blocks based on settings.DATABASES['default']['ENGINE']