Autonomous transaction

Autonomous Transaction
Indian PostgreSQL User Group Meetup
Author: Kumar Rajeev Rastogi
Email Id: rajeevrastogi@huawei.com
Cell No: +91-8971367787
Linked-Lin: in.linkedin.com/pub/rajeev-rastogi-krr/23/189/b35/
Contents
• Background
• Why Autonomous Transaction
• About Autonomous Transaction
• Autonomous Transaction Use-cases
• Autonomous Transaction by other DBs
• Conclusion
Background
Transactions are real world entities that can be expressed in the form of text,
numbers or both to be processed by a database management system. They should
make sense as actions against the database and they must be performed as a
group.
For example a request to transfer X amount from user A’s account to user B’s
account is a simple transaction, where debit from A’s account and credit to B’s
account should be performed as a group i.e. either both should be successful or
both should fail.
Other jargons related to transactions are:
1. Transaction Properties
2. Transaction isolation level
3. Sub-transaction
4. Prepare Transaction
Background: Transaction Properties
Transactions have the following four standard properties, usually referred to by the
acronym ACID:
• Atomicity: All changes to data are performed as if they are a single operation. That
is, all the changes are performed, or none of them are.
• Consistency: Data is in a consistent state when a transaction starts and when it
ends.
• Isolation: The intermediate state of a transaction is invisible to other transactions.
As a result, transactions that run concurrently appear to be serialized.
• Durability: After a transaction successfully completes, changes to data persist and
are not undone, even in the event of a system failure..
Background: Transaction Isolation
level
The isolation level of a transaction determines what data the transaction can see
when other transactions are running concurrently. Following are the supported
isolation level in PostgreSQL:
• Read-Committed: A statement can only see rows committed before it began. This
is the default behaviour.
• Repeatable Read: All statements of the current transaction can only see rows
committed before the first query or data-modification statement was executed in
this transaction
• Serializable: All statements of the current transaction can only see rows
committed before the first query or data-modification statement was executed in
this transaction. If a pattern of reads and writes among concurrent serializable
transactions would create a situation which could not have occurred for any serial
(one-at-a-time) execution of those transactions, one of them will be rolled back
with a serialization_failure error
Background: Sub-Transaction
Sub-transaction, as the name suggest is part of main transaction, which is used in
order to take decision on intermediate operation performed inside main
transactions. This is mainly used for below purposes:
• Savepoint: If within a main transaction, you sometime required to rollback some
part of transaction, then we can define a save-point at a point till where rollback
needs to be done. Once a save-point is defined and any operation done with-in
that a new nested transaction called sub-transaction gets started and main
transaction gets pushed to the stack. Once user issues the command to ROLLBACK
SAVEPOINT, subtransaction gets rollbacked without effecting the main transaction
and corresponding changes done to database. Also main transaction get popped
up to continue the further operation.
• Procedure with exception: If there is any procedure with exception handling
defined with-in that means there is failure chance during the execution of
procedure. So in such a sub-transaction gets under which all procedure related
operations are performed and if the failure happens, then this sub-transaction gets
rollbacked without effecting the operation done before procedure call.
There may be multiple level of nested sub-transaction, so once a sub-transaction
rollbacks, it rollbacks all the intermediate sub-transactions also.
Background: Prepare Transaction
PREPARE TRANSACTION prepares the current transaction for two-phase commit.
After this command, the transaction is no longer associated with the current
session; instead, its state is fully stored on disk, and there is a very high probability
that it can be committed successfully, even if a database crash occurs before the
commit is requested.
Each prepare transaction is given a name, which can be used later to commit
or rollback the transactions.
Contents
• Background
• Why Autonomous Transaction
• About Autonomous Transaction
• Autonomous Transaction Use-cases
• Autonomous Transaction by other DBs
• Conclusion
Why Autonomous Transaction
Already so many transaction jargons,
Why do we need one more?
Why Autonomous Transaction
Current form of transaction (called main transaction) in PostgreSQL uses the full
context of transaction i.e. it has control on whole transaction life span and has
visibility to all changes in current transaction.
So it is not possible to commit some part of transaction without effecting
the other part of transaction.
Hence a feature called “Autonomous Transaction” is required to address the
above mentioned issue.
Contents
• Background
• Why Autonomous Transaction
• About Autonomous Transaction
• Autonomous Transaction Use-cases
• Autonomous Transaction by other DBs
• Conclusion
About Autonomous Transaction
An autonomous transaction has its own COMMIT and ROLLBACK scope to ensure that
its outcome does not effect the caller’s uncommitted changes. Additionally, the
COMMITs and ROLLBACK in the calling transaction should not effect the changes that
were finalized on the completion of autonomous transaction itself.
Also calling transaction is suspended until the called transaction
returns control. You can suspend the calling transaction, perform SQL operations and
COMMIT or ROLLBACK them in autonomous transaction, and then resume the calling
transaction.
Autonomous Transaction have the following characteristics:
 The autonomous transaction does not see uncommitted changes made by the
main transaction and does not share locks or resources with main transaction.
 Changes in an autonomous transactions are visible to other transactions upon
commit of the autonomous transactions. Thus , users can access the updated
information without having to wait for the main transaction to commit.
 Autonomous transactions can start other autonomous transaction. There are no
limit, other than resource limits, on how many levels of autonomous transaction
can be started.
About Autonomous Transaction
Contd…
Following figures show how control flows from main transactions (MT) to
autonomous transaction (AT):
Prcoedure proc1
emp integer
Begin
emp = 10
insert …
select … proc2()
Delete …
commit;
End;
Prcoedure proc2
autonomous tx…
dept int
Begin
dept = 20
update …
commit;
End;
MT Begins
MT Ends
MT Suspends
AT begins
AT Ends
MT resumes
Contents
• Background
• Why Autonomous Transaction
• About Autonomous Transaction
• Autonomous Transaction Use-cases
• Autonomous Transaction by other DBs
• Conclusion
Autonomous Transaction Use-cases
Autonomous transaction is useful for many scenarios, some of the top use-cases are
as below:
 Error Logging
 Auditing
Autonomous Transaction Use-cases:
Error Logging
One of the very classic use-cases of autonomous transaction is “Error Logging”.
Say a procedure is defined, which does some operation on the database and
incase of any failure it maintains the failure information in a separate relation. But
because of current transaction behavior, whole data will be roll-backed and hence
error information will be also lost, which might have been required for future analysis.
In order to solve this issue, we can use autonomous transaction as shown
below:
CREATE OR REPLACE function operation(err_msg IN VARCHAR) returns void AS $$
BEGIN
INSERT INTO at_test(id, description) VALUES (998, ‘Description for 998’);
INSERT INTO at_test(id, description) VALUES (999, NULL);
EXCEPTION
WHEN OTHER THEN
PRAGMA AUTONOMOUS TRANSACTION;
INSERT INTO error_logs(id, timestamp, err_msg) VALUES(nextval(‘errno’),
timenow(), err_msg);
COMMIT;
RAISE not_null_violation;
END;
$$ LANGUAGE plpgsql;
Autonomous Transaction Use-cases:
Error Logging Contd…
Schema used in example are:
 Table to store actual data having NOT NULL constraint:
CREATE TABLE at_test(id int, description varchar(100) NOT NULL);
 Error logging table to store error information:
CREATE TABLE error_logs(id int, log_time timestamp, err_msg varchar(100));
 Sequence to maintain error counting:
