DB2 9 vs Oracle 10g Admin. Technology

103
© 2008 IBM Corporation IBM Software Group IBM DB2 Open Forum 3 rd DB2 9 vs Oracle 10g Admin. Technology 2008-04-22 Version 2.0 Aug. 20, 2006 Burt Vialpando & Vikram Khatri

Transcript of DB2 9 vs Oracle 10g Admin. Technology

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 9 vs Oracle 10g Admin. Technology

2008-04-22

Version 2.0 Aug. 20, 2006Burt Vialpando & Vikram Khatri

DB2 9 vs Oracle 10g© 2008 IBM Corporation 2

DB2 Information Management

Agenda

DB2 소개 및 개요

DB2 인스턴스 및 CLP

DB2 데이터베이스

DB2 백업 및 복구

DB2 HADR(High Availability Disaster Recovery)

DB2 동시성

Topics

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 소개및개요

9 slides

DB2 9 vs Oracle 10g© 2008 IBM Corporation 4

DB2 Information Management

제품 패키징비교

Oracle● Oracle Lite

Windows CE, Palm, EPOC, Windows 95/98/NT● Oracle Personal Edition

Windows● Oracle Standard Edition

Windows CE, LINUX (2 dist.), AIX, HP-UX, HP Compaq, Solaris, Tru64● Oracle Enterprise Edition

Windows CE, LINUX (2 dist.), AIX, HP-UX, HP Compaq, Solaris, Tru64RAC is an optional purchase feature

DB2● DB2 Everyplace 9

Windows CE, Palm, EPOC, Windows XP/Tablet PC, QNX Neutrino, Symbian, eLinux, Linux on PC● DB2 Express 9

Windows, Linux (200 dist.)● DB2 Workgroup 9

Windows, Linux (200 dist.), AIX, HP-UX, Solaris● DB2 Enterprise 9

Windows, Linux (200 dist.), AIX, HP-UX, Solaris, Linux/390Database Partitioning Feature optional purchase DPF

Try DPF or extenders free with licensing update ability !

DB2 9 vs Oracle 10g© 2008 IBM Corporation 5

DB2 Information Management

DB2 Express-C 9무료라이센스제공

Free to develop, deploy and redistribute*No database size limitNo limit on number of instances per server No user limit

* Free registration required

Production Ready

Same superior data server technology and programming support as DB2 Express Edition in a smaller package

Innovative Technology Developer Friendly

Dedicated team for DB2 community participation & development Free online community supportSkills & applications applicable to all editions of DB2

Workgroup 9 Enterprise 9Express 9/Express-C 9

Linux & Windows, 32 and 64-bit platforms1-2 CPU Server4GB Memory

Linux, UNIX & Windows, 32 and 64-bit platforms1-4 CPU Server16GB Memory

Linux, UNIX & Windows, 32 and 64-bit platformsNo limitsPartitioning feature

DB2 Edition Comparisons

DB2 Express-C 9 is:

DB2 9 vs Oracle 10g© 2008 IBM Corporation 6

DB2 Information Management

동일한코드기반

● 100% Common Code Base Pros & ConsA 100% common code base would

Allow for faster distribution of releases & fixes Give a higher likelihood of identical functionality Give similar installation procedure for all platforms

A 100% common code base would notBenefit from performance & functionality strengths inherent to specific platforms

● Oracle SolutionOracle develops on a few OS’s, then ports to others

● IBM DB2 SolutionDB2 data server has about a 90% common code base for LUW

Varying by about 10% for operating system & hardware differencesAll supported OS versions for LUW released simultaneously

IBM develops on the platforms it supports to optimize the code for themPorting is not done

DB2 z-OS, iSeries and VM/VSE products are a different code baseWhich take advantage of these platforms

DB2 end users & DBAs see little difference externally Mostly for OS considerations

Using DPF on LUW does not require a new code install

DB2 9 vs Oracle 10g© 2008 IBM Corporation 7

DB2 Information Management

툴및제품관리 & 개발툴 & 제품

Image searching, content management• DB2 Relational Extenders • IBM Content Manager (and family

of products which are many)

• Oracle Spatial & Intermedia• Oracle Time Series • COM Cartridge

Stored procedure & other object developmentDB2 Developer Workbench Oracle Procedure Developer

Query & session monitoringDB2 Query Patroller(9.5 Workload Management)

Oracle Progress Monitor

Forms creation, development, usageDB2 Table Editor Developer SuiteOracle Forms Developer

Database event info. collection & analysisDB2 Event Monitor / AnalyzerADDM

Query analysis & visual explains• DB2 Visual Explain• db2exfmt, db2expln

Oracle SQL AnalyzeNode cataloging & connecting, networkingDB2 Configuration AssistantOracle Net Config. Assistant

OS level line oriented database accessDB2 Command Line ProcessorOracle SQL Plus

GUI level line oriented & script saving database access

DB2 Command Editor• Oracle SQL Plus Worksheet

• iSQL

GUI database master console, control, management, auto login, recovery, etc.

• DB2 Control Center• DB2 Web Query Tool• DB2 Recovery Expert• DB2 High Performance Unload• DB2 Performance Expert

• Oracle Enterprise Manager • Enterprise Login Assistant • Database Configuration

Assistant • Administration Assistant

Relational Database Management SystemDB2 Enterprise 9Oracle 10g Enterprise Edition

Description of UsageIBMOracle

DB2 9 vs Oracle 10g© 2008 IBM Corporation 8

DB2 Information Management

툴및제품통신 & 연결툴 & 제품

Internet servicing, connection• WebSphere Portal Studio• IBM Enterprise Information Portal

• Internet Commerce Server• Internet Application Server

Replication, message queuing• MQ Series• DB2 Q Replication• DB2 SQL Replication

• Advanced Replication• Message Broker• Oracle Streams

Federation• DB2 Discovery Link• DB2 Connect, DB2 Relational

Connect • WebSphere Information Integrator

• Oracle Transparent Gateway

• Oracle Access Managers for CICS, IMS, DB2

File system for Internet useData Links ManagerFiles Online (iFS 8i)

Description of UsageIBMOracle

DB2 9 vs Oracle 10g© 2008 IBM Corporation 9

DB2 Information Management

툴및제품인터넷, 자바, 데이터웨어하우징 & OLAP 툴 & 제품

Data mining• DB2 Intelligent Miner • DB2 OLAP Server Miner

• Oracle Data Mining Suite• Oracle Darwin

Reporting in all its forms• QMF • DB2 Web Query Tool for

Multiplatforms

• Oracle Discoverer • Oracle Reports

OLAP, data marts, cubes• DB2 OLAP Server• Data Warehouse Center

• Oracle Express Server • Oracle Express Objects

Metadata sourcingInformation CatalogOne Meaning

Data cleansing Vality IntegrityOracle Pure*Integrate

Data Warehouse building , data movement, management

• DB2 Data Warehouse Manager • DB2 Data Propagator • IBM Data Refresher• WebSphere Inf. Integrator

• Oracle Data Mart Suite• Warehouse Builder

Java & web development & object modeling• Visual Age Family• WebSphere Studio • Net.Data • IBM Content Manager

• JDeveloper • Oracle Designer • Oracle Portal (WebDB) • Oracle Objects

Description of UsageIBMOracle

DB2 9 vs Oracle 10g© 2008 IBM Corporation 10

DB2 Information Management

툴및제품DB2 GUI 로드맵

● Tools that can be started from a command prompt show the command in parenthesis● Most others are accessed through the Control Center & Command Center

LicenseCenter

SmartGuides

or Wizards

VisualExplain

x

DB2 Desktop Folder

WizardsHealth Center(db2hc)

First Steps(db2steps)

x

Information Folder(db2ic)

Command Editor

(db2ce)Satellite

AdministrationCenter

SQL Assist

ToolSettingsActivity

Monitor(db2am)

ConfigurationAssistant(db2ca)

DB2 Command Window

(db2cmd)

Alert Center

Task Center(db2tc)

Journal

Data Warehouse

Center

Replication Center(db2rc)

Development Center(db2dc)

DB2 Command

LineProcessor

(db2)

ControlCenter(db2cc)

DB2 9 vs Oracle 10g© 2008 IBM Corporation 11

DB2 Information Management

툴및제품 –타벤더예Quest Software Support of DB2

Toad™ for DB2Toad™ for DB2 simplifies database development and allows database developers to be more productive by providing an intuitive graphical user interface to DB2. With Toad, developers can use a single, industry-proven tool for both development and DB2 object management.

Quest Central for DB2Quest Central for DB2 is an integrated suite of tools for managing DB2 on Linux, Unix, Windows, and z/OS. Quest Central provides complete database administration, SQL tuning, space management, and performance diagnostics across all platforms from a single console.

Quest SQL Optimizer for DB2SQL Optimizer for DB2 UDB offers complete SQL performance optimization by proactively detecting inefficient SQL and automatically rewriting and selecting best alternatives to maximize performance

Knowledge Xpert™ for DB2Knowledge Xpert™ for DB2 is a comprehensive, Windows-based technical resource designed to give you quick access to expert advice to solve common and complex management issues for DB2 on z/OS and UDB for NT and Unix.

Benchmark Factory®Benchmark Factory is a load testing solution that prevents unplanned downtime and slow performance by testing your system's limits before you go live.

DataFactory®DataFactory populates development, test and QA databases with millions of rows of meaningful, syntactically correct test data, providing you with a realistic view of application performance before going live.

Foglight® Cartridge for Databases - DB2/UDBFoglight is a powerful console that monitors every tier in your critical application technology stacks, including databases, networks, application servers, process schedulers and Web servers, alerting you to problems before they impact end users. This cartridge provides 24x7 monitoring for complex DB2/UDB database environments.

Spotlight® on DB2Spotlight® on DB2 diagnoses DB2 UDB and z/OS performance problems in real time by graphically displaying all database activity in an intuitive user interface, enabling you to respond quickly to issues that need attention.

DB2 9 vs Oracle 10g© 2008 IBM Corporation 12

DB2 Information Management

DB2 개발연구소

Toronto Boeblingen

Somers

Rochester Rochester

Menlo Park, Oakland, Portland, Silicon Valley

Menlo Park, Oakland, Portland, Silicon Valley

Denver

Hawthorne Research

Development 3,000+Sales / Mktg. 3,000+Partners 16,000+

Almaden ResearchAlmaden Research

Lenexa

Over 6,000 Strong WWData Management Research Strong Partnering

Over 6,000 Strong WWData Management Research Strong Partnering

Yamato Yamato

Austin Austin

DB2 9 vs Oracle 10g© 2008 IBM Corporation 13

DB2 Information Management

