Shared pool oracle что это
Экземпляр БД Oracle состоит из блоков разделяемой памяти, называемых system global area (SGA) и background процессов. SGA содержит три обязательные структуры данных:
- Thedatabasebuffercache / содержит копии блоков данных считанные из файлов данных
- Thelogbuffer / содержит данные о транзакциях которые ещё не записаны в redolog
- Thesharedpool / содержит проверенные SQL выражения и кэш словаря данных, содержащий таблицы, представления и триггеры.
Также дополнительно могут быть:
- Largepool
- Javapool
- Streemspool
Эти структруры показаны на рисунке 1-5 и мы обсудим обязательные структуры.
Пользовательские сессии тоже требуют памитя на сервере. Как мы помним это неразделяемая область памяти, которая называется PGA. У каждой сессии своя PGA.
Управление объёмом памяти может осуществляться автоматически, или управляться администратором базы данных. Рекомендуется использовать автоматический способ управления.
Буфер логов (log buffer)
Буфер логов – это небольшая, краткосрочная выделенная область памяти для хранения записей изменений (change vector) до записи их в журнал (redo log) на диске. Запись изменений – это изменение произошедшее с чем либо; выполнений DML команда создаёт записи изменений. Сохранение всех таких записей – это гарантия того, что данные никогда не будут утеряны. Когда бы не изменились данные в блоке – запись изменений в блоке должна быть записана в журнал. Впоследствии эти записи могут быть считаны и применены к резервной копии файлов данных, если возникла необходимость.
Изменения не пишутся в журнал серверными процессами сессий. Если бы это было реализовано таким образом, сессиям пришлось бы ждать выполнения операций чтения/записи чтобы закончить выполнения любой DML команды. Вместо этого сессии пишут в буфер логов в памяти. Это гораздо быстрее чем писать на диск. Уже из буфера логов записи изменений (сформированные из разных сессий) пишутся в журнал.Одна операция записи в журнал может влючать множество изменений. Эти изменения пишутся примерно в реальном времени – но как только какая-нибудь сессия исполняет команду COMMIT – тут же происходит запись в журнал. Запись осуществляется background процессом – log writer-ом (LGWR).
Буфер логов небольшая (по сравнению с другими) область памяти, потому что время жизни данных там очень короткое. Изменения записываются в этот буфер и почти в тот же момент времени пишутся на диск. Нет необходимости делать размер больше чем несколько мегабайт, и более того, использование значение сильно большего чем значение по умолчанию может плохо сказаться на производительности. Значение по умолчанию устанавливается сервером Oracle в зависимости от количества процессоров на серверах.
Невозможно задать значение, меньше чем значение по умолчанию. Если попробовать сделать это, Oracle просто установит значение по умолчанию. Можно установить большее значение, но обычно этого делать не стоит. Основаная проблема в том, что когда выполняется команда COMMIT, запускается запись изменений из буфера на диск, и пока операции записи осуществляется, сессия которая запустила команду COMMIT будет ждать. Запись изменений важная часть архитектуры Oracle. Идея того что подтверждённые изменения никогда не будут утеряны в том, что выполнение команды commit считается успешным только тогда, когда данные изменены в buffer cache и записи зименений (vector change) записаны в журнал на диске (это значит что изменения могуть быть повторены при необходимости). Большой буфер логов может привести к тому что операция записи из него на диск будет занимать длительное время, а в это время сессия не может продолжать работу.
Память для буфера логов выделяется в момент запуска экземпляра БД и размер не может быть изменен без перезапуска. Это круговой буффер. Серверные процессы пишут записи изменений, и текущий указатель перемещается. Log writer записывает эти изменения на диск группами, и когда он это делает, место занятое этими записями становится снова доступным и может быть переписано новыми записями. В момент самой высокой нагрузки на сервер, может случиться так, что новые векторы должны быть записаны быстрее чем log writer может записать их на диск. Если такое случается все команды манипулированяи данными будут «подвисать» на некоторое время, пока log writer не очистит буфер.
Процесс записи изменений из буфера на диск одно из самых главных узких мест в архитектуре Oracle. Команды изменения не могут выполняться быстрее чем запись log writer-ом из буфера на диск.
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
Database buffer cache
Database buffer cache – это область где выполняются SQL команды. Когда мы обновляем данные, они не изменяются непосредственно в файлах данных на жёстком диске. Блоки данных, которые содержат данные с которыми мы работает вначале копируются в buffer cache (если они ещё не находятся там). Изменения (вставка, измнение или удаление данных) применяются к этим копиям данных в буфферном кэше. Затем эти блоки данных остаются в памяти некоторое время, пока место которое они занимают не понадобится для работы над какими-либо другими данными.
Когда мы хотим посмотреть какие-то данные – операция выдачи информации тоже происходит через кэш. Вначале находятся блоки данных которые мы запросили и копируются в буфер кэш (опять же если их ещё там нет); затем нужные данные переносятся в PGA для дальнейшей обработки.
Термин блок. Файлы данных представляют из себя данные сгруппированые в блоки фиксированной длины. Данные в таблицах (строки) и другие объекты такие как индексы и т.п. хранятся в этих блоках. Buffer cache также сгруппирован в структуры в памяти, чтобы вмещать в себя ровно один блок. Строки же могут быть разной длины: длина строки зависит от количества столбцов в ней, не важно есть ли в этих столбцах данные или нет. В зависимости от размера блока (размер выбирается администратором базы данных) и размера строки может быть несколько строк в блоке, или строка занимать несколько блоков. Структуру блока мы более детально рассмотрим в теме организация данных.
В идеале – блоки данных содержащие наиболее часто используемые данные будут в buffer cache, таким образом снижая количество операций чтения/записи. Как типичный пример работы буфер кэша рассмотрим пример типичной операции продавца в магазине, который получает данные о клиенте и обновляет их. Будут использованы примерно такие запросы:
SELECT CUSTOMER_ID,CUSTOMER_NAME FROM CUSTOMERS;
UPDATE CUSTOMERS SET CUSTOMER_NAME=’Вася’ WHERE CUSTOMER_ID=100;
Для того чтобы выполнить SQL команду селект пришедшую от пользователя, серверный процесс этой сессии вначале посмотрим есть ли уже в буфере блок данных, который содержит необходимую информацию. Если эта информация найдена, данные будут прочитаны (hit) из буфера. Преположим что данные не в буфере (miss), тогда серверный процесс считает блоки из файлов данных и поместит их в буфер, перед тем как вернуть данные пользователю.
Потом пользователь запускает команды UPDATE и COMMIT, которые будут обработаны серверным процессом. Допуская, что данные всё ещё доступны в buffer cache на момент выполнения этого запроса, строка будет обновлена в буфер кэше. В данном примере мы получим эффективность использования буфера – 50%. 2 раза доступ к данным в кэше буфера, один раз чтение данных с диска. Формула расчёта: 1-«кол-во чтений с диска»/кол-во чтений с буфера»). В хорошо оптимизированных базах данных этот показатель может достигать 90%.
Буффер в котором данные в блоках отличаеются от данных этих блоков на дисковом пространстве – называбтся грязными (dirty buffers). Буфер будет чистым (clean) когда блок только скопирован с диска в память: в этот момент времени данные одинаковые и в памяти и на диске. В итоге, грязные блоки данных должны быть записан назад на диск и тогда буфер опять станет чистым. Но даже после записи на диск, блоки остаются в памяти, пока их не перепишут другими блоками.
Важно, что нету прямой зависмости количества обновлений данных в буфере (комманд COMMIT) и количества операция записи данных назад в файлы данных. Запись в файлы данных производится background process-ом – database writer.
Размер buffer cache очень важен для производительности. Значение должно быть адекватно рассчитано, не минимальное — чтобы все часто используемые блоки (неважно чистые или грязные) находились в буфере, но не настолько большое чтобы даже редко используемые данные тоже находились в буфере. Недостаточный объём приведёт к избыточному использованию чтения/записи с диска, так как блоки будут читаться с диска, тут же переписываться и снова читаться. Слишком большой объём не настолько плохо как слишкомй маленький (пока он меньше чем размер реальной доступной оперативной памяти) но тоже может вызывать определённые проблемы: например запуск базы данных будет дольше, так как требуется форматирование большого объёма памяти.
Память для buffer cache выделяется на этапе запуска экземпляра БД. До версии 9i нельзя изменить размер буфер кэша без перезапуска инстанса. Начиная с версии 10 g – размер буфера кэша можно изменять как автоматически (включить механизм автоматическго управления), так и вручную.
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 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 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
The shared pool
Shared pool самая сложная область в SGA. Она состоит из под-областей, которые управляются Oracle сервером. Мы обсудим только 4 кмпонента:
Data dictionary cache
SQL PL/SQL function result cache
Управление этими структурами происходит автоматически. Размер изменяется динамически в зависимости от писпользования, но не превышает размер всей области памяти. Shared pool может тоже изменять размер или посредством настройки автоматического управления или командами администратора базы данных.
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
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
Library cache
Library cache это область памяти где хранятся последние выполненные запросы в разобранном виде. Разбор (parsing) – это процесс преобразования инструкция написанный программистом в исполняемые команды понятные Oracle. Этот процесс Oracle запускает по требованию. Хранение разобранных команд очень сильно увеличивает производительность, потому что процесс разбора занимает время. Рассмотрим пример простого запроса:
SELECT * FROM PRODUCTS WHERE PRODUCT_ID=100;
Перед тем как выполнять запрос, надо узнать что написано в запросе и как его выполнять. Начиная с того, что такое PRODUCTS? Мжет быть это таблица? Или синоним, представление? Вообще существует ли такой объект? Дальше символ «звездочка» — какие столбцы в таблице PRODUCTS (если это действительно таблица)? Есть ли у пользователя необходимые права чтобы просматривать эту таблицу? Вопросы на эти ответы и многие другие надо найти в словаре данных. Важное замечание – алгоритм поиска разобранного запроса в кэше базируется на ASCII символах которые использованы в запросе. Небольшое различие (к примеру использование строчных символов вместо прописных) может привести к тому что запрос будет разбираться опять.
После разбора запроса, сервер должен решить как наиболее оптимально выполнять его. Есть ли индекс для поля PRODUCT_ID? Если он есть, будет ли быстрее использовать индекс чтобы найти нужную строку, или проще просмотреть всю таблицу? И ещё больше и больше запросов в словарь данных. Бывает что для простого запроса надо создать много запросов в словарь данных и разбор занимает больше времени чем выполнение самого запроса. Смысл library cache – хранить запросы в разобранном виде, готовые к выполнению. Первый вызов необходимо обработать – второй вызов такого же запроса, тут же готов к выполнению. В хороших приложениях запросы подготавливаются один раз – а выполняются миллионы раз. Это позволяет сэкономить огромное количество времени.
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
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
По порядку - Shared Pool.
Разделяемый пул (Shared Pool) содержит кэш библиотек, кэш словаря и управляющие структуры сервера (такие как набор символов БД). Кэш библиотеки хранит текст, форматы лексического анализатора и план выполнения предложений SQL, которые адресуются БД. Кроме того, здесь находятся заголовки PL/SQL пакетов и процедур, выполнявшихся ранее. Так же кэш словаря хранит строки словаря данных, которые были использованы для анализа предложений SQL. Сам сервер Oracle использует для повышения производительности и скорости выполнения операций и операторов SQL, кэш библиотеки. Таким образом, когда передается очередное SQL - выражение, сервер, в первую очередь, просматривает кэш в поисках подобного выражения, которое уже передавалось ранее. Если оно найдено, то используется соответствующее дерево лексического анализа, что приводит к повышению скорости выполнения операторов SQL. Но, есть одно существенное замечание - выражения SQL, должны быть полностью идентичны, вплоть до регистра символов операторов и переменных. Так как Oracle сравнивает тексты выражений, применяя алгоритм хеширования, который чувствителен к регистру символов текста. Так же кэш библиотек содержит разделяемые и локальные области SQL. Разделяемая область включает в себя дерево лексического анализа и план выполнения SQL - оператора, а локальная область информацию, зависящую от текущего сеанса работы. Локальная область формируется для каждой инициируемой транзакции и освобождается после того, как закрывается соответствующий курсор. Этот процесс определяет параметр open_cursor в файле init.ora. В соответствии с этим, Oracle может повторно использовать информацию, общую для всех выражений SQL, а информация, специфическая для данного сеанса, может быть выбрана из локальной области Shared Pool. Локальная область SQL в свою очередь делится, на переходящую (persistent) и область времени выполнения (runtime). Переходящая область содержит информацию, которая сохраняет свое значение и может быть использована несколькими выражениями SQL. А область времени выполнения - только информацию, для выражения выполняемого в текущий момент. Кэш словаря содержит информацию из словаря данных, необходимую СУРБД для лексического анализа SQL - выражения. В ней находятся данные, касающиеся сегментирования, привилегий доступа и размеров свободной памяти. Собственно сам размер выделяемого пула определяется параметром SHARED_POOL_SIZE в файле init.ora. Это кстати очень интересный параметр и когда мы, наконец, доберемся до раздела создания экземпляра, вы с ним познакомитесь более тесно. Если его размер не достаточен, то может наступить момент когда для загрузки очередного объекта не найдется непрерывной области памяти подходящего объема. Нужно просто определять его размер с "запасом"! :)
Управление размером shared pool
Выбор оптимального объёма shared pool-а очень важен для производительности. Он должен быть достаточно большой для хранения всех часто используемых запросов и объектов, но не настолько большой чтобы хранить кэши для всех запросов и объектов. Слишком маленький размер снижает производительность так как сессиям нужно выделять память и записывать данные для запросов, потом другой запрос может переписать эту информацию и придётся повторять операцию опять. Слишком большой размер плохо влияет на производительность так как увеличивается время поиска в кэше.
Память в shared pool выделятся согласно алгоритму LRU (least recently used). Когда нужно выделить место в shared pool, сервер будет искать объекты которые не использовались дольше всех. Если этот объект потом понадобится опять – его придется перезагрузить (возможно снова удалив другой объект).
Shared pool выделяет память в момент запуска экземпляра БД. Начиная с версии 9i размер может изменяться динамически без перезапуска, либо механизмом атовматического управления, либо администратором.
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
Область PL/SQL (PL/SQL Area)
Объектами PL/SQL являются процедуры, функции, пакеты, сложные типы, триггеры. Все они хранятся в словаре данных в виде исходного когда и скомпилированной программы. Когда PL/SQL объект вызывается сессией, необходимо прочитать нужную информацию из словаря данных. Для того чтобы исключить повторное чтение, эти объекты кэшируются в области PL/SQL в shared pool.
Первый вызод займёт некоторое время, так как нужно считать информацию, но следующие вызовы будут гораздо быстрыее так как объект уже будет в области PL/SQL.
SQL Query and PL/SQL Function Result Cache
Данный кэш появился в версии 11 g. Во многих приложениях, одинаковые запросы выполняются много раз, или одной сессией или разными. Создание этого кэша позволило Oracle серверу хранит результаты подобных запросов в памяти. Когда запрос будет выполняться повторно вместо его реального выполнения, результат возьмётся из кэша.
Механизм кэширования отслеживает изменились ли данные в таблицах, которые используются в такого рода запросах. Если данные изменились, запрос будет перевыполнен. Это позволяет устранить проблему выдачи некорретных данных.
PL/SQL функции работают примерно также. Когда функция выполняется – результат кэшируется. Если параметры или данные в таблицах используемых в функции изменились, функция будет перезапущена – иначе будет использоваться кэшированный результат.
По умолчанию, SQL Query PL/SQL function result cache отключен. Но если его включить – можно получить очень существенное ускорение производительности. Для данного вида кэша администратор может установить максимальный размер памяти.
Кэш словаря данных (Data dictionary cache)
Data dictionary cache иногда называют row cache. В нём хранятся определения использованных объектов: описания таблиц, индексов, пользователей и другие мета-данные. Хранения этих данные в кэше в памяти SGA, где они доступны для всех сессий, в отличии от чтения их со словаря данных с диска, сильно увеличивает производительность разбора команд.
Кэш словаря данных хранит информацию об объектах, и когда нужно разобрать запрос это можно сделать без чтения данных из словаря данных. Предположим что выполняются 2 запроса
SELECT SUM(ORDER_AMOUNT) FROM ORDERS;
SELECT * FROM ORDERS WHERE ORDER_NO=100;
Два запроса нужно разобрать, поскольку они разные, но разбор первого запроса загрузит информацию о таблице ORDERS в кэш, и разбор второга запроса будет быстрее, потому что уже не нужно считывать информацию.
Читайте также: