顯示具有 DB2 標籤的文章。 顯示所有文章
顯示具有 DB2 標籤的文章。 顯示所有文章

2011年8月21日 星期日

DB2 tips

下列指令依序列出資料庫中index的使用率

db2pd -db MY_DATABASE -tcbstats index

建立表格的MDC(Multiple Dimensinal Clustering) index。MDC比一般的Clustering index好的一點在於它會自動維護data的clustering,不像一般的Clustering index,隨著資料的異動,Clustering ratio會越來越低。且一般來說,MDC的效能會比較好。不過要注意的是MDC的dimention必需選擇cardinality較低的column,如此一來,一個Cell才可以包含愈多的範圍,可節省所需建立的Block數(即extent)

名解解釋:Cell是MDC中,每個dimension的值的交集,每個Cell至少會被指定一個Block

CREATE TABLE T1 
    (c1 DATE, 
     c2 INT, 
     c3 INT, 
     c4 DOUBLE, 
     c5 INT generated always as (INT(C1)/100) ) 
    ORGANIZE BY DIMENSIONS (c5, c3)

2011年7月19日 星期二

Trusted Context in DB2

在過去的3-tier應用程式中,App Server使用一個固定的user name與後端的DB Server建立起連結。這種作法容易造成必需grant給該user name所有的權限,才能讓App Server操作所有的功能,因而無法達到較細緻化的權限控管。然而,App Server若要為每一個應用程式的End User都建立一個connection的化,又太過耗費系統資源。

DB2的Trusted Context即是設計來解決這樣的問題。如下圖(擷自此),只要在DB2 定義一個Context物件,並且在上面設定可以套用該Context的條件(如連線的IP)。當符合這些條件的App Server在建立Connection時,就可以連結到這個Context物件。一但與這個Context物件連結,App Server可以動態更換End User的ID,而不需重新建立Connection。如此一來,就可以讓同一個Connection給不同的End User使用。

Three-tier application model with trusted context

以下為建立Trusted Context之語法(詳細語法介紹可參照參考資料2)

CREATE TRUSTED CONTEXT contextName BASED UPON CONNECTION USING
SYSTEM AUTHID root_authorization_name
ATTRIBUTES (ADDRESS 'ip_addr', ENCRYPTION 'NONE')
WITH USER FOR other_user_authorization_name with authentication

其中,root_authorization_name為此Trusted Context所連結的使用者ID,只有這個使用者才能從App Server建立Trusted Connection;另other_user_authorization_name則是App Server在換end user  ID時,可以更換的user id。

建立好之後,可以用下列sample code來進行測試