DB2 HistoryOn Linux, Unix and Windows (LUW)

V1.x 1993► OS/2 and AIX platform► Low-end OLTP

V2.x 1995► Multiple platforms► Capacity and performance► JDBC► UDTs, UDFs, LOBs► Low-end OLTP

V5.x 1997► SMP and MPP parallelism► Data Links Manager► SQLJ► Initial OLAP SQL

V6.1 1999► DB2 for Linux► DB2 Satellite Edition► Ease of Use► Ease of Application Development► Performance

V7.x 2000► Integration Warehousing► Integrated OLAP► Federated databases► Native OLE DB Client► Spatial extender► XML extender► Abstract Data Types► SQL stored procedures► TPC-H Leadership

V8.1 2003, V8.2 2005► Multidimensional Clustering► SMART technology► Expanded Linux support► Online utilities► Advanced BI, CubeViews► TPC-C leadership► Information Integration► SAP Optimization

V9.1 2006, V9.5 2007► Self Tuning Memory ► Automation automatically► Advanced SQL► Data Compression

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 인스턴스및 CLP

25 slides

DB2 9 vs Oracle 10g© 2008 IBM Corporation 15

DB2 Information Management

DB2 인스턴스개요

● 인스턴스 = Database Manager● 인스턴스가하는일:

데이터베이스메모리사용을위한디폴트값 -예:Utility impact limitsSort, hash, Java and other “heap” limits and defaults

모니터링

HealthSnapshot

감사기능

진단및 & 통지내용로깅연결관리

User authenticationCommunication protocolsAgents & pooling managementTransaction management (aka “sessions” in Oracle-speak)

연합데이터베이스 기능제어

분산트랜잭션관리

DB2 9 vs Oracle 10g© 2008 IBM Corporation 16

DB2 Information Management

Oracle SID

Database proddb1

Control files

Parameterfile

Passwordfile

Archived log file

DatafilesData

files

Redologfiles

서버프로세스아키텍쳐The Oracle SID

● An Oracle SID (or unique instance name) can 하나의데이터베이스만허용

● 인스턴스 = 물리적인구조를액세스하기위한논리적인메모리구조● 데이터베이스 = 물리구조● 인스턴스와데이터베이스용어가동일하게사용

그러나기술적으로다른의미

SET ORACLE_SID = inst1SQLPLUS> connect internalSQLPLUS> startup

DB2 9 vs Oracle 10g© 2008 IBM Corporation 17

DB2 Information Management

DB2 Instance

Database proddb1

Database proddb2

Catalog

Catalog

Log

Log

DBconfig

DBconfig

Buffer Pools

Buffer Pools

DBMconfig

서버프로세스아키텍처The DB2 Instance

● A DB2 instance can하나이상의데이터베이스허용

대부분운영시스템은하나의데이터베이스사용

● A DB2 instance is a logical access to The databases logical structuresThen to the databases physical structures

● In a DB2 instance 프로세스는데이터베이스들간공유

인스턴스구성변수(dbm cfg)가모든데이터베이스에공유각각의데이터베이스는각자의데이터베이스구성변수(db cfg)를소유

● DB2 terms "instance" & "database" have distinct meanings & purposes

SET db2instance = inst1db2start

DB2 9 vs Oracle 10g© 2008 IBM Corporation 18

DB2 Information Management

서버프로세스아키텍처Oracle Processes List (Not Exhaustive)

P4P3

P2P1

•can be many

Change Tracking Writer – RMAN supportCTWRRecovery Writer - Flashback supportRVWR

Memory Manager - SGA memory brokerMMAN

Automatic Storage Management - related processes are ASMB, ARB, RBALASM

Memory Monitor Light - Transfer statistics AWR collects to diskMMNLMemory Monitor – AWR problem detection and self tuningMMOM

Server processes - Either dedicated or shared, performs requests for the clientServerN/A

Queue monitor for advanced queuingQMNn *

Dispatchers - for shared server, & Shared Sever processesDnnn * &Snnn*

Inter-instance locking - for multiple instances for one database (RAC mode)LCKn *Snapshot & job schedulerSNPn *Archive log monitor - Writes logs to archive areas (in ARCHIVE LOG mode)ARCn *Resolve for distributed databases - (DISTRIBUTED_TRANSACTIONS mode)RECO

Check point – Flushes modified data from the buffer cache to the disk and updates the control file and data files by doing a header update (DBWn actually does the write)

CKPT

Space monitor - Space maintenance & crash recovery agentSMONProcess monitor - Cleans up failed user processes and frees of resources of these processesPMONDatabase writer - Writes the dirty buffers from the database buffer cache to the data file(s)DBWn *

Log Writer - Performs sequential writes from the redo log buffer in the SGA to the redo log file(s)LGWR

PurposeProcessLevel

DB2 9 vs Oracle 10g© 2008 IBM Corporation 19

DB2 Information Management

* can be many

서버프로세스아키텍처DB2 Processes List (Not Exhaustive)

MMMLHealth Monitor processdb2fmp

Either a process or thread, depending upon the OS

Page & buffer pool cleanerPre-fetcherArchive log monitorDeadlock detectionLogger - manipulates log files to handle transaction processing & recovery

TCP/IP communication listener, & other listeners (depending upon which protocols are specified in the DB2COMM variable)

Parallel system controller - handles parallel requests from remote nodes (DPF)Fast communications manager daemon - handles inter nodal communication (DPF)Inter-process listener - handles local client programs (DPF)Pre-allocates log files for database with log retain set on (Archive Log)Invokes user exits to archive or retrieve log files (Archive Log)Re-sync agent - scans the global re-sync list

Watchdog - UNIX systems only, handles abnormal terminationGlobal daemon spawner - UNIX systems onlySystem controller - exists for the database server to function

Purpose

ARCndb2uext2db2pfch0 *

DBWn & MMML

db2pclnr1

LGWRdb2loggrDatabasedb2dlock

Serverdb2agent *Application

db2tcpcm, & others *

db2pbcdb2fcmdm

Serverdb2ipccmdb2dartdb2cartdb2resyn

PMON & SMON

db2wdogdb2gdsdb2syscInstance

Like?ProcessLevel

P4P3

P2P1

DB2 9 vs Oracle 10g© 2008 IBM Corporation 20

DB2 Information Management

서버프로세스아키텍처DB2 Process Model

1. 클라이언트프로그램은리스너를통해 Coordinator agent를할당받음2. 연결요청은 coordinator agent를통해이루어짐3. db2fmp는 fenced SPs / UDFs실행

P4P3

P2P1

DB2 9 vs Oracle 10g© 2008 IBM Corporation 21

DB2 Information Management

System Global Area (SGA) - 서버 프로세스간 통신, statement cache, redo log buffers, data buffer cacheProgram Global Area (PGA) -응용프로그램과데이터베이스간통신User Global Area (UGA) - user context & row-cached cursors

메모리구조Oracle

Control Structures

Library Cache

Dictionary Cache

Fixed SGA Variables

Parameters

Data Buffers

Enqueues

Latches

Fixed Tables

Redo Buffers

Statistics

State Objects

Events

Shared Pool

SGALarge Pool (optional)

Java Pool (optional)

PGA

Stack Space

Session Info

Sort Area

DB2 9 vs Oracle 10g© 2008 IBM Corporation 22

DB2 Information Management

Database Manager Shared Memory-인스턴스 공유메모리Database Shared Memory -데이터베이스공유메모리Application Shared Memory -응용프로그램공유메모리Agent Private Memory -에이전트정보: sort heaps, cursor info & session contexts

메모리구조DB2

Database Manager Shared Memory

Buffer PoolsbuffpageUtility Heap

util_heap_sz

backbufsz

restbufsz

dbheap

logbufsz

Catalog catalog_cache_sz

Extended Memory Cache

Locklists Shared Sort Memorypckcachesz

Database Shared Memory

buffer pool

Application Global Memoryapp_ctl_heap_sz

stmtheap

stat_heap_sz applheapsz

sortheap

udf_mem_sz

agent_stack_sz

drda_heap_szquery_heap_sz

rqrioblk

Agent & App Shared Memory

aslheapsz

Local Client

Application Shared Memory

rqrioblk

Remote Client

Agent Private Memory

buffer pool buffer pool buffer pool

estore_seq_sz

locklist

Monitor Heap mon_heap_sz Audit Buffer audit_buf_sz

DB2 9 vs Oracle 10g© 2008 IBM Corporation 23

DB2 Information Management

중요파일들Oracle Manually Handled

● Oracle has a control file(s) whichOracle 복구에필수파일하나이상의복사본을관리

별도백업필요

Painstakingly maintained (e.g. ALTER DATABASE BACKUP CONTROL FILE TO ...)● Oracle has parameter files which

인스턴스시작을위한필수파일

OS버전에따라하나이상존재가능혼란가능성

별도백업필요 / painstakingly maintained재생성가능하나번거로움Oracle 9i does have a new "server parameter file" (SPFILE) option... are you using it?

Still requires a PFILE for database creation

● Oracle has a security (password) file which리모트데이터베이스관리를위한파일

OS에따라하나이상의버전이존재가능 –혼란가능성별도백업필요 / painstakingly maintained재생성가능

Controlfile

Securityfile

Key Oracle filesKey Oracle files

Parameterfiles

DB2 9 vs Oracle 10g© 2008 IBM Corporation 24

DB2 Information Management

중요파일들DB2 Automatically Handled

● 각데이터베이스당 Control 및 parameter 파일들이존재함데이터베이스의스스로자동다중관리:

SQLBP.1 & 2 (buffer pool info)SQLSPCS.1 & 2 (table space info)SQLOG* (log control files)SQLDBCON & F (db configuration)db2rhist.asc & .bak (recovery history file)

Backup명령에의해자동백업됨.Restore / Recover 명령에의해자동복구됨

● 별도의백업가능dbm cfg파일(“db2system”) (or the entire subdirectory it is in)Registry 파일 (db2set)

● DB2 가정 -설치및관리자기본적으로쉬운유지관리를하도록

기술력과 OS에대한지식이그다지높지않아도가능하게나중에원하는바대로조정하고보다복잡하게구성하도록

DB2 9 vs Oracle 10g© 2008 IBM Corporation 25

DB2 Information Management

Oracle 디렉토리구조Windows Example (Using OFA)

\oracle

\product

\10.1.0

\admin

\mydb1

\bdump

\cdump

\create

\pfile

\udump\db_1

\admin

\network

ORACLE_BASE

Product directory

ORACLE_HOME

\bin

Database

listener.ora tnsnames.ora sqlnet.ora, etc.sqlplus.exe

sqlldr.exerman.exe, etc

DB2 9 vs Oracle 10g© 2008 IBM Corporation 26

DB2 Information Management

DB2 디렉토리구조Windows Example

SQLTAG.NAM. This file marks the subdirectory as being in use SQL*.BKM (contains block allocation information if it is an MDC table) SQL*.LF (contains LONG VARCHAR or LONG VARGRAPHIC data) SQL*.LB (contains BLOB, CLOB, or DBCLOB data) SQL*.LBA (contains allocation and free space information about SQL*.LB files) SQL*.INX (contains index table data) SQL*.IN1 (contains index table data), etc.

db2start.exedb2stop.exe db2cmd.exe, etc.

\DB2

\node0000

\sql00001

Instance Name

Partition number (note: in ESE non DPF databases are a single node implementation)

Database ID

Default LOG directory

SYSCATSPACE table space (always created)

TEMPSPACE1 table space (always created)

USERSPACE1 table space (always created)

\SQLOGDIR

\SQLT0000.0

\SQLT0001.0

\SQLT0002.0

\mysmsts

\mydmsts.dat

\program files

\IBM

\sqllib

DB2 9 vs Oracle 10g© 2008 IBM Corporation 27

DB2 Information Management

환경 / 레지스트리변수

Variable Functionora_cwdora_sid_pfile oracle_home oracle_sidoracle_basenls_langrdbms_archiverdbms_controlsqlpath

Current Oracle directoryPath to init.ora fileEnvironment where products runDefault Instance (SID)Root of the Oracle directory treeLanguage, character & territory setLocation of backup database filesLocation of backup database control filesLocation of SQL scripts

Variable Functiondb2adminserverdb2commdb2includedb2instance (e)db2instdefdb2ownerdb2slogondb2path (e)db2system

Specifies which instance runs the admin. serverStarted communications managerPath to include in SQL searchesCurrent instanceDefault instanceInstance owning machineEnables secure logonDirectory where product is installedServer name id

● DB2 환경변수Use of the DB2 profile registry allows for changes without a system rebootUse db2set or use the Configuration AssistantDB2 environment variables (OS controlled) are: db2path, db2instance

● Oracle 환경변수

DB2 9 vs Oracle 10g© 2008 IBM Corporation 28

DB2 Information Management

DB2는 50개이상의변수가변경즉시반영됨 !

INIT.ora 와 DB2 파라미터

SQLBP.1, SQLSPCS.1, SQLOG*, SQLDBCON, db2rhist.asc. Multiple files in DB2 perform this functionality.

no equivalent parm neededcontrol_files

CommentsDB2 9 EquivalentOracle 10ginit.ora parm

Defined when database is created. pagesizedb_block_size

Number of asynchronous page cleaners. db cfg parm.num_iocleanersdb_writer_processes

With DB2 the database name is defined with create database command and not by a config parm. You can see the name (and provide aliases for that name) with the db2 catalog command and/or the db2 list database directory command.

no equivalent parm neededdb_name

DB2's buffer pool algorithm is more advanced (not just LRU) so you don't need to specify recycle pools.

no equivalent parm neededdb_recycle_cache_size

To have data pages kept in memory, create a buffer pool specifically for tables you want to pin.

no equivalent parm neededdb_keep_cache_size

Maximum open files. dbm cfg parm.maxtotfilopdb_files

Specifies where to change the log files location. db cfg parm.newlogpathndb_create_online_log_dest_n

Same as above.no equivalent parm neededdb_block_checksum

DB2 uses consistency bits to maintain page level integrity. This performs better then checksum page checking. Cannot be turned off.

no equivalent parm neededdb_block_checking

Same as above. If no buffer pools are created then use buffpage db cfg parm.

no equivalent parm neededsee: buffpage

db_block_buffers

Create as many buffer pools as you want of any page sizeno equivalent parm neededdb_nk_cache_size

DB2 9 vs Oracle 10g© 2008 IBM Corporation 29

DB2 Information Management

INIT.ora vs. DB2 Parameters(Continued)

DB2 has a global size for all sorts and hash joins using sortheap db cfg parm.

no exact equivalent -see: sortheap

sort_area_sizehash_area_size

No shared pool in db2. The closest parm would be the dbheap db cfg parm.

no exact equivalent -see: dbheap

shared_pool_size

DB2 locks are held in memory & are a set of db cfg parms for sizing this lock information.

no exact equivalent -see: locklist & maxlocks

dml_locks

CommentsDB2 9 EquivalentOracle 10ginit.ora parm

Specifies the size of the log buffer. db cfg parm.logbufszlog_buffer

Path to diagnostic dump data. dbm cfg parm.diagpathuser_dump_dest

Maximum number of concurrently connected applications. dbm cfg parm.

maxcagentssessions

Specifies the degree of parallelism to use if you want to override DB2s autonomics. db cfg parm.

dft_degreeparallel_max_server

The DB2 optimizer is fully cost based so there are no system level modes. The one exception is the dft_queryopt db cfg parm which indicates how much optimization DB2 should do.

no exact equivalent -see: dft_queryopt

optimizer_*

Checkpointing. db cfg parm.softmaxlog_checkpoint_interval

db cfg parm.logarchmeth1log_archive_dest

Specifies the port DB2 will listen on. dbm cfg parm.You must also specify the protocol as a registry variable.

svcenamedb2comm

local_listener

dbm cfg parm.java_heap_szjava_pool_size

DB2 9 vs Oracle 10g© 2008 IBM Corporation 30

DB2 Information Management

CLP 모드

● CLP는 3가지모드지원

● The command modeIs invoked from an OS shell window with db2cmd [return]

db2cmd.exe is an extension of the Windows OS shellInvokes OS commands directlyInvokes DB2 commands with db2 “db2-command”

● The batch modeIs like running Command Window commands en-masse

● The interactive modeIs invoked from the Command Window with db2 [return]Requires a ! to invoke OS commands

OS prompt, prefaced with a db2 before each commandCommand

OS prompt, db2 and an -f option to designate the input fileBatch

CLP prompt, default of which is db2 =>Interactive

Noted ByMode

DB2 9 vs Oracle 10g© 2008 IBM Corporation 31

DB2 Information Management

CLP 도움말C:\ db2 ?

db2 [option ...] [db2-command | sql-statement |[? [phrase | message | sqlstate | class-code]]]

option: -a, -c, -e{c|s}, -finfile, -lhistfile, -o, -n, -p, -rreport, -s,-t, -td;, -v, -w, -x, -zoutputfile.

db2-command:ACTIVATE DATABASE GET/UPDATE DB CFG RECONCILEADD CONTACT GET/UPDATE DBM CFG RECOVERADD CONTACTGROUP GET DBM MONITOR SWITCHES REDISTRIBUTE DB PARTITION

……etc.,GET CONTACTGROUPS QUIT UPDATE MONITOR SWITCHESGET CONTACTS REBIND

Note: Some commands are operating system specific and may not be available.For further help:

? db2-command - help for specified command? OPTIONS - help for all command options? HELP - help for reading help screens

The preceding three options can be run as db2 <option> from an OS prompt.!db2ic - DB2 Information Center (Windows only)

This command can also be run as db2ic from an OS prompt.

C:\ db2 ? sql0100 [this is an example of an SQL “message” help request]

Tip:

“db2 ? help” helps you read and use help

screens-----------------------------------

------“db2 help” launches the

Information Center

DB2 9 vs Oracle 10g© 2008 IBM Corporation 32

DB2 Information Management

Command Line Processor Option Settings

Backend process wait time (seconds) (DB2BQTIME) = 1No. of retries to connect to backend (DB2BQTRY) = 60Request queue wait time (seconds) (DB2RQTIME) = 5Input queue wait time (seconds) (DB2IQTIME) = 5Command options (DB2OPTIONS) =

Option Description Current Setting--------- ---------------------------------------------- ---------------------a Display SQLCA OFF-c Auto-Commit ON-e Display SQLCODE/SQLSTATE OFF-f Read from input file OFF-l Log commands in history file OFF-n Remove new line character OFF-o Display output ON-p Display interactive input prompt ON-r Save output to report file OFF-s Stop execution on command error OFF-t Set statement termination character OFF-v Echo current command OFF-w Display FETCH/SELECT warning msgs ON-x Suppress printing of column headings OFF-z Save all output to output file OFF

db2 => list command options

db2 => update command options using c OFF [turns this off]

db2 => set DB2OPTIONS=+c [Windows alternative for the same thing]

db2 => export DB2OPTIONS=“+c” [UNIX alternative for the same thing]

CLP 옵션

Tip:

Leaving the interactive mode turns off your db2option settings!

-------------------------------------------“? options” is different from “list

command options”-------------------------------------------Many db2option switches can be temporarily overridden in a batch

mode

DB2 9 vs Oracle 10g© 2008 IBM Corporation 33

DB2 Information Management

CLP History 및 runcmd명령

● Command history [reverse] [n] displays the last commands cached20 ascending is default display and 20 is the default cachedSet db2_clp_histsize registry variable to change cache size

● runcmd runs the numbered command from the history cache● These ONLY work in interactive mode

db2 => history

db2 => runcmd 3

db2 => history1 connect to sample2 list command options3 select * from sysibm.sysdummy1…20 select * from customer

db2 =>

db2 => runcmd 3IBMREQD-------------Y

1 record(s) selected

db2 =>

DB2 9 vs Oracle 10g© 2008 IBM Corporation 34

DB2 Information Management

CLP Command 창배치모드사용예

● Batch or shell files can execute saved DB2 command files● These can produce yet other output files for various purposes● Here is a “Generate RUNSTATS commands” example

–x to suppress column headings –td to set the end of command delimiter as @ –f to indicate input file name –z to indicate output file name

db2 connect to sample

db2 -x -td@ -f CLPxmp01.db2 -z CLPxmp01OUT.txt

db2 commit workdb2 connect reset

CLPxmp01.bat

CLPxmp01.db2

select 'RUNSTATS ON TABLE'||rtrim(tabschema)||'.'||tabname||‘ON ALL COLUMNS ALLOW WRITE ACCESS;'

from sysstat.tableswhere card = -1@

CLPxmp01OUT.txt

RUNSTATS ON TABLE SYSIBM.SYSVIEWSON ALL COLUMNS ALLOW WRITE ACCESS;RUNSTATS ON TABLE SYSIBM.SYSVIEWDEPON ALL COLUMNS ALLOW WRITE ACCESS;

… etc., etc.

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 데이터베이스

14 slides

DB2 9 vs Oracle 10g© 2008 IBM Corporation 36

DB2 Information Management

* Oracle 9i supports a "server parameter file" maintained by the Oracle engine

Database 관리유사한함수및용어

● 주요관리함수및용어기본적으로동일

Different enough to miss when new to DB2

AutoresizeAutoextend

Package CacheStatement CacheMaterialized Query TableMaterialized View (Snapshot)

DBM config (instance) DB config (database)

init.ora *QuiesceEnable Restricted & Quiesce

db2dartDump datafile #block# (ALTER SYSTEM)

InspectDbms_repairBuffer poolData CacheSystem CatalogData Dictionary

Archive LogArchive Redo Log

DB2Diag LogAdministration Notification Log

Alert Log

DB2 함수/용어Oracle 함수/용어

DB2 9 vs Oracle 10g© 2008 IBM Corporation 37

DB2 Information Management

Database 관리Dictionary 와 Catalog

● Oracle Dictionary 와 DB2 System Catalog 내용

SYS.xxxx$- Base Tables

SYS.GV_$ or GV$SYS.V_$ or V$ALL_%DBA_%USER_%- System Views

Oracle Data Dictionary 내용

SYSIBMBase tables

SYSCAT- Read-only views - Defined for catalog base tables

SYSSTAT- Updateable views- For access path manipulation

DB2 System Catalog 내용

SELECT table_name FROM user_tables

SELECT view_name FROM user_views

SELECT name FROM sysibm.systables WHERETYPE="T" and CREATOR=user

SELECT name FROM sysibm.systables WHERETYPE="V" and CREATOR=user

DB2 9 vs Oracle 10g© 2008 IBM Corporation 38

DB2 Information Management

Database

Table space

Segment

Extent

Oracle Block

Datafile

OS Page

Logical Physical

Oracle 스토리지구조

Database

Table space

Object

Extent

DB2 Page

Container

OS Page

Logical Physical

DB2 스토리지구조

물리데이터베이스저장모델스토리지구조

● Oracle과 DB2는물리데이터베이스구조가거의비슷함Below shows the slight differences in concept & semantics

DB2 9 vs Oracle 10g© 2008 IBM Corporation 39

DB2 Information Management

물리데이터베이스저장모델테이블공간타입

Oracle 테이블공간타입● System● Non-System

TemporaryDictionary ManagedLocally Managed

PermanentDictionary Managed Locally Managed (default)

TransportableUndo

DB2 테이블공간타입● Database Managed (DMS)

RegularTemporary (system & user)Large

● System Managed (SMS)RegularTemporary (system & user)

Oracle Table Space Storage 설정

INITIALNEXTMINEXTENTSMAXEXTENTSPCTINCREASEFREELIST/GROUPS

DB2 Table Space Storage 설정

PAGESIZEEXTENTSIZEPREFETCHSIZEOVERHEADTRANSFERRATEBUFFERPOOL

DB2 9 vs Oracle 10g© 2008 IBM Corporation 40

DB2 Information Management

물리데이터베이스저장모델DB2 테이블공간생성

● DB2 Table Space CreationOnly SYSADM & SYSCTRL authorities can perform thisOnly created & active buffer pools may be used in a CREATE TABLESPACE commandBuffer pools are dynamic & take immediate affect when added, dropped or alteredDFT_PREFETCH_SZ can be set to let DB2 calculate optimal prefetching for your environment

● To review information on these useLIST TABLESPACES [ SHOW DETAIL ]LIST TABLESPACE CONTAINERS FOR X [ SHOW DETAIL ]Or use Control Center GUI, or SYSCAT.TABLESPACES catalog view

CREATE [ REGULAR / LARGE / TEMPORARY ]TABLESPACE tablespacename PAGESIZE integerMANAGED BY [ AUTOMATIC STORAGE][ SYSTEM / DATABASE ]

[ system-container / database-container ]EXTENTSIZE [ number-of-pages / integer ]PREFETCHSIZE [ number-of-pages / integer ] BUFFERPOOL bufferpool-nameOVERHEAD number-of-milisecondsTRANSFERRATE number-of-milliseconds…AUTORESIZE YES…

DB2 9 vs Oracle 10g© 2008 IBM Corporation 41

DB2 Information Management

물리데이터베이스저장모델DB2 Container Types For DMS & SMS

● DMS is for database managed table spaces Basically what all Oracle table spaces translate toRecommended for larger more often used table spaces Supports automatic resizing and automatic storage similar to Oracle

● SMS is for system managed table spacesOnly DB2 has the option to use this type of table spaceRecommended for smaller, less used tables paces

For ease of maintenanceOperating system controlled

No database alterations possible to the container(s)More containers can be added to it with a redirected restore

DMS - Database Managed SMS - System Managed

File Device Directory

/database/tablespace/prod1

DB2 9 vs Oracle 10g© 2008 IBM Corporation 42

DB2 Information Management

물리데이터베이스저장모델DB2 Striping

● DB2 does automatic striping of data among the containers in a table spaceYou just make sure containers fall on different mount points You set PREFETCHSIZE for a table space setting to maximize striped reads & writesOr use block based buffer pools

● DB2 does automatic rebalancing of the data between containers when New DMS containers are added to a table spaceRebalancing can be avoided during table space alter by

Use of ALTER TABLESPACE ... BEGIN NEW STRIPE SETWith "policy" regulation to control impact on performance

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

DB2 Table Space

~~~~~~~~~~~~~~~

Container Stripe Set 0

~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~

Container Stripe Set 1

alter to add new

DB2 9 vs Oracle 10g© 2008 IBM Corporation 43

DB2 Information Management

물리데이터베이스저장모델DB2 행압축

● Dictionary 기반 - symbol table for compressing/decompressing data recordsLempel-Ziv (LZ) based algorithm (static dictionary based)Dictionary per table stored within the permanent table object

● 데이터는페이지에압축저장On table space disk – I/O 비용절감In buffer pools –메모리절감

● Insert/Update/Import/Load 시항시압축됨Does not compress rows where no storage saving is realized for that row

● 약간의 CPU 비용추가Rows must be decompressed before being processed for evaluation

75063TXDallas100000smpoBurt

75063TXDallas500000smpoVik

ZipSTCitySalaryDeptName

Etc ……

Dallas, TX, 75063(02)

smpo(01)

Etc…75063TXDallas500000smpoVik75063TXDallas100000smpoBurt

Etc…(02)500000(01)Vik(02)100000(01)Burt

Dictionary

DB2 9 vs Oracle 10g© 2008 IBM Corporation 44

DB2 Information Management

기타관리상차이

Optimizer가한정된정보에의해판단

● Hints● Environment variables

Version 7부터비용기반지원10g에서는 Rules based가지원되지않음

Optimizer는다양한정보에의해판단

● Query optimization class● Subcommands

OPTIMIZE FOR n ROWSFETCH FIRST n ROWS ONLY

● Registry variables● Volatile table● Informational constraints● Selectivity clause● Optimization profiles

Version1부터비용기반의 Optimizer

Cache (buffer pool) per block sizeblock size별로 Cache 할달가능

Buffer pool per table space테이블공간당각자의버퍼풀할당가능

동일한테이블공간이라하더라도다른버퍼풀사용가능

Static bitmap indexingDBA가만들고, 일반인덱스와동일하게관리

Dynamic bitmap indexing엔진스스로필요한시기에메모리에자동으로생성

OracleDB2

DB2 9 vs Oracle 10g© 2008 IBM Corporation 45

DB2 Information Management

기타관리상차이 (계속)

Initial column only compressionOracle은 direct path loader에만지원.

변경된행에대해서는후에 ALTER … MOVE 명령으로재압축필요. 칼럼레벨압축

True row compression Load/Import/Insert되는모든행이압축됨

행레벨및칼럼레벨압축

Optimizer not aware of extenders최적화미지원

Optimizer aware of extenders.NET 과 Spatial 정보에대한최적화지원

Federated Object최적화지원

Restricted parallel DMLRI cascase, Triggers, LOB처리시제약사항이있으며, DML의병렬처리는 partitioned

table일때만지원

Unrestricted parallel DML모든 Query, Utility, RI Cascade, Triggers, LOB처리시

병렬처리지원

No packaged codeOracle은 Static Access Path를보관하지않음

Packaged codeStatic access path를위한 Pacakge정보를카탈로그

테이블에보관됨.

User schema supportSchema를생성하기위해서는 User가먼저

생성되어야함

True schema support사용자와무관하게 Schema가존재가능. 데이터베이스

내또는데이터베이스간손쉽게이동가능

OracleDB2

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 백업및복구

28 slides

DB2 9 vs Oracle 10g© 2008 IBM Corporation 47

DB2 Information Management

아키텍처비교컴포넌트

Oracle

Data Files (Data Blocks)

Redo Logs

Control Files, List Backup

Undo Segments

RMAN

DB2

Data Files(Data Pages)

Recovery History File

Recovery Logs

Backup / Restore

Parameter Files

DB2 9 vs Oracle 10g© 2008 IBM Corporation 48

DB2 Information Management

아키텍처비교DB2 제어센터로깅구성Wizards

●효과적인학습툴

●GUI 도구에서로깅설정을위한명령어를자동생성하여실행

●DB2 로깅을위해추가적인파라미터구성불필요

Screens walk you through logging setup

DB2 9 vs Oracle 10g© 2008 IBM Corporation 49

DB2 Information Management

아키텍처비교DB2 제어센터백업, 리스토어및롤포어드Wizards

제어세터에서 3개의화면실행

●효과적인학습도구

●백업및리스토어, 롤포어드에대한모든구성내용제공

●GUI 도구에서명령을자동생성하여실행

DB2 9 vs Oracle 10g© 2008 IBM Corporation 50

DB2 Information Management

Archive Mode- Recover DB, TS, DF

- Dual logging & mirrored logging

- 3 redo log states

1 - Active

2 - Inactive

3 - Archived

NoArchive 모드- Full DB "crash" recovery

- Limited roll-forward available

Redo logs는인스턴스마다정의

Oracle 로깅옵션및컴포넌트

Archive Log (aka Log Retain)- Recover DB, TS

- Dual logging & mirrored logging

- 3 recovery log states

1 - Active

2 - Online archived

3 - Off-line archived

Circular 모드- Full "crash" recovery,

- No roll-forward recovery

데이터베이스마다별도정의

DB2 로깅옵션및컴포넌트

Oracle DB2

아키텍처비교로깅옵션

DB2 9 vs Oracle 10g© 2008 IBM Corporation 51

DB2 Information Management

아키텍처비교Archive 로깅

Oracle Archive Log

RedoLogFiles

SGA

Database Buffer Cache

Large & Shared

Pools, etc.

Instance Level

Redo Log Buffer

dbwr

ckpt

lgwrarch

