Docsity

Database Concurrency Control: Issues and Solutions, Study notes of Database Programming

Toggle sidebar
bg1
Database Design
Database Design is a collection of processes that facilitate the designing, development,
implementation and maintenance of enterprise data management systems. Properly designed
database are easy to maintain, improves data consistency and are cost effective in terms of disk
storage space. The database designer decides how the data elements correlate and what data must
be stored.
The main objectives of database designing are to produce logical and physical designs models of
the proposed database system.
The logical model concentrates on the data requirements and the data to be stored independent of
physical considerations. It does not concern itself with how the data will be stored or where it will
be stored physically.
The physical data design model involves translating the logical design of the database onto
physical media using hardware resources and software systems such as database management
systems (DBMS).
Why Database Design is Important?
It helps produce database systems
1. That meet the requirements of the users
2. Have high performance.
Database designing is crucial to high performance database system.
Note, the genius of a database is in its design. Data operations using SQL is relatively simple.
Database development life cycle
The database development life cycle has a number of stages that are followed when developing
database systems.
The steps in the development life cycle do not necessary have to be followed religiously in a
sequential manner.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download Database Concurrency Control: Issues and Solutions and more Study notes Database Programming in PDF only on Docsity!

Database Design

Database Design is a collection of processes that facilitate the designing, development, implementation and maintenance of enterprise data management systems. Properly designed database are easy to maintain, improves data consistency and are cost effective in terms of disk storage space. The database designer decides how the data elements correlate and what data must be stored.

The main objectives of database designing are to produce logical and physical designs models of the proposed database system.

The logical model concentrates on the data requirements and the data to be stored independent of physical considerations. It does not concern itself with how the data will be stored or where it will be stored physically.

The physical data design model involves translating the logical design of the database onto physical media using hardware resources and software systems such as database management systems (DBMS).

Why Database Design is Important? It helps produce database systems

  1. That meet the requirements of the users
  2. Have high performance. Database designing is crucial to high performance database system. Note, the genius of a database is in its design. Data operations using SQL is relatively simple.

Database development life cycle

The database development life cycle has a number of stages that are followed when developing

database systems.

The steps in the development life cycle do not necessary have to be followed religiously in a

sequential manner.

On small database systems, the database system development life cycle is usually very simple and

does not involve a lot of steps.

In order to fully appreciate the above diagram, let's look at the individual components listed in

each step.

Requirements analysis

Planning - This stages concerns with planning of entire Database Development Life Cycle It takes into consideration the Information Systems strategy of the organization.  System definition - This stage defines the scope and boundaries of the proposed database system.

Database designing

Logical model - This stage is concerned with developing a database model based on requirements. The entire design is on paper without any physical implementations or specific DBMS considerations.  Physical model - This stage implements the logical model of the database taking into account the DBMS and physical implementation factors.

Implementation

Data conversion and loading - this stage is concerned with importing and converting data from the old system into the new database.  Testing - this stage is concerned with the identification of errors in the newly implemented system .It checks the database against requirement specifications.

CONCURRENCY

Concurrency Control in Database Management System is a procedure of managing simultaneous operations without conflicting with each other. It ensures that Database transactions are performed concurrently and accurately to produce correct results without violating data integrity of the respective Database.

What is Concurrency Control? Concurrency Control in Database Management System is a procedure of managing simultaneous operations without conflicting with each other. It ensures that Database transactions are performed concurrently and accurately to produce correct results without violating data integrity of the respective Database. Concurrent access is quite easy if all users are just reading data. There is no way they can interfere with one another. Though for any practical Database, it would have a mix of READ and WRITE operations and hence the concurrency is a challenge. DBMS Concurrency Control is used to address such conflicts, which mostly occur with a multi- user system. Therefore, Concurrency Control is the most important element for proper functioning of a Database Management System where two or more database transactions are executed simultaneously, which require access to the same data. Potential problems of Concurrency Here, are some issues which you will likely to face while using the DBMS Concurrency Control method:  Lost Updates occur when multiple transactions select the same row and update the row based on the value selected  Uncommitted dependency issues occur when the second transaction selects a row which is updated by another transaction ( dirty read )  Non-Repeatable Read occurs when a second transaction is trying to access the same row several times and reads different data each time.  Incorrect Summary issue occurs when one transaction takes summary over the value of all the instances of a repeated data-item, and second transaction update few instances of that specific data-item. In that situation, the resulting summary does not reflect a correct result. Why use Concurrency method? Reasons for using Concurrency control method is DBMS:  To apply Isolation through mutual exclusion between conflicting transactions  To resolve read-write and write-write conflict issues  To preserve database consistency through constantly preserving execution obstructions  The system needs to control the interaction among the concurrent transactions. This control is achieved using concurrent-control schemes.  Concurrency control helps to ensure serializability