public class TestDB2TrustedContext {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DB2ConnectionPoolDataSource dataSource = new DB2ConnectionPoolDataSource();
        dataSource.setDatabaseName("PULI");
        dataSource.setServerName("localhost");
        dataSource.setPortNumber(50000);
        dataSource.setDriverType(4);
        Properties properties = new Properties();
        String user = "rootUser";
        String password = "rootPassword";
        try {
            /*傳回的 objects[0]為DB2PooledConnection
             *      objects[1]為之後要更改user name時,所要給的cookie
             */
           Object[] objects = dataSource.getDB2TrustedPooledConnection(
                    user,password, properties);
            DB2PooledConnection pooledConn = (DB2PooledConnection) objects[0];
            Connection conn = pooledConn.getConnection();
            PreparedStatement stmt = conn.prepareStatement("Select name from db2admin.basicinfo fetch first 10 rows only");;
            ResultSet result = stmt.executeQuery();
            while (result.next()){
                System.out.println(result.getString(1));
                Thread.sleep(500);
            }
            byte[] cookie = (byte[])objects[1];
            String newUser="otherUser";
            String newPwd = "otherPasswd";
            /*Mainframe才要用的*/
            String userRegistry = "registry";
            /*先不要給Security Token*/
            byte[] userSecTkn = null;
            /*先前的使用者ID,可不給*/
            String originalUser = null;
            /*重用舊的connection,並重新設定使用者名稱*/
           conn =
                  ((com.ibm.db2.jcc.DB2PooledConnection)pooledConn).getDB2Connection(
                     cookie,newUser,newPwd,userRegistry,userSecTkn,originalUser,properties);
            PreparedStatement stmt2 = conn.prepareStatement("Select name from db2admin.basicinfo fetch first 10 rows only");;
            ResultSet result2 = stmt2.executeQuery();
            while (result2.next()){
                System.out.println(result2.getString(1));
                Thread.sleep(500);
            }      
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

參考資料

  1. http://www.ibm.com/developerworks/data/library/techarticle/dm-0609mohan/
  2. Create Trusted Context語法

2011年3月3日 星期四

匯出 DB2 Catalog 的指令

有的時候需要把Server所Catalog的Database或Node轉移到別台Server,此時可以使用db2cfgexp(負責匯出 catalog)及db2cfgimp(負責匯入catalog) 來做Catalog資訊的轉移。使用方式如下

匯出:
db2cfexp fname [ template | backup | maintain ]:

其中 fname為輸出檔名, [template | backup | maintain ]為匯出的選項

匯入:
db2cfgimp fname

其中,fname為要匯入的檔名

2011年1月17日 星期一

使用LOAD解決無法匯入含有Generated Always的表格之方法

資料來源:http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/core/r0008304.htm

在設計資料庫的schema時,若針對Primary Key有設定Generated Identity屬性,在load資料時,會出現無法匯入的訊息,此時可以在LOAD    command中加上 modified by identityoverride 選項,如此一來,就會把 source table的identity column的值直接覆蓋到target table的identity column。範例指令如下

db2 load from load.del of del modified by identityoverride 
replace into table1


進階資訊(其它Import/Export/Load會用到的modifier,以及Import/Export/Load對這些modifier的支援)

http://www.ibm.com/developerworks/data/library/techarticle/dm-0405melnyk/index.html

2011年1月16日 星期日

更改DB2 Server Name---透過db2nodes.cfg

執行db2指令時,系統回報這個錯誤 Error in the db2nodes.cfg file at line number "1".  Reason code "10",經過google搜尋後,發現是因為該系統是由其它系統image複製過來,因此sqllib/db2nodes.cfg的hostname設定與目前機器的hostname不符。以下紀錄解決方法

db2nodes.cfg記錄了每個DB2 partition的資訊,其內容格式如下

nodenum    hostname    logical port   netname    resourcesetname

其中nodenum, hostname及logical port為必要的三個欄位。依據(http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/start/r0006351.htm)的說明,nodenum為介於 0999 之間的專用號碼,可識別分割資料庫系統中的資料庫分割區伺服器;hostname為資料庫伺服器所在的Hostname;logical port為資料分割伺服器的邏輯埠號。以下為不同的配置範例

一台電腦,四個資料庫分割區伺服器

如果您不是使用叢集環境,且想讓名為 ServerA 的實體工作站有四個資料庫分割區伺服器,則可更新 db2nodes.cfg 檔,如下所示:
   0          ServerA        0
1 ServerA 1
2 ServerA 2
3 ServerA 3

兩台電腦,每台電腦有一個資料庫分割區伺服器
如果您想讓分割的資料庫系統包含兩個名為 ServerAServerB 的實體工作站,則可更新 db2nodes.cfg 檔案,如下所示:

   0          ServerA        0
1 ServerB 0

兩台電腦,每台電腦有三個資料庫分割區伺服器
如果您想讓分割的資料庫系統包含兩個名為 ServerAServerB 的實體工作站, 且讓 ServerA 執行 3 個資料庫分割區伺服器,則可更新 db2nodes.cfg 檔案,如下所示:

   4          ServerA        0
6 ServerA 1
8 ServerA 2
9 ServerB 0

兩台電腦,具有高速切換的三個資料庫分割區伺服器
如果您想讓分割的資料庫系統包含兩台名為 ServerAServerB (ServerB 執行兩個資料庫分割區伺服器) 的電腦,並且使用名為 switch1switch2 的高速交互連接,則可更新 db2nodes.cfg 檔案,如下所示:

   0          ServerA        0              switch1
1 ServerB 0 switch2
2 ServerB 1 switch2


設定完成後,執行db2stop/db2start即可。詳細說明可看(http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/start/r0006351.htm)



#For Windows



DB2 windows版本的db2nodes.cfg在 DB2 v8及v9.1,是放在Program Files\IBM\SQLLIB\DB2\db2nodes.cfg中;而在9.5及以上,是放在Documents and Settings\All Users\Application Data\IBM\DB2\<DB2COPY>\DB2\db2nodes.cfg中。手冊建議不要直接修改檔案內容,可透過下列指令達到修改hostname目的




    db2nchg /n:nodeNumber /h:hostName


上述指令可以修改 node的 hostName,其中,在沒有partition的環境下,nodeNumber為0。



詳細db2nchg指令用法在此。另外,可以用db2nlist最出目前資料庫有那些nodes




2010年4月30日 星期五

DB2 Import資料時,設定來源資料 Date的格式

在使用 db2 import 指令匯入 DEL 格式的來源資料時,若來源資料中,date資料的表示方式與DB2預設的date表示方式不同,會造成無法匯入資料的問題。此時,可以在import指令中使用 modified by dateformat=’YYYY/MM/DD’來更改DB2預設的 date表現方式。參加下列指令

IMPORT FROM "USERS.csv" OF DEL modified by dateformat="YYYY/M/D" METHOD P (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17) MESSAGES "C:\log"  INSERT INTO DB2ADMIN.USERS (USER_ID, FIRST_NAME, MIDDLE_NAME, LAST_NAME, BIRTHDAY , GENDER, ID_CARD, EMERGENCY_CONTACT, IS_CAREPROVIDER, IS_AA_USE_MAC, ADDRESS, EMAIL, PHONE, STATUS, CREATE_TIME, ID, UPDATED)

以下舉幾個date表現方式的例子 (注意1個M和2個M的差別):

YYYY/MM/DD:   可以對應到   1978/01/01
YYYY/M/D:       可以對應到   1978/1/1

2010年4月24日 星期六

使用 DB2 pureXML的功能將XML文件Shred到 Relational Tables

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
本介紹使用的例子是在這篇 developerworks文章所附的範例。將這個範例解開後,可發現內含下列內容

image

其中,crdb及crtable分別為建立資料庫及 表格的SQL指令。首先需先使用這兩個檔案,建立所需的表格。而mail.xml是要匯入的XML檔案;mails.xsd則為該XML的schema檔案。
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

在DB2 V9中,可以使用下列兩種方式,將XML文件轉成Relational表格儲存

  1. 使用 Annotated XML decomposition功能
  2. 使用 XMLTABLE  functional call

其中,第一種方式需要將Annotated 過的 XML Schema註冊到 DB2的 XML Schema Repository(XSR)。Data Studio這個免費的程式可以協助在XML schema中進行annotation。Annotate 完成之後,再將其註冊到XSR中。註冊的方式有很多種,可以使用DB2 Command Line、呼叫DB2 提供的 Stored Procedure,或是直接用Java程式,透過DB2提供的JDBC Driver進行。這裡先介紹使用Command Line的方式

  1. REGISTER    XMLSCHEMA     ADD    'http://yourschemaURI'    FROM      'Schema檔案所在位置'     AS  userSchemaName.SchemaName
  2. 如果要匯入的XML Schema由多個Schema檔案組成,先使用上面的指令匯入主要的Schema後,再使用下列指令,加入其它的Schema檔案 
    ADD    XMLSCHEMA    DOCUMENT      TO     userSchemaName.SchemaName       ADD     ‘http://anotherSchemaURL’   FROM        ‘Schema檔案所在位置’
  3. 使用下列指令,完成Schema的註冊
    COMPLETE     XMLSCHEMA         userSchemaName.SchemaName

上面所述的  userSchemaName.SchemaName中, userSchemaName指的是 DB2的 Schema命名空間名稱;而SchemaName則是指匯入的Schema的XML Schema命名空間。

註冊完成後,還需啟用所匯入的Schema的 XML Decomposition功能。指令如下:
ALTER      XSROBJECT    xsrObjectName       ENABLE        DECOMPOSITION

最後,透過下列程式,可以將一個XML文件內容,轉成Relational Table。

///////////////////////////////////////////////////////////////////////////////
import java.sql.*;
import java.io.*;
public class AnnotatedXMLDecomposition {
/**這個程式用來測試使用DB2提供的Annotated XML Decomposition方法,來將XML的資料 parse到Relational Table中
* 使用這個方法來shred XML的前提是,DB2的 XSR(XML Schema Repository)必需先註冊要 Shred文件的 XML Schema。
* 註冊XML Schema的方法有很多,最簡單的方法是在DB2 Command Line中,執行下列指令
*      REGISTER XMLSCHEMA ADD 'http://yourschemaURI'
*                    FROM 'SchemaFileLocation' AS  userSchemaName.SchemaName
*     
*      其中,userSchemaName指的是 DB2的 current Schema name
*
*/
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String url = "jdbc:db2:MAILDCMP";
        try {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
            Connection con = DriverManager.getConnection(url);//取得Connection
            String sql = "{CALL xdbDecompXML(?,?,?,?,?,NULL,NULL,NULL)}";
            CallableStatement cstmt = con.prepareCall(sql);
            String filename = "E:/DB2_pureXML_Study/mail/mail/mail.xml";
            File currFile = new File(filename);
            long length = currFile.length();
            //設定DB2 current Schema名稱
            cstmt.setString(1, "BIOFLASH");
            //設定 XML Schema名稱
            cstmt.setString(2, "MAILSCHEMA");
            //讀入XML文件
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(currFile));
            cstmt.setBinaryStream(3,bis, (int) length);
            //XML 文件 ID
            cstmt.setString(4, "TEST001");
            //設定要不要進行XML的 Schema validation
            int validate = 1;
            cstmt.setInt(5, validate);
            //其它的參數先放為NULL
            cstmt.execute();
            con.commit();
            cstmt.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (SQLException e){
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
        }
    }

}

/////////////////////////////////////////////////////////

2009年12月15日 星期二

DB2 Process Model

從接到應用程式的請求開始,DB2就由一連串的agent(又稱EDU, Engine Dispatchable Units)協同作業,完成使用者的請求。9.5版以前,除了Windows是使用Thread model外,Unix和Linux都是使用Process model來建立這些agent,較耗費系統資源。9.5版以後,所有的agent統一使用Thread model。

如下圖所示,依據使用的Protocol不同,每一個Instance都會有一個相對應的Listener來等候使用者的請求,Listener有下列三種