Data Files

DB2 Archive Log

RecoveryLogFiles

DB Shared Memory

Buffer Pool

Package Cache, DB Heap, etc.

Data Base Level

Log Buffer

db2pgclnr

[softmax]

db2loggerdb2uext2

Data FilesLog

Control File

Control Files Archive

Log Files Archive Log Files

Active LogNon-Committed or Non-Externalized

Transactions

Online Archive LogCommitted & Externalized Transactions

Off-line Archive LogFiles moved from active log subdirectory

to another media

Active LogNon-Committed or Non-Externalized

Transactions

Inactive LogCommitted & Externalized Transactions

Archived LogFiles moved from active log subdirectory

to another media

DB2 9 vs Oracle 10g© 2008 IBM Corporation 52

DB2 Information Management

아키텍처비교Recovery History 정보

Oracle● For Online Backup● RMAN LIST BACKUP● V$BACKUP_FILES

DB2● Recovery History File updated during

Database backup, restore, roll-forward or recoveryTable space backup, restore or roll-forwardTable space is created, dropped, altered, renamed or quiesced Table is loaded, dropped or reorganizedLog file is archivedNew log file is written to

list history backup all for sample

prune history 200412

Format YYYYMM

select * from table(sysproc.admin_list_hist()) as history

DB2 9 vs Oracle 10g© 2008 IBM Corporation 53

DB2 Information Management

오프라인백업 (aka Cold Backup)가장단순한백업

DB2● Circular logging 모드

(except to make a base backup for an archive logged database)

● 모든사용자연결해제 (or quiesce or stop)● Backup 명령어사용

− 데이터베이스또는테이블공간레벨

− SYSADM, SYSCTRL or SYSMAINT authority needed

● 수동복사불필요하나필요시가능

backup database sample to c:\db2backup

Oracle● NOARCHIVELOG 모드● Shutdown in normal● 수동복사 :

− data files− control files− redo logs

(Use OS cpio, tar, backup manager, etc.)

DB2 9 vs Oracle 10g© 2008 IBM Corporation 54

DB2 Information Management

오프라인리스토어

Oracle● Shutdown Normal

● 백업이미지와동일한이름사용

● Data file, control files, redo logs, undo logs 파일들을수동으로복사

● 수동복사중에 datafile를변경가능

● 새로운데이터베이스로생성가능하나매우복잡

alter database rename filename <oldpath> to <newpath>

DB2● 데이터베이스 Stop 또는 quiesce● History file에서필요한백업본에대한

TIMESTAMP를가져옴 (사용편의성)● Restore 명령사용

● Restore 중에 container 를변경가능(“redirected restore”)

DB2는이작업의편의성을위해 script를생성해주기도함

● 새로운데이터베이스로손쉽게생성가능

Restore db… into newdb

restore database sample from "c:\db2backup" taken at 20040901144022 without prompting

DB2 9 vs Oracle 10g© 2008 IBM Corporation 55

DB2 Information Management

온라인백업 (aka Hot Backup) Archive 로깅구성필요

Oracle● init.ora변경

LOG_BUFFERLOG_ARCHIVE_DESTLOG_ARCHIVE_DUPLEX_DESTLOG_ARCHIVE_CONFIGOther optional…

데이터베이스백업수행

로그백업수행

DB2● 로깅변수변경

LOGFILSZLOGBUFSZLOGPRIMARYLOGSECOND

● 추가변경(선택적)− NEWLOGPATH

MIRRORLOGPATHBLK_LOG_DSK_FULLOVERFLOWLOGPATH

● LOGARCHMETH1 설정오프라인백업수행필요

● Wizard를통해구성가능

shutdown startup mountalter database archivelogshutdown immediate

alter database openalter database startarchive log listarchive log all

DB2 9 vs Oracle 10g© 2008 IBM Corporation 56

DB2 Information Management

아키텍처비교DB2 로깅파라미터

Number of secondary logs allocated if needed. -1 is unlimited active logs.Number of primary logs. Also determines number of logs in active log path.

Multi-function parameter used for rollforward and archived log retrieval operations.

Number of active log files that an active transaction can span. 0 means no limit.

Number of attempts that will be made to archive log files using the specified log archive method before they are archived to the path specified by the failarchpath.

Allows you to delay the writing of log records to disk until a minimum number of commits have been performed.

Location to change for log path away from default SQLOGDIR.Location where an identical copy of the logs will be kept.

Percentage of primary log space that can be consumed by one transaction. 0 means no limit.

The size of each configured log, in number of 4-KB pages.Amount of memory to use as a buffer for log records in 4-KB pages.

Works with logarchmeth1 & 2 for vendor options if using TSM or VENDOR values.

These parameters cause the database manager to archive log files to locations that are not the active log path. Values are OFF, RETAIN, USEREXIT, DISK, TSM, VENDOR

Alternate directory for the archive log files if the log archive method specified fails.

Prevent disk full errors from being generated.Wait in second between archive log failure attempts. 0 means no retry.Usage

2logsecondSecondary Logs

NULLoverflowlogpathOverflow Log Path

3logprimaryPrimary Logs

1mincommitsNumber of Commits to Group

5numarchretryNumber of Archive Retries

NULLnewlogpathNew Log Path

0num_log_spanNumber of Log Span

NULLmirrorlogpathMirror Log Path

0max_logMax Logs per Transaction1000logfilsizLog File Size8logbufszLog Buffer

NULLlogarchopt1logarchopt2

Log Archive Options 1 & 2

OFFlogarchmeth1logarchmeth2

Log Archive Methods 1 & 2

NULLfailarchpathFailover Archive PathNOblk_log_dsk_fulBlock on Log Disk Full 20archretrydelayArchive Retry Delay DefaultParameterFunction

DB2 9 vs Oracle 10g© 2008 IBM Corporation 57

DB2 Information Management

온라인백업작동및범위

Oracle● RMAN 사용● Table space 레벨, one at a time

(system 및 rollback 테이블공간은특별한주의필요)

● Alter table space begin backup 모드변경된내용들을모두디스크에반영SCN markers are frozenLog full images of changed blocks

● data files 과 control files 복사(all data blocks, changed & unchanged)

● Alter table space end backup 모드● 백업동안에최소한의 activity 권장● sysdba권한필요

DB2● BACKUP command 사용● Database 또는테이블공간레벨

로그에확약된트랜잭션을위해변경된페이지정보를보유

Very first full backup done offline● 백업이미지에포함되는것

변경된데이터페이지들

변경되지않는데이터페이지들

시스템파일들

History 파일들Control 파일들로그파일포함가능

● 우선순위조절가능

그래도온라인백업동안에는최소한의 activity 권장

● sysadmin, sysctrl , sysmaint권한필요

DB2 9 vs Oracle 10g© 2008 IBM Corporation 58

DB2 Information Management

온라인백업DB2 예

DB2● Online Database backup

● Online table space backup including logs

● Online database backup 압축및 Throttled

backup database sample online to c:\db2backup

backup database sample tablespace (userspace1) online to c:\db2backup include logs

backup database sample online to c:\db2backupCompress util impact priority 50

DB2 9 vs Oracle 10g© 2008 IBM Corporation 59

DB2 Information Management

온라인리스토어Database 고려사항

Oracle● Restore 와 recover 전략이무엇이

유실되었느냐에따라다름 (Examples, see paper on “Oracle Recovery Scenarios”)

● Restore –오프라인상태에서, 백업받은이미지복사

● Recover – roll-forward를위해 redo log 반영

● Database 레벨복구데이터베이스 Mount모든데이터파일을 Online 시킴유실된데이터파일을복사

Redo log 적용 (inactive and archived)

● Recover database는 2가지타입가능End of logsPoint in time

DB2● 데이터베이스 Restore 시에는오프라인상태에서온라인백업이미지를이용하여restore 실행

● 전체 Restore는모든주요시스템파일들을자동으로복원

– 손쉽게복구하고서비스시작가능

– Restore with roll-forward for more control

recover db sample to end of logs

restore database sample from c:\db2backup taken at 20041201194626 without promptingrollforward database sample to end of logs and complete

● Roll-forward 는 2가지타입제공− End of logs− Point in time

or

DB2 9 vs Oracle 10g© 2008 IBM Corporation 60

DB2 Information Management

온라인리스토어테이블공간고려사항

Oracle● 테이블공간레벨복구

테이블공간 Offline 시킴유실된데이터파일복사

Redo log 반영(online and archived)

● 복구시나리오

Media failure의심각도및백업전략에의존적이며, 일관성있는상태로복구하는것이힘겨운때가종종있음.예제 “Oracle Recovery Scenarios”

DB2● 테이블공간복구를온라인상태에서실행

restore database sample tablespace(userspace1) online from c:\db2backup taken at 20040901201428 without promptingrollforward database sample to end of logs and complete tablespace(userspace1) online

● 롤포어드는 2가지타입제공− End of logs− Point in time

● 테이블공간백업이미지들을이용하여전체데이터베이스를생성가능

DB2 9 vs Oracle 10g© 2008 IBM Corporation 61

DB2 Information Management

Incremental 백업비교

Oracle

● Cumulative Incremental BackupLevel 0 is a baselineLevel 1은가장마지막 Level 0 백업이래변경된모든block들을백업

● Differential Incremental Backup (default)

Level 0 is a baselineLevel 1 은가장마지막incremental backup이래변경된모든 block들을백업

DB2

● Incremental Backup마지막 full backup받은이래변경된모든페이지들을백업

● Delta Backup마지막 full, incremental, delta이래로변경된모든페이지들을백업

Similar

Similar

DB2 9 vs Oracle 10g© 2008 IBM Corporation 62

DB2 Information Management

Incremental BackupOracle Cumulative and Differential Incremental Backups *

Cumulative Incremental Backup

Differential Incremental Backup (default)

* Excerpt from Oracle documentation

DB2 9 vs Oracle 10g© 2008 IBM Corporation 63

DB2 Information Management

Incremental BackupDB2 Incremental & Delta

DB2 Incremental & Delta Backups

DB2 9 vs Oracle 10g© 2008 IBM Corporation 64

DB2 Information Management

Incremental BackupUsing

Oracle● 부분백업을위해 RMAN 사용● RMAN은마지막백업이래변경된

Block들을 Tracking하는파일을이용

● Tracking Enable

● Tracking Disable

DB2● Tracking을위해 db cfg에

TRACKMOD 를 YES로변경

● Full 백업을받은후, 이후에Incremental 백업수행

alter database enable block change tracking using file '/bkups/change.log‘

alter database disable block change tracking

update db cfg for sample usingtrackmod yes

backup database sample online incremental to c:\db2backup

backup database sample to c:\db2backup

backup database sample online incremental delta to c:\db2backup

DB2 9 vs Oracle 10g© 2008 IBM Corporation 65

DB2 Information Management

Incremental RestoreUsing

Oracle● Incremental restore를위해

RMAL 사용● RMAN은 Incremental

백업이미지로부터 Incremental Merge시킬수있음

DB2● 데이터의손실없이 restore

incremental 및 delta 백업을통한자동복구를위해 Automatic 키워드사용

Roll forward(예제 : 다음장)

● Restore wizard 사용시매우편리

DB2 9 vs Oracle 10g© 2008 IBM Corporation 66

DB2 Information Management

Incremental RestoreDB2 예제

DB2 Incremental Restore 단계● Restore using “automatic” keyword to apply incremental or delta backups

● Roll-forward

restore database sample incremental automatic from c:\DB2Backup taken at 20040901230402 without prompting

자동 restore를 위해, 가장최근의 incremental 및delta 백업이미지의 timestamp

rollforward database sample to end of logs and complete

DB2 9 vs Oracle 10g© 2008 IBM Corporation 67

DB2 Information Management

삭제된테이블복구과정비교

Oracle● FLASHBACK옵션이있으면

손쉬움:

● 영구적으로테이블삭제를하려면:

● 영구적으로삭제한테이블을복구하는일은매우어려움 (다음장)

DB2● 삭제된테이블 history 가보관됨(DROPPED TABLE RECOVERY가 On)

● 이전의백업이미지로부터테이블공간을 Restore

FLASHBACK TABLE RECYCLETEST TO BEFORE DROP

DROP TABLE RECYCLETEST PURGE

list history dropped table all for sample

restore db sample tablespace(userspace1) from c:\db2backup taken at 20040902100931 without rolling forward without prompting

DB2 9 vs Oracle 10g© 2008 IBM Corporation 68

DB2 Information Management

삭제된테이블복구과정비교(계속)

Oracle● 영구적으로삭제된테이블을

복구하는법

Database를다른서버에 restore테이블을삭제된바로이전의시점까지 point-in-time 복구실행삭제된테이블을 Export원래의데이터베이스에 Import

DB2● 삭제된테이블의데이터를 Unload

● Recovery history 파일로부터 DDL문추출하여테이블재생성

● 데이터로드

rollforward db sample to end of logs and complete recover dropped table 00000000000002010002000d to c:\db2backup

load from c:\db2backup\node0000\data of del method p(1) insert into recoverme

DB2 9 vs Oracle 10g© 2008 IBM Corporation 69

DB2 Information Management

백업및복구자동튜닝백업지원

● 자동튜닝기능이 BACKUP 유틸리티에도지원● 성능상장점

최악의시나리오에서도 4배의성능향상

● 자동설정:Buffer sizeNumber of buffersParallelism

DB2 9 vs Oracle 10g© 2008 IBM Corporation 70

DB2 Information Management

백업및복구지원유틸리티

● db2ckbkp (백업이미지점검)백업이미지의무결성점검 (로그포함여부확인가능)

● db2ckrst (incremental restore 이미지점검)Helps manage log chains to make sure they are complete for any given incremental restore

● db2adutl (TSM 오브젝트관리)Allows users to query, extract, verify, and delete backup images, logs, and load copy images saved using Tivoli Storage Manager.

● db2pd (문제해결)-LOGS 옵션 –모든로그에대한현재정보

DB2 9 vs Oracle 10g© 2008 IBM Corporation 71

DB2 Information Management

백업및복구교육

Oracle● 백업및복구가배우고

사용하기가쉽지않음.● Oracle은 Backup / Recovery를위해 3일교육과정제공

DB2● 백업및복구가배우고사용하기가매우간단

● DB2 ADMIN교육과정이 4일과정이며,− 백업및복구를위한 topic이포함− 습득위해 1일이하소요

DB2 9 vs Oracle 10g© 2008 IBM Corporation 72

DB2 Information Management

백업및복구결론

● 두데이터베이스모두제공Offline or online backup of database and table spacesTable space online backup and restore, relocation of table space with compressionRoll-forward to a point-in-time or to the end of logsIncremental and differential backup for data warehouse environmentEffective mechanisms and capabilities for securing data from loss due to media corruption or human error.

● 그러나, 백업및복구기술은 Oracle보다 DB2가매우간단하며손쉬움

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 High Availability Disaster Recovery (HADR)

29 slides

Primary

Standby

clone

DB2 9 vs Oracle 10g© 2008 IBM Corporation 74

DB2 Information Management

장애시간의 최소화(Ultra-fast failover)

관리의 용이함 및 비용의 최소화 (Easy administration)

이중화에 대한 성능 보장(Negligible impact on performance

업무 연속성 제공(H/W,S/W upgrades without interruption)

Fail-Over의 용이함 (Client Reroute)

Transparent failover & failback for applications

DB2 HADR 의목표

DB2 9 vs Oracle 10g© 2008 IBM Corporation 75

DB2 Information Management

데이터베이스를 이중 관리함으로써 사이트 장애 또는 Storage 장애에 대비

무 중단으로 버전 업그레이드 가능

최근 변경내용을 대기서버의 메모리(버퍼풀)에 저장

장애 시 대기서버의 가동시작 시간을 앞당김

15초 이내 장애복구

실재로 600명의 SAP 사용자를 서비스하는 시스템에서 11초만에 데이터베이스 서비스를 재 시작했음

대기서버에서도 장애 시 주 서버와 동일한 성능 (100%)으로 서비스 가능

TSA for server monitoringMonitors the primary and initiates the takeover.HACMP, heartbeat, TSA, MSCS, etc

txtxtxtx

Network Connection

2차 서버

HADR두 서버간 Sync 유지

Automatic Client RerouteClient application은 자동으로 대기서버에서 재 시작됨

txtx

1차서버

DB2 HADR -가장빠른장애복구솔루션

DB2 9 vs Oracle 10g© 2008 IBM Corporation 76

DB2 Information Management

HADR

Primary DatabaseRemote

Disaster Recovery

HADR Cluster

Local standby Database

DB1 DB1’DB1’’

Automatic client reroute

HADR 구성으로 Local Standby Database 구성Remote DR을 위해 HADR Standby 데이터베이스에 연결(주 서버의 네트웍 부하 고려)

Primary DB 서버 장애 감지

Local Standby Database로 자동 서비스 이전

서울 지역 전원장애 등 재해 발생

Remote DR 서버로 서비스 이전

Disk Mirroring

HADR 구성방안 (Local HA/Remote DR)

DB2 9 vs Oracle 10g© 2008 IBM Corporation 77

DB2 Information Management

“한 장의 설명으로 충분”

● Primary Setup

(1)db2 backup db hadr_db to backup_dir

(3)db2 update db cfg for hadr_db usingHADR_LOCAL_HOST host_a

HADR_REMOTE_HOST host_b

HADR_LOCAL_SVC svc_a

HADR_REMOTE_SVC svc_b

HADR_REMOTE_INST inst_b

HADR_TIMEOUT 120

HADR_SYNCMODE ASYNC

(6) db2 start hadr on database hadr_db as primary

● Standby Setup(2) db2 restore db hadr_db from backup_dir

(4) db2 update db cfg for hadr_db usingHADR_LOCAL_HOST host_bHADR_REMOTE_HOST host_aHADR_LOCAL_SVC svc_bHADR_REMOTE_SVC svc_aHADR_REMOTE_INST inst_aHADR_TIMEOUT 120HADR_SYNCMODE ASYNC

(5) db2 start hadr on database hadr_db as standby

서비스 이관 : db2 takeover hadr on db hadr_db

HADR의구현및관리 –손쉽게구성하고관리

DB2 9 vs Oracle 10g© 2008 IBM Corporation 78

DB2 Information Management

HADR Setup클라이언트리라우트

● Client reroute 구성

Standby :Primary :

DatabasePrimary

Active Standby ActiveLoss

DatabaseStandby

HADR

Databaseloss

DatabasePrimary

Before AfterClient re-route Client re-route

Failover

Cluster manager executes “db2 TAKEOVER HADR ON DATABASE HADRDB BY FORCE” on standby

db2 UPDATE ALTERNATE SERVER FOR DATABASE HADRDB USING Host1.ibm.com PORT 50000

db2 UPDATE ALTERNATE SERVER FOR DATABASE HADRDB USINGHost2.ibm.com PORT 55000

DB2 9 vs Oracle 10g© 2008 IBM Corporation 79

DB2 Information Management

HADR솔루션은 RAC에 비해 고 가용성은 물론이고 성능, 관리성, 비용 면에서 모두 탁월한 장점을 가진솔루션입니다.

H/W비용은 RAC솔루션이 보다 저렴하나, Oracle 및 RAC를 위한라이센스 비용으로 인해, HADR솔루션이 전체적인 비용을 절감시킵니다. 이에따라 S/W유지보수비용도 RAC가 더 비싸게 책정될 수 있습니다. RAC 3 노드를 가정했을 때, 동일한 용량을 가지는 HADR솔루션이 24% 더저렴합니다.

HADR > RAC비용

한대의 노드가 장애 시 HADR은 RAC와 비교했을 때 최소한 비슷하거나또는 보다 빠른 재 가동 시간을 확보할 수 있습니다. 또한 DB2는 고 가용성을위한 다양한 기능들을 제공하고 있습니다.

HADR > RAC고 가용성

한대의 SMP로 관리하는 것이 Cluster 시스템을 운영하는 거에 비해관리하기가 더 쉽습니다. 이로 인해 관리비용이 RAC가 더 많이 소요됩니다.

또한 RAC는 구축 시 Application의 디자인 고려 등 구현하기가 어렵지만, HADR은 구성하기가 매우 쉽습니다.

HADR > RAC구현 및 관리

DB2는 한대의 SMP기계에서 OLTP업무 최고의 성능(tpc-c)을 내고있습니다. 가장 최근 자료(2006/12)에 의하면, 동일한 기계 사양에서Oracle에 비해 3.4배의 성능 차이를 보였습니다.

HADR > RAC성능

세부내용비교구분

RAC 대비 HADR의우수성

DB2 9 vs Oracle 10g© 2008 IBM Corporation 80

DB2 Information Management

Data Block Remastering

한 노드가 실패하면 실패한 노드의 블럭들을 다른 노드에서 재 분산되어야 함. 이 과정 동안 전 노드의 GCS가 중단되며, 데이터베이스 서비스도 중단됩니다.

Global ResourceDirectory

Master for block14710…

Global ResourceDirectory

Master for block25811…

Global ResourceDirectory

Master for block36912…

Instance 1 Instance 2 Instance 3

Oracle RAC 장애복구

DB2 9 vs Oracle 10g© 2008 IBM Corporation 81

DB2 Information Management

총 업무량 처리를 위해 12장의 CPU가 필요하다고 가정했을 때 Oracle RAC는 장애 시 한대의 서버에서 가동되어야하므로, 업무 대비한 CPU 개수에 대한 추가적인 고려가 필요하나, 이를 감안하지 않더라도 도입비용 면에서 DB2 HADR 이 보다 저렴합니다. HADR은 DB2의 고가용을 지원하는 기능이며, DR기능도 포함합니다.

p570 12-way p570 12-way p570 4-way p570 4-way

$793,533Total

$0HADR (High Availability Disaster Recovery)

*$430,625DB2 ESE (Enterprise Server Edition) 9

$151,168Storage

$211,740Server

$1,050,254Total

***$292,800RAC(Real Application Cluster)

**$576,000Oracle EE 10g

$75,584Storage

$105,870Server(8822.5)

*$33,125 per CPU for DB2 ESE**$48,000 per CPU for Oracle EE***$24,400 per CPU for Oracle RAC

Assumes that RAC scales linearly

$256,721 절감 (24%)

초기 도입시 Disk 추가비용 소요

HADR을 위한 추가 라이센스 없음

Standby장비:1 CPU 라이센스 구매

RAC 추가 라이센스 구매

두개 장비 모두 CPU 기반 라이센스 구매

라이센스구매비용↑=유지보수비용↑

p570 4-way

초기도입비용비교

DB2 9 vs Oracle 10g© 2008 IBM Corporation 82

DB2 Information Management

장애 발생 시 다시 정상적으로 서비스가 제공되기까지의 시간(Fail-over Time)을 비교하였습니다.

DB2 HADR/HAFail-over

필요필요 없음없음

필요필요 없음없음

20 20 초초 미만미만

필요필요 없음없음

필요필요 없음없음

20 20 초초

Oracle 단일 서버Fail-over

Fail-over 동작

필요필요 없음없음1) Cluster 1) Cluster 서버서버 그룹그룹 재구성재구성

