当前位置:网站首页>Talking about acid of database

Talking about acid of database

2022-06-13 08:59:00 xiongpursuit88

One . Business

Definition : Transaction , It's a sequence of operations , These operations are either performed , Either not , It is an indivisible unit of work .

preparation : To illustrate the nature of the transaction ACID principle , We use the case of bank account and fund management to analyze .

   //  Create database 

   create table account(

      idint primary key not null,

      namevarchar(40),

      moneydouble

   );



   //  Two people opened accounts and saved money 

   insert into account values(1,'A',1000);

   insert into account values(2,'B',1000);

Two .ACID

   ACID, In a reliable database management system (DBMS) in , Business (transaction) Should have four characteristics : Atomicity (Atomicity)、 Uniformity (Consistency)、 Isolation, (Isolation)、 persistence (Durability). These are the characteristics of a reliable database . The following will explain these features one by one .

3、 ... and . Atomicity

Atomicity means that a transaction is an indivisible unit of work , Either the operations in the transaction occur , Or none at all .

   1. Case study 

          A to B transfer 100 Yuan 

 20131105115813406







   2. analysis 

Deduction and addition statements in the transaction , Or both , Or they don't do it . Otherwise, if only the deduction statement is executed , Just submitted , If there is a sudden power failure ,A The account has been deducted ,B The account didn't receive the additional payment , It can cause disputes in life .

   3. resolvent 

In the database management system (DBMS) in , By default, one SQL It's a separate business , Transactions are committed automatically . Only explicit use start transaction Start a transaction , To put a block of code in a transaction . It is the responsibility of the database management system to ensure the atomicity of transactions , For this reason, many data sources use logging mechanism . for example ,SQL Server Use a pre written transaction log , Before submitting the data to the actual data page , Write it in the transaction log first .

Four . Uniformity

Consistency means before and after the transaction , The database integrity constraint is not broken . This means that database transactions cannot destroy the integrity of relational data and the consistency of business logic .

   1. Case study 

For bank transfers , Whether the transaction succeeds or fails , It should be ensured that after the end of the transaction ACCOUNT In the table aaa and bbb The total amount of the deposit is 2000 element .

   2. resolvent 

Ensure the consistency of affairs , We can start from the following two levels

   2.1 Database mechanism level 

Consistency at the database level is , Before and after a transaction is executed , The data will conform to the constraints you set ( Unique constraint , Foreign key constraints ,Check Constraints etc. ) And trigger settings . This is due to SQL SERVER Guaranteed . For example, transfer accounts. , You can use CHECK Restrict the sum of two accounts to be equal to 2000 To achieve consistency

   2.2 Business level 

At the business level , Consistency is to maintain business consistency . This business consistency needs to be guaranteed by developers . Of course , A lot of business consistency , It can also be guaranteed by transferring to the database mechanism level .

5、 ... and . Isolation,

When multiple transactions are accessed concurrently , Transactions are isolated , A transaction should not affect the running effect of other transactions .

This means in a concurrent environment , When different transactions manipulate the same data at the same time , Each transaction has its own full data space . Changes made by concurrent firms must be isolated from changes made by any other concurrent firms . When transactions view data updates , The state of the data is either the state of another transaction before it was modified , Or another transaction changes its state , Transactions do not see data in the intermediate state .

stay Windows in , If multiple processes modify the same file, it is not allowed ,Windows In this way, we can ensure the isolation of different processes :

Enterprise development , The most complex problems of transactions are caused by transaction isolation . When multiple transactions are concurrent ,SQL Server Locking and blocking are used to ensure different levels of isolation between transactions . In general , Complete isolation is unrealistic , Complete isolation requires the database to execute only one transaction at a time , This can seriously affect performance . Want to understand SQL Server Protection of isolation in , First, understand how concurrent transactions interfere with each other .

   1. The interaction between transactions 

There are several kinds of interactions between transactions , Respectively : Dirty reading , It can't be read repeatedly , Fantasy reading , Lost update

   1.1 Dirty reading 

Dirty read means that one transaction reads uncommitted data from another transaction , And it's possible to roll back this data ; The following cases , At this point, if the transaction 1 Roll back , be B The account is bound to lose .