CREATE SEQUENCE errno;
So above procedure operation is defined in such a way that if insertion to at_test
fails, then it should log the failure information in the error_logs table along with
error number and timestamp at which error happened.
Now lets see below for execution of procedure:
postgres=# select operation(‘failure’);
ERROR: not null violation
STATEMENT: select operation(‘failure’);
ERROR: not_null_violation
Autonomous Transaction Use-cases:
Error Logging Contd…
*After execution of procedure:
Postgres=# select * from error_logs;
id | log_time | err_msg
----+---------------------+---------
5 | 2014-01-17 19:57:11 | error
postgres=# select * from at_test;
id | decsription
----+-------------
(0 rows)
As we can see from procedure definition, on failure, it catches the exception and
starts the autonomous transaction to log error and then it commits only operation
done in autonomous transaction and rest of operation gets roll-backed. As result
shows the error log information still available in error_logs table but other data from
at_test table got roll-backed.
* Result is based on current prototype of autonomous transaction.
Autonomous Transaction Use-cases:
Auditing
Autonomous transaction is useful for auditing purpose also as explained below:
As we can see from above picture, although customer order for item got roll-backed
because of unavailability of items but still customer information’s are committed in
audit table for future use.
MTx Scope ATx Scope
ATx
MTx
MT scope begins the main
transaction, MTx insert buy order
into a table
MTx invokes the autonomous
transaction scope (AT scope).
When AT scope begins, MT scope
suspends
AT updates the audit table with
customer information and
commit.
MTx seek to validate the order,
finds that the selected items are
unavailable, therefore rollback
the main transaction.
Contents
• Background
• Why Autonomous Transaction
• About Autonomous Transaction
• Autonomous Transaction Use-cases
• Autonomous Transaction by other DBs
• Conclusion
Autonomous Transaction by other
DBs
Oracle
• Autonomous Transaction was
supported by oracle starting from
8i version, which was released in
1999.
• An autonomous transaction is
defined in the declaration of
pl/sql block. This can be an
anonymous block, procedure or
trigger.
• This is done by adding the
statement ‘PRAGMA
AUTONOMOUS TRANSACTION;’
anywhere in the declaration
block.
IBM DB2
• Autonomous transaction was
supported by DB2 starting from
9.7 version, which was released in
2009.
• In DB2, autonomous transaction
are implemented through
autonomous procedure.
Autonomous Transaction by other
DBs Contd…
Oracle
• Example:
PROCEDURE test_autonomous IS
PRAGMA AUTONOMOUS
TRANSACTION;
BEGIN
insert…
commit…
END test_autonomous;
IBM DB2
• Example:
CREATE OR REPLACE your_procedure
LANGUAGE SQL AUTONOMOUS
BEGIN
insert…
commit…
END;
Contents
• Background
• Why Autonomous Transaction
• About Autonomous Transaction
• Autonomous Transaction Use-cases
• Autonomous Transaction by other DBs
• Conclusion
Conclusion
 Autonomous Transaction is very useful specifically for auditing (e.g. in retail
sector, banking sector etc) and error logging.
 This feature can be one of very attractive feature while comparing to other open
source database available.
Thank You
1 de 25

Recomendados

Go Faster With Native Compilation por
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native CompilationRajeev Rastogi (KRR)
769 vistas43 diapositivas
Go faster with_native_compilation Part-2 por
Go faster with_native_compilation Part-2Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2Rajeev Rastogi (KRR)
546 vistas44 diapositivas
DataWeave 2.0 - MuleSoft CONNECT 2019 por
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019Sabrina Marechal
1K vistas40 diapositivas
Memento Pattern Implementation por
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern ImplementationSteve Widom
230 vistas7 diapositivas
Data weave 2.0 advanced (recursion, pattern matching) por
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)ManjuKumara GH
3.9K vistas39 diapositivas
Refactoring por
RefactoringRefactoring
RefactoringTausun Akhtary
1.1K vistas89 diapositivas

Más contenido relacionado

La actualidad más candente

Unit 1 por
Unit  1Unit  1
Unit 1donny101
221 vistas48 diapositivas
Unit 3 por
Unit 3Unit 3
Unit 3Abha Damani
256 vistas19 diapositivas
Function in C Programming por
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
165 vistas23 diapositivas
Function & procedure por
Function & procedureFunction & procedure
Function & procedureatishupadhyay
1.3K vistas10 diapositivas
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S... por
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...Dmytro Sokolov
1.3K vistas79 diapositivas
Sql optimize por
Sql optimizeSql optimize
Sql optimizeJainul Khan
354 vistas38 diapositivas

La actualidad más candente(19)

Unit 1 por donny101
Unit  1Unit  1
Unit 1
donny101221 vistas
Function in C Programming por Anil Pokhrel
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel165 vistas
Function & procedure por atishupadhyay
Function & procedureFunction & procedure
Function & procedure
atishupadhyay1.3K vistas
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S... por Dmytro Sokolov
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
Dmytro Sokolov1.3K vistas
Sqlapi0.1 por jitendral
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral384 vistas
Functions in c++ por Maaz Hasan
Functions in c++Functions in c++
Functions in c++
Maaz Hasan3.2K vistas
VB Function and procedure por pragya ratan
VB Function and procedureVB Function and procedure
VB Function and procedure
pragya ratan16.6K vistas
Spring Transaction por patinijava
Spring TransactionSpring Transaction
Spring Transaction
patinijava2.8K vistas
Functions in C++ por home
Functions in C++Functions in C++
Functions in C++
home 3.1K vistas

Similar a Autonomous transaction

chp13.pdf por
chp13.pdfchp13.pdf
chp13.pdfcscmsai54
3 vistas49 diapositivas
Spring Transaction Management por
Spring Transaction ManagementSpring Transaction Management
Spring Transaction ManagementYe Win
2.1K vistas18 diapositivas
DBMS UNIT 4 por
DBMS UNIT 4DBMS UNIT 4
DBMS UNIT 4SURBHI SAROHA
10 vistas53 diapositivas
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx por
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxKoteswari Kasireddy
5 vistas47 diapositivas

Similar a Autonomous transaction(20)

Spring Transaction Management por Ye Win
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
Ye Win2.1K vistas
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx por Koteswari Kasireddy
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Distributed Database Design and Relational Query Language por AAKANKSHA JAIN
Distributed Database Design and Relational Query LanguageDistributed Database Design and Relational Query Language
Distributed Database Design and Relational Query Language
AAKANKSHA JAIN106 vistas
Effective Spring Transaction Management por UMA MAHESWARI
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
UMA MAHESWARI3K vistas
Introduction to transaction processing concepts and theory por Zainab Almugbel
Introduction to transaction processing concepts and theoryIntroduction to transaction processing concepts and theory
Introduction to transaction processing concepts and theory
Zainab Almugbel2.2K vistas
Dbms sixth chapter_part-1_2011 por sumit_study
Dbms sixth chapter_part-1_2011Dbms sixth chapter_part-1_2011
Dbms sixth chapter_part-1_2011
sumit_study5.3K vistas
UNIT-IV: Transaction Processing Concepts por Raj vardhan
UNIT-IV: Transaction Processing ConceptsUNIT-IV: Transaction Processing Concepts
UNIT-IV: Transaction Processing Concepts
Raj vardhan149 vistas
Introduction to transaction processing por Jafar Nesargi
Introduction to transaction processingIntroduction to transaction processing
Introduction to transaction processing
Jafar Nesargi483 vistas
Chapter 9 introduction to transaction processing por Jafar Nesargi
Chapter 9 introduction to transaction processingChapter 9 introduction to transaction processing
Chapter 9 introduction to transaction processing
Jafar Nesargi6.3K vistas

Último

Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue por
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueShapeBlue
218 vistas20 diapositivas
Future of AR - Facebook Presentation por
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook PresentationRob McCarty
64 vistas27 diapositivas
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... por
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...ShapeBlue
106 vistas12 diapositivas
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... por
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...ShapeBlue
161 vistas13 diapositivas
Ransomware is Knocking your Door_Final.pdf por
Ransomware is Knocking your Door_Final.pdfRansomware is Knocking your Door_Final.pdf
Ransomware is Knocking your Door_Final.pdfSecurity Bootcamp
96 vistas46 diapositivas
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... por
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...ShapeBlue
119 vistas17 diapositivas