최대최대 20 20 분분3) 3) 디스크디스크 볼륨볼륨 절체절체

4) 4) 데이터베이스데이터베이스 서버서버 재재 기동기동

5) 5) 데이터베이스데이터베이스 복구복구//롤포워드롤포워드

25 25 분분 이상이상총총 소요소요 시간시간 -- Failover TimeFailover Time

최대최대 5 5 분분

필요필요 없음없음2) 2) 분산분산 Lock Lock 재구성재구성

20 20 초초

15 15 초초

필요필요 없음없음

필요필요 없음없음

20 20 초초

60 60 초초 미만미만

5 5 초초

Oracle RACFail-over

DB2의 HADR 솔루션이 Oracle RAC에 비해 2배 이상 빠른 Fail-Over 시간 제공!

장애복구시간비교

DB2 9 vs Oracle 10g© 2008 IBM Corporation 83

DB2 Information Management

No / LimitedYesExpress/Workgroup에서도 지원

YesYes장애 복구 이후 서비스 가동

NoYes사이트 장애 대비

YesYes수분 대 장애 복구

NoYes지역적인 분산

NoYes구성 및 모니터가 간단

NoYes응용프로그램 변경이 불필요

NoYesRolling Upgrade 지원

NoYes디스크 장애 대비

YesYesServer 장애 대비

YesYes소프트웨어 장애 대비

Oracle 10g RACDB2 HADR구 분

HADR vs RAC 가용성

© 2008 IBM Corporation

IBM Software Group

IBM DB2 Open Forum 3rd

DB2 동시성

분리레벨및잠금

18 slides

DB2 9 vs Oracle 10g© 2008 IBM Corporation 85

DB2 Information Management

동시성개요

● 동시성:다중사용자및응용프로그램들이자원을공유하는것을허용

데이터일관성유지

2가지메커니즘► 분리레벨

► 잠금

● 동시성이슈

Lost updates2개의 Transaction이 동일한 데이터를 변경하려고 시도하여, 첫 번째 변경된 데이터는 두 번째 변경된데이터에의해사라지는현상

Phantom ReadsTransaction이두번째결과집합을생성할때, 처음에없던새로운행들이추가되는현상

Nonrepeatable ReadsTransaction이 두 번째 결과집합을 생성할 때, 변경된 행이 존재하거나 또는 삭제되어 나타나지 않는행이있는현상.

Uncommitted Reads다른 transaction에의해변경되었으나, 아직확약되지않은데이터를읽는현상Old Data ReadsTransaction이읽어온데이터가이미다른 transaction에의해변경되어, 구데이터가되는현상.

DB2 9 vs Oracle 10g© 2008 IBM Corporation 86

DB2 Information Management

동시성ANSI 분리레벨개요

트랜잭션이 실행되는 동안 잠금을 확보하지 않음(No locking is done on any records at any time during a transaction (with the exception of a dropped or altered table which is not transactional anyway))

Uncommitted Read

결과집합 중 현재 참조되는 행에 대해서만 cursor가 이동하거나 또는트랜잭션이 마칠 때까지 잠금을 보유(Only the row that is currently being referenced in that result set is locked until that cursor is repositioned or the transaction ends)

Cursor Stability

실제적으로 검색된 모든 행들에 대해 트랜잭션이 마칠 때까지 잠금을보유(Any row that is actually retrieved to produce the result set is locked until the transaction ends)

Read Stability

결과집합에 영향을 미치는 모든 행들에 대해 트랜잭션이 마칠 때까지잠금을 보유(Any row that is referenced in any mannerto produce a result set is locked until the transaction ends)

Repeatable Read

잠금 영향ANSI 분리 레벨

DB2 9 vs Oracle 10g© 2008 IBM Corporation 87

DB2 Information Management

동시성ANSI 분리레벨 –동시성이슈해결

No

No

No

No

Old Data Reads?

Yes

Yes

Yes

No

Phantom Reads?

Yes

No

No

No

Uncommitted Reads?

Yes

Yes

No

No

Non-repeatable

Reads?

No

No

No

No

Lost Updates?

Read Uncommitted

Read Committed

Repeatable Read

Serialization

J2EE Isolation Level *

Uncommitted Read

Cursor Stability

Read Stability

Repeatable Read

ANSI Isolation Level

* From Oracle’s documentation on J2EE isolation levels:

http://www.oracle.com/technology/oramag/oracle/03-may/o33j2ee_2.html#t4

Concurrency Problems . . .Concurrency Problems . . .Phantom ReadsUncommitted Reads

Nonrepeatable ReadsLost Updates

DB2 9 vs Oracle 10g© 2008 IBM Corporation 88

DB2 Information Management

동시성ANSI 분리레벨튜닝 : 보다많은동시성확보

● DB2_EVALUNCOMMITTED 레지스트리변수RS나 CS분리레벨에서,조건을만족시키는행이있을때까지, 행잠금을연기함. 조건을만족시키지않는행들은통과

CS 나 RS 트랜잭션은미확약데이터에대해서도조건만족여부를검사

● DB2_SKIPDELETED 레지스트리변수CS나 RS 트랜잭션은삭제된행(아직 commit되지않음)에대해조건검사를 Skip.

● DB2_SKIPINSERTED 레지스트리변수CS나 RS 트랜잭션은추가된행(아직 commit되지않음)에대해조건검사를 Skip.

● Other DB2 Concurrency Improvement Suggestions 자주 commit을하도록보다작은 UOW를생성가능한한빨리 Cursor를 CloseTable 잠금이필요한경우(Load나 utility작업을하는경우)에는 SHARE모드에서함

DB2 9 vs Oracle 10g© 2008 IBM Corporation 89

DB2 Information Management

동시성DB2 분리레벨설정

● Statement 레벨: SELECT (INTO), DELETE, UPDATE ... WITH {RR, RS, CS, UR}

● 현재세션에서 dynamic SQL: SET CURRENT ISOLATION = {RR, RS, CS, UR} or SET ISOLATION {RR, RS, CS, UR}

● precompile이나 bind 시: ISOLATION {RR, RS, CS, UR} option of the command line processor PREP or BIND commands

● DB2 Call Level Interface (DB2 CLI): For DB2 CLI, change the isolation level as part of the DB2 CLI configuration (db2cli.ini). This can be done either by:

UPDATE CLI CFG FOR SECTION sectionname USING TXNISOLATION {1, 2, 4, 8} where: 1 = SQL_TXN_READ_UNCOMMITTED - Read Uncommitted (Uncommitted Read) 2 = SQL_TXN_READ_COMMITTED (default) - Read Committed (Cursor Stability) 4 = SQL_TXN_REPEATABLE_READ - Repeatable Read (Read Stability) 8 = SQL_TXN_SERIALIZABLE - Serializable (Repeatable Read) Editing db2cli.ini and setting applTxnIsolation = {1, 2, 4, 8}

● JDBC 또는 SQLJ : Use the setTransactionIsolation method in the java.sql interface connection, where: TRANSACTION_SERIALIZABLE = Repeatable read TRANSACTION_REPEATABLE_READ = Read stability TRANSACTION_READ_COMMITTED = Cursor stability TRANSACTION_READ_UNCOMMITTED = Uncommitted read

● Command Line Processor (CLP) : CHANGE ISOLATION TO {RR, RS, CS, UR, NC} where NC stands for No Commit

● REXX: CHANGE SQLISL TO {RR|CS|UR|RS|NC} {RR, RS, CS, UR, NC}

DB2 9 vs Oracle 10g© 2008 IBM Corporation 90

DB2 Information Management

동시성잠금모드

Applicable ObjectLocking Mode

RowsW (Weak Exclusive)

Table spaces, tables Z (Super Exclusive)

Rows, blocks, tables, buffer poolsX (Exclusive)

RowsNW (Next Key Weak Exclusive)

Rows, blocks, tables U (Update)

Table spaces, blocksSIX (Share with Intent Exclusive)

Table spaces, blocks, tables IX (Intent Exclusive)

Rows, blocks, tables S (Share)

RowsNS (Next Key Share)

Table spaces, blocks, tables IS (Intent Share)

Table spaces, blocks, tables IN (Intent None)

DB2 9 vs Oracle 10g© 2008 IBM Corporation 91

DB2 Information Management

동시성잠금타입호환성

Legend:YES - grant lock requested immediately NO - wait for held lock to be released or timeout to occur

NOYESNONONONONONONONONOYESYESW

YESNONONONONONONONOYESNOYESYESNW

NONONONONONONONONONONONOYESZ

NONONONONONONONONONONOYESYESX

