oracle xdb что это

. К несчастию, никак не мог прибрать рифмы для лядунок и киверов; итак, пусть будет это в прозе.
А. С. Грибоедов, Письмо из Бреста Литовского к издателю «Вестника Европы»

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

Введение

Возможности XML DB были развиты в версии 10, а судя по просачивающимся сведениям, получат дальнейшее развитие и в версии Oracle 11, существующей сегодня в бета-варианте и возможно планируемой к выпуску в 2007 году.

В этой статье рассказано, как можно установить XML DB в своей БД и как наладить внешнее взаимодействие с ней. В следующих статьях будет рассказано, как при установленной XML DB работать с репозитарием, регистрировать и использовать схему XML и создавать сервлеты в СУБД для досупа к данным.

Большинство возможностей Oracle XML DB, обозначенных ниже, обеспечены уже в версии Oracle 9.2.0.2, однако в некоторых технических подробностях могут иметься отличия по отношению к более поздним версиям.

Установка XML DB может выполняться средствами Database Configuration Assistant (DBCA), либо вручную. Типовой вариант БД, начиная с версии 9.2 включает предустановленную XML DB и не требует дополнительной установки.

Узнать о наличии установленной XML DB и готовности к работе можно так:

SQL> CONNECT / AS SYSDBA

2 FROM dba_objects

3 WHERE owner = ‘XDB’ AND status = ‘INVALID’;

SQL> COLUMN comp_name FORMAT A30

SQL> SELECT comp_name, status, version

2 FROM dba_registry

3 WHERE comp_name = ‘Oracle XML Database’;

COMP_NAME STATUS VERSION

Oracle XML Database VALID 10.2.0.1.0

При полученных выше ответах может потребоваться, однако, разблокировать подключение к СУБД (уже имеющемуся) пользователю XDB, например :

ALTER USER xdb ACCOUNT UNLOCK IDENTIFIED BY xdb;

Если же в существующей БД XML DB не установлена, вручную это можно сделать следующей последовательностью действий от имени SYS :

1) Завести табличное пространство для нужд пользователя XDB (желательно).

2) Прогнать сценарий catqm.sql заведения необходимой инфраструктуры в БД (реестр XML DB, служебные пакеты PL / SQL и пр.):

SQL > @?/ rdbms / admin / catqm пароль_для_ XDB табличное_пространство_для_ XDB табличное_пространство_для_временных данных_ XDB

3) Прогнать сценарий catqm.sql заведения необходимых библиотек на Java и типов (они могут иметься и без этого):

4) Прогнать сценарий создания пакетов из состава XDK (по желанию):

5) Выполнить SHUTDOWN и STARTUP.

Для убирания из БД XML DB достаточно выполнить от имени SYS:

1) SQL> @?/rdbms/admin/catnoqm

2) SHUTDOWN и STARTUP

Пользователь XDB и сопутствующие пакеты будут удалены.

Как открыть доступ к репозитарию по протоколам HTTP и FTP


Действия по открытию доступа

Во-первых, требуется удостовериться в нужных значениях параметров СУБД DISPATCHERS (обязательно) и LOCAL_LISTENER (при наличии нескольких процессов listener ). Установка нужных значений может быть выполнена так:

SET dispatchers = ‘(PROTOCOL=TCP)(SERVICE= ORCLXDB )’

EXECUTE DBMS_XDB. SETFTPPORT ( 2100 )

EXECUTE DBMS_XDB. SETHTTPPORT ( 8080 )

ALTER SYSTEM REGISTER;

Выдача последней команды некритична. После этого по некоторым рекомендациям нужно перезапустить СУБД:

SQL> SHUTDOWN IMMEDIATE

В ОС следует выдать:

Ожидаемый результат должен выглядеть примерно так:

Listening Endpoints Summary.

Service «PLSExtProc» has 1 instance(s).

Instance «PLSExtProc», status UNKNOWN, has 1 handler(s) for this service.

Service «orcl» has 1 instance(s).

Instance «orcl», status READY, has 1 handler(s) for this service.

Service » orclXDB » has 1 instance(s).

Instance «orcl», status READY, has 1 handler(s) for this service.

Проверка доступа по FTP

(А) Проверка средствами командной строки ОС:

ftp> open localhost 2100

Connected to FLEXIT-V3TNTGIS.

Unauthorised use of this FTP server is prohibited and may be subject to civil and criminal prosecution.

220 FLEXIT-V3TNTGIS FTP Server (Oracle XML DB/Oracle Database) ready.

User (FLEXIT-V3TNTGIS:(none)): xdb

331 pass required for XDB

200 PORT Command successful

150 ASCII Data Connection

226 ASCII Transfer Complete

ftp: 34 bytes received in 0,39Seconds 0,09Kbytes/sec.

ftp> get xdbconfig.xml

200 PORT Command successful

150 ASCII Data Connection

226 ASCII Transfer Complete

ftp: 11612 bytes received in 0,61Seconds 19,07Kbytes/sec.

2) Подключиться по FTP под именем SCOTT и удостовериться в невозможности извлечь файл из XML DB.

(Б) Проверка средствами браузера MS IE:

Войти в браузер MS IE, набрать в поле адреса следующие варианты и проверить работу:

Проверка доступа по HTTP

Войти в браузер Web, набрать в поле адреса следующие варианты и проверить работу:

Обратите внимание на доступность текстового вида страниц.

Организация доступа по WebDAV в Windows

При установленном доступе по HTTP, Oracle поддерживает также основанное на этом протоколе средство WebDAV (Web-based Distributed Authoring and Versioning, http://techinfo.net.ru/webdav.html ). ОС Windows обеспечивает клиентский доступ к серверу WebDAV, позволяя обращаться к репозитарию XML DB как к каталогу собственной файловой системы.

Заведение каталога в Windows на основе доступа по WebDAV

Действия в Windows:

Соединение заведено. Войти в репозитарий можно, нажав дважды на имя «каталога» XML DB Repository.

Проверка доступа

Доступ по WebDAV обеспечивает не обязательно только Windows Explorer, но и целый ряд продуктов разных фирм.

Источник

oracle xdb что это. Смотреть фото oracle xdb что это. Смотреть картинку oracle xdb что это. Картинка про oracle xdb что это. Фото oracle xdb что этоВ любой типичной организации информация хранится в нескольких форматах, часть которой, возможно, помещается в реляционные базы данных, но большая часть все-таки хранится за пределами этих баз данных. Не помещаемая в базы данных информация может храниться в формате конкретных приложений, например, электронных таблиц Excel. Сохранение ее вместо этого в формате XML позволяет упрощать процесс получения доступа и обновления неструктурированных данных организации.

Oracle XML DB (XML-база данных Oracle) не является базой данных специально предназначенного для XML-данных типа. Она просто дополнительно содержит набор встроенных технологий для хранения, извлечения и манипулирования XML-данными. Она обладает преимуществами одновременно и технологии реляционных баз данных, и технологии XML. Например, одна из главных проблем при работе с XML-данными в реляционной базе данных состоит в том, что большинство XML-данных имеют иерархическую структуру по своей природе, в то время как база данных Oracle основана на реляционной модели. Через Oracle XML DB предоставляется возможность эффективной обработки иерархических XML-данных за счет применения специальных SQL-операторов и методов, которые позволяют запрашивать и обновлять XML-данные в базе Oracle. Посредством Oracle XML DB в ядро Oracle встраивается объектная модель документов XML ( Document Object Model — DOM). Благодаря этому, большинство операций с данными XML воспринимается как часть обычного процесса обработки данных.

Oracle XML DB предоставляет возможность просматривать как структурированную, так и неструктурированную информацию в формате реляционных данных. То есть данные можно просматривать как в виде строк в таблице, так и в виде узлов в XML-документе.

Ниже приведен краткий перечень предлагаемых XML-базой данных Oracle преимуществ:

Сохранение XML-данных в Oracle XML DB

Для сохранения и управления XML-данными в реляционной таблице применяется специальный тип данных XMLType. Этот тип, а также тип XDBURIType, который представляет собой еще один встроенный тип, предназначенный для работы с данными XML, позволяет возлагать ответственность за выполнение синтаксического анализа, хранение и извлечение XML-данных на базу данных Oracle. Использовать тип XMLType можно точно так же, как и обычные типы данных в базе данных Oracle. Благодаря ему, правильно оформленный XML-документ теперь можно сохранять в базе данных в виде XML-теста с использованием базового типа данных CLOB.

Ниже приведен пример применения типа данных XMLType:

Тип данных XMLType поставляется с набором специальных XML-методов, которые можно использовать для работы с объектами XMLType. Эти методы можно применять для выполнения как типичных операций в базе данных, наподобие проверки на предмет существования узла или извлечения узла, так и нескольких специальных операций, позволяющих получать доступ к XML-данными и манипулировать ими в виде части обычного SQL-оператора. Эти специальные операции являются отражением развивающегося стандарта SQL/XML. За счет использования уже хорошо известной нотации XPath, они осуществляют обход по структурам XML и отыскивают тот узел или узлы, к которым им следует применить указанные SQL-операторы. Ниже перечислены некоторые наиболее важные операции SQL/XML.

XML-данные имеют абстрактную форму по сравнению с записями в обычных реляционных таблицах. Для оптимизации и выполнения операторов, подразумевающих обработку XML-данных, в Oracle применяется механизм перезаписи запросов, преобразующий выражение XPath в обычный эквивалентный оператор SQL. После этого оптимизатор обрабатывает этот преобразованный SQL-оператор подобно любому другому оператору SQL.

Сохранять XML-данные в XML-базе данных Oracle можно двумя способами.

Ниже приведен простой пример, в котором для демонстрации выполнения основанной на SQL операции DML в отношении поддерживающей XML таблицы используется таблица sales_catalog_table. В листинге 2 в эту таблицу вставляется XML-документ.

Теперь для просмотра XML-документа в его исходном формате достаточно просто запросить столбец sales_order таблицы sales_catalog_table, как показано в листинге 3.

oracle xdb что это. Смотреть фото oracle xdb что это. Смотреть картинку oracle xdb что это. Картинка про oracle xdb что это. Фото oracle xdb что это

После создания из таблицы sales_catalog_table можно очень легко извлекать данные с помощью любого из описанных выше методов. Ниже показан пример применения метода extract(). В этом примере выражения XPath и операции SQL/XML extractValue и existsNode применяются для поиска названия того отправления, у которого в узле SalesOrder/SalesLocation/text() содержится значение Dallas.

Репозиторий Oracle XML DB

Обрабатывать XML-документы в Oracle XML DB лучше всего, сначала загрузив их в специальное хранилище, называемое репозиторием Oracle XML DB. Этот репозиторий имеет иерархическую структуру, как и большинство XML-данных, и позволяет легко запрашивать XML-данные. Для представления отношений между XML-данными в нем используются пути и URL-адреса, а для прохода по содержащимся внутри него папкам и путей — специальный иерархический индекс. В нем могут храниться и данные, отличные от XML, наподобие изображений JPEG, документов Word и многое другое.

Для получения доступа к этому репозиторию можно применять SQL и PL/SQL. Инструменты авторизации XML позволяют получать доступ к находящимся внутри него документам напрямую за счет использования популярных Интернет-протоколов вроде HTTP, FTP и WebDAV. Например, для работы с хранящимися в этом репозитории XML-документами можно легко применять такие приложения, как Windows Explorer, Microsoft Office и Adobe Acrobat. XML-данные являются документными по своей природе, а репозиторий XML обеспечивает приложения возможностью абстрагировать файлы при работе с ними.

Настройка схемы XML

Прежде чем приступить к использованию Oracle XML DB для работы с XML-документами, понадобится выполнить следующие задачи.

Создание реляционного представления из XML-документа

Даже если разработчик плохо разбирается в XML, он все равно может использовать XML-документы, хранящиеся в базе данных Oracle, за счет создания на их основе реляционных представлений. Ниже приведен пример отображения узлов в XML-документе на столбцы в реляционном представлении по имени salesorder_view:

Далее к этому представлению salesorder_view можно выполнять запросы точно так же, как и к любому другому представлению в базе данных Oracle, как показано ниже:

Источник

Oracle xdb что это

Возможности XML DB были развиты в версии 10, а судя по просачивающимся сведениям, получат дальнейшее развитие и в версии Oracle 11, существующей сегодня в бета-варианте и возможно планируемой к выпуску в 2007 году.

В этой статье рассказано, как можно установить XML DB в своей БД и как наладить внешнее взаимодействие с ней. В следующих статьях будет рассказано, как при установленной XML DB работать с репозитарием, регистрировать и использовать схему XML и создавать сервлеты в СУБД для досупа к данным.

Большинство возможностей Oracle XML DB, обозначенных ниже, обеспечены уже в версии Oracle 9.2.0.2, однако в некоторых технических подробностях могут иметься отличия по отношению к более поздним версиям.

Установка и убирание XML DB

Установка XML DB может выполняться средствами Database Configuration Assistant (DBCA), либо вручную. Типовой вариант БД, начиная с версии 9.2, включает предустановленную XML DB и не требует дополнительной установки.

Узнать о наличии установленной XML DB и готовности к работе можно так:

При полученных выше ответах может потребоваться, однако, разблокировать подключение к СУБД (уже имеющемуся) пользователю XDB, например:

Пользователь XDB и сопутствующие пакеты будут удалены.

Как открыть доступ к репозитарию по протоколам HTTP и FTP

Действия по открытию доступа

Во-первых, требуется удостовериться в нужных значениях параметров СУБД DISPATCHERS (обязательно) и LOCAL_LISTENER (при наличии нескольких процессов listener). Установка нужных значений может быть выполнена так:

Выдача последней команды некритична. После этого по некоторым рекомендациям нужно перезапустить СУБД:

В ОС следует выдать:

Ожидаемый результат должен выглядеть примерно так:

Проверка доступа по FTP

Проверка доступа к репозитарию- возможно наиболее эффектный шаг в освоении XML DB. Для FTP может выполняться двояко.

(А) Проверка средствами командной строки ОС:

Жирным шрифтом выделены команды, набранные пользователем (набор пароля для пользователя XDB на экране не отразился). По результату этих действий из репозитария XML DB в текущий каталог ОС скопировался файл xdbconfig.xml. Подключиться по FTP к репозитарию XML DB можно было и под любым другим именем пользователя Oracle, однако не все пользователи смогут совершать все операции с имеющимися файлами.

(Б) Проверка средствами браузера MS IE:
Проверка доступа по HTTP

Обратите внимание на доступность текстового вида страниц.

Организация доступа по WebDAV в Windows

При установленном доступе по HTTP, Oracle поддерживает также основанное на этом протоколе средство WebDAV (Web-based Distributed Authoring and Versioning, http://techinfo.net.ru/webdav.html). ОС Windows обеспечивает клиентский доступ к серверу WebDAV, позволяя обращаться к репозитарию XML DB как к каталогу собственной файловой системы.

Заведение каталога в Windows на основе доступа по WebDAV

Соединение заведено. Войти в репозитарий можно, нажав дважны на имя «каталога» XML DB Repository.

Проверка доступа

Подключиться в Windows Explorer к сетевому ресурсу с именем ‘XML DB Repository’ и копировать файлы между репозитарием XML DB и файловой системой ОС методом Drag and Drop.

Доступ по WebDAV обеспечивает не обязательно только Windows Explorer, но и целый ряд продуктов разных фирм.

Источник

Oracle xdb что это

Репозитарий XML DB фактически представляет из себя древовидно-организованую файловую систему внутри БД, при том что элементами ее являются ресурсы: каталоги (папки) и файлы. В статье показано, как можно работать с репозитарием XML DB.

Введение

Технически ресурсы репозитария XML DB суть документы XML. Элемент Contents каждого такого документа представляет содержание ресурса, а все остальные элементы являются метаданными, описывающими ресурс.

Здесь рассматриваются две первые категории средств, а последняя оставлена для самостоятельных упражнений.

Доступ к ресурсам средствами SQL

Обе таблицы хранят список ресурсов с путями доступа, однако благодаря возможности определять связки (links), подобно как в файловой системе, путей доступа к одному ресурсу может оказаться несколько; их-то все и покажет таблица PATH_VIEW, в отличие от RESOURCE_VIEW.

Примеры запросов.

Описание первого попавшегося ресурса:

Выдать описания ресурсов, имеющихся в папке /sys/acls:

Выдать относительные имена ресурсов, имеющихся в папке /sys/acls (в данном случае это будут имена файлов), и их полные имена:

Описание ресурса-папки /sys/acls:

Полное описание ресурса-файла /sys/acls/all_all_acl.xml:

С запросами последнего типа следует соблюдать осторожность, так как элемент Contents результирующего документа XML хранит для ресурса-файла его содержимое, а оно может оказаться очень объемистым («большой файл»).

Содержание ресурса-файла /sys/acls/all_all_acl.xml с содержимым в формате XML:

Другие типы файлов могут хранить описание содержимого в элементе /Resource/Contents/text или /Resource/Contents/binary.

Работа с ресурсами в программе

Заводить, изменять свойства и удалять ресурсы в репозитарии XML DB можно с помощью пакета PL/SQL DBMS_XDB.

Обратите внимание, что XML DB по-разному хранит файл в зависимости от его расширения (упражнение: убедитесь, что XML DB интерпретирует содержимое именно по расширению файла, а не оттого, что внутри). Соответствие расширений файлов типам MIME устанавливается и выясняется в файле-ресурсе /xdbconfig.xml.

Создание связи (link):

Обратите внимание на два пути доступа в репозитарии к одному и тому же файлу (ресурсу).

Упражнение. Проверьте реакцию XML DB на попытку удалить несуществующий файл или непустую папку.

В отличие от производных таблиц (view) словаря-стправочника в Oracle, производные таблицы RESOURCE_VIEW и PATH_VIEW обновляемы (на деле это «объектно-реляционные» таблицы). Это позвляет, например, удалить связь также и командой DELETE, или переместить существующий ресурс в другую папку обычной операцией UPDATE:

Пример помещения в репозитарий файла ОС:

Технически файлы репозитария размещаются служебных таблицах БД (документы XML) или в объектах LOB (файлы всех остальных типов). Использование формата MIME для хранения двоичных файлов не является самым экономным, что относится к издержкам метода.

Разграничение доступа

В XML DB имеются несколько встроенных ACL, заданных следующими ресурсами:

/sys/acls/all_all_acl.xml
/sys/acls/all_owner_acl.xml
/sys/acls/bootstrap_acl.xml
/sys/acls/ro_all_acl.xml

ACL файла /public/OracleXML.doc в программе можно узнать так:

Пример замены ACL ресурса:

Создадим в БД роль и создадим в XML DB соответствующий ей файл ACL:

Защитим файл /public/OracleXML.doc созданым ACL:

Проверим видимость ресурса пользователем SCOTT. Для удобства создадим сначала файл с запросом:

При включении пользователя в группу ранее невидимый ресурс стал виден.

Тип XDBURITYPE для работы с ресурсами

Для работы с ресурсами репозитария можно использовать системный подтип XDBURITYPE абстрактного типа URITYPE. В частности, методы типа XDBURITYPE позволяют извлекать из репозитария содержимое ресурсов.

Пример определения длины файла /public/OracleXML.doc:

Таким же образом можно извлечь большой файл (содержимое, а не длину) в переменную программы.

Другие возможности

Любой ресурс репозитария можно перевести в режим версионного доступа (version control resource, VCR). С этой целью, и с целью самого доступа, следует использовать особый пакет DBMS_XDB_VERSION.

Любой ресурс репозитария можно снабдить собственным описанием (метаданными; в дополнение к «системным» метаданным), добавив в его описание XML («системное») свои элементы. Для этой цели можно использовать разные средства:

    методом PROPPATCH протокола WebDAV.

    Подробности имеются в документации по Oracle.

    Источник

    1 Introduction to Oracle XML DB

    Oracle XML DB provides Oracle Database with native XML support by encompassing both the SQL and XML data models in an interoperable way.

    1.1 Overview of Oracle XML DB

    Oracle XML DB is a set of Oracle Database technologies related to high-performance handling of XML data: storing, generating, accessing, searching, validating, transforming, evolving, and indexing. It provides native XML support by encompassing both the SQL and XML data models in an interoperable way.

    Oracle XML DB is included as part of Oracle Database starting with Oracle9 i Release 2 (9.2).

    Oracle XML DB and the XMLType abstract data type make Oracle Database XML-aware. Storing XML data as an XMLType column or table lets the database perform XML-specific operations on the content. This includes XML validation and optimization. XMLType storage allows highly efficient processing of XML content in the database.

    Oracle XML DB includes the following features:

    Enterprise-level Oracle Database features for XML content: reliability, availability, scalability, and security. XML-specific memory management and optimizations.

    Industry-standard ways to access and update XML data. You can use FTP, HTTP(S), and WebDAV to move XML content into and out of Oracle Database. Industry-standard APIs provide programmatic access and manipulation of XML content using Java, C, and PL/SQL.

    Ways to store, query, update, and transform XML data while accessing it using SQL and XQuery.

    Ways to perform XML operations on SQL data.

    Oracle XML DB Repository: a simple, lightweight repository where you can organize and manage database content, including XML content, using a file/folder/URL metaphor.

    Ways to access and combine data from disparate systems through gateways, using a single, common data model. This reduces the complexity of developing applications that must deal with data from different stores.

    Ways to use Oracle XML DB in conjunction with Oracle XML Developer’s Kit (XDK) to build applications that run in the middle tier in either Oracle Fusion Middleware or Oracle Database.

    Oracle XML DB functionality is partially based on the Oracle XML Developer’s Kit C implementations of the relevant XML standards, such as XML Parser, XSLT Virtual Machine, XML DOM, and XML Schema Validator.

    1.2 Oracle XML DB Benefits

    Oracle XML DB supports all major XML, SQL, Java, and Internet standards. It provides high performance and scalability for XML operations. It brings database features such as transaction control, data integrity, replication, reliability, availability, security, and scalability to the world of XML.

    Figure 1-1 presents an overview of the standards supported by Oracle XML DB.

    Figure 1-1 Oracle XML DB Benefits

    oracle xdb что это. Смотреть фото oracle xdb что это. Смотреть картинку oracle xdb что это. Картинка про oracle xdb что это. Фото oracle xdb что это
    Description of «Figure 1-1 Oracle XML DB Benefits»

    1.2.1 Data and Content Unified

    With Oracle XML DB, you can store and manage data that is structured, unstructured, and semi-structured using a standard data model and standard SQL and XML. You can perform SQL operations on XML documents and XML operations on object-relational (such as table) data.

    Most application data and Web content is stored in a relational database, a file system, or both. XML data is often used for data exchange, and it can be generated from a relational database or a file system. As the volume of XML data exchanged grows, the cost of regenerating this data grows, and these storage methods become less effective at accommodating XML content.

    Figure 1-2 Unifying Data and Content: Some Common XML Architectures

    oracle xdb что это. Смотреть фото oracle xdb что это. Смотреть картинку oracle xdb что это. Картинка про oracle xdb что это. Фото oracle xdb что это
    Description of «Figure 1-2 Unifying Data and Content: Some Common XML Architectures»

    Organizations often manage their structured data and unstructured data differently:

    Unstructured data, stored in tables, makes document access transparent and table access complex.

    Structured data, often stored in binary large objects (such as in BLOB instances), makes access more complex and table access transparent.

    1.2.1.1 Database Capabilities for Working with XML

    Oracle Database provides database capabilities for working with XML: indexing and search; updates and transaction processing; managing relationships using constraints; multiple data views; high performance and scalability. It supports XML Schema, XQuery, XPath, and DOM.

    Indexing and search – Just as your database data can be more or less structured, so can your queries. One query can look for all product definitions created between March and April 2014. Another query can look for products whose descriptions contain the words » wireless » and » router » but not the term » wireless router «.

    A query such as the former targets structured data, and it is typically supported by a B-tree index on a date column. A query such as the latter targets unstructured data, and for Oracle Database it is typically supported by an Oracle Text (full-text) index. Applications can of course combine structured and unstructured queries, and targeted data can be a mix of structured and unstructured data.

    For XML data the situation is similar. Oracle XML DB provides indexing features that let you target the gamut of XML possibilities, from data and queries that are highly structured to those that are highly unstructured.

    Updates and transaction processing – Commercial relational databases use fast updates of subparts of records, with minimal contention between users trying to update. As traditionally document-centric data participate in collaborative environments through XML, this requirement becomes more important. File or CLOB storage cannot provide the granular concurrency control that Oracle XML DB does.

    Managing relationships – Data with any structure typically has foreign-key constraints. XML data stores generally lack this feature, so you must implement any constraints in application code. Oracle XML DB enables you to constrain XML data according to XML schema definitions, and hence achieve control over relationships that structured data has always enjoyed.

    The purchase-order examples in Query and Update of XML Data

    Multiple views of data – Most enterprise applications need to group data together in different ways for different modules. This is why relational views are necessary—to allow for these multiple ways to combine data. By allowing views on XML, Oracle XML DB creates different logical abstractions on XML for, say, consumption by different types of applications.

    Performance and scalability – Users expect data storage, retrieval, and query to be fast. Loading a file or CLOB value, and parsing, are typically slower than relational data access. Oracle XML DB dramatically speeds up XML storage and retrieval.

    Ease of development – Databases are foremost an application platform that provides standard, easy ways to manipulate, transform, and modify individual data elements. While typical XML parsers give standard read access to XML data they do not provide an easy way to modify and store individual XML elements. Oracle XML DB supports several standard ways to store, modify, and retrieve data. These include XML Schema, XQuery, XPath, DOM, and Java.

    1.2.1.2 Advantages of Storing Data as XML in the Database

    Storing data as XML in the database provides these advantages: storage independence, ease of presentation, and ease of interchange.

    Storage independence: When you use relational design, your client programs must know where your data is stored, in what format, what table, and what the relationships are among those tables. XMLType enables you to write applications without that knowledge and lets database administrators map structured data to physical table and column storage.

    Ease of presentation: XML is understood natively by Web browsers, many popular desktop applications, and most Internet applications. Relational data is generally not accessible directly from applications. Additional programming is required to make relational data accessible to standard clients. Oracle XML DB stores data as XML and makes it available as XML outside the database. No extra programming is required to display database content.

    Ease of interchange – XML is the language of choice in business-to-business (B2B) data exchange. If you are forced to store XML in an arbitrary table structure, you are using some kind of proprietary translation. Whenever you translate a language, information is lost and interchange suffers. By natively understanding XML and providing DOM fidelity in the storage/retrieval process, Oracle XML DB enables a clean interchange.

    1.2.2 Data Duality: XML and Relational

    Oracle XML DB presents a symmetric, dual view of data: as XML and as relational.

    A key feature of Oracle XML DB is that it lets you work with XML data as if it were relational data and relational data as if it were XML data. You can leverage the power of the relational model when working with XML content, and you can leverage the flexibility of XML when working with relational content. You can use the most appropriate tools for different aspects of a particular business problem.

    This duality means that the same data can be exposed as rows in a table and manipulated using SQL or exposed as nodes in an XML document and manipulated using XQuery, the DOM, or XSL transformation. Access and processing techniques are independent of the underlying storage method.

    These features can provide simple solutions to common business problems:

    You can generate XML data directly from a SQL query. You can transform the XML data into other formats, such as HTML, using the database-resident XSLT processor.

    You can access XML content without converting between different data formats, using SQL queries, on-line analytical processing (OLAP), and business-intelligence/data warehousing operations.

    You can perform text, spatial data, and multimedia operations on XML content.

    1.2.2.1 Use XMLType Views If Your Data Is Not XML

    XMLType views provide a way for you to wrap existing relational or object-relational data in XML format.

    This can be especially useful if your legacy data is not in XML format but you must migrate it to XML format. Using XMLType views, you need not alter your application code or the stored data.

    To use XMLType views, you must first register an XML schema with annotations that represent a bidirectional mapping between XML Schema data types and either SQL data types or binary XML encoding types. You can then create an XMLType view conforming to this mapping, by providing an underlying query that constructs instances of the appropriate types.

    1.2.3 Efficient Storage and Retrieval of Complex XML Documents

    Oracle XML DB provides high performance and scalability for XML operations, letting you manage the storage and retrieval of complex, large, or many XML documents.

    These are the major performance features of Oracle XML DB:

    Indexing XML data for structured or full-text search. See Indexes for XMLType Data and Full-Text Search over XML Data Without XQuery.

    Parallelism and Oracle Exadata Smart Scan. Query and update of XML data can be carried out in parallel. Oracle Exadata Smart Scan is enabled automatically for XML data.

    1.3 Oracle XML DB Architecture

    Oracle XML DB gives you protocol and programmatic access to XML data in the form of local and remote XMLType tables and views. It provides a WebDAV repository with resource versioning and access control.

    Figure 1-3 shows the software architecture of Oracle XML DB. The main features are:

    Storage of XMLType tables and views.

    You can store data that is in XMLType views in local or remote tables. You can access remote tables using database links.

    Support for XQuery, including XQuery Update and XQuery Full Text.

    Oracle XML DB Repository. You can store any kind of documents in the repository, including XML documents that are associated with an XML schema that is registered with Oracle XML DB. You can access documents in the repository in any of the following ways:

    HTTP(S), through the HTTP protocol handler

    WebDAV and FTP, through the WebDAV and FTP protocol handlers

    SQL, through Oracle Net Services, including Java Database Connectivity (JDBC)

    Figure 1-3 XMLType Storage

    oracle xdb что это. Смотреть фото oracle xdb что это. Смотреть картинку oracle xdb что это. Картинка про oracle xdb что это. Фото oracle xdb что это
    Description of «Figure 1-3 XMLType Storage»

    1.4 Oracle XML DB Features

    Oracle XML DB provides standard database features such as transaction control, data integrity, replication, reliability, availability, security, and scalability, while also allowing for efficient indexing, querying, updating, and searching of XML documents in an XML-centric manner.

    The hierarchical nature of XML presents a traditional relational database with some challenges:

    In a relational database, the table-row metaphor locates content. Primary-Key Foreign-Key relationships help define the relationships between content. Content is accessed and updated using the table-row-column metaphor.

    XML, on the other hand, uses hierarchical techniques to achieve the same functionality. A URL is used to locate an XML document. URL-based standards such as XLink are used to define relationships between XML documents. W3C Recommendations such as XPath are used to access and update content contained within XML documents. Both URLs and XPath expressions are based on hierarchical metaphors. A URL uses a path through a folder hierarchy to identify a document, whereas XPath uses a path through the node hierarchy of an XML document to access part of an XML document.

    Oracle XML DB addresses these challenges by introducing SQL functions and methods that allow the use of XML-centric metaphors, such as XQuery and XPath expressions for querying and updating XML Documents.

    The following sections describe the major features of Oracle XML DB:

    1.4.1 XMLType Data Type

    You can use XMLType as you would any other SQL data type. For example, you can create an XMLType table or view, or an XMLType column in a relational table.

    You can use XMLType in PL/SQL stored procedures for parameters, return values, and variables.

    XMLType is an Oracle Database object type, so you can also create a table of XMLType object instances. By default, an XMLType table or column can contain any well-formed XML document.

    You can constrain XMLType tables or columns to conform to an XML schema, in which case the database ensures that only XML data that validates against the XML schema is stored in the column or table. invalid documents are excluded.

    Oracle Database Object-Relational Developer’s Guide for information about Oracle Database object types and object-relational storage

    Oracle Database PL/SQL Packages and Types Reference for information about XMLType constructors and methods

    1.4.2 XMLType Storage Models

    XMLType is an abstract data type that provides different storage models to best fit your data and your use of it. As an abstract data type, your applications and database queries gain in flexibility: the same interface is available for all XMLType operations.

    XMLType tables and columns can be stored in these ways:

    Binary XML storage (the default) – XMLType data is stored in a post-parse, binary format designed specifically for XML data. Binary XML is compact, post-parse, XML schema-aware XML data. This is also referred to as post-parse persistence.

    Object-relational storage – XMLType data is stored as a set of objects. This is also referred to as structured storage and object-based persistence.

    With the use of appropriate indexes, binary XML storage offers good performance for most use cases. However, some advanced use cases can benefit from using object-relational storage.

    You can change XMLType storage from one model to another using database import/export. Your application code need not change. You can change XML storage options when tuning your application.

    For binary XML storage, SecureFiles is the default storage option. Foot 1 However, if either of the following is true then it is not possible to use SecureFiles LOB storage. In that case, BasicFiles is the default option for binary XML data:

    The tablespace for the XMLType table does not use automatic segment space management.

    Oracle Database SecureFiles and Large Objects Developer’s Guide for information about LOB storage options SecureFiles and BasicFiles

    Oracle Database Administrator’s Guide for information about automatic segment space management

    Oracle Database Reference for information about parameter DB_SECUREFILE

    1.4.3 XML Schema Support

    Support for the Worldwide Web Consortium (W3C) XML Schema Recommendation is a key feature in Oracle XML DB.

    The W3C Schema Working Group publishes a particular XML schema, often referred to as the schema for schemas, that provides the definition, or vocabulary, of the XML Schema language. An XML schema definition ( XSD Foot 2 ), also called an XML schema, is an XML document that is compliant with the vocabulary defined by the schema for schemas.

    An XML schema uses vocabulary defined by the schema for schemas to create a collection of XML Schema type definitions and element declarations that comprise a vocabulary for describing the contents and structure of a new class of XML documents, the XML instance documents that conform to that XML schema.

    This manual uses the term «XML schema» (lower-case «s») to reference any XML schema that conforms to the W3C XML Schema (upper-case «S») Recommendation. Since an XML schema is used to define a class of XML documents, the term «instance document» is often used to describe an XML document that conforms to a particular XML schema.

    XML schemas are commonly used as a mechanism for checking (validating) whether XML instance documents conform with their specifications. Oracle XML DB includes XMLType methods and SQL functions that you can use to validate XML documents against an XML schema.

    In Oracle XML DB, you can use a standard data model for all of your data, regardless of how structured it is. You can use XML Schema to automatically create database tables for storing your XML data. XML schema-based data maintains DOM fidelity and allows for significant database optimizations.

    XML schema-based data can be stored using either Oracle XML DB XMLType storage model: binary XML storage or object-relational storage. Non-schema-based XML data can be stored only using binary XML storage.

    You can also wrap existing relational and object-relational data as XMLType views, which can optionally be XML schema-based. You can map from incoming XML documents to XMLType storage, specifying the mapping using a registered XML schema.

    Choice of XMLType Storage and Indexing for information about XMLType storage models

    XML Schema Storage and Query: Basic for more information about using XML schemas with Oracle XML DB

    1.4.4 DTD Support in Oracle XML DB

    An XML schema is in general a much more powerful way to define XML document structure than is a DTD. You can nevertheless use DTDs to some extent with Oracle XML DB.

    Like an XML schema, A DTD is a set of rules that define the allowable structure of an XML document. DTDs are text files that derive their format from SGML. They can be associated with an XML document by using DTD element DOCTYPE or by using an external file through a DOCTYPE reference.

    Oracle XML DB uses XML Schema, not DTDs, to define structured mappings to XMLType storage, but XML processors can still access and interpret your DTDs.

    You can use a DTD to obtain the XML entities defined in it. The entities are the only information used from the DTD. The structural and type information in the DTD is not used by Oracle XML DB.

    Inline DTD Definitions

    When an XML instance document has an inline DTD definition, that definition is used during document parsing. Any DTD validations and entity declaration handling are done at this point. However, once parsed, the entity references are replaced with actual values and the original entity reference is lost.

    External DTD Definitions

    1.4.5 Static Data Dictionary Views Related to XML

    Several static data dictionary views are related to XML.

    Table 1-1 lists these views. Information about a given view can be obtained by using SQL command DESCRIBE :

    Table 1-1 Static Data Dictionary Views Related to XML

    Registered XML schemas owned by the current user

    Registered XML schemas usable by the current user

    Registered XML schemas in Oracle XML DB

    XMLType tables owned by the current user

    XMLType tables usable by the current user

    XMLType tables in Oracle XML DB

    XMLType table columns owned by the current user

    XMLType table columns usable by the current user

    XMLType table columns in Oracle XML DB

    XMLType views owned by the current user

    XMLType views usable by the current user

    XMLType views in Oracle XML DB

    XMLType view columns owned by the current user

    XMLType view columns usable by the current user

    XMLType view columns in Oracle XML DB

    1.4.6 SQL/XML Standard Functions

    Oracle XML DB provides the SQL functions that are defined in the SQL/XML standard.

    SQL/XML functions fall into two groups:

    Functions that you can use to generate XML data from the result of a SQL query. In this book, these are called SQL/XML publishing functions. They are also sometimes called SQL/XML generation functions.

    Functions that you can use to query and update XML content as part of normal SQL operations. In this book, these are called SQL/XML query and update functions.

    Using SQL/XML functions you can address XML content in any part of a SQL statement. These functions use XQuery or XPath expressions to traverse the XML structure and identify the nodes on which to operate. The ability to embed XQuery and XPath expressions in SQL statements greatly simplifies XML access.

    Oracle Database SQL Language Reference for information about Oracle support for the SQL/XML standard

    Query and Update of XML Data and XQuery and Oracle XML DB for detailed descriptions of the SQL/XML standard functions for querying XML data

    Generation of XML Data Using SQL Functions for information about SQL/XML standard functions for generating XML data

    Overview of How To Use Oracle XML DB for additional examples that use SQL/XML standard functions

    1.4.7 Programmatic Access to Oracle XML DB (Java, PL/SQL, and C)

    All Oracle XML DB functionality is accessible from C, PL/SQL, and Java.

    You can build Web-based applications that take advantage of Oracle XML DB in various ways, including these:

    Using servlets and Java Server Pages (JSP). A typical API accesses data using Java Database Connectivity (JDBC).

    Using Extensible Stylesheet Language (XSL) plus XML Server Pages (XSP). A typical API accesses data in the form of XML documents that are processed using a Document Object Model (DOM) API implementation.

    Oracle XML DB supports such styles of application development. It provides Java, PL/SQL, and C implementations of the DOM API. Applications that use JDBC, such as those based on servlets, need prior knowledge of the data structure they are processing. Oracle JDBC drivers allow you to access and update XMLType tables and columns, and call PL/SQL procedures that access Oracle XML DB Repository. Applications that use DOM, such as those based on XSLT transformations, typically require less knowledge of the data structure. DOM-based applications use string names to identify pieces of content, and must dynamically walk through the DOM tree to find the required information. For this, Oracle XML DB supports the use of the DOM API to access and update XMLType columns and tables. Programming to a DOM API is more flexible than programming through JDBC, but it may require more resources at run time.

    1.4.8 Oracle XML DB Repository: Overview

    Oracle XML DB Repository is a component of Oracle Database that lets you handle XML data using a file/folder/URL metaphor.

    Oracle XML DB Repository contains resources, which can be either folders (directories, containers) or files.

    A resource, whether folder or file, has these properties:

    It has content (data), which can be XML data but need not be.

    It might also have user-defined metadata. Like system-defined metadata, this is information that is not part of the content, but is associated with it.

    It has an associated access control list that determines who can access the resource, and for what operations.

    Although Oracle XML DB Repository treats XML content specially, you can use the repository to store other kinds of data besides XML. You can use the repository to access any data that is stored in Oracle Database.

    You can access data in the repository in the following ways:

    SQL – Using views RESOURCE_VIEW and PATH_VIEW

    Standard protocols – FTP, HTTP(S), and WebDAV

    PL/SQL – Using PL/SQL package DBMS_XDB_REPOS

    Java – Using the Oracle XML DB resource API for Java

    Besides providing APIs for accessing and manipulating repository data, Oracle XML DB provides APIs for the following repository services, which are based on IETF WebDAV:

    Versioning – Using PL/SQL package DBMS_XDB_VERSION

    ACL Security – Using access control lists (ACLs)

    Foldering – Using repository path names

    Figure 1-4 illustrates the architecture of Oracle XML DB Repository.

    Figure 1-4 Oracle XML DB Repository Architecture

    oracle xdb что это. Смотреть фото oracle xdb что это. Смотреть картинку oracle xdb что это. Картинка про oracle xdb что это. Фото oracle xdb что это
    Description of «Figure 1-4 Oracle XML DB Repository Architecture»

    1.5 Standards Supported by Oracle XML DB

    Oracle XML DB supports all major XML, SQL, Java, and Internet standards.

    These include the following:

    W3C XML Schema 1.0 Recommendation. You can register XML schemas, validate stored XML content against XML schemas, or constrain XML stored in the server to XML schemas.

    W3C XQuery 1.0 Recommendation and W3C XPath 2.0 Recommendation. You can search or traverse XML stored inside the database using XQuery and XPath, either from HTTP(S) requests or from SQL.

    ANSI/ISO/IEC 9075-14:2011, Information technology—Database languages—SQL—Part 14: XML-Related Specifications (SQL/XML).

    W3C DOM Recommendation Levels 1.0 and 2.0 Core. You can retrieve XML stored in the server as an XML DOM, for dynamic access.

    Java Database Connectivity (JDBC) API. Provides Java access to XML data.

    XQuery API for Java (XQJ). Provides Java access to XML data using XQuery.

    W3C XSL 1.0 Recommendation. You can transform XML documents at the server using XSLT.

    Protocol support. You can store or retrieve XML data from Oracle XML DB using Oracle Net or standard protocols such as HTTP(S), FTP, and IETF WebDAV.

    Web services: SOAP 1.1. You can access XML stored in the server from SOAP requests. You can build, publish, or find Web Services using Oracle XML DB and Oracle Fusion Middleware, using WSDL and UDDI. You can use Oracle Streams Advanced Queuing IDAP, the SOAP specification for queuing operations, on XML stored in Oracle Database.

    W3C XML Linking Language (Xlink) 1.0 Recommendation. You can define various types of links between XML documents.

    W3C XML Pointer Language (XPointer) Recommendation and XPointer Framework. You can include the content of multiple XML documents or fragments in a single infoset.

    «SQL/XML Standard Functions» for more information about the SQL/XML functions

    Oracle Database SQL Language Reference for information about Oracle support for the SQL/XML standard

    How To Use XLink and XInclude with Oracle XML DB for more information about XLink and XPointer support

    Repository Access Using Protocols for more information about protocol support

    How to Write Oracle XML DB Applications in Java for information about using the Java servlet

    1.6 Oracle XML DB Technical Support

    Besides the regular channels of support through your customer representative or consultant, technical support for Oracle Database XML-enabled technologies is available free through the discussion forums Oracle Technology Network (OTN).

    The URL for the discussion forums is as follows: https://community.oracle.com/community/database

    1.7 Oracle XML DB Examples

    The examples that illustrate the use of Oracle XML DB and XMLType are based on various database schemas, sample XML documents, and sample XML schemas.

    1.8 Oracle XML DB Case Studies and Demonstrations on OTN

    Visit OTN to view Oracle XML DB examples, white papers, case studies, and demonstrations.

    Comprehensive XML classes on how to use Oracle XML DB are also available. See the Oracle University link on OTN.

    Detailed Oracle XML DB case studies available on OTN include the following:

    Oracle XML DB Downloadable Demonstration. This detailed demonstration illustrates how to use many Oracle XML DB features. Parts of this demonstration are also included in Overview of How To Use Oracle XML DB.

    SAX Loader Application. This demonstrates an efficient way to break up large files containing multiple XML documents outside the database and insert them into the database as a set of separate documents. This is provided as a standalone and a Web-based application.

    Источник

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    SchemaDescription
    USER_XML_SCHEMAS