Example Assume that two people who go to electronic kiosks at the same time to buy a movie ticket for the same movie and the same show time. However, there is only one seat left in for the movie show in that particular theatre. Without concurrency control in DBMS, it is possible that both moviegoers will end up purchasing a ticket.

However, concurrency control method does not allow this to happen. Both moviegoers can still access information written in the movie seating database. But concurrency control only provides a ticket to the buyer who has completed the transaction process first. Concurrency Control Protocols Different concurrency control protocols offer different benefits between the amount of concurrency they allow and the amount of overhead that they impose. Following are the Concurrency Control techniques in DBMS:  Lock-Based Protocols  Two Phase Locking Protocol  Timestamp-Based Protocols  Validation-Based Protocols

Lock-based Protocols Lock Based Protocols in DBMS is a mechanism in which a transaction cannot Read or Write the data until it acquires an appropriate lock. Lock based protocols help to eliminate the concurrency problem in DBMS for simultaneous transactions by locking or isolating a particular transaction to a single user. A lock is a data variable which is associated with a data item. This lock signifies that operations that can be performed on the data item. Locks in DBMS help synchronize access to the database items by concurrent transactions. All lock requests are made to the concurrency-control manager. Transactions proceed only once the lock request is granted. Binary Locks: A Binary lock on a data item can either locked or unlocked states. Shared/exclusive: This type of locking mechanism separates the locks in DBMS based on their uses. If a lock is acquired on a data item to perform a write operation, it is called an exclusive lock.

1. Shared Lock (S): A shared lock is also called a Read-only lock. With the shared lock, the data item can be shared between transactions. This is because you will never have permission to update data on the data item. For example, consider a case where two transactions are reading the account balance of a person. The database will let them read by placing a shared lock. However, if another transaction wants to update that account's balance, shared lock prevent it until the reading process is over. 2. Exclusive Lock (X): With the Exclusive Lock, a data item can be read as well as written. This is exclusive and can't be held concurrently on the same data item. X-lock is requested using lock-x instruction. Transactions may unlock the data item after finishing the 'write' operation. For example, when a transaction needs to update the account balance of a person. You can allows this transaction by placing X lock on it. Therefore, when the second transaction wants to read or write, exclusive lock prevent this operation. 3. Simplistic Lock Protocol This type of lock-based protocols allows transactions to obtain a lock on every object before beginning operation. Transactions may unlock the data item after finishing the 'write' operation.

The Two-Phase Locking protocol allows each transaction to make a lock or unlock request in two steps:

Growing Phase : In this phase transaction may obtain locks but may not release any locks.  Shrinking Phase : In this phase, a transaction may release locks but not obtain any new lock

It is true that the 2PL protocol offers serializability. However, it does not ensure that deadlocks do not happen.

In the above-given diagram, you can see that local and global deadlock detectors are searching for deadlocks and solve them with resuming transactions to their initial states.

Strict Two-Phase Locking Method Strict-Two phase locking system is almost similar to 2PL. The only difference is that Strict-2PL never releases a lock after using it. It holds all the locks until the commit point and releases all the locks at one go when the process is over.

Centralized 2PL In Centralized 2 PL, a single site is responsible for lock management process. It has only one lock manager for the entire DBMS.

