I'm trying to have a transaction for simple queries written in Navicat Premium, when using a Oracle database:
ALTER TABLE "APPLICATIONS_EXTENSION"
ADD CONSTRAINT "APPLICATIONS_EXTENSION_F01" FOREIGN KEY ("APPLICATION_ID")
REFERENCES "MYDB"."APPLICATIONS" ("APPLICATION_ID")
DEFERRABLE INITIALLY DEFERRED;
UPDATE "APPLICATIONS_EXTENSION" SET "APPLICATION_ID" = 100000; -- Fake ID
UPDATE "APPLICATIONS_EXTENSION" SET "APPLICATION_ID" = 1; -- Good ID
COMMIT;
This should execute fine, since, at COMMIT time, the deferred foreign-key constraint is satisfied.
However, Navicat seems to have auto-commit active, so, right-after the second statement an error is thrown:
> ORA-02091: transaction rolled back
ORA-02291: integrity constraint (MYDB.APPLICATIONS_EXTENSION_F01) violated - parent key not found
I found no way to have auto-commit off, nor an explicit way to start a transaction.
The "Automatically start a transaction" option in the "Records" tab of Navicat Options seems to just apply to table views (as its tab name seemed to indicate).
Related
Assume an employees table like the one in Oracle's HR sample schema. It includes the following:
CREATE TABLE employees
(
employee_id NUMBER(6) NOT NULL PRIMARY KEY,
...
manager_id NUMBER(6)
);
ALTER TABLE employees
ADD CONSTRAINT employee_manager_fk
FOREIGN KEY (manager_id)
REFERENCES employees(employee_id);
I want to prevent a reciprocal relationship: if the employee with id 110 reports to the employee with id 110, I don't want to allow employee 110 to report to employee 100. I want to prevent the following:
employee_id manager_id
100 110
110 100
I don't think this is doable with a constraint, because it would require a subquery. So, I think a trigger is necessary. This is only a concern on an UPDATE as it's impossible to create this situation with a DELETE or INSERT. I've created the following trigger, which does the job:
CREATE OR REPLACE TRIGGER employees_bu_trigger
BEFORE
UPDATE OF manager_id
ON employees
FOR EACH ROW
DECLARE
l_managers_manager_id employees.manager_id%TYPE;
reciprocal_managers EXCEPTION;
-- This prevents ORA-04091: table C##HR.EMPLOYEES
-- is mutating, trigger/function may not see it
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
SELECT manager_id
INTO l_managers_manager_id
FROM employees
WHERE employee_id = :new.manager_id;
IF l_managers_manager_id = :new.employee_id THEN
RAISE reciprocal_managers;
END IF;
EXCEPTION
WHEN reciprocal_managers THEN
-- re-raise the error to be caught by calling code
RAISE_APPLICATION_ERROR(-20102,
'Employees cannot manage each other.');
END;
But I'm worried about the PRAGMA AUTONOMOUS_TRANSACTION; line. That's needed to prevent the ORA-04091 error, but it makes me think there might be some further underlying problem here.
Is this trigger okay or will it have unforeseen negative side effects?
The danger of the PRAGMA AUTONOMOUS_TRANSACTION is that it runs in a separate transaction. So if your active transaction just added a entry and then before committing you do the update, this trigger will not see the inserted record and will allow records that violate your rule. This problem also occurs with other concurrent users (i.e. if user a makes an update in a transaction and user b makes an update the check will pass for both of them, but once they both commit the error state can exist even though both checks passed.)
Also while the example provided does not have this problem (as Oracle's documentation states that A writer never blocks a reader.), there is a danger of deadlocks if you do any writes in the trigger.
It may be possible to refactor your check to be a AFTER trigger without the FOR EACH ROW.
This will eliminate the danger of deadlocks, and of the test passing in the single user case. BUT it will not eliminate the multiuser issue.
Jon Heller's comment on multilevel loops may also be relevant to our specific problem, but any changes to the checks do not impact the issues you were specifically asking about.
I have searched extensively on this and I have found a lot of people asking the question but no answers that included code examples to help me understand.
I'd like to write a transaction (in sql using the command line sqlite3 interface) that performs several update statements, and if any of them fail for any reason, rolls back the transaction. The default behaviour appears to be to roll-back the statement that failed but commit the others.
This tutorial appears to advise that it's sufficient to add begin; and rollback; before and after the statements, but that's not true because I've tried it with deliberate errors and the non-error statements were definitely committed (which I don't want).
This example really confuses me because the two interlocutors seem to give conflicting advice at the end - one says that you need to write error handling (without giving any examples) whereas the other says that no error handling is needed.
My MWE is as follows:
create table if not exists accounts (
id integer primary key not null,
balance decimal not null default 0
);
insert into accounts (id, balance) values (1,200),(2,300);
begin transaction;
update accounts set balance = field1 - 100 where id = 1;
update accounts set balance = field1 + 100 where id = 2;
update accounts set foo = 23; //Deliberate error
commit;
The idea is that none of these changes should be committed.
The sqlite3 command-line shell is intended to be used interactively, so it allows you to continue after an error.
To abort on the first error instead, use the -bail option:
sqlite3 -bail my.db < mwe.sql
If you are executing line by line, then the idea is that you first run these commands:
create table if not exists accounts (
id integer primary key not null,
balance decimal not null default 0
);
insert into accounts (id, balance) values (1,200),(2,300);
begin transaction;
update accounts set balance = field1 - 100 where id = 1;
update accounts set balance = field1 + 100 where id = 2;
update accounts set foo = 23; //Deliberate error
At this point, if you have no errors, you run the commit:
commit;
All the updates should be visible if you open a second connection and query the table.
On another hand if you got an error, instead of committing you rollback:
rollback;
All the updates should be rolled back;
If you are doing it programatically in java you would enclose the updates in a try - catch block, and commit at the end of the try, or rollback inside the catch.
I'm new to sqlite and sql in gerneral so I don't know if my approach is reasonable.
I want to model inventory items that can be created, lent, returned and discarded.
I want to model this using two tables, one for items, containing an id, a name and a reference to the last transaction (created, lent, returned, ...) and a table of transactions containing an id transaction type, date, and a reference to the item.
Since creating only one table leaves the database in an inconsitent state with one table referencing a non existant table I thought of using a transaction to crate both tables at once, and defining the foreign keys as deferrable. Creation of a new item would have to be done together in one transaction with creating a "created" event to leave the database in a consistent state.
The following code gives me the error Query Error: not an error Unable to execute multiple statements at a time in sqliteman on linux.
PRAGMA foreign_keys = ON;
begin transaction;
create table items (
id integer primary key,
name char(30),
foreign key (last_transaction) references transactions(transaction_id) DEFERRABLE INITIALLY DEFERRED
);
create table transactions(
transaction_id integer primary key,
text char(100)
foreign key (item) references items(id) DEFERRABLE INITIALLY DEFERRED
);
commit transaction;
Does my approach make sense at all?
If yes, why does the code not work? (Did I make a mistake somewhere, or is what I'm trying impossible in mysql?)
Note: simply creating the tables in one transaction without the foreign key constraints gives the same error. (Could this be a similar Problem to: this question)
I need to modify all the content in a table. So I wrap the modifications inside a transaction to ensure either all the operations succeed, or none do. I start the modifications with a DELETE statement, followed by INSERTs. What I’ve discovered is even if an INSERT fails, the DELETE has still takes place, and the database is not rolled back to the pre-transaction state.
I’ve created an example to demonstrate this issue. Put the following commands into a script called EXAMPLE.SQL
CREATE TABLE A(id INT PRIMARY KEY, val TEXT);
INSERT INTO A VALUES(1, “hello”);
BEGIN;
DELETE FROM A;
INSERT INTO A VALUES(1, “goodbye”);
INSERT INTO A VALUES(1, “world”);
COMMIT;
SELECT * FROM A;
If you run the script: “sqlite3 a.db < EXAMPLE.SQL”, you will see:
SQL error near line 10: column id is not unique
1|goodbye
What’s surprising is that the SELECT statement results did not show ‘1|hello’.
It would appear the DELETE was successful, and the first INSERT was successful. But when the second INSERT failed (as it was intended to)….it did not ROLLBACK the database.
Is this a sqlite error? Or an error in my understanding of what is supposed to happen?
Thanks
It works as it should.
COMMIT commits all operations in the transaction. The one involving world had problems so it was not included in the transaction.
To cancel the transaction, use ROLLBACK, not COMMIT. There is no automatic ROLLBACK unless you specify it as conflict resolution with e.g. INSERT OR ROLLBACK INTO ....
And use ' single quotes instead of “ for string literals.
This documentation shows the error types that lead to an automatic rollback:
SQLITE_FULL: database or disk full
SQLITE_IOERR: disk I/O error
SQLITE_BUSY: database in use by another process
SQLITE_NOMEM: out or memory
SQLITE_INTERRUPT: processing interrupted by application request
For other error types you will need to catch the error and rollback, more on this is covered in this SO question.
I am currently trying to create an sqlite database where I can import a table from another sqlite database (can't attach) and add some extra data to each column.
Since there is no INSERT OR UPDATE I came up with this:
I was thinking about splitting the data into two tables and join them afterwards so I can just dump the whole import into one table replacing everything that changed and manage the extra data separately since that does not change on import.
The first table (let's call it base_data) would look like
local_id | remote_id | base_data1 | base_data2 | ...
---------+-----------+------------+------------+----
besides the local_id everything would just be a mirror of the remote database (I'll probably add a sync timestamp but that does not matter now).
The second table would look similar but has remote_id set as foreign key
remote_id | extra_data1 | extra_data2 | ...
----------+-------------+-------------+----
CREATE TABLE extra_data (
remote_id INTEGER
REFERENCES base_data(remote_id)
ON DELETE CASCADE ON UPDATE CASCADE
DEFERRABLE INITIALLY DEFERRED,
extra_data1 TEXT,
extra_data2 TEXT,
/* etc */
)
Now my idea was to simply INSERT OR REPLACE INTO base_data ... values because the database I import from has no sync timestamp or whatsoever and I would have to compare everything to find out what row I have to UPDATE / what to INSERT.
But here lies the problem: INSERT OR REPLACE is actually a DELETE followed by an INSERT and the delete part triggers the foreign key ON DELETE which I thought I could prevent by making the constraint DEFERRED. It does not work if I wrap INSERT OR REPLACE in a transaction either. It's always deleting my extra data although the same foreign key exists after the statement.
Is it possible to stop ON DELETE to trigger until the INSERT OR REPLACE is finished? Maybe some special transaction mode / pragma ?
It seems work if I replace the ON DELETE CASCADE part by a trigger like:
CREATE TRIGGER on_delete_trigger
AFTER DELETE ON base_data
BEGIN
DELETE FROM extra_data WHERE extra_data.remote_id=OLD.remote_id;
END;
That trigger is only triggered by a DELETE statement and should solve my problem so far.
(Answer provided by the OP in the question)
Additional info by jmathew, citing the documentation:
When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.
Assuming you only have a single foreign key relationship on a primary key in your referenced table (as you do in your example), this proved to be a fairly painless solution for me.
Simply disable foreign key checks, run the replace query, then enable foreign keys again.
If the replace query is the only query that runs while foreign keys are disabled, you can be assured that no foreign keys will be fouled up. If you are inserting a new row, nothing will have had a chance to be linked to it yet and if you are replacing a row, the existing row will not be removed or have its primary key changed by the query so the constraint will still hold once foreign keys are re-enabled.
SQLlite code looks something like this:
PRAGMA foreign_keys=OFF;
INSERT OR REPLACE ...;
PRAGMA foreign_keys=ON;
What about the reasons of such behavior, there's an explanation from PostgreSQL team:
Yeah, this is per SQL spec as far as we can tell. Constraint checks can
be deferred till end of transaction, but "referential actions" are not
deferrable. They always happen during the triggering statement. For
instance SQL99 describes the result of a cascade deletion as being that
the referencing row is "marked for deletion" immediately, and then
All rows that are marked for deletion are effectively deleted
at the end of the SQL-statement, prior to the checking of any
integrity constraints.