You are on page 1of 101

System z DB2 E0 Training Material

Agenda
DB2 Architecture

DB2 Utilities
DB2 Triggers
Stored Procedures
User Defined functions
DB2 locks and Concurrency

DB2 ARCHITECTURE

DB2 Architecture

IMS
Batch
Application

IMS
Terminal

CICS
Terminal

TSO
Terminal

IMS/DC

CICS

TSO

TSO

IMS
Online
Application

CICS
Online
Application

TSO
Online
Application

TSO
Batch
Application

CAF
Application

DB2
System
Services

Locking
Services

Databases
services

Distributed data
facilities

MVS

DB2 Architecture
DB2 contains a very large number of Internal components.
These could be grouped according to their functionality into four groups
or major components.
They are :
System Services
Locking Services
Database Services
Distributed Data Facilities
Each of these components runs in a separate operating system
(MVS ) address space.

DB2 Architecture ( Contd. )


System Services
Controls connections to other MVS subsystems running under different
address spaces.
e.g.
CICS, TSO etc.
Handles System startup and shutdown.
Manages the System Log
DB2 uses two Active Log datasets. When one Active Log is full, DB2
automatically switches to other Log.

DB2 Architecture ( Contd. )


System Services ( Contd. )
While the second Log Dataset is being written to, the first dataset is
backed up on an Archive Log which is usually a Cartridge or disk.

DB2 maintains two copies of both the Active and Archived Datasets.

DB2 Architecture ( Contd. )


System Services ( Contd. )
It allocates a thread at the beginning of program execution.
Monitors the progress of execution.

DB2 Architecture ( Contd. )


Locking Services
The Locking Services are better known as IRLM (Intersystem
Resource Lock Manager)

IRLM is responsible for the concurrent access to DB2 data through


its locking and deadlock resolving mechanisms.

DB2 Architecture ( Contd. )


Database Services
Database Services are responsible for :
Manipulation of DB2 data structures
Storage, Retrieval and Update of database data.
Preparation of Application Programs for execution.
Allocating resources and subsequent execution of those programs.
This component is responsible for the execution of SQL and
management of buffers

DB2 Architecture ( Contd. )


Database Services ( Contd. )
The various components that implement the functions listed above are
Precompiler
Bind
Runtime Supervisor
Data Manager ( DM )
Buffer Manager ( BM )
Environmental Descriptor Manager (EDM)

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Precompiler :
Input
: The source program written in the host language e.g.
COBOL, PL/I etc. is the input to the Precompiler.
Outputs
: The outputs are the modified Source Program and
DBRMs.
Process
: Precompiler strips out all the embedded SQL
statements from the host language program, replaces
them with host language CALL statements and using the
extracted SQL statements, constructs a Database
Request Module ( DBRM )

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Precompiler ( Contd. )
The inserted CALL statements issue a call to the DB2 Language
Interface Module.
Bind
Input : Source DBRMs constructed by the Precompiler.
Outputs: Package and Application Plan.
Process : There are two distinct stages in which Bind can be used.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Bind ( Contd. )
Bind compiles the DBRMs into a Package.
It then compiles a list of packages into an Application Plan.
The Package and Application Plan are stored in the Directory.
A Package is a compiled form of the Database Requests.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Bind ( Contd. )
Package contains complete information regarding the runtime
access path ( access strategy ) of the SQL statements in the
DBRM.
Thus Bind is really an Optimizing Compiler.
Bind performs the compilation in four steps.
1) Syntax checking
2) Optimization : Bind Optimizer chooses the optimum access path
from the database statistics stored in the various Catalog Tables.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Bind ( Contd. )
a special utility called RUNSTATS is provided for gathering this
statistics. e.g. The optimizer may choose to have a sequential table
scan instead of using an Index defined on a table.
3) Package generation
4) Authorization checking
Bind checks that the owner of the bind is allowed to perform the
operations requested in the SQL statements that constitute the
DBRMs to be bound.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Bind ( Contd. )
If an object is dropped, all Application Plans that were using the
object are marked by DB2 as invalid.

At run-time, when a program requests to load such an invalid plan,


DB2 automatically invokes Bind and the corresponding Application
Plan is rebound to use an alternative access path.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Bind ( Contd. )
However if a new object is created, DB2 does not automatically
start using it.
e.g. If a new Index is defined on a table, all concerned Application
Plans must be explicitly rebound by the developer for DB2 to be
able to use the Index.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Runtime Supervisor
Its job is to oversee the running of the Application Program.
When the runtime supervisor comes across an SQL statement, it
loads the corresponding Application Plan,
and as per the plan requests the Data Manager to perform
appropriate operations.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Data Manager
Performs functions such as search, retrieval and update of data,
index maintenance.
Buffer Manager
Responsible for the physical transfer of data between DASD and
virtual memory.
It keeps the frequently read and updated pages in the main
memory to minimize physical I/Os.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Buffer Manager
The buffer pages that are Least Recently Used
( LRU ) are swapped out first.
It uses techniques such as read ahead buffering for better
performance.

DB2 Architecture ( Contd. )


Database Services ( Contd. )
Buffer Manager
If the required Application Plan is not present in the Bufferpools
at run-time, Buffer Manager loads the Plan and passes control
to the Environment Descriptor Manager.
Environment Descriptor Manager.
The Plan is physically stored as Skeleton Cursor Table or
SKCT and a Package is called a Skeleton Package Table or
SKPT.DB2 loads the copy of this in the EDM pool

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
END EXEC

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
Language Interface
END EXEC Module

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
Language Interface
END EXEC Module
Runtime Supervisor

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
Language Interface
END EXEC Module
Runtime Supervisor
Data Manager

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
Language Interface
END EXEC Module
Runtime Supervisor
Data Manager

Buffer Manager

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
Language Interface
END EXEC Module
Runtime Supervisor
Data Manager

Buffer Manager
EDM Manager

DB2 Architecture ( Contd. )


Source Module
EXEC SQL
.....
Language Interface
END EXEC Module
Runtime Supervisor
Data Manager

Buffer Manager
EDM Manager
Application Plan/Package

DB2 Utilities

DB2-DM-1

DB2 Utilities
RUNSTATS
LOAD
CHECK(INDEX/DATA)

REORG
QUIESCE
COPY
REPORT
MERGECOPY

STOSPACE
COPYTOCOPY
RECOVER

MODIFY (RECOVERY /
Statistics)

REPAIR

DIAGNOSE

UNLOAD Utility

UNLOAD Utility

Following are the tasks of the UNLOAD utility


Unload the data from Image copy data set
Unload the data from multiple partitions in parallel
Select the data by using similar syntax of SQL Select statement
Sample rows by table

Phase Flow
UTILINT

UNLOAD

UTILTERM

UNLOAD Utility

Unload Utility : Example

UNLOAD TABLESPACE DSN8D71A.DSN8S71E


FROM TABLE DSN8710.EMP

UNLOAD TABLESPACE DSN8D71A.DSN8S71E


FROM TABLE DSN8710.EMP
(EMPNO, LASTNAME, SALARY DECIMAL EXTERNAL)

LOAD Utility

Used to load data into one or more tables

Input:
LOAD DATA statement describing the data to be loaded
File containing data
Output:

Loaded table or partition


Discard file of rejected records
Summary reports of errors encountered

Features:
Automatic data conversion between compatible data types
Data loaded in the sequence presented; no sort invoked
Indexes built; duplicates checked

LOAD Utility

UTILINIT

RELOAD

SORT

BUILD

INDEXVAL

ENFORCE

DISCARD

REPORT

LOAD Utility
Example

LOAD DATA INDDN(SYSREC)


RESUME YES
ENFORCE CONSTRAINTS
INTO TABLE TRGD55.PROJ
(PROJNO
POSITION(1)
CHAR(6),
PROJNAME POSITION(8)
VARCHAR,
DEPTNO
POSITION(33) CHAR(3))

Data File contains :


1
8
PROJ01
08training
PROJ02
07Support

33
TRG
SSG

REORG utility

Reorganizes tablespace to reclaim fragmented space and improve access


performance
Alter the physical space parameters for the tablespace
Unload data in a format acceptable by the LOAD utility
Reorganize tablespace or a partition

Input:
Name of tablespace or partition or index to be reorganized

Output:
Reorganized tablespace and / or indexes
Table data in LOAD format

REORG utility
Phase Flow:

UTILINIT
UNLOAD
RELOAD
SORT
BUILD
UTILTERM

REORG utility
Example :
Reorganizing a table space
REORG TABLESPACE DSN8D81A.DSN8S81D
Reorganizing a table space partition.
REORG TABLESPACE DSN8D81A.DSN8S81E
PART 3
SORTDEVT SYSDA
REORG TABLESPACE DSN8D81A.DSN8S81E
PART 3:5
SORTDEVT SYSDA
SHRLEVEL NONE
COPYDDN SYSCOPY

RUNSTATS Utility

Gathers information about data in tablespaces and indexes and updates DB2
catalog.

Use RUNSTATS when

a table is loaded

a table is reorganized

an index is created

extensive modifications done on tablespace

RUNSTATS Utility

RUNSTATS Utility

Input:
Tablespace for which statistics is to be updated / reported

Output:
Report containing new statistics
Updated DB2 catalog tables

Phase Flow:
UTILINIT
RUNSTATS
UTILTERM

RUNSTATS Utility
Example

Updating catalog statistics for a table space while allowing changes

RUNSTATS TABLESPACE DSN8D81A.DSN8S81E


TABLE(ALL) SAMPLE 25
INDEX(ALL)
SHRLEVEL CHANGE

Updating index statistics


RUNSTATS INDEX (DSN8810.XEMPL1)

Updating all statistics for a table space


RUNSTATS TABLESPACE(DSN8D81P.DSN8S81C) TABLE INDEX

Copy Utility

Creates backup copies of a tablespace or a single partition


Reset copy pending status
Two types:
Full image copy
Incremental image copy

Input:
Name of tablespace or partition to be copied

Output:
A sequential dataset containing the imagecopy
SYSIBM.SYSCOPY updated
Copy pending status reset

Copy Utility
Outputs
Creates upto 4 imagecopies
Rows in SYSIBM.SYSCOPY for catalog and SYSUTILX , SYSLGRNX for
direct.
Either FULL or INCREMENTAL
Can generate 2 sets of ics - local and remote set
Used by RECOVER TABLESPACE

Copy Utility
COPY utility FULL

A Full imagecopy with SHRLEVEL REFERENCE is required, to reset the COPY


pending state of a tablespace.
Recommended to take a full imagecopy after a LOAD or a REORG
Page Validation - inconsistencies are checked for.

Example :
COPY TABLESPACE DSN8D81A.DSN8S81E

COPY utility Incremental


For large tables with update rates of 10% or less, an incremented IC maybe faster
than a full IC

FULL NO SHRLEVEL CHANGE

Has to be taken only after a FULL IC


Example:
COPY TABLESPACE DSN8D81A.DSN8S81E FULL NO

Copy Utility
Example

TEMPLATE COPYDS UNIT 3590-1 STACK YES


DSN (SENIMGCP.&DB..&TS..I&IC..D&DATE.)
DISP(NEW,CATLG,CATLG)
LISTDEF COPYLIST
INCLUDE TABLESPACE SEN1T06.*
EXCLUDE TABLESPACE SEN1T06.L9TMZEZQ
COPY LIST COPYLIST COPYDDN(COPYDS)

TEMPLATE COPYDS UNIT SYSDA


DSN (SENIMGCP.&DB..&TS..I&IC..D&DATE.)
DISP(NEW,CATLG,CATLG)
LISTDEF COPYLIST
INCLUDE TABLESPACE SEN1T01.TS261206
COPY LIST COPYLIST COPYDDN(COPYDS)

CHECK Utility
Checks the integrity of DB2 data structures
Checks the referential integrity between two tables and also checks DB2
indexes for consistency

Can delete invalid rows and copies them to a exception table