  • db2ipccm:處理來自Local Client的請求,當client與server位於同一個OS image,可以使用IPC的 protocol與此Listener溝通
  • db2tcpcm:處理遠端Client的請求,當client 與server位於不同OS image時,使用TCP/IP與此Listener溝通
  • db2tcpdm:處理DB2的 Discovery工具所發出的請求,DB2有個Discovery工具可以找尋遠端的Instance中,有那些資料庫可以使用。這類的請求由此Listener處理

image

Listener接受到請求後,會指定一個coordinator agent(db2agent)給該應用程式連線,被assign的db2agent就在DB2中,擔任應用程式的代理人,負責與應用程式溝通,處理應用程式的請求。若在一個Partitioned的資料庫環境,或INTRA_PARALLEL參數設為Yes時,coordinator agent會再把工作交代給 subagent來處理,coordinator agent的角色就變成協調這些subagent完成工作。

如果Access Plan Manager分析結果產生的 Access Plan表示需要進行Prefetch,coordinator agent會送 prefetch的請求到 Prefetch Queue。每個資料庫都有一個Prefetcher,prefetcher從Queue中取得請求後,會把資料由Disk讀取到Bufferpool中。一但資料存在Bufferpool後,coordinator就可以依據應用程式的需求更新資料,更新的資料會暫存在bufferpool中,直到page cleaner將其再寫回Disk。

除此之外,每個應用程式所發出的交易都會由 logger這個agent寫入 transaction log,以備recovery之需。

下圖展示每個agent作用的範圍

image

接下來介紹db2相關的process。如前所述,9.5版以後 agent是採用thread model,所有的agent都成為依附在主 process下的一個thread,如此一來可大幅減少

Process名稱 描述 適用平台
db2acd 為autonomic computing的 daemon,用來處理client端與automatic相關的工作,如healther monitor、automatic maintenance utilities等。health-monitor process以一個DB2 fenced mode的process執行,在Windows環境,以db2fmp的方式呈現 只限Linux及Unix
db2ckpwd 在DB2 Server端檢驗使用者的ID/Password 只限Linux及Unix
db2fmcd 預設的fault monitor coordinator daemon,每一個實體的機器會有一個 只限Unix
db2fmd 預設的monitor daemon,每個DB2的instance都有一個fault monitor。這個daemon會受 db2fmcd所監控,若把這個process殺掉,db2fmcd會再把這個process叫起來 只限Unix
db2fmp 在DB2的firewall外,在DB2 server上執行user的code。每個db2fmp基本上都是獨立的process,不過對於某些種類的 runtime,可以用multithread的方式執行 所有LUW平台
db2sysc DB2 System Controller引擎。在DB2 9.5中,每個partition中只會有一個db2sysc引擎 process,所有的EDU(Engine Dispathcable Unit)都會以一個Thread的形式,掛在這個process下。一但這個process停止了,DB2 server就無法作用了。 (p.s. 在Windows平台中,這個process名稱為 db2syscs) 所有LUW平台
db2vend Fenced vendor process,這是在DB2 9.5版後才引進。在Threaded的引擎下,DB2無法讓vendor的code更改它的signal mask、啟動新的thread或破壞agent的stack。所以所有的vendor code都是獨立於DB2 engine外,在這個process執行 只限Linux及Unix
db2wdog DB2 watchdog. 這個process是db2sysc的 parent process,負責下列internal事項
  - 當db2sysc不正常結束時,清除IPC資源
  - 產生 db2fmp及 health-monitor process。當這些process不正常結束時,清除該db2fmp佔用的系統資源,若需要重啟health monitor,也會進行重啟動作
只限Linux及Unix

2009年12月12日 星期六

DB2 Database Performance Tuning實例

目前進行一個應用系統的效能測試,所測試的交易含有大量的資料庫Select/Insert/Update的動作,執行完一次交易大概要執行大約3、4千行的 Dynamic SQL語句。測試結果發現效能非常地差,同時50個使用者執行該交易,就需要32分鐘才能將交易做完,利用nmon來監控其CPU使用率發現這30多分鐘的CPU都是滿載使用。

image

因為這樣的效能實在不能接受,因此開始進行DB2及應用程式的效能調整,因為是第一次有機會做這樣的測試,所以一切就在邊作邊學的過程進行,幸好DB2 Infocenter寫的都還滿詳細的,讓我能一步步達到我的目的。接下來就分享整個Tunning的過程。

首先,要找出使應用程式DB使用效能的原因,我們必需啟用DB2的 monitor switch收及一些統計資訊,輸入 DB2 GET MONITOR SWITCHES 指令可以得到目前這些switche的狀態。

[db2inst1@db01 source_db]$ db2 get monitor switches

            Monitor Recording Switches

Switch list for db partition number 0
Buffer Pool Activity Information  (BUFFERPOOL) = OFF
Lock Information                        (LOCK) = OFF
Sorting Information                     (SORT) = OFF
SQL Statement Information          (STATEMENT) = OFF
Table Activity Information             (TABLE) = OFF
Take Timestamp Information         (TIMESTAMP) = ON  12/12/2009 15:13:18.256534
Unit of Work Information                 (UOW) = OFF

如上面所示,目前除了TIMESTAMP這個預設會打開的switch外,其它都是關閉的狀態,要啟動任一個 switch只需輸入 db2 UPDATE MONITOR SWITCHES USING XXX ON,比方說若要啟用LOCK這個switch的話,就輸入db2 UPDATE MONITOR SWITCHES USING LOCK ON,結果如下

[db2inst1@db01 source_db]$ db2 update monitor switches using lock on
DB20000I  The UPDATE MONITOR SWITCHES command completed successfully.

回到DB2的效能檢視,因為DB2的使用率已達到100%,因此暫不朝向有太多lock的方向思考,且db2 v9版以後,已經有很多Database Configuration參數,如heap size、bufferpool等都可以動態調整了,也不朝向Database Configuration的方向思考。排除上述的因子後,決定直接看 SQL執行的效能如何。

要查看SQL執行效能,首先要把 STATEMENT 這個 Monitor Switch打開,如下

[db2inst1@db01 source_db]$ db2 update monitor switches using statement on
DB20000I  The UPDATE MONITOR SWITCHES command completed successfully.

接著模擬1個使用者,執行所要測試的交易,交易執行完後,使用 GET SNAPSHOT FOR DYNAMIC SQL ON    database_name  的指令,收集執行一次交易,所有會執行的dynamic SQL統計資訊。將其導向一個檔案

[db2inst1@db01 source_db]$ db2 get snapshot for dynamic sql on test_db > executed_sql

檢視該檔案,可發現每一筆錄到的dynamic SQL的Snapshot的格式如下,在這裡會用到的是 Total Execution Time、Total CPU Time及 SQL statement這三個欄位的資訊(用藍色標出的部分)

Number of executions               = 1
Number of compilations             = 1
Worst preparation time (ms)        = 7
Best preparation time (ms)         = 7
Internal rows deleted              = 0
Internal rows inserted             = 0
Rows read                          = 1590
Internal rows updated              = 0
Rows written                       = 0
Statement sorts                    = 0
Statement sort overflows           = 0
Total sort time                    = 0
Buffer pool data logical reads     = Not Collected
Buffer pool data physical reads    = Not Collected
Buffer pool temporary data logical reads   = Not Collected
Buffer pool temporary data physical reads  = Not Collected
Buffer pool index logical reads    = Not Collected
Buffer pool index physical reads   = Not Collected
Buffer pool temporary index logical reads  = Not Collected
Buffer pool temporary index physical reads = Not Collected
Buffer pool xda logical reads      = Not Collected
Buffer pool xda physical reads     = Not Collected
Buffer pool temporary xda logical reads    = Not Collected
Buffer pool temporary xda physical reads   = Not Collected
Total execution time (sec.microsec)= 25.435582
Total user cpu time (sec.microsec) = 25.377444
Total system cpu time (sec.microsec)= 0.000000
Total statistic fabrication time (milliseconds) = 0
Total synchronous runstats time  (milliseconds) = 0
 
Statement text                     = SELECT CURR_NO,   DEPT_NO,        GL_ACCT_NO,     SUM(CASH_DR_NO_OF_VOH) CSHDRVOH,        SUM(TRANSFER_DR_NO_OF_VOH) TRNDRVOH,    SUM(CASH_CR_NO_OF_VOH) CSHCRVOH,        SUM(TRANSFER_CR_NO_OF_VOH) TRNCRVOH   FROM ACCT01  T1  WHERE VOH_SEQ_NO = (SELECT MIN(VOH_SEQ_NO) FROM ACCT01                   WHERE T1.VOH_NO = VOH_NO                        AND T1.BRANCH_NO = BRANCH_NO)   AND VOH_DATE = '20090518'       AND VOH_DATE = ORG_VOH_DATE     AND (VOH_SPLIT_NO = '00' OR VOH_SPLIT_NO = '99')        AND BRANCH_NO = '9964' GROUP BY CURR_NO, DEPT_NO, GL_ACCT_NO

因為所錄到的SQL數量非常龐大,無法用肉眼找出那些SQL耗掉最多的CPU time,因此在這裡寫了一個簡單的小程式來過濾這些record。程式內容如下(下列程式會挑出所有執行時間大於0.5秒的SQL,若要改成其它時間,只需在藍色該行的if 敘述中改為其它值

#!/usr/bin/perl
undef $/;
my $data = <>;
my $long_execution_sql_count=0;
while($data=~/(Total execution time \(sec.microsec\)= (.+?)\n.+?\n.+?\n.+?\n.+?\n.+?\n)/g)
{
        if ($2>0.5)          #這裡使用0.5會挑出所有執行時間大於0.5秒的SQL。
        {
                print $1,"\n";
                $long_execution_sql_count++;
        }
}

print "Total Long Execution SQLs: ",$long_execution_sql_count;

使用此小程式來過濾Dynamic SQL snapshot 所錄到的結果,可發現這個應用程式最耗時的SQL語句如下:

 Total execution time (sec.microsec)= 27.081611 
Total user cpu time (sec.microsec) = 27.067162
 
Total system cpu time (sec.microsec)= 0.000000
Total statistic fabrication time (milliseconds) = 0
Total synchronous runstats time  (milliseconds) = 0
Statement text                     = SELECT CURR_NO, DEPT_NO, GL_ACCT_NO, SUM(CASH_DR_NO_OF_VOH)CSHDRVOH,
          SUM(TRANSFER_DR_NO_OF_VOH)TRNDRVOH, SUM(CASH_CR_NO_OF_VOH)
          CSHCRVOH, SUM(TRANSFER_CR_NO_OF_VOH)TRNCRVOH
  FROM ACCT01 T1
  WHERE VOH_SEQ_NO =
     (SELECT MIN(VOH_SEQ_NO)
     FROM ACCT01
     WHERE T1.VOH_NO =VOH_NO AND T1.BRANCH_NO =BRANCH_NO)AND VOH_DATE
          ='20090518' AND ORG_VOH_DATE= '20090518' AND (VOH_SPLIT_NO = '00' OR VOH_SPLIT_NO = '99')
          AND BRANCH_NO ='9964'
  GROUP BY CURR_NO, DEPT_NO, GL_ACCT_NO

是的,只單單執行一次這個SQL就要花費 27秒,很顯然地,它就是要被tune的SQL。接下來使用db2expln這個命令來Explain DB2的Optimizer倒底是如何來執行這個SQL的,下面範例會把explain的結果,輸出到 sql_explain這個檔案中。先把上述要explain的SQL語句,寫入input_sql這個檔案中,執行下列指令

[db2inst1@db01 ~]$ db2expln -database test_db -stmtfile input_sql -terminator ';' -o sql_explain -graph

DB2 Universal Database Version 9.5, 5622-044 (c) Copyright IBM Corp. 1991, 2007
Licensed Material - Program Property of IBM
IBM DB2 Universal Database SQL and XQUERY Explain Tool

Output is available in "sql_explain".

接下來檢視sql_explain這個output檔案,以下擷取 Optimizer Plan這個Tree的結果,可以看到這個SQL已經使用Index Search了,所以應該也不是沒建 index的問題。

Rows  
                   Operator
                     (ID)  
                     Cost  
                   1.03085
                   RETURN 
                    ( 1)  
                   4517.06
                     |    
                   1.03085
                    GRPBY 
                    ( 2)  
                   4517.06
                     |    
                   1.03085
                   TBSCAN 
                    ( 3)  
                   4517.06
                     |    
                   1.03085
                    SORT  
                    ( 4)  
                   4517.06
                     |    
                   3.43618
                   NLJOIN 
                    ( 5)  
                   4517.06
                  /       \
          6.87235            0.5  
           FETCH           FILTER 
           ( 6)             ( 8)  
          556.13           3547.89
         /       \           |    
  171.809    5.10504e+06      1   
  IXSCAN     Table:         GRPBY 
   ( 7)      DB2INST1       ( 9)  
  93.3323    ACCT01        3547.89
    |                        |    
5.10504e+06               0.531085
Index:                     IXSCAN 
DB2ADMIN                    (10)  
ACCT01                    3547.89 
                            |      
                        5.10504e+06
                        Index:     
                        DB2ADMIN   
                        ACCT01
     

由上面的Tree可以看到,最大的cost來自Index Scan,判斷可能是因為資料太多而導致,再仔細檢視一下這個耗時的SQL,發現它是由一個主要的Select join Sub-Select的結果組成,且主Select與Sub-Select都是指向同一個Table。看到標示紅色部分的SQL的寫法有點奇怪T1.VOH_NO其實就是VOH_NO;而T1.BRANCH_NO其實就是BRANCH_NO,因為ACCT01這個表格有很多record,如果有500萬筆的record的話,這樣寫就等於做500萬筆對500萬筆資料的比對,難怪會消耗大量的CPU time。

SELECT CURR_NO, DEPT_NO, GL_ACCT_NO, SUM(CASH_DR_NO_OF_VOH)CSHDRVOH,
          SUM(TRANSFER_DR_NO_OF_VOH)TRNDRVOH, SUM(CASH_CR_NO_OF_VOH)
          CSHCRVOH, SUM(TRANSFER_CR_NO_OF_VOH)TRNCRVOH
  FROM ACCT01 T1
  WHERE VOH_SEQ_NO =
     (SELECT MIN(VOH_SEQ_NO)
     FROM ACCT01
     WHERE T1.VOH_NO =VOH_NO AND T1.BRANCH_NO =BRANCH_NO
)AND VOH_DATE
          ='20090518' AND ORG_VOH_DATE= '20090518' AND (VOH_SPLIT_NO = '00' OR VOH_SPLIT_NO = '99')
          AND BRANCH_NO ='9964'
  GROUP BY CURR_NO, DEPT_NO, GL_ACCT_NO

經過與程式開發人員確認後,原本的Sub-select還是有其意義,因此需保留。幸好,他想到在該Sub-select中加入另一個條件,縮小資料的範圍,上述的Sub-select修改如下

SELECT MIN(VOH_SEQ_NO) FROM ACCT01
            WHERE T1.VOH_NO = VOH_NO AND VOH_DATE = '20090518'
             AND T1.BRANCH_NO = BRANCH_NO

結果重新執行這個SQL,就發現CPU time大幅縮小

Total execution time (sec.microsec)= 0.051433
Total user cpu time (sec.microsec) = 0.037532

Total system cpu time (sec.microsec)= 0.000000
Total statistic fabrication time (milliseconds) = 0
Total synchronous runstats time  (milliseconds) = 0
Statement text                     = SELECT CURR_NO, DEPT_NO, GL_ACCT_NO, SUM(CASH_DR_NO_OF_VOH)CSHDRVOH,
          SUM(TRANSFER_DR_NO_OF_VOH)TRNDRVOH, SUM(CASH_CR_NO_OF_VOH)
          CSHCRVOH, SUM(TRANSFER_CR_NO_OF_VOH)TRNCRVOH
  FROM ACCT01 T1
  WHERE VOH_SEQ_NO =
     (SELECT MIN(VOH_SEQ_NO) FROM ACCT01
            WHERE T1.VOH_NO = VOH_NO AND VOH_DATE = '20090518'
             AND T1.BRANCH_NO = BRANCH_NO)AND VOH_DATE
          ='20090518' AND ORG_VOH_DATE= '20090518' AND (VOH_SPLIT_NO = '00' OR VOH_SPLIT_NO = '99')
          AND BRANCH_NO ='9964'
  GROUP BY CURR_NO, DEPT_NO, GL_ACCT_NO

接著再回到50個人來測試這個交易,發現執行時間有所縮減,由原本的32分鐘,縮減至27分鐘,這樣的縮減還是無法令人滿意…

再做一次 Dynamic SQL statement 的 Snapshot,發現大多數的SQL statement的執行時間都在3秒以內,只是CPU time 只要0.07秒!  這應該是執行時間很久的原因吧!

Total execution time (sec.microsec)= 2.891382
Total user cpu time (sec.microsec) = 0.076323

Total system cpu time (sec.microsec)= 0.000000
Total statistic fabrication time (milliseconds) = 0
Total synchronous runstats time  (milliseconds) = 0
Statement text                     = UPDATE ACCT04   SET CASH_DR_AMT = 0, TRANSFER_DR_AMT = 0, CASH_CR_AMT = 0,        TRANSFER_CR_AMT = 0, CASH_DR_NO_OF_VOH = 0,     TRANSFER_DR_NO_OF_VOH = 0, CASH_CR_NO_OF_VOH = 0,       TRANSFER_CR_NO_OF_VOH = 0,      DR_ACCT_CODE_CURR_BAL = DR_ACCT_CODE_PREV_BAL,          CR_ACCT_CODE_CURR_BAL = CR_ACCT_CODE_PREV_BAL  WHERE TX_DATE =  '20090518'      AND BRANCH_NO = '9963'

檢視一下ACCT04這個表格,它足足佔用了5G的空間,而且這個交易執行非常多次這個SQL,如果時間都等在從這個表格找資料、更新資料,會大幅拖慢交易執行速度。為了避免這個問題,這裡考慮把這個表格放在獨立的 TABLE SPACE中,然後assign給他獨立的Buffer Pool。

以下為建立這個獨立的Buffer Pool的指令
CREATE BUFFERPOOL ACCT04 IMMEDIATE  SIZE 100000 PAGESIZE 4 K ;
再來是建立這個獨立的Table Space的指令,選用上面建立的獨立Buffer Pool
CREATE  LARGE  TABLESPACE ACCT04_TABSPACE PAGESIZE 4 K  MANAGED BY AUTOMATIC STORAGE EXTENTSIZE 64 OVERHEAD 10.5 PREFETCHSIZE 64 TRANSFERRATE 0.14 BUFFERPOOL  ACCT04 ;
最後再把ACCT04這個表格建在新建的 TABLE SPACE上,再執行50人的case時,就發現時間可由原本的 32分鐘縮減到13分鐘,且DB2的 CPU utilization也不會在100%使用率持續太久(如下圖),Tuning暫告完成

image

2009年12月9日 星期三

DB2 List Applications -- 列出目前連結到資料庫的所有應用程式

List application命令可以列出目前連結到資料庫的所有應用程式資訊,若下命令時沒有指定要看那個資料庫,則所有的資料庫連結都會被列出

image

以下為使用 DB2 LIST APPLICATIONS FOR SAMPLE SHOW DETAIL指令後,所得到的資訊

DB2INST1 db2jcc_application 3638 9.181.158.212.38221.09120917185 03285 1 0 273 UOW Waiting 12/10/2009 07:47:53.099138 xxxDB /mnt/db_data/db2inst1/NODE0000/SQL00001/

以下簡介每個欄位所代表意義

DB2INST1: Connection Authentication ID
db2jcc_application : Application Name
3957: Application Handle
9.181.158.212.38221.09120917185 : Application ID
03285: Sequence Number
1: Number of agent
0: Database partition number
273: Coordinator PID
UOW Waiting:Status
12/10/2009 07:47:53.099138:Status change time
xxxDB: DB Name
/mnt/db_data/db2inst1/NODE0000/SQL00001/ : DB Path

DB2 Update Monitor Switches

無論是要使用 event monitor 或是 snapshot monitor,若要監控相關資訊,需要打開相關的monitor switches,使用 get monitor switches可以得到目前 monitor的狀態。

[db2inst1@db01 ~]$ db2 get monitor switches

            Monitor Recording Switches

Switch list for db partition number 0
Buffer Pool Activity Information  (BUFFERPOOL) = OFF
Lock Information                        (LOCK) = OFF
Sorting Information                     (SORT) = OFF
SQL Statement Information          (STATEMENT) = OFF
Table Activity Information             (TABLE) = OFF
Take Timestamp Information         (TIMESTAMP) = ON  12/08/2009 10:20:24.309342
Unit of Work Information                 (UOW) = OFF

若要把某個monitor switch設為 on,使用 update monitor switches for xxx on 的指令,如下列指令可以將 bufferpool這個 switch打開

[db2inst1@db01 ~]$ db2 update monitor switches using bufferpool on

要注意的是,所做的monitor switch更動只限於此次 attach到instance的 session有效,一但離線後再連回去,monitor switch就會被重設為預設值了

重設Monitor Switches值

Monitor switch所收集的值從打開後,會一直累積,若要Reset其數值,可使用 RESET MONITOR 指令,用法如下

image

DB2 GET SNAPSHOT FOR APPLICATION APPLID application_id執行結果

把所有的monitor switch打開後,使用db2 get snapshot for application applid application_id指令,可以得到下列結果。接下來分別描述其所代表意義

Application handle = 3302
Application status = UOW Waiting =>Application status顯示目前應用程式的狀態,UOW waiting代表這個unit of work正在等待此application id所代表的程式在做程式自己的邏輯。若值為 UOWEXEC表示Database Manager正在代替程式執行查詢,這個網址可看到更多的值。
Status change time = 12/09/2009 21:59:47.610770
Application code page = 1208
Application country/region code = 0
DUOW correlation token = xx.xx.xx.xx.xxxx.09120913583
Application name = db2jcc_application
Application ID = xx.xx.xx.xx.xxxx.09120913583
Sequence number = 02139
TP Monitor client user ID =
TP Monitor client workstation name = was03.csc.ibm.com
TP Monitor client application name =
TP Monitor client accounting string =

Connection request start timestamp = 12/09/2009 21:58:28.648173 =>應用程式發出請求要connect資料庫的時間
Connect request completion timestamp = 12/09/2009 21:58:28.658785 =>資料庫接受connection請求的時間
Application idle time = 1 second =>應用程式自最後一次發出request後,經歷了多少時間,此數值可用來強制結束idle過久的應用程式連接
CONNECT Authorization ID = DB2INST1
Client login ID = DB2INST1
Configuration NNAME of client = was03.csc.ibm.com
Client database manager product ID = JCC03530
Process ID of client application = 0
Platform of client application = Unknown via DRDA
Communication protocol of client = TCP/IP

Inbound communication address = xx.xx.xx.xx xxxxx

Database name = xxxxDB
Database path = /mnt/db_data/db2inst1/NODE0000/SQL00001/
Client database alias = xxxxDB
Input database alias =
Last reset timestamp =
Snapshot timestamp = 12/09/2009 21:59:48.269429
Authorization level granted =
User authority:
DBADM authority
CREATETAB authority
BINDADD authority
CONNECT authority
CREATE_NOT_FENC authority
LOAD authority
IMPLICIT_SCHEMA authority
CREATE_EXT_RT authority
QUIESCE_CONN authority
Group authority:
SYSADM authority
CREATETAB authority
BINDADD authority
CONNECT authority
IMPLICIT_SCHEMA authority
Coordinating database partition number = 0
Current database partition number = 0
Coordinator agent process or thread ID = 255
Current Workload ID = 1
Agents stolen = 0
Agents waiting on locks = 0
Maximum associated agents = 1
Priority at which application agents work = 0
Priority type = Dynamic

Lock timeout (seconds) = -1
Locks held by application = 0
Lock waits since connect = 2
Time application waited on locks (ms) = 2
Deadlocks detected = 0
Lock escalations = 0
Exclusive lock escalations = 0
Number of Lock Timeouts since connected = 0
Total time UOW waited on locks (ms) = 0

Total sorts = 920
Total sort time (ms) = 74
Total sort overflows = 2

Buffer pool data logical reads = 391625 =>此為資料直接從bufferpool讀取次數 以及 資料不在bufferpool中,而需I/O到bufferpool才能為CPU讀取的次數總合
Buffer pool data physical reads = 128 =>此為因為資料不在bufferpool,而需先進行I/O將資料讀入bufferpool中,才能被CPU所用的次數 1 - (Buffer pool data physical reads / Buffer pool data logical reads) 即為 bufferpool的hit ratio。Hit ratio愈高,表示要經過實際I/O才能拿到資料的次數愈少,讀取資料所花費的時間會愈少
Buffer pool temporary data logical reads = 8614 => 與前面兩個值類似,只是這個是記錄 temporary table space的buffer pool使用狀況
Buffer pool temporary data physical reads = 0 => 與前面兩個值類似,只是這個是記錄 temporary table space的buffer pool使用狀況
Buffer pool data writes = 0 =>Bufferpool的資料實際寫入disk的次數
Buffer pool index logical reads = 1365796 => 此為index page直接從bufferpool讀取次數 以及 index page不在bufferpool中,而需I/O到bufferpool才能為CPU讀取的次數總合
Buffer pool index physical reads = 934
Buffer pool temporary index logical reads = 0
Buffer pool temporary index physical reads = 0
Buffer pool index writes = 0
Buffer pool xda logical reads = 0
Buffer pool xda physical reads = 0
Buffer pool temporary xda logical reads = 0
Buffer pool temporary xda physical reads = 0
Buffer pool xda writes = 0
Total buffer pool read time (milliseconds) = 32
Total buffer pool write time (milliseconds)= 0
Time waited for prefetch (ms) = 169
Unread prefetch pages = 0
Direct reads = 56
Direct writes = 0
Direct read requests = 8
Direct write requests = 0
Direct reads elapsed time (ms) = 1
Direct write elapsed time (ms) = 0

Number of SQL requests since last commit = 0
Commit statements = 2138
Rollback statements = 0
Dynamic SQL statements attempted = 3426
Static SQL statements attempted = 2138
Failed statement operations = 0
Select SQL statements executed = 631
Xquery statements executed = 0
Update/Insert/Delete statements executed = 1507
DDL statements executed = 0
Inactive stmt history memory usage (bytes) = 0
Internal automatic rebinds = 0
Internal rows deleted = 0
Internal rows inserted = 0
Internal rows updated = 0
Internal commits = 1
Internal rollbacks = 0
Internal rollbacks due to deadlock = 0
Binds/precompiles attempted = 0
Rows deleted = 0
Rows inserted = 0
Rows updated = 3816
Rows selected = 2196
Rows read = 6715606
Rows written = 11779

UOW log space used (Bytes) = 0
Previous UOW completion timestamp = 12/09/2009 21:59:47.307801
Elapsed time of last completed uow (sec.ms)= 0.001300
UOW start timestamp = 12/09/2009 21:59:47.609463
UOW stop timestamp = 12/09/2009 21:59:47.610763
UOW completion status = Committed - Commit Statement

Open remote cursors = 0
Open remote cursors with blocking = 0
Rejected Block Remote Cursor requests = 0
Accepted Block Remote Cursor requests = 631
Open local cursors = 0
Open local cursors with blocking = 0
Total User CPU Time used by agent (s) = 38.172826
Total System CPU Time used by agent (s) = 0.000000
Host execution elapsed time = 40.473861

Package cache lookups = 2138
Package cache inserts = 2097
Application section lookups = 3426
Application section inserts = 2129
Catalog cache lookups = 4257
Catalog cache inserts = 11
Catalog cache overflows = 0
Catalog cache high water mark = 0

Workspace Information

Shared high water mark = 0
Total shared overflows = 0
Total shared section inserts = 0
Total shared section lookups = 0
Private high water mark = 0
Total private overflows = 0
Total private section inserts = 0
Total private section lookups = 0

Most recent operation = Static Commit
Most recent operation start timestamp = 12/09/2009 21:59:47.610752
Most recent operation stop timestamp = 12/09/2009 21:59:47.610763
Agents associated with the application = 1
Number of hash joins = 9
Number of hash loops = 0
Number of hash join overflows = 0
Number of small hash join overflows = 0
Number of OLAP functions = 0
Number of OLAP function overflows = 0

Statement type = Static SQL Statement
Statement = Static Commit
Section number = 0
Application creator =
Package name =
Consistency Token =
Cursor name =
Statement database partition number = 0
Statement start timestamp = 12/09/2009 21:59:47.610752
Statement stop timestamp = 12/09/2009 21:59:47.610763
Elapsed time of last completed stmt(sec.ms)= 0.000011
Total Statement user CPU time = 0.000009 => Database manager agent實際處理應用程式請求的時間,若應用程式有呼叫到 stored procedure,stored procedure執行的時間也包含在內
Total Statement system CPU time = 0.000000 => Database manager agent為了處理應用程式請求,而發出System Call執行的時間
SQL compiler cost estimate in timerons = 0
SQL compiler cardinality estimate = 0
Degree of parallelism requested = 1
Number of agents working on statement = 1
Number of subagents created for statement = 1
Statement sorts = 0
Total sort time = 0
Sort overflows = 0
Rows read = 0
Rows written = 0
Rows deleted = 0
Rows updated = 0
Rows inserted = 0
Rows fetched = 0
Buffer pool data logical reads = 0
Buffer pool data physical reads = 0
Buffer pool temporary data logical reads = 0
Buffer pool temporary data physical reads = 0
Buffer pool index logical reads = 0
Buffer pool index physical reads = 0
Buffer pool temporary index logical reads = 0
Buffer pool temporary index physical reads = 0
Buffer pool xda logical reads = 0
Buffer pool xda physical reads = 0
Buffer pool temporary xda logical reads = 0
Buffer pool temporary xda physical reads = 0
Blocking cursor = NO

Memory usage for application:

Memory Pool Type = Application Heap
Current size (bytes) = 65536
High water mark (bytes) = 65536
Configured size (bytes) = 1048576

Agent process/thread ID = 255
Agent Lock timeout (seconds) = -1
Memory usage for agent:

Memory Pool Type = Other Memory
Current size (bytes) = 589824
High water mark (bytes) = 786432
Configured size (bytes) = 5267759104

DB2 Get Snapshot 指令用法

參考網址:http://publib.boulder.ibm.com/infocenter/db2luw/v9/topic/com.ibm.db2.udb.admin.doc/doc/r0001945.htm?resultof=%22%67%65%74%22%20%22%73%6e%61%70%73%68%6f%74%22%20

Snapshot可以收集某個時間點下,DB2運作的狀態。把相對應的 monitor switch打開後,就可以使用 GET SNAPSHOT的指令來取得資料

Authorizition:

只有下列權限的人,才能執行 GET SNAPSHOT指令

  • SYSADM
  • SYSCTRL
  • SYSMAINT
  • SYSMON

需要的Connection:

Snapshot是作用在INSTANCE Level的,所以執行此指令時,至少要 Attach到一個Instance

指令語法:

image

如下圖所示,GET SNAPSHOT指令的基本寫法就是

GET SNAPSHOT  FOR  XXX

其中,XXX表示要抓取的資訊,若XXX的值是下列值,不需在最後指定 on database_alias

  • DBM
  • ALL DATABASES
  • ALL APPLICATIONS
  • ALL BUFFERPOOLS
  • APPLICATION APPLID  application_id
  • FCM FOR ALL DBPARTITIONNUMS
  • LOCKS FOR APPLICATION APPLID application_id
  • ALL REMOTE DATABASES
  • ALL REMOTE APPLICATIONS

若XXX是下列值,因為其是屬於資料庫層級的資訊,需在最後指定 on database_alias告知要monitor那個資料庫

  • DATABASE
  • APPLICATIONS
  • TABLES
  • LOCKS
  • BUFFERPOOLS
  • REMOTE DATABASES
  • REMOTE APPLICATIONS

接下來簡介上述各種監控參數

DATABASE MANAGER:取得目前所attach到的active的 database manager instance的統計資訊

ALL DATABASES:提供目前這個database partition中active的 database的基本統計資訊

ALL APPLICATIONS:提供目前連結到資料庫的active application的統計資訊

ALL BUFFERPOOLS:提供目前所有active的資料庫的所有bufferpool資訊

APPLICATION APPLID  application_id:提供某個application_id所代表的application的統計資訊

…….

重設Monitor Switches值

Monitor switch所收集的值從打開後,會一直累積,若要Reset其數值,可使用 RESET MONITOR 指令,用法如下

image

2009年12月6日 星期日

DB2 更改Bufferpool大小

使用 db2 get db cfg 指令得到的 Bufferpool 這個 database configuration值指的是在建立bufferpool時預設的大小,如下圖

image

bufferpool在建立後可使用指令更改其大小,以下說明修改的方式。首先要知道要改的是那個Bufferpool以及它現在的大小,使用這個SQL可查詢目前系統中有那些Bufferpools

SELECT * FROM SYSCAT.BUFFERPOOLS

image

回傳結果中,NPAGES欄位若為-2,表示現在的bufferpool設定為Automatic。而BPNAME的值則為bufferpool之名稱,知道之後,使用下列指令,更改bufferpool 大小

db2 alter bufferpool ibmdefaultbp immediate size 4

上述指令將bufferpool設為4個4K pages;若要把它設為Automatic,則使用下列指令

db2 alter bufferpool ibmdefaultbp immediate size automatic

將bufferpool設為自動後,可使用snapshot monitor來擷取當下該bufferpool的大小

db2 get snapshot for bufferpools on db_name     ##以下為結果(紅色方框列出目前該Buferpool實際大小)

image

……中間略過……

image

2009年11月30日 星期一

DB2 檢視 Snapshot的內容

Snapshot可以抓取某一個時間點下,monitor switches所收集的資料。因此在進行snapshot前,需先開啟monitor switches,這裡以lock的switch為例

db2 update monitor switches using lock on

接著查一下monitor  switch是否被打開了

db2 get monitor switches

image

確定LOCK的switch被打開後,執行下列指令,就可以抓取LOCK這個monitor switches所收集的資料了

db2 get snapshot for locks on db_name




以下為範例結果




Database Lock Snapshot

Database name = SAMPLE
Database path = C:\DB2\NODE0000\SQL00001\
Input database alias = SAMPLE
Locks held = 5
Applications currently connected = 1
Agents currently waiting on locks = 0
Snapshot timestamp = 06-05-2002 17:08:25.048027

Application handle = 8
Application ID = *LOCAL.DB2.0098C5210749
Sequence number = 0001
Application name = db2bp.exe
CONNECT Authorization ID = DB2ADMIN
Application status = UOW Waiting
Status change time = Not Collected
Application code page = 1252
Locks held = 5
Total wait time (ms) = 0

List Of Locks
Lock Name = 0x02000300050000000000000052
Lock Attributes = 0x00000000
Release Flags = 0x00000001
Lock Count = 1
Hold Count = 0
Lock Object Name = 5
Object Type = Row
Tablespace Name = USERSPACE1
Table Schema = DB2ADMIN
Table Name = STAFF
Mode = U

Lock Name = 0x02000300000000000000000054
Lock Attributes = 0x00000000
Release Flags = 0x00000001
Lock Count = 1
Hold Count = 0
Lock Object Name = 3
Object Type = Table
Tablespace Name = USERSPACE1
Table Schema = DB2ADMIN
Table Name = STAFF
Mode = IX

Lock Name = 0x01000000010000000100810056
Lock Attributes = 0x00000000
Release Flags = 0x40000000
Lock Count = 1
Hold Count = 0
Lock Object Name = 0
Object Type = Internal Variation Lock
Mode = S

Lock Name = 0x41414141414A48520000000041
Lock Attributes = 0x00000000
Release Flags = 0x40000000
Lock Count = 1
Hold Count = 0
Lock Object Name = 0
Object Type = Internal Plan Lock
Mode = S

Lock Name = 0x434F4E544F4B4E310000000041
Lock Attributes = 0x00000000
Release Flags = 0x40000000
Lock Count = 1
Hold Count = 0
Lock Object Name = 0
Object Type = Internal Plan Lock
Mode = S



由上面的例子可以看到,目前資料有1個應用程式連接,而這個應用程式產生了5個lock,目前這個應用程式花費0秒在等lock

DB2 DFT_DEGREE 參數

dft_degree - Default degree configuration parameter

Configuration Type
Database
Parameter Type
Configurable Online
Propagation Class
Immediate
Default [Range]
1 [ -1, 1 - 32 767 ]

----------------------------------------------------------------------------------------------------------------------------------------

這個參數可以設定CURRENT DEGREE這個特殊的REGISTER及DEGREE bind option的值,系統的預設值為1。

值為1時表示沒有intra-partition parallelism的情形,若把它設為-1,系統的optimizer會依照CPU的數目及查詢的種類,自動決定 intra-partition parallelism的值

SQL語句的 Degree of intra-partition parallelism是在該語句的編譯時期,用CURRENT DEGREE這個特殊的REGISTER或DEGREE bind option所指定。一個active application的最大的執行時期的 degree of intra-partition parallelism則是透過SET RUNTIME DEGREE命令來達行。最大的query degree of parallelism(max_querydegree)參數指定所有SQL查詢的最大的query degree of intra-partition parallelism

而執行時期實際的 degree則是取下列三個值中最小的

  • max_querydegree =>即上面提到的所有SQL查詢中,最大的query degree of intra-partition parallelism
  • application runtime degree=>即上面提供的一個active application的最大執行時期的 degree of intra-parition parallelism
  • SQL statement compilation degree=>即這個dft_degree參數定義的值

資料來源:http://publib.boulder.ibm.com/infocenter/db2luw/v8//topic/com.ibm.db2.udb.doc/admin/r0000346.htm?resultof=%22%64%66%74%5f%64%65%67%72%65%65%22%20