20131105115822218

   1.2 It can't be read repeatedly 

Non repeatable reading means , In database access , Two identical queries within a transaction scope return different data . This is caused by the commit of other transaction modifications in the system during query . The following cases , Business 1 It's bound to get confused , I don't know what happened .

20131105115826281

   1.3 Fantasy reading ( Virtual reading )

Fantasy reading , A phenomenon that occurs when a transaction is not executed independently , For example, the first transaction modifies the data in a table , This modification involves all data rows in the table . meanwhile , The second transaction also modifies the data in this table , This modification is to insert a new row of data into the table . that , In the future, the user who operates on the first transaction will find out whether there are any modified data rows in the table , It's like an illusion .

20131105115830531

   1.4 Lost update 

Two transactions read the same record at the same time ,A Change the record first ,B Also modify the record (B I don't know A A modified ),B After submitting the data B The result of the modification covers A Modification results of .

   2. understand SQL SERVER Isolation level in 

Transaction isolation level of the database (TRANSACTION ISOLATION LEVEL) It is a very basic concept in a database . Why is there a transaction isolation level ,SQL Server What transaction isolation levels are implemented on ? The premise of transaction isolation level is a multi-user 、 Multi process 、 Multithreaded concurrent system , In this system, in order to ensure the consistency and integrity of data , We introduced the concept of transaction isolation level , For a single user 、 This problem does not exist for single threaded applications .

In order to avoid the impact between the above transactions ,SQL Server By setting different isolation levels, different degrees of avoidance can be carried out . Because a high isolation level means more locks , At the expense of performance . Therefore, this option is open to users to set according to specific needs . But the default isolation level Read Commited It meets most of the actual needs .

Isolation level

Dirty reading

Lost update

It can't be read repeatedly

Fantasy reading

Concurrency model

Update conflict detection

image

   SQL Server Isolating the impact between transactions is achieved through locks , Stop the above effects by blocking . Different isolation levels are achieved by adding different locks , Cause a blockage to achieve , So at the cost of performance ; The higher the security level , The lower the processing efficiency ; The lower the security level , Efficient .

Usage method :SET TRANSACTIONISOLATION LEVEL REPEATABLE READ

Uncommitted read : No locks are checked or used when reading data . therefore , In this isolation level, uncommitted data may be read .

Read committed : Just read the committed data and wait for other transactions to release the exclusive lock . The shared lock of read data is released immediately after the read operation is completed . Submitted reading is SQL Server The default isolation level of .

Repeatable : Read data as committed read levels , But the shared lock will remain until the end of the transaction .

Serially readable : It works in a way similar to repeatable reading . But it will not only lock the affected data , It will also lock this range . This prevents new data from being inserted into the scope of the query .

6、 ... and . persistence

persistence , It means after the transaction is completed , Changes made by the firm to the database are persisted in the database , It will not be rolled back .

Even if there is any accident, such as power failure , Once the transaction is committed , Then the persistence is saved in the database .

SQL SERVER adopt write-ahead transaction log To ensure durability .write-ahead transaction log It means , Changes to the database in a transaction are made before they are written to the database , First write to the transaction log . The transaction logs are numbered in order (LSN). When the database crashes or the server breaks down , Restart SQL SERVER,SQLSERVER First, the log sequence number is checked , Persist changes that should have been made to the database but not made to the database , This ensures durability .

7、 ... and . summary

The transaction (ACID) Features are created by a relational database management system (RDBMS, Database system ) To achieve . The database management system uses logs to ensure the atomicity of transactions 、 Consistency and persistence . The log records the transaction's updates to the database , If a transaction has an error during execution , According to the log , Undo the update that the transaction has made to the database , Return the database to its original state before executing the transaction .

Database management system adopts lock mechanism to realize transaction isolation . When multiple transactions update the same data in the database at the same time , Only transactions that hold locks are allowed to update the data , Other business must wait , Until the previous transaction releases the lock , Other transactions have the opportunity to update the data

原网站

版权声明
本文为[xiongpursuit88]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270535255198.html