Primary copy 2PL Primary copy 2PL mechanism, many lock managers are distributed to different sites. After that, a particular lock manager is responsible for managing the lock for a set of data items. When the primary copy has been updated, the change is propagated to the slaves.

Distributed 2PL In this kind of two-phase locking mechanism, Lock managers are distributed to all sites. They are responsible for managing locks for data at that site. If no data is replicated, it is equivalent to primary copy 2PL. Communication costs of Distributed 2PL are quite higher than primary copy 2PL

Timestamp-based Protocols

Timestamp based Protocol in DBMS is an algorithm which uses the System Time or Logical Counter as a timestamp to serialize the execution of concurrent transactions. The Timestamp-based protocol ensures that every conflicting read and write operations are executed in a timestamp order.

The older transaction is always given priority in this method. It uses system time to determine the time stamp of the transaction. This is the most commonly used concurrency protocol.

Lock-based protocols help you to manage the order between the conflicting transactions when they will execute. Timestamp-based protocols manage conflicts as soon as an operation is created.

Example:

Suppose there are there transactions T1, T2, and T3. T1 has entered the system at time 0010 T2 has entered the system at 0020 T3 has entered the system at 0030 Priority will be given to transaction T1, then transaction T2 and lastly Transaction T3. Advantages :

 Schedules are serializable just like 2PL protocols  No waiting for the transaction, which eliminates the possibility of deadlocks!

Disadvantages: Starvation is possible if the same transaction is restarted and continually aborted Validation Based Protocol Validation based Protocol in DBMS also known as Optimistic Concurrency Control Technique is a method to avoid concurrency in transactions. In this protocol, the local copies of the transaction data are updated rather than the data itself, which results in less interference while execution of the transaction. The Validation based Protocol is performed in the following three phases:

  1. Read Phase
  2. Validation Phase
  3. Write Phase

Read Phase In the Read Phase, the data values from the database can be read by a transaction but the write operation or updates are only applied to the local data copies, not the actual database.

Validation Phase In Validation Phase, the data is checked to ensure that there is no violation of serializability while applying the transaction updates to the database.

Write Phase In the Write Phase, the updates are applied to the database if the validation is successful, else; the updates are not applied, and the transaction is rolled back.

Characteristics of Good Concurrency Protocol An ideal concurrency control DBMS mechanism has the following objectives:  Must be resilient to site and communication failures.  It allows the parallel execution of transactions to achieve maximum concurrency.  Its storage mechanisms and computational methods should be modest to minimize overhead.  It must enforce some constraints on the structure of atomic actions of transactions.

Table 13. Locking Solution to Concurrent Update Problem Time Connection 1 Connection 2 T1 Request book table lock T2 Lock granted Request book table lock

T

select price from book where bookid = "cbronte03"; PRICE

T update book set price=10500. where bookid "cbronte03"; T5 Free book table lock Lock granted

T

select price from book where bookid = "cbronte03"; PRICE

T update book set price=14500. where bookid "cbronte03"; T8 Free book table lock;

Locking In RDM SQL

RDM SQL provides two types of locks. A read ( share ) lock locks a table for read-only access. Any number of different connections can have a read lock on a table. During the time that a table is read locked, no modifications can occur on the table. A write ( exclusive ) lock locks a table for exclusive access by the connection which was granted the write lock. When one connection has been granted a write lock on a table, lock requests from other connections are queued and granted on a first-come, first-served basis.

Queued lock requests do not wait forever. When a lock request has waited for 10 seconds, it will be deleted from the queue and a timeout status code (errTIMEOUT) will be returned. The timeout value for a connection can be changed using the SET TIMEOUT statement as shown below or through a call to function rdm_sqlSetTimeout.

set_timeout_stmt: SET TIMEOUT [TO | =] integer

A timeout value equal to -1 disables timeout checking so that lock calls will wait indefinitely. Timeouts should only be disabled when you are certain that there is no possibility of a deadlock situation arising (see deadlock discussion below). Any non-negative value specifies the number of seconds to wait for the requested table lock(s) to be granted. Setting the timeout to zero means that a lock request will return immediately if the lock cannot be granted.