Use CHECK DATA when loading a table without specifying the ENFORCE
CONSTRAINTS option or after the partial recovery of tablespaces in a
referential set

CHECK Utility
CHECK DATA TABLESPACE DSN8D81A.DSN8S81D
TABLESPACE DSN8D81A.DSN8S81E
FOR EXCEPTION IN DSN8810.DEPT
USE DSN8810.EDEPT
IN DSN8810.EMP
USE DSN8810.EEMP
IN DSN8810.PROJ
USE DSN8810.EPROJ
IN DSN8810.PROJACT USE DSN8810.EPROJACT
IN DSN8810.EMPPROJACT USE DSN8810.EEPA
DELETE YES

REPORT Utility

Report Tablespaceset reports tables and RIs.


Report Recovery gives
Syscopy entries
SYSLGRNX entries for log ranges
Archive log dataset info
DSNUM option for TS /PARTITION
History - CURRENT
Local Site/Recovery site

Example
REPORT RECOVERY TABLESPACE DSN8D81A.DSN8S81E

QUIESCE Utility

Stores a point of consistency for list of tablespaces

Only concurrent read access is allowed for QUIESCE utility

SYSCOPY has ICTYPE Q and Log RBA in SYSIBM.SYSCOPY with timestamp

Run QUIESCE on all RI related tables after a REPORT

Use QUIESCE at time of low activity

Example
QUIESCE TABLESPACE DSN8D81A.DSN8S81D

Mergecopy
The MERGECOPY utility combines multiple incremental image copy data sets
into a new full or incremental image copy data set

NEWCOPY YES creates a full IC

NEWCOPY NO creates an incremental IC

Example:
MERGECOPY TABLESPACE DSN8D81P.DSN8S81C
COPYDDN (COPY1,COPY2)
NEWCOPY NO

Recover
Restore DB2 tablespaces and indexes to a specific instance
Data can be recovered for single page, pages that contain I/O errors, a single
partition or an entire tablespace
Indexes are always recovered from the actual table data, not from image copy
and log data, as in the case of tablespace recovery
Standard unit of recovery is a Tablespace

Explain
This feature can be used to obtain the details about the access paths chosen
by the DB2 optimizer for SQL statements.

Used specifically for performance monitoring.


When EXPLAIN is requested the access paths that the DB2 chooses are put
in coded format into the table PLAN_TABLE, which is created in the default
database.

Explain (contd...)
To EXPLAIN a single SQL statement precede that SQL statement with the
EXPLAIN Command
EXPLAIN ALL SET QUERYNO = integer
FOR SQL statement
The other method is specifying EXPLAIN YES with the Bind command
Then PLAN_TABLE is to be queried to get the required information.

Explain (contd...)
The information provided include the type of access of particular tables used
in the SQL or Package or Plan, the order in which the tables or joined in a
JOIN, whether SORT is required and so on
Since the EXPLAIN results are dependent on the DB catalog, it is better to run
RUNSTATS before running a EXPLAIN

DB2 TRIGGERS

Trigger
Whats Trigger?

Trigger is a defined set of SQL defined for a table that executes when a specified
SQL event occurs.
A trigger defines a set of action and can be activated when a specified SQL
operation
a DELETE, INSERT or UPDATE -- occurs on a table.
Triggers, unlike referential and check constraints, can even be used to update
other tables.

Trigger
Why Triggers ?!
Validate input data
Note that validation of non-transitional data is usually better handled by check and
referential constraints. By contrast, triggers are appropriate for validation of
transitional data, that is, validations which require comparisons between the
value before and after an update operation.
Automatically generate values for newly inserted rows
Read from other tables for cross-referencing purposes
Write to other tables for audit-trail purposes
Support alerts (for example, through e-mail messages)

Trigger

To create a trigger you will need to specify the following

Trigger Name

Triggering Table

Activation (BEFORE / AFTER)

Triggering Event (INSERT, UPDATE, DELETE)

Granularity (row / statement)

Transition Variables (old / new)

Triggered Action

Trigger

Example