NONONONONONONONONOYESNOYESYESNX

NONONONONONONONOYESYESYESYESYESU

NONONONONONONONONONOYESYESYESSIX

NONONONONONONOYESNONOYESYESYESIX

NONONONONOYESNONOYESYESYESYESYESS

NOYESNONOYESYESNONOYESYESYESYESYESNS

NONONONONOYESYESYESYESYESYESYESYESIS

YESYESNOYESYESYESYESYESYESYESYESYESYESIN

YESYESYESYESYESYESYESYESYESYESYESYESYESNone

W NW Z X NX U SIX IX S NS IS IN None STATEREQUESTED

STATE OF HELD RESOURCE

DB2 9 vs Oracle 10g© 2008 IBM Corporation 92

DB2 Information Management

동시성DB2 잠금튜닝

● LOCKLIST 잠금정보를저장하는메모리

● LOCKTIMEOUT 응용프로그램이잠금을획득하기위해기다리는시간(초)

● MAXLOCKS Lock escalation이일어나는 LOCKLIST 중의비율

● DLCHKTIME Deadlock 발생점검주기

● SET CURRENT LOCK TIMEOUT [ WAIT | NOT WAIT | NULL | WAIT integer ]

트랜잭션내에서 Lock timeout 값등록

● ALTER TABLE…LOCKSIZE BLOCKINSERT Insert 잠금을최소화하는 MDC 테이블옵션

DB2 9 vs Oracle 10g© 2008 IBM Corporation 93

DB2 Information Management

동시성TPC-C: OLTP 벤치마크

● “벤치마크는 DB2 동시성이효율적임을증명”DB2는비슷한 H/W구성에서 Oracle보다성능상우수

DB2 9 vs Oracle 10g© 2008 IBM Corporation 94

DB2 Information Management

동시성SAP 벤치마크 –가장큰 OLTP 벤더

● “벤치마크는 DB2 동시성이효율적임을증명”SAP 테스트에서 DB2는최고의성능을내는데이터베이스

DB2 9 vs Oracle 10g© 2008 IBM Corporation 95

DB2 Information Management

MVRC 와 ANSI 분리레벨Oracle 분리레벨

Oracle은 Multi Version Read Consistency (MVRC) 분리레벨사용• Query에서보는데이터는시작시점의존재데이터• Any statement seeing an update "rolls back" to get an older version of the data

- 잠금비용을줄이는경우도있으나, I/O 비용을항상증가시킴- 모든 변경될 가능성 있는 data block들은 물리적인 복사본(undo tablespace에기록)이항상필요하기때문

- 디스크요구량증가- Cache 사용량증가- Log 사용량증가

• 일기만 하는 Transaction은 writer를 기다리지 않으나, 읽어온 데이터가 구 데이터일

가능성이있음

- 이이슈는 MVRC에만존재두개의 “WITH UPDATE”문장은서로를기다려야함더구나 Oracle은벤치마크테스트시에는 “serializable” 분리레벨을 사용 (See Oracle TPC-C benchmark to see it widely uses serialized isolation.)

DB2 9 vs Oracle 10g© 2008 IBM Corporation 96

DB2 Information Management

MVRC 와 ANSI 분리레벨Oracle 분리레벨문제점

Oracle MVRC는여러가지문제유발• 다른 RDBMS들은이분리레벨을사용하지않음• ANSI 기반의 J2EE 분리모델과매치되지않음• 확약된트랜잭션도 Update문이전에시작되었으면구데이터를읽어감.• 보관된구데이터를찾기위해추가적인 CPU 자원이필요• 동일한 Block의데이터가여러버전 Cache되어, cache의효율성이떨어짐• Undo Tablespace(9i이전 : Rollback segments)가필요• RBS는복구를위해 redo log에저장됨• RBS는 Oracle DBA에게는문제가많음

► 구데이터보관을위해추가적은디스크필요

► Segment의크기및숫자관리필요► Transaction의크기나기간을알필요가있음► Sync가이루어지지않으면, Oracle은트랜잭션을취소시킴► ORA-01555 에러발생 (snapshot old) 시해결방법

▪ DBA가 RBS의크기를늘려주거나숫자를늘려해결▪ 개발자가자주 Commit을자주찍지않도록수정하여해결

DB2 9 vs Oracle 10g© 2008 IBM Corporation 97

DB2 Information Management

MVRC 와 ANSI 분리레벨실상황예제

Reserve seat.Commit Transaction

Commit Transaction.

Successful Commit with lost update.Flight is oversold!

SELECT available seats on flight ABC111.Also see 23F available as Oracle goes to rollback segment to get the old version of that block.

SELECT available seats from flight ABC111. See seat 23F is last available.Reserve seat.

Begin Transaction

Begin Transaction.

Transaction 2Transaction 1

첫번째예제: MVRC 두번째예제: MVRC force serializingDB2와유사

SELECT returns with no seats available.

Commit Transaction.

Book on another flight.

SELECT available seats on flight ABC111 using FOR UPDATE.Blocks wait on lock from first transaction.

SELECT available seats from flight ABC111 using FOR UPDATE clause. See seat 23F is last available.Reserve seat.

Begin Transaction

Begin Transaction.

Transaction 2Transaction 1

DB2 9 vs Oracle 10g© 2008 IBM Corporation 98

DB2 Information Management

MVRC 와 ANSI 분리레벨벤치마크테스트에서의프로그램코딩

● TPC-C 벤치마크발표보고서에의하면…질문: 왜 Oracle은 MVRC를사용하지않는가?답변: 최고도의트랜잭션시스템에서는 Overhead가너무많기때문!

DB2 9 vs Oracle 10g© 2008 IBM Corporation 99

DB2 Information Management

MVRC 와 ANSI 분리레벨DB2 분리레벨

DB2는 ANSI 표준분리레벨을사용• RR –모든참조되는행을잠금• RS -모든검색된행에대해잠금• CS –현재처리되고있는행에대해서만잠금• UR –어떤행도잠그지않음

현재의확약된데이터만을읽도록트랜잭션을나열하는게기본

UR 분리레벨은 Dirty Read를허용하여, Reader가Writer를기다리지않게함DB2는 Undo(rollback) 오버헤드를가지지않음DB2는행수준잠금은진정한행수준잠금이며, 메모리에저장

• Oracle의 SCN은물리데이터블록의헤더에저장• Oracle의 SCN은동일한페이지의행을필요로하는다른트랜잭션에의해변경될수있음.

자주 commit을 하지 않도록 짜여진 Oracle응용프로그램을 DB2로 전환 시에는 많은 Locking을유발하게됨. 그러나반대로,

• 자주 commit을하도록짜여진 DB2 응용프로그램을 Oracle에전환시에는많은 ORA-01555 에러가발생될수있다

MVRC가벤치마크에서어떻게사용되었는가?TPC-H (warehousing), SAP, PeopleSoft, Baan (OLTP) 테스트에서 DB2 가선두!TPC-C테스트에서, ORACLE은

ƒ MVRC와 ORA-01555의에러핸들링을 Skip하며코딩했는가?ƒ 왜결과를얻기위해 serializable분리레벨을사용했는가?ƒ 그럼에도불구하고왜여전히 DB2에비해처리량이낮은가?

DB2 9 vs Oracle 10g© 2008 IBM Corporation 100

DB2 Information Management

잠금Oracle 행수준잠금

Oracle 잠금접근• 해당데이터페이지에 lock 정보를저장• 모든 data 및 인덱스 페이지에는 동시에 접근하는 트랜잭션 수에 따라 가변적으로 늘어나는

Transaction layer 가있다.• 모든트랜잭션은해당페이지내에 ITL(Interested Transaction List)에하나의엔트리를추가한다.• 동일한페이지를액세스하는트랜잭션이많아질수록, transaction layer의크기는커짐

비용

• 디스크공간 Overhead• 디스크속도 Overhead• MAXTRANS는 ITL의수를제한• DBA는 “hot”테이블에대한 disk overhead와 MAXTRANS에대해고려필요• MAXTRANS에도달하면, Transaction들은 “sleep”됨

장점

• 메모리불필요

DB2 9 vs Oracle 10g© 2008 IBM Corporation 101

DB2 Information Management

잠금DB2 행수준잠금

DB2 잠금접근• 모든잠금은이름을가짐 (Lock Request Block 또는 LRB)• Lock이요청될때, LRB가 locklist메모리영역에저장됨• 다중 응용프로그램이 동일한 레코드를 exclusive 모드로 잠그려고 하면, DB2는 first come first served 에의해링크목록을생성함.

• 다중응용프로그램이 reading을위해서는공유가능• 링크목록은 lock을사용하는 transaction과 lock을기다리는 transaction 정보를모두포함• Transaction이 lock을기다릴때, semaphore에서기다림(Oracle 처럼 sleep timer가아님)• 첫번째 transaction이 lock을해제하면, 다음 transaction 으로 lock의 ownership이전수됨

비용

• 메모리가필요장점

동일한 행에 대해 x-Lock을 필요로 하는 transaction은 먼저 선점한 Transaction이 lock을 해제할 때가지기다려야함. 순서대로처리됨.디스크보다빠르고, 사용을마치면사라짐ƒ 데이터베이스가다운되었을때, Lock이필요한가?ƒ "Hot“테이블들은 DB2의 Lock escalation에의해행수준잠금의수를줄임.ƒ Lock escalation은 Oracle에는없음. Memory locking에만있음

DB2 9 vs Oracle 10g© 2008 IBM Corporation 102

DB2 Information Management

Row-level LockingRow-level LockingMechanism

디스크에 저장

Data Page가 있는 동일 블록에 저장

메모리에 저장

LOCKLIST 공간관리

48 bytes + 24 bytes per transaction68 bytes fixed소요 바이트

•Lock을 요청한 순서대로 처리

•Lock은 일시적인 정보일 뿐 데이터베이스가 다운되면

붚필요한 정보이므로 메모리 관리가 더 효율적

•“Hot table”에 대한 효율적/동적 Lock Escalation (메모리

공간 절약 및 성능 향상)

•Locking을 위한 메모리 공간 필요

DB2 9

•Locking을 위한 메모리 불필요

장점

•추가 디스크 공간 필요

•디스크 I/O 필요

•MAXTRANS 가 최대 Lock을 제한

•MAXTRANS에 도달하면 트랜잭션은 정지

•DBA는 대량의 Lock을 요구하는 “Hot table”의

Overhead를 고려하여 테이블 공간 설계가 필요함

고려사항

Oracle 10gLocking

Locking 비교

DB2 9 vs Oracle 10g© 2008 IBM Corporation 103

DB2 Information Management

감사합니다