Only table-level locking is provided in RDM SQL. Table locking is simple and is therefore very efficient but because an entire table is locked at a time, it works best in applications where there are a limited number of concurrent connections. If, however, you keep the duration of your

transactions as short as possible good throughput is achievable for most embedded systems applications.

Lock requests are automatically issued by RDM SQL when needed ( implicit locking ). For example, read locks are requested for each table that is accessed by a SELECT statement. When the locks on all of the needed tables have been granted then statement execution will proceed. If the SELECT statement was executed outside a transaction, the locks are held until the statement handle on which the SELECT is associated (i.e., the cursor ) is closed which occurs automatically after the last row has been fetched. If the SELECT was executed after a transaction has started then the locks will be held until the transaction is either committed or rolled back.

A write-lock is requested by RDM SQL for the tables that are being modified by an INSERT, UPDATE, or DELETE statement. Write-locks are not freed until either a COMMIT or ROLLBACK operation is executed.

Table locks can be explicitly requested by either executing a LOCK TABLE statement or through a call to the RDM SQL API function rdm_sqlLockTables. The syntax for the LOCK TABLE statement is shown below.

If neither READ nor WRITE is specified, then READ is the default outside of a transaction and WRITE is the default inside a transaction. If a read only transaction (see below) is active then the lock request will return an error. Either all lock requests will succeed or none will. I.e, this is an either all or none request which can be used to prevent a deadlock situation in which one process holds a lock on table A while requesting a lock on table B while a second process is holding a lock on table B while requesting a lock on table A.

The system will switch into explicit locking mode on execution of the first LOCK TABLE statement (rdm_sqlLockTables call). In this mode, all tables that are accessed by any subsequent SQL statements must be explicitly locked. If not, SQL will return an errNOTLOCKED status. Note that the values of foreign key columns are retrieved from the referenced row in the primary key table (RDM SQL does not actually store them in the foreign key table). Hence, both the foreign and primary key tables must be explicitly locked when accessing foreign key column values.

This statement will free the READ lock on table tabname or will free all read locks. This can only be executed outside of a transaction. The locks held within a transaction can only be freed through a transaction COMMIT or ROLLBACK.

The SQL system automatically reverts to implicit locking mode when all table locks have been freed.

Read Only Transactions

A read only transaction allows a transaction consistent snapshot of the database to be queried without the need to place locks on the accessed tables. A read only transaction can be explicitly started by executing the following statement.

statement—a transactional stored procedure —then the system will issue a grouped lock request at the start of execution of the stored procedure to acquire all of the locks on all of the tables involved in the modification. The EXECUTE statement (or call to rdm_stmtExecuteProcedure) will return status errTIMEOUT when one or more of the requested locks could not be acquired within the timeout window.

Transactional stored procedures can modify only one database at a time. If you use more than one database at a time, then the modifications for each must be made in separate transactions.

Avoiding Deadlock

A deadlock (also known as deadly embrace ) is an egregious situation that can arise in any system that involves concurrent access to shared data from multiple processes. In its simplest form, process 1 holds an exclusive lock on data item A and is requesting a lock on data item B while at the same time process 2 holds an exclusive lock on data item B while requesting a lock on data item A. As you can easily see, both processes will wait forever unless one or the other releases the lock it holds. Of course, much more complex deadlock scenarios exist that involve multiple processes.

The primary application programming technique available in RDM that can be used to avoid deadlock is the timeout. A lock request will fail if the lock is not granted within the time duration specified by the connection's timeout value. The default timeout is set to 10 seconds. As noted above, this value can be changed using either the SET TIMEOUT statement or through a call to the rdm_sqlSetTimeout function.

While timeouts can be used to avoid deadlock, a related condition known as a livelock can still occur in which, in the example above both of process 1's and process 2's lock requests timeout at the same time, causing each to free the other lock as well and then restart their respective transactions with the timing of the operations such that the same situation continues to repeat itself.