CREATE TRIGGER SALARY_UPDATE


BEFORE UPDATE OF SALARY
ON EMP
FOR EACH ROW MODE DB2SQL
WHEN (NEW.SALARY > (OLD.SALARY * 1.5))
BEGIN ATOMIC
SIGNAL SQLSTATE '75001' ('Raise exceeds 50%');
END;

Trigger
Trigger Activation time
SQL Statement

Before

After

SELECT

Yes

Yes

VALUES

Yes

Yes

CALL

Yes

Yes

SIGNAL SQLSTATE

Yes

Yes

SET transition-variable

Yes

No

INSERT

No

Yes

UPDATE

No

Yes

DELETE

No

Yes

Trigger
Trigger Limitations:
Cannot define DB2 triggers on:
a system catalog table
PLAN_TABLE
STATEMENT_TABLE
DSN_FUNCTION_TABLE
View
Alias
Synonym
Any table with a three-part name.

Using Triggers to Implement Referential Integrity

Trigger
Trigger Packages
When a trigger is executed, DB2 creates a trigger package for the statements in
the triggered action.
The trigger package is recorded in SYSIBM.SYSPACKAGE and has the same
name as the trigger and package TYPE =T

To delete the trigger package, you must use the DROP TRIGGER statement

DB2 - User Defined Functions

DB2 - User Defined Functions

What is UDF?
It is procedural functionality added to DB2 by the user. The UDF, once coded and
implemented , users can specify the UDF in SQL statements just like built-in SQL
functions (SUM , AVG ,COUNT etc )
Type of UDF
Based on value return
Scalar functions - applied to a column or expression and operates on a
single value
Table functions - return an entire table

Based on
External UDFS
Sourced UDFS

DB2 - User Defined Functions

Type of UDF

Based on value return

Scalar functions - applied to a column or expression and operates on a single value

Table functions - return an entire table

Based on method of creation


External UDFS
It must be written in a host programming language such as Assembler, C, COBOL, or
PL/I.

Sourced UDFS
It registers a user-defined function that is based on an existing scalar or aggregate
function with a database server.

DB2 - User Defined Functions

External Scalar Function :

Example :
CREATE FUNCTION NTEST1 (SMALLINT)
RETURNS SMALLINT
EXTERNAL NAME 'NTESTMOD'
SPECIFIC MINENULL1
LANGUAGE C
DETERMINISTIC
NO SQL
FENCED
PARAMETER STYLE SQL
RETURNS NULL ON NULL INPUT
NO EXTERNAL ACTION;

DB2 - User Defined Functions

External Table Function :

CREATE FUNCTION DOCMATCH (VARCHAR(30), VARCHAR(255))


RETURNS TABLE (DOC_ID CHAR(16))
EXTERNAL NAME ABC
LANGUAGE C
PARAMETER STYLE SQL
NO SQL
DETERMINISTIC
NO EXTERNAL ACTION
FENCED
SCRATCHPAD
FINAL CALL
DISALLOW PARALLEL
CARDINALITY 20;

DB2 - User Defined Functions

Sourced Functions

CREATE FUNCTION AVE (HATSIZE) RETURNS HATSIZE


SOURCE SYSIBM.AVG (INTEGER);

CREATE FUNCTION MYCENTER (INTEGER, INTEGER)


RETURNS FLOAT
SOURCE SMITH.CENTER (INTEGER, FLOAT);

DB2 STORED PROCEDURE

DB2 Stored Procedure

Stored procedure is program that is sored and executed within control of the
DBMS
It can be executed from local as well as from remote server
Type of stored procedure :
SQL stored procedure : It contains only sql statements
External stored procedure: Wriiten in Host loanguage such as cobol, C , java,
assembler etc

DB2 Stored Procedure


Most Beneficial Uses of Stored Procedures
Improved performance across a network
Security
Availability
Reduced dependency on client code
Reusability
Access to non-DB2 data

DB2 Stored Procedure


Most Common Abuses of Stored Procedures

An overuse of stored procedures often leading to performance problems, especially in high


volume situations.

