Pragma Autonomous_Transaction :: Explanação Téorica.

Dúvidas, dicas e truques de PL/SQL. Aqui também vão assuntos relacionados a pacotes, triggers, funções, Java-Stored Procedures, etc
Responder
Trevisolli
Moderador
Moderador
Mensagens: 2016
Registrado em: Qua, 12 Jan 2005 3:25 pm
Localização: Araraquara - SP
Abraço,

Trevisolli
OCA Oracle PL/SQL Developer Certified Associate
OCP Oracle Forms Developer Certified Professional
Araraquara-SP

Pessoal, bom dia.

Algum de vocês, poderia estar colaborando, com uma definição teórica, sobre o comando:

Selecionar tudo

PRAGMA Autonomous_Transaction;

????

Motivo: Criamos aqui uma trigger que guarda o usuário que logou na base e horário, e guarda numa tabela de log...

1) Usuário loga, grava em uma tabela (com commit);
2) Esta tabela tem uma trigger (com commit também);

Daí o alerta do banco alega este tipo de transação.

Sei que resolvi, com a sintaxe acima, mas, gostaria de saber o POR QUE?


Muito obrigado mesmo.
Avatar do usuário
dr_gori
Moderador
Moderador
Mensagens: 5024
Registrado em: Seg, 03 Mai 2004 3:08 pm
Localização: Portland, OR USA
Contato:
Thomas F. G

Você já respondeu a dúvida de alguém hoje?
https://glufke.net/oracle/search.php?search_id=unanswered

O PRAGMA AUTONOMOUS TRANSACTION cria uma nova sessao para a rotina. Ou seja, você pode comitar ali dentro sem afetar a primeira sessao. Por isso que é muito util justamente para LOGS, pois, imagine que deu um ERRO que você tem que fazer ROLLBACK geral. Se não fosse com autonomous, ia fazer rollback no LOG também.

Mas aí vai um alerta: Muito cuidado ao ficar criando coisas com P.A.T. pois você pode estar criando um emaranhado disso que poderá levar a bugs dificílimos de solucionar. Em casos de LOG apenas, creio que não há problema. Mas em outras situações, pense bem antes de fazer e principalmente tenha bem documentado.
Trevisolli
Moderador
Moderador
Mensagens: 2016
Registrado em: Qua, 12 Jan 2005 3:25 pm
Localização: Araraquara - SP
Abraço,

Trevisolli
OCA Oracle PL/SQL Developer Certified Associate
OCP Oracle Forms Developer Certified Professional
Araraquara-SP

Muito obrigado, Dr_Gori.

Neste caso, deve ser mesmo FRISADA a utilização.
Até mesmo em outros casos, quando, utilizamos um determinado comando, soluciona nosso problema, mas, não sabemos o POR QUÊ DELE.

Fica aí então a dica e a atenção.
Trevisolli
Moderador
Moderador
Mensagens: 2016
Registrado em: Qua, 12 Jan 2005 3:25 pm
Localização: Araraquara - SP
Abraço,

Trevisolli
OCA Oracle PL/SQL Developer Certified Associate
OCP Oracle Forms Developer Certified Professional
Araraquara-SP

Pessoal, ainda me resta uma dúvida...

Assim que utilizo P.A.T., independentemente do meu Banco ser auto-commit ou não, eu tenho que informar, OBRIGATÓRIAMENTE, meus comandos de controle de transação ??? (commit, rollback)...

Muito obrigado.
Trevisolli
Moderador
Moderador
Mensagens: 2016
Registrado em: Qua, 12 Jan 2005 3:25 pm
Localização: Araraquara - SP
Abraço,

Trevisolli
OCA Oracle PL/SQL Developer Certified Associate
OCP Oracle Forms Developer Certified Professional
Araraquara-SP

Pessoal, achei interessante este link , resolvi postá-lo aqui.

AUTONOMOUS_TRANSACTION Pragma
The AUTONOMOUS_TRANSACTION pragma instructs the PL/SQL compiler to mark a routine as autonomous (independent). An autonomous transaction is an independent transaction started by another transaction, the main transaction. Autonomous transactions let you suspend the main transaction, do SQL operations, commit or roll back those operations, then resume the main transaction. For more information, see "Doing Independent Units of Work with Autonomous Transactions".

Syntax

Text description of the illustration autonomous_transaction_pragma.gif


Keyword and Parameter Description
PRAGMA
This keyword signifies that the statement is a pragma (compiler directive). Pragmas are processed at compile time, not at run time. They do not affect the meaning of a program; they simply convey information to the compiler.

Usage Notes
In this context, the term routine includes

Top-level (not nested) anonymous PL/SQL blocks
Local, standalone, and packaged functions and procedures
Methods of a SQL object type
Database triggers
You cannot use the pragma to mark all subprograms in a package (or all methods in an object type) as autonomous. Only individual routines can be marked autonomous. You can code the pragma anywhere in the declarative section of a routine. But, for readability, code the pragma at the top of the section.

Once started, an autonomous transaction is fully independent. It shares no locks, resources, or commit-dependencies with the main transaction. So, you can log events, increment retry counters, and so on, even if the main transaction rolls back.

Unlike regular triggers, autonomous triggers can contain transaction control statements such as COMMIT and ROLLBACK. Also, unlike regular triggers, autonomous triggers can execute DDL statements (such as CREATE and DROP) using native dynamic SQL.

Changes made by an autonomous transaction become visible to other transactions when the autonomous transaction commits. The changes also become visible to the main transaction when it resumes, but only if its isolation level is set to READ COMMITTED (the default).

If you set the isolation level of the main transaction to SERIALIZABLE, as follows, changes made by its autonomous transactions are not visible to the main transaction when it resumes:

When in the main transaction, rolling back to a savepoint marked before you started an autonomous transaction does not roll back the autonomous transaction. Remember, autonomous transactions are fully independent of the main transaction.

If an autonomous transaction attempts to access a resource held by the main transaction (which cannot resume until the autonomous routine exits), a deadlock can occur. In that case, Oracle raises an exception in the autonomous transaction, which is rolled back if the exception goes unhandled.

If you try to exit an active autonomous transaction without committing or rolling back, Oracle raises an exception. If the exception goes unhandled, the transaction is rolled back.

Examples
In the following example, you mark a packaged function as autonomous:

Selecionar tudo


CREATE PACKAGE banking AS
   ...
   FUNCTION balance (acct_id INTEGER) RETURN REAL;
END banking;

CREATE PACKAGE BODY banking AS
   ...
   FUNCTION balance (acct_id INTEGER) RETURN REAL IS
      PRAGMA AUTONOMOUS_TRANSACTION;
      my_bal REAL;
   BEGIN
      ...
   END;
END banking;

In the example below, you mark a database trigger as autonomous. Unlike regular triggers, autonomous triggers can contain transaction control statements.

Selecionar tudo


CREATE TRIGGER parts_trigger
BEFORE INSERT ON parts FOR EACH ROW
DECLARE
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   INSERT INTO parts_log VALUES(:new.pnum, :new.pname);
   COMMIT;  -- allowed only in autonomous triggers
END;

Fonte: http://www.lc.leidenuniv.nl/awcourse/or ... elems3.htm
Responder
  • Informação
  • Quem está online

    Usuários navegando neste fórum: Nenhum usuário registrado e 19 visitantes