Both livelock and deadlock can be avoided by including in a single request locks on all of the tables (i.e., a grouped lock request) that will potentially be modified by a transaction. As noted in the last section, a transactional stored procedure performs a grouped lock request for all needed locks at the beginning of the transaction, before any modification statements have executed. The table locks included in grouped lock requests made by RDM SQL are always specified in the same order. While a timeout can still certainly occur, neither a deadlock nor livelock situation will occur.

However, if you are issuing dynamic SQL transactions that include multiple database modification statements, you need to explicitly lock all tables that can be modified in the transaction immediately following the START TRANSACTION statement. While not strictly necessary, it is also best to specify the tables in the LOCK TABLE statement in the order in which they are declared in your DDL specification (this is the order in which SQL automatically issues the grouped lock request when a transactional stored procedure is executed). If you do not explicitly lock the tables in a dynamic SQL transaction, SQL will automatically make the lock requests for each statement. If a timeout occurs during execution of a database modification statement, the correct response is to roll back the transaction and then restart it.

It is highly recommended that you encapsulate all of your transactions in transactional stored procedures in order to ensure that deadlock and live lock situations are avoided. It is also recommended that you use read only transactions as much as possible as these will not block other updating processes. Both regular and read only transactions should execute in as short a time frame as possible.

create table sales_order( cust_id char(3) references customer, ord_num smallint primary key, ord_date date key, amount double );

RDM SQL will generate two indexes for each table. The customer table has an index on cust_id and a compound index for cust_geo on state and city. The sales_order table has an index on ord_num and another on ord_date. With this in mind, consider the following query.

select company, ord_num, ord_date, amount from customer natural join sales_order where state = "CO" and ord_date = date "2010-11-23";

Note that this is functionally identical to the query...

select company, ord_num, ord_date, amount from customer, sales_order where customer.cust_id = sales_order.cust_id and state = "CO" and ord_date = date "2010-11-23";

In this second form, two tables will be accessed: customer and sales_order. The first relational expression in the WHERE clause specifies the join predicate, which relates the two tables based on their declared foreign and primary keys. RDM SQL implements foreign and primary key relationships using a bi-directional, direct access method. This means that it is possible to optimally go from 1) the foreign key row to the referenced primary key row and 2) from the primary key row to each row that references it. Note also that the state column in the customer table is the first column in the cust_geo key, and the ord_date column in the sales_order table is the first column in the order_key key. Thus the optimizer has choices of which index to use. All possible execution plans considered by the RDM Server query optimizer for this query are listed in the following table.

Table 1. Possible Execution Plans for Example Query

Plan Description

Scan customer table (i.e., read all rows) to locate rows where state = "CO", then for each matching customer row, scan sales_order table to locate rows that match customer's cust_id and have ord_date = 2010- 11 - 23.

Scan customer table to locate rows where state = "CO", then for each customer row, read each sales_order row through the primary to foreign key join, and return only those that have ord_date = 2010- 11 - 23.

Table 1. Possible Execution Plans for Example Query

Plan Description

Use the cust_geo index to find the customer rows where state = "CO", then for each customer row, scan sales_order table to locate rows that match customer's cust_id and have ord_date = 2010- 11 - 23.

Use the cust_geo index to find the customer rows where state = "CO", then for each customer row, read each sales_order row through the primary to foreign key join, and return only those that have ord_date = 2010 - 11 - 23.

Scan sales_order table to locate rows where ord_date = 2010- 11 - 23 , then for each sales_order row, scan customer table to locate rows that match sales_order's cust_id and have state = "CO".

Scan sales_order table to locate rows where ord_date = 2010- 11 - 23 , then for each sales_order row, read the customer row through the foreign to primary key join, and return only those that have state = "CO".

Use the order_ndx index to find the sales_order rows where ord_date = 2010 - 11 - 23 , then for each sales_order row, scan customer table to locate rows that match sales_order's cust_id and have state = "CO".

Use the order_ndx index to find the sales_order rows where ord_date = 2010 - 11 - 23 , then for each sales_order row, read the customer row through the foreign to primary key join, and return only those that have state = "CO".