Use of stored procedures as I/O modules

Use of stored procedures for security or predictable access paths

Blind conversion of stored procedures from another DBMS/platform

Overuse of nesting

Use of DB2 managed SPAS vs. WLM

Converting to stored procedures just in case

DB2 Stored Procedure

SQL Stored Procedure - Example


CREATE PROCEDURE UPDATE_SALARY_1
(IN EMPLOYEE_NUMBER CHAR(10),
IN RATE DECIMAL(6,2))
LANGUAGE SQL
MODIFIES SQL DATA
UPDATE EMP
SET SALARY = SALARY * RATE
WHERE EMPNO = EMPLOYEE_NUMBER

External stored procedure - Example

CREATE PROCEDURE SYSPROC.MYPROC(IN INT, OUT INT, OUT DECIMAL(7,2))


LANGUAGE COBOL
EXTERNAL NAME MYMODULE
PARAMETER STYLE GENERAL
WLM ENVIRONMENT PARTSA
DYNAMIC RESULT SETS 1;

DB2 Stored Procedure

Preparing a stored procedure

1. Pre compile and compile the application.

2. Link-edit the application. Your stored procedure must either link-edit or load
one of these language interface modules: DSNALI / DSNRLI

3. Bind the DBRM to DB2 using the command BIND PACKAGE

4. Define the stored procedure to DB2.

5. Use GRANT EXECUTE to authorize the appropriate users to use the stored
procedure
GRANT EXECUTE ON PROCEDURE SPSCHEMA.STORPRCA TO JONES;

DB2 Stored Procedure


DB2 supplied Stored
procedure

DESCRIPTION

DSNUTILS

Utilities stored procedure for EBCDIC input

DSNUTILU

Utilities stored procedure for Unicode input

DSNACCQC

DB2 UDB Control Center - table space and index information stored procedure

DSNACCAV

Control Center partition information stored procedure

DSNACCOR

Real-time statistics stored procedure

WLM_REFRESH

WLM environment refresh stored procedure

DSNACICS

CICS transaction invocation stored procedure

DSNLEUSR

SYSIBM.USERNAMES encryption stored procedure

DSNAIMS

IMS transactions stored procedure

DB2 Function and Components

DB2 Catalog
Data about data DB2 is managing - Metadata
Stored in DB2 Tables
Can be accessed in the same way as user data

Transactions
SQL Command

Begin Transaction

SQL Command
COMMIT
SQL Command

SQL Command
Error Condition
ROLLBACK

End Transaction
All Changes DONE
Begin Transaction

End Transaction

All Changes UNDONE

Transactions : An example
Account 1
Balance = 2000

Account 2
Balance = 5000

Transaction
Withdraw 1000 from Account 1
Deposit 1000 into Account 2

Account 1
Balance = 1000

Account 2
Balance = 6000

Lost Update Problem


User 1

Send 1000 units

Quantity = 2000

Quantity = 1000

Quantity = 4000

User2

Receive 2000 units

Incorrect Summary Problem

Roll#

Marks

101

80

102

77

103

91

104

64

Percentile

Read
All the
rows
twice

DB2 Concurrency - Locking Mechanism


Lock on data indicates data is being used
Attribute of Locks
Object

: How much data is marked in-use

Duration

: How long is the lock needed

Mode

: How severe is the lock

DB2 Concurrency - Locking Mechanism


There are various classification criteria according to which DB2 locking
mechanism is better understood.
Types of Locks
Lock Promotion / Escalation mechanism
Size of the Locks
Duration of Locks
Types of Locks
Types of Locks
Shared Lock or S Lock
Exclusive Lock or X Lock

DB2 Concurrency - Locking Mechanism


If a transaction FETCHES a record, it is imperative that it has a Shared lock
on it.
If a transaction successfully UPDATES a record, it is imperative that it has
an Exclusive lock on it.
In a FETCH / UPDATE or FETCH / DELETE sequence of operations, a
Shared Lock is promoted to an Exclusive lock.

This promotion happens through Intent locks.

DB2 Concurrency - Locking Mechanism


