Ошибка violation of foreign key constraint

Программа Retail Declaration более не поддерживается.

Для работы с ЕГАИС рекомендуем использовать Контур.Маркет.

В Retail Declaration при попытке принять ТТН может возникать ошибка Violation of  FOREIGN KEY constraint

Причина: Как правило, данная ошибка возникает в случае, если данная ТТН была принята в RD и ее пытаются принять повторно. 

Решение:

  1. Сделайте копию БД по инструкции.
  2. Посмотрите, нет ли данной ТТН в Журнале документов, в том числе среди удаленных документов. Посмотреть удаленные документы можно по инструкции. 
  3. Если данная ТТН присутствует в Журнале документов, то выполните следующие действия (после выполнения каждого пункта следует проверять, сохранилась ли ошибка):
    — Удалите данную ТТН, если она не удалена.
    — В удаленной ТТН измените номер документа, добавив нижнее подчеркивание.
    — Удалите в данной ТТН все позиции. 

Внимание! После повторного приема может потребоваться подача корректирующей декларации. Перейдите в раздел Движение продукции/Движение продукции и запросите движение продукции в целом по подразделениям, по 1 регистру и по 2 регистру. Посмотрите, нет ли там красных строк. Если красные строки есть, то отредактируйте документы таким образом, чтобы не было красных строк. 

Возможно это и не баг, но данная особенность нигде не описана… (буду честнее — не встречал такого описания)

Использовался IBExpert, FB 2.0.12748-win32 на win2003

Имеем две таблицы (приведу скрипт так, как его показывает ibexpert за искл. комментариев, возможно, что это важно):

Первая таблица:

Код: Выделить всё

SET SQL DIALECT 3;

CREATE GENERATOR GEN_MAIN_ID;

CREATE TABLE MAIN (
    ID       INTEGER NOT NULL,
    BALANCE  DECIMAL(15,2) DEFAULT 0.00 NOT NULL
);


ALTER TABLE MAIN ADD CONSTRAINT PK_MAIN PRIMARY KEY (ID);


SET TERM ^ ;

/* Trigger: MAIN_BI */
CREATE TRIGGER MAIN_BI FOR MAIN
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GEN_MAIN_ID,1);
END
^


SET TERM ; ^

Вторая таблица:

Код: Выделить всё

SET SQL DIALECT 3;

CREATE GENERATOR GEN_PAYMENTS_ID;

CREATE TABLE PAYMENTS (
    ID       INTEGER NOT NULL,
    ID_MAIN  INTEGER NOT NULL,
    MONEY    DECIMAL(15,2) NOT NULL
);


ALTER TABLE PAYMENTS ADD CONSTRAINT PK_PAYMENTS PRIMARY KEY (ID);

ALTER TABLE PAYMENTS ADD CONSTRAINT FK_PAYMENTS_1 FOREIGN KEY (ID_MAIN) REFERENCES MAIN (ID) ON DELETE CASCADE ON UPDATE CASCADE;

SET TERM ^ ;


/* Trigger: PAYMENTS_BI */
CREATE TRIGGER PAYMENTS_BI FOR PAYMENTS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.ID IS NULL) THEN
    NEW.ID = GEN_ID(GEN_PAYMENTS_ID,1);
END
^


SET TERM ; ^

Добавляем в MAIN записи (одну, например):

Код: Выделить всё

INSERT INTO MAIN (ID, BALANCE) VALUES (1, 2325);

Здесь можно было не указывать ID и 1, ну да уж как получилось. Далее COMMIT этой транзакции.

В PAYMENTS добавляем одну запись:

Код: Выделить всё

INSERT INTO PAYMENTS (ID, ID_MAIN, MONEY) VALUES (1, 1, 200);

Далее снова COMMIT этой транзакции. Все нормально.
Теперь начинаем транзакцию и обновляем баланс

Код: Выделить всё

update main set balance = balance + 120 where id = 1

Транзакцию пока не завершаем!

Начинаем другую транзакцию (в другом или этом же коннекте) и делаем

Код: Выделить всё

update payments set money = 0 where id_main = 1

Все нормально, ошибок нет. Но, если мы сделаем

Код: Выделить всё

insert into payments (id_main, money) values (1, 0)