Último(20)

Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue por ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue218 vistas
Future of AR - Facebook Presentation por Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty64 vistas
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And... por ShapeBlue
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
Enabling DPU Hardware Accelerators in XCP-ng Cloud Platform Environment - And...
ShapeBlue106 vistas
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... por ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue161 vistas
Ransomware is Knocking your Door_Final.pdf por Security Bootcamp
Ransomware is Knocking your Door_Final.pdfRansomware is Knocking your Door_Final.pdf
Ransomware is Knocking your Door_Final.pdf
Security Bootcamp96 vistas
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... por ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue119 vistas
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online por ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue221 vistas
Initiating and Advancing Your Strategic GIS Governance Strategy por Safe Software
Initiating and Advancing Your Strategic GIS Governance StrategyInitiating and Advancing Your Strategic GIS Governance Strategy
Initiating and Advancing Your Strategic GIS Governance Strategy
Safe Software176 vistas
Why and How CloudStack at weSystems - Stephan Bienek - weSystems por ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue238 vistas
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ... por ShapeBlue
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...
Backroll, News and Demo - Pierre Charton, Matthias Dhellin, Ousmane Diarra - ...
ShapeBlue186 vistas
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... por ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue139 vistas
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit... por ShapeBlue
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
Transitioning from VMware vCloud to Apache CloudStack: A Path to Profitabilit...
ShapeBlue159 vistas
The Role of Patterns in the Era of Large Language Models por Yunyao Li
The Role of Patterns in the Era of Large Language ModelsThe Role of Patterns in the Era of Large Language Models
The Role of Patterns in the Era of Large Language Models
Yunyao Li85 vistas
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... por TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc170 vistas
NTGapps NTG LowCode Platform por Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu423 vistas
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading... por The Digital Insurer
Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading...
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue por ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue138 vistas
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... por Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker54 vistas
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ por ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue130 vistas

