Thursday, 4 September 2014

Parallel Execution (Parallel Hint)

 Parallel Execution (Parallel Hint):-

Parallel execution is a commonly used method of speeding up operations by splitting a task in smaller sub tasks.
Imagine that your task is to count the number of cars in a street. There are two ways to do this, one, you can go through the street by yourself and count the number of cars or you can enlist a friend and then the two of you can start on opposite ends of the street, count cars until you meet each other and add the results of both counts to complete the task.
Assuming your friend counts equally fast as you do, you expect to complete the task of counting all cars in a street in roughly half the time compared to when you perform the job all by yourself. If this is the case then your operations scales linearly; 2x the number of resources halves the total processing time.
The database is not very different from the counting cars example. If you allocate twice the number of resources and achieve a processing time that is half of what it was with the original amount of resources, then the operation scales linearly. Scaling linearly is the ultimate goal of parallel processing, both in counting cars as well as in delivering answers from a database query.
Processing Parallel SQL Statement:-
  1. When you execute a SQL statement in the Oracle Database it is decomposed into individual steps or row-sources, which are identified as separate lines in an execution plan. Below is an example of a simple SQL statement that touches just one table and its execution plan. The statement returns the total number of customers in the CUSTOMERS table: 

    SELECT count(*) FROM customers c;




    logistical processing steps due to the parallel processing that we did not have before.
    following section discusses these concepts that help you understand the parallel execution setup in your database and read the basics of parallel SQL execution plans. 


    Query Coordinator(QC) and Parallel Server (PX):-


    called the Query Coordinator – QC for short) and parallel execution (PX) server processes. The QC is the session that initiates the parallel SQL statement and the PX servers are the individual sessions that perform work in parallel. The QC distributes the work to the PX servers and may have to perform a minimal
    QC is the session that initiates the parallel SQL statement and the PX servers are the individual
    sessions that perform work in parallel. The QC distributes the work to the PX servers and may
    have to perform a minimal – mostly logistical – portion of the work that cannot be executed in parallel. For example a parallel query with a SUM() operation requires a final adding up of all individual sub-totals calculated by each PX server.
    parallel. For example a parallel query with a SUM() operation requires a final adding up of all
    individual sub-totals calculated by each PX server.
    given operation . All the work shown below the QC
    entry in our sample parallel plans is done by the PX servers.



    1. A more complex serial execution plan would be one that includes a join between multiple tables. In the example below, information about purchases made by customers is requested. This requires a join between the CUSTOMERS and SALES tables. 

      SELECT c.name, s.purchase_date, s.amount
      FROM customers c, sales s
      WHERE s.customer_id = c.id ;




    If you execute a statement in parallel, the Oracle Database will parallelize as many of the individual steps as possible and reflects this in the execution plan. If we were to re-execute the two statements above in parallel we could get the following execution plans1.


    These plans look quite a bit different than before, mainly because we are having additional
    SQL parallel execution in the Oracle database is based on a few fundamental concepts. The
    SQL parallel execution in the Oracle Database is based on the principles of a coordinator (often The QC is easily identified in the parallel execution plans above as 'PX COORDINATOR' The process acting as the QC of a parallel SQL operation is the actual user session process itself.
    The PX servers are taken from a pool of globally available PX server processes and assigned to a given operation (the setup is discussed in a later section). All the work shown below the QC entry in our sample parallel plans is done by the PX servers.

Monday, 25 August 2014

Oracle Architecture



TNSLSNR : This is a generic listener for stating and stopping  oracle.

Types of Processes :-

A database instance contains or interacts with the following types of processes:

1. Client processes run the application or Oracle tool code.

2. Oracle processes run the Oracle database code. Oracle processes including the following subtypes:
         1. Background processes start with the database instance and perform maintenance tasks such as              performing instance recovery, cleaning up processes, writing redo buffers to disk, and so on.

         2. Server processes perform work based on a client request. For example, these processes parse                 SQL queries, place them in the shared pool, create and execute a query plan for                each query,and read buffers from the database buffer cache or from disk.
            Server processes, and the process memory allocated in these processes, run in the instance. The              instance continues to function when server processes terminate.
        3. Slave processes perform additional tasks for a background or server process.

Overview of Client Processes

When a user runs an application such as a Pro*C program or SQL*Plus, the operating system creates a client process (sometimes called a user process) to run the user application. The client application has Oracle Database libraries linked into it that provide the APIs required to communicate with the database.
Connections and Sessions

A connection is a physical communication pathway between a client process and a database instance. A communication pathway is established using available interprocess communication mechanisms or network software. Typically, a connection occurs between a client process and a server process or dispatcher, but it can also occur between a client process and Oracle Connection Manager (CMAN).
A session is a logical entity in the database instance memory that represents the state of a current user login to a database. For example, when a user is authenticated by the database with a password, a session is established for this user. A session lasts from the time the user is authenticated by the database until the time the user disconnects or exits the database application.
A single connection can have 0, 1, or more sessions established on it. The sessions are independent: a commit in one session does not affect transactions in other sessions.


Server Processes

Oracle creates server processes to handle the requests of user processes connected to the instance. In some situations when the application and Oracle operate on the same machine, it is possible to combine the user process and corresponding server process into a single process to reduce system overhead. However, when the application and Oracle operate on different machines, a user process always communicates with Oracle through a separate server process.
Server processes (or the server portion of combined user/server processes) created on behalf of each user's application can perform one or more of the following:

1. Parse and run SQL statements issued through the application,including creating and executing the query plan. 
2. Execute PL/SQL code
3. Read necessary data blocks from datafiles on disk into the shared database buffers of the SGA, if the blocks are not already present in the SGA
4. Return results in such a way that the application can process the information

Dedicated Server Processes

n dedicated server connections, the client connection is associated with one and only one server process On Linux, 20 client processes connected to a database instance are serviced by 20 server processes. Each client process communicates directly with its server process. This server process is dedicated to its client process for the duration of the session. The server process stores process-specific information and the UGA in its PGA.

Shared Server Processes 

In shared server connections, client applications connect over a network to a dispatcher process, not a server process For example, 20 client processes can connect to a single dispatcher process.
The dispatcher process receives requests from connected clients and puts them into a request queue in the large pool  The first available shared server process takes the request from the queue and processes it. Afterward, the shared server place the result into the dispatcher response queue. The dispatcher process monitors this queue and transmits the result to the client.
Like a dedicated server process, a shared server process has its own PGA. However, the UGA for a session is in the SGA so that any shared server can access session data

Overview of Background Processes

A multiprocess Oracle database uses some additional processes called background processes. The background processes perform maintenance tasks required to operate the database and to maximize performance for multiple users.

Each background process has a separate task, but works with the other processes. For example, the LGWR process writes data from the redo log buffer to the online redo log. When a filled log file is ready to be archived, LGWR signals another process to archive the file.

Oracle Database creates background processes automatically when a database instance starts. An instance can have many background processes, not all of which always exist in every database configuration. The following query lists the background processes running on your database:

SELECT PNAME 
FROM   V$PROCESS 
WHERE  PNAME IS NOT NULL 
ORDER BY PNAME;

Mandatory Background Processes
=========================================

1. Process Monitor Process (PMON):  

The process monitor (PMON) monitors the other background processes and performs process recovery when a server or dispatcher process terminates abnormally. PMON is responsible for cleaning up the database buffer cache and freeing resources that the client process was using. For example, PMON resets the status of the active transaction table, releases locks that are no longer required, and removes the process ID from the list of active processes.PMON also registers information about the instance and dispatcher processes with the Oracle Net listenerWhen an instance starts, PMON polls the listener to determine whether it is running. If the listener is running, then PMON passes it relevant parameters. If it is not running, then PMON periodically attempts to contact it.

2. System Monitor Process (SMON): 
The system monitor process (SMON) is in charge of a variety of system-level cleanup duties. The duties assigned to SMON include:

1. Performing instance recovery, if necessary, at instance startup. In an Oracle RAC database, the SMON process of one database instance can perform instance recovery for a failed instance.

2. Recovering terminated transactions that were skipped during instance recovery because of file-read or tablespace offline errors. SMON recovers the transactions when the tablespace or file is brought back online.

3. Cleaning up unused temporary segments. For example, Oracle Database allocates extents when creating an index. If the operation fails, then SMON cleans up the temporary space.

4. Coalescing contiguous free extents within dictionary-managed tablespaces. SMON checks regularly to see whether it is needed. Other processes can call SMON if they detect a need for it.

Database Writer Process (DBWn) : The database writer process (DBWn) writes the contents of database buffers to data files. DBWn processes write modified buffers in the database buffer cache to disk. 

Although one database writer process (DBW0) is adequate for most systems, you can configure additional processes—DBW1 through DBW9 and DBWa through DBWj—to improve write performance if your system modifies data heavily. These additional DBWn processes are not useful on uniprocessor systems. The DBWn process writes dirty buffers to disk under the following conditions:

1. When a server process cannot find a clean reusable buffer after scanning a threshold number of buffers, it signals DBWn to write. DBWn writes dirty buffers to disk asynchronously if possible while performing other processing.

2. DBWn periodically writes buffers to advance the checkpoint, which is the position in the redo thread from which instance recovery begins (see "Overview of Checkpoints"). The log position of the checkpoint is determined by the oldest dirty buffer in the buffer cache.

Log Writer Process (LGWR): 

The log writer process (LGWR) manages the redo log buffer. LGWR writes one contiguous portion of the buffer to the online redo log. By separating the tasks of modifying database buffers, performing scattered writes of dirty buffers to disk, and performing fast sequential writes of redo to disk, the database improves performance.

In the following circumstances, LGWR writes all redo entries that have been copied into the buffer since the last time it wrote:

1. A user commits a transaction (see "Committing Transactions").
2. An online redo log switch occurs.
3. Three seconds have passed since LGWR last wrote.
4. The redo log buffer is one-third full or contains 1 MB of buffered data.
5. DBWn must write modified buffers to disk.

Before DBWn can write a dirty buffer, redo records associated with changes to the buffer must be written to disk (the write-ahead protocol). If DBWn finds that some redo records have not been written, it signals LGWR to write the records to disk and waits for LGWR to complete before writing the data buffers to disk.

LGWR and Commits

Oracle Database uses a fast commit mechanism to improve performance for committed transactions. When a user issues a COMMIT statement, the transaction is assigned a system change number (SCN). LGWR puts a commit record in the redo log buffer and writes it to disk immediately, along with the commit SCN and transaction's redo entries.

The redo log buffer is circular. When LGWR writes redo entries from the redo log buffer to an online redo log file, server processes can copy new entries over the entries in the redo log buffer that have been written to disk. LGWR normally writes fast enough to ensure that space is always available in the buffer for new entries, even when access to the online redo log is heavy.

The atomic write of the redo entry containing the transaction's commit record is the single event that determines the transaction has committed. Oracle Database returns a success code to the

committing transaction although the data buffers have not yet been written to disk. The corresponding changes to data blocks are deferred until it is efficient for DBWn to write them to the data files.
When activity is high, LGWR can use group commits. For example, a user commits, causing LGWR to write the transaction's redo entries to disk. During this write other users commit. LGWR cannot write to disk to commit these transactions until its previous write completes. Upon completion, LGWR can write the list of redo entries of waiting transactions (not yet committed) in one operation. In this way, the database minimizes disk I/O and maximizes performance. If commits requests continue at a high rate, then every write by LGWR can contain multiple commit records.

Memory Structures : The basic memory structures associated with Oracle Database include:
=================

1. Software code areas

Software code areas are portions of memory used to store code that is being run or can be run. Oracle Database code is stored in a software area that is typically at a different location from users' programs—a more exclusive or protected location.

2. System global area (SGA)

The SGA is a group of shared memory structures, known as SGA components, that contain data and control information for one Oracle Database instance. The SGA is shared by all server and background processes. Examples of data stored in the SGA include cached data blocks and shared SQL areas.

3. Program global area (PGA)

A PGA is a memory region that contains data and control information for a server process. It is nonshared memory created by Oracle Database when a server process is started. Access to the PGA is exclusive to the server process. There is one PGA for each server process.


Background processes also allocate their own PGAs. The total memory used by all individual PGAs is known as the total instance PGA memory, and the collection of individual PGAs is referred to as the total instance PGA, or just instance PGA. You use database initialization parameters to set the size of the instance PGA, not individual PGAs.

Program Global Areas (PGA)

A program global area (PGA) is a memory region containing data and control information for a single process (server or background). Consequently, a PGA is sometimes called a "process global area." A PGA is nonshared memory area to which a process can write. One PGA is allocated for each server process; the PGA is exclusive to that server process and is read and written only by Oracle code acting on behalf of that process.
A PGA is allocated by Oracle when a user connects to an Oracle database and a session is created, though this varies by operating system and configuration.

Contents of a PGA

The contents of a PGA vary, depending on whether the associated instance is running the multi-threaded server.

Stack Space : A PGA always contains a stack space, which is memory allocated to hold a session's variables, arrays, and other information.
Session Information : If the instance is running without the multi-threaded server, the PGA also contains information about the user's session, such as private SQL areas. If the instance is running in multi-threaded server configuration, this session information is not in the PGA, but is instead allocated in the SGA.


UGA Memory : 

he UGA, or User Global Area, is allocated in the PGA for each session connected to Oracle in a dedicated server environment. The PGA is memory allocated at the client to hold a stack which contains all of the session's variables, etc. In a Shared Server environment, Oracle allocates this memory in the Shapred Pool (the shared pool is contained in the SGA), for all sessions. This helps to reduce the PGA (client) memory footprint of Oracle, but will increase the SGA (shared pool) requirements.Private SQL Area Components

The private SQL area of a cursor is itself divided into two areas whose lifetimes are different:

1. The persistent area—This area contains bind variable values. It is freed only when the cursor is closed.

2. The runtime area—Oracle Database creates this area as the first step of an execute request. It contains the following structures:
      A. Query execution state information
           For example, for a full table scan, this area contains information on the progress of the scan
      B. SQL work areas
            These areas are allocated as needed for memory-intensive operations like sorting or hash-joins.               More detail is provided later in this section.
3. For DML, the run-time area is freed when the statement finishes running. For queries, it is freed after all rows are fetched or the query is canceled.

SQL Work Areas

SQL work areas are allocated to support memory-intensive operators such as the following:

1. Sort-based operators (order by, group-by, rollup, window function)
2. Hash-join
3. Bitmap merge
4. Bitmap create

For example, a sort operator uses a work area (sometimes called the sort area) to perform the in-memory sort of a set of rows. Similarly, a hash-join operator uses a work area (also called the hash area) to build a hash table from its left input. If the amount of data to be processed by these two operators does not fit into a work area, the input data is divided into smaller pieces. This enables some data pieces to be processed in memory while the rest are spilled to temporary disk storage to be processed later. Although bitmap operators do not spill to disk when their associated work area is too small, their complexity is inversely proportional to the size of their work area. Thus, these operators run faster with larger work area.


The System Global Area (SGA) and the set of database processes constitute an Oracle Database instance. Oracle Database automatically allocates memory for an SGA when you start an instance, and the operating system reclaims the memory when you shut down the instance. Each instance has its own SGA.


The SGA is read/write. All database background processes and all server processes that execute on behalf of users can read information contained within the instance's SGA, and several processes write to the SGA during database operation.

Part of the SGA contains general information about the state of the database and the instance, which the background processes need to access. This is called the fixed SGA. No user data is stored here. The SGA also includes information communicated between processes, such as locking information.

If the system uses shared server architecture, then the request and response queues and some contents of the PGA are in the SGA.

Database Buffer Cache
The database buffer cache is the portion of the SGA that holds copies of data blocks read from datafiles. All users concurrently connected to the instance share access to the database buffer cache.

Organization of the Database Buffer Cache :
he buffers in the cache are organized in two lists: the write list and the least recently used (LRU) list. The write list holds dirty buffers, which contain data that has been modified but has not yet been written to disk. The LRU list holds free buffers, pinned buffers, and dirty buffers that have not yet been moved to the write list. Free buffers do not contain any useful data and are available for use. Pinned buffers are currently being accessed.

When an Oracle Database process accesses a buffer, the process moves the buffer to the most recently used (MRU) end of the LRU list. As more buffers are continually moved to the MRU end of the LRU list, dirty buffers age toward the LRU end of the LRU list.

The first time an Oracle Database user process requires a particular piece of data, it searches for the data in the database buffer cache. If the process finds the data already in the cache (a cache hit), it can read the data directly from memory. If the process cannot find the data in the cache (a cache miss), it must copy the data block from a datafile on disk into a buffer in the cache before accessing the data. 

Accessing data through a cache hit is faster than data access through a cache miss.
Before reading a data block into the cache, the process must first find a free buffer. The process searches the LRU list, starting at the least recently used end of the list. The process searches either until it finds a free buffer or until it has searched the threshold limit of buffers.

If the user process finds a dirty buffer as it searches the LRU list, it moves that buffer to the write list and continues to search. When the process finds a free buffer, it reads the data block from disk into the buffer and moves the buffer to the MRU end of the LRU list.

If an Oracle Database user process searches the threshold limit of buffers without finding a free buffer, the process stops searching the LRU list and signals the DBW0 background process to write some of the dirty buffers to disk.

The LRU Algorithm and Full Table Scans : 

When the user process is performing a full table scan, it reads the blocks of the table into buffers and puts them on the LRU end (instead of the MRU end) of the LRU list. This is because a fully scanned table usually is needed only briefly, so the blocks should be moved out quickly to leave more frequently used blocks in the cache.

You can control this default behavior of blocks involved in table scans on a table-by-table basis. To specify that blocks of the table are to be placed at the MRU end of the list during a full table scan, use the CACHE clause when creating or altering a table or cluster. You can specify this behavior for small lookup tables or large static historical tables to avoid I/O on subsequent accesses of the table.

Redo Log Buffer

The redo log buffer is a circular buffer in the SGA that holds information about changes made to the database. This information is stored in redo entries. Redo entries contain the information necessary to reconstruct, or redo, changes made to the database by INSERT, UPDATE, DELETE, CREATE, ALTER, or DROP operations. Redo entries are used for database recovery, if necessary.

Redo entries are copied by Oracle Database processes from the user's memory space to the redo log buffer in the SGA. The redo entries take up continuous, sequential space in the buffer. The background process LGWR writes the redo log buffer to the active redo log file (or group of files) on disk.

Shared Pool
The shared pool portion of the SGA contains the library cache, the dictionary cache, the result cache, buffers for parallel execution messages, and control structures

Library Cache : 
The library cache includes the shared SQL areas, private SQL areas (in the case of a shared server configuration), PL/SQL procedures and packages, and control structures such as locks and library cache handles.
Shared SQL areas are accessible to all users, so the library cache is contained in the shared pool within the SGA.



How to execute a query in oracle

Steps for how to execute a query in oracle : 


1. An instance has started on the computer running Oracle (often called the host or database server).

2. A computer running an application(a local computer or client workstation ) run the application in a user process. the client application attempts to establish a connection to the server using the proper Oracle Net Services driver.

3. The server detects the connection request from the application and creates a dedicated server process on behalf of the user process.

4. For this server process oracle allocate program global area(PGA) that contains : stack space for stores the session’s variables, array and other information. 

5. PGA also contains the session information if connection is establish to dedicated server otherwise it will manage in SGA.

In SGA some checks are perform on query as:



The first two function of the parse phase syntax check and Semantic analysis for each and every sql statement within the database.

Syntax Check :

Oracle checks that the SQL statement is valid. Does it make sense given the SQL grammar documented in the SQL Reference Manual? Does it follow all of the rules for SQL?

Semantic Analysis :

This function of the parse phase, takes the Syntax Check one step further by checking if the statement is valid in light of the objects in the database.

1. Do the tables and columns referenced in the SQL statement actually exist in the database?

2. Does the user executing the statement have access to the objects and are the proper privileges in place?

3. Are there ambiguities in the statement? (like two tables using same column name in join operation) .

Hard Parse vs. Soft Parse : 

We now consider the next and one of the most important functions of Oracle's parse phase. The Oracle database now needs to check in the Shared Pool to determine if the current SQL statement being parsed has already been processed by any other sessions.
If the current statement has already been processed, the parse operation can skip the next two functions in the process: Optimization and Row Source Generation. If the parse phase does, in fact, skip these two functions, it is called a soft parse. 
On the other hand, if the current SQL statement has never been parsed by another session, the parse phase must execute ALL of the parsing steps. This type of parse is called a hard parse.

Optimization : 

Query transformation is a set of techniques used by the optimizer to rewrite a query and optimizer it better. Few optimization paths open up to the optimizer after query transformation. Some query transformations must be costed to be chosen and some do not need to be costed. For example, if a table can be eliminated completely from the join, then that transformation is applied and need to cost that transformation is minimal.

Sunday, 24 August 2014

ROWID in Oracle

ROWID :- For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle Database rowid values contain information necessary to locate a row.

An extended ROWID needs 10 bytes of storage on disk and is displayed by using 18 characters. It consists of the following components:

 Data object number: Is assigned to each data object, such as table or index when it is created, and it is unique within the database
 Relative file number: Is unique to each file within a tablespace
 Block number: Represents the position of the block, containing the row, within the file
 Row number: Identifies the position of the row directory slot in the block header

Internally, the data object number needs 32 bits, the relative file number needs 10 bits, block number needs 22 bits, and the row number needs 16 bits, adding up to a total of 80 bits or 10 bytes.
An extended ROWID is displayed using a base-64 encoding scheme, which uses six positions for the data object number, three positions for the relative file number, six positions for the block number, and three positions for the row number. The base-64 encoding scheme uses characters A-Z, a-z, 0-9, and /. This is a total of 64 characters, as in the following example:

SQL> select rowid,empid,name,sal from emp where empid <= 105;

ROWID                                        EMPID        NAME                                  SAL
------------------                             ----------         ------------------------------ ----------
AAAFDwAABAAARcJAAA        101                aman                                 3000
AAAFDwAABAAARcJAAB        102                rk                                          400
AAAFDwAABAAARcJAAC        103               am                                      1000
AAAFDwAABAAARcJAAD        104               vinod                                  1000
AAAFDwAABAAARcJAAE        105               kamal                                   900
AAAFDwAABAAARcJAAI         100               akhlesh                              3000

In this example:

• AAAFDw is the data object number
• AAB is the relative file number
• AAARcJ is the block number
• AAA is the row number for the emp with EMPID = 101;


 Row header: Used to store the number of columns in the row, the chaining information, and the row lock status

    • Row data: For each column, the Oracle server stores the column length and value (One byte is needed to store the column length if the column will require more than 250 bytes of storage in which case three bytes will be used for column length. The column value is stored immediately following the column length bytes.)

Using dbms_rowid one can map rowid back to object id, file id so the tablespace name and also using the file_id and block_no one can map it back to object_name.

declare
      my_rowid rowid := 'AAAFDwAABAAARcJAAA';
      rowid_type number;
     object_id number;
     relative_fno number;
     block_no number;
     row_no number;
begin
     dbms_rowid.rowid_info(my_rowid, rowid_type, object_id, relative_fno, block_no, row_no);
    dbms_output.put_line('ROWID: ' || my_rowid);
    dbms_output.put_line('Object#: ' || object_id);
    dbms_output.put_line('RelFile#: ' || relative_fno);
    dbms_output.put_line('Block#: ' || block_no);
   dbms_output.put_line('Row#: ' || row_no);
end;

Output:--

ROWID: AAAFDwAABAAARcJAAA
Object#: 20720
RelFile#: 1
Block#: 71433
Row#: 1

Using the object_id you can can map the row id to object_name

SQL> select object_name,object_type from dba_objects where object_id = 20720;

OBJECT_NAME                                                OBJECT_TYPE
-------------------------------------------------- -------------------
EMP                                                                    TABLE

By using the below query you can know know the segment,tablespace and owner name.

select owner, segment_name,tablespace_name from dba_extents where file_id = 1 and block_id<= 71433 and block_id + blocks > 71433;

OWNER                          SEGMENT_NAME              TABLESPACE_NAME              
 ------------------------------------------------------------------- ------------------------------
SYSTEM                         EMP                                       SYSTEM                         

Wednesday, 20 August 2014

Oracle Pipes

To explain the purpose of the dbms_pipe package, take into account the use of pipe in UNIX,
represented by the ?|? symbol, which allows the communication between one command and another. In
other words, dbms_pipe allows inter-session communication on the same database.

Alone, this is not a very reliable way of message exchange as all information generated by dbms_pipe
is stored in the System Global Area (SGA).  As with any information inside SGA, it will be lost if
the database goes down. Thus, applications that use it often combine it with Streams, proprietary
methods to store the data sent, or rely on it only for non-critical data exchange.

To increase the security of this communication, two pipes can be used; private pipes and public
pipes.  Public pipes are dropped when there is no more data in it.  They may be created implicitly,
i.e. created automatically when first referenced, or explicitly, i.e. using the create_pipe
procedure. The script used for creating the dbms_pipe package is dbms_pipe.sql and can be found at
$ORACLE_HOME/rdbms/admin.

The next example works as an alert to inform an application that data has changed and needs to have
its cache refreshed in order to show the new information. Suppose that there is an employees table
and we want to know each time the salary field is updated.  To accomplish this, create a trigger that
sends updated information to a session that is waiting for these changes.

irst of all, create the employees table that will be used in this example.


create or replace package test_dbms_pipe as
  procedure send_message_pipe (v_name in varchar2, v_sal in number, v_date in date default sysdate);
  procedure receive_message_pipe;
  procedure log_message (v_name in out varchar2, v_sal in out number, v_date in out date);
end test_dbms_pipe;
/

create or replace package body test_dbms_pipe as
procedure send_message_pipe
(
v_name in varchar2,
                  v_sal  in number,
                        v_date in date
                ) as
    v_status number;
  begin
    dbms_pipe.pack_message(v_name);
    dbms_pipe.pack_message(v_sal);
    dbms_pipe.pack_message(v_date);

    v_status := dbms_pipe.send_message('message from pipe!');
    if v_status != 0 then
      raise_application_error(-20001, '!! message pipe error !!');
    end if;
  end send_message_pipe;


  --Create the procedure that will receive the message pipe
  procedure receive_message_pipe as
    v_result integer;
    v_name_r varchar2(3000);
    v_sal_r  number;
  begin
    v_result := dbms_pipe.receive_message(
                    pipename => 'message from pipe!',
                    timeout  => 10);

    if v_result = 0 then
      while v_result = 0 loop
v_result := dbms_pipe.receive_message(
pipename => 'message from pipe!',
timeout  => 10);
dbms_pipe.unpack_message(v_name_r);
dbms_pipe.unpack_message(v_sal_r);
dbms_output.put_line('Full Name: ' || v_name_r);
dbms_output.put_line('Salary: ' || v_sal_r);
      end loop;
    else
      if v_result = 1 then
        dbms_output.put_line('Timeout limit exceeded!');
      else
        raise_application_error(-20002,
                                'error receiving message pipe: ' ||
                                v_result);
      end if;
    end if;
  exception
    when others then
      null;
  end receive_message_pipe;
end test_dbms_pipe;

Create the trigger on the employees table that will use the send_message_pipe procedure to send
information to the pipe. This information will be read with the receive_message_pipe procedure.
--Create the trigger on employee table using the send procedure
create or replace trigger employees_upd_sal
after insert on employees
    for each row
declare
   v_date_1 date;
begin
   v_date_1 := sysdate;
   test_dbms_pipe.send_message_pipe(v_name => :new.name, v_sal => :new.sal);
exception
   when others then
     raise_application_error(num => -20002,
                            msg => 'error message on trigger!');
end employees_upd_sal;
/

Finally, we open two sessions. In one, we execute the receive_message_pipe procedure that has a
timeout configured for 15 seconds. This session will wait for 15 seconds if no inserts are being
made to the employees table. After the 15 seconds, the timeout finishes and shows the values that
were inserted in the table.
--On the first session, execute the procedure receive_message that will output values being inserted in employees table.
set serveroutput on
exec test_dbms_pipe.receive_message_pipe;

--On the second session execute some insert commands on employees table.
insert into employees (name,sal) values ('John Paul',300000);
insert into employees (name,sal) values ('Mike',350000);
insert into employees (name,sal) values ('Brad',400000);
commit;
After we wait for fifteen seconds; the results of the first session will then be displayed.
To check pipes created on the database, use the v$db_pipes view as shown:
col name for a30
select
   *
from
   v$db_pipes;
OWNERID    NAME                           TYPE     PIPE_SIZE
---------- ------------------------------ ------- ----------
           message from pipe!             public        4480
To recap, one session has communicated with the other via send_message_pipe and receive_message_pipe procedures which are inside the dbms_pipe package. This is commonly known as inter-session communication.

Tuesday, 19 August 2014

PCTUSED and PCTFREE?

Both the parameters are applicable and used for each data block in the Database. I hope an example will give you the right answer.
Consider 8K block size. The total bytes 8 x 1024 = 8196 bytes
Each block requires approximately 117 bytes for the header. Please note that the header size varies depending upon the block size.
The total available bytes for data = ( 8196 – 117) = 8079 bytes.

A table is created with PCTFREE 20 PCTUSED 50 .

PCTRFREE in bytes = 1615
PCTUSED in bytes = 4039

Now the data available for insert and update = (8079 – (20 * 8079)/100 ) = 6463 Bytes.

Now user can insert new rows into this block as long as the old rows’ total bytes + new row’s total byte is less than or equal to 6463 bytes. If the new row’s total byte cannot be put into this block, then Oracle will get the next block from the free list, and inserts into it.

When a row is updated and the row’s data is expanded, then PCTFREE come into play. The updated row’s data is placed into PCTFREE’s area, provided the updated row’s new data can be fit into PCTFREE area. If it is not fit into that area, another new block will be obtained from the Freelist, and the row will be migrated. But the original row info (pointer) is kept in the old block. For subsequent access to this row involves 2 read I/O. That is why row migration should be avoided because of excessive I/Os.

ROW DELETION:

The PCTUSED parameter value (in this example 50 %) is the threshold limit for the old block to be added in the FREELIST. To understand better, let us assume that a block is of full data. Now the user starts deleting rows from the block. When a row is deleted, Oracle does not put the block into the
FREELIST because it requires many recursive calls to update the FREELIST. The PCTUSED % (50) determines when the block should be added into FREELIST.
When the total bytes in the block is less than or equal to 4039 bytes, then the block will be added into FREELIST.

If a table has high inserts and high deletion, then you should decrease the PCTUSED value in order to minimize the frequent update of FREELIST.