HOW DB2 SOLVES PROBLEMS OF CONCURRENCY
DB2 employs LOCKING as a concurrency control mechanism.
When a transaction needs an assurance that some database
object, generally a row, will not change in some unpredictable
manner while its back is turned, it acquires a lock on that object.
The effect of the lock is to prevent other transactions from changing
it. The transaction is thus able to carry out processing with the
assumption that the object would remain stable as long as the
transaction wishes it to be.

DB2 Concurrency - Locking Mechanism

Index entries, like database rows, are also subject to locking


DB2 supports two kinds of locks, Shared and Exclusive. Other types exist
but S and X locks are the most important ones. S and X locks are referred
as Read and Write locks.

DB2 Concurrency - Locking Mechanism


Acquiring Locks
1. If transaction A holds X lock on row R, If transaction B requests for
either S or X lock, then B would go into wait state until A releases the
lock
2. If transaction A holds S lock on row R, If transaction B requests for S
lock, then B would be granted the lock, If transaction B requests for X
lock, then B would go into wait state until A releases the lock

DB2 Concurrency - Locking Mechanism


Acquiring Locks (Contd).
3. Transaction requests for row locks are implicit. When a transaction
successfully fetches a row, it acquires an S lock. When a transaction
successfully updates a row, it acquires an X lock. If a transaction holds
an S lock and tries to update the row, it promotes the S lock to X lock.
4. All locks are held until the next syncpoint.

DB2 Concurrency - Locking Mechanism


Size of Locks ( LOCKSIZE Parameter )
LOCKSIZE can be
TABLESPACE
TABLE
PAGE
SUBPAGE ( Only for Indexes )
In general smaller the Locksize, higher is the concurrency.
However as locksize reduces, the absolute number of locks taken
at any time increases, thus using up more virtual memory and CPU.

DB2 Concurrency - Locking Mechanism


Deadlocks
The elaborate locking mechanism solves the concurrency problems
we discussed. However this introduces the possibility of Deadlocks.
A Deadlock is a situation in which two or more transactions are in a
simultaneous wait state, each waiting for the other to release a lock
before it can proceed.
If a deadlock occurs, the system detects it and breaks it. Breaking a
deadlock involves choosing one of the deadlocked transactions as
a victim and either rolling it back or requesting it to roll back.
The rolled back transaction releases the locks thus allowing other
transactions to proceed.

DB2 Concurrency - Locking Mechanism


Deadlocks ( Contd. )
DB2 has a mechanism to resolve a Deadlock situation.
When a Deadlock occurs, DB2 chooses one or more of the contending
transactions as a victim and requests those transactions to release the
locks for the updates of other transactions to go through.
The victim transaction returns a negative SQLCODE.

DB2 Concurrency - Lock Object


PAGE or ROW
Great Concurrency
More Locking overhead
TABLE or TABLESPACE
Less Locking overhead
More data is restricted

DB2 Concurrency Lock Duration


Different options for Application programs
ACQUIRE/RELEASE

ISOLATION LEVEL

DB2 Concurrency - Lock Mode


Shared Data is being Read
Other users can read the same data
Exclusive

Data is being changed


No other users allowed

DEADLOCK
User 1

Lock
Held

Table 1

User 2

Lock

Requested

Lock
Held

Table 2

Failures

Hardware Failure

Program Failure

Natural Calamity

System Log
[ Begin Transaction T1]
[T1, table 1, Page 1, Before Image]
[T1, table 1, Page 1, After Image]
[T1, table 2, Page 3, Before Image]
[T1, table 2, Page 3, After Image]
[ Begin Transaction T2]
[T2, table 3, Page 9, Before Image]
[T2, table 3, Page 9, After Image]
[ End transaction T2]
[ End transaction T1]

Recovery
RECOVER Utility
Tablespace is the unit of recovery

Point of time recovery


Disaster Recovery

Integrity Enforcement
Table Check Constraint
Designates the values that columns of a table can contain
Referential Constraint
The limiting of a set of foreign key values to a set of primary key values.

THANK YOU

You might also like