Sga oracle что такое

Обновлено: 03.07.2024

  • Что такое триггер?
  • Что такое транзакция?
  • Какие категории файлов включает физический уровень БД 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. приватная SQL-область - это часть PGA, где хранятся связанные переменные и буферы реального времени.

Процесс (или нить) - это механизм выполнения программного кода, который может выполняться незаметно для пользователя. Кроме того, несколько процессов могут работать одновременно. В разных операционных системах и на разных платформах они могут называться по-разному (процессы, нити, демоны и т.д.), но, в сущности, одинаковы. СУРБД Oracle работает с двумя видами процессов: пользовательские процессы и процессы Oracle (также известные как фоновые или теневые). В некоторых операционных системах (таких как Windows NT) процессы действительно являются нитями, но, чтобы не путаться в понятиях, будем называть их просто "процессами".

Пользовательские (клиентские) процессы - это пользовательские соединения с СУРБД. Пользовательский процесс управляет вводом и взаимодействует с серверными процессами Oracle через программный интерфейс Oracle. Пользовательский процесс используется также для выдачи информации пользователю, и, при необходимости, представляет ее в более удобной форме.

Процессы Oracle выполняют функции для пользовательских процессов. Могут быть разбиты на две группы: серверные процессы (выполняющие функции для активных процессов) и фоновые процессы (выполняют функции СУРБД в целом).

Серверные процессы (теневые) взаимодействуют между процессами пользовательскими и Oracle, исполняя пользовательские запросы. Например, если пользовательский процесс запрашивает часть данных, которых еще нет в SGA, то теневой процесс несет ответственность за чтение блоков данных из БД в SGA. Между пользовательским и теневым процессом возникает связь один-к-одному (конфигурация выделенного сервера), хотя один теневой процесс может одновременно взаимодействовать с несколькими пользовательскими (конфигурация мультинитевого сервера), экономя системные ресурсы.

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

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

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

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

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

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

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

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 создает и использует структуры памяти для различных целей. Например, память хранит выполняемый код программы, данные, которые совместно используются пользователями, а также частные области данных для каждого подключенного пользователя. Две основных структуры памяти связаны с экземпляром:

Системная Глобальная область (SGA): Группа структур разделяемой памяти, известных как компоненты SGA, которые содержат данные и управляющую информацию для одного экземпляра Базы данных Oracle. SGA совместно используется всеми серверными и фоновыми процессами. Примеры данных, хранимых в SGA, включают кэшированные блоки данных и общие области SQL.

Глобальные программные области (PGA): области памяти, которые содержат данные и управляющую информацию для серверного или фонового процесса. PGA - неразделяемая память, создаваемая Базой данных Oracle при запуске серверного или фонового процесса. Доступ к PGA является монопольным для серверного процесса. У каждого серверного процесса и фонового процесса есть своя собственная PGA.

SGA - область памяти, которая содержит данные и управляющую информацию для экземпляра. SGA включает следующие структуры данных:

Разделяемый пул: Кэширует различные конструкты, которые могут совместно использоваться пользователями

Кэш буферов базы данных: Кэширует блоки данных, получаемые от базы данных

Буферный пул хранения: специализированный тип буферного кэша базы данных, который настраивается для хранения блоков данных в памяти на длительные промежутки времени

Буферный пул удаления: специализированный тип буферного кэша БД, который настраивается для быстрого повторного использования или удаления блока из памяти

Буферный кэш nK: Один из нескольких специализированных буферных кэшей БД, разработанный для хранения блоков с размером, отличающимся от размера блока базы данных по умолчанию

Буфер журнала повторов: Кэширует информацию о повторах (используемую, например, при восстановлении экземпляра), пока она не будет записана в физические файлы журнала повторов, хранимые на диске

Большой пул: Дополнительная область, которая обеспечивает выделения памяти большого объема для определенных больших процессов, таких как резервное копирование и операции восстановления Oracle, или серверные процессы ввода-вывода

Пул Java: Используется для всех специфичных для сеанса кода Java и данных в виртуальной машине Java (JVM)

Пул потоков: Используется потоками Oracle, чтобы хранить информацию, требуемую для операций захвата и применения

Когда Вы запускаете экземпляр с помощью Enterprise Manager или SQL*Plus, объем памяти, выделенный для SGA, выводится на экран.

Глобальной программной областью (PGA) является область памяти, которая содержит данные и управляющую информацию для каждого серверного процесса. Серверный процесс Oracle обслуживает запросы клиента. У каждого серверного процесса есть своя собственная частная PGA, которая выделяется при запуске серверного процесса. Доступ к PGA является монопольным для соответствующего серверного процесса, чтение и запись в PGA выполняется только кодом Oracle, действующим по запросу PGA. PGA делится на две главных области: стековое пространство и пользовательская глобальная область (UGA).

С динамичной инфраструктурой SGA размеры буферного кэша базы данных, разделяемого пула, большого пула, пула Java и пула потоков могут изменяться без необходимости завершения экземпляра.

База данных Oracle использует параметры инициализации, чтобы создать и управлять структурами памяти. Самый простой способ управлять памятью состоит в том, чтобы позволить базе данных автоматически управлять и настраивать ее для Вас. Чтобы сделать это (на большинстве платформ), необходимо только установить целевые параметры инициализации объема памяти (MEMORY_TARGET) и максимального объема памяти (MEMORY_MAX_TARGET).

Читайте также: