By default, you cannot TRUNCATE (empty) a table that has foreign key constraints applied on it. This is to keep the data consistent over multiple tables that are linked by constraints. Nevertheless, it might be necessary to truncate all data from a table.
Here are a few options you can consider to resolve this issue:
Solution 1 – Disable Foreign Key Checks
The fastest way to clean the table is to disable FOREIGN_KEY_CHECKS. Temporarily disabling foreign key checks allows you to truncate the table without encountering the error. However, this should be done with caution as it can lead to data integrity issues if not handled properly.
SQL
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `table1`;
TRUNCATE TABLE `table2`;
SET FOREIGN_KEY_CHECKS = 1;
Solution 2 – Delete Rows Instead of Truncating
Instead of truncating the table, you can delete rows from it. Deleting rows one by one will trigger the foreign key constraint checks, allowing MySQL to maintain referential integrity. You can use the DELETE statement with a WHERE clause to remove specific rows.
SQL
DELETE FROM your_table WHERE condition;
Solution 3 – Drop and Recreate Foreign Key Constraints
If it’s acceptable for your application, you can drop the foreign key constraints referencing the table you want to truncate, truncate the table, and then recreate the foreign key constraints.
SQL
ALTER TABLE referencing_table DROP FOREIGN KEY constraint_name;
TRUNCATE TABLE your_table;
ALTER TABLE referencing_table ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES your_table(column_name);
Photo by Jan Antonin Kolar on Unsplash
Issue type:
[x] question
[x] bug report
[ ] feature request
[ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[x] postgres
[x] sqlite
[ ] sqljs
[ ] websql
TypeORM version:
[x] latest
[ ] @next
[ ] 0.x.x (or put your version here)
Steps to reproduce or a small repository showing the problem:
I have simple OneToOne relation like this:
@Entity({name: 'user'})
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({length: '50', nullable: true})
firstName: string;
@Column({length: '50', nullable: true})
lastName: string;
}
and:
@Entity({name: 'account'})
export class Account extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
balance: number;
@OneToOne(type => User, {})
@JoinColumn()
user: User;
}
Delete all users and create new one with following code:
createConnection().then(async (connection) => {
console.log('Inserting a new user into the database...');
await connection.getRepository(User).clear(); // remove all users
const user = new User();
user.email = 'admin@admin.com';
user.role = Role.BORROWER;
user.password = 'admin';
user.idnp = '2342332342300';
await connection.manager.save(user);
console.log('Saved a new user with id: ' + user.id);
console.log('Loading users from the database...');
const users = await connection.manager.find(User);
console.log('Loaded users: ', users);
console.log('Here you can setup and run express/koa/any other framework.');
debug('postgres database connected successfully...');
}).catch((err) => error(err));
Witch produces the following error (error with postgres, with sqlite this error is not pesent.):
_
Inserting a new user into the database…
executing query: TRUNCATE TABLE «user»
query failed: TRUNCATE TABLE «user»
error: { error: cannot truncate a table referenced in a foreign key constraint
at Connection.parseE { … }backend\node_modules\pg\lib\connection.js:113:22)
at Socket.emit (events.js:160:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
at TCP.onread (net.js:602:20)
name: ‘error’,
length: 238,
severity: ‘ERROR’,
code: ‘0A000’,
detail: ‘Table «account» references «user».’,
hint: ‘Truncate table «account» at the same time, or use TRUNCATE … CASCADE.’,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: ‘heap.c’,
line: ‘2983’,
routine: ‘heap_truncate_check_FKs’ }
error: { QueryFailedError: cannot truncate a table referenced in a foreign key constraint
….
backend\node_modules\pg\lib\connection.js:117:12)
at Socket.emit (events.js:160:13)
at addChunk (_stream_readable.js:269:12)
at readableAddChunk (_stream_readable.js:256:11)
at Socket.Readable.push (_stream_readable.js:213:10)
message: ‘cannot truncate a table referenced in a foreign key constraint’,
name: ‘QueryFailedError’,
length: 238,
severity: ‘ERROR’,
code: ‘0A000’,
detail: ‘Table «account» references «user».’,
hint: ‘Truncate table «account» at the same time, or use TRUNCATE … CASCADE.’,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: ‘heap.c’,
line: ‘2983’,
routine: ‘heap_truncate_check_FKs’,
query: ‘TRUNCATE TABLE «user»‘,
parameters: [] }
internal/child_process.js:409
throw errnoException(err, ‘kill’);
^
_
|
Aricus 2 / 1 / 2 Регистрация: 29.04.2017 Сообщений: 56 |
||||||||||||||||||||
Как удалить внешний ключ, вызывающий ошибку?01.04.2021, 09:42. Показов 2921. Ответов 1 Метки нет (Все метки)
Cannot delete or update a parent row: a foreign key constraint fails (`control`.`devcomp`, CONSTRAINT `devcomp_ibfk_2` FOREIGN KEY (`component_id`) REFERENCES `components` (`ID`))
#1701 — Cannot truncate a table referenced in a foreign key constraint (`control`.`analogs`, CONSTRAINT `analogs_ibfk_1` FOREIGN KEY (`component_id`) REFERENCES `control`.`components` (`ID`)) Пробовал:
#1091 — Невозможно удалить (DROP) ‘devcomp_ibfk_1’. Убедитесь что столбец/ключ действительно существует
0 |
|
IT_Exp Эксперт 34794 / 4073 / 2104 Регистрация: 17.06.2006 Сообщений: 32,602 Блог |
01.04.2021, 09:42 |
|
Ответы с готовыми решениями: Как назначить внешний ключ? Как добавить внешний ключ? Внешний ключ — это простой ключ? 1 |
|
5393 / 1465 / 513 Регистрация: 31.05.2012 Сообщений: 5,153 |
|
|
01.04.2021, 10:14 |
|
|
Сообщение было отмечено Aricus как решение Решениевнешние связи devcomp_ibfk_2 для devcomp и analogs_ibfk_1 для analogs вижу в сообщениях об ошибках devcomp_ibfk_1 — что это? ну даже удалишь связи, почистишь components, а что делать с devcomp и analogs в которых остались поля с идешками несуществующих записей components? Может стоит сначала удалить записи из дочерних таблиц? add связь удаляется сомандой ALTER TABLE devcomp DROP CONSTRAINT devcomp_ibfk_2 Добавлено через 6 минут
1 |
El Forum
Unregistered
[eluser]piotrpolak[/eluser]
It is not a reall bug.
I have got 2 tables:
Code:
CREATE TABLE table1 (
myid serial NOT NULL PRIMARY KEY
);
Code:
CREATE TABLE table2 (
myid int NOT NULL REFERENCES table1(myid) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
);
Lets suppose table2 is empty, and we try to truncate table1. This is what we get:
Code:
ERROR: cannot truncate a table referenced in a foreign key constraint
Method truncate from CI_DB_postgre_driver:
Code:
function _truncate($table)
{
return "TRUNCATE ".$this->_escape_table($table);
}
Should/could be:
Code:
function _truncate($table)
{
return "TRUNCATE ".$this->_escape_table($table)." CASCADE"; // HERE!
}
Though it is a rare occurrence, we have had occasions where we need to purge ALL data from a table. Our preferred is the TRUNCATE TABLE approach because it’s orders of magnitude faster than the DELETE FROM construct. You however can’t use TRUNCATE TABLE unqualified, if the table you are truncating has foreign key references from other tables.
In comes its extended form, the TRUNCATE TABLE .. CASCADE construct which was introduced in PostgreSQL 8.2, which will not only delete all data from the main table, but will CASCADE to all the referenced tables.
Here is a quick demonstration. Suppose you had two tables orders and order_items where the order_items table references the orders.order_id column. If you do this:
TRUNCATE TABLE orders;
You’ll get notice
ERROR: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "order_items" references "orders". HINT: Truncate table "order_items" at the same time, or use TRUNCATE ... CASCADE.
It doesn’t matter if you have CASCADE UPDATE or DELETE rule in place, the CASCADE approach will still be able to purge all data in the referenced tables by changing your statement to:
TUNCATE TABLE orders CASCADE;
You’ll get a notice of the form:
NOTICE: truncate cascades to table "order_items"
