Large Objects (LOB) это тип данных используемый для хранения больших объектов — различные форматы текстов, изображения, видео, звуковые файлы. Использование LOB для хранения данных позволяет эффективно манипулировать данными в приложении.
Компоненты LOB
LOB состоит из локатора и значения.
Локатор – это внутренний указатель на фактическое значение большого объекта.
Значение – это реальное содержимое объекта.
LOB хранит локатор в таблице и данные в различных сегментах, за исключением случая, когда размер данных меньше 4000 байт.
Максимальный размер LOB составляет ( 4 GB (4 294 967 295 байт) — 1 ) * (значение CHUNK parameter of LOB storage); размер может достигать до 128 терабайт.
Типы данных LOB
SQL Datatype
Описание
BLOB
Двоичный большой объект (Binary Large OBject) Хранит данные в двоичном формата, используется для хранения изображений, аудио и видео, а также компилированного программного кода
CLOB
Символьный большой объект (Character Large Object) Хранит текстовые данные в формате БД
NCLOB
Национальный символьный большой объект (National Character Set Large Object) Хранит текстовые данные в национальной кодировке.
BFILE
Внешний двоичный файл (External Binary File) Файл хранящийся вне базы данных, как файл операционной системы, но доступный из таблиц БД. BFILEs имеет доступ только для чтения. Когда LOB удаляется, Oracle сервер не удаляет сам файл. BFILE поддерживает только случайное(не последовательное) чтение, не участвует в транзакции.
Виды LOB
Как внутренние, так и внешние большие объекты могут быть использованы как столбцы таблицы, переменные в pl/sql, атрибуты объектов.
Internal LOB
Внутренние большие объекты — хранятся в табличных пространствах БД, поддерживаются следующие типы данных: BLOB, CLOB, and NCLOB.
Persistent and Temporary LOB
Внутренние большие объекты могут быть временными или постоянными. Постоянные LOB существуют в строках таблицы БД. Временные LOB создается для использования только в пределах локального приложения. Временный экземпляр становится постоянным если его вставить в строку таблицы.
Свойства Temporary LOB
External LOB
Внешние большие объекты — вид данных, который хранится в файлах операционной системы, вне табличных пространств БД. Используется тип данных – BFILE. BFILE может быть только внешним.
Использование пакета DBMS_LOB
DBMS_LOB предоставляет методы манипулирования внутренними и внешними LOBами.
Методы DBMS_LOB можно условно разделить на два типа mutators и observers:
Для инициализации LOB локаторов используются следующие функции:
CLOB и BLOB колонки, так же могут быть инициализированы с помощью символьной или raw строки, если длина не превыщает 4000 байт.
The DBMS_LOB package provides subprograms to operate on BLOBs, CLOBs, and NCLOBs. You can use DBMS_LOB to access and manipulate specific parts of LOBs or complete LOBs.
This chapter contains the following topics:
Using DBMS_LOB
Overview
DBMS_LOB can read, manipulate, and modify BLOBs, CLOBs, and NCLOBs.
Security model
Any DBMS_LOB subprogram called from an anonymous PL/SQL block is executed using the privileges of the current user. Any DBMS_LOB subprogram called from a stored procedure is executed using the privileges of the owner of the stored procedure.
When creating the procedure, users can set the AUTHID to indicate whether they want definer’s rights or invoker’s rights. For example:
Constants
The DBMS_LOB package uses the constants shown in Table 2-1:
Table 2-1 DBMS_LOB constants
Constant
Type
Value
Description
Create the temporary LOB with call duration.
This is the default character set ID.
This is the default language context.
Open the specified LOB read-only.
Open the specified LOB read/write.
Set maximum size of a BLOB in bytes.
Set maximum size of a CLOB in bytes.
Indicates success, no warning message.
Create the temporary LOB with session duration.
Note : In TimesTen, LOB duration cannot extend past the end of the transaction. Temporary LOB contents are destroyed when the corresponding locator is invalidated at the end of the transaction.
Create the temporary LOB with transaction duration.
Used by the conversion functions to indicate there is an inconvertible character.
The PLS_INTEGER and BINARY_INTEGER data types are identical. This document uses BINARY_INTEGER to indicate data types in reference information (such as for table types, record types, subprogram parameters, or subprogram return values), but may use either in discussion and examples.
The INTEGER and NUMBER(38) data types are also identical. This document uses INTEGER throughout.
Data types
The DBMS_LOB package uses the data types shown in Table 2-2.
Table 2-2 Data types used by DBMS_LOB
Source or destination binary LOB
Source or destination RAW buffer (used with BLOBs)
Source or destination character LOB (including NCLOBs)
Source or destination character buffer (used with CLOBs and NCLOBs)
Size of a buffer or LOB, offset into a LOB, or amount to access (in bytes for BLOBs or characters for CLOBs or NCLOBs)
The DBMS_LOB package defines no special types.
An NCLOB is a CLOB for holding fixed-width and varying-width, multibyte national character sets.
The clause ANY_CS in the specification of DBMS_LOB subprograms for CLOBs enables the CLOB type to accept a CLOB or NCLOB locator variable as input.
Rules and limits
General rules and limits
The following rules apply in the specification of subprograms in this package:
A subprogram raises an INVALID_ARGVAL exception if the following restrictions are not followed in specifying values for parameters (unless otherwise specified):
Only positive, absolute offsets from the beginning of LOB data are permitted. Negative offsets from the tail of the LOB are not permitted.
For CLOBs consisting of fixed-width multibyte characters, the maximum value for these parameters must not exceed ( CLOBMAXSIZE / character_width_in_bytes ) characters.
PL/SQL language specifications stipulate an upper limit of 32767 bytes (not characters) for RAW and VARCHAR2 parameters used in DBMS_LOB subprograms. For example, if you declare a variable as follows:
Then charbuf can hold 3000 single byte characters or 1500 two-byte fixed width characters. This has an important consequence for DBMS_LOB subprograms for CLOBs and NCLOBs.
The %CHARSET clause indicates that the form of the parameter with %CHARSET must match the form of the ANY_CS parameter to which it refers.
For DBMS_LOB subprograms that take two-character LOB parameters, both parameters must have the same form. That is, they must both be NCLOBs or they must both be CLOBs.
If the value of amount plus offset exceeds the maximum LOB size allowed by the database, then access exceptions are raised. In TimesTen, the maximum BLOB size is 16 MB and the maximum CLOB or NCLOB size is 4 MB.
The end-of-LOB condition is indicated by the READ procedure using a NO_DATA_FOUND exception. This exception is raised only upon an attempt by the user to read beyond the end of the LOB. The READ buffer for the last read contains 0 bytes.
Unless otherwise stated, the default value for an offset parameter is 1, which indicates the first byte in the BLOB data or the first character in the CLOB or NCLOB data. No default values are specified for the amount parameter. You must input the values explicitly.
Maximum LOB size
The maximum size for LOBs in TimesTen is 16 MB for BLOBs and 4 MB for CLOBs or NCLOBs.
Maximum buffer size
The maximum buffer size is 32767 bytes.
For BLOBs, where buffer size is expressed in bytes, the number of bytes cannot exceed 32767.
For CLOBs or NCLOBs, where buffer size is expressed in characters, the number of characters cannot result in a buffer larger than 32767 bytes. For example, if you are using fixed-width, two-byte characters, then specifying 20000 characters is an error (20000*2 = 40000, which is greater than 32767).
Operational notes
DBMS_LOB subprograms operate based on LOB locators. For the successful completion of DBMS_LOB subprograms, you must provide an input locator that represents a LOB, either a temporary LOB (discussed below) or a persistent LOB that already exists in the database tablespaces.
In TimesTen, LOB locators do not remain valid past the end of the transaction.
In TimesTen, you can write data into the middle of a LOB only by overwriting previous data. There is no functionality to insert data into the middle of a LOB and move previous data, beginning at that point, toward the end of the LOB correspondingly. Similarly, in TimesTen you can delete data from the middle of a LOB only by overwriting previous data with zeros or null data. There is no functionality to remove data from the middle of a LOB and move previous data, beginning at that point, toward the beginning of the LOB correspondingly. In either case in TimesTen, the size of the LOB does not change, except in the circumstance where from the specified offset there is less space available in the LOB than there is data to write. (In Oracle Database you can use the DBMS_LOB FRAGMENT procedures to insert or delete data, move other data accordingly, and change the size of the LOB. TimesTen does not support those procedures.)
DBMS_LOB procedures and functions are supported for both TimesTen LOBs and passthrough LOBs, which are LOBs in Oracle Database accessed through TimesTen and exposed as TimesTen LOBs. Note, however, that CREATETEMPORARY can only be used to create a temporary LOB in TimesTen. If a temporary passthrough LOB is created using some other mechanism, such as SQL, ISTEMPORARY and FREETEMPORARY can be used on that LOB.
TimesTen does not support DBMS_LOB subprograms intended specifically for BFILEs, SecureFiles (including Database File System features), or inserting or deleting data fragments in the middle of a LOB ( FRAGMENT subprograms).
The rest of this section discusses the following topics:
Persistent LOBs
Temporary LOBs
TimesTen supports the definition, creation, deletion, access, and update of temporary LOBs. The temporary data partition stores the temporary LOB data. Temporary LOBs are not permanently stored in the database. Their primary purpose is for performing transformations on LOB data from applications.
You can use PL/SQL to create or manipulate a temporary LOB (BLOB, CLOB, or NCLOB).
A temporary LOB is empty when it is created. In TimesTen, all temporary LOBs are deleted at the end of the transaction in which they were created. Also, if a process dies unexpectedly or if the database crashes, temporary LOBs are deleted and the space for temporary LOBs is freed.
There is no support for consistent-read, undo, backup, parallel processing, or transaction management for temporary LOBs. Because consistent-read and rollbacks are not supported for temporary LOBs, you must free the temporary LOB and start over again if you encounter an error.
In PL/SQL, do not use more than one locator for a temporary LOB. Because consistent-read, undo, and versions are not generated for temporary LOBs, there is potentially a performance impact if you assign multiple locators to the same temporary LOB. Semantically, each locator should have its own copy of the temporary LOB. A temporary LOB locator can be passed by reference to other procedures if necessary.
A copy of a temporary LOB is created if the user modifies the temporary LOB while another locator is also pointing to it. The locator on which a modification was performed now points to a new copy of the temporary LOB. Other locators no longer see the same data as the locator through which the modification was made. A deep copy was not incurred by persistent LOBs in these types of situations, because consistent-read snapshots and version pages enable users to see their own versions of the LOB cheaply.
Because temporary LOBs are not associated with any table schema, there are no meanings to the terms in-row and out-of-row for temporary LOBs. Creation of a temporary LOB instance by a user causes the engine to create and return a locator to the LOB data. The PL/SQL DBMS_LOB package, as well as other programmatic interfaces, operates on temporary LOBs through these locators just as they do for persistent LOBs.
There is no concept of client-side temporary LOBs. All temporary LOBs reside in the server.
When you are finished with a temporary LOB instance, use the FREETEMPORARY procedure to free it.
Security is provided through the LOB locator. Only the user who created the temporary LOB is able to see it. Locators cannot be passed from one user session to another. Even if someone did pass a locator from one session to another, they would not access the temporary LOBs from the original session.
The following notes are specific to temporary LOBs:
Operations based on CLOBs do not verify whether the character set IDs (CSIDs) of the parameters ( CLOB parameters, VARCHAR2 buffers and patterns, and so on) match. It is the user’s responsibility to ensure this.
Exceptions
Table 2-3 DBMS_LOB exceptions
Exception
Code
Description
There was an attempt to write too much data to the LOB. In TimesTen, BLOB size is limited to 16 MB and CLOB or NCLOB size is limited to 4 MB.
Cannot perform operation with LOB buffering enabled.
The length of the contenttype string exceeds the defined maximum. Modify the length of the contenttype string and retry the operation.
The length of the contenttype buffer is less than the defined constant. Modify the length of the contenttype buffer and retry the operation.
This is the end-of-LOB indicator for looping read operations. It is not a hard error.
Cannot perform a LOB write inside a query. (This is not applicable for TimesTen.)
This is a PL/SQL error for invalid values to subprogram parameters.
Summary of DBMS_LOB subprograms
Table 2-4 DBMS_LOB subprograms
Subprogram
Description
Appends the contents of the source LOB to the destination LOB.
Closes a previously opened LOB.
Compares two entire LOBs or parts of two LOBs.
Reads character data from a source CLOB or NCLOB, converts the character data to the specified character set, writes the converted data to a destination BLOB in binary format, and returns the new offsets.
Takes a source BLOB, converts the binary data in the source to character data using the specified character set, writes the character data to a destination CLOB or NCLOB, and returns the new offsets.
Copies all or part of the source LOB to the destination LOB.
Creates a temporary LOB in the temporary data partition.
Erases all or part of a LOB.
Frees a temporary LOB in the temporary data partition.
Returns the amount of space used in the LOB chunk to store the LOB value.
Returns the length of the LOB value, in bytes for a BLOB or characters for a CLOB.
Returns the storage limit for the LOB type of the specified LOB.
Returns the matching position of the n th occurrence of the pattern in the LOB.
Checks to see if the LOB was already opened using the input locator.
Checks if the locator is pointing to a temporary LOB.
Opens a LOB (persistent or temporary) in the indicated mode, read/write or read-only.
Reads data from the LOB starting at the specified offset.
Returns part of the LOB value starting at the specified offset.
Trims the LOB value to the specified length.
Writes data to the LOB from a specified offset.
Appends a buffer to the end of a LOB.
APPEND procedures
This procedure appends the contents of a source LOB to a destination LOB. It appends the complete source LOB. (Do not confuse this with the WRITEAPPEND procedure.)
Table 2-5 APPEND procedure parameters
Parameter
Description
Locator for the LOB to which the data is being appended
Locator for the LOB from which the data is being read
It is recommended that you enclose write operations to the LOB with OPEN and CLOSE calls, but not mandatory. If you opened the LOB before performing the operation, however, you must close it before you commit or roll back the transaction.
Table 2-6 APPEND procedure exceptions
Exception
Description
Cannot perform a LOB write inside a query. (This is not applicable for TimesTen.)
Cannot perform operation if LOB buffering is enabled on either LOB.
This example shows use of the APPEND procedure.
(Output is shown after running the commands from a SQL script.)
CLOSE procedures
This procedure closes a previously opened LOB.
Table 2-7 CLOSE procedure parameters
Parameter
Description
Locator for the LOB
CLOSE requires a round-trip to the server.
It is not mandatory that you wrap LOB operations inside OPEN and CLOSE calls. However, if you open a LOB, you must close it before you commit or roll back the transaction.
It is an error to commit the transaction before closing all LOBs that were opened by the transaction. When the error is returned, the «open» status of the open LOBs is discarded, but the transaction is successfully committed. Hence, all the changes made to the LOB and non-LOB data in the transaction are committed.
An error is returned if the LOB is not open.
COMPARE functions
This function compares two entire LOBs or parts of two LOBs.
Table 2-8 COMPARE function parameters
Parameter
Description
Locator for the first LOB for comparison
Locator for the second LOB for comparison
Number of bytes (for BLOBs) or characters (for CLOBs or NCLOBs) to compare
Offset in bytes or characters in the first LOB (starting from 1)
Offset in bytes or characters in the second LOB (starting from 1)
The function returns one of the following:
0 (zero) if the data matches exactly over the specified range
-1 if the first LOB is less than the second
1 if the first LOB is greater than the second
You can only compare LOBs of the same type. For example, you cannot compare a BLOB to a CLOB.
CONVERTTOBLOB procedure
This procedure reads character data from a source CLOB or NCLOB, converts the character data to the character set you specify, writes the converted data to a destination BLOB in binary format, and returns the new offsets. You can use this procedure with any combination of persistent or temporary LOBs.
Table 2-9 CONVERTTOBLOB procedure parameters
Parameter
Description
Locator for the destination LOB
Locator for the source LOB
Number of characters to convert from the source LOB
(IN) Offset in bytes in the destination LOB for the start of the write
Specify a value of 1 to start at the beginning of the LOB.
(OUT) The new offset in bytes after the end of the write
(IN) Offset in characters in the source LOB for the start of the read
(OUT) Offset in characters in the source LOB right after the end of the read
Character set ID for the converted BLOB data
(IN) Language context, such as shift status, for the current conversion (ignored by TimesTen)
(OUT) The language context at the time when the current conversion is done (set to 0 by TimesTen)
This parameter is not supported by TimesTen.
This parameter is not supported by TimesTen.
Both the source and destination LOBs must exist.
If the destination LOB is a persistent LOB, the row must be locked. To lock the row, select the LOB using the FOR UPDATE clause of the SELECT statement.
Constants and defaults
All parameters are required. You must pass a variable for each OUT or IN OUT parameter. You must pass either a variable or a value for each IN parameter.
Работа с большими объектами в PL/SQL (BFILE, LOB, SecureFiles)
Тема работы с большими объектами весьма объемна, поэтому мы не сможем рассмотреть все ее аспекты. Данную статью блога следует рассматривать как введение в программирование больших объектов для разработчиков PL/SQL. Мы познакомимся с некоторыми нюансами, которые необходимо учитывать, и рассмотрим примеры важнейших операций. Хочется надеяться, что представленный материал станет хорошей основой для ваших дальнейших исследований в этой области.
Прежде чем переходить к основному материалу, необходимо указать, что все примеры данного раздела основаны на следующем определении таблицы (см. файл source_code.sql):
Рис. 1. Водопад Драйер-Хоуз возле Мунисинга (штат Мичиган)
Таблица содержит информацию о водопадах, расположенных в северной части штата Мичиган. На рис. 1 изображен водопад Драйер-Хоуз возле Мунисинга; в замерзшем состоянии его часто посещают альпинисты.
Понятие локатора LOB
Рис. 2. Локатор LOB указывает на объект в базе данных
Этот механизм в корне отличается от того, как работают другие типы данных. Переменные и значения в столбцах LOB содержат локаторы больших объектов, которые идентифицируют реальные данные, хранящиеся в другом месте базы данных или вне ее. Для работы с данными типа LOB нужно сначала извлечь локатор, а затем с помощью встроенного пакета DBMS_LOB получить и/или модифицировать реальные данные. Так, для получения двоичных данных фотографии, локатор которой хранится в столбце BLOB из приведенной ранее таблицы, необходимо выполнить следующие действия:
Не все эти действия являются обязательными; не огорчайтесь, если что-то пока остается непонятным. Далее все эти операции будут описаны более подробно.
LOB-ДАННЫЕ В ДОКУМЕНТАЦИИ ORACLE
Если вам часто приходится работать с большими объектами, настоятельно рекомендуем ознакомиться со следующими документами Oracle:
Большие объекты — пустые и равные NULL
Очень важно понимать это различие, потому что у типов LOB способ проверки наличия либо отсутствия данных получается более сложным, чем у скалярных типов. Для традиционных скалярных типов достаточно простой проверки IS NULL :
Итак, проверять нужно два условия вместо одного.
Для создания пустого объекта BLOB используется функция EMPTY_BLOB (). Для типов CLOB и NCLOB используется функция EMPTY_CLOB ().
Запись данных в объекты LOB
Чтение данных из объектов LOB
В результате выполнения этого кода выводится следующий текст:
Особенности типа BFILE
Как упоминалось ранее, типы данных BLOB, CLOB и NCLOB представляют внутренние большие объекты, хранящиеся в базе данных, в то время как BFILE является внешним типом. Между объектами BFILE и внутренними LOB существуют три важных различия:
Создание локатора BFILE
Локатор BFILE — всего лишь комбинация псевдонима каталога и имени файла. Реальный файл и каталог даже не обязаны существовать. Иначе говоря, Oracle позволяет создавать псевдонимы для несуществующих каталогов, а BFILENAME — локаторы для несуществующих файлов. Иногда это бывает удобно.
Доступ к данным BFILE
Результат выполнения этого кода:
Использование BFILE для загрузки столбцов LOB
Не путайте предупреждения с ошибками PL/SQL; загрузка все равно будет выполнена в соответствии с запросом.
Следующий пример SQL*Plus демонстрирует загрузку данных из внешнего файла с использованием LOADCLOBFROMFILE :
SecureFiles и BasicFiles
По данным тестирования Oracle, повышение быстродействия от использования SecureFiles составляет от 200 до 900%. В простом тесте с загрузкой файлов PDF на сервер Microsoft Windows я наблюдал снижение времени загрузки от 80 до 90% от 169 секунд до 20–30 секунд (в зависимости от конфигурации и количества загрузок). В системе x86 Linux выигрыш был более скромным. Возможно, в вашей ситуации цифры будут другими, но ускорение будет наверняка!
Если вы не уверены относительно базы данных, обратитесь за помощью к администратору.
Устранение дубликатов
Сжатие
Чтобы включить режим устранения дубликатов одновременно со сжатием, укажите соответствующие параметры в определении LOB :
При включении обоих режимов сначала выполняется устранение дубликатов, а затем сжатие.
Шифрование
Созданный бумажник необходимо открывать заново после каждого перезапуска экземпляра. Открытие и закрытие бумажника выполняется следующим образом:
Временные объекты LOB
Создание временного объекта LOB
Другой способ создания временного объекта LOB основан на объявлении переменной LOB в коде PL/SQL и присваивании ей значения. Например, следующий фрагмент создает временные объекты BLOB и CLOB :
Освобождение временного объекта LOB
Процедура DBMS_LOB.FREETEMPORARY освобождает временный объект типа BLOB или CLOB в текущем временном табличном пространстве. Заголовок процедуры:
В следующем примере сначала создаются, а затем освобождаются два временных объекта LOB :
После вызова FREETEMPORARY освобожденный локатор LOB ( lob_loc ) помечается как недействительный. Если присвоить его другому локатору с помощью обычного оператора присваивания PL/SQL, то и этот локатор будет освобожден и помечен как недействительный.
PL/SQL неявно освобождает временные объекты LOB при выходе за пределы области действия блока.
Проверка статуса объекта LOB
Функция ISTEMPORARY позволяет определить, является ли объект с заданным локатором временным или постоянным. Она возвращает целочисленный код: 1 для временного объекта, 0 для постоянного.
Управление временными объектами LOB
Временные большие объекты обрабатываются не так, как обычные постоянные. Для них не поддерживаются транзакции, операции согласованного чтения, откаты и т. д. Такое сокращение функциональности имеет ряд следствий:
Встроенные операции LOB
Семантика SQL
Возможности, упомянутые в предыдущем разделе, Oracle называет «поддержкой семантики SQL для LOB ». С точки зрения разработчика PL/SQL это означает, что с LOB можно работать на уровне встроенных операторов (вместо отдельного пакета).
Следующий пример демонстрирует некоторые возможности семантики SQL:
Маленький фрагмент кода в этом примере содержит несколько интересных моментов:
Семантика SQL может создавать временные объекты LOB
Чтобы получить описание местонахождения водопада в верхнем регистре, сохранив возможность обновления исходного описания, необходимо получить два локатора LOB :
Влияние семантики SQL на быстродействие
А теперь представьте, сколько времени потребуется для создания копии каждого объекта CLOB для его преобразования к верхнему регистру, для выделения и освобождения пространства временных объектов CLOB во временном пространстве и для посимвольного поиска данных в CLOB средним объемом в 1 Гбайт. Конечно, такие запросы навлекут на вас гнев администратора базы данных.
Oracle Text и семантика SQL
За дополнительной информацией о CONTAINS и индексах Oracle Text, игнорирующих регистр символов, обращайтесь к документации Oracle Text Application Developer’s Guide.
Функции преобразования объектов LOB
Oracle предоставляет в распоряжение программиста несколько функций преобразования больших объектов. Перечень этих функций приведен в табл. 2.