То получим ошибку:

Код: Выделить всё

Unsuccessful execution caused by system error that does not preclude successful execution of subsequent statements.
lock conflict on no wait transaction.
violation of FOREIGN KEY constraint "FK_PAYMENTS_1" on table "PAYMENTS".
Foreign key reference target does not exist.

А мне очень хочется что-то подобное делать! Пока что просто убрал foreign key. Это нормальное поведение?

Логика создания новой записи в DM.Karto4ka выглядит несколько странно. Зачем вообще допускать возможность ввода на уровне ввода (модификации) данных карточки кода «не существующего» врача. Исключаются такие ситуации LookUp полями, которые в принципе не позволят ввести несуществующий код.
Далее, если в приложении, тем не менее есть место (или места), в которых может возникнуть исключение, то можно воспользоваться соответствующими событиями наборов данных (допустим, OnPostError, если в компонентах, которыми Вы пользуетесь, предусмотрен такой обработчик) или просто проверять данные и искусственно создавать исключения. Например

Delphi
1
2
  if FILIALSID.IsNull then begin
    raise Exception.Create('Ввод объекта автоматизации невозможен. Не назначен филиал!');

Здесь в обработчике BeforPost проверяется поле FILIALSID и генерируется исключение с текстом сообщения, «понятным» конечному пользователю.
Исключения можно создавать и непосредственно в БД. Например

Oracle 11 SQL
1
CREATE EXCEPTION MANUFACTUREDTCTRL1 'Дата изготовления не может быть БОЛЬШЕ даты получения';

Тогда это исключение можно инициировать, например, в триггерах БД

Oracle 11 SQL
1
2
3
4
5
6
7
CREATE OR ALTER TRIGGER terminalequipment_mnfctrdtctrl FOR terminalequipment
active before INSERT OR UPDATE position 0
AS
BEGIN
  IF ((NEW.manufacturedt IS NOT NULL)AND(NEW.getdate IS NOT NULL)AND
    (NEW.manufacturedt > NEW.getdate)) THEN  EXCEPTION manufacturedtctrl1;
END

Я сделал резервную копию базы данных, а затем я пытаюсь сделать восстановление сейчас, но я получил эту ошибку, когда я делаю восстановление

gbak: ERROR:violation of FOREIGN KEY constraint "FK_WINDOW_4" on table "WINDOW" 
gbak: ERROR:    Foreign key reference target does not exist 
gbak: ERROR:    Problematic key value is ("QUOTE_ID" = 107) 

Я проверил и нашел целевой идентификатор QUOTE_ID = 107 уже существует, так почему я получаю эту ошибку или где я должен смотреть?

2015-09-06 15:20

1
ответ

Была предыдущая ошибка, предшествующая этой, о поле было установлено как not null и в некоторых записях это поле имеет значение null, поэтому, когда я исправил эту ошибку и попытался снова выполнить резервное копирование и восстановление, я не получил больше ошибок.

2015-09-06 15:54

The «ERROR: update or delete on table ‘tablename’ violates foreign key constraint» is a common error message encountered by PostgreSQL users when attempting to modify data in a table that has foreign key constraints. This error occurs when there is a constraint violation between two tables, preventing the user from updating or deleting the desired data. To resolve this issue, the user must either remove the foreign key constraint, update the related data in the referenced table, or find another solution that allows the update or deletion to take place without violating the constraint.

Method 1: Remove Foreign Key Constraint

To remove a foreign key constraint in PostgreSQL, you can use the ALTER TABLE command with the DROP CONSTRAINT option. Here’s an example of how to do it:

-- First, find the name of the foreign key constraint
SELECT constraint_name FROM information_schema.table_constraints
WHERE table_name = 'tablename' AND constraint_type = 'FOREIGN KEY';

-- Then, use the name to drop the constraint
ALTER TABLE tablename DROP CONSTRAINT constraint_name;

Alternatively, you can use the ALTER TABLE command with the DROP CONSTRAINT option and the name of the foreign key constraint directly:

ALTER TABLE tablename DROP CONSTRAINT foreign_key_constraint_name;

Once the foreign key constraint is removed, you should be able to update or delete rows in the table without violating the constraint.

It’s important to note that removing a foreign key constraint can have unintended consequences, such as allowing invalid data to be inserted into the table. Make sure you understand the implications of removing the constraint before doing so.

When you try to update or delete a row in a table that has a foreign key constraint, you may encounter the error message «ERROR: update or delete on table ‘tablename’ violates foreign key constraint». This error occurs because the row you are trying to update or delete is referenced by another table through a foreign key constraint. In order to fix this error, you need to update the related data in the referenced table first. Here’s how you can do it:

Step 1: Find the Foreign Key Constraint

The first step is to find the foreign key constraint that is causing the error. You can do this by running the following query:

SELECT conname FROM pg_constraint WHERE confrelid = 'tablename'::regclass;

Replace ‘tablename’ with the name of the table that is causing the error. This will return the name of the foreign key constraint.

Once you have the name of the foreign key constraint, you can update the related data in the referenced table. Here’s an example:

UPDATE referenced_table SET column1 = new_value WHERE id IN (SELECT referenced_id FROM referencing_table WHERE referencing_id = old_value);

Replace ‘referenced_table’ with the name of the table that is referenced by the foreign key constraint, ‘column1’ with the name of the column that needs to be updated, ‘new_value’ with the new value that you want to set, ‘referencing_table’ with the name of the table that is referencing the foreign key constraint, ‘referenced_id’ with the name of the column in the referencing table that references the primary key of the referenced table, ‘referencing_id’ with the name of the column in the referencing table that contains the old value that you want to update, and ‘old_value’ with the old value that you want to update.

Step 3: Update the Row in the Original Table

After you have updated the related data in the referenced table, you can update or delete the row in the original table without encountering the foreign key constraint error.

UPDATE original_table SET column1 = new_value WHERE id = old_value;

Replace ‘original_table’ with the name of the table that you want to update, ‘column1’ with the name of the column that needs to be updated, ‘new_value’ with the new value that you want to set, and ‘old_value’ with the old value that you want to update.

By following these steps, you can fix the «ERROR: update or delete on table ‘tablename’ violates foreign key constraint» error in Postgresql using «Update Related Data in Referenced Table».

Method 3: Use CASCADE Option for DELETE or UPDATE Statement

To fix the «ERROR: update or delete on table ‘tablename’ violates foreign key constraint» error in PostgreSQL, you can use the CASCADE option for the DELETE or UPDATE statement. This option automatically deletes or updates the dependent rows in the child table when a row in the parent table is deleted or updated. Here’s how to use the CASCADE option:

  1. Create a parent table and a child table with a foreign key constraint:
CREATE TABLE parent (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50) NOT NULL
);

CREATE TABLE child (
    id SERIAL PRIMARY KEY,
    parent_id INTEGER NOT NULL REFERENCES parent(id) ON DELETE CASCADE,
    name VARCHAR(50) NOT NULL
);
  1. Insert some data into the parent and child tables:
INSERT INTO parent (name) VALUES ('Parent 1'), ('Parent 2');

INSERT INTO child (parent_id, name) VALUES (1, 'Child 1'), (2, 'Child 2'), (2, 'Child 3');
  1. Try to delete a row from the parent table that has dependent rows in the child table:
DELETE FROM parent WHERE id = 2;
  1. You will get the «ERROR: update or delete on table ‘parent’ violates foreign key constraint» error. To fix it, use the CASCADE option:
DELETE FROM parent WHERE id = 2 CASCADE;
  1. This will delete the row from the parent table and all the dependent rows from the child table.

  2. You can also use the CASCADE option with the UPDATE statement. For example, if you want to update the id of a row in the parent table that has dependent rows in the child table:

UPDATE parent SET id = 3 WHERE id = 1 CASCADE;
  1. This will update the id of the row in the parent table and all the dependent rows in the child table.

That’s it! Using the CASCADE option for the DELETE or UPDATE statement is an easy way to fix the «ERROR: update or delete on table ‘tablename’ violates foreign key constraint» error in PostgreSQL.

Понравилась статья? Поделить с друзьями:
  • Ошибка word при обработке xml файла
  • Ошибка u2103 00 опель астра h z18xer акпп
  • Ошибка word не удается зарегистрировать данный документ
  • Ошибка video tdr failure windows 10 как исправить
  • Ошибка word при копировании