Autonomous transaction

  • 1. Autonomous Transaction Indian PostgreSQL User Group Meetup Author: Kumar Rajeev Rastogi Email Id: rajeevrastogi@huawei.com Cell No: +91-8971367787 Linked-Lin: in.linkedin.com/pub/rajeev-rastogi-krr/23/189/b35/
  • 2. Contents • Background • Why Autonomous Transaction • About Autonomous Transaction • Autonomous Transaction Use-cases • Autonomous Transaction by other DBs • Conclusion
  • 3. Background Transactions are real world entities that can be expressed in the form of text, numbers or both to be processed by a database management system. They should make sense as actions against the database and they must be performed as a group. For example a request to transfer X amount from user A’s account to user B’s account is a simple transaction, where debit from A’s account and credit to B’s account should be performed as a group i.e. either both should be successful or both should fail. Other jargons related to transactions are: 1. Transaction Properties 2. Transaction isolation level 3. Sub-transaction 4. Prepare Transaction
  • 4. Background: Transaction Properties Transactions have the following four standard properties, usually referred to by the acronym ACID: • Atomicity: All changes to data are performed as if they are a single operation. That is, all the changes are performed, or none of them are. • Consistency: Data is in a consistent state when a transaction starts and when it ends. • Isolation: The intermediate state of a transaction is invisible to other transactions. As a result, transactions that run concurrently appear to be serialized. • Durability: After a transaction successfully completes, changes to data persist and are not undone, even in the event of a system failure..
  • 5. Background: Transaction Isolation level The isolation level of a transaction determines what data the transaction can see when other transactions are running concurrently. Following are the supported isolation level in PostgreSQL: • Read-Committed: A statement can only see rows committed before it began. This is the default behaviour. • Repeatable Read: All statements of the current transaction can only see rows committed before the first query or data-modification statement was executed in this transaction • Serializable: All statements of the current transaction can only see rows committed before the first query or data-modification statement was executed in this transaction. If a pattern of reads and writes among concurrent serializable transactions would create a situation which could not have occurred for any serial (one-at-a-time) execution of those transactions, one of them will be rolled back with a serialization_failure error
  • 6. Background: Sub-Transaction Sub-transaction, as the name suggest is part of main transaction, which is used in order to take decision on intermediate operation performed inside main transactions. This is mainly used for below purposes: • Savepoint: If within a main transaction, you sometime required to rollback some part of transaction, then we can define a save-point at a point till where rollback needs to be done. Once a save-point is defined and any operation done with-in that a new nested transaction called sub-transaction gets started and main transaction gets pushed to the stack. Once user issues the command to ROLLBACK SAVEPOINT, subtransaction gets rollbacked without effecting the main transaction and corresponding changes done to database. Also main transaction get popped up to continue the further operation. • Procedure with exception: If there is any procedure with exception handling defined with-in that means there is failure chance during the execution of procedure. So in such a sub-transaction gets under which all procedure related operations are performed and if the failure happens, then this sub-transaction gets rollbacked without effecting the operation done before procedure call. There may be multiple level of nested sub-transaction, so once a sub-transaction rollbacks, it rollbacks all the intermediate sub-transactions also.
  • 7. Background: Prepare Transaction PREPARE TRANSACTION prepares the current transaction for two-phase commit. After this command, the transaction is no longer associated with the current session; instead, its state is fully stored on disk, and there is a very high probability that it can be committed successfully, even if a database crash occurs before the commit is requested. Each prepare transaction is given a name, which can be used later to commit or rollback the transactions.
  • 8. Contents • Background • Why Autonomous Transaction • About Autonomous Transaction • Autonomous Transaction Use-cases • Autonomous Transaction by other DBs • Conclusion
  • 9. Why Autonomous Transaction Already so many transaction jargons, Why do we need one more?
  • 10. Why Autonomous Transaction Current form of transaction (called main transaction) in PostgreSQL uses the full context of transaction i.e. it has control on whole transaction life span and has visibility to all changes in current transaction. So it is not possible to commit some part of transaction without effecting the other part of transaction. Hence a feature called “Autonomous Transaction” is required to address the above mentioned issue.
  • 11. Contents • Background • Why Autonomous Transaction • About Autonomous Transaction • Autonomous Transaction Use-cases • Autonomous Transaction by other DBs • Conclusion
  • 12. About Autonomous Transaction An autonomous transaction has its own COMMIT and ROLLBACK scope to ensure that its outcome does not effect the caller’s uncommitted changes. Additionally, the COMMITs and ROLLBACK in the calling transaction should not effect the changes that were finalized on the completion of autonomous transaction itself. Also calling transaction is suspended until the called transaction returns control. You can suspend the calling transaction, perform SQL operations and COMMIT or ROLLBACK them in autonomous transaction, and then resume the calling transaction. Autonomous Transaction have the following characteristics:  The autonomous transaction does not see uncommitted changes made by the main transaction and does not share locks or resources with main transaction.  Changes in an autonomous transactions are visible to other transactions upon commit of the autonomous transactions. Thus , users can access the updated information without having to wait for the main transaction to commit.  Autonomous transactions can start other autonomous transaction. There are no limit, other than resource limits, on how many levels of autonomous transaction can be started.
  • 13. About Autonomous Transaction Contd… Following figures show how control flows from main transactions (MT) to autonomous transaction (AT): Prcoedure proc1 emp integer Begin emp = 10 insert … select … proc2() Delete … commit; End; Prcoedure proc2 autonomous tx… dept int Begin dept = 20 update … commit; End; MT Begins MT Ends MT Suspends AT begins AT Ends MT resumes
  • 14. Contents • Background • Why Autonomous Transaction • About Autonomous Transaction • Autonomous Transaction Use-cases • Autonomous Transaction by other DBs • Conclusion
  • 15. Autonomous Transaction Use-cases Autonomous transaction is useful for many scenarios, some of the top use-cases are as below:  Error Logging  Auditing
  • 16. Autonomous Transaction Use-cases: Error Logging One of the very classic use-cases of autonomous transaction is “Error Logging”. Say a procedure is defined, which does some operation on the database and incase of any failure it maintains the failure information in a separate relation. But because of current transaction behavior, whole data will be roll-backed and hence error information will be also lost, which might have been required for future analysis. In order to solve this issue, we can use autonomous transaction as shown below: CREATE OR REPLACE function operation(err_msg IN VARCHAR) returns void AS $$ BEGIN INSERT INTO at_test(id, description) VALUES (998, ‘Description for 998’); INSERT INTO at_test(id, description) VALUES (999, NULL); EXCEPTION WHEN OTHER THEN PRAGMA AUTONOMOUS TRANSACTION; INSERT INTO error_logs(id, timestamp, err_msg) VALUES(nextval(‘errno’), timenow(), err_msg); COMMIT; RAISE not_null_violation; END; $$ LANGUAGE plpgsql;
  • 17. Autonomous Transaction Use-cases: Error Logging Contd… Schema used in example are:  Table to store actual data having NOT NULL constraint: CREATE TABLE at_test(id int, description varchar(100) NOT NULL);  Error logging table to store error information: CREATE TABLE error_logs(id int, log_time timestamp, err_msg varchar(100));  Sequence to maintain error counting: CREATE SEQUENCE errno; So above procedure operation is defined in such a way that if insertion to at_test fails, then it should log the failure information in the error_logs table along with error number and timestamp at which error happened. Now lets see below for execution of procedure: postgres=# select operation(‘failure’); ERROR: not null violation STATEMENT: select operation(‘failure’); ERROR: not_null_violation
  • 18. Autonomous Transaction Use-cases: Error Logging Contd… *After execution of procedure: Postgres=# select * from error_logs; id | log_time | err_msg ----+---------------------+--------- 5 | 2014-01-17 19:57:11 | error postgres=# select * from at_test; id | decsription ----+------------- (0 rows) As we can see from procedure definition, on failure, it catches the exception and starts the autonomous transaction to log error and then it commits only operation done in autonomous transaction and rest of operation gets roll-backed. As result shows the error log information still available in error_logs table but other data from at_test table got roll-backed. * Result is based on current prototype of autonomous transaction.
  • 19. Autonomous Transaction Use-cases: Auditing Autonomous transaction is useful for auditing purpose also as explained below: As we can see from above picture, although customer order for item got roll-backed because of unavailability of items but still customer information’s are committed in audit table for future use. MTx Scope ATx Scope ATx MTx MT scope begins the main transaction, MTx insert buy order into a table MTx invokes the autonomous transaction scope (AT scope). When AT scope begins, MT scope suspends AT updates the audit table with customer information and commit. MTx seek to validate the order, finds that the selected items are unavailable, therefore rollback the main transaction.
  • 20. Contents • Background • Why Autonomous Transaction • About Autonomous Transaction • Autonomous Transaction Use-cases • Autonomous Transaction by other DBs • Conclusion
  • 21. Autonomous Transaction by other DBs Oracle • Autonomous Transaction was supported by oracle starting from 8i version, which was released in 1999. • An autonomous transaction is defined in the declaration of pl/sql block. This can be an anonymous block, procedure or trigger. • This is done by adding the statement ‘PRAGMA AUTONOMOUS TRANSACTION;’ anywhere in the declaration block. IBM DB2 • Autonomous transaction was supported by DB2 starting from 9.7 version, which was released in 2009. • In DB2, autonomous transaction are implemented through autonomous procedure.
  • 22. Autonomous Transaction by other DBs Contd… Oracle • Example: PROCEDURE test_autonomous IS PRAGMA AUTONOMOUS TRANSACTION; BEGIN insert… commit… END test_autonomous; IBM DB2 • Example: CREATE OR REPLACE your_procedure LANGUAGE SQL AUTONOMOUS BEGIN insert… commit… END;
  • 23. Contents • Background • Why Autonomous Transaction • About Autonomous Transaction • Autonomous Transaction Use-cases • Autonomous Transaction by other DBs • Conclusion
  • 24. Conclusion  Autonomous Transaction is very useful specifically for auditing (e.g. in retail sector, banking sector etc) and error logging.  This feature can be one of very attractive feature while comparing to other open source database available.