Because the time (based on the number of disk accesses) required to scan an entire table is generally much greater than the time needed to locate a row through an index, plans 4 and 8 seem the best. However, it is unclear which of the two plans is optimal. In fact, both are probably good enough to obtain acceptable performance.

Additional information to help you make the best choice includes the number of rows in each table, the number of customers from Colorado, and the number of orders for November 23, 2010. Let's assume that there are 1000 customers and 20,000 sales orders. Thus there is an average of 20 sales orders per customer. Of the 1000 customers, 25 are located in Colorado and 8 sales orders were made on 2010-11-23.

Now let's estimate the number of disk accesses for plan 4. Since all 25 Colorado customers are grouped together in the index for cust_geo (state is the first column in the index) it is likely that no more than 3 index reads are needed to locate them but each of the 25 rows need to be read and then for each customer row its related sales_order rows (average of 20) need to be read and the ord_date checked. That gives a total number of disk accesses as…

Figure 9 - RDM SQL Query Optimization Process

Using the information in the catalog, the SELECT statement is parsed, validated, and represented in a set of easily processed query description tables. These tables include a tree representation of the WHERE clause expressions (called the expression tree) and information about the tables, columns, and keys in the database.

The system then analyzes those tables, and constructs both the access rule table and the expression table. For table that is referenced in the FROM clause, the analysis process uses information in the catalog and other data related statistics such as then number of rows in each table, blocking factors, and column distribution statistics. The access rule table contains a rule entry for each possible access method (for example, table scan or index lookup) for each table. The expression table has one entry for each conditional expression specified in the WHERE clause. These tables drive the actual optimization process.

Finally, the optimizer determines the plan with the lowest total cost. An execution plan basically consists of a series of steps (one step for each table listed in the FROM clause), of how the table in that particular plan step will be accessed. The possible access rules that can be applied at that step are sorted by their cost so that the first candidate rule is the cheapest. The optimizer's goal is to select one access rule for each step that minimizes the total cost of the complete execution plan. As the optimizer iterates through the steps, the cost of the candidate plan is updated. As soon as a candidate plan's cost exceeds the cost of the currently best complete plan, the candidate plan is abandoned at its current step and the next rule for that step is then tested. Conditional expressions that are incorporated into the plan are deleted from the expression tree so that they are not redundantly executed.

Cost-Based Optimization

The cost to determine the execution plan is the time it takes the optimizer to find the "optimal" plan. An execution plan consists of n steps where n is the number of tables listed in the FROM clause. Each step of the plan specifies the table to be accessed and the method to be used to access rows from that table. The cost increases factorially to the number of tables listed in the FROM clause ( n !). Performance impacts start to become noticeable for queries that reference more than about 15-20 tables (this will, of course, vary depending on the speed of your processor). This is due to the increasing number of combinations of access orderings that must be considered (2 tables have 2 possible orderings, 3 have 6, 4 have 24, etc.). The cost to estimate each candidate plan also includes a linear factor of the number of access methods available at each step in a plan from which the optimizer must choose. More access methods means the optimizer must do more work, but the odds of finding a good plan improve.

The cost to carry out an execution plan is the total number of file reads required to access the necessary database information. Because it is extremely difficult to accurately estimate the effects caused by caching performance and diverse database page sizes, physical disk read estimates are not possible. Hence, the system estimates the number of logical file reads based on an analysis of the number required to read a row for each access method.

The statistics maintained for use by cost-based optimizers are used to: 1) guide the choice between alternative access methods derived from the relational expressions specified in the WHERE clause,

  1. estimate the number of output rows that result from each plan step, and 3) estimate the number of logical reads incurred by each possible access method.

The statistics used by the RDM cost-based optimizer include:

 Number of rows in a table

 Number of rows per page in a table (database I/O is performed a page at a time)

 Depth of an index's B-tree

 Number of keys per page in an index

 Distribution counts of common column values

 The range of possible values in a column

 The number of distinct values in a column

The distribution counts of common column values are collected through the execution of the UPDATE STATS statement and provide the optimizer with the most accurate data. For databases on which an UPDATE STATS has not been executed, the last two stats can be specified by the