ora2pgpro — это утилита, используемая при переносе базы данных из Oracle™ в схему, совместимую с Postgres Pro™. Утилита подключается к БД Oracle, автоматически сканирует её и извлекает её структуру или данные, а затем генерирует SQL-скрипты, которые можно загрузить в базу данных Postgres Pro. ora2pgpro можно использовать для разных целей от обратного проектирования БД Oracle до миграции баз данных крупных предприятий или для простого переноса данных из БД Oracle в БД Postgres Pro. Для использования утилиты не требуются знания БД Oracle — достаточно предоставить параметры подключения к БД Oracle.
Утилита ora2pgpro состоит из Perl-скрипта ora2pgpro и Perl-модуля Ora2PgPro.pm. Для использования утилиты достаточно указать в файле конфигурации ora2pgpro.conf DSN для подключения к БД Oracle и, при необходимости, имя схемы. После этого необходимо указать тип экспорта: TABLE с ограничениями, VIEW, MVIEW, TABLESPACE, SEQUENCE, INDEXES, TRIGGER, GRANT, FUNCTION, PROCEDURE, PACKAGE, PARTITION, TYPE, INSERT или COPY, FDW, QUERY, SYNONYM.
По умолчанию ora2pgpro экспортирует данные в файл, который можно загрузить в БД Postgres Pro, используя клиент psql. Кроме того, можно настроить импорт напрямую в БД Postgres Pro, указав DSN в файле конфигурации. Множество параметров конфигурации ora2pgpro.conf позволяют гибко управлять процессом экспорта. Доступны следующие функциональные возможности:
- Полный экспорт схемы БД (таблицы, представления, последовательности, индексы) с ограничениями уникальности, первичным ключом, внешними ключами и ограничениями-проверками.
- Экспорт прав пользователей и групп.
- Экспорт секций по спискам и по диапазонам.
- Экспорт нескольких таблиц (с указанием имён).
- Экспорт схемы Oracle как схемы Postgres Pro.
- Экспорт предопределённых функций, триггеров, процедур, пакетов и тел пакетов.
- Экспорт всех данных или выбранных предложением
WHERE. - Полная поддержка экспорта объектов BLOB Oracle как bytea Postgres Pro.
- Экспорт представлений Oracle как таблиц Postgres Pro.
- Экспорт определяемых пользователем типов Oracle.
- Базовое автоматическое преобразование кода PL/SQL в код PL/pgSQL.
- Работа на любой платформе.
- Экспорт таблиц Oracle как таблиц, реализованных через обёртку сторонних данных.
- Экспорт материализованных представлений.
- Вывод отчёта о содержимом БД Oracle.
- Оценка стоимости миграции БД Oracle.
- Оценка сложности миграции БД Oracle.
- Оценка стоимости миграции кода PL/SQL из файла.
- Оценка стоимости миграции SQL-запросов Oracle, хранящихся в файле.
- Экспорт Oracle Locator и пространственных данных в PostGIS.
- Экспорт
DBLINKв Oracle FDW. - Экспорт
SYNONYMкак представлений. - Экспорт
DIRECTORYкак внешних таблиц или каталога для расширенияexternal_file. - Передача SQL-команд с использованием нескольких соединений с Postgres Pro.
- Сравнение БД Oracle и Postgres Pro для целей тестирования.
Утилита ora2pgpro делает всё возможное, чтобы преобразовать БД Oracle в Postgres Pro автоматически, но некоторые действия необходимо выполнить вручную, например, проверить код PL/SQL, сгенерированный для функций, процедур, пакетов и триггеров, на соответствие синтаксису Postgres Pro. Некоторые рекомендации по портированию кода из PL/SQL в PL/pgSQL даны в разделах Портирование из Oracle PL/SQL и Инструменты миграции в Postgres Pro.
Утилите ora2pgpro требуется Oracle Instant Client, который не входит в состав ora2pgpro. Необходимо скачать RPM-пакет oracle-instantclient12.1-basic (например, файл oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm) отсюда или из другого источника и установить его. Для ora2pgpro используется старая версия 12.1, поскольку новые версии 19 и 21 могут обновиться в любой момент, и пакетный менеджер может посчитать их несовместимыми с пакетами Postgres Pro.
При использовании системы на базе Debian (Debian, Ubuntu, Astra Linux) необходимо конвертировать RPM-пакет в Debian-пакет, воспользовавшись alien или dpkg.
Загрузите скрипт подключения
pgpro-repo-add.sh. Это также можно сделать, используя wget:$ wget --user your-username --ask-password https://repo.postgrespro.ru/ora2pgpro/keys/pgpro-repo-add.sh
Запустите его с правами
root. Если дистрибутив поддерживается, то репозиторий будет подключён. Обратите внимание, что для системы на базе Debian следует подключить не только разделmain, но и разделcontrib, поскольку необходимый пакетlibdbd-oracle-perlнаходится именно в нём.
Установите пакет ora2pgpro с помощью пакетного менеджера. В зависимости от дистрибутива это может быть:
apt-get: Debian, Ubuntu, Astra, Альт Линуксdnf: Системы Red Hat Enterprise Linux (RHEL) и производные от них: РЕД ОС, РОСАyum: старые версии РОСАzypper: SLES
В любом случае укажите параметры install ora2pgpro.
Настройка ora2pgpro заключается в выборе экспортируемой БД Oracle и типа экспорта.
Используя один файл конфигурации ora2pgpro.conf, можно полностью управлять процессом миграции БД Oracle. В файле записывается имя директивы заглавными буквами и её значение после символа табуляции. Строки, начинающиеся с #, представляют собой комментарии. Директивы можно задавать в любом порядке, а включаются они при считывании значения в файле конфигурации.
Директивы, принимающие одно значение, можно задавать в файле конфигурации несколько раз, при этом будет использоваться последнее вхождение. Директивы, принимающие список значений, также можно задавать несколько раз, и значения из последующих вхождений будут добавляться в список. Если для загрузки пользовательского файла конфигурации используется директива IMPORT, директивы из этого файла будут сохраняться в файле конфигурации после директивы IMPORT, поэтому рекомендуется задавать её в конце файла конфигурации.
Значения, переданные в командой строке, переопределяют значения из файла конфигурации.
Сначала необходимо убедиться, что пути ко всем библиотекам и двоичным файлам включают каталог установки Oracle Instant Client:
export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib export PATH="/usr/lib/oracle/11.2/client64/bin:$PATH"
По умолчанию ora2pgpro выполняет поиск файла конфигурации /etc/ora2pgpro/ora2pgpro.conf, и если этот файл существует, достаточно выполнить команду:
/usr/local/bin/ora2pgpro
Если необходимо вызвать другой файл конфигурации, задайте путь в командной строке:
/usr/local/bin/ora2pgpro -c /etc/ora2pgpro/new_ora2pgpro.conf
Ниже приведены все доступные параметры командной строки для ora2pgpro:
ora2pgpro [-dhpqv --estimate_cost --dump_as_html] [--параметр значение]-a,--allowЗадать список экспортируемых объектов, разделённых запятыми. Параметр может также использоваться с типом
SHOW_COLUMN.-b,--basedirЗадать выходной каталог для файлов, полученных в результате экспорта.
-c,--confУказать файл конфигурации, отличный от используемого по умолчанию
/etc/ora2pgpro/ora2pgpro_scanner.conf.-C,--cdc_fileУказать файл для хранения/чтения SCN таблиц во время экспорта. По умолчанию:
TABLES_SCN.logв текущем каталоге. Для создания этого файла используйте параметр--cdc_ready.-d,--debugВыводить подробные сообщения.
-D,--data_typeРазрешить использование пользовательских типов в командной строке.
-e,--excludeИсключить из экспорта список указанных объектов, разделённых запятыми. Может использоваться с типом
SHOW_COLUMN.-h,--helpВыводить краткую справку.
-g,--grant_objectИзвлекать права для данного типа объектов. Возможные значения даны в описании конфигурации
GRANT_OBJECT.-i,--inputУказать файл, содержащий код PL/SQL для портирования, когда подключение к БД Oracle отсутствует.
-j,--jobsЗадать число параллельных процессов при передаче данных в Postgres Pro.
-J,--copiesЗадать число параллельных соединений для извлечения данных из Oracle.
-l,--logУказать файл журнала. По умолчанию:
stdout.-L,--limitЗадать количество кортежей, извлекаемых из Oracle и сохраняемых в памяти до записи, по умолчанию 10000.
-n,--namespaceУказать схему Oracle для извлечения данных.
-N,--pg_schemaЗадать
search_pathдля Postgres Pro.-o,--outУказать путь к выходному файлу, в который записываются команды SQL. По умолчанию:
output.sqlв текущем каталоге.-p,--plsqlВключить преобразование кода PL/SQL в код PL/pgSQL.
-P,--parallelЗадать число таблиц для параллельного извлечения данных.
-q,--quietОтключить вывод индикатора выполнения.
-r,--relativeИспользовать параметр
\irвместо\iв создаваемых скриптах psql.-s,--sourceЗадать источник данных DBI для Oracle.
-S,--scnЗадать системный номер изменения Oracle (System Change Number, SCN) для экспорта данных. Он используется в предложениях
WHEREдля получения данных с типами экспортаCOPYилиINSERT.-t,--typeЗадать тип экспорта. Параметр переопределяет значение, заданное в файле конфигурации (
TYPE).-T,--temp_dirУказать отдельный временный каталог для одновременного запуска двух или более экземпляров ora2pgpro.
-u,--userУказать пользователя для подключения к БД Oracle. Вместо этого параметра можно использовать переменную окружения
ORA2PG_USER.-v,--versionПоказать версию ora2pgpro и прервать выполнение.
-w,--passwordУказать пароль для пользователя БД Oracle. Вместо этого параметра можно использовать переменную окружения
ORA2PG_PASSWD.-W,--whereЗадать предложение
WHERE, добавляемое к запросу Oracle для получения данных. Параметр можно указывать несколько раз.--forceownerПринудительно назначать владельца таблиц и последовательностей, как в Oracle. Если в значении указать имя пользователя, он будет назначен владельцем. По умолчанию владельцем будет пользователь, используемый для подключения к БД Postgres Pro.
--nls_langЗадать кодировку клиента Oracle в
NLS_LANG.--client_encodingЗадать кодировку клиента Postgres Pro.
--view_as_tableУказать список представлений, разделённых запятыми, для экспорта в виде таблиц.
--estimate_costАктивировать оценку стоимости миграции для
SHOW_REPORT.--cost_unit_valueЗадать число минут для оценки стоимости. По умолчанию 5 минут, что соответствует скорости миграции, выполняемой специалистом Postgres Pro. Для первой миграции установите значение 10.
--dump_as_htmlВыгружать отчёт в формате HTML. Параметр используется только с
SHOW_REPORT. По умолчанию отчёт выгружается в формате простого текста.--dump_as_csvАналогично предыдущему, но отчёт выгружается в формате CSV.
--dump_as_sheetВыводить отчёт по оценке миграции с отдельной строкой в формате CSV для каждой БД.
--init_projectИнициализировать стандартное дерево проекта ora2pgpro. Каталог верхнего уровня создаётся в базовом каталоге проекта.
--project_baseУказать базовый каталог для деревьев проекта ora2pgpro. По умолчанию это текущий каталог.
--print_headerВыводить заголовок CSV, что особенно полезно при первом запуске ora2pgpro. Параметр используется вместе с параметром
--dump_as_sheet.--human_days_limitЗадать предел человеко-дней, по достижении которого уровень оценки миграции меняется с B на C. По умолчанию 5 человеко-дней.
--audit_userУказать список имён пользователей для фильтрации запросов в таблице
AUDIT_USER. Используется только с типами экспортаSHOW_REPORTиQUERY.--pg_dsnУказать источник данных для прямого импорта в Postgres Pro.
--pg_userУказать пользователя Postgres Pro.
--pg_pwdУказать пароль пользователя Postgres Pro.
--count_rowsПринудительно подсчитывать действительное количество строк при выполнении
TEST,TEST_COUNTиSHOW_TABLE.--no_headerНе выводить заголовок ora2pgpro в выходной файл.
--oracle_speedУзнать скорость, с которой могут передаваться данные из Oracle. Данные не обрабатываются и не записываются.
--ora2pg_speedУзнать скорость, с которой ora2pgpro может отправлять преобразованные данные. Данные не записываются.
--blob_to_loЭкспортировать BLOB в виде больших объектов. Параметр может использоваться только при выполнении
SHOW_COLUMN,TABLEиINSERT.--cdc_readyИспользовать текущие SCN для экспорта данных из таблиц и записать их в файл под названием
TABLES_SCN.logпо умолчанию. Другое имя файла можно указать, используя параметр-C|--cdc_file.--lo_importИспользовать команду psql \lo_import для импорта BLOB в виде больших объектов. Параметр можно использовать для импорта с типом
COPYи последующим импортом большого объекта вручную. Необходим для импорта BLOB размером более 1 ГБ.--mview_as_tableУказать список материализованных представлений, разделённых запятыми, для экспорта в виде обычных таблиц.
--drop_if_existsУдалить объект перед созданием, если он уже существует.
В случае успеха ora2pgpro возвращает 0, а в случае ошибки 1. Если дочерний процесс прерывается, возвращается 2 и выводится следующее предупреждение: «WARNING: an error occurs during data export. Please check what's happen.» (ПРЕДУПРЕЖДЕНИЕ: Во время экспорта данных произошла ошибка. Обратите внимание.) В большинстве случаев ошибка вызвана нехваткой памяти — попробуйте уменьшить значение DATA_LIMIT.
Обратите внимание, что производительность можно увеличить, обновив статистику в Oracle:
DBMS_STATS.GATHER_SCHEMA_STATS DBMS_STATS.GATHER_DATABASE_STATS DBMS_STATS.GATHER_DICTIONARY_STATS
Если заданы параметры --project_base и --init_project, ora2pgpro создаёт шаблон проекта, содержащий дерево проекта, файл конфигурации и скрипт для экспорта всех объектов из БД Oracle. Пример использования команды:
ora2pgpro --project_base /app/migration/ --init_project test_project Creating project test_project. /app/migration/test_project/ schema/ dblinks/ directories/ functions/ grants/ mviews/ packages/ partitions/ procedures/ sequences/ synonyms/ tables/ tablespaces/ triggers/ types/ views/ sources/ functions/ mviews/ packages/ partitions/ procedures/ triggers/ types/ views/ data/ config/ reports/ Generating generic configuration file Creating script export_schema.sh to automate all exports. Creating script import_all.sh to automate all imports.
При этом создаётся стандартный файл конфигурации, в котором можно задать параметры подключения к БД Oracle, и скрипт оболочки export_schema.sh. Каталог sources/ будет содержать код Oracle, каталог schema/ — код для портирования в Postgres Pro. Каталог reports/ будет содержать HTML-отчёты с оценкой стоимости миграции.
Если вы хотите использовать собственный файл конфигурации, укажите путь к нему в параметре -c. Допишите к имени файла суффикс .dist, чтобы добавить в него стандартные параметры конфигурации ora2pgpro, в противном случае файл будет копирован в исходном состоянии.
После установки подключения к БД Oracle можно выполнить скрипт export_schema.sh, чтобы экспортировать все типы объектов из БД Oracle и вывести файлы DDL в подкаталоги схемы. По завершении процесса, когда импортируемая схема будет проверена, будет выдана команда для последующего экспорта данных.
Можно загрузить созданные файлы DDL вручную или воспользоваться скриптом import_all.sh, чтобы импортировать файлы интерактивно. Если миграция не выполняется сразу, рекомендуется использовать эти скрипты.
Следующие директивы управляют доступом к БД Oracle.
ORACLE_HOMEЗадаёт переменную окружения
ORACLE_HOMEдля библиотек Oracle, используемых модулем PerlDBD::Oracle.ORACLE_DSNЗадаёт имя источника данных в формате DBI DSN. Например:
dbi:Oracle:host=oradb_host.myhost.com;sid=DB_SID;port=1521
или
dbi:Oracle:DB_SID
Пример для 18c:
dbi:Oracle:host=192.168.1.29;service_name=pdb1;port=1521
Для использования второй нотации необходимо объявить SID в файле
$ORACLE_HOME/network/admin/tnsnames.oraили в пути, указанном в переменной окруженияTNS_ADMIN.ORACLE_DSNORACLE_PWDЗадают имя пользователя и пароль для подключения к БД Oracle. Обратите внимание, что лучше входить в систему с правами суперпользователя Oracle во избежание проблем доступа во время сканирования базы данных и пропуска данных.
Если не задать пароль в
ORACLE_PWDи установить Perl-модульTerm::ReadKey, ora2pgpro запросит пароль интерактивно. Если имя пользователя не задано вORACLE_USER, его тоже нужно будет задать интерактивно.Чтобы подключиться к локальному экземпляру Oracle с правами
SYSDBA, необходимо задать дляORACLE_USERзначение/и пустой пароль.USER_GRANTSЗадайте для этого параметра значение 1, если вы подключаетесь к БД Oracle как простой пользователь без права извлекать данные из таблиц
DBA_. Будут использоваться таблицыALL_.Предупреждение: при использовании типа экспорта
GRANTнеобходимо задать для этого параметра значение 0, в противном случае он работать не будет.TRANSACTIONЭту директиву можно использовать, чтобы изменить уровень изоляции по умолчанию для экспортируемых транзакций. По умолчанию задаётся сериализуемый уровень изоляции для сохранения целостности данных. Допустимые значения директивы
- readonly: 'SET TRANSACTION READ ONLY',
- readwrite: 'SET TRANSACTION READ WRITE',
- serializable: 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE'
- committed: 'SET TRANSACTION ISOLATION LEVEL READ COMMITTED',
ORA_INITIAL_COMMANDЭту директиву можно использовать для отправки начальных команд в Oracle сразу после подключения, например, чтобы разблокировать политику для чтения объектов или установить параметры сеанса. Директиву можно задавать несколько раз.
Если файл конфигурации клиента Oracle уже содержит метод шифрования, DBD:Oracle использует эти параметры для шифрования соединения во время извлечения данных. Например, файл конфигурации клиента Oracle (sqlnet.or или .sqlnet) содержит следующую информацию:
# Настройка шифрования подключений к Oracle SQLNET.ENCRYPTION_CLIENT = required SQLNET.ENCRYPTION_TYPES_CLIENT = (AES256, RC4_256) SQLNET.CRYPTO_SEED = '7-10 случайных символов'
Любая утилита, использующая клиент Oracle для взаимодействия с базой данных, будет защищена шифрованием, если настроить шифрование сеанса вышеописанным способом.
Например, Perl DBI использует DBD-Oracle, который в свою очередь использует клиент Oracle для взаимодействия с базой данных. Если при установке клиента Oracle, используемого Perl, было настроено требование зашифрованных соединений, то и соединение Perl с БД Oracle будет зашифровано.
После установки DSN БД Oracle можно запустить утилиту ora2pgpro, чтобы проверить, работает ли она:
ora2pgpro -t SHOW_VERSION -c config/ora2pgpro.conf
Эта команда выведет версию сервера БД Oracle. Кроме того, можно проверить правильность установки, поскольку большинство проблем возникает именно на этом этапе настройки, остальные этапы являются более техническими.
Если файл output.sql не содержит ничего, кроме заголовка и нижнего колонтитула транзакции Postgres Pro, возможны следующие причины:
Perl-скрипт ora2pgpro выдаёт ошибку
ORA-XXX— это означает, что указан некорректный DSN или данные для входа в систему. Проверьте сообщение об ошибке и указанную информацию и попробуйте снова.Perl-скрипт ничего не выдаёт, а выходной файл пустой — пользователь не имеет доступа к данным из базы. Попробуйте подключиться к Oracle с правами суперпользователя или используйте
USER_GRANTSвыше или директивы из следующего раздела, в частностиSCHEMA.
Можно ограничить экспорт БД Oracle отдельной схемой или пространством имён вручную. Если для подключения указан пользователь с ограниченными правами, только соответствующие объекты будут выгружены.
SCHEMAДиректива используется для указания имени схемы, используемой во время экспорта. Например, с указанием
SCHEMA APPSбудут выгружены объекты, связанные со схемойAPPS.Если включить
EXPORT_SCHEMAи не задать имя схемы, ora2pgpro экспортирует все объекты из всех схем экземпляра Oracle, добавляя к именам объектов имя схемы в виде префикса.EXPORT_SCHEMAПо умолчанию схема Oracle не экспортируется в БД Postgres Pro, а все объекты создаются в пространстве имён Postgres Pro по умолчанию. Если необходимо и экспортировать схему, и создать все объекты в этом пространстве имён, задайте для
EXPORT_SCHEMAзначение 1. При этом в пути к схеме (search_path) в начале SQL-файла для экспорта будет записана схема, указанная в директивеSCHEMA(по умолчаниюpg_catalog). Если вы хотите изменить путь, используйте директивуPG_SCHEMA.CREATE_SCHEMAДиректива включает/отключает команду CREATE SCHEMA в начале выходного файла. По умолчанию включена, используется с типом экспорта
TABLE.COMPILE_SCHEMAПо умолчанию ora2pgpro экспортирует только рабочий код PL/SQL. Можно перекомпилировать нерабочий код в Oracle, чтобы добиться корректности и в дальнейшем экспортировать его.
Чтобы схема компилировалась в Oracle перед экспортом кода, включите эту директиву. В этом случае, если
При этом в Oracle отправится запрос на перекомпиляцию кода PL/SQL, который мог стать нерабочим, например, после экспорта/импорта. В результате для функций, процедур, пакетов и пользовательских типов проставляется статус
VALIDилиINVALID. Кроме того, это распространяется на отключённые триггеры.EXPORT_INVALIDЕсли предыдущей директивы недостаточно для проверки корректности кода PL/SQL, включите эту директиву, чтобы разрешить экспорт всего кода PL/SQL, даже если он помечен как нерабочий. В результате для функций, процедур, пакетов и пользовательских типов проставляется статус
VALIDилиINVALID.PG_SCHEMAПозволяет указать / принудительно использовать схему Postgres Pro. По умолчанию, если для
EXPORT_SCHEMAзадано значение 1, для параметраsearch_pathв Postgres Pro будет задано имя схемы, указанной вSCHEMA.Значением может быть список имён схем, разделённых запятыми, но не с типом экспорта
TABLE, потому что в этом случае создаётся оператор CREATE SCHEMA, не поддерживающий несколько имён схем. Например, если дляPG_SCHEMAуказатьuser_schema, public, путь поиска задаётся следующим образом:SET search_path = user_schema, public;
В этом случае используется схема (здесь
user_schema), отличная от схемы Oracle, которая указана в директивеSCHEMA.Кроме того, для пользователя Postgres Pro, под именем которого вы подключаетесь к целевой базе данных, можно задать значение
search_pathпо умолчанию следующим образом:ALTER ROLE username SET search_path TO user_schema, public;
Тогда задавать
PG_SCHEMAне понадобится.SYSUSERSЕсли не задать схему явным образом, ora2pgpro экспортирует все объекты, не принадлежащие системной схеме или роли:
SYSTEM,CTXSYS,DBSNMP,EXFSYS,LBACSYS,MDSYS,MGMT_VIEW, OLAPSYS,ORDDATA,OWBSYS,ORDPLUGINS,ORDSYS,OUTLN, SI_INFORMTN_SCHEMA,SYS,SYSMAN,WK_TEST,WKSYS,WKPROXY, WMSYS,XDB,APEX_PUBLIC_USER,DIP,FLOWS_020100,FLOWS_030000, FLOWS_040100,FLOWS_010600,FLOWS_FILES,MDDATA,ORACLE_OCM, SPATIAL_CSW_ADMIN_USR,SPATIAL_WFS_ADMIN_USR,XS$NULL,PERFSTAT, SQLTXPLAIN,DMSYS,TSMSYS,WKSYS,APEX_040000,APEX_040200, DVSYS,OJVMSYS,GSMADMIN_INTERNAL,APPQOSSYS,DVSYS,DVF, AUDSYS,APEX_030200,MGMT_VIEW,ODM,ODM_MTR,TRACESRV,MTMSYS, OWBSYS_AUDIT,WEBSYS,WK_PROXY,OSE$HTTP$ADMIN, AURORA$JIS$UTILITY$,AURORA$ORB$UNAUTHENTICATED, DBMS_PRIVILEGE_CAPTURE,CSMIG,MGDSYS,SDE,DBSFWUSER
В зависимости от инсталляции Oracle, могут быть определены несколько системных ролей. Чтобы добавить этих пользователей в список исключений схемы, укажите их через запятую в директиве
SYSUSERS. Например:SYSUSERS INTERNAL,SYSDBA,BI,HR,IX,OE,PM,SH
В результате пользователи
INTERNALиSYSDBAбудут добавлены в список исключений.FORCE_OWNERПо умолчанию владельцем объектов БД будет пользователь, используемый для подключения к БД Postgres Pro в psql. Если используется другой пользователь (например,
postgres), можно указать ora2pgpro назначать владельцем объектов пользователя, используемого в БД Oracle, задав для этой директивы значение 1. Если в значении указать имя пользователя, он и будет назначен владельцем.FORCE_SECURITY_INVOKERДля экспорта функций ora2pgpro использует права из Oracle (чаще всего
SECURITY DEFINER). Включите эту директиву, если необходимо переопределить права для всех функций наSECURITY INVOKER.USE_TABLESPACEКогда директива включена, ora2pgpro экспортирует все таблицы, ограничения и индексы, используя имя пространства имён, указанное в БД Oracle. Не работает с пространствами имён
TEMP,USERSиSYSTEM.WITH_OIDКогда директива включена, при создании таблиц или представлений как таблиц ora2pgpro добавляет указание
WITH OIDS. По умолчанию отключена, как и в Postgres Pro.LOOK_FORWARD_FUNCTIONСписок схем, из которых извлекаются метаданные о функциях/процедурах, используемые в экспорте схем. Если при замене вызова функции с параметрами
OUTэта функция объявлена в другом пакете, вызов не может быть перезаписан, поскольку ora2pgpro знает только про функции, объявленные в текущей схеме. Если задать в этой директиве список схем, разделённых запятыми, ora2pgpro будет выполнять поиск всех функций, процедур и объявлений пакетов по всем пакетам перед тем, как начать экспорт текущей схемы.NO_FUNCTION_METADATAОтключает поиск объявления функции для ora2pgpro. Обратите внимание, что при этом ora2pgpro не будет перезаписывать вызов функции. Включайте эту директиву, только если поиск функции нарушает экспорт.
Директива TYPE определяет выполняемые во время экспорта действия, другие директивы позволяют только уточнить детали экспорта.
TYPEДля директивы
TYPEможно задать следующие значения (по умолчаниюTABLE):TABLE: извлекать все таблицы с индексами, первичными ключами, ограничениями уникальности, внешними ключами и ограничениями-проверками.VIEW: извлекать только представления.GRANT: извлекать роли, преобразуемые в группы Postgres Pro, пользователей и права для все объектов.SEQUENCE: извлекать все последовательности и их текущие значения.TABLESPACE: извлекать пространства для таблиц и индексов.TRIGGER: извлекать событийные триггеры.FUNCTION: извлекать функции.PROCEDURE: извлекать процедуры.PACKAGE: извлекать пакеты и тела пакетов.INSERT: извлекать данные через оператор INSERT.COPY: извлекать данные через оператор COPY.PARTITION: извлекать секции по диапазонам и спискам с подсекциями.TYPE: извлекать пользовательские типы Oracle.FDW: извлекать таблицы Oracle как сторонние таблицы для oracle_fdw.MVIEW: эскпортировать материализованные представления.QUERY: автоматически преобразовывать SQL-запросы Oracle.DBLINK: создать сервер обёртки сторонних данных Oracle, чтобы использовать его какdblink.SYNONYM: экспортировать синонимы Oracle как представления на базе других объектов схемы.DIRECTORY: экспортировать каталоги Oracle как объекты расширенияexternal_file.LOAD: отправлять набор запросов с использованием нескольких соединений с Postgres Pro.TEST: выполнить сравнение БД Oracle и Postgres Pro.TEST_COUNT: выполнить сравнение количества строк в таблицах Oracle и Postgres Pro.TEST_VIEW: подсчитать число строк, возвращаемых представлениями на обеих сторонах.TEST_DATA: выполнить проверку корректности строк на обеих сторонах.SHOW_VERSION: показать версию Oracle.SHOW_SCHEMA: вывести список доступных схем.SHOW_TABLE: вывести список доступных таблиц.SHOW_COLUMN: вывести список доступных столбцов таблиц и тип, используемый ora2pgpro при преобразовании из Oracle в Postgres Pro. Кроме того, выводится предупреждение, если в именах объектов Oracle есть зарезервированные слова Postgres Pro.SHOW_REPORT: вывести подробный отчёт о содержимом БД Oracle для оценки размера объектов и стоимости миграции.
Только один тип экспорта можно выполнить за один раз, поэтому директива
TYPEдолжна быть уникальной. Если указать директиву несколько раз, будет использоваться последнее обнаруженное значение.Результаты экспорта некоторых типов невозможно или не следует загружать в БД Postgres Pro напрямую — требуются дополнительные действия вручную. Это относится к типам экспорта
GRANT,TABLESPACE,TRIGGER,FUNCTION,PROCEDURE,TYPE,QUERYиPACKAGE, особенно если есть код PL/SQL или SQL, специфичный для Oracle.Для типа экспорта
TABLESPACEв системе должен существовать путь к файлу, а дляSYNONYM— владельцы объектов и схемы должны соответствовать новому проекту БД Postgres Pro.Обратите внимание, что можно запустить серию операций экспорта, указав в директиве
TYPEсписок типов, разделённых запятыми, но типыCOPYиINSERTс другими типами указывать нельзя.ora2pgpro преобразовывает секции Oracle, используя наследование, триггеры и функции. За дополнительной информацией обратитесь к разделу Секционирование таблиц.
Директива
TYPEпозволяет экспортировать пользовательские типы Oracle. Если не использовать параметр--plsqlв командной строке, пользовательский тип Oracle выгружается как есть, в противном случае ora2pgpro попробует преобразовать его с использованием синтаксиса Postgres Pro.Пример вывода с использованием
SHOW_COLUMN:[2] TABLE CURRENT_SCHEMA (1 rows) (Warning: 'CURRENT_SCHEMA' is a reserved word in PostgreSQL) CONSTRAINT : NUMBER(22) => bigint (Warning: 'CONSTRAINT' is a reserved word in PostgreSQL) FREEZE : VARCHAR2(25) => varchar(25) (Warning: 'FREEZE' is a reserved word in PostgreSQL) ... [6] TABLE LOCATIONS (23 rows) LOCATION_ID : NUMBER(4) => smallint STREET_ADDRESS : VARCHAR2(40) => varchar(40) POSTAL_CODE : VARCHAR2(12) => varchar(12) CITY : VARCHAR2(30) => varchar(30) STATE_PROVINCE : VARCHAR2(25) => varchar(25) COUNTRY_ID : CHAR(2) => char(2)
Нижеописанные ключевые слова только показывают запрошенную информацию и прерывают выполнение. Это позволяет узнать, с чем предстоит работать.
С типом
SHOW_COLUMNв командной строке разрешается передавать параметры ora2pgpro--allow relnameили-a relname, чтобы ограничить выводимую информацию одной таблицей.С типом
SHOW_ENCODINGотображаются значенияNLS_LANGиCLIENT_ENCODING, которые будет использовать ora2pgpro, и фактическая кодировка БД Oracle с соответствующей кодировкой клиента, которая будет использоваться в Postgres Pro.ora2pgpro может экспортировать определение таблицы Oracle для использования через обёртку сторонних данных oracle_fdw. Если задать тип
FDW, таблицы Oracle экспортируются следующим образом:CREATE FOREIGN TABLE oratab ( id integer NOT NULL, text character varying(30), floating double precision NOT NULL ) SERVER oradb OPTIONS (table 'ORATAB');
Теперь таблицу можно использовать как обычную таблицу Postgres Pro.
Также можно вывести более подробный отчёт с информацией о стоимости миграции, подробнее см. «Оценка стоимости миграции».
ESTIMATE_COSTАктивирует оценку стоимости миграции. Используется только с типами экспорта
SHOW_REPORT,FUNCTION,PROCEDURE,PACKAGEиQUERY. По умолчанию отключена. Эта же функциональность включается с помощью параметра--estimate_costкомандной строки. Обратите внимание, что включение этой директивы активируетPLSQL_PGSQL.COST_UNIT_VALUEЗадаёт значение в минутах для блока оценки стоимости миграции. По умолчанию 5 минут на блок. Чтобы поменять значение в командной строке, используйте
--cost_unit_value.DUMP_AS_HTMLЕсли включить эту директиву, ora2pgpro выведет отчёт о миграции в формате HTML. По умолчанию при использовании
SHOW_REPORTотчёт выводится в формате простого текста.HUMAN_DAYS_LIMITИспользуйте эту директиву, чтобы переопределить предел человеко-дней, по достижении которого уровень оценки миграции меняется с B на C. По умолчанию 10 человеко-дней.
JOBSЭта директива включает поддержку многопоточности для типов экспорта
COPY,FUNCTIONиPROCEDUREи задаёт число используемых процессов. По умолчанию многопоточность отключена.Эта директива используется, чтобы указать число ядер для параллельного импорта данных в Postgres Pro. С типом экспорта
FUNCTIONилиPROCEDUREкаждая функция будет переведена в PL/pgSQL в новом отдельном процессе, что может дать значительное ускорение при большом количестве функций.Параллельная обработка ограничивается только числом ядер и производительностью ввода-вывода Postgres Pro.
Не работает с ОС Windows, директива отключена.
ORACLE_COPIESЭта директива включает поддержку многопоточности для извлечения данных из Oracle. Значением является число процессов для параллельного выполнения запроса. По умолчанию параллельность запросов отключена.
Параллельность построена на разделение запроса по числу ядер, переданному в качестве значения
ORACLE_COPIES:SELECT * FROM MYTABLE WHERE ABS(MOD(COLUMN, ORACLE_COPIES)) = CUR_PROC
Здесь
COLUMN— это технический ключ, такой как первичный ключ или уникальный ключ, на основе которого осуществляется разделение и используется текущее ядро (CUR_PROC). В директивеDEFINED_PKможно задать имя используемого столбца.Не работает с ОС Windows, директива отключена.
DEFINED_PKЭта директива используется, чтобы определить технический ключ, используемый для разделения запроса по числу ядер, которое задано в переменной
ORACLE_COPIES. Например:DEFINED_PK EMPLOYEES:employee_id
Предположим, что в
-JилиORACLE_COPIESзадано значение 8, используется параллельный запрос:SELECT * FROM EMPLOYEES WHERE ABS(MOD(employee_id, 8)) = N
Здесь N — это текущий дочерний процесс (начиная с 0).
PARALLEL_TABLESЭта директива используется, чтобы задать число таблиц, обрабатываемых параллельно для извлечения данных. Пределом является число ядер на машине. ora2pgpro устанавливает по одному подключению к БД для каждого параллельного процесса. Если значение этой директивы больше 1,
ORACLE_COPIESотключается, ноJOBSиспользуется, так что фактическое число процессов =PARALLEL_TABLES*JOBS.Обратите внимание, что если значение этой директивы больше 1, при экспорте в файлы автоматически активируется
FILE_PER_TABLE, чтобы экспортировать таблицы и представления в разные файлы.Используйте
PARALLEL_TABLES, чтобы включить параллельность для действийCOPY,INSERTиTEST_DATA. Также полезно дляTEST,TEST_COUNTиSHOW_TABLE, если--count_rowsиспользуется для подсчёта действительного количества строк.DEFAULT_PARALLELISM_DEGREEЕсли задать для этой директивы значение больше 1, ora2pgpro будет принудительно использовать указание
/*+ PARALLEL(tbname, degree) */в каждом запросе экспорта данных из Oracle. Значение 0 или 1 отключает использование указаний для параллельности. По умолчанию отключена.FDW_SERVERЭта директива используется, чтобы указывать имя сервера сторонних данных для команды CREATE SERVER name FOREIGN DATA WRAPPER oracle_fdw. Затем это имя используется в командах CREATE FOREIGN TABLE и в импорте данных с помощью oracle_fdw. По умолчанию сторонний сервер не определён. Директива используется с типами экспорта
FDW,COPYиINSERT. Для типа экспортаFDWзначение по умолчанию —orcl.FDW_IMPORT_SCHEMAСхема, в которой будут созданы сторонние таблицы для миграции данных. Если для миграции данных используются несколько экземпляров ora2pgpro с использованием обёртки сторонних данных, может потребоваться изменять имя схемы для отдельных экземпляров. По умолчанию
ora2pg_fdw_import.DROP_FOREIGN_SCHEMAПо умолчанию перед каждым новым импортом ora2pgpro удаляет временную схему
ora2pg_fdw_import, используемую для импорта сторонней схемы Oracle. Отключите директиву, если необходимо сохранить существующую схему из-за внесённых изменений или использования стороннего сервера.EXTERNAL_TO_FDWЭта директива (по умолчанию включена) позволяет экспортировать сторонние таблицы Oracle как сторонние таблицы file_fdw. Чтобы не экспортировать такие таблицы, задайте значение 0.
INTERNAL_DATE_MAXВнутренние отметки времени, получаемые из пользовательских типов, извлекаются в следующем формате:
01-JAN-77 12.00.00.000000 AM. Поскольку точное столетие неизвестно, по умолчанию каждый год меньше 49 относится к 2000, а остальные — к 1900. Эта директива используется, чтобы изменить значение по умолчанию 49. Директива имеет смысл, только если есть пользовательский тип со столбцом timestamp.AUDIT_USERЗадаёт список разделённых запятыми имён пользователей для фильтрации запросов к таблице
DBA_AUDIT_TRAIL. По умолчанию эта таблица не сканируется, и поиск запросов не выполняется. Директива используется только с типами экспортаSHOW_REPORTиQUERY, когда не указан файл с запросами. Обратите внимание, что перед выводом выполняется нормализация текста запроса, в отличие от случаев, когда передаётся входной файл в параметре-i.FUNCTION_CHECKОтключите эту директиву, чтобы отключить
check_function_bodies.SET check_function_bodies = false;
При этом отключается проверка корректности строки с телом функции, передаваемой команде CREATE FUNCTION. По умолчанию используется параметр из
postgresql.conf, включающий эту функциональность.ENABLE_BLOB_EXPORTЭкспорт BLOB занимает время, поэтому иногда может потребоваться экспортировать все данные, кроме BLOB. В этом случае отключите эту директиву, и столбцы типа BLOB будут исключены из экспорта. Обратите внимание, что у целевого столбца типа bytea не должно быть ограничения
NOT NULL.DATA_EXPORT_ORDERПо умолчанию экспорт данных выполняется в порядке имён таблиц. Если в базе есть огромные таблицы с именами в конце алфавита, при использовании многопоточности может быть полезно настроить сортировку по размеру, чтобы множество небольших таблиц были обработаны до того, как завершится обработка самых больших таблиц. В этом случае задайте для этой директивы значение
size. Возможные значения:nameиsize. Обратите внимание, что с типами экспортаSHOW_TABLEиSHOW_COLUMNтоже можно использовать сортировку, не только сCOPYилиINSERT.
Иногда может потребоваться экспортировать только часть БД Oracle. Нижеописанные директивы позволяют ограничить экспорт отдельными объектами БД.
ALLOWЭта директива позволяет задать список объектов, которые необходимо экспортировать, исключив все остальные объекты. Значением является список имён объектов, разделённых запятыми. В список можно добавлять регулярные выражения. Например:
ALLOW EMPLOYEES SALE_.* COUNTRIES .*_GEOM_SEQ
С таким значением будут экспортированы объекты с именами
EMPLOYEES,COUNTRIES, а также с именами, начинающимися наSALE_, и именами, заканчивающимися на_GEOM_SEQ. Типы объектов зависят от типа экспорта. Обратите внимание, что регулярные выражения не сработают в БД 8i, вместо них надо использовать местозаполнители%, чтобы утилита ora2pgpro использовала операторLIKE.Так задаются глобальные фильтры для текущего типа экспорта. Можно также задавать расширенные фильтры, применяемые к определённым объектам или для соответствующего типа экспорта. Например:
ora2pgpro -p -c ora2pgpro.conf -t TRIGGER -a 'TABLE[employees]'
При этом будут экспортироваться только триггеры для таблицы
employees. Если нужны все триггеры, кроме некоторыхINSTEAD OF:ora2pgpro -c ora2pgpro.conf -t TRIGGER -e 'VIEW[trg_view_.*]'
Или в более сложном виде:
ora2pgpro -p -c ora2pgpro.conf -t TABLE -a 'TABLE[EMPLOYEES]' \ -e 'INDEX[emp_.*];CKEY[emp_salary_min]'Эта команда экспортирует определение таблицы
employees, но без индексов, начинающихся сemp_, и ограниченияCHECKс именемemp_salary_min.При эскпорте секций можно исключить секционированные таблицы с помощью следующей команды:
ora2pgpro -p -c ora2pgpro.conf -t PARTITION -e 'PARTITION[PART_199.* PART_198.*]'
При этом из экспорта будут исключены секции для лет с 1980 по 1999, но не основная таблица. Кроме того, будут исключены соответствующие триггеры.
С типом экспорта
GRANTможно использовать такой расширенный формат, чтобы исключить пользователей из экспорта или ограничить отдельными пользователями:ora2pgpro -p -c ora2pgpro.conf -t GRANT -a 'USER1 USER2' or ora2pgpro -p -c ora2pgpro.conf -t GRANT -a 'GRANT[USER1 USER2]'
Последняя команда ограничит экспорт пользователями
USER1иUSER2. Если же нет необходимости экспортировать права этих пользователей на определённые функции, можно использовать, например:ora2pgpro -p -c ora2pgpro.conf -t GRANT -a 'USER1 USER2' -e 'FUNCTION[adm_.*];PROCEDURE[adm_.*]'
Oracle не допускает использование выражений с предварительным просмотром, поэтому может потребоваться исключить из экспорта некоторые объекты, соответствующие заданному в
ALLOWрегулярному выражению. Например, если необходимо экспортировать все таблицы, начинающиеся наE, но исключить начинающиеся наEXP, отфильтровать таблицы одним выражением невозможно. Поэтому можно начать регулярное выражением с символа!, чтобы исключить объекты, соответствующие следующему регулярному выражению. Предыдущий пример можно записать следующим образом:ALLOW E.* !EXP.*
В выражении поиска объекта это будет выглядеть следующим образом:
REGEXP_LIKE(..., '^E.*$') AND NOT REGEXP_LIKE(..., '^EXP.*$')
EXCLUDEЭта директива противоположна предыдущей — она позволяет задавать список разделённых пробелами или запятыми имён объектов, которые исключаются из экспорта. В списке можно указать регулярное выражение. Например:
EXCLUDE EMPLOYEES TMP_.* COUNTRIES
При этом из экспорта будут исключены объекты с именами
EMPLOYEES,COUNTRIESи все таблицы, начинающиеся наtmp_.Например, с помощью этой директивы можно исключить ненужные функции:
EXCLUDE write_to_.* send_mail_.*
В вышеприведённом примере из экспорта исключаются все функции, процедуры или функции из пакетов с именами, начинающимися как задано регулярным выражением. Обратите внимание, что регулярные выражения не сработают в БД 8i, вместо них надо использовать местозаполнители
%, чтобы утилита ora2pgpro использовала операторNOT LIKE. Расширенный синтаксис описан выше (см. директивуALLOW).NO_EXCLUDED_TABLEПо умолчанию ora2pgpro исключает из экспорта «мусорные» таблицы Oracle, которые никогда не должны включаться. При этом создаётся множество выражений
REGEXP_LIKE, что замедляет анализ таблиц при экспорте. Чтобы отключить это поведение, включите данную директиву, но ненужные таблицы придётся впоследствии исключать или удалять вручную. Регулярные выражения для исключения таблиц задаются в массиве@EXCLUDED_TABLESвlib/Ora2Pgpro.pm. Обратите внимание, что это поведение не зависит от директивыEXCLUDE.VIEW_AS_TABLEЗадаёт представления для экспорта как таблицы. По умолчанию никакие. В значении указывается регулярное выражение или список имён представлений, разделённых пробелами или запятыми. Если имя объекта — это представление и задан тип экспорта
TABLE, представление экспортируется как оператор CREATE TABLE. С типом экспортаCOPYилиINSERTсоответствующие данные экспортируются. За подробным описанием обратитесь к разделу Экспорт представлений как таблиц Postgres Pro.MVIEW_AS_TABLEЗадаёт материализованные представления для экспорта как таблицы. По умолчанию никакие. В значении указывается регулярное выражение или список имён материализованных представлений, разделённых пробелами или запятыми. Если имя объекта — это материализованное представление и задан тип экспорта
TABLE, представление экспортируется как оператор CREATE TABLE. С типом экспортаCOPYилиINSERTсоответствующие данные экспортируются.NO_VIEW_ORDERINGПо умолчанию ora2pgpro пытается упорядочить представления во избежание ошибок со вложенными представлениями во время импорта. Если представлений очень много, это может занять много времени, поэтому можно отключить упорядочивание, задав эту директиву.
GRANT_OBJECTМожно задать список разделённых запятыми объектов, права для которых экспортируются. По умолчанию права экспортируются для всех объектов. Возможные значения:
TABLE,VIEW,MATERIALIZED VIEW,SEQUENCE,PROCEDURE,FUNCTION,PACKAGE BODY,TYPE,SYNONYM,DIRECTORY. Разрешается указывать только один тип объектов. Например, для экспорта прав только для таблиц задайте значениеTABLE. Значение можно переопределить параметром-g.WHEREЭта директива позволяет задавать фильтр по предложению
WHEREпри выгрузке содержимого таблиц. Значение задаётся в форматеTABLE_NAME[WHERE_CLAUSE]или только предложениеWHEREпри наличии только одного такого предложения на каждую таблицу. Можно задавать оба варианта одновременно. Примеры:# Глобальное предложение
WHEREприменяется ко всем таблицам в экспорте WHERE 1=1 # ПредложениеWHEREтолько для таблицы TABLE_NAME WHERE TABLE_NAME[ID1='001'] # Два разных предложения для таблиц TABLE_NAME и OTHER_TABLE # и общее предложениеWHEREпо DATE_CREATE для всех остальных таблиц WHERE TABLE_NAME[ID1='001' OR ID1='002] DATE_CREATE > '2001-01-01' OTHER_TABLE[NAME='test']Если предложение
WHEREуказывается не в скобках с именем таблицы, оно применяется для всех экспортируемых таблиц, включая таблицы, указанные в предложенииWHERE. ПредложенияWHEREполезны, если необходимо обратиться к архивным данным или, наоборот, недавно созданным.Чтобы быстро протестировать импорт данных, удобно ограничить экспорт данных первой тысячей кортежей из каждой таблицы. Для Oracle укажите следующее предложение:
WHERE ROWNUM < 1000
Также директиву можно использовать, чтобы ограничить экспорт несколькими таблицами.
Параметр
-Wили--where, передаваемый в командной строке, переопределит значение этой директивы глобально и для отдельных таблиц, если имена таблиц совпадают.TOP_MAXЭта директива используется, чтобы ограничить количество элементов, отображаемых в начале списков объектов с наибольшими характеристиками, например в списке таблиц с наибольшим количеством и списке самых больших таблиц по мегабайтам. По умолчанию 10 элементов.
LOG_ON_ERRORВключите эту директиву, если хотите продолжать импорт данных в случае ошибки. Когда ora2pgpro получает ошибку в операторах COPY или INSERT в Postgres Pro, этот оператор записывается в файл журнала
TABLENAME_error.logв выходном каталоге, и работа продолжается. Можно попробовать корректировать оператор и вручную перезагрузить файл журнала ошибок. По умолчанию импорт прерывается при ошибке.REPLACE_QUERYИногда может потребоваться извлечь данные из таблицы Oracle, но для этого нужен отдельный запрос — не простой запрос SELECT * FROM table от ora2pgpro, а более сложный. Эта директива позволяет переопределить запрос, используемый ora2pgpro для извлечения данных. Формат запроса:
TABLENAME[SQL_QUERY]. Если таблиц много, с заменой запроса ora2pgpro можно указать несколько строкREPLACE_QUERY.REPLACE_QUERY EMPLOYEES[SELECT e.id,e.fisrtname,lastname FROM EMPLOYEES e JOIN EMP_UPDT u ON (e.id=u.id AND u.cdate>'2014-08-01 00:00:00')]
Для управления экспортом индексов для полнотекстового поиска в ora2pgpro предусмотрено несколько директив. По умолчанию индексы CONTEXT экспортируются в Postgres Pro как индексы FTS, а индексы CTXCAT экспортируются с использованием расширения pg_trgm.
CONTEXT_AS_TRGMПринудительно переводит полнотекстовые индексы Oracle в индексы Postgres Pro с использованием расширения pg_trgm. По умолчанию индексы
CONTEXTпереводятся в индексыFTS, а индексыCTXCAT— с использованием расширения pg_trgm. Эта директива позволяет использовать pg_trgm, чего достаточно в большинстве случаев. Перед импортом объектов необходимо создать расширение pg_trgm в целевой базе данных.FTS_INDEX_ONLYПо умолчанию ora2pgpro создаёт индекс на основе функции, чтобы перенести полнотекстовые индексы Oracle.
CREATE INDEX ON t_document USING gin(to_tsvector('pg_catalog.french', title));Необходимо переписать предложение
CONTAIN()с использованиемto_tsvector(), например:SELECT id,title FROM t_document WHERE to_tsvector(title) @@ to_tsquery('search_word');Отключите эту директиву, чтобы утилита ora2pgpro создавала дополнительный столбец типа tsvector с выделенными триггерами для индексов
FTS. В этом случае ora2pgpro добавляет столбец следующим образом:ALTER TABLE t_document ADD COLUMN tsv_title tsvector;
Затем столбец обновляется для вычисления векторов
FTS, если данные были загружены до команды UPDATE t_document SET tsv_title = to_tsvector('pg_catalog.french', coalesce(title,''));. Чтобы автоматически обновлять столбец при изменении заголовка, ora2pgpro добавляет следующий триггер:CREATE FUNCTION tsv_t_document_title() RETURNS trigger AS $$ BEGIN IF TG_OP = 'INSERT' OR new.title != old.title THEN new.tsv_title := to_tsvector('pg_catalog.french', coalesce(new.title,'')); END IF; return new; END $$ LANGUAGE plpgsql; CREATE TRIGGER trig_tsv_t_document_title BEFORE INSERT OR UPDATE ON t_document FOR EACH ROW EXECUTE PROCEDURE tsv_t_document_title();Если полнотекстовый индекс Oracle создан по нескольким столбцам, ora2pgpro будет использовать функцию
setweight(), чтобы задать вес в порядке объявления столбцов.FTS_CONFIGИспользуйте эту директиву, чтобы принудительно задать конфигурацию текстового поиска. Если директива не задана, ora2pgpro автоматически определяет стеммер, используемый в Oracle для каждого индекса, и
pg_catalog.english, если информация не найдена.USE_UNACCENTВключите эту директиву, если текстовый поиск должен выполняться без учёта символов ударения или акцента. ora2pgpro создаст вспомогательную функцию на
unaccent()и индексы pg_trgm, использующие эту функцию. Для индексовFTSora2pgpro переопределит конфигурацию текстового поиска, например:CREATE TEXT SEARCH CONFIGURATION fr (COPY = french); ALTER TEXT SEARCH CONFIGURATION fr ALTER MAPPING FOR hword, hword_part, word WITH unaccent, french_stem;Затем задайте для директивы
FTS_CONFIGвora2pgpro.confзначениеfrвместоpg_catalog.english.Если директива включена, ora2pgpro создаёт функцию-обёртку:
CREATE OR REPLACE FUNCTION unaccent_immutable(text) RETURNS text AS $$ SELECT public.unaccent('public.unaccent', $1); $$ LANGUAGE sql IMMUTABLE COST 1;Индексы экспортируются так:
CREATE INDEX t_document_title_unaccent_trgm_idx ON t_document USING gin (unaccent_immutable(title) gin_trgm_ops);Чтобы использовать индекс на основе функции, в запросах необходимо использовать эту же функцию, например:
SELECT * FROM t_document WHERE unaccent_immutable(title) LIKE '%donnees%';USE_LOWER_UNACCENTТо же, что и выше, но вызывается функция
lower()в функцииunaccent_immutable():CREATE OR REPLACE FUNCTION unaccent_immutable(text) RETURNS text AS $$ SELECT lower(public.unaccent('public.unaccent', $1)); $$ LANGUAGE sql IMMUTABLE;
Гибкость ora2pgpro позволяет перенести БД Oracle в БД Postgres Pro с другой структурой или схемой. Нижеописанные директивы позволяют настроить необходимое для этого сопоставление.
REORDERING_COLUMNSВключите эту директиву, чтобы переупорядочить столбцы и уменьшить занимаемое место на диске. В результате на страницу поместится больше строк, что играет важную роль для увеличения скорости. По умолчанию отключена (
disabled), то есть используется такой же порядок определения таблиц, как в Oracle, — для большинства случаев этого достаточно. Директива используется только с типом экспортаTABLE.MODIFY_STRUCTЭта директива позволяет ограничить извлекаемые столбцы для указанной таблицы. В значении задаётся список имён таблиц, разделённых пробелами, с набором столбцов в скобках:
MODIFY_STRUCT NOM_TABLE(nomcol1,nomcol2,...) .... Например:MODIFY_STRUCT T_TEST1(id,dossier) T_TEST2(id,fichier)
В примере выше извлекаются столбцы
idиdossierиз таблицыT_TEST1и столбцыidиfichierиз таблицыT_TEST2. Директива может используется только с типами экспортаTABLE,COPYилиINSERT. С типомTABLEоператор CREATE TABLE создаёт столбцы по новому списку, и никакие индексы или внешние ключи, связанные с исключёнными столбцами, не экспортируются.EXCLUDE_COLUMNSВместо того, чтобы переопределять структуру таблицы с помощью
MODIFY_STRUCT, можно исключить некоторые столбцы из экспорта. В значении задаётся список имён таблиц, разделённых пробелами, с набором столбцов в скобках:EXCLUDE_COLUMNS NOM_TABLE(nomcol1,nomcol2,...) .... Например:EXCLUDE_COLUMNS T_TEST1(id,dossier) T_TEST2(id,fichier)
В примере выше из экспорта исключаются столбцы
idиdossierтаблицыT_TEST1и столбцыidиfichierтаблицыT_TEST2. Директива может используется только с типами экспортаTABLE,COPYилиINSERT. С типомTABLEоператор CREATE TABLE создаёт столбцы по новому списку, и никакие индексы или внешние ключи, связанные с исключёнными столбцами, не экспортируются.REPLACE_TABLESЭта директива позволяет соотнести список имён таблиц Oracle с именами таблиц Postgres Pro. В значении задаётся список имён таблиц, разделённых пробелами:
REPLACE_TABLES ORIG_TBNAME1:DEST_TBNAME1 ORIG_TBNAME2:DEST_TBNAME2
Таблицы Oracle
ORIG_TBNAME1иORIG_TBNAME2будут переименованы вDEST_TBNAME1иDEST_TBNAME2соответственно.REPLACE_COLSКак и имена таблиц, имена экспортируемых столбцов можно переопределить следующим образом:
REPLACE_COLS ORIG_TBNAME(ORIG_COLNAME1:NEW_COLNAME1,ORIG_COLNAME2:NEW_COLNAME2). Например:REPLACE_COLS T_TEST(dico:dictionary,dossier:folder)
При этом столбцы Oracle
dicoиdossierиз таблицыT_TESTбудут переименованы вdictionaryиfolder.REPLACE_AS_BOOLEANЕсли во время экспорта необходимо поменять тип столбцов Oracle на boolean в Postgres Pro, можно указать в этой директиве список таблиц и столбцов, разделённых пробелами:
REPLACE_AS_BOOLEAN TB_NAME1:COL_NAME1 TB_NAME1:COL_NAME2 TB_NAME2:COL_NAME2
Значения в столбцах типа boolean будут заменены на
tиf, при этом используются значения по умолчанию и заданные в директивеBOOLEAN_VALUES.Обратите внимание, что если имя таблицы и/или имя столбца было изменено директивой
REPLACE_TABLES, необходимо использовать имя оригинальной таблицы и/или столбца.REPLACE_COLS TB_NAME1(OLD_COL_NAME1:NEW_COL_NAME1) REPLACE_AS_BOOLEAN TB_NAME1:OLD_COL_NAME1
Можно также задать тип и точность для преобразования всех полей этого типа в boolean автоматически, например:
REPLACE_AS_BOOLEAN NUMBER:1 CHAR:1 TB_NAME1:COL_NAME1 TB_NAME1:COL_NAME2
В примере выше все поля типа number(1) или char(1) заменяются на boolean во всех экспортируемых таблицах.
BOOLEAN_VALUESИспользуйте эту директиву, чтобы дать дополнительное определение для значений типа boolean в полях Oracle. Необходимо задать список значений вида
TRUE:FALSE, разделённых пробелами. По умолчанию ora2pgpro распознает следующие типы значений:BOOLEAN_VALUES yes:no y:n 1:0 true:false enabled:disabled
Любые значения, заданные в этой директиве, добавляются в список значений по умолчанию.
REPLACE_ZERO_DATEЕсли утилита ora2pgpro находит «нулевую» дату (
0000-00-00 00:00:00), то заменяет её на NULL. Это может привести к проблемам, если в столбце есть ограничениеNOT NULL. Если удалить ограничение невозможно, используйте эту директиву, чтобы указать произвольную дату для использования вместо NULL. Если фиктивные даты использовать неуместно, можно задать значение-INFINITY.INDEXES_SUFFIXДобавляет заданное значение к именам индексов в виде суффикса. Полезно, если имена индексов совпадают с именами таблиц. Например:
INDEXES_SUFFIX _idx
Ко всем именам индексов в конце добавится
_idx. Не самый распространённый случай, но может быть полезно.INDEXES_RENAMINGВключите эту директиву, чтобы переименовать все индексы в таком формате:
tablename_columns_names. Может быть очень полезно в базах данных, где имена индексов совпадают между собой или с именем таблицы, что не допускается в Postgres Pro. По умолчанию отключена.USE_INDEX_OPCLASSКлассы операторов
text_pattern_ops,varchar_pattern_opsиbpchar_pattern_opsподдерживают индексы B-деревья соответствующих типов. Отличие от классов операторов по умолчанию заключается в том, что выполняется строгое посимвольное сравнение, а не по правилам сортировки, определяемым локалью, благодаря чему эти классы операторов удобно использовать в запросах с выражениями поиска по шаблону (регулярные выражения LIKE или POSIX), когда локаль базы данных отличается от используемой по умолчаниюC. Если задать значение 1, ora2pgpro будет экспортировать все индексы, построенные по столбцам типа varchar2() и char(), с использованием этих операторов. Если задать значение больше 1, будут изменяться только индексы по столбцам с ограничением по символам больше или равным указанному значению. Например, при значении 128 будут создаваться индексы по столбцам типа varchar2(N), где N >= 128.RENAME_PARTITIONВключите эту директиву, если необходимо переименовывать секционированные таблица. По умолчанию отключена. При большом количестве секционированных таблиц может случиться, что у секций разных родительских таблиц совпадают имена, что недопустимо в Postgres Pro, где имена таблиц должны быть уникальными. По умолчанию применяются следующие правила переименования:
- Секция: "tablename"_part"pos", где "pos" — это номер секции.
- Подсекция: "tablename"_part"pos"_subpart"pos".
- Секция/подсекция: "tablename"_part_default "tablename"_part"pos"_subpart_default.
DISABLE_PARTITIONВключите эту директиву, если сохранять секционирование как в Oracle не требуется и достаточно экспортировать все данные секционированных таблиц в одну таблицу в Postgres Pro. По умолчанию секционирование сохраняется — ora2pgpro экспортирует данные из каждой секции и импортирует их в соответствующую секционированную таблицу в Postgres Pro.
DISABLE_UNLOGGEDПо умолчанию ora2pgpro экспортирует таблицы Oracle со свойством
NOLOGGINGкакUNLOGGED. Можно полностью отключить эту функциональность, поскольку данные из таблицUNLOGGEDмогут быть потеряны в случае сбоя Postgres Pro. Если задать для директивы значение 1, все таблицы будут экспортировать как таблицы обычного типа.
ora2pgpro поддерживает полный экспорт пространственных объектов из БД Oracle. Для управления этим типом экспорта предусмотрены следующие директивы.
AUTODETECT_SPATIAL_TYPEПо умолчанию ora2pgpro анализирует индексы, чтобы определить тип пространственного ограничения и размерность, определённую в Oracle. Эти ограничения передаются при создании индекса, например, так:
CREATE INDEX ... INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS('sdo_indx_dims=2, layer_gtype=point');Если параметры ограничений в Oracle не указаны, по умолчанию эти столбцы экспортируются с универсальным типом GEOMETRY, чтобы получать любой тип пространственных данных.
Директива
AUTODETECT_SPATIAL_TYPEзаставляет ora2pgpro автоматически определять фактический тип пространственных данных и размерность, используемые в столбце с пространственными данными, в противном случае используется тип геометрии без ограничений. Когда эта функциональность включена (по умолчанию), ora2pgpro сканирует выборку из 50000 строк, чтобы проанализировать используемый тип GTYPE. Размер выборки можно увеличить или уменьшить, указав вAUTODETECT_SPATIAL_TYPEнеобходимое количество строк для сканирования.Например, если директива
AUTODETECT_SPATIAL_TYPEотключена, столбецshapeс типом Oracle SDO_GEOMETRY будет преобразован следующим образом:shape geometry(GEOMETRY) or shape geometry(GEOMETRYZ, 4326)
Если директива включена и столбец содержит отдельный тип геометрии, использующий одно измерение с двумерными или трёхмерными многоугольниками:
shape geometry(POLYGON, 4326) or shape geometry(POLYGONZ, 4326)
CONVERT_SRIDЭта директива позволяет управлять автоматическим преобразованием SRID Oracle в значения, соответствующие стандарту EPSG. Когда директива включена, ora2pgpro использует функцию Oracle
sdo_cs.map_oracle_srid_to_epsg()для преобразования всех SRID. По умолчанию включена.Если Oracle возвращает NULL для
SDO_SRID, NULL заменяется значением по умолчанию 8307, преобразованным в значение по EPSG: 4326 (см.DEFAULT_SRID).Если задать значение больше 1, все SRID получат это значение, то есть
DEFAULT_SRIDне используется, если Oracle возвращает NULL.Обратите внимание, что значение
EPSGможно задать на стороне Oracle, еслиsdo_cs.map_oracle_srid_to_epsg()возращает NULL:system@db> UPDATE sdo_coord_ref_sys SET legacy_code=41014 WHERE srid = 27572;
DEFAULT_SRIDИспользуйте эту директиву, чтобы переопределить значение EPSG для SRID по умолчанию (4326).
CONVERT_SRIDпереопределяет это значение, см. выше.GEOMETRY_EXTRACT_TYPEЭта директива может принимать следующие значения:
WKT(по умолчанию),WKBилиINTERNAL. Если задано значениеWKT, ora2pgpro используетSDO_UTIL.TO_WKTGEOMETRY(), чтобы извлечь геометрические данные. Когда задано значениеWKB, ora2pgpro выводит их в двоичном формате с использованиемSDO_UTIL.TO_WKBGEOMETRY(). Если извлекать данные вышеописанными способами в виде вызовов на стороне Oracle, при большом количестве строк может произойти нехватка памяти из-за значительного времени выполнения. Кроме того, сWKB3D геометрии и некоторые другие геометрии, такие какCURVEPOLYGON, не извлекаются. В таких случаях можно использовать тип извлеченияINTERNAL. При этом для преобразования данныхSDO_GEOMETRYвWKTиспользуется библиотека Pure Perl, а само преобразование осуществляется на стороне ora2pgpro. Эта функциональность требует доработки, поэтому перед использованием необходимо проверять корректность экспортированных геометрий. Для пространственных объектов по умолчанию используется тип извлеченияINTERNAL.POSTGIS_SCHEMAИспользуйте эту директиву, чтобы добавить определённую схему в путь поиска для функций PostGIS.
ST_SRID_FUNCTIONЗадаёт функцию Oracle для извлечения SRID из метаданных
ST_Geometry. По умолчанию:ST_SRID. Для ArcSDE, например, следует указатьsde.st_srid.ST_DIMENSION_FUNCTIONЗадаёт функцию Oracle для извлечения размерности из метаданных
ST_Geometry. По умолчанию:ST_DIMENSION. Для ArcSDE, например, следует указатьsde.st_dimension.ST_GEOMETRYTYPE_FUNCTIONЗадаёт функцию Oracle для извлечения типа геометрии из столбца
ST_Geometry. По умолчанию:ST_GEOMETRYTYPE. Для ArcSDE, например, следует указатьsde.st_geometrytype.ST_ASBINARY_FUNCTIONЗадаёт функцию Oracle для преобразования значения
ST_Geometryв форматWKB. По умолчанию:ST_ASBINARY. Для ArcSDE, например, следует указатьsde.st_asbinary.ST_ASTEXT_FUNCTIONЗадаёт функцию Oracle для преобразования значения
ST_Geometryв форматWKT. По умолчанию:ST_ASTEXT. Для ArcSDE, например, следует указатьsde.st_astext.
По умолчанию результаты преобразования в формат Postgres Pro выводятся в файл output.sql.
psql mydb < output.sql
Эта команда импортирует содержимое файла output.sql в БД Postgres Pro mydb.
DATA_LIMITПри экспорте типа
INSERT/COPYora2pgpro ведёт обработку блоками поDATA_LIMITкортежей для увеличения скорости. Перед записью на диск кортежи хранятся в памяти, так что если необходимо увеличить скорость, то при наличии достаточных системных ресурсов можно увеличить этот предел, например, до 100000 или 1000000. Значение 0 означает, что используется размер блока по умолчанию: 10000.BLOB_LIMITКогда ora2pgpro обнаруживает таблицу с BLOB, значение
DATA_LIMITавтоматически уменьшается путём деления на 10 до тех пор, пока оно не станет меньше 1000. Можно отдельно указать директивуBLOB_LIMITдля экспорта BLOB, но обратите внимание, что экспорт BLOB задействует много ресурсов, поэтому большое значение может вызвать нехватку памяти.OUTPUTЭта директива позволяет изменить выходной файл для ora2pgpro. Значение по умолчанию —
output.sql. Если задать имя файла с расширением.gzили.bz2, вывод будет сжат автоматически. При этом для файлов.gzтребуется установленный модуль PerlCompress::Zlib, а для.bz2— утилита командной строки bzip2.OUTPUT_DIRВ этой директиве можно задать каталог для записи файла. Указанный каталог должен существовать.
BZIP2В этой директиве можно указать полный путь к утилите bzip2, если она не обнаружена в переменной окружения
PATH.FILE_PER_CONSTRAINTПозволяет сохранять ограничения для объектов в отдельном файле во время экспорта схемы. Файл будет назван
CONSTRAINTS_OUTPUT, гдеOUTPUT— это значение соответствующей директивы. Для сжатия можно использовать расширение.gzили.bz2. По умолчанию все данные сохраняются в файле, указанном вOUTPUT. Эта директива используется только с типом экспортаTABLE.Ограничения можно быстро импортировать в Postgres Pro с типом экспорта
LOAD, чтобы создавать их параллельно, используя несколько соединений (-jилиJOBS).FILE_PER_INDEXПозволяет сохранять индексы в отдельном файле во время экспорта схемы. Файл будет назван
INDEXES_OUTPUT, гдеOUTPUT— это значение соответствующей директивы. Для сжатия можно использовать расширение.gzили.bz2. По умолчанию все данные сохраняются в файле, указанном вOUTPUT. Эта директива используется только с типами экспортаTABLEиTABLESPACE. С типом экспортаTABLESPACEкоманды ALTER INDEX ... TABLESPACE ... записываются в отдельный файлTBSP_INDEXES_OUTPUT, который можно загрузить в конце миграции после создания индексов для их перемещения.Индексы можно быстро импортировать в Postgres Pro с типом экспорта
LOAD, чтобы создавать их параллельно, используя несколько соединений (-jилиJOBS).FILE_PER_FKEYSПозволяет сохранять объявления внешних ключей в отдельном файле во время экспорта схемы. По умолчанию внешние ключи экспортируются в основной выходной файл или
CONSTRAINT_output.sql. Если директива задана, внешние ключи экспортируются в файлFKEYS_output.sql.FILE_PER_TABLEПозволяет сохранять результаты экспорта в отдельных файлах для каждой таблицы или представления. Файлы будут названы
tablename_OUTPUT, гдеOUTPUT— это значение соответствующей директивы. Для сжатия можно использовать расширение.gzили.bz2в директивеOUTPUT. С заданным значением 0 (по умолчанию) все данные сохраняются в одном файле, значение 1 включает эту функциональность. Используется только с типами экспортаINSERTилиCOPY.FILE_PER_FUNCTIONПозволяет сохранять функции, процедуры и триггеры в отдельных файлах для каждого объекта. Файлы будут названы
objectname_OUTPUT, гдеOUTPUT— это значение соответствующей директивы. Для сжатия можно использовать расширение.gzили.bz2в директивеOUTPUT. С заданным значением 0 (по умолчанию) все данные сохраняются в одном файле, значение 1 включает эту функциональность. Используется только с соответствующим типом экспорта, а для пакетов предусмотрено другое поведение.Если директива включена с типом экспорта
PACKAGE, ora2pgpro создаёт отдельный каталог для каждого пакета с именем, называя его по имени пакета в нижнем регистре, и создаёт отдельные файлы для каждой функции/процедуры в этом каталоге. Если директива отключена, создаётся отдельный файл для каждого пакета с именемpackagename_OUTPUT, гдеOUTPUT— это значение соответствующей директивы.TRUNCATE_TABLEЕсли задано значение 1, перед загрузкой данных добавляется команда TRUNCATE TABLE. Используется только с типами экспорта
INSERTилиCOPY.Когда директива включена, команда добавляется, только если нет глобального предложения DELETE или для текущей таблицы (см. ниже).
DELETEВключает поддержку фильтрации по предложению DELETE FROM ... WHERE перед импортом данных с удалением строк вместо опустошения таблиц. Значение задаётся в таком формате:
TABLE_NAME[DELETE_WHERE_CLAUSE], или если есть только одно предложениеWHEREдля всех таблиц, задаётся одно предложениеDELETEв качестве значения. Можно задавать оба варианта одновременно. Примеры:DELETE 1=1 # Применяется ко всем таблицам и удаляет все кортежи DELETE TABLE_TEST[ID1='001'] # Применяется только к таблице TABLE_TEST DELETE TABLE_TEST[ID1='001' OR ID1='002] DATE_CREATE > '2001-01-01' TABLE_INFO[NAME='test']
Последний вариант применяет два разных предложения DELETE ... WHERE к таблицам
TABLE_TESTиTABLE_INFOи общее предложениеDELETEпоDATE_CREATEко всем остальным таблицам. Если директиваTRUNCATE_TABLEвключена, она применяется ко всем таблицам, к которым не применяетсяDELETE. Такие предложенияDELETEмогут быть полезны при обычных изменениях.STOP_ON_ERRORЗадайте для директивы значение 0, чтобы исключить вызов \set ON_ERROR_STOP ON из всех SQL-скриптов, создаваемых ora2pgpro. По умолчанию эта команда всегда присутствует, чтобы скрипт немедленно завершал работу при ошибках.
COPY_FREEZEВключите эту директиву, чтобы использовать
COPY FREEZEвместо обычноCOPYдля экспорта данных с уже замороженными строками. Это позволяет увеличить производительность при начальном добавлении данных. Строки будут замораживаться, только если загружаемая таблица была создана или опустошена в текущей подтранзакции. Работает только для экспорта в файл, когда не заданы ни параметр-J, ни директиваORACLE_COPIESили они равны 1. Может использоваться для импорта в Postgres Pro напрямую при тех же условиях, но-jиJOBSдолжны быть не заданы или равны 1.CREATE_OR_REPLACEПо умолчанию ora2pgpro использует CREATE OR REPLACE в функциях и представлениях. Если нет необходимости переопределять существующие функции или представления, отключите эту директиву, и команды не будут содержать OR REPLACE.
DROP_IF_EXISTSЧтобы добавлять команду DROP
ОБЪЕКТIF EXISTS перед созданием объекта, включите эту директиву. Может быть полезно в итерационной работе. По умолчанию директива отключена.EXPORT_GTTPostgres Pro не поддерживает глобальные временные таблицы, но для эмуляции этой функциональности можно использовать расширение pgtt. Включите эту директиву, чтобы экспортировать глобальные временные таблицы.
NO_HEADERЕсли включить эту директиву, ora2pgpro не будет добавлять заголовок в выходные файлы, будет записываться только преобразованный код.
PSQL_RELATIVE_PATHПо умолчанию ora2pgpro использует команду psql
\i, чтобы выполнять создаваемые SQL-файлы. Если задать эту директиву, будет использоваться команда\ir, чтобы интерпретировать имена файлов относительно каталога, в котором расположен скрипт. За подробной информацией обратитесь к справке по psql.DATA_VALIDATION_ROWSЧисло строк, которые необходимо получить с обеих сторон для проверки корректности данных. По умолчанию сравниваются первые 10000 строк. При значении 0 сравниваются все строки.
DATA_VALIDATION_ORDERINGПосле изменения данных порядок строк на обеих сторонах отличается. Директива включает упорядочивание данных по первичному ключу или уникальному индексу, так что данные таблицы без этих объектов сравнить невозможно. Если проверка корректности выполняется сразу после миграции, все таблицы могут быть проверены без упорядочивания.
DATA_VALIDATION_ERRORОстанавливает проверку данных таблицы после определённого количества несовпадающих строк. По умолчанию проверка останавливается после 10 строк с ошибками несовпадения.
TRANSFORM_VALUEИспользуйте эту директиву, чтобы указать тип трансформации, применяемый к столбцам при экспорте данных, в виде списка значений, разделённых точкой с запятой:
TABLE[COLUMN_NAME,
код в целевом списке SELECT]Например, чтобы заменить строку «Oracle» на «PostgreSQL» в столбце типа varchar2, используйте следующее значение:
TRANSFORM_VALUE ERROR_LOG_SAMPLE[DBMS_TYPE:regexp_replace("DBMS_TYPE",'Oracle','PostgreSQL')]Чтобы заменить все значения типа char(0) в строке пробельными символами:
TRANSFORM_VALUE CLOB_TABLE[CHARDATA:translate("CHARDATA", chr(0), ' ')]Выражение будет применяться в операторе SQL, используемом для извлечения данных из исходной базы данных.
Если для выгрузки данных в файл задан тип экспорта INSERT или COPY и включена директива FILE_PER_TABLE, будет выдано предупреждение, что ora2pgpro не будет экспортировать данные, если файл уже существует, чтобы не допустить повторную загрузку огромных таблиц. Чтобы принудительно загружать данные из таких таблиц, необходимо сначала удалить существующий выходной файл.
Если необходимо импортировать данные в БД Postgres Pro "на лету", можно настроить подключение, используя нижеописанные директивы, но только для типа экспорта COPY или INSERT, поскольку для схемы БД это не нужно.
PG_DSNИспользуйте эту директиву, чтобы задать пространство имён в качестве источника данных Postgres Pro, используя модуль Perl
DBD::Pgследующим образом:dbi:Pg:dbname=pgdb;host=localhost;port=5432
Он подключается к базе данных
pgdbнаlocalhostпо TCP-порту 5432.Обратите внимание, что эта директива используется только для экспорта данных, результаты других типов экспорта необходимо импортировать вручную с использованием psql или любого другого клиента Postgres Pro.
Чтобы использовать зашифрованное соединение SSL, необходимо добавить в строку подключения
sslmode=requireследующим образом:dbi:Pg:dbname=pgdb;host=localhost;port=5432;sslmode=require
PG_USER,PG_PWDЭти директивы используются, чтобы задать имя пользователя и пароль. Если не задать пароль в
PG_PWDи установить Perl-модульTerm::ReadKey, ora2pgpro запросит пароль интерактивно. Если имя пользователя не задано вPG_USER, его тоже нужно будет задать интерактивно.SYNCHRONOUS_COMMITУказывает, что записи WAL должны быть записаны на диск до того, как команда фиксации транзакции сообщит клиенту об успешном завершении. Функциональность равнозначна установке параметра
synchronous_commitв файлеpostgresql.conf. Используется только для загрузки данных в Postgres Pro напрямую, по умолчанию синхронная фиксация отключена для увеличения скорости записи данных.PG_INITIAL_COMMANDЭту директиву можно использовать для отправки начальных команд в Postgres Pro сразу после подключения, например, чтобы установить параметры сеанса. Директиву можно задавать несколько раз.
PG_NUMERIC_TYPEЕсли задано значение 1, переносимые числовые типы заменяются внутренними типами Postgres Pro. Тип данных Oracle NUMBER(p,s) преобразовывается в типы данных Postgres Pro real и float приблизительно. Если есть поля с денежными суммами, во избежание проблем с округлением десятичных чисел необходимо сохранить тот же тип Postgres Pro numeric(p,s). Задавайте эту директиву, только если точность обязательна, поскольку преобразование в numeric(p,s) выполняется медленнее, чем в real или double precision .
PG_INTEGER_TYPEЕсли задано значение 1, переносимые числовые типы заменяются внутренними типами Postgres Pro. Тип данных Oracle NUMBER(p) преобразовывается в типы данных Postgres Pro smallint, integer или bigint в зависимости от точности. NUMBER без указания точности преобразуется в
DEFAULT_NUMERIC(см. ниже).DEFAULT_NUMERICNUMBER без указания точности преобразуется по умолчанию в bigint, только если
PG_INTEGER_TYPEимеет значение true. Можно поменять значение переменной на любой тип Postgres Pro, такой как integer или float.DATA_TYPEЕсли при преобразовании типов вы столкнулись с проблемами, используйте эту директиву, чтобы переопределить соответствие типов Oracle и Postgres Pro для преобразования ora2pgpro. Через запятую указываются пары типов
тип Oracle:тип Postgres Pro. По умолчанию используется такой список:DATA_TYPE VARCHAR2:varchar,NVARCHAR2:varchar,NVARCHAR:varchar,NCHAR:char,DATE:timestamp(0),LONG:text,LONG RAW:bytea,CLOB:text,NCLOB:text,BLOB:bytea,BFILE:bytea,RAW(16):uuid,RAW(32):uuid,RAW:bytea,UROWID:oid,ROWID:oid,FLOAT:double precision,DEC:decimal,DECIMAL:decimal,DOUBLE PRECISION:double precision,INT:integer,INTEGER:integer,REAL:real,SMALLINT:smallint,BINARY_FLOAT:double precision,BINARY_DOUBLE:double precision,TIMESTAMP:timestamp,XMLTYPE:xml,BINARY_INTEGER:integer,PLS_INTEGER:integer,TIMESTAMP WITH TIME ZONE:timestamp with time zone,TIMESTAMP WITH LOCAL TIME ZONE:timestamp with time zone
Имя директивы и определяемый список должны записываться в одной строке.
Обратите внимание, что если обнаруживаются столбцы типа RAW(16) и RAW(32) или в столбце типа RAW стоит значение по умолчанию
SYS_GUID(), ora2pgpro автоматически преобразует тип столбца в uuid, что правильно в большинстве случаев. Такие данные автоматически переносятся как данные типа Postgres Pro uuid, предоставляемого модулем uuid-ossp.Для замены типа с указанием точности и масштаба необходимо экранировать запятую с помощью символа обратной косой черты. Например, для преобразования всех значений типа NUMBER(*,0) в bigint вместо numeric(38), запишите так:
DATA_TYPE NUMBER(*\,0):bigint
Записывайте только тот тип, который необходимо переопределить, не следует копировать все значения преобразования по умолчанию.
Преобразование BFILE имеет ряд особенностей. Если указать целевой тип TEXT, значения будут содержать только полный путь к внешнему файлу. Если указать BYTEA (по умолчанию), ora2pgpro экспортирует содержимое BFILE как bytea. Если указать целевой тип EFILE, ora2pgpro экспортирует данные как записи EFILE: (DIRECTORY, FILENAME). Используйте тип экспорта
DIRECTORY, чтобы извлечь каталоги и права для этих каталогов.SQL-функции для получения пути к BFILE нет, ora2pgpro создаёт её с использованием пакета
DBMS_LOB.CREATE OR REPLACE FUNCTION ora2pg_get_bfilename( p_bfile IN BFILE ) RETURN VARCHAR2 AS l_dir VARCHAR2(4000); l_fname VARCHAR2(4000); l_path VARCHAR2(4000); BEGIN dbms_lob.FILEGETNAME( p_bfile, l_dir, l_fname ); SELECT directory_path INTO l_path FROM all_directories WHERE directory_name = l_dir; l_dir := rtrim(l_path,'/'); RETURN l_dir || '/' || l_fname; END;Эта функция создаётся, только если ora2pgpro находит таблицу со столбцом типа BFILE и указан целевой тип TEXT. По окончании экспорта функция удаляется. Директива используется с типами экспорта
COPYиINSERT.SQL-функции для получения записи типа EFILE из BFILE нет, ora2pgpro создаёт её с использованием пакета
DBMS_LOB.CREATE OR REPLACE FUNCTION ora2pg_get_efile( p_bfile IN BFILE ) RETURN VARCHAR2 AS l_dir VARCHAR2(4000); l_fname VARCHAR2(4000); BEGIN dbms_lob.FILEGETNAME( p_bfile, l_dir, l_fname ); RETURN '(' || l_dir || ',' || l_fnamei || ')'; END;Эта функция создаётся, только если ora2pgpro находит таблицу со столбцом типа BFILE и указан целевой тип EFILE. По окончании экспорта функция удаляется. Директива используется с типами экспорта
COPYиINSERT.Чтобы указать целевой тип, используйте директиву
DATA_TYPE.DATA_TYPE BFILE:EFILE
Тип EFILE — это пользовательский тип, который можно создать с помощью расширения external_file для портирования типа BFILE в Postgres Pro.
SQL-функции для получения содержимого BFILE нет, ora2pgpro создаёт её с использованием пакета
DBMS_LOB.CREATE OR REPLACE FUNCTION ora2pg_get_bfile( p_bfile IN BFILE ) RETURN BLOB AS filecontent BLOB := NULL; src_file BFILE := NULL; l_step PLS_INTEGER := 12000; l_dir VARCHAR2(4000); l_fname VARCHAR2(4000); offset NUMBER := 1; BEGIN IF p_bfile IS NULL THEN RETURN NULL; END IF; DBMS_LOB.FILEGETNAME( p_bfile, l_dir, l_fname ); src_file := BFILENAME( l_dir, l_fname ); IF src_file IS NULL THEN RETURN NULL; END IF; DBMS_LOB.FILEOPEN(src_file, DBMS_LOB.FILE_READONLY); DBMS_LOB.CREATETEMPORARY(filecontent, true); DBMS_LOB.LOADBLOBFROMFILE (filecontent, src_file, DBMS_LOB.LOBMAXSIZE, offset, offset); DBMS_LOB.FILECLOSE(src_file); RETURN filecontent; END;Эта функция создаётся, только если ora2pgpro находит таблицу со столбцом типа BFILE и указан целевой тип bytea (по умолчанию). По окончании экспорта функция удаляется. Директива используется с типами экспорта
COPYиINSERT.Типы ROWID и UROWID преобразуются в OID по умолчанию, но при импорте данных будут выдаваться ошибки. Аналогичного типа данных нет, поэтому используйте директиву
DATA_TYPE, чтобы указать соответствующий тип Postgres Pro. Можно рассмотреть возможность замены на bigserial (последовательность с автоувеличением), text или uuid.MODIFY_TYPEИногда может потребоваться принудительно использовать определённый целевой тип: например, столбец, экспортируемый ora2pgpro с типом timestamp, можно принудительно экспортировать как date. Значение следует указывать в формате
TABLE:COLUMN:TYPEчерез запятую. Если внутри определения типа нужна запятая или пробел, следует экранировать их с помощью символа обратной косой черты.MODIFY_TYPE TABLE1:COL3:varchar,TABLE1:COL4:decimal(9\,6)
Тип
table1.col3заменяется на varchar, аtable1.col4— на decimal с указанием точности и масштаба.Если задан пользовательский тип столбца, ora2pgpro автоматически определяет составной тип и экспортирует данные с помощью функции
ROW(). Некоторые пользовательские типы Oracle представляют собой массивы из значений встроенных типов, в этом случае можно преобразовать значения такого типа в простой массив из значений встроенных типов Postgres Pro. Для этого укажите необходимый целевой тип, и ora2pgpro преобразует данные в массив. Например, если есть такое определение в Oracle:CREATE OR REPLACE TYPE mem_type IS VARRAY(10) of VARCHAR2(15); CREATE TABLE club (Name VARCHAR2(10), Address VARCHAR2(20), City VARCHAR2(20), Phone VARCHAR2(8), Members mem_type );Здесь пользовательский тип mem_type — это простой массив строк, который можно преобразовать следующим образом:
CREATE TABLE club ( name varchar(10), address varchar(20), city varchar(20), phone varchar(8), members text[] ) ;Директиву следует указывать следующим образом:
MODIFY_TYPE CLUB:MEMBERS:text[]
ora2pgpro преобразует все данные из этого столбца в нужный формат. Поддерживаются массивы значений только символьных и числовых типов.
TO_NUMBER_CONVERSIONПо умолчанию вызовы функции
TO_NUMBERв Oracle преобразовываются в функции приведения к типу numeric. Например,TO_NUMBER('10.1234')преобразуется в вызовto_number('10.1234')::numericв Postgres Pro. Измените значение этой директивы, если требуется выполнять приведение к типу integer или bigint. Формат приведения к типу тоже можно указать в значении директивы: например, со значениемTO_NUMBER_CONVERSION 99999999999999999999.9999999999код выше будет преобразован вTO_NUMBER('10.1234', '99999999999999999999.9999999999'). Любое значение директивы, отличное от numeric, integer или bigint, принимается как маска формата. Если значение отсутствует, преобразование не выполняется.VARCHAR_TO_TEXTПо умолчанию varchar2 без ограничения размера преобразуется в text. Если необходимо сохранить varchar, отключите эту директиву.
FORCE_IDENTITY_BIGINTКак правило, столбец идентификации должен иметь тип bigint, чтобы соответствовать последовательности с автоувеличением, поэтому ora2pgpro всегда принудительно использует bigint. Если по каким-либо причинам необходимо сохранить тип данных, заданный для столбца идентификации, отключите эту директиву.
TO_CHAR_NOTIMEZONEВключите эту директиву, если необходимо удалять информацию о часовом поясе для функций
TO_CHAR(). По умолчанию отключена.
Нижеописанные директивы напрямую влияют на процесс экспорта и дают возможность оптимально настроить его.
SKIPЕсли с типом экспорта
TABLEне нужно экспортировать все ограничения схемы, укажите в директивеSKIPсписок ненужных ограничений, разделённых пробелами или запятыми. Возможные значения:fkeys: исключить ограничения внешнего ключа.pkeys: исключить первичные ключи.ukeys: исключить ограничения уникальности столбцов.indexes: исключить все остальные типы индексов.checks: исключить ограничения-проверки.
SKIP indexes,checks
В примере выше из экспорта исключаются индексы и ограничения-проверки.
PKEY_IN_CREATEВключите эту директиву, если необходимо добавить определение первичного ключа в оператор CREATE TABLE. Если директива отключена (по умолчанию), определение первичного ключа добавляется в оператор ALTER TABLE.
KEEP_PKEY_NAMESПо умолчанию имена первичных и уникальных ключей в исходной БД Oracle игнорируются, они генерируются автоматически в целевой БД Postgres Pro по соответствующим правилам именования. Если необходимо сохранить имена первичных и уникальных ключей из Oracle, задайте для этой директивы значение 1.
FKEY_ADD_UPDATEЭта директива позволяет добавить параметр
ON UPDATE CASCADEдля внешнего ключа, когда естьON DELETE CASCADEили всегда. Oracle не поддерживает эту функциональность, для добавленияON UPDATE CASCADEнеобходимо использовать триггер. Поскольку в Postgres Pro эта функциональность есть, можно выбрать метод добавления действия внешнего ключа. Для директивы доступны следующие значения:never: внешние ключи объявляются так, как в Oracle.delete: действиеON UPDATE CASCADEдобавляется только, если для внешних ключей естьON DELETE CASCADE.always: внешние ключи определяются во время изменения.
FKEY_DEFERRABLEПри экспорте таблиц ora2pgpro, как правило, экспортирует ограничения как есть: если они неоткладываемые, то экспортируются как неоткладываемые. Однако неоткладываемые ограничения могут вызвать проблемы при попытке импорта данных в Postgres Pro. Задайте для директивы
FKEY_DEFERRABLEзначение 1, чтобы все ограничения внешнего ключа экспортировались как откладываемые.DEFER_FKEYКогда для директивы
DEFER_FKEYзадано значение 1, добавляется команда для откладывания всех ограничений внешнего ключа во время экспорта, а импорт выполняется в одной транзакции. Это будет работать, только если внешние ключи экспортируются как откладываемые и данные не импортируются в Postgres Pro напрямую (не задана директиваPG_DSN). Ограничения проверяются в конце транзакции.Кроме того, директиву можно включить, чтобы принудительно создавать все внешние ключи как откладываемые и изначально отложенные во время экспорта схемы (тип экспорта
TABLE).DROP_FKEYЕсли откладывание внешних ключей не представляется возможным из-за большого объёма данных в одной транзакции, внешние ключи не были экспортированы как откладываемые или импорт в Postgres Pro осуществляется напрямую, можно использовать директиву
DROP_FKEY, чтобы удалить все внешние ключи до импорта данных и создать их заново в конце импорта.DROP_INDEXESЭта директива позволяет значительно увеличить скорость импорта данных путём удаления всех индексов, не являющихся автоматическими (индексы по первичным ключам), и создания их заново в конце импорта. Рекомендуется не импортировать индексы и ограничения до импорта всех данных.
DISABLE_TRIGGERSДиректива используется для отключения триггеров для всех таблиц при типе экспорта
COPYилиINSERT. Возможные значения:USER(отключение только пользовательских триггеров) иALL(включая системные триггеры для ссылочной целостности). Значение по умолчанию 0 — для отключения триггера до импорта данных SQL-операторы не добавляются.Если необходимо отключить триггеры во время миграции данных, при подключении под именем суперпользователя Postgres Pro задайте значение
ALL, в противном случае —USER. Значение 1 равняетсяUSER.DISABLE_SEQUENCEСо значением 1 директива отключает изменение последовательностей для всех таблиц, если указан тип экспорта
COPYилиINSERT. Полезно во избежание изменения последовательности во время миграции данных. Значение по умолчанию — 0, то есть последовательности меняются.NOESCAPEПо умолчанию все данные типов, отличных от даты или времени, должны экранироваться. Если с этим возникают проблемы, задайте для данной директивы значение 1, чтобы отключить экранирование символов во время экспорта данных. Эта директива используется только с типом экспорта
COPY. Включить/отключить экранирование символов для операторов INSERT можно с помощью директивыSTANDARD_CONFORMING_STRINGS.STANDARD_CONFORMING_STRINGSЭта директива определяет, будет ли обратная косая черта в обычных строковых константах (
'...') восприниматься буквально, как того требует стандарт SQL. По умолчанию директива включена, то есть при её ненулевом значении ora2pgpro использует синтаксис спецпоследовательностей(E'...'). Директива работает точно так же, как аналогичный параметр в Postgres Pro, и используется во время экспорта только для операторовINSERT. Включить/отключить экранирование символов для операторов COPY можно с помощью директивыNOESCAPE.TRIM_TYPEЕсли для преобразования CHAR(n) из Oracle в varchar(n) или text в Postgres Pro задана директива
DATA_TYPE, может потребоваться усечение данных. Если задать данную директиву, по умолчанию ora2pgpro автоматически находит и удаляет пробельные символы в начале и конце строки (значениеBOTH). Если необходимо удалять пробелы только в начале строк, задайте значениеLEADING. Если необходимо удалять пробелы только в конце строк, задайте значениеTRAILING.TRIM_CHARПо умолчанию директива закомментирована, усекаются пробелы. Используйте директиву, чтобы поменять удаляемый символ: например, на
-, чтобы усекать-в начале поля типа char(n).PRESERVE_CASEЕсли необходимо сохранить регистр имён объектов Oracle, задайте для этой директивы значение 1. По умолчанию ora2pgpro преобразует все имена объектов Oracle в нижний регистр. Не рекомендуется включать эту директиву, поскольку в таком случае придётся заключать в кавычки все имена объектов во всех SQL-скриптах.
ORA_RESERVED_WORDSРазрешает экранировать имена столбцов с использованием зарезервированных слов Oracle. В значении указывается список зарезервированных слов, разделённых запятыми. По умолчанию:
audit,comment,references.USE_RESERVED_WORDSВключите эту директиву, если есть имена таблиц или столбцов, являющиеся зарезервированными словами Postgres Pro. ora2pgpro заключит имена таких объектов в кавычки.
GEN_USER_PWDЗадайте для этой директивы значение 1, чтобы заменить пароль по умолчанию случайным паролем для всех пользователей во время экспорта
GRANT.PG_SUPPORTS_MVIEWВ Postgres Pro материализованные представления создаются с помощью SQL-синтаксиса CREATE MATERIALIZED VIEW. Используйте эту директиву (по умолчанию включена), чтобы в ora2pgpro использовалась встроенная поддержка Postgres Pro. Отключите директиву, чтобы использовать старый вариант синтаксиса с таблицей и набором функций.
PG_VERSIONЗадаёт номер мажорной версии целевой БД Postgres Pro. Например: 11 или 16. Значение по умолчанию — последняя мажорная версия на момент релиза.
BITMAP_AS_GINВключает использование расширения btree_gin для создания индексов со сканированием битовой карты. Расширение должно быть создано. По умолчанию создаются индексы GIN, когда директива отключена — индексы B-деревья.
LONGREADLENИспользуйте эту директиву, чтобы задать предполагаемый размер самого большого объекта в Oracle по свойству
LongReadLen. Значение по умолчанию — 1 МБ, чего может быть недостаточно для извлечения файлов BLOB или CLOB. Если размер LOB превышаетLONGREADLEN,DBD::Oracleвозвращает ошибку «ORA-24345: A Truncation» (Усечение). По умолчанию: 1023*1024 байт.![[Важно]](https://repo.postgrespro.ru/doc/ora2pgpro/23.2.3/ru/html/html/important.png)
Важно Если увеличить значение этой директивы, по всей вероятности нужно уменьшить значение
DATA_LIMIT. Даже если размер файла BLOB составляет 1МБ, при попытке прочитать 10000 таких файлов (значениеDATA_LIMITпо умолчанию) понадобится 10 ГБ памяти. Попробуйте извлекать данные из таких таблиц по очереди и задать дляDATA_LIMITзначение 500 или ниже, в противном случае может произойти нехватка памяти.LONGTRUNKOKЕсли необходимо обойти ошибку «ORA-24345: A Truncation», задайте для этой директивы значение 1, чтобы данные усекались до значения
LONGREADLEN. По умолчанию директива отключена, то есть будет выводиться предупреждение, если дляLONGREADLENзадано недостаточно большое значение.USE_LOB_LOCATORОтключите эту директиву, если необходимо загрузить содержимое файлов BLOB и CLOB полностью без использования указателей на LOB. Для этого необходимо выставить подходящее значение
LONGREADLEN. Обратите внимание, что при этом скорость экспорта BLOB не увеличится, поскольку большая часть времени уходит на экранирование значений bytea и экспорт происходит построчно, а не блоками поDATA_LIMITстрок. По умолчанию директива включена, используются указатели на LOB.LOB_CHUNK_SIZEOracle рекомендует чтение и запись LOB порциями величиной, кратной размеру блоков LOB. Размер блока по умолчанию составляет 8КБ (8192). Последние тесты показывали улучшение производительности при более высоких значениях, таких как 512KБ или 4МБ.
Результаты быстрого теста на 30120 строках с файлами BLOB разного размера (200x5МБ, 19800x212КБ, 10000x942КБ, 100x17МБ, 20x156МБ) при DATA_LIMIT=100, LONGREADLEN=170МБ и общим размером таблицы 20 ГБ:
no lob locator : 22m46,218s (1365 sec., avg: 22 recs/sec) chunk size 8k : 15m50,886s (951 sec., avg: 31 recs/sec) chunk size 512k : 1m28,161s (88 sec., avg: 342 recs/sec) chunk size 4Mb : 1m23,717s (83 sec., avg: 362 recs/sec)
Таким образом, со значением
LOB_CHUNK_SIZEв 4 МБ можно получить ускорение более чем в 10 раз. В этой директиве можно подбирать подходящее значение в зависимости от размера большинства объектов BLOB. Например, если размер большинства объектов LOB меньше 8KБ, достаточно задать для директивы значение 8192 для экономии памяти. ЗначениеLOB_CHUNK_SIZEпо умолчанию — 512000.XML_PRETTYУказывает использовать функцию
getStringVal()вместоgetClobVal()для экспорта данных XML. По умолчанию 1, функциональность включена для обратной совместимости. Задайте значение 0, чтобы извлекать данные как CLOB. Обратите внимание, что значение XML, извлекаемое с помощью withgetStringVal()не должно превышать заданный в VARCHAR2 предел (4000), в противном случае выдаётся ошибка.ENABLE_MICROSECONDЗадайте для директивы значение O, если необходимо отключить экспорт миллисекунд из столбцов типа timestamp Oracle. По умолчанию миллисекунды экспортируются с использованием следующего формата:
'YYYY-MM-DD HH24:MI:SS.FF'
При отключенной директиве будет использоваться такой формат:
to_char(..., 'YYYY-MM-DD HH24:MI:SS')
По умолчанию миллисекунды экспортируются.
DISABLE_COMMENTЗадайте для директивы значение 1, чтобы не экспортировать комментарии к таблицам и столбцам. По умолчанию директива включена.
NLS_LANGПо умолчанию ora2pgpro задаёт для
NLS_LANGзначениеAMERICAN_AMERICA.AL32UTF8, а дляNLS_NCHAR—AL32UTF8. Не рекомендуется изменять эти значения, но в некоторых случаях это может быть полезно. При изменении значений этой директивы кодировка клиента на стороне Oracle изменится с изменением значений переменных окружения$ENV{NLS_LANG}и$ENV{NLS_NCHAR}.BINMODEПо умолчанию ora2pgpro заставляет Perl использовать кодировку ввода-вывода UTF8 путём вызова прагмы Perl:
use open ':utf8';
Кодировку можно переопределить, задав директиву
BINMODE: например, задайте значение:locale, чтобы использовать локаль системы, илиiso-8859-7.use open ':locale'; use open ':encoding(iso-8859-7)';
Если в
NLS_LANGзадана локаль, отличная от кодировки UTF8, можно дополнительно указать эту директиву. Для большинства случаев оставьте директиву закомментированной.CLIENT_ENCODINGВо избежание проблем кодировка клиента Postgres Pro автоматически указывается как UTF8. Если не используется значение
NLS_LANGпо умолчанию, может понадобиться изменить кодировку клиента Postgres Pro.Список поддерживаемых Postgres Pro наборов символов описан в разделе Поддержка кодировок.
FORCE_PLSQL_ENCODINGВключите эту директиву, чтобы использовать кодировку UTF8 для экспортируемого кода PL/SQL. Директива может быть полезна в особых случаях.
Автоматическое преобразование кода из PL/SQL Oracle в PL/pgSQL Postgres Pro требует доработки в ora2pgpro и некоторых ручных действий. Код Perl code, используемый для преобразования, хранится в специально модуле Perl Ora2Pgpro/PLSQL.pm.
PLSQL_PGSQLВключает/отключает преобразование PL/SQL в PL/pgSQL. По умолчанию включено.
NULL_EQUAL_EMPTYora2pgpro может заменять все условия с тестом на NULL вызовом функции
coalesce(), чтобы имитировать поведение Oracle, где пустые строки считаются равными NULL.(field1 IS NULL) is replaced by (coalesce(field1::text, '') = '') (field2 IS NOT NULL) is replaced by (field2 IS NOT NULL AND field2::text <> '')
Такая замена может потребоваться, чтобы приложение работало аналогично, но рекомендуется преобразовывать пустые строки в NULL, поскольку Postgres Pro воспринимает их по-разному.
EMPTY_LOB_NULLВключает экспорт функций
empty_clob()иempty_blob()как NULL вместо пустой строки для первой и\xдля второй. Если использование NULL в столбце допускается, это поможет увеличить скорость экспорта при наличии большого количества пустых больших объектов. По умолчанию точно сохраняются данные из Oracle.PACKAGE_AS_SCHEMAЕсли необходимо экспортировать пакеты как простые функции, а не схемы, можно заменить все вызовы
package_name.function_name. Если отключить директивуPACKAGE_AS_SCHEMA, ora2pgpro заменит все вызовыpackage_name.function_name()наpackage_name_function_name(). По умолчанию пакеты экспортируются как схемы.Замена будет производиться во всех операциях DDL или коде, разбираемом при преобразовании кода PL/SQL в PL/pgSQL. При этом должна быть включена директива
PLSQL_PGSQL, или в командной строке передан параметр-p.REWRITE_OUTER_JOINВключите эту директиву, если не работает модификация стандартного синтаксиса Oracle для
OUTER JOIN(+). В этом случае ora2pgpro не будет модифицировать такой код, по умолчанию сейчас производится модификация простой формы правого внешнего соединения.UUID_FUNCTIONПо умолчанию ora2pgpro преобразует вызов функции Oracle
SYS_GUID()в вызов функцииuuid_generate_v4расширения uuid-ossp. Чтобы использовать вместо неё функциюgen_random_uuidрасширения pgcrypto, можно задать в качестве значения этой директивы имя функции. По умолчанию используетсяuuid_generate_v4.Обратите внимание, что если обнаруживаются столбцы типа RAW(16) и RAW(32) или в столбце типа RAW стоит значение по умолчанию
SYS_GUID(), ora2pgpro автоматически преобразует тип столбца в uuid, что правильно в большинстве случаев. В этом случае данные автоматически переносятся как данные типа Postgres Pro uuid, предоставляемого модулем uuid-ossp.FUNCTION_STABLEПо умолчанию функции Oracle помечаются как
STABLE, поскольку они не изменяют данные, кроме как в PL/SQL с назначением переменных или в качестве условного выражения. Отключите эту директиву, чтобы утилита ora2pgpro создавала такие функции какVOLATILE.COMMENT_COMMIT_ROLLBACKПо умолчанию ora2pgpro оставляет вызовы COMMIT/ROLLBACK без изменений, чтобы пользователь проверил логику функции. Включите эту директиву, когда исходный код Oracle исправлен или необходимо закомментировать эти вызовы.
COMMENT_SAVEPOINTВ процедурах PL/SQL вызовам SAVEPOINT часто сопутствуют команды ROLLBACK TO savepoint_name. Когда директива
COMMENT_COMMIT_ROLLBACKвключена и вызовы SAVEPOINT также нужно закомментировать, включите эту директиву.STRING_CONSTANT_REGEXPВо время преобразования кода PL/SQL в PL/pgSQL утилитаora2pgpro заменяет все строковые константы на текст в одинарных кавычках. Если в динамических вызовах используются местозаполнители в строках, в данной директиве можно задать список регулярных выражений, которые заменяются на время разбора. Например:
STRING_CONSTANT_REGEXP <placeholder value=".*">
Регулярные выражения в списке разделяются точкой с запятой.
ALTERNATIVE_QUOTING_REGEXPВ данной директиве задайте в качестве значения регулярное выражение с поиском подходящих строк для извлечения текстовой части, чтобы включить поддержку механизма альтернативных кавычек ('Q' или 'q'). Например, для переменной, заданной как
c_sample VARCHAR2(100 CHAR) := q'{This doesn't work.}';следует использовать регулярное выражение:
ALTERNATIVE_QUOTING_REGEXP q'{(.*)}'ora2pgpro использует разделитель
$$, результат будет следующим:c_sample varchar(100) := $$This doesn't work.$$;
Значение данной директивы представляет собой список регулярных выражений, разделённых точкой с запятой. Обязательно указать часть поиска подходящих строк (в скобках) для каждого выражения, если необходимо восстановить строковую константу.
USE_ORAFCEВключите эту директиву, если необходимо использовать функции, определённые в библиотеке orafce, и не преобразовывать вызовы этих функций с помощью ora2pgpro.
По умолчанию ora2pgpro заменяет функции
add_month(),add_year(),date_trunc()иto_char(), но можно использовать версии этих функций из orafce, которые не требуют преобразования кода.INCLUDE_PACKAGESСодержит список экспортируемых пакетов, разделённых запятыми. Используется только с типом экспорта
PACKAGEи только последнее вхождение в файле конфигурации.EXCLUDE_PACKAGESСодержит список исключаемых из экспорта пакетов, разделённых запятыми. Используется только с типом экспорта
PACKAGEи только последнее вхождение в файле конфигурации.POSTGRESPRO_ATXЕсли задано значение 1, автономные транзакции экспортируются напрямую как автономные транзакции Postgres Pro.
Материализованные представления экспортируются в виде снимка «Snapshot Materialized Views» (Снимок материализованных представлений), поскольку Postgres Pro поддерживает только полное обновление.
При экспорте материализованных представлений ora2pgpro сначала добавляет код SQL для создания таблицы materialized_views (материализованные представления):
CREATE TABLE materialized_views (
mview_name text NOT NULL PRIMARY KEY,
view_name text NOT NULL,
iname text,
last_refresh TIMESTAMP WITH TIME ZONE
);Для каждого материализованного представления создаётся одна запись в этой таблице. Затем добавляется код PL/pgSQL для создания деревьев функций:
- Функция
create_materialized_view(text, text, text)используется для создания материализованного представления. - Функция
drop_materialized_view(text)используется для удаления материализованного представления. - Функция
refresh_full_materialized_view(text)используется для обновления материализованного представления.
Далее добавляется SQL-код для создания представления и материализованного представления:
CREATE VIEW mviewname_mview AS
SELECT ... FROM ...;
SELECT create_materialized_view('mviewname','mviewname_mview', заменить на имя столбца, используемого для создания индекса);Первый аргумент — это имя материализованного представления, второй — имя представления, на основе которого создаётся материализованное представление, а третий — имя столбца для построения индекса (а также первичного ключа в большинстве случаев). Этот столбец не рассчитывается автоматически, поэтому его имя необходимо заменить.
Как было сказано выше, ora2pgpro поддерживает только снимок материализованных представлений, поэтому таблица будет обновлена полностью при опустошении таблицы и повторной загрузке данных из представления:
refresh_full_materialized_view('mviewname');Чтобы удалить материализованное представление, вызовите функцию drop_materialized_view() с именем материализованного представления в качестве параметра.
DEBUGСо значением 1 выводятся подробные сообщения.
IMPORTОбщие директивы ora2pgpro можно записать в отдельном файле и импортировать этот файл в другие файлы конфигурации, используя директиву
IMPORTследующим образом:IMPORT commonfile.conf
При этом все директивы из файла
commonfile.confбудут импортированы в текущий файл конфигурации.
Любое представление Oracle можно экспортировать как таблицу Postgres Pro, задав для директивы TYPE значение TABLE, чтобы создавались соответствующие операторы CREATE TABLE. Также можно использовать тип экспорта COPY или INSERT, чтобы экспортировать данные соответствующим образом. Чтобы это было возможно, укажите представления в директиве VIEW_AS_TABLE.
В этом случае, если ora2pgpro обнаруживает представление, то извлекает схемы (если TYPE=TABLE) в форме CREATE TABLE, а затем извлекает данные (если TYPE=COPY или TYPE=INSERT) по схеме.
Например, рассмотрим следующее представление:
CREATE OR REPLACE VIEW product_prices (category_id, product_count, low_price, high_price) AS
SELECT category_id, COUNT(*) as product_count,
MIN(list_price) as low_price,
MAX(list_price) as high_price
FROM product_information
GROUP BY category_id;Если для такого представления задать для директивы VIEW_AS_TABLE значение product_prices и использовать тип экспорта TABLE, ora2pgpro определит типы возвращаемых столбцов и создаст соответствующий оператор CREATE TABLE:
CREATE TABLE product_prices (
category_id bigint,
product_count integer,
low_price numeric,
high_price numeric
);Данные будут загружены в зависимости от типа экспорта COPY или INSERT и объявления типа.
Кроме того, для фильтрации экспортируемых объектов можно использовать директивы ALLOW и EXCLUDE.
Нелегко оценить стоимость процесса миграции из Oracle в Postgres Pro. Чтобы достаточно хорошо произвести такую оценку, ora2pgpro анализирует все объекты в БД, все функции и хранимые процедуры, чтобы определить, есть ли объекты и код PL/SQL, которые невозможно преобразовать автоматически.
Для анализа БД Oracle в ora2pgpro есть специальный режим анализа, который позволяет сгенерировать отчёт о содержимом БД и возможности его экспорта.
Чтобы активировать режим анализа и отчёта, необходимо использовать тип экспорта SHOW_REPORT следующим образом:
ora2pgpro -t SHOW_REPORT
Пример отчёта, генерируемого командой:
--------------------------------------
Ora2Pg: Oracle Database Content Report
--------------------------------------
Version Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
Schema HR
Size 880.00 MB
--------------------------------------
Object Number Invalid Comments
--------------------------------------
CLUSTER 2 0 Clusters are not supported and will not be exported.
FUNCTION 40 0 Total size of function code: 81992.
INDEX 435 0 232 index(es) are concerned by the export, others are automatically generated and will
do so on PostgreSQL. 1 bitmap index(es). 230 b-tree index(es). 1 reversed b-tree index(es)
Note that bitmap index(es) will be exported as b-tree index(es) if any. Cluster, domain,
bitmap join and IOT indexes will not be exported at all. Reverse indexes are not exported
too, you may use a trigram-based index (see pg_trgm) or a reverse() function based index
and search. You may also use 'varchar_pattern_ops', 'text_pattern_ops' or 'bpchar_pattern_ops'
operators in your indexes to improve search with the LIKE operator respectively into
varchar, text or char columns.
MATERIALIZED VIEW 1 0 All materialized view will be exported as snapshot materialized views, they
are only updated when fully refreshed.
PACKAGE BODY 2 1 Total size of package code: 20700.
PROCEDURE 7 0 Total size of procedure code: 19198.
SEQUENCE 160 0 Sequences are fully supported, but all call to sequence_name.NEXTVAL or sequence_name.CURRVAL
will be transformed into NEXTVAL('sequence_name') or CURRVAL('sequence_name').
TABLE 265 0 1 external table(s) will be exported as standard table. See EXTERNAL_TO_FDW configuration
directive to export as file_fdw foreign tables or use COPY in your code if you just
want to load data from external files. 2 binary columns. 4 unknown types.
TABLE PARTITION 8 0 Partitions are exported using table inheritance and check constraint. 1 HASH partitions.
2 LIST partitions. 6 RANGE partitions. Note that Hash partitions are not supported.
TRIGGER 30 0 Total size of trigger code: 21677.
TYPE 7 1 5 type(s) are concerned by the export, others are not supported. 2 Nested Tables.
2 Object type. 1 Subtype. 1 Type Boby. 1 Type inherited. 1 Varrays. Note that Type
inherited and Subtype are converted as table, type inheritance is not supported.
TYPE BODY 0 3 Export of type with member method are not supported, they will not be exported.
VIEW 7 0 Views are fully supported, but if you have updatable views you will need to use
INSTEAD OF triggers.
DATABASE LINK 1 0 Database links will not be exported. You may try the dblink perl contrib module or use
the SQL/MED PostgreSQL features with the different Foreign Data Wrapper (FDW) extensions.
Note: Invalid code will not be exported unless the EXPORT_INVALID configuration directive is activated.Поскольку утилита ora2pgpro может преобразовывать код SQL и PL/SQL из синтаксиса Oracle в Postgres Pro, она может оценивать трудности в коде и время, необходимое для выполнения полной миграции БД.
Для оценки стоимости миграции в человеко-днях, ora2pgpro предоставляет директиву ESTIMATE_COST, которую также можно включить в командной строке: --estimate_cost.
Эту функциональность можно использовать только с типами экспорта SHOW_REPORT, FUNCTION, PROCEDURE, PACKAGE и QUERY.
ora2pgpro -t SHOW_REPORT --estimate_cost
Сгенерированный отчёт выглядит так же, как в предыдущем примере, но добавляется столбец Estimated cost (Предполагаемая стоимость) следующим образом:
--------------------------------------
Ora2Pg: Oracle Database Content Report
--------------------------------------
Version Oracle Database 10g Express Edition Release 10.2.0.1.0
Schema HR
Size 890.00 MB
--------------------------------------
Object Number Invalid Estimated cost Comments
--------------------------------------
DATABASE LINK 3 0 9 Database links will be exported as SQL/MED PostgreSQL's Foreign Data Wrapper (FDW) extensions
using oracle_fdw.
FUNCTION 2 0 7 Total size of function code: 369 bytes. HIGH_SALARY: 2, VALIDATE_SSN: 3.
INDEX 21 0 11 11 index(es) are concerned by the export, others are automatically generated and will do so
on PostgreSQL. 11 b-tree index(es). Note that bitmap index(es) will be exported as b-tree
index(es) if any. Cluster, domain, bitmap join and IOT indexes will not be exported at all.
Reverse indexes are not exported too, you may use a trigram-based index (see pg_trgm) or a
reverse() function based index and search. You may also use 'varchar_pattern_ops', 'text_pattern_ops'
or 'bpchar_pattern_ops' operators in your indexes to improve search with the LIKE operator
respectively into varchar, text or char columns.
JOB 0 0 0 Job are not exported. You may set external cron job with them.
MATERIALIZED VIEW 1 0 3 All materialized view will be exported as snapshot materialized views, they
are only updated when fully refreshed.
PACKAGE BODY 0 2 54 Total size of package code: 2487 bytes. Number of procedures and functions found
inside those packages: 7. two_proc.get_table: 10, emp_mgmt.create_dept: 4,
emp_mgmt.hire: 13, emp_mgmt.increase_comm: 4, emp_mgmt.increase_sal: 4,
emp_mgmt.remove_dept: 3, emp_mgmt.remove_emp: 2.
PROCEDURE 4 0 39 Total size of procedure code: 2436 bytes. TEST_COMMENTAIRE: 2, SECURE_DML: 3,
PHD_GET_TABLE: 24, ADD_JOB_HISTORY: 6.
SEQUENCE 3 0 0 Sequences are fully supported, but all call to sequence_name.NEXTVAL or sequence_name.CURRVAL
will be transformed into NEXTVAL('sequence_name') or CURRVAL('sequence_name').
SYNONYM 3 0 4 SYNONYMs will be exported as views. SYNONYMs do not exists with PostgreSQL but a common workaround
is to use views or set the PostgreSQL search_path in your session to access
object outside the current schema.
user1.emp_details_view_v is an alias to hr.emp_details_view.
user1.emp_table is an alias to hr.employees@other_server.
user1.offices is an alias to hr.locations.
TABLE 17 0 8.5 1 external table(s) will be exported as standard table. See EXTERNAL_TO_FDW configuration
directive to export as file_fdw foreign tables or use COPY in your code if you just want to
load data from external files. 2 binary columns. 4 unknown types.
TRIGGER 1 1 4 Total size of trigger code: 123 bytes. UPDATE_JOB_HISTORY: 2.
TYPE 7 1 5 5 type(s) are concerned by the export, others are not supported. 2 Nested Tables. 2 Object type.
1 Subtype. 1 Type Boby. 1 Type inherited. 1 Varrays. Note that Type inherited and Subtype are
converted as table, type inheritance is not supported.
TYPE BODY 0 3 30 Export of type with member method are not supported, they will not be exported.
VIEW 1 1 1 Views are fully supported, but if you have updatable views you will need to use INSTEAD OF triggers.
--------------------------------------
Total 65 8 162.5 162.5 cost migration units means approximatively 2 man day(s).Последняя строка показывает предполагаемое количество человеко-дней на миграцию кода с блоками миграции для каждого объекта. Блок миграции составляет 5 минут, что соответствует скорости миграции, выполняемой специалистом Postgres Pro. Для первой миграции можно увеличить это значение в директиве COST_UNIT_VALUE или передав параметр --cost_unit_value в командной строке:
ora2pgpro -t SHOW_REPORT --estimate_cost --cost_unit_value 10
ora2pgpro может выдавать оценку уровня сложности миграции, например Migration level: B-5.
Уровни миграции:
A - Миграцию можно запустить автоматически.
B - Миграция требует замены кода, срок до 5 человеко-дней.
C - Миграция требует замены кода, срок свыше 5 человеко-дней.
Технические уровни:
1 = незначительный: без хранимых процедур и триггеров.
2 = простой: без хранимых процедур, но с триггерами, без замены кода вручную.
3 = средний: хранимые процедуры и/или триггеры, без замены кода вручную.
4 = ручной: без хранимых процедур, но с триггерами или представлениями, с заменой кода.
5 = сложный: хранимые процедуры и/или триггеры, с заменой кода.Выдаваемый уровень оценки содержит букву (A и B), показывающую необходимость ручной замены кода, и цифру от 1 до 5, определяющую уровень технической сложности. Кроме того, предоставляется параметр --human_days_limit, в котором можно задать предел человеко-дней, по достижении которого уровень миграции меняется на C, чтобы показать необходимость проведения длительных работ и управления проектом миграции с поддержкой. Значение по умолчанию — 10 человеко-дней. Чтобы изменить это значение на постоянной основе, используйте директиву HUMAN_DAYS_LIMIT.
Эта функциональность помогает определить порядок миграции баз данных и команду для выполнения работ.
ora2pgpro содержит скрипт ora2pgpro_scanner, который можно использовать при большом количестве анализируемых экземпляров и схем.
ora2pgpro_scanner -l CSVFILE [-o OUTDIR]
-b | --binpath DIR: full path to directory where the ora2pgpro binary stays.
Might be useful only on Windows OS.
-c | --config FILE: set custom configuration file to use otherwise ora2pgpro
will use the default: /etc/ora2pgpro/ora2pgpro.conf.
-l | --list FILE : CSV file containing a list of databases to scan with
all required information. The first line of the file
can contain the following header that describes the
format that must be used:
"type","schema/database","dsn","user","password"
-o | --outdir DIR : (optional) by default all reports will be dumped to a
directory named 'output', it will be created automatically.
If you want to change the name of this directory, set the name
at second argument.
-t | --test : just try all connections by retrieving the required schema
or database name. Useful to validate your CSV list file.
-u | --unit MIN : redefine globally the migration cost unit value in minutes.
Default is taken from the ora2pgpro.conf (default 5 minutes).
Here is a full example of a CSV databases list file:
"type","schema/database","dsn","user","password"
"MYSQL","sakila","dbi:mysql:host=192.168.1.10;database=sakila;port=3306","root","secret"
"ORACLE","HR","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager"
"MSSQL","HR","dbi:ODBC:driver=msodbcsql18;server=srv.database.windows.net;database=testdb","system","manager"
The CSV field separator must be a comma.
Note that if you want to scan all schemas from an Oracle instance you just
have to leave the schema field empty, Ora2PgPro will automatically detect all
available schemas and generate a report for each one. Of course you need to
use a connection user with enough privileges to be able to scan all schemas.
For example:
"ORACLE","","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager"
"MSSQL","","dbi:ODBC:driver=msodbcsql18;server=srv.database.windows.net;database=testdb","usrname","passwd"
will generate a report for all schema in the XE instance. Note that in this
case the SCHEMA directive in ora2pgpro.conf must not be set.В результате создаётся файл CSV с оценкой, в котором каждой строке соответствует одна схема или база данных, и подробный HTML-отчёт для каждой сканируемой БД.
Подсказка: используйте параметр -t | --test, чтобы в файле CSV протестировать все соединения.
Пользователям Windows следует использовать в командной строке параметр -b, чтобы указать каталог для хранения ora2pgpro_scanner, в противном случае вызовы команд ora2pgpro завершатся ошибкой.
ora2pgpro всегда включает 2 блока миграции с типом TEST и 1 блок с SIZE на 1000 строк кода в оценку миграции функций. Это означает, что по умолчанию на каждую функцию в оценку миграции добавляется 15 минут. Разумеется, при наличии модульных тестов или множества простых функций оценка будет завышенной.
Показатели миграции, назначаемые для каждого типа объекта БД Oracle, определяются в библиотеке Perl lib/Ora2Pg/PLSQL.pm, указанной в переменной %OBJECT_SCORE.
Количество строк PL/SQL для блока миграции также задаётся в этом файле в переменной $SIZE_SCORE.
Количество блоков миграции, связанных с трудностями в коде PL/SQL, также указываются в библиотеке Perl lib/Ora2Pgpro/PLSQL.pm в %UNCOVERED_SCORE.
Этот метод оценки требует доработки.
С типом экспорта LOAD можно отправлять SQL-команды из файла по нескольким соединениям с Postgres Pro. Чтобы использовать эту функциональности, необходимо задать директивы PG_DSN, PG_USER и PG_PWD.
ora2pgpro -t LOAD -c config/ora2pgpro.conf -i schema/tables/INDEXES_table.sql -j 4
При этом индексы будут создаваться одновременно по 4 соединениям с Postgres Pro. Это значительно ускорит часть процесса миграции с большим объёмом данных.
ora2pgpro не может экспортировать данные столбцов типа LONG RAW. Библиотека OCI не может экспортировать и всегда возвращает одну и ту же запись. Чтобы экспортировать такие данные, преобразуйте поле в BLOB путём создания временной таблицы до миграции данных.
SQL> DESC TEST_LONGRAW Name NULL ? Type -------------------- -------- ---------------------------- ID NUMBER C1 LONG RAW
Например, таблицу Oracle выше нужно перенести в таблицу с BLOB следующим образом:
CREATE TABLE test_blob (id NUMBER, c1 BLOB);
А затем копировать данные с помощью такого запроса INSERT:
INSERT INTO test_blob SELECT id, to_lob(c1) FROM test_longraw;
Затем нужно исключить изначальную таблицу из экспорта (см. EXCLUDE) и переименовать новую временную таблицу "на лету" при помощи директивы REPLACE_TABLES.
Oracle допускает использование глобальных переменных в пакетах. Утилита ora2pgpro экспортирует эти переменные как переменные пакетов Postgres Pro.
Тип экспорта TEST позволяет проверить, что все объекты из БД Oracle были созданы в Postgres Pro. Для проверки стороны Postgres Pro необходимо задать PG_DSN.
Обратите внимание, что эта функциональность учитывает ограничения имён схем, если заданы директивы EXPORT_SCHEMA и SCHEMA или PG_SCHEMA. Если задана только директива EXPORT_SCHEMA, сканируются все схемы в Oracle и Postgres Pro. Можно отфильтровать до одной схемы с помощью SCHEMA и/или PG_SCHEMA, но нельзя указать список схем. Чтобы протестировать список схем, вызывайте ora2pgpro несколько раз, отдельно указывая имя необходимой схемы по очереди.
ora2pgpro -t TEST -c config/ora2pgpro.conf > migration_diff.txt
Например, эта команда создаст файл с отчётом по всем объектам с подсчётом строк на обеих сторонах, Oracle и Postgres Pro, с отдельной секцией ошибок с описанием различий для каждого объекта. Пример результата:
[TEST INDEXES COUNT] ORACLEDB:DEPARTMENTS:2 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:6 POSTGRES:employees:6 [ERRORS INDEXES COUNT] Table departments don't have the same number of indexes in Oracle (2) and in PostgreSQL (1). [TEST UNIQUE CONSTRAINTS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS UNIQUE CONSTRAINTS COUNT] OK, Oracle and PostgreSQL have the same number of unique constraints. [TEST PRIMARY KEYS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS PRIMARY KEYS COUNT] OK, Oracle and PostgreSQL have the same number of primary keys. [TEST CHECK CONSTRAINTS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS CHECK CONSTRAINTS COUNT] OK, Oracle and PostgreSQL have the same number of check constraints. [TEST NOT NULL CONSTRAINTS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS NOT NULL CONSTRAINTS COUNT] OK, Oracle and PostgreSQL have the same number of not null constraints. [TEST COLUMN DEFAULT VALUE COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS COLUMN DEFAULT VALUE COUNT] OK, Oracle and PostgreSQL have the same number of column default value. [TEST IDENTITY COLUMN COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:0 POSTGRES:employees:0 [ERRORS IDENTITY COLUMN COUNT] OK, Oracle and PostgreSQL have the same number of identity column. [TEST FOREIGN KEYS COUNT] ORACLEDB:DEPARTMENTS:0 POSTGRES:departments:0 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS FOREIGN KEYS COUNT] OK, Oracle and PostgreSQL have the same number of foreign keys. [TEST TABLE COUNT] ORACLEDB:TABLE:2 POSTGRES:TABLE:2 [ERRORS TABLE COUNT] OK, Oracle and PostgreSQL have the same number of TABLE. [TEST TABLE TRIGGERS COUNT] ORACLEDB:DEPARTMENTS:0 POSTGRES:departments:0 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS TABLE TRIGGERS COUNT] OK, Oracle and PostgreSQL have the same number of table triggers. [TEST TRIGGER COUNT] ORACLEDB:TRIGGER:2 POSTGRES:TRIGGER:2 [ERRORS TRIGGER COUNT] OK, Oracle and PostgreSQL have the same number of TRIGGER. [TEST VIEW COUNT] ORACLEDB:VIEW:1 POSTGRES:VIEW:1 [ERRORS VIEW COUNT] OK, Oracle and PostgreSQL have the same number of VIEW. [TEST MVIEW COUNT] ORACLEDB:MVIEW:0 POSTGRES:MVIEW:0 [ERRORS MVIEW COUNT] OK, Oracle and PostgreSQL have the same number of MVIEW. [TEST SEQUENCE COUNT] ORACLEDB:SEQUENCE:1 POSTGRES:SEQUENCE:0 [ERRORS SEQUENCE COUNT] SEQUENCE does not have the same count in Oracle (1) and in PostgreSQL (0). [TEST TYPE COUNT] ORACLEDB:TYPE:1 POSTGRES:TYPE:0 [ERRORS TYPE COUNT] TYPE does not have the same count in Oracle (1) and in PostgreSQL (0). [TEST FDW COUNT] ORACLEDB:FDW:0 POSTGRES:FDW:0 [ERRORS FDW COUNT] OK, Oracle and PostgreSQL have the same number of FDW. [TEST FUNCTION COUNT] ORACLEDB:FUNCTION:3 POSTGRES:FUNCTION:3 [ERRORS FUNCTION COUNT] OK, Oracle and PostgreSQL have the same number of functions. [TEST SEQUENCE VALUES] ORACLEDB:EMPLOYEES_NUM_SEQ:1285 POSTGRES:employees_num_seq:1285 [ERRORS SEQUENCE VALUES COUNT] OK, Oracle and PostgreSQL have the same values for sequences [TEST ROWS COUNT] ORACLEDB:DEPARTMENTS:27 POSTGRES:departments:27 ORACLEDB:EMPLOYEES:854 POSTGRES:employees:854 [ERRORS ROWS COUNT] OK, Oracle and PostgreSQL have the same number of rows.
Проверка корректности данных заключается в сопоставлении данных, полученных из сторонней таблицы, с указанием на исходную таблицу Oracle и локальную таблицу Postgres Pro, получаемую в результате экспорта.
Чтобы проверить корректность данных, можно подключаться напрямую, как делает ora2pgpro, но также можно использовать расширение oracle_fdw, причём нужно задать директивы FDW_SERVER и PG_DSN.
По умолчанию ora2pgpro извлекает первые 10000 строк с обеих сторон, это количество можно изменить, задав директиву DATA_VALIDATION_ROWS. Когда задано нулевое значение, сравниваться будут все строки таблиц.
Для проверки корректности данных требуется первичный ключ или уникальный индекс не по столбцу LOB. Сортировка строк выполняется по этому уникальному ключу. По причине различий в поведении Oracle и Postgres Pro, если в Postgres Pro не используется правило сортировки C, порядок сортировки может отличаться от Oracle. В этом случае проверка завершится ошибкой.
Проверку данных следует выполнять до изменения данных.
ora2pgpro прервёт сопоставление двух таблиц после достижения DATA_VALIDATION_ROWS или после 10 ошибок; результат выводится в файл data_validation.log, записываемый в текущий каталог по умолчанию. Число ошибок, после которых останавливается проверка, можно задать в директиве DATA_VALIDATION_ERROR. Для удобства анализа все строки с ошибками выводятся в выходной файл.
Можно выполнять проверку корректности данных в несколько потоков, задав параметр -P или соответствующую директиву PARALLEL_TABLES в ora2pgpro.conf.
ora2pgpro может экспортировать данные по указанному SCN. Задать его можно в командной строке в параметре -S или --scn. Можно указать нужный SCN или текущий SCN при первом подключении (значение current). В этом случае у пользователя, подключающегося к БД, должна быть роль SELECT ANY DICTIONARY или SELECT_CATALOG_ROLE — поиск текущего SCN выполняется в представлении v$database.
ora2pgpro -c ora2pgpro.conf -t COPY --scn 16605281
При этом в запрос извлечения данных добавляется такое предложение:
AS OF SCN 16605281
Кроме того, в параметре --scn вместо SCN можно указать выражение с меткой времени, чтобы вернуться к определённой точке в прошлом.
ora2pgpro -c ora2pgpro.conf -t COPY --scn "TO_TIMESTAMP('2021-12-01 00:00:00', 'YYYY-MM-DD HH:MI:SS')"При этом в запрос извлечения данных добавляется такое предложение:
AS OF TIMESTAMP TO_TIMESTAMP('2021-12-01 00:00:00', 'YYYY-MM-DD HH:MI:SS')Пример извлечения только данных предыдущих суток:
ora2pgpro -c ora2pgpro.conf -t COPY --scn "SYSDATE - 1"
ora2pgpro не допускает импорт данных с применением изменений после первого импорта, но указав параметр --cdc_ready, можно экспортировать данные со времени экспорта таблицы. Все SCN для таблиц по умолчанию записываются в файл TABLES_SCN.log, каталог хранения можно задать в параметре -C|--cdc_file.
Эти SCN для каждой таблицы, записанные во время экспорта COPY или INSERT, можно экспортировать с помощью утилиты CDC. Формат записей в файле: tablename:SCN.
По умолчанию ora2pgpro импортирует объекты BLOB как bytea, и целевой столбец создаётся с типом bytea. Если вместо bytea нужно использовать большие объекты, добавьте в команду ora2pgpro параметр --blob_to_lo. При этом создаётся целевой столбец типа oid и BLOB сохраняются как большие объекты с использованием функции lo_from_bytea(). OID, возвращаемый вызовом lo_from_bytea(), записывается в целевой столбец вместо типа bytea. Поскольку используется функция, параметр разрешается только с типами экспорта SHOW_COLUMN, TABLE и INSERT. С типом экспорта COPY использовать этот параметр не допускается.
Если используется тип экспорта COPY или есть огромные BLOB ( > 1ГБ), которые невозможно импортировать функцией lo_from_bytea(), в команду ora2pgpro можно добавить параметр --lo_import. Тогда данные можно будет импортировать в два этапа.
Сначала экспортируйте данные с типом экспорта
COPYилиINSERT, в процессе чего в целевом столбце OID для BLOB проставляются 0, а значение BLOB сохраняется в отдельный файл. Также создаётся скрипт оболочки для импорта файлов BLOB в базу данных с помощью команды psql\lo_importи обновления столбца OID возвращаемыми значениями OID. Скрипт называетсяlo_import-TABLENAME.sh.Затем задайте переменную окружения
PGDATABASEи, возможно,PGHOST,PGPORT,PGUSERи т. д., если их значения отличаются от значений по умолчанию в libpq, и выполните все скриптыlo_import-TABLENAME.sh.
Кроме того, можно вручную выполнить VACUUM FULL для таблицы, чтобы устранить раздувание, вызванное изменением таблицы.
![]() | Примечание |
|---|---|
Ограничение: в таблице должен быть первичный ключ, он используется в предложениях |
Table of Contents
ora2pgpro is a tool used to migrate an Oracle™ database to a Postgres Pro™ compatible schema. It connects your Oracle database, scans it automatically and extracts its structure or data, then generates SQL scripts that you can load into your Postgres Pro database. ora2pgpro can be used for anything from reverse engineering of an Oracle database to huge enterprise database migration or simply replicating some Oracle data into a Postgres Pro database. It does not require any Oracle database knowledge other than providing the parameters needed to connect to the Oracle database.
ora2pgpro consists of a Perl script ora2pgpro and a Perl module Ora2PgPro.pm, the only thing you have to modify is the configuration file ora2pgpro.conf by setting the DSN to the Oracle database and optionally the name of a schema. Once that is done you just have to set the type of export you want: TABLE with constraints, VIEW, MVIEW, TABLESPACE, SEQUENCE, INDEXES, TRIGGER, GRANT, FUNCTION, PROCEDURE, PACKAGE, PARTITION, TYPE, INSERT or COPY, FDW, QUERY, SYNONYM.
By default, ora2pgpro exports to a file that you can load into Postgres Pro with the psql client, but you can also import directly into a Postgres Pro database by setting its DSN into the configuration file. With all configuration options of ora2pgpro.conf, you have full control of what should be exported and how. The following features are included:
- Export full database schema (tables, views, sequences, indexes), with unique, primary, foreign key, and check constraints.
- Export grants/privileges for users and groups.
- Export range/list partitions and subpartitions.
- Export a table selection (by specifying the table names).
- Export Oracle schema to a Postgres Pro schema.
- Export predefined functions, triggers, procedures, packages, and package bodies.
- Export full data or following a
WHEREclause. - Full support of Oracle BLOB objects as Postgres Pro bytea.
- Export Oracle views as Postgres Pro tables.
- Export Oracle user-defined types.
- Provide some basic automatic conversion of PL/SQL code to PL/pgSQL.
- Works on any platform.
- Export Oracle tables as foreign data wrapper tables.
- Export materialized views.
- Show a report of an Oracle database content.
- Migration cost assessment of an Oracle database.
- Migration difficulty level assessment of an Oracle database.
- Migration cost assessment of PL/SQL code from a file.
- Migration cost assessment of Oracle SQL queries stored in a file.
- Export Oracle locator and spatial geometries into PostGIS.
- Export
DBLINKas Oracle FDW. - Export
SYNONYMs as views. - Export
DIRECTORYas external table or directory forexternal_fileextension. - Dispatch a list of SQL orders over multiple Postgres Pro connections.
- Perform a diff between Oracle and Postgres Pro database for test purposes.
ora2pgpro does its best to convert your Oracle database to Postgres Pro automatically, but there is still manual work to do. The Oracle-specific PL/SQL code generated for functions, procedures, packages, and triggers has to be reviewed to match the Postgres Pro syntax. You can find some useful recommendations on porting Oracle PL/SQL code to Postgres Pro PL/pgSQL in Porting from Oracle PL/SQL and Migration Tools in Postgres Pro.
ora2pgpro requires Oracle Instant Client, but it cannot be distributed together with ora2pgpro. You can download the RPM package oracle-instantclient12.1-basic (for example, oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm file) here or from a different source, and install it. ora2pgpro uses an older version 12.1, because newer versions 19 and 21 can be upgraded any time, and your package manager will consider them incompatible with Postgres Pro packages.
If you use a Debian-based system (Debian, Ubuntu, Astra Linux), you have to convert the RPM package to a Debian package using alien or dpkg.
Download the connection script
pgpro-repo-add.sh. You can also do it using wget:$ wget --user your-username --ask-password https://repo.postgrespro.ru/ora2pgpro/keys/pgpro-repo-add.sh
Run it with the rights of
root. If your distribution is supported, the repository will be connected. Note that for a Debian-based system make sure to connect not only themainsection but also thecontribsection since it contains the requiredlibdbd-oracle-perlpackage.
Install the ora2pgpro package using your package manager. Depending on your system, it can be one of the following:
apt-get: Debian, Ubuntu, Astra, AltLinuxdnf: Red Hat Enterprise Linux (RHEL) systems and its derivatives: Red OS, Rosayum: older Rosa versionszypper: SLES
In any case, specify the parameters for install ora2pgpro.
ora2pgpro configuration can be as simple as choosing the Oracle database to export and choosing the export type.
The full control of the Oracle database migration is managed in a single configuration file named ora2pgpro.conf. The format of this file consists of a directive name in upper case followed by a tab character and a value. Comments are lines beginning with a #. There is no specific order to place the configuration directives, they are set at the time they are read in the configuration file.
For configuration directives that just take a single value, you can use them multiple times in the configuration file but only the last occurrence found in the file will be used. For configuration directives that allow a list of values, you can use it multiple times, the values will be appended to the list. If you use the IMPORT directive to load a custom configuration file, directives defined in this file will be stored from the place the IMPORT directive is found, so it is better to put it at the end of the configuration file.
Values set in the command line options override values from the configuration file.
First of all, make sure that libraries and binaries path include the Oracle Instant Client installation:
export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib export PATH="/usr/lib/oracle/11.2/client64/bin:$PATH"
By default, ora2pgpro looks for /etc/ora2pgpro/ora2pgpro.conf configuration file, if the file exists, you can simply execute:
/usr/local/bin/ora2pgpro
If you want to call another configuration file, give the path as the command-line argument:
/usr/local/bin/ora2pgpro -c /etc/ora2pgpro/new_ora2pgpro.conf
Here are all command-line parameters available when using ora2pgpro:
ora2pgpro [-dhpqv --estimate_cost --dump_as_html] [--option value]
-a,--allowComma-separated list of objects to allow from export. Can be used with
SHOW_COLUMNtoo.-b,--basedirSet the default output directory where files resulting from exports will be stored.
-c,--confSet an alternative configuration file other than the default
/etc/ora2pgpro/ora2pgpro.conf.-C,--cdc_fileFile used to store/read SCN per table during export. Default:
TABLES_SCN.login the current directory. This is the file written by the--cdc_readyoption.-d,--debugEnable verbose output.
-D,--data_typeAllow custom type replacement in command line.
-e,--excludeComma-separated list of objects to exclude from export. Can be used with
SHOW_COLUMNtoo.-h,--helpPrint this short help.
-g,--grant_objectExtract privilege for the given object type. See possible values in
GRANT_OBJECTconfiguration.-i,--inputFile containing Oracle PL/SQL code to convert with no Oracle database connection initiated.
-j,--jobsNumber of parallel processes to send data to Postgres Pro.
-J,--copiesNumber of parallel connections to extract data from Oracle.
-l,--logSet a log file. Default is
stdout.-L,--limitNumber of tuples extracted from Oracle and stored in memory before writing, default: 10000.
-n,--namespaceSet the Oracle schema to extract from.
-N,--pg_schemaSet Postgres Pro
search_path.-o,--outSet the path to the output file where SQL will be written. Default:
output.sqlin running directory.-p,--plsqlEnable PL/SQL to PL/pgSQL code conversion.
-P,--parallelNumber of parallel tables to extract at the same time.
-q,--quietDisable progress bar.
-r,--relativeUse
\irinstead of\iin the psql scripts generated.-s,--sourceSet the Oracle DBI data source.
-S,--scnSet the Oracle System Change Number (SCN) to use to export data. It will be used in the
WHEREclause to get the data. It is used withCOPYorINSERT.-t,--typeSet the export type. It will override the one given in the configuration file (
TYPE).-T,--temp_dirSet a distinct temporary directory when two or more ora2pgpro instances run in parallel.
-u,--userSet the Oracle database connection user.
ORA2PG_USERenvironment variable can be used instead.-v,--versionShow ora2pgpro version and exit.
-w,--passwordSet the password of the Oracle database user.
ORA2PG_PASSWDenvironment variable can be used instead.-W,--whereSet the
WHEREclause to apply to the Oracle query to retrieve data. Can be used multiple times.--forceownerForce ora2pgpro to set tables and sequences owner like in Oracle database. If the value is set to a username, this one will be used as the objects owner. By default it is the user used to connect to the Postgres Pro database that will be the owner.
--nls_langSet the Oracle
NLS_LANGclient encoding.--client_encodingSet the Postgres Pro client encoding.
--view_as_tableComma-separated list of views to export as table.
--estimate_costActivate the migration cost evaluation with
SHOW_REPORT.--cost_unit_valueNumber of minutes for a cost evaluation unit. Default: 5 minutes, corresponds to a migration conducted by a Postgres Pro expert. Set it to 10 if this is your first migration.
--dump_as_htmlForce ora2pgpro to dump report in HTML, used only with
SHOW_REPORT. Default is to dump report as simple text.--dump_as_csvAs above but force ora2pgpro to dump report in CSV.
--dump_as_sheetReport migration assessment with one CSV line per database.
--init_projectInitialize a typical ora2pgpro project tree. Top directory will be created under the project base directory.
--project_baseDefine the base directory for ora2pgpro project trees. Default is the current directory.
--print_headerUsed with
--dump_as_sheetto print the CSV header, especially for the first run of ora2pgpro.--human_days_limitSet the number of man-days limit where the migration assessment level switches from B to C. Default is set to 5 man-days.
--audit_userComma-separated list of usernames to filter queries in the
AUDIT_USERtable. Used only withSHOW_REPORTandQUERYexport type.--pg_dsnSet the data source to Postgres Pro for direct import.
--pg_userSet the Postgres Pro user to be used.
--pg_pwdSet the Postgres Pro password to be used.
--count_rowsForce ora2pgpro to perform a real row count in
TEST,TEST_COUNT, andSHOW_TABLEactions.--no_headerDo not append ora2pgpro header to output file.
--oracle_speedUse to know at which speed Oracle is able to send data. No data will be processed or written.
--ora2pg_speedUse to know at which speed ora2pgpro is able to send transformed data. Nothing will be written.
--blob_to_loExport BLOBs as large objects, can only be used with action
SHOW_COLUMN,TABLE, andINSERT.--cdc_readyUse current SCN per table to export data and register them into a file named
TABLES_SCN.logby default. It can be changed using-C|--cdc_file.--lo_importUse psql \lo_import command to import BLOBs as large objects. Can be used to import data with
COPYand import the large object manually in a second pass. It is required for BLOBs larger than 1GB.--mview_as_tableComma-separated list of materialized views to export as regular tables.
--drop_if_existsDrop the object before creation if it exists.
ora2pgpro returns 0 on success, 1 on error. It returns 2 when a child process has been interrupted and you received the warning message: “WARNING: an error occurs during data export. Please check what's happen.” Most of the time this is an OOM issue, first try reducing DATA_LIMIT value.
Note that performance might be improved by updating stats on Oracle:
DBMS_STATS.GATHER_SCHEMA_STATS DBMS_STATS.GATHER_DATABASE_STATS DBMS_STATS.GATHER_DICTIONARY_STATS
The two options --project_base and --init_project, when used, indicate that ora2pgpro has to create a project template with a work tree, a configuration file and a script to export all objects from the Oracle database. Here is a sample of the command usage:
ora2pgpro --project_base /app/migration/ --init_project test_project Creating project test_project. /app/migration/test_project/ schema/ dblinks/ directories/ functions/ grants/ mviews/ packages/ partitions/ procedures/ sequences/ synonyms/ tables/ tablespaces/ triggers/ types/ views/ sources/ functions/ mviews/ packages/ partitions/ procedures/ triggers/ types/ views/ data/ config/ reports/ Generating generic configuration file Creating script export_schema.sh to automate all exports. Creating script import_all.sh to automate all imports.
It creates a generic configuration file where you define the Oracle database connection and a shell script called export_schema.sh. The sources/ directory will contain the Oracle code, the schema/ will contain the code ported to Postgres Pro. The reports/ directory will contain the HTML reports with the migration cost assessment.
If you want to use your own default configuration file, use the -c option to give the path to that file. Rename it with the .dist suffix if you want ora2pgpro to apply the generic configuration values, the configuration file will be copied untouched otherwise.
Once you have set the connection to the Oracle database, you can execute the script export_schema.sh that will export all object type from your Oracle database and output DDL files into the schema subdirectories. At end of the export, it will give you the command to export data later when the import of the schema will be done and verified.
You can choose to load the DDL files generated manually or use the second script import_all.sh to import those files interactively. If this kind of migration is not currently in progress for you, it is recommended you to use those scripts.
The following configuration directives control the access to the Oracle database.
ORACLE_HOMEUsed to set
ORACLE_HOMEenvironment variable to the Oracle libraries required by theDBD::OraclePerl module.ORACLE_DSNThis directive is used to set the data source name in the form of standard DBI DSN. For example:
dbi:Oracle:host=oradb_host.myhost.com;sid=DB_SID;port=1521
or
dbi:Oracle:DB_SID
On 18c, this could be for example:
dbi:Oracle:host=192.168.1.29;service_name=pdb1;port=1521
For the second notation, the SID should be declared in the file
$ORACLE_HOME/network/admin/tnsnames.oraor in the path given to theTNS_ADMINenvironment variable.ORACLE_DSNORACLE_PWDThese two directives are used to define the user and password for the Oracle database connection. Note that if you can, it is better to log in as Oracle super admin to avoid grants problem during the database scan and be sure that nothing is missing.
If you do not supply a credential with
ORACLE_PWD, and you have installed theTerm::ReadKeyPerl module, ora2pgpro will ask for the password interactively. IfORACLE_USERis not set, it will be asked interactively too.To connect to a local Oracle instance with connections as
SYSDBA, you have to setORACLE_USERto/and an empty password.USER_GRANTSSet this directive to 1 if you connect to the Oracle database as a simple user and do not have enough grants to extract things from the
DBA_tables. It will use tablesALL_instead.Warning: if you use the export type
GRANT, you must set this configuration option to 0, or it will not work.TRANSACTIONThis directive may be used if you want to change the default isolation level of the data export transaction. Default is to set the level to a serializable transaction to ensure data consistency. The allowed values for this directive are:
- readonly: 'SET TRANSACTION READ ONLY',
- readwrite: 'SET TRANSACTION READ WRITE',
- serializable: 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE'
- committed: 'SET TRANSACTION ISOLATION LEVEL READ COMMITTED',
ORA_INITIAL_COMMANDThis directive can be used to send an initial command to Oracle, just after the connection, for example, to unlock a policy before reading objects or to set some session parameters. This directive can be used multiple times.
If your Oracle Client configuration file already includes the encryption method, then DBD:Oracle uses those settings to encrypt the connection while you extract the data. For example, if you have configured the Oracle Client configuration file (sqlnet.or or .sqlnet) with the following information:
# Configure encryption of connections to Oracle SQLNET.ENCRYPTION_CLIENT = required SQLNET.ENCRYPTION_TYPES_CLIENT = (AES256, RC4_256) SQLNET.CRYPTO_SEED = 'should be 10-70 random characters'
Any tool that uses the Oracle client to talk to the database will be encrypted if you set up session encryption like above.
For example, Perl DBI uses DBD-Oracle, which uses the Oracle client for actually handling database communication. If the installation of Oracle client used by Perl is set up to request encrypted connections, then your Perl connection to the Oracle database will also be encrypted.
Once you have set the Oracle database DSN, you can run ora2pgpro to see if it works:
ora2pgpro -t SHOW_VERSION -c config/ora2pgpro.conf
This will show the Oracle database server version. You can test your installation as most problems take place here, the other configuration steps are more technical.
If the output.sql file has not exported anything other than the Postgres Pro transaction header and footer, there are two possible reasons:
The Perl script ora2pgpro dumps an
ORA-XXXerror: that means that your DSN or login information is wrong, check the error and your settings, and try again.The Perl script says nothing, and the output file is empty: the user lacks permission to extract something from the database. Try to connect to Oracle as super user or take a look at the directive
USER_GRANTSabove and in the next section, especially theSCHEMAdirective.
The Oracle database export can be limited to a specific schema or namespace, this can be mandatory following the database connection user.
SCHEMAThis directive is used to set the schema name to use during export. For example,
SCHEMA APPSwill extract objects associated to theAPPSschema.When no schema name is provided and
EXPORT_SCHEMAis enabled, ora2pgpro will export all objects from all schemas of the Oracle instance with their names prefixed with the schema name.EXPORT_SCHEMABy default, the Oracle schema is not exported into the Postgres Pro database, and all objects are created under the default Postgres Pro namespace. If you also want to export this schema and create all objects under this namespace, set the
EXPORT_SCHEMAdirective to 1. This will set the schemasearch_pathat the top of the export SQL file to the schema name set in theSCHEMAdirective with the defaultpg_catalogschema. If you want to change this path, use the directivePG_SCHEMA.CREATE_SCHEMAEnable/disable the CREATE SCHEMA command at starting of the output file. It is enabled by default and concerns the
TABLEexport type.COMPILE_SCHEMABy default ora2pgpro will only export valid PL/SQL code. You can force Oracle to compile again the invalidated code to get a chance to have it obtain the valid status and then be able to export it.
Enable this directive to force Oracle to compile schema before exporting code. When this directive is enabled, and
SCHEMAis set to a specific schema name, only invalid objects in this schema will be recompiled. IfSCHEMAis not set, then all schemas will be recompiled. To force recompile invalid objects in a specific schema, setCOMPILE_SCHEMAto the schema name you want to recompile.This will ask to Oracle to validate the PL/SQL code that could have been invalidated after an export/import, for example. The
VALIDorINVALIDstatus applies to functions, procedures, packages, and user-defined types. It also concerns disabled triggers.EXPORT_INVALIDIf the above configuration directive is not enough to validate your PL/SQL code, enable this configuration directive to allow export of all PL/SQL code even if it is marked as invalid. The
VALIDorINVALIDstatus applies to functions, procedures, packages and user-defined types.PG_SCHEMAAllows you to define/force the Postgres Pro schema to use. By default, if you set
EXPORT_SCHEMAto 1, the Postgres Prosearch_pathwill be set to the schema name exported set as the value of theSCHEMAdirective.The value can be a comma-separated list of schema names but not when using the
TABLEexport type because in this case it will generate the CREATE SCHEMA statement, and it does not support multiple schema names. For example, if you setPG_SCHEMAto something likeuser_schema, public, the search path will be set like this:SET search_path = user_schema, public;
This forces the use of another schema (here
user_schema) than the one from Oracle schema set inSCHEMAdirective.You can also set the default
search_pathfor the Postgres Pro user you are using to connect to the destination database by using:ALTER ROLE username SET search_path TO user_schema, public;
In this case, you do not have to set
PG_SCHEMA.SYSUSERSWithout an explicit schema, ora2pgpro will export all objects that do not belong to the system schema or role:
SYSTEM,CTXSYS,DBSNMP,EXFSYS,LBACSYS,MDSYS,MGMT_VIEW, OLAPSYS,ORDDATA,OWBSYS,ORDPLUGINS,ORDSYS,OUTLN, SI_INFORMTN_SCHEMA,SYS,SYSMAN,WK_TEST,WKSYS,WKPROXY, WMSYS,XDB,APEX_PUBLIC_USER,DIP,FLOWS_020100,FLOWS_030000, FLOWS_040100,FLOWS_010600,FLOWS_FILES,MDDATA,ORACLE_OCM, SPATIAL_CSW_ADMIN_USR,SPATIAL_WFS_ADMIN_USR,XS$NULL,PERFSTAT, SQLTXPLAIN,DMSYS,TSMSYS,WKSYS,APEX_040000,APEX_040200, DVSYS,OJVMSYS,GSMADMIN_INTERNAL,APPQOSSYS,DVSYS,DVF, AUDSYS,APEX_030200,MGMT_VIEW,ODM,ODM_MTR,TRACESRV,MTMSYS, OWBSYS_AUDIT,WEBSYS,WK_PROXY,OSE$HTTP$ADMIN, AURORA$JIS$UTILITY$,AURORA$ORB$UNAUTHENTICATED, DBMS_PRIVILEGE_CAPTURE,CSMIG,MGDSYS,SDE,DBSFWUSER
Following your Oracle installation, you may have several other system roles defined. To append these users to the schema exclusion list, set the
SYSUSERSconfiguration directive to a comma-separated list of system users to exclude. For example:SYSUSERS INTERNAL,SYSDBA,BI,HR,IX,OE,PM,SH
This will add users
INTERNALandSYSDBAto the schema exclusion list.FORCE_OWNERBy default the owner of the database objects is the one you are using to connect to Postgres Pro using psql. If you use another user (
postgres, for example), you can force ora2pgpro to set the object owner to be the one used in the Oracle database by setting the directive to 1, or to a completely different username by setting the directive value to that username.FORCE_SECURITY_INVOKERora2pgpro use the function security privileges set in Oracle, and it is often defined as
SECURITY DEFINER. If you want to override those security privileges for all functions and useSECURITY INVOKERinstead, enable this directive.USE_TABLESPACEWhen enabled, this directive forces ora2pgpro to export all tables, indexes constraints and indexes using the tablespace name defined in Oracle database. This works only with tablespaces that are not
TEMP,USERS, andSYSTEM.WITH_OIDActivating this directive will force ora2pgpro to add
WITH OIDSwhen creating tables or views as tables. Default is the same as in Postgres Pro, disabled.LOOK_FORWARD_FUNCTIONList of schemas to get functions/procedures meta information that is used in the current schema export. When replacing call to function with
OUTparameters, if a function is declared in another package then the function call rewriting can not be done because ora2pgpro only knows about functions declared in the current schema. By setting a comma-separated list of schemas as the value of this directive, ora2pgpro will look forward in these packages for all functions, procedures and packages declaration before proceeding to current schema export.NO_FUNCTION_METADATAForce ora2pgpro to not look for function declaration. Note that this will prevent ora2pgpro to rewrite function replacement call if needed. Do not enable it unless looking forward at function breaks other export.
The export action is performed following a single configuration directive TYPE, some others add more control on what should be really exported.
TYPEHere are the different values of the
TYPEdirective, default isTABLE:TABLE: Extract all tables with indexes, primary keys, unique keys, foreign keys, and check constraints.VIEW: Extract only views.GRANT: Extract roles converted to Postgres Pro groups, users, and grants on all objects.SEQUENCE: Extract all sequences and their last positions.TABLESPACE: Extract storage spaces for tables and indexes.TRIGGER: Extract triggers defined following actions.FUNCTION: Extract functions.PROCEDURE: Extract procedures.PACKAGE: Extract packages and package bodies.INSERT: Extract data as INSERT statement.COPY: Extract data as COPY statement.PARTITION: Extract range and list Oracle partitions with subpartitions.TYPE: Extract user-defined Oracle type.FDW: Export Oracle tables as foreign tables for oracle_fdw.MVIEW: Export materialized views.QUERY: Try to automatically convert Oracle SQL queries.DBLINK: Generate Oracle foreign data wrapper server to use asdblink.SYNONYM: Export Oracle synonyms as views on other schema's objects.DIRECTORY: Export Oracle directories asexternal_fileextension objects.LOAD: Dispatch a list of queries over multiple Postgres Pro connections.TEST: Perform a diff between Oracle and Postgres Pro database.TEST_COUNT: Perform a row count diff between Oracle and Postgres Pro table.TEST_VIEW: Perform a count on both sides of number of rows returned by views.TEST_DATA: Perform data validation check on rows on both sides.SHOW_VERSION: Display Oracle version.SHOW_SCHEMA: Display the list of schemas available in the database.SHOW_TABLE: Display the list of tables available.SHOW_COLUMN: Display the list of tables columns available and the ora2pgpro conversion type from Oracle to Postgres Pro that will be applied. It will also warn you if there are Postgres Pro reserved words in Oracle object names.SHOW_REPORT: Show a detailed report of the Oracle database content to evaluate the content of the database to migrate, in terms of objects and cost to end the migration.
Only one type of export can be performed at the same time so the
TYPEdirective must be unique. If you have more than one, only the last found in the file will be registered.Some export type can not or should not be loaded directly into the Postgres Pro database and still require little manual editing. This is the case for
GRANT,TABLESPACE,TRIGGER,FUNCTION,PROCEDURE,TYPE,QUERY, andPACKAGEexport types, especially if you have PL/SQL code or Oracle-specific SQL in it.For
TABLESPACE, you must ensure that the file path exists in the system and forSYNONYM, ensure that the object's owners and schemas correspond to the new Postgres Pro database design.Note that you can chain multiple export by giving to the
TYPEdirective a comma-separated list of export type, but in this case you must not useCOPYorINSERTwith other export type.ora2pgpro will convert Oracle partition using table inheritance, trigger, and functions. For more information, see Table Partitioning.
The
TYPEexport allows export of user-defined Oracle types. If you do not use the--plsqlcommand-line parameter, it dumps Oracle user type as-is, else ora2pgpro will try to convert it to Postgres Pro syntax.Here is an example of the
SHOW_COLUMNoutput:[2] TABLE CURRENT_SCHEMA (1 rows) (Warning: 'CURRENT_SCHEMA' is a reserved word in PostgreSQL) CONSTRAINT : NUMBER(22) => bigint (Warning: 'CONSTRAINT' is a reserved word in PostgreSQL) FREEZE : VARCHAR2(25) => varchar(25) (Warning: 'FREEZE' is a reserved word in PostgreSQL) ... [6] TABLE LOCATIONS (23 rows) LOCATION_ID : NUMBER(4) => smallint STREET_ADDRESS : VARCHAR2(40) => varchar(40) POSTAL_CODE : VARCHAR2(12) => varchar(12) CITY : VARCHAR2(30) => varchar(30) STATE_PROVINCE : VARCHAR2(25) => varchar(25) COUNTRY_ID : CHAR(2) => char(2)
Those extraction keywords are used only to display the requested information and exit. This allows you to quickly know on what you are going to work with.
The
SHOW_COLUMNallows another ora2pgpro command-line option:--allow relnameor-a relnameto limit the displayed information to the given table.The
SHOW_ENCODINGexport type will display theNLS_LANGandCLIENT_ENCODINGvalues that ora2pgpro will use, and the real encoding of the Oracle database with the corresponding client encoding that could be used with Postgres Pro.ora2pgpro allows you to export your Oracle table definition to be used with the oracle_fdw foreign data wrapper. By using type
FDW, your Oracle tables will be exported as follows:CREATE FOREIGN TABLE oratab ( id integer NOT NULL, text character varying(30), floating double precision NOT NULL ) SERVER oradb OPTIONS (table 'ORATAB');
Now you can use the table like a regular Postgres Pro table.
There is also a more advanced report with migration cost, see the section called “Migration Cost Assessment”.
ESTIMATE_COSTActivate the migration cost evaluation. Must only be used with
SHOW_REPORT,FUNCTION,PROCEDURE,PACKAGE, andQUERYexport type. Default is disabled. You may want to use the--estimate_costcommand-line option instead to activate this functionality. Note that enabling this directive will forcePLSQL_PGSQLactivation.COST_UNIT_VALUESet the value in minutes of the migration cost evaluation unit. Default is five minutes per unit. See
--cost_unit_valueto change the unit value in the command line.DUMP_AS_HTMLBy default, when using
SHOW_REPORT, the migration report is generated as simple text, enabling this directive will force ora2pgpro to create a report in HTML format.HUMAN_DAYS_LIMITUse this directive to redefine the number of man-days limit where the migration assessment level must switch from B to C. Default is set to 10 man-days.
JOBSThis configuration directive adds multiprocess support to
COPY,FUNCTION, andPROCEDUREexport type, the value is the number of processes to use. By default multiprocess is disabled.This directive is used to set the number of cores to be used to parallelize data import into Postgres Pro. During
FUNCTIONorPROCEDUREexport type each function will be translated to PL/pgSQL using a new process, the performances gain can be very important when you have many functions to convert.There is no limitation in parallel processing other than the number of cores and the Postgres Pro I/O performance capabilities.
Doesn't work under Windows Operating System, it is simply disabled.
ORACLE_COPIESThis configuration directive adds multiprocess support to extract data from Oracle. The value is the number of processes to use to parallelize the select query. By default parallel query is disabled.
The parallelism is built on splitting the query following of the number of cores given as value to
ORACLE_COPIESas follows:SELECT * FROM MYTABLE WHERE ABS(MOD(COLUMN, ORACLE_COPIES)) = CUR_PROC
Here
COLUMNis a technical key like a primary or unique key where split will be based and the current core used by the query (CUR_PROC). You can also force the column name to use with theDEFINED_PKconfiguration directive.Doesn't work under Windows Operating System, it is simply disabled.
DEFINED_PKThis directive is used to define the technical key to be used to split the query between number of cores set with the
ORACLE_COPIESvariable. For example:DEFINED_PK EMPLOYEES:employee_id
The parallel query that will be used supposing that
-JorORACLE_COPIESis set to 8:SELECT * FROM EMPLOYEES WHERE ABS(MOD(employee_id, 8)) = N
Here N is the current process forked starting from 0.
PARALLEL_TABLESThis directive is used to define the number of tables that will be processed in parallel for data extraction. The limit is the number of cores on your machine. ora2pgpro will open one database connection for each parallel table extraction. This directive, when more than 1, will invalidate
ORACLE_COPIESbut notJOBS, so the real number of process that will be used isPARALLEL_TABLES*JOBS.Note that this directive when set more that 1 will also automatically enable the
FILE_PER_TABLEdirective if you are exporting to files. This is used to export tables and views in separate files.Use
PARALLEL_TABLESto use parallelism withCOPY,INSERT, andTEST_DATAactions. It is also useful withTEST,TEST_COUNT, andSHOW_TABLEif--count_rowsis used for real row count.DEFAULT_PARALLELISM_DEGREEYou can force ora2pgpro to use
/*+ PARALLEL(tbname, degree) */hint in each query used to export data from Oracle by setting a value more than 1 to this directive. A value of 0 or 1 disables the use of the parallel hint. Default is disabled.FDW_SERVERThis directive is used to set the name of the foreign data server that is used in the CREATE SERVER name FOREIGN DATA WRAPPER oracle_fdw command. This name will then be used in the CREATE FOREIGN TABLE commands and to import data using oracle_fdw. By default no foreign server is defined. This only concerns export types
FDW,COPY, andINSERT. For export typeFDW, the default value isorcl.FDW_IMPORT_SCHEMASchema where foreign tables for data migration will be created. If you use several instances of ora2pgpro for data migration through the foreign data wrapper, you might need to change the name of the schema for each instance. Default:
ora2pg_fdw_import.DROP_FOREIGN_SCHEMABy default ora2pgpro drops the temporary schema
ora2pg_fdw_importused to import the Oracle foreign schema before each new import. If you want to preserve the existing schema because of modifications or the use of a third-party server, disable this directive.EXTERNAL_TO_FDWThis directive, enabled by default, allows to export Oracle external tables as file_fdw foreign tables. To not export these tables at all, set the directive to 0.
INTERNAL_DATE_MAXInternal timestamps retrieved from custom type are extracted in the following format:
01-JAN-77 12.00.00.000000 AM. It is impossible to know the exact century that must be used, so by default any year below 49 will be added to 2000 and others to 1900. You can use this directive to change the default value 49. This is only relevant if you have a user-defined type with a columntimestamp.AUDIT_USERSet the comma-separated list of usernames that must be used to filter queries from the
DBA_AUDIT_TRAILtable. Default is to not scan this table and to never look for queries. This parameter is used only withSHOW_REPORTandQUERYexport types with no input file for queries. Note that queries will be normalized before output unlike when a file is given at input using the-ioption.FUNCTION_CHECKDisable this directive if you want to disable
check_function_bodies.SET check_function_bodies = false;
It disables validation of the function body string during CREATE FUNCTION. Default is to use the
postgresql.confsetting that enables it by default.ENABLE_BLOB_EXPORTExporting BLOB takes time, in some circumstances you may want to export all data except the BLOB columns. In this case disable this directive and the BLOB columns will not be included into data export. Take care that the target bytea column do not have a
NOT NULLconstraint.DATA_EXPORT_ORDERBy default data export order will be done by sorting on table names. If you have huge tables at the end of alphabetic order and you are using multiprocess, it can be better to set the sort order on size so that multiple small tables can be processed before the largest tables finish. In this case set this directive to size. Possible values are
nameandsize. Note that export typeSHOW_TABLEandSHOW_COLUMNwill use this sort order too, not onlyCOPYorINSERTexport type.
You may want to export only a part of an Oracle database, here is a set of configuration directives that will allow you to control what parts of the database should be exported.
ALLOWThis directive allows you to set a list of objects on which the export must be limited, excluding all other objects in the same type of export. The value is a space or comma-separated list of objects names to export. You can include valid regex into the list. For example:
ALLOW EMPLOYEES SALE_.* COUNTRIES .*_GEOM_SEQ
This will export objects with name
EMPLOYEES,COUNTRIES, all objects beginning withSALE_, and all objects with a name ending by_GEOM_SEQ. The object depends on the export type. Note that regex will not work with 8i database, you must use the%placeholder instead, ora2pgpro will use theLIKEoperator.This is the manner to declare global filters that will be used with the current export type. You can also use extended filters that will be applied to specific objects or only on their related export type. For example:
ora2pgpro -p -c ora2pgpro.conf -t TRIGGER -a 'TABLE[employees]'
This will limit the export of triggers to those defined on table
employees. If you want to extract all triggers but not someINSTEAD OFtriggers:ora2pgpro -c ora2pgpro.conf -t TRIGGER -e 'VIEW[trg_view_.*]'
Or a more complex form:
ora2pgpro -p -c ora2pgpro.conf -t TABLE -a 'TABLE[EMPLOYEES]' \ -e 'INDEX[emp_.*];CKEY[emp_salary_min]'This command will export the definition of the
employeestable but will exclude all index beginning withemp_and theCHECKconstraint calledemp_salary_min.When exporting partition, you can exclude some partition tables by using the following command:
ora2pgpro -p -c ora2pgpro.conf -t PARTITION -e 'PARTITION[PART_199.* PART_198.*]'
This will exclude partitioned tables for years 1980 to 1999 from the export but not the main partition table. The trigger will also be adapted to exclude those tables.
With
GRANTexport, you can use this extended form to exclude some users from the export, or limit the export to some others:ora2pgpro -p -c ora2pgpro.conf -t GRANT -a 'USER1 USER2' or ora2pgpro -p -c ora2pgpro.conf -t GRANT -a 'GRANT[USER1 USER2]'
The latter will limit export grants to users
USER1andUSER2. But if you do not want to export grants on some functions for these users, for example:ora2pgpro -p -c ora2pgpro.conf -t GRANT -a 'USER1 USER2' -e 'FUNCTION[adm_.*];PROCEDURE[adm_.*]'
Oracle does not allow the use of look-ahead expression so you may want to exclude some objects that match the
ALLOWregexp you have defined. For example, if you want to export all table starting withEbut not those starting withEXP, it is not possible to do that in a single expression. This is why you can start a regular expression with the!character to exclude object matching the regexp given just after. The previous example can be written as follows:ALLOW E.* !EXP.*
It will be translated into the following in the object search expression:
REGEXP_LIKE(..., '^E.*$') AND NOT REGEXP_LIKE(..., '^EXP.*$')
EXCLUDEThis directive is the opposite of the previous one, it allows you to define a space or comma-separated list of object name to exclude from the export. You can include a valid regular expression into the list. For example:
EXCLUDE EMPLOYEES TMP_.* COUNTRIES
This will exclude objects with names
EMPLOYEES,COUNTRIES, and all tables beginning withtmp_.For example, you can ban from export unwanted functions with this directive:
EXCLUDE write_to_.* send_mail_.*
This example will exclude all functions, procedures, or functions in a package with the name beginning with those regex. Note that regex will not work with 8i database, you must use the
%placeholder instead, ora2pgpro will use theNOT LIKEoperator. See above (directiveALLOW) for the extended syntax.NO_EXCLUDED_TABLEBy default ora2pgpro excludes from export some Oracle “garbage” tables that should never be part of an export. This behavior generates a lot of
REGEXP_LIKEexpressions which are slowing down the export when looking at tables. To disable this behavior, enable this directive, but you will have to exclude or clean up later by yourself the unwanted tables. The regexp used to exclude the table are defined in the array@EXCLUDED_TABLESinlib/Ora2Pgpro.pm. Note that this behavior is independent to theEXCLUDEconfiguration directive.VIEW_AS_TABLESet which view to export as a table. By default none. The value must be a list of view names or regexp separated by space or comma. If the object name is a view and the export type is
TABLE, the view will be exported as a CREATE TABLE statement. If export type isCOPYorINSERT, the corresponding data will be exported. See Exporting Views as Postgres Pro Tables for more details.MVIEW_AS_TABLESet which materialized view to export as a table. By default none. Value must be a list of materialized view names or regexp separated by space or comma. If the object name is a materialized view and the export type is
TABLE, the view will be exported as a CREATE TABLE statement. If export type isCOPYorINSERT, the corresponding data will be exported.NO_VIEW_ORDERINGBy default ora2pgpro tries to order views to avoid error at the import time with nested views. With a huge number of views, this can take a very long time, you can bypass this ordering by enabling this directive.
GRANT_OBJECTWhen exporting grants, you can specify a comma-separated list of objects for which privileges will be exported. Default is export for all objects. Here are the possibles values
TABLE,VIEW,MATERIALIZED VIEW,SEQUENCE,PROCEDURE,FUNCTION,PACKAGE BODY,TYPE,SYNONYM,DIRECTORY. Only one object type is allowed at a time. For example, set it toTABLEif you just want to export privileges on tables. You can use the-goption to overwrite it.WHEREThis directive allows you to specify a
WHEREclause filter when dumping the contents of tables. Value constructs as follows:TABLE_NAME[WHERE_CLAUSE], or if you have only one where clause for each table just put the where clause as the value. Both are possible too. Here are some examples:# Global where clause applying to all tables included in the export WHERE 1=1 # Apply the where clause only on table TABLE_NAME WHERE TABLE_NAME[ID1='001'] # Applies two different clause on tables TABLE_NAME and OTHER_TABLE # and a generic where clause on DATE_CREATE to all other tables WHERE TABLE_NAME[ID1='001' OR ID1='002] DATE_CREATE > '2001-01-01' OTHER_TABLE[NAME='test']
Any where clause not included into a table name bracket clause will be applied to all exported table including the tables defined in the
WHEREclause. TheseWHEREclauses are very useful if you want to archive some data or to the opposite only export some recent data.To be able to test data import quickly, it is useful to limit data export to the first thousand tuples of each table. For Oracle, define the following clause:
WHERE ROWNUM < 1000
This can also be restricted to some tables data export.
The command-line option
-Wor--wherewill override this directive for the global part and per table if the table names are the same.TOP_MAXThis directive is used to limit the number of items shown in the top N lists like the top list of tables per number of rows and the top list of largest tables in megabytes. By default it is set to 10 items.
LOG_ON_ERROREnable this directive if you want to continue direct data import on error. When ora2pgpro receives an error in the COPY or INSERT statement from Postgres Pro, it will log the statement to a file called
TABLENAME_error.login the output directory and continue to the next bulk of data. Like this you can try to fix the statement and manually reload the error log file. Default is disabled: abort import on error.REPLACE_QUERYSometimes you may want to extract data from an Oracle table but you need a custom query for that. Not just a SELECT * FROM table like ora2pgpro does but a more complex query. This directive allows you to overwrite the query used by ora2pgpro to extract data. The format is
TABLENAME[SQL_QUERY]. If you have multiple table to extract by replacing the ora2pgpro query, you can define multipleREPLACE_QUERYlines.REPLACE_QUERY EMPLOYEES[SELECT e.id,e.fisrtname,lastname FROM EMPLOYEES e JOIN EMP_UPDT u ON (e.id=u.id AND u.cdate>'2014-08-01 00:00:00')]
Several directives can be used to control the way ora2pgpro will export the Oracle text search indexes. By default CONTEXT indexes will be exported to Postgres Pro FTS indexes but CTXCAT indexes will be exported as indexes using the pg_trgm extension.
CONTEXT_AS_TRGMForce ora2pgpro to translate Oracle text indexes into Postgres Pro indexes using the pg_trgm extension. Default is to translate
CONTEXTindexes intoFTSindexes andCTXCATindexes using pg_trgm. Most of the time using pg_trgm is enough, this is what this directive is for. You need to create the pg_trgm extension into the destination database before importing the objects.FTS_INDEX_ONLYBy default, ora2pgpro creates a function-based index to translate Oracle text indexes.
CREATE INDEX ON t_document USING gin(to_tsvector('pg_catalog.french', title));You will have to rewrite the
CONTAIN()clause usingto_tsvector(), for example:SELECT id,title FROM t_document WHERE to_tsvector(title) @@ to_tsquery('search_word');To force ora2pgpro to create an extra tsvector column with dedicated triggers for
FTSindexes, disable this directive. In this case, ora2pgpro will add the column as follows:ALTER TABLE t_document ADD COLUMN tsv_title tsvector;
Then update the column to compute
FTSvectors if the data have been loaded before UPDATE t_document SET tsv_title = to_tsvector('pg_catalog.french', coalesce(title,''));. To automatically update the column when a modification in the title column appears, ora2pgpro adds the following trigger:CREATE FUNCTION tsv_t_document_title() RETURNS trigger AS $$ BEGIN IF TG_OP = 'INSERT' OR new.title != old.title THEN new.tsv_title := to_tsvector('pg_catalog.french', coalesce(new.title,'')); END IF; return new; END $$ LANGUAGE plpgsql; CREATE TRIGGER trig_tsv_t_document_title BEFORE INSERT OR UPDATE ON t_document FOR EACH ROW EXECUTE PROCEDURE tsv_t_document_title();When the Oracle text index is defined over multiple columns, ora2pgpro will use
setweight()to set a weight in the order of the column declaration.FTS_CONFIGUse this directive to force text search configuration to use. When it is not set, ora2pgpro will autodetect the stemmer used by Oracle for each index and
pg_catalog.englishif the information is not found.USE_UNACCENTIf you want to perform your text search in an accent-insensitive way, enable this directive. ora2pgpro will create a helper function over
unaccent()and the pg_trgm indexes using this function. With FTS, ora2pgpro will redefine your text search configuration, for example:CREATE TEXT SEARCH CONFIGURATION fr (COPY = french); ALTER TEXT SEARCH CONFIGURATION fr ALTER MAPPING FOR hword, hword_part, word WITH unaccent, french_stem;Then set the
FTS_CONFIGora2pgpro.confdirective tofrinstead ofpg_catalog.english.When enabled, ora2pgpro will create the wrapper function:
CREATE OR REPLACE FUNCTION unaccent_immutable(text) RETURNS text AS $$ SELECT public.unaccent('public.unaccent', $1); $$ LANGUAGE sql IMMUTABLE COST 1;The indexes are exported as follows:
CREATE INDEX t_document_title_unaccent_trgm_idx ON t_document USING gin (unaccent_immutable(title) gin_trgm_ops);In your queries, you will need to use the same function in the search to be able to use the function-based index. Example:
SELECT * FROM t_document WHERE unaccent_immutable(title) LIKE '%donnees%';USE_LOWER_UNACCENTSame as above but call
lower()in theunaccent_immutable()function:CREATE OR REPLACE FUNCTION unaccent_immutable(text) RETURNS text AS $$ SELECT lower(public.unaccent('public.unaccent', $1)); $$ LANGUAGE sql IMMUTABLE;
One of the main advantages of ora2pgpro is its flexibility to replicate Oracle database into Postgres Pro database with a different structure or schema. There are configuration directives that allow you to map those differences.
REORDERING_COLUMNSEnable this directive to reorder columns and minimize the footprint on disc, so that more rows fit on a data page, which is the most important factor for speed. Default is
disabled, which means that the same order as in Oracle tables definition is used, that should be enough for most usages. This directive is only used withTABLEexport.MODIFY_STRUCTThis directive allows you to limit the columns extracted for a given table. The value consists of a space-separated list of table names with a set of columns in parenthesis as follows:
MODIFY_STRUCT NOM_TABLE(nomcol1,nomcol2,...) .... For example:MODIFY_STRUCT T_TEST1(id,dossier) T_TEST2(id,fichier)
This will only extract the columns
idanddossierfrom the tableT_TEST1and columnsidandfichierfrom the tableT_TEST2. This directive can only be used withTABLE,COPY, orINSERTexport. WithTABLEexport, the CREATE TABLE DDL statement will respect the new list of columns, and all indexes or foreign keys pointing to or from a column removed will not be exported.EXCLUDE_COLUMNSInstead of redefining the table structure with
MODIFY_STRUCT, you may want to exclude some columns from the table export. The value consists of a space-separated list of table names with a set of columns in parenthesis as follows:EXCLUDE_COLUMNS NOM_TABLE(nomcol1,nomcol2,...) .... For example:EXCLUDE_COLUMNS T_TEST1(id,dossier) T_TEST2(id,fichier)
This will exclude from the export the columns
idanddossierfrom the tableT_TEST1and columnsidandfichierfrom the tableT_TEST2. This directive can only be used withTABLE,COPY, orINSERTexport. WithTABLEexport, the CREATE TABLE DDL statement will respect the new list of columns, and all indexes or foreign key pointing to or from a column removed will not be exported.REPLACE_TABLESThis directive allows you to remap a list of Oracle table names to Postgres Pro table names during export. The value is a list of space-separated values with the following structure:
REPLACE_TABLES ORIG_TBNAME1:DEST_TBNAME1 ORIG_TBNAME2:DEST_TBNAME2
Oracle tables
ORIG_TBNAME1andORIG_TBNAME2will be respectively renamed toDEST_TBNAME1andDEST_TBNAME2.REPLACE_COLSLike table names, the names of the columns can be remapped to different ones using the following syntax:
REPLACE_COLS ORIG_TBNAME(ORIG_COLNAME1:NEW_COLNAME1,ORIG_COLNAME2:NEW_COLNAME2). For example:REPLACE_COLS T_TEST(dico:dictionary,dossier:folder)
This renames the Oracle columns
dicoanddossierfrom tableT_TESTtodictionaryandfolder.REPLACE_AS_BOOLEANIf you want to change the type of some Oracle columns to Postgres Pro boolean during the export, you can define here a list of tables and columns separated by space as follows:
REPLACE_AS_BOOLEAN TB_NAME1:COL_NAME1 TB_NAME1:COL_NAME2 TB_NAME2:COL_NAME2
The values set in the boolean columns list will be replaced with the
tandffollowing the default replacement values and those additionally set in directiveBOOLEAN_VALUES.Note that if you have modified the table name with
REPLACE_TABLESand/or the column name, you need to use the name of the original table and/or column.REPLACE_COLS TB_NAME1(OLD_COL_NAME1:NEW_COL_NAME1) REPLACE_AS_BOOLEAN TB_NAME1:OLD_COL_NAME1
You can also give a type and precision to convert all fields of that type as a boolean automatically. For example:
REPLACE_AS_BOOLEAN NUMBER:1 CHAR:1 TB_NAME1:COL_NAME1 TB_NAME1:COL_NAME2
This will also replace any field of type number(1) or char(1) as a boolean in all exported tables.
BOOLEAN_VALUESUse this to add additional definition of the possible boolean values used in Oracle fields. You must set a space-separated list of
TRUE:FALSEvalues. By default here are the values recognized by ora2pgpro:BOOLEAN_VALUES yes:no y:n 1:0 true:false enabled:disabled
Any values defined here will be added to the default list.
REPLACE_ZERO_DATEWhen ora2pgpro finds a “zero” date
0000-00-00 00:00:00, it is replaced by NULL. This could be a problem if your column is defined with theNOT NULLconstraint. If you can not remove the constraint, use this directive to set an arbitral date that will be used instead. You can also use-INFINITYif you do not want to use a fake date.INDEXES_SUFFIXAdd the given value as suffix to index names. Useful, if you have indexes with same name as tables. For example:
INDEXES_SUFFIX _idx
This will add
_idxat the end of all index names. Not so common but can help.INDEXES_RENAMINGEnable this directive to rename all indexes in the following format:
tablename_columns_names. Could be very useful for databases that have the same index name multiple times or that use the same name as a table, which is not allowed by Postgres Pro. Disabled by default.USE_INDEX_OPCLASSOperator classes
text_pattern_ops,varchar_pattern_ops, andbpchar_pattern_opssupport B-tree indexes on the corresponding types. The difference from the default operator classes is that the values are compared strictly character by character rather than according to the locale-specific collation rules. This makes these operator classes suitable for use by queries involving pattern-matching expressions (LIKE or POSIX regular expressions) when the database does not use the standardClocale. If you enable, with value 1, this will force ora2pgpro to export all indexes defined on varchar2() and char() columns using those operators. If you set it to a value greater than 1, it will only change indexes on columns where the character limit is greater or equal than this value. For example, set it to 128 to create these kind of indexes on columns of type varchar2(N) where N >= 128.RENAME_PARTITIONEnable this directive if you want that your partition tables will be renamed. Disabled by default. If you have multiple partitioned tables, when exported to Postgres Pro some partitions could have the same name but different parent tables. This is not allowed, a table name must be unique, in this case enable this directive. The following rules are applied by default:
- Partition: "tablename"_part"pos" where "pos" is the partition number.
- Subpartition: "tablename"_part"pos"_subpart"pos".
- Partition/subpartition: "tablename"_part_default "tablename"_part"pos"_subpart_default.
DISABLE_PARTITIONIf you do not want to reproduce the partitioning like in Oracle and want to export all partitioned Oracle data into the main single table in Postgres Pro, enable this directive. ora2pgpro will export all data into the main table. Default is to use partitioning, ora2pgpro will export data from each partition and import them into the Postgres Pro dedicated partition table.
DISABLE_UNLOGGEDBy default ora2pgpro exports Oracle tables with the
NOLOGGINGattribute asUNLOGGEDtables. You may want to fully disable this feature because you will lose all data from unlogged tables in case of a Postgres Pro crash. Set it to 1 to export all tables as normal tables.
ora2pgpro fully exports spatial objects from Oracle databases. There are some configuration directives that could be used to control the export.
AUTODETECT_SPATIAL_TYPEBy default, ora2pgpro is looking at indexes to see the spatial constraint type and dimensions defined under Oracle. Those constraints are passed at index creation using for example:
CREATE INDEX ... INDEXTYPE IS MDSYS.SPATIAL_INDEX PARAMETERS('sdo_indx_dims=2, layer_gtype=point');If those Oracle constraints parameters are not set, the default is to export those columns as generic type GEOMETRY to be able to receive any spatial type.
The
AUTODETECT_SPATIAL_TYPEdirective allows to force ora2pgpro to autodetect the real spatial type and dimensions used in a spatial column otherwise a non-constrained geometry type is used. Enabling this feature will force ora2pgpro to scan a sample of 50000 column to look at the GTYPE used. You can increase or reduce the sample size by setting the value ofAUTODETECT_SPATIAL_TYPEto the desired number of line to scan. The directive is enabled by default.For example, in the case of a column named
shapeand defined with Oracle type SDO_GEOMETRY, withAUTODETECT_SPATIAL_TYPEdisabled, it will be converted as:shape geometry(GEOMETRY) or shape geometry(GEOMETRYZ, 4326)
If the directive is enabled and the column just contains a single geometry type that uses a single dimension with a two or three dimensional polygon:
shape geometry(POLYGON, 4326) or shape geometry(POLYGONZ, 4326)
CONVERT_SRIDThis directive allows you to control the automatic conversion of Oracle SRID to standard EPSG. If enabled, ora2pgpro will use the Oracle function
sdo_cs.map_oracle_srid_to_epsg()to convert all SRIDs. Enabled by default.If the
SDO_SRIDreturned by Oracle is NULL, it will be replaced by the default value 8307 converted to its EPSG value: 4326 (seeDEFAULT_SRID).If the value is more than 1, all SRIDs will be forced to this value, in this case
DEFAULT_SRIDwill not be used when Oracle returns a null value and the value will be forced toCONVERT_SRID.Note that it is also possible to set the
EPSGvalue on Oracle side whensdo_cs.map_oracle_srid_to_epsg()returns NULL if your want to force the value:system@db> UPDATE sdo_coord_ref_sys SET legacy_code=41014 WHERE srid = 27572;
DEFAULT_SRIDUse this directive to override the default EPSG SRID to be used: 4326. Can be overwritten by
CONVERT_SRID, see above.GEOMETRY_EXTRACT_TYPEThis directive can take three values:
WKT(default),WKB, andINTERNAL. When it is set toWKT, ora2pgpro will useSDO_UTIL.TO_WKTGEOMETRY()to extract the geometry data. When it is set toWKB, ora2pgpro will use the binary output usingSDO_UTIL.TO_WKBGEOMETRY(). If those two extract types are calls at Oracle side, they are slow and you can easily reach Out Of Memory when you have a lot of rows. AlsoWKBis not able to export 3D geometry and some geometries likeCURVEPOLYGON. In this case you may use theINTERNALextraction type. It will use a Pure Perl library to convert theSDO_GEOMETRYdata into aWKTrepresentation, the translation is done on ora2pgpro side. This is a work in progress, validate your exported data geometries before use. Default spatial object extraction type isINTERNAL.POSTGIS_SCHEMAUse this directive to add a specific schema to the search path to look for PostGIS functions.
ST_SRID_FUNCTIONOracle function to use to extract the SRID from
ST_Geometrymeta information. Default:ST_SRID, for example, it should be set tosde.st_sridfor ArcSDE.ST_DIMENSION_FUNCTIONOracle function to use to extract the dimension from
ST_Geometrymeta information. Default: ST_DIMENSION, for example it should be set tosde.st_dimentionfor ArcSDE.ST_GEOMETRYTYPE_FUNCTIONOracle function to use to extract the geometry type from a
ST_Geometrycolumn. Default:ST_GEOMETRYTYPE, for example it should be set tosde.st_geometrytypefor ArcSDE.ST_ASBINARY_FUNCTIONOracle function to be used to convert an
ST_Geometryvalue intoWKBformat. Default:ST_ASBINARY, for example it should be set tosde.st_asbinaryfor ArcSDE.ST_ASTEXT_FUNCTIONOracle function to be used to convert an
ST_Geometryvalue intoWKTformat. Default:ST_ASTEXT, for example it should be set tosde.st_astextfor ArcSDE.
By default conversion to Postgres Pro format is written to file output.sql.
psql mydb < output.sql
This command will import content of the file output.sql into Postgres Pro mydb database.
DATA_LIMITWhen you are performing
INSERT/COPYexport, ora2pgpro proceeds by chunks ofDATA_LIMITtuples for speed improvement. Tuples are stored in memory before being written to disk, so if you want speed and have enough system resources you can raise this limit to an higher value for example: 100000 or 1000000. A value of 0 means that the chunk will be set to the default: 10000.BLOB_LIMITWhen ora2pgpro detects a table with some BLOB, it will automatically reduce the value of this directive by dividing it by 10 until its value is below 1000. You can control this value by setting
BLOB_LIMIT. Exporting BLOB use lot of resources, setting it to a too high value can produce OOM.OUTPUTThe ora2pgpro output filename can be changed with this directive. Default value is
output.sql. If you set the file name with extension.gzor.bz2, the output will be automatically compressed. This requires that theCompress::ZlibPerl module is installed if the filename extension is.gzand that the bzip2 system command is installed for the.bz2extension.OUTPUT_DIRYou can define a base directory where the file will be written. The directory must exist.
BZIP2This directive allows you to specify the full path to the bzip2 program if it can not be found in the
PATHenvironment variable.FILE_PER_CONSTRAINTAllow object constraints to be saved in a separate file during schema export. The file will be named
CONSTRAINTS_OUTPUT, whereOUTPUTis the value of the corresponding configuration directive. You can use.gzor.bz2extension to enable compression. Default is to save all data in theOUTPUTfile. This directive is usable only withTABLEexport type.The constraints can be imported quickly into Postgres Pro using the
LOADexport type to parallelize their creation over multiple (-jorJOBS) connections.FILE_PER_INDEXAllow indexes to be saved in a separate file during schema export. The file will be named
INDEXES_OUTPUT, whereOUTPUTis the value of the corresponding configuration directive. You can use.gzor.bz2file extension to enable compression. Default is to save all data in theOUTPUTfile. This directive is usable only withTABLEANDTABLESPACEexport type. With theTABLESPACEexport, it is used to write ALTER INDEX ... TABLESPACE ... into a separate file namedTBSP_INDEXES_OUTPUTthat can be loaded at end of the migration after the indexes creation to move the indexes.The indexes can be imported quickly into Postgres Pro using the
LOADexport type to parallelize their creation over multiple (-jorJOBS) connections.FILE_PER_FKEYSAllow foreign key declaration to be saved in a separate file during schema export. By default foreign keys are exported into the main output file or in the
CONSTRAINT_output.sqlfile. When enabled, foreign keys will be exported into a file namedFKEYS_output.sql.FILE_PER_TABLEAllow data export to be saved in one file per table/view. The files will be named as
tablename_OUTPUT, whereOUTPUTis the value of the corresponding configuration directive. You can still use.gzor.bz2extension in theOUTPUTdirective to enable compression. Default 0 will save all data in one file, set it to 1 to enable this feature. This is usable only duringINSERTorCOPYexport type.FILE_PER_FUNCTIONAllow functions, procedures and triggers to be saved in one file per object. The files will be named as
objectname_OUTPUT, whereOUTPUTis the value of the corresponding configuration directive. You can still use.gzor.bz2extension in theOUTPUTdirective to enable compression. Default 0 will save all in one single file, set it to 1 to enable this feature. This is usable only during the corresponding export type, the package body export has a special behavior.When export type is
PACKAGE, and you enabled this directive, ora2pgpro will create a directory per package, named with the lower-case name of the package, and will create one file per function/procedure into that directory. If the configuration directive is not enabled, it will create one file per package aspackagename_OUTPUT, whereOUTPUTis the value of the corresponding directive.TRUNCATE_TABLEIf this directive is set to 1, a TRUNCATE TABLE instruction will be added before loading data. This is usable only during
INSERTorCOPYexport type.When activated, the instruction will be added only if there is no global DELETE clause or not one specific to the current table (see below).
DELETESupport for include a DELETE FROM ... WHERE clause filter before importing data and perform a deletion of some lines instead of truncating tables. Value is constructed as follows:
TABLE_NAME[DELETE_WHERE_CLAUSE], or if you have only oneWHEREclause for all tables just put theDELETEclause as a single value. Both are possible too. Here are some examples:DELETE 1=1 # Apply to all tables and delete all tuples DELETE TABLE_TEST[ID1='001'] # Apply only on table TABLE_TEST DELETE TABLE_TEST[ID1='001' OR ID1='002] DATE_CREATE > '2001-01-01' TABLE_INFO[NAME='test']
The last applies two different delete where clause on tables
TABLE_TESTandTABLE_INFOand a genericDELETEclause onDATE_CREATEto all other tables. IfTRUNCATE_TABLEis enabled, it will be applied to all tables not covered by theDELETEdefinition. TheseDELETEclauses might be useful with regular updates.STOP_ON_ERRORSet this parameter to 0 to not include the call to \set ON_ERROR_STOP ON in all SQL scripts generated by ora2pgpro. By default this order is always present so that the script will immediately abort when an error is encountered.
COPY_FREEZEEnable this directive to use
COPY FREEZEinstead of a simpleCOPYto export data with rows already frozen. This is intended as a performance option for initial data loading. Rows will be frozen only if the table being loaded has been created or truncated in the current sub-transaction. This will only work with export to file and when-JorORACLE_COPIESis not set or defaults to 1. It can be used with direct import into Postgres Pro under the same condition, but-jorJOBSmust also be unset or default to 1.CREATE_OR_REPLACEBy default ora2pgpro uses CREATE OR REPLACE in functions and views DDL, if you need not to override existing functions or views disable this configuration directive, DDL will not include OR REPLACE.
DROP_IF_EXISTSTo add a DROP
OBJECTIF EXISTS before creating the object, enable this directive. Can be useful in an iterative work. Default is disabled.EXPORT_GTTPostgres Pro does not support Global Temporary Table natively but you can use the pgtt extension to emulate this behavior. Enable this directive to export global temporary table.
NO_HEADEREnabling this directive will prevent ora2pgpro to print its header into output files. Only the translated code will be written.
PSQL_RELATIVE_PATHBy default ora2pgpro use
\ipsql command to execute generated SQL files if you want to use a relative path following the script execution file enabling this option will use\ir. See psql help for more information.DATA_VALIDATION_ROWSNumber of rows that must be retrieved on both sides for data validation. Default it to compare the 10000 first rows. A value of 0 means to compare all rows.
DATA_VALIDATION_ORDERINGOrder of rows between both sides is different once the data have been modified. In this case data must be ordered using a primary key or a unique index, that means that a table without such objects can not be compared. If the validation is done just after the data migration without any data modification, the validation can be done on all tables without any ordering.
DATA_VALIDATION_ERRORStop validating data from a table after a certain amount of row mismatch. Default is to stop after 10 rows validation errors.
TRANSFORM_VALUEUse this directive to specify which transformation should be applied to a column when exporting data. Value must be a semicolon-separated list of the following:
TABLE[COLUMN_NAME,
code in SELECT target list]For example, to replace string “Oracle” by “PostgreSQL” in a varchar2 column, use the following:
TRANSFORM_VALUE ERROR_LOG_SAMPLE[DBMS_TYPE:regexp_replace("DBMS_TYPE",'Oracle','PostgreSQL')]To replace all Oracle char(0) in a string with a space character:
TRANSFORM_VALUE CLOB_TABLE[CHARDATA:translate("CHARDATA", chr(0), ' ')]The expression will be applied in the SQL statement used to extract data from the source database.
When using ora2pgpro the export type INSERT or COPY to dump data to the file and that FILE_PER_TABLE is enabled, you will be warned that ora2pgpro will not export data again if the file already exists. This is to prevent downloading twice the table with a huge amount of data. To force the download of data from these tables, you have to remove the existing output file first.
If you want to import data on the fly to the Postgres Pro database, you have three configuration directives to set the Postgres Pro database connection. This is only possible with COPY or INSERT export type as for the database schema there is no real interest to do that.
PG_DSNUse this directive to set the Postgres Pro data source namespace using
DBD::PgPerl module as follows:dbi:Pg:dbname=pgdb;host=localhost;port=5432
It will connect to the database
pgdbonlocalhostat TCP port 5432.Note that this directive is only used for data export, other export needs to be imported manually through the use of psql or any other Postgres Pro client.
To use SSL-encrypted connection, you must add
sslmode=requireto the connection string like this:dbi:Pg:dbname=pgdb;host=localhost;port=5432;sslmode=require
PG_USER,PG_PWDThese two directives are used to set the login user and password. If you do not supply a credential with
PG_PWD, and you have installed theTerm::ReadKeyPerl module, ora2pgpro will ask for the password interactively. IfPG_USERis not set, it will be asked interactively too.SYNCHRONOUS_COMMITSpecifies whether the transaction commit will wait for WAL records to be written to disk before the command returns a success indication to the client. This is the equivalent to setting
synchronous_commitdirective of thepostgresql.conffile. This is only used when you load data directly to Postgres Pro, the default is off to disable the synchronous commit to gain speed at writing data.PG_INITIAL_COMMANDThis directive can be used to send an initial command to Postgres Pro, just after the connection, for example, to set some session parameters. This directive can be used multiple times.
PG_NUMERIC_TYPEIf set to 1, replace portable numeric types with Postgres Pro internal types. Oracle data type NUMBER(p,s) is approximatively converted to real and float Postgres Pro data types. If you have monetary fields or do not want rounding issues with the extra decimals, you should preserve the same numeric(p,s) Postgres Pro data type. Do that only if you need exactness because using numeric(p,s) is slower than using real or double.
PG_INTEGER_TYPEIf set to 1, replace portable numeric type into Postgres Pro internal type. Oracle data type NUMBER(p) or NUMBER are converted to a smallint, integer, or bigint Postgres Pro data type following the value of the precision. NUMBER without precision is set to
DEFAULT_NUMERIC(see below).DEFAULT_NUMERICNUMBER without precision is converted by default to bigint only if
PG_INTEGER_TYPEis true. You can overwrite this value to any Postgres Pro type, like integer or float.DATA_TYPEIf you are experiencing any problem in data type schema conversion with this directive, you can take full control of the correspondence between Oracle and Postgres Pro types to redefine data type translation used in ora2pgpro. The syntax is a comma-separated list of
Oracle datatype:Postgres Pro datatype. Here is the default list used:DATA_TYPE VARCHAR2:varchar,NVARCHAR2:varchar,NVARCHAR:varchar,NCHAR:char,DATE:timestamp(0),LONG:text,LONG RAW:bytea,CLOB:text,NCLOB:text,BLOB:bytea,BFILE:bytea,RAW(16):uuid,RAW(32):uuid,RAW:bytea,UROWID:oid,ROWID:oid,FLOAT:double precision,DEC:decimal,DECIMAL:decimal,DOUBLE PRECISION:double precision,INT:integer,INTEGER:integer,REAL:real,SMALLINT:smallint,BINARY_FLOAT:double precision,BINARY_DOUBLE:double precision,TIMESTAMP:timestamp,XMLTYPE:xml,BINARY_INTEGER:integer,PLS_INTEGER:integer,TIMESTAMP WITH TIME ZONE:timestamp with time zone,TIMESTAMP WITH LOCAL TIME ZONE:timestamp with time zone
The directive and the list definition must be a single line.
Note that when RAW(16) and RAW(32) columns is found or that the RAW column has
SYS_GUID()as the default value, ora2pgpro will automatically translate the type of the column into uuid, which might be the right translation in most of cases. In this case data will be automatically migrated as Postgres Pro uuid data type provided by the uuid-ossp extension.If you want to replace a type with a precision and scale, you need to escape the comma with a backslash. For example, if you want to replace all NUMBER(*,0) into bigint instead of numeric(38), add the following:
DATA_TYPE NUMBER(*\,0):bigint
You do not have to recopy all default type conversion but just the one you want to rewrite.
There is a special case with BFILE when they are converted to type TEXT, they will just contain the full path to the external file. If you set the destination type to BYTEA, the default, ora2pgpro will export the content of the BFILE as bytea. The third case is when you set the destination type to EFILE, in this case, ora2pgpro will export it as an EFILE record: (DIRECTORY, FILENAME). Use the
DIRECTORYexport type to export the existing directories as well as the privileges on those directories.There is no SQL function available to retrieve the path to BFILE. ora2pgpro has to create one using the
DBMS_LOBpackage.CREATE OR REPLACE FUNCTION ora2pg_get_bfilename( p_bfile IN BFILE ) RETURN VARCHAR2 AS l_dir VARCHAR2(4000); l_fname VARCHAR2(4000); l_path VARCHAR2(4000); BEGIN dbms_lob.FILEGETNAME( p_bfile, l_dir, l_fname ); SELECT directory_path INTO l_path FROM all_directories WHERE directory_name = l_dir; l_dir := rtrim(l_path,'/'); RETURN l_dir || '/' || l_fname; END;This function is only created if ora2pgpro found a table with a BFILE column and that the destination type is TEXT. The function is dropped at the end of export. This concerns both
COPYandINSERTexport types.There is no SQL function available to retrieve BFILE as an EFILE record, then ora2pgpro have to create one using the
DBMS_LOBpackage.CREATE OR REPLACE FUNCTION ora2pg_get_efile( p_bfile IN BFILE ) RETURN VARCHAR2 AS l_dir VARCHAR2(4000); l_fname VARCHAR2(4000); BEGIN dbms_lob.FILEGETNAME( p_bfile, l_dir, l_fname ); RETURN '(' || l_dir || ',' || l_fnamei || ')'; END;This function is only created if ora2pgpro found a table with a BFILE column and that the destination type is EFILE. The function is dropped at the end of the export. This concerns both
COPYandINSERTexport types.To set the destination type, use the
DATA_TYPEconfiguration directive:DATA_TYPE BFILE:EFILE
The EFILE type is a user-defined type created by the extension that can be found here: external_file This is a port of the BFILE Oracle type to Postgres Pro.
There is no SQL function available to retrieve the content of a BFILE. ora2pgpro have to create one using the
DBMS_LOBpackage.CREATE OR REPLACE FUNCTION ora2pg_get_bfile( p_bfile IN BFILE ) RETURN BLOB AS filecontent BLOB := NULL; src_file BFILE := NULL; l_step PLS_INTEGER := 12000; l_dir VARCHAR2(4000); l_fname VARCHAR2(4000); offset NUMBER := 1; BEGIN IF p_bfile IS NULL THEN RETURN NULL; END IF; DBMS_LOB.FILEGETNAME( p_bfile, l_dir, l_fname ); src_file := BFILENAME( l_dir, l_fname ); IF src_file IS NULL THEN RETURN NULL; END IF; DBMS_LOB.FILEOPEN(src_file, DBMS_LOB.FILE_READONLY); DBMS_LOB.CREATETEMPORARY(filecontent, true); DBMS_LOB.LOADBLOBFROMFILE (filecontent, src_file, DBMS_LOB.LOBMAXSIZE, offset, offset); DBMS_LOB.FILECLOSE(src_file); RETURN filecontent; END;This function is only created if ora2pgpro found a table with a BFILE column and that the destination type is bytea (the default). The function is dropped at the end of the export. This concerns both
COPYandINSERTexport type.About the ROWID and UROWID, they are converted into OID by logical default but this will throw an error at data import. There is no equivalent data type so you might want to use the
DATA_TYPEdirective to change the corresponding type in Postgres Pro. You should consider replacing this data type by a bigserial (autoincremented sequence), text or uuid data type.MODIFY_TYPESometimes you need to force the destination type, for example a column exported as timestamp by ora2pgpro can be forced into type date. Value is a comma-separated list of
TABLE:COLUMN:TYPEstructure. If you need to use comma or space inside type definition, you will have to backslash them.MODIFY_TYPE TABLE1:COL3:varchar,TABLE1:COL4:decimal(9\,6)
Type of
table1.col3will be replaced by a varchar andtable1.col4by a decimal with precision and scale.If the column's type is a user-defined type, ora2pgpro will autodetect the composite type and will export its data using
ROW(). Some Oracle user defined types are just array of a native type, in this case you may want to transform this column in simple array of a Postgres Pro native type. To do so, just redefine the destination type as wanted and ora2pgpro will also transform the data as an array. For example, with the following definition in Oracle:CREATE OR REPLACE TYPE mem_type IS VARRAY(10) of VARCHAR2(15); CREATE TABLE club (Name VARCHAR2(10), Address VARCHAR2(20), City VARCHAR2(20), Phone VARCHAR2(8), Members mem_type );Here custom type mem_type is just a string array and can be translated into the following in Postgres Pro:
CREATE TABLE club ( name varchar(10), address varchar(20), city varchar(20), phone varchar(8), members text[] ) ;To do so, just use the directive as follow:
MODIFY_TYPE CLUB:MEMBERS:text[]
ora2pgpro will take care to transform all data of this column in the correct format. Only arrays of characters and numerics types are supported.
TO_NUMBER_CONVERSIONBy default Oracle calls to function
TO_NUMBERwill be translated as a cast into numeric. For example,TO_NUMBER('10.1234')is converted into a Postgres Pro callto_number('10.1234')::numeric. If you want you can cast the call to integer or bigint by changing the value of the configuration directive. If you need better control of the format, just set it as value, for example:TO_NUMBER_CONVERSION 99999999999999999999.9999999999will convert the code above as:TO_NUMBER('10.1234', '99999999999999999999.9999999999')Any value of the directive that is not numeric, integer, or bigint will be taken as a mask format. If set to none, no conversion will be done.VARCHAR_TO_TEXTBy default varchar2 without size constraint is tranlated into text. If you want to keep the varchar name, disable this directive.
FORCE_IDENTITY_BIGINTUsually identity column must be bigint to correspond to an auto increment sequence so ora2pgpro always forces it to be a bigint. If, for any reason you want ora2pgpro to respect the
DATA_TYPEyou have set for identity column, then disable this directive.TO_CHAR_NOTIMEZONEIf you want ora2pgpro to remove any timezone information into the format part of the
TO_CHAR()function, enable this directive. Disabled by default.
The following other configuration directives interact directly with the export process and give you fine granularity in database export control.
SKIPFor
TABLEexport, you may not want to export all schema constraints, theSKIPconfiguration directive allows you to specify a space or comma-separated list of constraints that should not be exported. Possible values are:fkeys: turn off foreign key constraintspkeys: turn off primary keysukeys: turn off unique column constraintsindexes: turn off all other index typeschecks: turn off check constraints
SKIP indexes,checks
For example, this will remove indexes and check constraints from export.
PKEY_IN_CREATEEnable this directive if you want to add primary key definition inside the CREATE TABLE statement. If disabled (the default), primary key definition will be added with an ALTER TABLE statement.
KEEP_PKEY_NAMESBy default, names of the primary and unique keys in the source Oracle database are ignored, and key names are autogenerated in the target Postgres Pro database with the Postgres Pro internal default naming rules. If you want to preserve Oracle primary and unique key names, set this option to 1.
FKEY_ADD_UPDATEThis directive allows you to add an
ON UPDATE CASCADEoption to a foreign key whenON DELETE CASCADEis defined or always. Oracle does not support this feature, you have to use a trigger to operate theON UPDATE CASCADE. As Postgres Pro has this feature, you can choose how to add the foreign key option. This directive has the following values:never: the default that means that foreign keys will be declared exactly like in Oracledelete: theON UPDATE CASCADEoption will be added only if theON DELETE CASCADEis already defined on the foreign keysalways: forces all foreign keys to be defined using the update option
FKEY_DEFERRABLEWhen exporting tables, ora2pgpro normally exports constraints as they are, if they are non-deferrable, they are exported as non-deferrable. However, non-deferrable constraints will probably cause problems when attempting to import data to Postgres Pro. The
FKEY_DEFERRABLEoption set to 1 will cause all foreign key constraints to be exported as deferrable.DEFER_FKEYIn addition to exporting data when the
DEFER_FKEYoption is set to 1, it will add a command to defer all foreign key constraints during data export, and the import will be done in a single transaction. This will work only if foreign keys have been exported as deferrable and you are not using direct import to Postgres Pro (PG_DSNis not defined). Constraints will then be checked at the end of the transaction.This directive can also be enabled if you want to force all foreign keys to be created as deferrable and initially deferred during schema export (
TABLEexport type).DROP_FKEYIf deferring foreign keys is not possible due to the amount of data in a single transaction, you have not exported foreign keys as deferrable or you are using direct import to Postgres Pro, you can use the
DROP_FKEYdirective. It will drop all foreign keys before all data import and recreate them at the end of the import.DROP_INDEXESThis directive allows you to gain lot of speed improvement during data import by removing all indexes that are not an automatic index (indexes of primary keys) and recreate them at the end of data import. It is far better to not import indexes and constraints before having imported all data.
DISABLE_TRIGGERSThis directive is used to disable triggers on all tables in
COPYorINSERTexport modes. Available values areUSER(disable user-defined triggers only) andALL(includes RI system triggers). Default is 0: do not add SQL statements to disable trigger before data import.If you want to disable triggers during data migration, set the value to
USERif you are connected as non-superuser, andALLif you are connected as Postgres Pro superuser. A value of 1 is equal toUSER.DISABLE_SEQUENCEIf set to 1, it disables alter of sequences on all tables during
COPYorINSERTexport mode. This is used to prevent the update of sequence during data migration. Default is 0, alter sequences.NOESCAPEBy default all data that are not of type date or time are escaped. If you experience any problem with that you can set it to 1 to disable character escaping during data export. This directive is only used during a
COPYexport. SeeSTANDARD_CONFORMING_STRINGSfor enabling/disabling escape with INSERT statements.STANDARD_CONFORMING_STRINGSThis controls whether ordinary string literals ('...') treat backslashes literally, as specified in SQL standard. This is on by default, causing ora2pgpro to use the escape string syntax
(E'...')if this parameter is not set to 0. This is the exact behavior of the same option in Postgres Pro. This directive is only used during data export to buildINSERTstatements. SeeNOESCAPEfor enabling/disabling escape in COPY statements.TRIM_TYPEIf you want to convert CHAR(n) from Oracle into varchar(n) or text in Postgres Pro using directive
DATA_TYPE, you might want to do some trimming on the data. By default, ora2pgpro will auto-detect this conversion and remove any whitespace at both leading and trailing position. If you just want to remove the leadings character set the value toLEADING. If you just want to remove the trailing character, set the value toTRAILING. Default value isBOTH.TRIM_CHARThe default trimming character is space, use this directive if you need to change the character that will be removed. For example, set it to
-if you have a leading-in the char(n) field. To use space as trimming charger, comment this directive, this is the default value.PRESERVE_CASEIf you want to preserve the case of Oracle object names, set this directive to 1. By default, ora2pgpro will convert all Oracle object names to lower case. It is not recommended to enable this, unless you will always have to double-quote object names on all your SQL scripts.
ORA_RESERVED_WORDSAllow escaping of column name using Oracle reserved words. Value is a list of comma-separated reserved words. Default:
audit,comment,references.USE_RESERVED_WORDSEnable this directive if you have table or column names that are a reserved word for Postgres Pro. ora2pgpro will double quote the name of the object.
GEN_USER_PWDSet this directive to 1 to replace default password by a random password for all extracted user during a
GRANTexport.PG_SUPPORTS_MVIEWIn Postgres Pro, materialized views are supported with the SQL syntax CREATE MATERIALIZED VIEW. To force ora2pgpro to use the native Postgres Pro support you must enable this configuration - enable by default. If you want to use the old style with table and a set of function, you should disable it.
PG_VERSIONSet the Postgres Pro major version number of the target database. For example: 11 or 16. Default is the current major version at the time of a new release.
BITMAP_AS_GINUse btree_gin extension to create bitmap like indexes. You will need to create the extension. Default is to create GIN index, when disabled, a B-tree index will be created.
LONGREADLENUse this directive to set how the database handles the
LongReadLenattribute to a value that will be larger than the expected size of the LOBs. The default is 1MB which may not be enough to extract BLOBs or CLOBs. If the size of the LOB exceeds theLONGREADLENDBD::Oraclewill return a “ORA-24345: A Truncation” error. Default: 1023*1024 bytes.![[Important]](https://repo.postgrespro.ru/doc/ora2pgpro/23.2.3/en/html/html/important.png)
Important If you increase the value of this directive, take care that
DATA_LIMITprobably needs to be reduced. Even if you only have a 1MB blob, trying to read 10000 of them (the defaultDATA_LIMIT) all at once will require 10GB of memory. You may extract data from those tables separately and set aDATA_LIMITto 500 or lower, otherwise you may experience out of memory.LONGTRUNKOKIf you want to bypass the “ORA-24345: A Truncation” error, set this directive to 1, it will truncate the data extracted to the
LONGREADLENvalue. Disabled by default so that you will be warned if yourLONGREADLENvalue is not high enough.USE_LOB_LOCATORDisable this if you want to load full contents of BLOB and CLOB and not use LOB locators. In this case you will have to set
LONGREADLENto the right value. Note that this will not improve speed of BLOB export as most of the time is always consumed by the bytea escaping and in this case export is done line-by-line and not by chunk ofDATA_LIMITrows. Default is enabled, it uses LOB locators.LOB_CHUNK_SIZEOracle recommends reading from and writing to a LOB in batches using a multiple of the LOB chunk size. This chunk size defaults to 8k (8192). Recent tests shown that the best performances can be reach with higher value like 512K or 4Mb.
A quick benchmark with 30120 rows with different size of BLOB (200x5Mb, 19800x212k, 10000x942K, 100x17Mb, 20x156Mb), with DATA_LIMIT=100, LONGREADLEN=170Mb and a total table size of 20GB gives:
no lob locator : 22m46,218s (1365 sec., avg: 22 recs/sec) chunk size 8k : 15m50,886s (951 sec., avg: 31 recs/sec) chunk size 512k : 1m28,161s (88 sec., avg: 342 recs/sec) chunk size 4Mb : 1m23,717s (83 sec., avg: 362 recs/sec)
In conclusion it can be more than 10 time faster with
LOB_CHUNK_SIZEset to 4Mb. Depending on the size of most BLOB you may want to adjust the value here. For example, if you have a majority of small lobs bellow 8K, using 8192 is better to not waste space. Default value forLOB_CHUNK_SIZEis 512000.XML_PRETTYForce the use
getStringVal()instead ofgetClobVal()for XML data export. Default is 1, enabled for backward compatibility. Set it to 0 to use extract method as CLOB. Note that XML value extracted withgetStringVal()must not exceed VARCHAR2 size limit (4000), otherwise it will return an error.ENABLE_MICROSECONDSet it to O if you want to disable export of millisecond from Oracle timestamp columns. By default milliseconds are exported with the use of the following format:
'YYYY-MM-DD HH24:MI:SS.FF'
Disabling will force the use of the following Oracle format:
to_char(..., 'YYYY-MM-DD HH24:MI:SS')
By default milliseconds are exported.
DISABLE_COMMENTSet this to 1 if you do not want to export comment associated to tables and columns definition. Default is enabled.
NLS_LANGBy default, ora2pgpro will set
NLS_LANGtoAMERICAN_AMERICA.AL32UTF8andNLS_NCHARtoAL32UTF8. It is not recommended to change those settings but in some case it could be useful. Using your own settings with those configuration directive will change the client encoding at Oracle side by setting the environment variables$ENV{NLS_LANG}and$ENV{NLS_NCHAR}.BINMODEBy default, ora2pgpro will force Perl to use UTF8 I/O encoding. This is done through a call to the Perl pragma:
use open ':utf8';
You can override this encoding by using the
BINMODEdirective, for example you can set it to:localeto use your locale oriso-8859-7.use open ':locale'; use open ':encoding(iso-8859-7)';
If you have changed the
NLS_LANGto non-UTF8 encoding, you might want to set this directive. Most of the time, leave this directive commented.CLIENT_ENCODINGBy default, Postgres Pro client encoding is automatically set to UTF8 to avoid encoding issues. If you have changed the value of
NLS_LANG, you might have to change the encoding of the Postgres Pro client.For the Postgres Pro supported character sets, see Character Set Support.
FORCE_PLSQL_ENCODINGTo force UTF8 encoding of the PL/SQL code exported, enable this directive. Could be helpful in some rare condition.
Automatic code conversion from Oracle PL/SQL to Postgres Pro PL/pgSQL is a work in progress in ora2pgpro and you have to do manual work. The Perl code used for automatic conversion is all stored in a specific Perl Module named Ora2Pgpro/PLSQL.pm.
PLSQL_PGSQLEnable/disable PL/SQL to PL/pgSQL conversion. Enabled by default.
NULL_EQUAL_EMPTYora2pgpro can replace all conditions with a test on NULL by a call to the
coalesce()function to mimic the Oracle behavior where empty string are considered equal to NULL.(field1 IS NULL) is replaced by (coalesce(field1::text, '') = '') (field2 IS NOT NULL) is replaced by (field2 IS NOT NULL AND field2::text <> '')
You might want this replacement to be sure that your application will have the same behavior but if you have control on you application a better way is to change it to transform empty string into NULL because Postgres Pro makes the difference.
EMPTY_LOB_NULLForce
empty_clob()andempty_blob()to be exported as NULL instead as empty string for the first one and\xfor the second. If NULL is allowed in your column, this might improve data export speed if you have a lot of empty lobs. Default is to preserve the exact data from Oracle.PACKAGE_AS_SCHEMAIf you do not want to export package as schema but as simple functions you might also want to replace all calls to
package_name.function_name. If you disable thePACKAGE_AS_SCHEMAdirective, then ora2pgpro will replace all call topackage_name.function_name()bypackage_name_function_name(). Default is to use a schema to emulate package.The replacement will be done in all kind of DDL or code that is parsed by the PL/SQL to PL/pgSQL converter.
PLSQL_PGSQLmust be enabled or-pused in command line.REWRITE_OUTER_JOINEnable this directive if the rewrite of Oracle native syntax (+) of
OUTER JOINis broken. This will force ora2pgpro to not rewrite such code, default is to try to rewrite simple form of the right outer join for the moment.UUID_FUNCTIONBy default ora2pgpro will convert call to SYS_GUID() Oracle function with a call to uuid_generate_v4 from uuid-ossp extension. You can redefined it to use the gen_random_uuid function from pgcrypto extension by changing the function name. Default to uuid_generate_v4.
Note that when a RAW(16) and RAW(32) columns is found or that the RAW column has "SYS_GUID()" as default value ora2pgpro will automatically translate the type of the column into uuid which might be the right translation in most of the case. In this case data will be automatically migrated as Postgres Pro uuid data type provided by the "uuid-ossp" extension.
FUNCTION_STABLEBy default Oracle functions are marked as
STABLEas they can not modify data unless when used in PL/SQL with variable assignment or as conditional expression. You can force ora2pgpro to create these function asVOLATILEby disabling this configuration directive.COMMENT_COMMIT_ROLLBACKBy default call to COMMIT/ROLLBACK are kept untouched by ora2pgpro to force the user to review the logic of the function. Once it is fixed in Oracle source code or you want to comment these calls, enable the following directive.
COMMENT_SAVEPOINTIt is common to see SAVEPOINT calls inside PL/SQL procedure together with a ROLLBACK TO savepoint_name. When
COMMENT_COMMIT_ROLLBACKis enabled, you may want to also comment SAVEPOINT calls, in this case enable it.STRING_CONSTANT_REGEXPora2pgpro replaces all string constants during the PL/SQL to PL/pgSQL translation, string constants are all text included between single quote. If you have a string placeholder used in dynamic call to queries, you can set a list of regexp to be temporary replaced to not break the parser. For example:
STRING_CONSTANT_REGEXP <placeholder value=".*">
The list of regexp must use the semicolon as separator.
ALTERNATIVE_QUOTING_REGEXPTo support the Alternative Quoting Mechanism ('Q' or 'q') for String Literals set the regexp with the text capture to use to extract the text part. For example with a variable declared as
c_sample VARCHAR2(100 CHAR) := q'{This doesn't work.}';the regexp to use must be:
ALTERNATIVE_QUOTING_REGEXP q'{(.*)}'ora2pgpro will use the
$$delimiter, with the example the result will be:c_sample varchar(100) := $$This doesn't work.$$;
The value of this configuration directive can be a list of regexp separated by a semicolon. The capture part (in parenthesis) is mandatory in each regexp if you want to restore the string constant.
USE_ORAFCEIf you want to use functions defined in the orafce library and prevent ora2pgpro to translate calls to these functions, enable this directive.
By default ora2pgpro rewrite
add_month(),add_year(),date_trunc()andto_char()functions, but you may prefer to use the orafce version of these function that do not need any code transformation.INCLUDE_PACKAGESContains the comma-separated list of packages to allow to be exported. Used only with the
PACKAGEexport type. Only the last occurrence found in the file will be used.EXCLUDE_PACKAGESContains the comma-separated list of packages to exclude from export. Used only with the
PACKAGEexport type. Only the last occurrence found in the file will be used.POSTGRESPRO_ATXIf set to 1, enables export of autonomous transactions directly as Postgres Pro autonomous transactions.
Materialized views are exported as snapshot "Snapshot Materialized Views" as Postgres Pro only supports full refresh.
When exporting materialized view, ora2pgpro will first add the SQL code to create the materialized_views table:
CREATE TABLE materialized_views (
mview_name text NOT NULL PRIMARY KEY,
view_name text NOT NULL,
iname text,
last_refresh TIMESTAMP WITH TIME ZONE
);
All materialized views will have an entry in this table. It then adds the PL/pgSQL code to create tree functions:
create_materialized_view(text, text, text)is used to create a materialized viewdrop_materialized_view(text)is used to delete a materialized viewrefresh_full_materialized_view(text)is used to refresh a view
Then it adds the SQL code to create the view and the materialized view:
CREATE VIEW mviewname_mview AS
SELECT ... FROM ...;
SELECT create_materialized_view('mviewname','mviewname_mview', change with the name of the column to be used for the index);
The first argument is the name of the materialized view, the second the name of the view on which the materialized view is based and the third is the column name on which the index should be build (aka most of the time the primary key). This column is not automatically deduced so you need to replace its name.
As said above, ora2pgpro only supports snapshot materialized views so the table will be entirely refreshed by issuing first a truncate of the table and then by load again all data from the view:
refresh_full_materialized_view('mviewname');
To drop the materialized view, call the drop_materialized_view() function with the name of the materialized view as parameter.
DEBUGSetting it to 1 enables verbose output.
IMPORTYou can define common ora2pgpro configuration directives into a single file that can be imported into other configuration files with the
IMPORTconfiguration directive as follows:IMPORT commonfile.conf
This will import all configuration directives defined into
commonfile.confinto the current configuration file.
You can export any Oracle view as a Postgres Pro table simply by setting TYPE configuration option to TABLE to have the corresponding create table statement. Or use type COPY or INSERT to export the corresponding data. To allow that you have to specify your views in the VIEW_AS_TABLE configuration option.
Then, if ora2pgpro finds the view, it extracts its schema (if TYPE=TABLE) into a Postgres Pro CREATE TABLE form, then it will extract the data (if TYPE=COPY or TYPE=INSERT) following the view schema.
For example, with the following view:
CREATE OR REPLACE VIEW product_prices (category_id, product_count, low_price, high_price) AS
SELECT category_id, COUNT(*) as product_count,
MIN(list_price) as low_price,
MAX(list_price) as high_price
FROM product_information
GROUP BY category_id;
Setting VIEW_AS_TABLE to product_prices and using export type TABLE, will force ora2pgpro to detect columns returned types and to generate a create table statement:
CREATE TABLE product_prices (
category_id bigint,
product_count integer,
low_price numeric,
high_price numeric
);
Data will be loaded following the COPY or INSERT export type and the view declaration.
You can use the ALLOW and EXCLUDE directives in addition to filter other objects to export.
Estimating the cost of a migration process from Oracle to Postgres Pro is not easy. To obtain a good assessment of this migration cost, ora2pgpro will inspect all database objects, all functions and stored procedures to detect if there are still some objects and PL/SQL code that can not be automatically converted by ora2pgpro.
ora2pgpro has a content analysis mode that inspect the Oracle database to generate a text report on what the Oracle database contains and what can not be exported.
To activate the "analysis and report" mode, you have to use the export type SHOW_REPORT like in the following command:
ora2pgpro -t SHOW_REPORT
Here is a sample report obtained with this command:
--------------------------------------
Ora2Pg: Oracle Database Content Report
--------------------------------------
Version Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
Schema HR
Size 880.00 MB
--------------------------------------
Object Number Invalid Comments
--------------------------------------
CLUSTER 2 0 Clusters are not supported and will not be exported.
FUNCTION 40 0 Total size of function code: 81992.
INDEX 435 0 232 index(es) are concerned by the export, others are automatically generated and will
do so on PostgreSQL. 1 bitmap index(es). 230 b-tree index(es). 1 reversed b-tree index(es)
Note that bitmap index(es) will be exported as b-tree index(es) if any. Cluster, domain,
bitmap join and IOT indexes will not be exported at all. Reverse indexes are not exported
too, you may use a trigram-based index (see pg_trgm) or a reverse() function based index
and search. You may also use 'varchar_pattern_ops', 'text_pattern_ops' or 'bpchar_pattern_ops'
operators in your indexes to improve search with the LIKE operator respectively into
varchar, text or char columns.
MATERIALIZED VIEW 1 0 All materialized view will be exported as snapshot materialized views, they
are only updated when fully refreshed.
PACKAGE BODY 2 1 Total size of package code: 20700.
PROCEDURE 7 0 Total size of procedure code: 19198.
SEQUENCE 160 0 Sequences are fully supported, but all call to sequence_name.NEXTVAL or sequence_name.CURRVAL
will be transformed into NEXTVAL('sequence_name') or CURRVAL('sequence_name').
TABLE 265 0 1 external table(s) will be exported as standard table. See EXTERNAL_TO_FDW configuration
directive to export as file_fdw foreign tables or use COPY in your code if you just
want to load data from external files. 2 binary columns. 4 unknown types.
TABLE PARTITION 8 0 Partitions are exported using table inheritance and check constraint. 1 HASH partitions.
2 LIST partitions. 6 RANGE partitions. Note that Hash partitions are not supported.
TRIGGER 30 0 Total size of trigger code: 21677.
TYPE 7 1 5 type(s) are concerned by the export, others are not supported. 2 Nested Tables.
2 Object type. 1 Subtype. 1 Type Boby. 1 Type inherited. 1 Varrays. Note that Type
inherited and Subtype are converted as table, type inheritance is not supported.
TYPE BODY 0 3 Export of type with member method are not supported, they will not be exported.
VIEW 7 0 Views are fully supported, but if you have updatable views you will need to use
INSTEAD OF triggers.
DATABASE LINK 1 0 Database links will not be exported. You may try the dblink perl contrib module or use
the SQL/MED PostgreSQL features with the different Foreign Data Wrapper (FDW) extensions.
Note: Invalid code will not be exported unless the EXPORT_INVALID configuration directive is activated.
Once the database can be analysed, ora2pgpro, by its ability to convert SQL and PL/SQL code from Oracle syntax to Postgres Pro, can go further by estimating the code difficulties and estimate the time necessary to operate a full database migration.
To estimate the migration cost in man-days, ora2pgpro allows you to use a configuration directive ESTIMATE_COST that you can also enable in the command line: --estimate_cost.
This feature can only be used with the SHOW_REPORT, FUNCTION, PROCEDURE, PACKAGE, and QUERY export types.
ora2pgpro -t SHOW_REPORT --estimate_cost
The generated report is same as above but with a new Estimated cost column as follow:
--------------------------------------
Ora2Pg: Oracle Database Content Report
--------------------------------------
Version Oracle Database 10g Express Edition Release 10.2.0.1.0
Schema HR
Size 890.00 MB
--------------------------------------
Object Number Invalid Estimated cost Comments
--------------------------------------
DATABASE LINK 3 0 9 Database links will be exported as SQL/MED PostgreSQL's Foreign Data Wrapper (FDW) extensions
using oracle_fdw.
FUNCTION 2 0 7 Total size of function code: 369 bytes. HIGH_SALARY: 2, VALIDATE_SSN: 3.
INDEX 21 0 11 11 index(es) are concerned by the export, others are automatically generated and will do so
on PostgreSQL. 11 b-tree index(es). Note that bitmap index(es) will be exported as b-tree
index(es) if any. Cluster, domain, bitmap join and IOT indexes will not be exported at all.
Reverse indexes are not exported too, you may use a trigram-based index (see pg_trgm) or a
reverse() function based index and search. You may also use 'varchar_pattern_ops', 'text_pattern_ops'
or 'bpchar_pattern_ops' operators in your indexes to improve search with the LIKE operator
respectively into varchar, text or char columns.
JOB 0 0 0 Job are not exported. You may set external cron job with them.
MATERIALIZED VIEW 1 0 3 All materialized view will be exported as snapshot materialized views, they
are only updated when fully refreshed.
PACKAGE BODY 0 2 54 Total size of package code: 2487 bytes. Number of procedures and functions found
inside those packages: 7. two_proc.get_table: 10, emp_mgmt.create_dept: 4,
emp_mgmt.hire: 13, emp_mgmt.increase_comm: 4, emp_mgmt.increase_sal: 4,
emp_mgmt.remove_dept: 3, emp_mgmt.remove_emp: 2.
PROCEDURE 4 0 39 Total size of procedure code: 2436 bytes. TEST_COMMENTAIRE: 2, SECURE_DML: 3,
PHD_GET_TABLE: 24, ADD_JOB_HISTORY: 6.
SEQUENCE 3 0 0 Sequences are fully supported, but all call to sequence_name.NEXTVAL or sequence_name.CURRVAL
will be transformed into NEXTVAL('sequence_name') or CURRVAL('sequence_name').
SYNONYM 3 0 4 SYNONYMs will be exported as views. SYNONYMs do not exists with PostgreSQL but a common workaround
is to use views or set the PostgreSQL search_path in your session to access
object outside the current schema.
user1.emp_details_view_v is an alias to hr.emp_details_view.
user1.emp_table is an alias to hr.employees@other_server.
user1.offices is an alias to hr.locations.
TABLE 17 0 8.5 1 external table(s) will be exported as standard table. See EXTERNAL_TO_FDW configuration
directive to export as file_fdw foreign tables or use COPY in your code if you just want to
load data from external files. 2 binary columns. 4 unknown types.
TRIGGER 1 1 4 Total size of trigger code: 123 bytes. UPDATE_JOB_HISTORY: 2.
TYPE 7 1 5 5 type(s) are concerned by the export, others are not supported. 2 Nested Tables. 2 Object type.
1 Subtype. 1 Type Boby. 1 Type inherited. 1 Varrays. Note that Type inherited and Subtype are
converted as table, type inheritance is not supported.
TYPE BODY 0 3 30 Export of type with member method are not supported, they will not be exported.
VIEW 1 1 1 Views are fully supported, but if you have updatable views you will need to use INSTEAD OF triggers.
--------------------------------------
Total 65 8 162.5 162.5 cost migration units means approximatively 2 man day(s).
The last line shows the total estimated migration code in man-days following the number of migration units estimated for each object. This migration unit represent around five minutes for a Postgres Pro expert. If this is your first migration, you can get it higher with the configuration directive COST_UNIT_VALUE or the --cost_unit_value command line option:
ora2pgpro -t SHOW_REPORT --estimate_cost --cost_unit_value 10
ora2pgpro is also able to give you a migration difficulty level assessment, here is a sample: Migration level: B-5
Migration levels:
A - Migration that might be run automatically
B - Migration with code rewrite and a man-days cost up to 5 days
C - Migration with code rewrite and a man-days cost above 5 days
Technical levels:
1 = trivial: no stored functions and no triggers
2 = easy: no stored functions but with triggers, no manual rewriting
3 = simple: stored functions and/or triggers, no manual rewriting
4 = manual: no stored functions but with triggers or views with code rewriting
5 = difficult: stored functions and/or triggers with code rewriting
This assessment consists of a letter (A or B) to specify if the migration needs manual rewriting or not, and a number from 1 to 5 to give you a technical difficulty level. You have an additional option --human_days_limit to specify the number of man-days limit where the migration level should be set to C to indicate that it needs a huge amount of work and a full project management with migration support. Default is 10 man-days. You can use the configuration directive HUMAN_DAYS_LIMIT to change this default value permanently.
This feature has been developed to help you decide which database to migrate first and the team that must be mobilized to operate the migration.
ora2pgpro comes with a script ora2pgpro_scanner that can be used when you have a huge number of instances and schema to scan for migration assessment.
ora2pgpro_scanner -l CSVFILE [-o OUTDIR]
-b | --binpath DIR: full path to directory where the ora2pgpro binary stays.
Might be useful only on Windows OS.
-c | --config FILE: set custom configuration file to use otherwise ora2pgpro
will use the default: /etc/ora2pgpro/ora2pgpro.conf.
-l | --list FILE : CSV file containing a list of databases to scan with
all required information. The first line of the file
can contain the following header that describes the
format that must be used:
"type","schema/database","dsn","user","password"
-o | --outdir DIR : (optional) by default all reports will be dumped to a
directory named 'output', it will be created automatically.
If you want to change the name of this directory, set the name
at second argument.
-t | --test : just try all connections by retrieving the required schema
or database name. Useful to validate your CSV list file.
-u | --unit MIN : redefine globally the migration cost unit value in minutes.
Default is taken from the ora2pgpro.conf (default 5 minutes).
Here is a full example of a CSV databases list file:
"type","schema/database","dsn","user","password"
"MYSQL","sakila","dbi:mysql:host=192.168.1.10;database=sakila;port=3306","root","secret"
"ORACLE","HR","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager"
"MSSQL","HR","dbi:ODBC:driver=msodbcsql18;server=srv.database.windows.net;database=testdb","system","manager"
The CSV field separator must be a comma.
Note that if you want to scan all schemas from an Oracle instance you just
have to leave the schema field empty, Ora2PgPro will automatically detect all
available schemas and generate a report for each one. Of course you need to
use a connection user with enough privileges to be able to scan all schemas.
For example:
"ORACLE","","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager"
"MSSQL","","dbi:ODBC:driver=msodbcsql18;server=srv.database.windows.net;database=testdb","usrname","passwd"
will generate a report for all schema in the XE instance. Note that in this
case the SCHEMA directive in ora2pgpro.conf must not be set.
It will generate a CSV file with the assessment result, one line per schema or database and a detailed HTML report for each database scanned.
Hint: Use the -t | --test option before to test all your connections in your CSV file.
For Windows users you must use the -b command-line option to set the directory where ora2pgpro_scanner stays, otherwise the ora2pgpro command calls will fail.
In the migration assessment details about functions ora2pgpro always includes per default 2 migration units for TEST and 1 unit for SIZE per 1000 characters in the code. This mean that by default it will add 15 minutes in the migration assessment per function. Obviously, if you have unitary tests or very simple functions, this will not represent the real migration time.
Migration unit scores given to each type of Oracle database object are defined in the Perl library lib/Ora2Pg/PLSQL.pm in the %OBJECT_SCORE variable definition.
The number of PL/SQL lines associated to a migration unit is also defined in this file in the $SIZE_SCORE variable value.
The number of migration units associated to each PL/SQL code difficulties can be found in the same Perl library lib/Ora2Pg/PLSQL.pm in the hash %UNCOVERED_SCORE initialization.
This assessment method is a work in progress.
Using the LOAD export type and a file containing SQL orders to perform, it is possible to dispatch those orders over multiple Postgres Pro connections. To be able to use this feature, PG_DSN, PG_USER and PG_PWD must be set.
ora2pgpro -t LOAD -c config/ora2pgpro.conf -i schema/tables/INDEXES_table.sql -j 4
This will dispatch indexes creation over 4 simultaneous Postgres Pro connections. This will considerably accelerate this part of the migration process with huge data size.
If you still have columns defined as LONG RAW, ora2pgpro will not be able to export this kind of data. The OCI library fails to export them and always returns the same first record. To be able to export the data you need to transform the field as BLOB by creating a temporary table before migrating data.
SQL> DESC TEST_LONGRAW Name NULL ? Type -------------------- -------- ---------------------------- ID NUMBER C1 LONG RAW
For example, the above Oracle table needs to be "translated" into a table using BLOB as follows:
CREATE TABLE test_blob (id NUMBER, c1 BLOB);
And then copy the data with the following INSERT query:
INSERT INTO test_blob SELECT id, to_lob(c1) FROM test_longraw;
Then you just have to exclude the original table from the export (see EXCLUDE directive) and to rename the new temporary table onthe fly using the REPLACE_TABLES configuration directive.
Oracle allows the use of global variables defined in packages. ora2pgpro will export these variables as Postgres Pro package variables.
The type of action called TEST allows you to check that all objects from Oracle database have been created under Postgres Pro. PG_DSN must be set to be able to check the Postgres Pro side.
Note that this feature respects the schema name limitation if EXPORT_SCHEMA and SCHEMA or PG_SCHEMA are defined. If only EXPORT_SCHEMA is set, all schemes from Oracle and Postgres Pro are scanned. You can filter to a single schema using SCHEMA and/or PG_SCHEMA but you can not filter by a list of schemas. To test a list of schema, you will have to repeat the calls to ora2pgpro by specifying a single schema each time.
ora2pgpro -t TEST -c config/ora2pgpro.conf > migration_diff.txt
For example, this command will create a file containing the report of all object and row count on both sides, Oracle and Postgres Pro, with an error section giving you the details of the differences for each kind of object. Here is a sample result:
[TEST INDEXES COUNT] ORACLEDB:DEPARTMENTS:2 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:6 POSTGRES:employees:6 [ERRORS INDEXES COUNT] Table departments don't have the same number of indexes in Oracle (2) and in PostgreSQL (1). [TEST UNIQUE CONSTRAINTS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS UNIQUE CONSTRAINTS COUNT] OK, Oracle and PostgreSQL have the same number of unique constraints. [TEST PRIMARY KEYS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS PRIMARY KEYS COUNT] OK, Oracle and PostgreSQL have the same number of primary keys. [TEST CHECK CONSTRAINTS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS CHECK CONSTRAINTS COUNT] OK, Oracle and PostgreSQL have the same number of check constraints. [TEST NOT NULL CONSTRAINTS COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS NOT NULL CONSTRAINTS COUNT] OK, Oracle and PostgreSQL have the same number of not null constraints. [TEST COLUMN DEFAULT VALUE COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS COLUMN DEFAULT VALUE COUNT] OK, Oracle and PostgreSQL have the same number of column default value. [TEST IDENTITY COLUMN COUNT] ORACLEDB:DEPARTMENTS:1 POSTGRES:departments:1 ORACLEDB:EMPLOYEES:0 POSTGRES:employees:0 [ERRORS IDENTITY COLUMN COUNT] OK, Oracle and PostgreSQL have the same number of identity column. [TEST FOREIGN KEYS COUNT] ORACLEDB:DEPARTMENTS:0 POSTGRES:departments:0 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS FOREIGN KEYS COUNT] OK, Oracle and PostgreSQL have the same number of foreign keys. [TEST TABLE COUNT] ORACLEDB:TABLE:2 POSTGRES:TABLE:2 [ERRORS TABLE COUNT] OK, Oracle and PostgreSQL have the same number of TABLE. [TEST TABLE TRIGGERS COUNT] ORACLEDB:DEPARTMENTS:0 POSTGRES:departments:0 ORACLEDB:EMPLOYEES:1 POSTGRES:employees:1 [ERRORS TABLE TRIGGERS COUNT] OK, Oracle and PostgreSQL have the same number of table triggers. [TEST TRIGGER COUNT] ORACLEDB:TRIGGER:2 POSTGRES:TRIGGER:2 [ERRORS TRIGGER COUNT] OK, Oracle and PostgreSQL have the same number of TRIGGER. [TEST VIEW COUNT] ORACLEDB:VIEW:1 POSTGRES:VIEW:1 [ERRORS VIEW COUNT] OK, Oracle and PostgreSQL have the same number of VIEW. [TEST MVIEW COUNT] ORACLEDB:MVIEW:0 POSTGRES:MVIEW:0 [ERRORS MVIEW COUNT] OK, Oracle and PostgreSQL have the same number of MVIEW. [TEST SEQUENCE COUNT] ORACLEDB:SEQUENCE:1 POSTGRES:SEQUENCE:0 [ERRORS SEQUENCE COUNT] SEQUENCE does not have the same count in Oracle (1) and in PostgreSQL (0). [TEST TYPE COUNT] ORACLEDB:TYPE:1 POSTGRES:TYPE:0 [ERRORS TYPE COUNT] TYPE does not have the same count in Oracle (1) and in PostgreSQL (0). [TEST FDW COUNT] ORACLEDB:FDW:0 POSTGRES:FDW:0 [ERRORS FDW COUNT] OK, Oracle and PostgreSQL have the same number of FDW. [TEST FUNCTION COUNT] ORACLEDB:FUNCTION:3 POSTGRES:FUNCTION:3 [ERRORS FUNCTION COUNT] OK, Oracle and PostgreSQL have the same number of functions. [TEST SEQUENCE VALUES] ORACLEDB:EMPLOYEES_NUM_SEQ:1285 POSTGRES:employees_num_seq:1285 [ERRORS SEQUENCE VALUES COUNT] OK, Oracle and PostgreSQL have the same values for sequences [TEST ROWS COUNT] ORACLEDB:DEPARTMENTS:27 POSTGRES:departments:27 ORACLEDB:EMPLOYEES:854 POSTGRES:employees:854 [ERRORS ROWS COUNT] OK, Oracle and PostgreSQL have the same number of rows.
Data validation consists in comparing data retrieved from a foreign table pointing to the source Oracle table and a local Postgres Pro table resulting from the data export.
To run data validation, you can use a direct connection like any other ora2pgpro action but you can also use the oracle_fdw extension provided that FDW_SERVER and PG_DSN configuration directives are set.
By default, ora2pgpro will extract the 10000 first rows from both sides, you can change this value using directive DATA_VALIDATION_ROWS. When it is set to zero, all rows of the tables will be compared.
Data validation requires that the table has a primary key or unique index and that the key columns is not a LOB. Rows will be sorted using this unique key. Due to differences in sort behavior between Oracle and Postgres Pro, if the collation of unique key columns in Postgres Pro is not C, the sort order can be different compared to Oracle. In this case the data validation will fail.
Data validation must be done before any data is modified.
ora2pgpro will stop comparing two tables after DATA_VALIDATION_ROWS is reached or that 10 errors has been encountered, result is dumped in a file named data_validation.log written in the current directory by default. The number of error before stopping the diff between rows can be controlled using the configuration directive DATA_VALIDATION_ERROR. All rows in errors are printed to the output file for your analyze.
It is possible to parallelize data validation by using -P option or the corresponding configuration directive PARALLEL_TABLES in ora2pgpro.conf.
ora2pgpro is able to export data as of a specific SCN. You can set it at command line using the -S or --scn option. You can give a specific SCN or if you want to use the current SCN at first connection time set the value to current. In this last case, the connection user has the SELECT ANY DICTIONARY or the SELECT_CATALOG_ROLE role, the current SCN is looked at the v$database view.
ora2pgpro -c ora2pgpro.conf -t COPY --scn 16605281
This adds the following clause to the query used to retrieve data for example:
AS OF SCN 16605281
You can also use the --scn option to use the Oracle flashback capabality by specifying a timestamp expression instead of a SCN.
ora2pgpro -c ora2pgpro.conf -t COPY --scn "TO_TIMESTAMP('2021-12-01 00:00:00', 'YYYY-MM-DD HH:MI:SS')"
This will add the following clause to the query used to retrieve data:
AS OF TIMESTAMP TO_TIMESTAMP('2021-12-01 00:00:00', 'YYYY-MM-DD HH:MI:SS')
Or for example to only retrive yesterday's data:
ora2pgpro -c ora2pgpro.conf -t COPY --scn "SYSDATE - 1"
ora2pgpro does not allow to import data and to only apply changes after the first import. But you can use the --cdc_ready option to export data with registration of the SCN at the time of the table export. All SCN per tables are written to a file named TABLES_SCN.log by default, it can be changed using -C|--cdc_file option.
These SCN registered per table during COPY or INSERT export can be used with a CDC tool. The format of the file is tablename:SCN per line.
By default ora2pgpro imports Oracle BLOB as bytea, the destination column is created using the bytea data type. If you want to use large object instead of bytea, just add the --blob_to_lo option to the ora2pgpro command. It will create the destination column as data type oid and will save the BLOB as a large object using the lo_from_bytea() function. The OID returned by the call to lo_from_bytea() is inserted in the destination column instead of a bytea. Because of the use of the function, this option can only be used with actions SHOW_COLUMN, TABLE and INSERT. Action COPY is not allowed.
If you want to use COPY or have huge size BLOB ( > 1GB) than can not be imported using lo_from_bytea(), you can add option --lo_import to the ora2pgpro command. This will allow to import data in two passes.
Export data using
COPYorINSERTwill set the OID destination column for BLOB to value 0 and save the BLOB value into a dedicated file. It will also create a Shell script to import the BLOB files into the database using psql command\lo_importand to update the table OID column to the returned large object OID. The script is namedlo_import-TABLENAME.sh.Execute all scripts
lo_import-TABLENAME.shafter setting the environment variablesPGDATABASEand optionallyPGHOST,PGPORT,PGUSER, etc. if they do not correspond to the default values for libpq.
You might also execute manually a VACUUM FULL on the table to remove the bloat created by the table update.
![]() | Note |
|---|---|
Limitation: the table must have a primary key, it is used to set the |
![[Примечание]](https://repo.postgrespro.ru/doc/ora2pgpro/23.2.3/ru/html/html/note.png)
![[Note]](https://repo.postgrespro.ru/doc/ora2pgpro/23.2.3/en/html/html/note.png)