1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu OCA: Oracle Database 11g Administrator Certified Associate- P19 pdf

50 567 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 0,97 MB

Nội dung

Identifying PL/SQL Objects 731 ,’No grant to PUBLIC allowed for ‘ ||DICTIONARY_OBJ_OWNER||’.’ ||DICTIONARY_OBJ_NAME); END IF; END LOOP; END; In the preceding example, the DDL event is a GRANT statement issued by user engineering. The code examines the grantee list, and if it finds the special user/role PUBLIC , an exception is raised, causing the grant to fail. Table 13.2 shows the DDL trigger events. TABLE 13.2 DDL Trigger Events Event When It Fires [BEFORE/AFTER] ALTER When an ALTER statement changes a database object [BEFORE/AFTER] ANALYZE When the database gathers or deletes statistics or validates the structure of an object [BEFORE/AFTER] ASSOCIATE STATISTICS When the database associates a statistic with a database object with an ASSOCIATE STATISTICS statement [BEFORE/AFTER] AUDIT When the database records an audit action (except FGA) [BEFORE/AFTER] COMMENT When a comment on a table or column is modified [BEFORE/AFTER] CREATE When the database object is created [BEFORE/AFTER] DDL In conjunction with any of the following: ALTER , ANALYZE , ASSOCIATE STATISTICS , AUDIT , COMMENT , CREATE , DISASSOCIATE STATISTICS , DROP GRANT , NOAUDIT , RENAME , REVOKE , or TRUNCATE [BEFORE/AFTER] DISASSOCIATE STATISTICS When a database disassociates a statistic type from a database object with a DISASSOCIATE STATISTICS statement [BEFORE/AFTER] DROP When a DROP statement removes an object from the database [BEFORE/AFTER] GRANT When a GRANT statement assigns a privilege [BEFORE/AFTER] NOAUDIT When a NOAUDIT statement changes database auditing [BEFORE/AFTER] RENAME When a RENAME statement changes an object name [BEFORE/AFTER] REVOKE When a REVOKE statement rescinds a privilege [BEFORE/AFTER] TRUNCATE When a TRUNCATE statement purges a table 95127c13.indd 731 2/17/09 2:49:22 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 732 Chapter 13 N Managing Data and Undo Database Trigger Events Database event triggers fire when the specified database-level event occurs. Most of these triggers are available only before or after the database event, but not both. The following example creates an after-server error trigger that sends an email notifica- tion when an ORA-01555 error occurs: CREATE OR REPLACE TRIGGER Email_on_1555_Err AFTER SERVERERROR ON DATABASE DECLARE mail_conn UTL_SMTP.connection; smtp_relay VARCHAR2(32) := ‘mailserver’; recipient_address VARCHAR2(64) := ‘DBA@hotmail.com’; sender_address VARCHAR2(64) := ‘oracle@sybex.com’; mail_port NUMBER := 25; msg VARCHAR2(200); BEGIN IF USER = ‘SYSTEM’ THEN -- Ignore this error NULL; ELSIF IS_SERVERERROR (1555) THEN -- compose the message msg := ‘Subject: ORA-1555 error’; msg := msg||’Snapshot too old err at ‘||systimestamp; -- send email notice mail_conn := UTL_SMTP.open_connection(smtp_relay ,mail_port); UTL_SMTP.HELO(mail_conn, smtp_relay); UTL_SMTP.MAIL(mail_conn, sender_address); UTL_SMTP.RCPT(mail_conn, recipient_address); UTL_SMTP.DATA(mail_conn, msg); UTL_SMTP.QUIT(mail_conn); END IF; END; Be careful when using database triggers. Fully test them in development before deploying them to production. Table 13.3 shows the database trigger events. TABLE 13.3 Database Trigger Events Event When It Fires AFTER LOGON When a database session is established—only the AFTER trigger is allowed BEFORE LOGOFF When a database session ends normally—only the BEFORE trigger is allowed 95127c13.indd 732 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Identifying PL/SQL Objects 733 Event When It Fires AFTER STARTUP When the database is opened—only the AFTER trigger is allowed BEFORE SHUTDOWN When the database is closed—only the BEFORE trigger is allowed AFTER SERVERERROR When a database exception is raised—only the AFTER trigger is allowed AFTER SUSPEND When a server error causes a transaction to be suspended—only the AFTER trigger is allowed Enabling and Disabling Triggers The database automatically enables a trigger when you create it. After creating a trigger, you can disable (temporarily prevent it from firing) or reenable it. You can disable and enable triggers by name with an ALTER TRIGGER statement. Here are two examples: ALTER TRIGGER after_ora60 DISABLE; ALTER TRIGGER load_packages ENABLE; Alternatively, you can enable and disable multiple DML triggers with an ALTER TABLE statement, like this: ALTER TABLE employees DISABLE ALL TRIGGERS; ALTER TABLE employees ENABLE ALL TRIGGERS; You can also create a trigger with the ENABLE or DISABLE clause. ENABLE is the default. You can query the STATUS column of the DBA_TRIGGERS view to find out whether a trig- ger is enabled or disabled. Using and Administering PL/SQL Programs Oracle 11g comes bundled with hundreds of built-in packages that give you significant capabilities for administering your database. Many features in the database are imple- mented through one or more of these built-in packages. To use the job scheduler, collect and manage optimizer statistics, implement fine-grained auditing, send email from the database, and use Data Pump or Log Miner, you must engage built-in packages. As you gain experience, you will use these built-in packages more extensively. These are some of the commonly used built-in catalog packages: DBMS_STATS ÛN DBMS_METADATA ÛN DBMS_MONITOR ÛN TABLE 13.3 Database Trigger Events (continued) 95127c13.indd 733 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 734 Chapter 13 N Managing Data and Undo UTL_FILE ÛN UTL_MAIL ÛN To view the names and parameter lists for stored programs (except triggers), use the S QL*Plu s DESCRIBE command like this: describe dbms_monitor -- some output is deleted for brevity PROCEDURE SESSION_TRACE_DISABLE Argument Name Type In/Out Default? --------------- ------------------- ------ -------- SESSION_ID BINARY_INTEGER IN DEFAULT SERIAL_NUM BINARY_INTEGER IN DEFAULT PROCEDURE SESSION_TRACE_ENABLE Argument Name Type In/Out Default? --------------- ------------------- ------ -------- SESSION_ID BINARY_INTEGER IN DEFAULT SERIAL_NUM BINARY_INTEGER IN DEFAULT WAITS BOOLEAN IN DEFAULT BINDS BOOLEAN IN DEFAULT PLAN_STAT VARCHAR2 IN DEFAULT You can see in this output from DESCRIBE that the packaged procedure DBMS_MONITOR con- tains several procedures, including SESSION_TRACE_DISABLE and SESSION_TRACE_ENABLE . Furthermore, you can see the names, datatypes, and in/out mode for each parameter ( SESSION_ID , SERIAL_NUM , and so on). An extensive list of Oracle built-in PL/SQL packages is available in the manual “Oracle Database PL/SQL Packages and Types Reference 11g Release 1 (11.1) Part Number B28419-03.” Fortunately, you don’t have to know all these programs for the certification exam! A PL/SQL program may be invalidated when a dependent object is changed through the ALTER command. The database automatically recompiles the package body the next time it is called, but you can choose to compile invalid PL/SQL programs yourself and thus elimi- nate the costly recompile during regular system processing. To explicitly compile a named SQL program, use the ALTER…COMPILE statement, like this: ALTER PROCEDURE archive_orders COMPILE; ALTER FUNCTION is_weekend COMPILE; ALTER PACKAGE table_util COMPILE; 95127c13.indd 734 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Monitoring Locks and Resolving Lock Conflicts 735 ALTER PACKAGE table_util COMPILE BODY; ALTER TRIGGER fire_me COMPILE; Other objects, such as views or types, are similarly compiled. Oracle 11g implements a finer-grained dependency control; hence, if the package speci- fication is not changed, the PL/SQL objects that reference the functions and procedures of the package are not invalidated when only the package body is changed. Monitoring Locks and Resolving Lock Conflicts In any database with many users, you will eventually have to deal with locking conflicts when two or more users try to change the same row in the database. In the following sec- tions, I’ll present an overview of how locking works in the Oracle Database, how users are queued for a particular resource once it is locked, and how Oracle classifies lock types in the database. Then, I’ll show you a number of ways to detect and resolve locking issues; I’ll also cover a special type of lock situation: the deadlock. Understanding Locks and Transactions Locks prevent multiple users from changing the same data at the same time. Before one or more rows in a table can be changed, the user executing the DML statement must obtain a lock on the row or rows; a lock gives the user exclusive control over the data until the user has committed or rolled back the transaction that is changing the data. In Oracle 11g, a transaction can lock one row, multiple rows, or an entire table. Although you can manually lock rows, Oracle can automatically lock the rows needed at the lowest possible level to ensure data integrity and minimize conflicts with other transac- tions that may need to access other rows in the table. In Table 13.4, both updates to the EMPLOYEES table return to the command prompt immediately after the UPDATE because the locks are on different rows in the EMPLOYEES table and neither session is waiting for the other lock to be released. TABLE 13.4 Concurrent Transactions on Different Rows of the Same Table Session 1 Time Session 2 update employees set salary = salary * 1.2 where employee_id = 102; 11:29 update employees set manager = 100 where employee_id = 109; commit; 11:30 commit; 95127c13.indd 735 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 736 Chapter 13 N Managing Data and Undo Packaged Applications and Locking The HR department recently purchased a benefits-management package that interfaced well with our existing employee-management tables; however, once HR started using the application, other users who accessed the employee tables started complaining of severe slowdowns in updates to the employee information. Reviewing the CPU and I/O usage of the instance did not reveal any problems, and it wasn’t until we looked at the locking information that we noticed a table lock on the employees table whenever the benefits-management features were being used! The benefits-management application was written to work on a number of database platforms, and the least capable of those platforms did not support row locking. As a result, no one could make changes to the employees table whenever an employee’s benefits were being changed, and every- one had to wait for the benefits changes to complete. Fortunately, the parameter file for the benefits-management package had an option to specify Oracle as the target platform; after setting the specific database version in the package’s parameter file, the package was smart enough to use row locking instead of table locking whenever the employee table needed to be updated. Queries never require a lock. Even if another transaction has locked several rows or an entire table, a query always succeeds, using the prelock image of the data stored in the undo tablespace. If multiple users require a lock on a row or rows in a table, the first user to request the lock obtains it, and the remaining users are enqueued using a first-in, first-out (FIFO) method. At a SQL> command prompt, a DML statement ( INSERT , UPDATE , DELETE , or MERGE ) that is waiting for a lock on a resource appears to hang, unless the NOWAIT keyword is used in a LOCK statement. The WAIT and NOWAIT keywords are explained in the next section, “Maxi- mizing Data Concurrency.” At the end of a transaction, when either a COMMIT or a ROLLBACK is issued (either explic- itly by the user or implicitly when the session terminates normally or abnormally), all locks are released. Maximizing Data Concurrency Rows of a table are locked either explicitly by the user at the beginning of a transaction or implicitly by Oracle, usually at the row level, depending on the operation. If a table must 95127c13.indd 736 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Monitoring Locks and Resolving Lock Conflicts 737 be locked for performance reasons (which is rare), you can use the LOCK TABLE command, specifying the level at which the table should be locked. In the following example, you lock the EMPLOYEES and DEPARTMENTS tables at the highest possible level, EXCLUSIVE : SQL> lock table hr.employees, hr.departments in exclusive mode; Table(s) Locked. Until the transaction with the LOCK statement either commits or rolls back, only queries are allowed on the EMPLOYEES or DEPARTMENTS table. In the sections that follow, I will review the lock modes, as well as show you how to avoid the lock enqueue process and terminate the command if the requested resource is already locked. Lock Modes Lock modes provide a way for you to specify how much and what kinds of access other users have on tables that you are using in DML commands. In Table 13.5, you can see the types of locks that can be obtained at the table level. TABLE 13.5 Table Lock Modes Table Lock Mode Description ROW SHARE Permits concurrent access to the locked table but prohibits other users from locking the entire table for exclusive access. ROW EXCLUSIVE Same as ROW SHARE but also prohibits locking in SHARE mode. This type of lock is obtained automatically with standard DML com- mands such as UPDATE , INSERT , or DELETE . SHARE Permits concurrent queries but prohibits updates to the table; this mode is required to create an index on a table and is automatically obtained when using the CREATE INDEX statement. SHARE ROW EXCLUSIVE Used to query a whole table and to allow other users to query the table but to prevent other users from locking the table in SHARE mode or updating rows. EXCLUSIVE The most restrictive locking mode; permits queries on the locked table but prohibits DML by any other users. This mode is required to drop the table and is automatically obtained when using the DROP TABLE statement. Manual lock requests wait in the same queue as implicit locks and are satisfied in a FIFO manner as each request releases the lock with an implicit or explicit COMMIT or ROLLBACK . 95127c13.indd 737 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 738 Chapter 13 N Managing Data and Undo You can explicitly obtain locks on individual rows by using the SELECT … FOR UPDATE statement, as you can see in the following example: SQL> select * from hr.employees where manager_id = 100 for update; Not only does this query show the rows that satisfy the query conditions, but it also locks the selected rows and prevents other transactions from locking or updating these rows until a COMMIT or ROLLBACK occurs. NOWAIT Mode Using NOWAIT in a LOCK TABLE statement returns control to the user immediately if any locks already exist on the requested resource, as you can see in the following example: SQL> lock table hr.employees in share row exclusive mode nowait; lock table hr.employees * ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired SQL> This is especially useful in a PL/SQL application if an alternate execution path can be followed if the requested resource is not yet available. NOWAIT can also be used in the SELECT … FOR UPDATE statement. WAIT Mode You can tell Oracle 11g to wait a specified number of seconds to acquire a DML lock. If you do not specify a NOWAIT or WAIT clause, then the database waits indefinitely if the table is locked by another user. In the following example, Oracle will wait for 60 seconds to acquire the lock. If the lock is not acquired within 60 seconds, an error is returned. SQL> lock table hr.employees in share row exclusive mode wait 60; DDL Lock Waits When DML statements have rows locked in a table or if the table is manually locked by a user, DDL statements on the table fail with the ORA-00054 error. To have the DDL state- ments wait for a specified number of seconds before throwing the ORA-00054 error, you 95127c13.indd 738 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Monitoring Locks and Resolving Lock Conflicts 739 can set the initialization parameter DDL_LOCK_TIMEOUT . The default value is 0, which means the error is issued immediately. You can specify a value up to 1,000,000 seconds. SQL> alter table hr.employees modify salary number (15,2); alter table hr.employees modify salary number (15,2) * ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired SQL> show parameter ddl_lock NAME TYPE VALUE ------------------------------------ ----------- ------------------------------ ddl_lock_timeout integer 0 SQL> Detecting and Resolving Lock Conflicts Although locks are a common and sometimes unavoidable occurrence in many databases, they are usually resolved by waiting in the queue. In some cases, you may need to resolve the lock problem manually (such as if a user makes an update at 4:59 p.m. and does not perform a COMMIT before leaving for the day). In the next few sections, I will describe in more detail some of the reasons that lock conflicts occur and how to detect lock conflicts, and I’ll discuss a more specific and serious type of lock conflict: a deadlock. Understanding Lock Conflicts In addition to the proverbial user who makes a change at 4:59 p.m. and forgets to perform a COMMIT before leaving for the day, other more typical lock conflicts are caused by long- running transactions that perform hundreds, thousands, or even hundreds of thousands of DML commands in the overnight batch run but are not finished updating the tables when the normal business day starts. The uncommitted transactions from the overnight batch jobs may lock tables that need to be updated by clerical staff during the business day, caus- ing a lock conflict. Another typical cause of lock conflicts is using unnecessarily high locking levels. In the “Packaged Applications and Locking” sidebar earlier in this chapter, we described a third- party application that routinely locked resources at the table level instead of at the row level to be compatible with every SQL-based database on the market. Developers may unneces- sarily code updates to tables with higher locking levels than required by Oracle 11g. Detecting Lock Conflicts Detecting locks in Oracle 11g using EM Database Control makes your job easy; you don’t need to query against V$SESSION , V$TRANSACTION , V$LOCK , and V$LOCKED_OBJECT to see who 95127c13.indd 739 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 740 Chapter 13 N Managing Data and Undo is locking what resource. You can click the Instance Locks link on the Performance tab of EM Grid Control. In Figure 13.1, you can see the tables locked by the user SCOTT after executing the following statement: SQL> lock table hr.employees, hr.departments in exclusive mode; Table(s) Locked. FIGURE 13.1 The Instance Locks screen in EM Database Control 95127c13.indd 740 2/17/09 2:49:23 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... unusable objects Successful database administrators are always on the lookout for potential database problems that could adversely impact the availability or performance of the systems they manage Fortunately, Oracle 11g comes with an array for proactive performance monitoring and an alert mechanism to help you do this The Oracle Database 11g periodically collects statistics on the database objects and uses... available in Oracle 11g Instead, use manual undo management only for compatibility with Oracle8 i or earlier Automatic undo management is the default for the Oracle 11g database To configure automatic undo management, use the initialization parameters UNDO_MANAGEMENT, UNDO_ TABLESPACE, and UNDO_RETENTION UNDO_MANAGEMENT The parameter UNDO_MANAGEMENT specifies the way in which undo data is managed in the database: ... performance statistics of the database Oracle 11g also offers several advisors that help DBAs fine-tune the database components One new tool is Automatic Memory Management, which greatly simplifies memory management In this chapter, you will learn about all the database- management and performancemanagement tools available to DBAs for better database administration Proactive Database Maintenance You can... well as how to identify, execute, and compile PL/SQL programs, including triggers You also learned how locks work in Oracle 11g database and how undo is managed To create, change, and remove data from an Oracle Database, use the INSERT, UPDATE, MERGE, and DELETE statements Although Oracle usually manages locks at the minimum level to ensure that two sessions do not try to simultaneously update the... constructs such as IF statements EXECUTE is used to run a procedure RUN is used to execute a SQL or PL/SQL script file Chapter 14 Maintaining the Database and Managing Performance Oracle Database 11g: Administration I exam objectives covered in this chapter: ÛÛ Database Maintenance NN Use and manage Optimizer Statistics NN Use and manage Automatic Workload Repository (AWR) NN Use Advisory Framework NN... to perform proactive monitoring Proactive monitoring allows you to identify and respond to common database- performance and -management issues before they occur Most of the features in Enterprise Manager Database Control are geared toward proactive monitoring The database- maintenance framework in Oracle 11g consists of these proactive tool sets: NN Automated tasks, such as collecting optimizer statistics... 743 Leveraging Undo Management Whenever a process or a user session changes data in the database, Oracle saves the old value as it existed before it was modified as undo data This provides a number of benefits to the database user: NN NN NN It lets the user change their minds and roll back, or undo, the change to the database It supports read-consistent queries Once a query starts, any changes to the... tablespace Tablespace recovery is discussed in Chapter 16, “Recovering the Database. ” Using Undo Data Undo data is the old value of data when a process or user changes data in a table or an index Undo data serves four purposes in an Oracle Database: NN User rollback of a transaction NN Read consistency of DML operations and queries NN Database recovery operations NN Flashback functionality 746  Chapter 13 ... recovery operations NN Flashback functionality 746  Chapter 13    Managing Data and Undo n User Transaction Rollback In Chapter 8, “Introducing Oracle Database 11g Components and Architecture,” you learned about transactions and how they are managed within the database architecture At the user level, you might have one or hundreds of DML commands (such as DELETE, INSERT, UPDATE, or MERGE) within a particular... retention setting 18 C.  Though options A and D can be used to achieve the same result, they are not the most efficient There is no UPSERT statement in Oracle 11g The MERGE statement is used to conditionally update or insert rows into a table 19 D.  In Oracle, locks never block readers Option A is true, if it did not include the word queries in it Only DML statements wait when the table is locked in . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 732 Chapter 13 N Managing Data and Undo Database Trigger Events Database event. An extensive list of Oracle built-in PL/SQL packages is available in the manual Oracle Database PL/SQL Packages and Types Reference 11g Release 1 (11.1)

Ngày đăng: 24/12/2013, 02:17

Nguồn tham khảo

Tài liệu tham khảo Loại Chi tiết
1. Create an extended statistics group using the DBMS_STATS.CREATE_EXTENDED_STATSfunction. The function returns the name of the extended stat group created. This function has three arguments: the owner, the table name, and the extension. The“extension” could be a combination of columns, up to 32 or expression on column (for function-based statistics, discussed later) Sách, tạp chí
Tiêu đề: extension
1. Set the table preference parameter PUBLISH to FALSE . If you’re messing with many tables, you can use the SET_SCHEMA_PREFS , SET_DATABASE_PREFS , or SET_GLOBAL_PREFS proce- dure. For demonstrating the example, the statistics on table HR.EMPLOYEES are deleted:SQL> select table_name, num_rows, last_analyzed from dba_tables 2 where owner = ’HR’ and table_name = ’EMPLOYEES’;TABLE_NAME NUM_ROWS LAST_ANAL ---------- ---------- --------- EMPLOYEESSQL> select dbms_stats.get_prefs(‘PUBLISH’,’HR’,’EMPLOYEES’) from dual;DBMS_STATS.GET_PREFS(‘PUBLISH’,’HR’,’EMPLOYEES’)-----------------------------------------------------------TRUESQL> exec dbms_stats.set_table_prefs(‘HR’,’EMPLOYEES’,’PUBLISH’,’FALSE’);PL/SQL procedure successfully completed Khác
2. Gather table statistics as you normally would using the DBMS_STATS package. Since the PUBLISH preference is set to FALSE , you do not see the statistics:SQL> exec dbms_stats.gather_table_stats(‘HR’,’EMPLOYEES’);PL/SQL procedure successfully completed.SQL> select num_rows, last_analyzed from dba_tables 2 where owner = ‘HR’ and table_name = ‘EMPLOYEES’;NUM_ROWS LAST_ANAL ---------- --------- Khác
5. When you’re ready to publish the statistics, perform the following:SQL> exec dbms_stats.publish_pending_stats(‘HR’,’EMPLOYEES’);PL/SQL procedure successfully completed.SQL> select num_rows, last_analyzed from dba_tables 2 where owner = ‘HR’ and table_name = ‘EMPLOYEES’;NUM_ROWS LAST_ANAL ---------- --------- 107 15-FEB-08SQL> select table_name, num_rows, blocks, sample_size 2 from dba_tab_pending_stats;no rows selectedThe PUBLISH_PENDING_STATS procedure accepts the schema name and table name as the first two parameters. If you specify NULL for the schema name, the default user’s schema will be used. If you specify NULL for the table name, all pending stats on all tables in the schema are published Khác
2. Collect histogram statistics on the table using the GATHER_TABLE_STATS procedure. FOR ALL COLUMNS SIZE SKEWONLY is a good option because Oracle collects histograms only on columns with large data distribution Khác

TỪ KHÓA LIÊN QUAN