Sga oracle что такое
Знает названье потока лишь тот, кто вблизи обитает.
От Махачкалы до Баку
Луны плавают на боку,
И, качаясь, плывут валы
От Баку до Махачкалы.
Введение
Потоки данных появились в Oracle версии 9, а в версии 10 получили свое развитие в возможностях (например, Down Stream) и в организации (например, собственный источник памяти streams pool).
В отличие от "обычной" репликации Oracle Streams не требует заведения особых структур в БД (журналов таблиц, materialized views). Подбно механизму репликации, давно использовавшемуся в Sybase, репликация в Oracle Streams основана на обработке информации из журнала БД.
Основные понятия
Конфигурация СУБД и БД для возможности организации потоков
Параметры СУБД
Для организации потоков данных нужно иметь должные значения целого ряда параметров СУБД, однако чаще всего достаточно удостовериться в следующем:
COMPATIBLE >= 9.2
Далее предполагается >= 10.1.0.
GLOBAL_NAMES = TRUE
для каждой БД, участвующей в переносе данных.
STREAMS_POOL_SIZE >= 200m
Параметр существует с версии 10.1 и задает область памяти для временного размещения захваченных событий. Если STREAMS_POOL_SIZE = 0, будет использована память из shared pool, вплоть до 10% от этой области.
- + 10m для каждого нового уровня параллелизма процесса захвата
- + 1m для каждой степени параллелизма процесса применения
- + 10m для каждой новой очереди захваченных событий.
В версии 9.2 нагрузка на выделение памяти под нужды потоков ложится на shared pool.
SHARED_POOL_SIZE
Каждый процесс захвата требует 10M в памяти shared pool для буфера очереди; в то же время все нужды Oracle Streams в shared pool не могут занимать более 10% этой области.
SGA_MAX_SIZE
(Если речь идет о версии 10). Значение должно учитывать нужды частей SGA (см. выше), особенно для выполнения захвата изменений с помощью LogMiner. Пример, приводимый ниже, в силу его простоты работает даже при значении SGA_MAX_SIZE = 400m.
Конфигурация БД
БД, поддерживающая процесс захвата изменений, должна обеспечить на уровне отдельных таблиц или всей БД режим расширенной журнализации (supplemental logging). В этом режиме журнальные записи об изменениях в таблицах заносятся в расширенном формате, включая данные старых и новых значений полей (независимо от того, какие поля фактически изменялись) для того, чтобы процесс применения изменения в принимающей СУБД смог однозначно воспроизвести изменение.
- индексирован (хотя бы вследствие имеющегося ограничения целостности)
- участвует в правиле преобразования данных или обрабатывается программой обработки (handler)
Как БД-источник, так и БД-получатель используют рабочие таблицы для хранения данных очередей и прочих нужд. Для их размещения целесообразно выделить отдельные табличные пространства. В БД-источнике желательно назначить процессу LogMiner табличное пространство, иное, чем SYSTEM.
Системные пакеты
Технологически организация потоков осуществляется через употребление ряда встроенных пакетов из схемы SYS:
DBMS_APPLY_ADM
DBMS_CAPTURE_ADM
DBMS_PROPAGATION_ADM
DBMS_STREAMS_ADM
DBMS_STREAMS
DBMS_STREAMS_MESSAGING
DBMS_RULE_ADM
DBMS_RULE
DBMS_STREAMS_AUTH 2
DBMS_STREAMS_TABLESPACE_ADM 2
Пример построения потока изменений
В этом примере БД-источник потока носит имя MAINDB.CLASS, БД-приемник потока носит имя SUBDB1.CLASS. Сетевые имена баз в Oracle Net соответственно SOURCE и DESTINATION. Предполагается, что в обеих БД имеется схема SCOTT.
Пример приводится для версии 10.2. Предполагается, что команды выдаются в SQL*Plus.
Подготовка
CONNECT /@source AS SYSDBA
STARTUP MOUNT FORCE
ALTER DATABASE ARCHIVELOG;
ALTER DATABASE OPEN;
Создадим рабочие табличные пространства в обоих БД, например:
CREATE TABLESPACE streams_ts
DATAFILE 'C:\oracle\oradata\maindb\streams_ts.dbf' SIZE 25m;
CONNECT /@destination AS SYSDBA
CREATE TABLESPACE streams_ts
DATAFILE 'C:\oracle\oradata\subdb1\streams_ts.dbf' SIZE 25m;
В версия 9.2 в БД-источнике желательно назначить процессу LogMiner табличное пространство, иное, чем SYSTEM (в версия 10 оно уже SYSAUX), например:
CONNECT /@source AS SYSDBA
EXECUTE DBMS_LOGMNR_D.SET_TABLESPACE ( 'TOOLS' )
В обеих базах создадим администратора потоков:
CONNECT /@source AS SYSDBA
CREATE USER streamadmin IDENTIFIED BY streamadmin
DEFAULT TABLESPACE streams_ts
TEMPORARY TABLESPACE temp
QUOTA UNLIMITED ON streams_ts
;
GRANT dba TO streamadmin;
EXECUTE DBMS_STREAMS_AUTH.GRANT_ADMIN_PRIVILEGE ( 'streamadmin' )
Повторить те же действия для SUBDB1.CLASS.
В БД-источнике заведем связь с БД-получателем. Так как БД-получатель именована глобально, имя связи обязано совпадать с этим глобальным именем:
CONNECT streamadmin/streamadmin@source
CREATE DATABASE LINK subdb1.class
CONNECT TO streamadmin
IDENTIFIED BY streamadmin
USING 'destination'
;
Формирование потоков
Создадим очередь для передачи событий в БД-источнике и очередь для применения событий в БД-получателе, например:
CONNECT streamadmin/streamadmin@destination
Коли указано специально, очереди в обеих БД (и таблицы для данных этих очередей) получили умолчательные названия. Их можно наблюдать так:
Для возможности передавать потоком изменения в исходной таблице SCOTT.EMP требуется заявить расширенную журнализацию хотя бы для этой таблицы:
CONNECT scott/tiger@source
ALTER TABLE emp ADD SUPPLEMENTAL LOG DATA ( PRIMARY KEY ) COLUMNS;
Теперь правка любого поля в таблице EMP будет сопровождаться (безусловно) занесением в журнал не только старого и нового значений этого поля, но также и значения ключевого поля (то есть EMPNO).
В БД-источнике создадим процесс захвата изменений, одновременно указав правила отбора изменений в очередь: Проверка:
Среди прочих умолчаний при создании процесса захвата изменений выше использовано подразумеваемое молчаливо имя очереди STREAMS_QUEUE. В нашем случае это можно было бы обозначить явно, указав параметр QUEUE_NAME => 'streamadmin.streams_queue'. Этим же параметром можно воспользоваться, когда процесс захвата потребуется связать с очередью под иным именем.
Правила отбора изменений в очередь STREAMS_QUEUE также были построены автоматически, но могли бы быть дополнены, или даже выписаны явно с помощью других параметров процедуры ADD_TABLE_RULES.
Создадим процесс переноса изменений: Проверка: Убедиться в учете процессом применения для таблиц точки отсчета можно запросом: Принимающая БД готова к активации процесса применения изменений: Проверка: Для удобства отключим реакцию на ошибки, иначе процесс применения изменений может самопроизвольно прекращаться: Осталось запустить процессы захвата и примения изменений: Проверка: Заметьте, что поток переносит изменения только в одну сторону. Таблица-приемник при этом не закрыта от обычной правки. Однако же такую правку следует выполнять осмотрительно, поскольку она может привести к ошибкам при автоматическом изменении данных потоком (эта проблема решается специально седствами разрешении конфликтов). Вдобавок учтите, что множественные операции INSERT, UPDATE, DELETE применяются в принимающей БД в рамках одной (автономной) транзакции (невзирая на то, что в журнале БД множественные изменения фиксируются набором однострочных изменений). Следовательно ошибка хотя бы в изменении одной-единственной строки приведет к отказу изменений всей множественной операции.
Упражнение. Внести изменения в таблицу SCOTT.EMP на принимающей БД. Убедиться в сохраняющихся расхождениях в таблицах БД-источника и БД-получателя.
Упражнение. Проверить передачу изменений DDL. Добавить столбец в таблицу SCOTT.EMP@MAINDB.CLASS. Наблюдать результат в SCOTT.EMP@SUBDB1.CLASS. Изменить тип столбца, наблюдать результат в базе-получателе.
This chapter discusses the memory architecture of a database instance.
This chapter contains the following sections:
Oracle Database Administrator’s Guide for instructions for configuring and managing memory
Introduction to Oracle Database Memory Structures
When an instance is started, Oracle Database allocates a memory area and starts background processes.
The memory area stores information such as the following:
Information about each connected session , even if it is not currently active
Information needed during program execution, for example, the current state of a query from which rows are being fetched
Information such as lock data that is shared and communicated among processes
Cached data, such as data blocks and redo records, that also exists on disk
Overview of the User Global Area
The UGA is session memory, which is memory allocated for session variables, such as logon information, and other information required by a database session. Essentially, the UGA stores the session state.
The following figure depicts the UGA.
Figure 14-2 User Global Area (UGA)
If a session loads a PL/SQL package into memory, then the UGA contains the package state , which is the set of values stored in all the package variables at a specific time. The package state changes when a package subprogram changes the variables. By default, the package variables are unique to and persist for the life of the session.
The OLAP page pool is also stored in the UGA. This pool manages OLAP data pages, which are equivalent to data blocks. The page pool is allocated at the start of an OLAP session and released at the end of the session. An OLAP session opens automatically whenever a user queries a dimensional object such as a cube .
The UGA must be available to a database session for the life of the session. For this reason, the UGA cannot be stored in the PGA when using a shared server connection because the PGA is specific to a single process. Therefore, the UGA is stored in the SGA when using shared server connections, enabling any shared server process access to it. When using a dedicated server connection, the UGA is stored in the PGA.
Oracle OLAP User’s Guide for an overview of Oracle OLAP
Contents of the PGA
The PGA is subdivided into different areas, each with a different purpose.
The following figure shows the possible contents of the PGA for a dedicated server session. Not all of the PGA areas will exist in every case.
Figure 14-4 PGA Contents
Private SQL Area
A private SQL area holds information about a parsed SQL statement and other session-specific information for processing.
When a server process executes SQL or PL/SQL code, the process uses the private SQL area to store bind variable values, query execution state information, and query execution work areas.
Do not confuse a private SQL area, which is in the PGA, with the shared SQL area, which stores execution plans in the SGA. Multiple private SQL areas in the same or different sessions can point to a single execution plan in the SGA. For example, 20 executions of SELECT * FROM sales in one session and 10 executions of the same query in a different session can share the same plan. The private SQL areas for each execution are not shared and may contain different values and data.
A cursor is a name or handle to a specific private SQL area. As shown in the following graphic, you can think of a cursor as a pointer on the client side and as a state on the server side. Because cursors are closely associated with private SQL areas, the terms are sometimes used interchangeably.
Figure 14-5 Cursor
A private SQL area is divided into the following areas:
The run-time area
This area contains query execution state information. For example, the run-time area tracks the number of rows retrieved so far in a full table scan .
Oracle Database creates the run-time area as the first step of an execute request. For DML statements, the run-time area is freed when the SQL statement is closed.
The persistent area
This area contains bind variable values. A bind variable value is supplied to a SQL statement at run time when the statement is executed. The persistent area is freed only when the cursor is closed.
The client process is responsible for managing private SQL areas. The allocation and deallocation of private SQL areas depends largely on the application, although the number of private SQL areas that a client process can allocate is limited by the initialization parameter OPEN_CURSORS .
Although most users rely on the automatic cursor handling of database utilities, the Oracle Database programmatic interfaces offer developers more control over cursors. In general, applications should close all open cursors that will not be used again to free the persistent area and to minimize the memory required for application users.
SQL Work Areas
A work area is a private allocation of PGA memory used for memory-intensive operations.
For example, a sort operator uses the sort area to sort a set of rows. Similarly, a hash join operator uses a hash area to build a hash table from its left input, whereas a bitmap merge uses the bitmap merge area to merge data retrieved from scans of multiple bitmap indexes.
The following example shows a join of employees and departments with its query plan :
In the preceding example, the run-time area tracks the progress of the full table scans. The session performs a hash join in the hash area to match rows from the two tables. The ORDER BY sort occurs in the sort area.
If the amount of data to be processed by the operators does not fit into a work area, then Oracle Database divides the input data into smaller pieces. In this way, the database processes some data pieces in memory while writing the rest to temporary disk storage for processing later.
The database automatically tunes work area sizes when automatic PGA memory management is enabled. You can also manually control and tune the size of a work area. See "Memory Management" for more information.
Generally, larger work areas can significantly improve performance of an operator at the cost of higher memory consumption. Optimally, the size of a work area is sufficient to accommodate the input data and auxiliary memory structures allocated by its associated SQL operator. If not, response time increases because part of the input data must be cached on disk. In the extreme case, if the size of a work area is too small compared to input data size, then the database must perform multiple passes over the data pieces, dramatically increasing response time.
Oracle Database Administrator’s Guide to learn how to use automatic PGA management
This chapter discusses the memory architecture of a database instance.
This chapter contains the following sections:
Oracle Database Administrator’s Guide for instructions for configuring and managing memory
Overview of the Program Global Area (PGA)
The PGA is memory specific to an operating process or thread that is not shared by other processes or threads on the system. Because the PGA is process-specific, it is never allocated in the SGA.
The PGA is a memory heap that contains session-dependent variables required by a dedicated or shared server process. The server process allocates memory structures that it requires in the PGA.
An analogy for a PGA is a temporary countertop workspace used by a file clerk. In this analogy, the file clerk is the server process doing work on behalf of the customer (client process). The clerk clears a section of the countertop, uses the workspace to store details about the customer request and to sort the folders requested by the customer, and then gives up the space when the work is done.
The following figure shows an instance PGA (collection of all PGAs) for an instance that is not configured for shared servers. You can use an initialization parameter to set a target maximum size of the instance PGA. Individual PGAs can grow as needed up to this target size.
Figure 16-3 Instance PGA
Background processes also allocate their own PGAs. This discussion focuses on server process PGAs only.
Oracle Database Performance Tuning Guide for an overview of PGA memory management
Contents of the PGA
The PGA is subdivided into different areas, each with a different purpose.
The following figure shows the possible contents of the PGA for a dedicated server session. Not all of the PGA areas will exist in every case.
Figure 16-4 PGA Contents
Private SQL Area
A private SQL area holds information about a parsed SQL statement and other session-specific information for processing.
When a server process executes SQL or PL/SQL code, the process uses the private SQL area to store bind variable values, query execution state information, and query execution work areas.
Do not confuse a private SQL area, which is in the PGA, with the shared SQL area, which stores execution plans in the SGA. Multiple private SQL areas in the same or different sessions can point to a single execution plan in the SGA. For example, 20 executions of SELECT * FROM sales in one session and 10 executions of the same query in a different session can share the same plan. The private SQL areas for each execution are not shared and may contain different values and data.
A cursor is a name or handle to a specific private SQL area. As shown in the following graphic, you can think of a cursor as a pointer on the client side and as a state on the server side. Because cursors are closely associated with private SQL areas, the terms are sometimes used interchangeably.
Figure 16-5 Cursor
A private SQL area is divided into the following areas:
The run-time area
This area contains query execution state information. For example, the run-time area tracks the number of rows retrieved so far in a full table scan .
Oracle Database creates the run-time area as the first step of an execute request. For DML statements, the run-time area is freed when the SQL statement is closed.
The persistent area
This area contains bind variable values. A bind variable value is supplied to a SQL statement at run time when the statement is executed. The persistent area is freed only when the cursor is closed.
The client process is responsible for managing private SQL areas. The allocation and deallocation of private SQL areas depends largely on the application, although the number of private SQL areas that a client process can allocate is limited by the initialization parameter OPEN_CURSORS .
Although most users rely on the automatic cursor handling of database utilities, the Oracle Database programmatic interfaces offer developers more control over cursors. In general, applications should close all open cursors that will not be used again to free the persistent area and to minimize the memory required for application users.
SQL Work Areas
A work area is a private allocation of PGA memory used for memory-intensive operations.
For example, a sort operator uses the sort area to sort a set of rows. Similarly, a hash join operator uses a hash area to build a hash table from its left input, whereas a bitmap merge uses the bitmap merge area to merge data retrieved from scans of multiple bitmap indexes.
The following example shows a join of employees and departments with its query plan :
In the preceding example, the run-time area tracks the progress of the full table scans. The session performs a hash join in the hash area to match rows from the two tables. The ORDER BY sort occurs in the sort area.
If the amount of data to be processed by the operators does not fit into a work area, then Oracle Database divides the input data into smaller pieces. In this way, the database processes some data pieces in memory while writing the rest to temporary disk storage for processing later.
The database automatically tunes work area sizes when automatic PGA memory management is enabled. You can also manually control and tune the size of a work area.
Generally, larger work areas can significantly improve performance of an operator at the cost of higher memory consumption. Optimally, the size of a work area is sufficient to accommodate the input data and auxiliary memory structures allocated by its associated SQL operator. If not, response time increases because part of the input data must be cached on disk. In the extreme case, if the size of a work area is too small compared to input data size, then the database must perform multiple passes over the data pieces, dramatically increasing response time.
Oracle Database Administrator’s Guide to learn how to use automatic PGA management
This chapter discusses the memory architecture of a database instance.
This chapter contains the following sections:
Oracle Database Administrator’s Guide for instructions for configuring and managing memory
Overview of the Program Global Area (PGA)
The PGA is memory specific to an operating process or thread that is not shared by other processes or threads on the system. Because the PGA is process-specific, it is never allocated in the SGA.
The PGA is a memory heap that contains session-dependent variables required by a dedicated or shared server process. The server process allocates memory structures that it requires in the PGA.
An analogy for a PGA is a temporary countertop workspace used by a file clerk. In this analogy, the file clerk is the server process doing work on behalf of the customer (client process). The clerk clears a section of the countertop, uses the workspace to store details about the customer request and to sort the folders requested by the customer, and then gives up the space when the work is done.
The following figure shows an instance PGA (collection of all PGAs) for an instance that is not configured for shared servers. You can use an initialization parameter to set a target maximum size of the instance PGA. Individual PGAs can grow as needed up to this target size.
Figure 14-3 Instance PGA
Background processes also allocate their own PGAs. This discussion focuses on server process PGAs only.
Introduction to Oracle Database Memory Structures
When an instance is started, Oracle Database allocates a memory area and starts background processes.
The memory area stores information such as the following:
Information about each connected session , even if it is not currently active
Information needed during program execution, for example, the current state of a query from which rows are being fetched
Information such as lock data that is shared and communicated among processes
Cached data, such as data blocks and redo records, that also exists on disk
Basic Memory Structures
Oracle Database includes several memory areas, each of which contains multiple subcomponents.
The basic memory structures associated with Oracle Database include:
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. All server and background processes share the SGA. Examples of data stored in the SGA include cached data blocks and shared SQL areas.
Program global area (PGA)
A PGA is a nonshared memory region that contains data and control information exclusively for use by an Oracle process. Oracle Database creates the PGA when an Oracle process starts.
One PGA exists for each server process and background process. The collection of individual PGAs is the total instance PGA, or instance PGA . Database initialization parameters set the size of the instance PGA, not individual PGAs.
User global area (UGA)
The UGA is memory associated with a user session.
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 user programs—a more exclusive or protected location.
The following figure illustrates the relationships among these memory structures.
Figure 14-1 Oracle Database Memory Structures
Oracle Database Memory Management
Memory management involves maintaining optimal sizes for the Oracle instance memory structures as demands on the database change. Oracle Database manages memory based on the settings of memory-related initialization parameters.
The basic options for memory management are as follows:
Automatic memory management
You specify the target size for the database instance memory. The instance automatically tunes to the target memory size, redistributing memory as needed between the SGA and the instance PGA.
Automatic shared memory management
This management mode is partially automated. You set a target size for the SGA and then have the option of setting an aggregate target size for the PGA or managing PGA work areas individually.
Manual memory management
Instead of setting the total memory size, you set many initialization parameters to manage components of the SGA and instance PGA individually.
If you create a database with Database Configuration Assistant (DBCA) and choose the basic installation option, then automatic memory management is the default.
"Memory Management" for more information about memory management options for DBAs
Oracle Database Administrator’s Guide to learn about memory management options
Basic Memory Structures
Oracle Database includes several memory areas, each of which contains multiple subcomponents.
The basic memory structures associated with Oracle Database include:
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. All server and background processes share the SGA. Examples of data stored in the SGA include cached data blocks and shared SQL areas.
Program global area (PGA)
A PGA is a nonshared memory region that contains data and control information exclusively for use by an Oracle process. Oracle Database creates the PGA when an Oracle process starts.
One PGA exists for each server process and background process. The collection of individual PGAs is the total instance PGA, or instance PGA . Database initialization parameters set the size of the instance PGA, not individual PGAs.
User global area (UGA)
The UGA is memory associated with a user session.
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 user programs—a more exclusive or protected location.
The following figure illustrates the relationships among these memory structures.
Figure 14-1 Oracle Database Memory Structures
Overview of the User Global Area
The UGA is session memory, which is memory allocated for session variables, such as logon information, and other information required by a database session. Essentially, the UGA stores the session state.
The following figure depicts the UGA.
Figure 14-2 User Global Area (UGA)
If a session loads a PL/SQL package into memory, then the UGA contains the package state , which is the set of values stored in all the package variables at a specific time. The package state changes when a package subprogram changes the variables. By default, the package variables are unique to and persist for the life of the session.
The OLAP page pool is also stored in the UGA. This pool manages OLAP data pages, which are equivalent to data blocks. The page pool is allocated at the start of an OLAP session and released at the end of the session. An OLAP session opens automatically whenever a user queries a dimensional object such as a cube .
The UGA must be available to a database session for the life of the session. For this reason, the UGA cannot be stored in the PGA when using a shared server connection because the PGA is specific to a single process. Therefore, the UGA is stored in the SGA when using shared server connections, enabling any shared server process access to it. When using a dedicated server connection, the UGA is stored in the PGA.
Oracle OLAP User’s Guide for an overview of Oracle OLAP
Oracle Database Memory Management
Memory management involves maintaining optimal sizes for the Oracle instance memory structures as demands on the database change. Oracle Database manages memory based on the settings of memory-related initialization parameters.
The basic options for memory management are as follows:
Automatic memory management
You specify the target size for the database instance memory. The instance automatically tunes to the target memory size, redistributing memory as needed between the SGA and the instance PGA.
Automatic shared memory management
This management mode is partially automated. You set a target size for the SGA and then have the option of setting an aggregate target size for the PGA or managing PGA work areas individually.
Manual memory management
Instead of setting the total memory size, you set many initialization parameters to manage components of the SGA and instance PGA individually.
If you create a database with Database Configuration Assistant (DBCA) and choose the basic installation option, then automatic memory management is the default.
"Memory Management" for more information about memory management options for DBAs
Oracle Database Administrator’s Guide to learn about memory management options
Introduction to Oracle Database Memory Structures
When an instance is started, Oracle Database allocates a memory area and starts background processes.
The memory area stores information such as the following:
Information about each connected session , even if it is not currently active
Information needed during program execution, for example, the current state of a query from which rows are being fetched
Information such as lock data that is shared and communicated among processes
Cached data, such as data blocks and redo records, that also exists on disk
Basic Memory Structures
Oracle Database includes several memory areas, each of which contains multiple subcomponents.
The basic memory structures associated with Oracle Database include:
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. All server and background processes share the SGA. Examples of data stored in the SGA include cached data blocks and shared SQL areas.
Program global area (PGA)
A PGA is a nonshared memory region that contains data and control information exclusively for use by an Oracle process. Oracle Database creates the PGA when an Oracle process starts.
One PGA exists for each server process and background process. The collection of individual PGAs is the total instance PGA, or instance PGA . Database initialization parameters set the size of the instance PGA, not individual PGAs.
User global area (UGA)
The UGA is memory associated with a user session.
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 user programs—a more exclusive or protected location.
The following figure illustrates the relationships among these memory structures.
Figure 16-1 Oracle Database Memory Structures
Oracle Database Memory Management
Memory management involves maintaining optimal sizes for the Oracle instance memory structures as demands on the database change. Oracle Database manages memory based on the settings of memory-related initialization parameters.
The basic options for memory management are as follows:
Automatic memory management
You specify the target size for the database instance memory. The instance automatically tunes to the target memory size, redistributing memory as needed between the SGA and the instance PGA.
Automatic shared memory management
This management mode is partially automated. You set a target size for the SGA and then have the option of setting an aggregate target size for the PGA or managing PGA work areas individually.
Manual memory management
Instead of setting the total memory size, you set many initialization parameters to manage components of the SGA and instance PGA individually.
If you create a database with Database Configuration Assistant (DBCA) and choose the basic installation option, then automatic memory management is the default.
Oracle Database Performance Tuning Guide for more information about memory management options for DBAs
Oracle Database Administrator’s Guide to learn about memory management options
Overview of the User Global Area
The UGA is session memory, which is memory allocated for session variables, such as logon information, and other information required by a database session. Essentially, the UGA stores the session state.
The following figure depicts the UGA.
Figure 16-2 User Global Area (UGA)
If a session loads a PL/SQL package into memory, then the UGA contains the package state , which is the set of values stored in all the package variables at a specific time. The package state changes when a package subprogram changes the variables. By default, the package variables are unique to and persist for the life of the session.
The OLAP page pool is also stored in the UGA. This pool manages OLAP data pages, which are equivalent to data blocks. The page pool is allocated at the start of an OLAP session and released at the end of the session. An OLAP session opens automatically whenever a user queries a dimensional object such as a cube .
The UGA must be available to a database session for the life of the session. For this reason, the UGA cannot be stored in the PGA when using a shared server connection because the PGA is specific to a single process. Therefore, the UGA is stored in the SGA when using shared server connections, enabling any shared server process access to it. When using a dedicated server connection, the UGA is stored in the PGA.
Oracle OLAP User’s Guide for an overview of Oracle OLAP
Overview of the Program Global Area (PGA)
The PGA is memory specific to an operating process or thread that is not shared by other processes or threads on the system. Because the PGA is process-specific, it is never allocated in the SGA.
The PGA is a memory heap that contains session-dependent variables required by a dedicated or shared server process. The server process allocates memory structures that it requires in the PGA.
An analogy for a PGA is a temporary countertop workspace used by a file clerk. In this analogy, the file clerk is the server process doing work on behalf of the customer (client process). The clerk clears a section of the countertop, uses the workspace to store details about the customer request and to sort the folders requested by the customer, and then gives up the space when the work is done.
The following figure shows an instance PGA (collection of all PGAs) for an instance that is not configured for shared servers. You can use an initialization parameter to set a target maximum size of the instance PGA. Individual PGAs can grow as needed up to this target size.
Figure 14-3 Instance PGA
Background processes also allocate their own PGAs. This discussion focuses on server process PGAs only.
Contents of the PGA
The PGA is subdivided into different areas, each with a different purpose.
The following figure shows the possible contents of the PGA for a dedicated server session. Not all of the PGA areas will exist in every case.
Figure 14-4 PGA Contents
Private SQL Area
A private SQL area holds information about a parsed SQL statement and other session-specific information for processing.
When a server process executes SQL or PL/SQL code, the process uses the private SQL area to store bind variable values, query execution state information, and query execution work areas.
Do not confuse a private SQL area, which is in the PGA, with the shared SQL area, which stores execution plans in the SGA. Multiple private SQL areas in the same or different sessions can point to a single execution plan in the SGA. For example, 20 executions of SELECT * FROM sales in one session and 10 executions of the same query in a different session can share the same plan. The private SQL areas for each execution are not shared and may contain different values and data.
A cursor is a name or handle to a specific private SQL area. As shown in the following graphic, you can think of a cursor as a pointer on the client side and as a state on the server side. Because cursors are closely associated with private SQL areas, the terms are sometimes used interchangeably.
Figure 14-5 Cursor
A private SQL area is divided into the following areas:
The run-time area
This area contains query execution state information. For example, the run-time area tracks the number of rows retrieved so far in a full table scan .
Oracle Database creates the run-time area as the first step of an execute request. For DML statements, the run-time area is freed when the SQL statement is closed.
The persistent area
This area contains bind variable values. A bind variable value is supplied to a SQL statement at run time when the statement is executed. The persistent area is freed only when the cursor is closed.
The client process is responsible for managing private SQL areas. The allocation and deallocation of private SQL areas depends largely on the application, although the number of private SQL areas that a client process can allocate is limited by the initialization parameter OPEN_CURSORS .
Although most users rely on the automatic cursor handling of database utilities, the Oracle Database programmatic interfaces offer developers more control over cursors. In general, applications should close all open cursors that will not be used again to free the persistent area and to minimize the memory required for application users.
SQL Work Areas
A work area is a private allocation of PGA memory used for memory-intensive operations.
For example, a sort operator uses the sort area to sort a set of rows. Similarly, a hash join operator uses a hash area to build a hash table from its left input, whereas a bitmap merge uses the bitmap merge area to merge data retrieved from scans of multiple bitmap indexes.
The following example shows a join of employees and departments with its query plan :
In the preceding example, the run-time area tracks the progress of the full table scans. The session performs a hash join in the hash area to match rows from the two tables. The ORDER BY sort occurs in the sort area.
If the amount of data to be processed by the operators does not fit into a work area, then Oracle Database divides the input data into smaller pieces. In this way, the database processes some data pieces in memory while writing the rest to temporary disk storage for processing later.
The database automatically tunes work area sizes when automatic PGA memory management is enabled. You can also manually control and tune the size of a work area. See "Memory Management" for more information.
Generally, larger work areas can significantly improve performance of an operator at the cost of higher memory consumption. Optimally, the size of a work area is sufficient to accommodate the input data and auxiliary memory structures allocated by its associated SQL operator. If not, response time increases because part of the input data must be cached on disk. In the extreme case, if the size of a work area is too small compared to input data size, then the database must perform multiple passes over the data pieces, dramatically increasing response time.
Oracle Database Administrator’s Guide to learn how to use automatic PGA management
- Что такое триггер?
- Что такое транзакция?
- Какие категории файлов включает физический уровень БД Oracle?
- В каком табличном пространстве хранится словарь данных?
- Какая разница между сегментом, экстентом и блоком данных?
На эти вопросы очень просто ответить, внимательно прочитав предыдущий выпуск.
Экземпляр Oracle состоит из процессов и разделяемой памяти, необходимой для доступа к информации в БД. Если копнуть чуть глубже, то экземпляр составляют пользовательские процессы, фоновые процессы Oracle и разделяемая область памяти, которую используют все эти процессы.
Что же представляет собой разделяемая память (shared memory)? Oracle использует разделяемую память в разных целях: как кэширование данных и индексов, так и хранение программного кода. Разделяемая память делится на несколько частей (или структур памяти). Основными структурами памяти Oracle являются Системная Глобальная Область (System Global Area или SGA) и Программная Глобальная Область (Program Global Area или PGA). Рассмотрим SGA и PGA более подробно.
Системная Глобальная Область (SGA)
кэш буферов БД - здесь хранятся последние открытые блоки данных. Эти блоки могут содержать данные, которые изменились, но еще не были записаны на диск (грязные блоки); данные, которые не изменялись либо были записаны на диск после изменения (чистые блоки). Так как кэш буферов БД хранит блоки данных на основе алгоритма последних используемых блоков, то наиболее активно используемые блоки постоянно остаются в памяти (тем самым, снижая дисковый ввод/вывод и увеличивая производительность системы).
буфер журнала изменений - хранит данные об изменениях БД. Буфер журнала изменений записывается в файл журнала изменений настолько быстро и эффективно, насколько это возможно. Помните, что журнал изменений используется для восстановления экземпляра СУБД Oracle в случае сбоя системы.
разделяемый пул - Это область SGA, в которой хранятся такие структуры разделяемой памяти, как разделяемые SQL-области в библиотечном кэше и внутренняя информация словаря данных. Разделяемый пул важен, потому что недостаточный объем памяти, выделенный для него, может привести к деградации производительности всей системы. Разделяемый пул состоит из библиотечного кэша и кэша словаря данных.
Библиотечный кэш используется для хранения разделяемых SQL. Здесь для каждого уникального SQL-выражения строиться дерево разбора строк и план исполнения, которые кэшируются (т.е. сохраняются в библиотечном кэше). Если несколько приложений отправляют одинаковые SQL-выражения, то для ускорения работы используется разделяемая SQL-область (так как используются уже разобранные строки и готовый план исполнения, то происходит экономия времени).
Oracle часто обращается к словарю данных при разборе SQL-выражений. Эти обращения составляют сущность работы Oracle. Узкие места в словаре данных влияют работу всех пользователей системы Oracle. Поэтому Вы всегда должны быть уверены, что объем памяти, определенный для словаря данных, достаточно велик для кэширования данных. Если кэш словаря данных мал, то Вы заметите значительное снижение производительности. Когда под кэш словаря данных Вы определите достаточный объем памяти, существенных проблем с производительностью быть не должно.
Программная Глобальная Область (PGA)
информация сеанса - если Oracle работает не в мультинитевом режиме, то информация сеанса хранится в PGA. В противном случае, информация сеанса хранится в SGA.
Процесс (или нить) - это механизм выполнения программного кода, который может выполняться незаметно для пользователя. Кроме того, несколько процессов могут работать одновременно. В разных операционных системах и на разных платформах они могут называться по-разному (процессы, нити, демоны и т.д.), но, в сущности, одинаковы. СУРБД Oracle работает с двумя видами процессов: пользовательские процессы и процессы Oracle (также известные как фоновые или теневые). В некоторых операционных системах (таких как Windows NT) процессы действительно являются нитями, но, чтобы не путаться в понятиях, будем называть их просто "процессами".
Пользовательские (клиентские) процессы - это пользовательские соединения с СУРБД. Пользовательский процесс управляет вводом и взаимодействует с серверными процессами Oracle через программный интерфейс Oracle. Пользовательский процесс используется также для выдачи информации пользователю, и, при необходимости, представляет ее в более удобной форме.
Процессы Oracle выполняют функции для пользовательских процессов. Могут быть разбиты на две группы: серверные процессы (выполняющие функции для активных процессов) и фоновые процессы (выполняют функции СУРБД в целом).
Серверные процессы (теневые) взаимодействуют между процессами пользовательскими и Oracle, исполняя пользовательские запросы. Например, если пользовательский процесс запрашивает часть данных, которых еще нет в SGA, то теневой процесс несет ответственность за чтение блоков данных из БД в SGA. Между пользовательским и теневым процессом возникает связь один-к-одному (конфигурация выделенного сервера), хотя один теневой процесс может одновременно взаимодействовать с несколькими пользовательскими (конфигурация мультинитевого сервера), экономя системные ресурсы.
DBWR (DataBase Writer) - ответственен за запись грязных блоков из блоковых буферов БД на диск. Когда транзакция изменяет информацию в блоке данных, этот блок данных не обязан быть немедленно записан на диск. Следовательно, DBWR может записывать данные на диск способом более эффективным, чем запись всех изменений по отдельности. DBWR обычно записывает данные тогда, когда они уже нужны для чтения. Записываются также те данные, которые были недавно использованы. Для систем с асинхронным вводом/выводом достаточно одного процесса DBWR. Для остальных систем можно значительно увеличить производительность, создав несколько процессов DBWR.
CKPT (ChecK PoinT) - дает сигнал процессам DBWR о необходимости выполнения контрольной точки и обновления всех файлов данных и управляющих файлов. Контрольная точка - это событие, когда все измененные буферы БД записываются на диск. CKPT - это не обязательный процесс. Если процесс CKPT не запущен, то его работу принимает на себя LGWR.
PMON (Process MONitor) - используется для поддержания остальных процессов и перезапуска преждевременно погибших :) Также PMON очищает неиспользуемые области буферов и освобождает те ресурсы, которые могут быть еще заняты. Ответственен за перезапуск всех зависших процессов и диспетчеров.
SMON (System MONitor) - выполняет восстановление экземпляра при его запуске. Это включает очистку временных сегментов и восстановление незаконченных транзакций. А также дефрагментирует БД.
RECO (RECOvery) - очищает незаконченные транзакции в распределенной БД. Выполняет фиксацию или откат спорных транзакций.
ARCH (ARCHiver) - копирует файлы журнала изменений при их заполнении. ARCH активен только в том случае, если СУРБД работает в режиме ARCHIVELOG. Если система не работает в этом режиме, то возможны ситуации, в которых не удастся восстановить систему после сбоя. В некоторых случаях все же можно работать и в режиме NOARCHIVELOG.
LCKn (Parallel Server LoCK) - до десяти процессов (где n - от 0 до 9) могут использоваться при работе сервера в параллельном режиме. Выполняют функции межэкземплярной блокировки.
Dnnn (Dispatcher) - при работе сервера в мультинитевом режиме, то существует хотя бы один диспетчерский процесс, ответственный за каждый протокол взаимосвязи. Диспетчерские процессы организуют взаимодействие между пользовательскими и разделяемыми серверными процессами.
Читайте также: