From d406a7f7c5cc99ea6de84f7bee68e7a7ef5ba152 Mon Sep 17 00:00:00 2001 From: Steven Niu Date: Thu, 3 Dec 2026 12:57:52 +0800 Subject: [PATCH 1/5] fix docs errors --- CN/modules/ROOT/nav.adoc | 3 --- .../compat_alter_index_unusable.adoc | 14 ++++++++++ .../compat_create_index_online.adoc | 3 --- EN/modules/ROOT/nav.adoc | 26 +++++++++---------- ...pl.adoc => all_tab_columns_view_impl.adoc} | 0 ...en.adoc => alter_index_unusable_impl.adoc} | 0 ...ect_en.adoc => create_type_as_object.adoc} | 0 ...adoc => with_function_procedure_impl.adoc} | 0 .../{pg_readonly_en.adoc => pg_readonly.adoc} | 0 ...zer_en.adoc => postgresql_anonymizer.adoc} | 0 .../{zhparser_en.adoc => zhparser.adoc} | 0 ...zone_impl_en.adoc => dbtimezone_impl.adoc} | 0 .../{vsize_en.adoc => vsize.adoc} | 0 ....adoc => compat_all_tab_columns_view.adoc} | 0 ....adoc => compat_alter_index_unusable.adoc} | 14 ++++++++++ .../compat_create_index_online.adoc | 3 --- ...adoc => compat_create_type_as_object.adoc} | 0 ...imezone_en.adoc => compat_dbtimezone.adoc} | 0 ...e_en.adoc => with_function_procedure.adoc} | 0 19 files changed, 40 insertions(+), 23 deletions(-) rename EN/modules/ROOT/pages/v6.0/compatibility_features_design/{xxx_cons_columns_view_impl.adoc => all_tab_columns_view_impl.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/compatibility_features_design/{alter_index_unusable_impl_en.adoc => alter_index_unusable_impl.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/compatibility_features_design/{create_type_as_object_en.adoc => create_type_as_object.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/compatibility_features_design/{with_function_procedure_impl_en.adoc => with_function_procedure_impl.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/ecosystem_components/{pg_readonly_en.adoc => pg_readonly.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/ecosystem_components/{postgresql_anonymizer_en.adoc => postgresql_anonymizer.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/ecosystem_components/{zhparser_en.adoc => zhparser.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/{dbtimezone_impl_en.adoc => dbtimezone_impl.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/{vsize_en.adoc => vsize.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{compat_xxx_cons_columns_view.adoc => compat_all_tab_columns_view.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{compat_alter_index_unusable_en.adoc => compat_alter_index_unusable.adoc} (96%) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{compat_create_type_as_object_en.adoc => compat_create_type_as_object.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{compat_dbtimezone_en.adoc => compat_dbtimezone.adoc} (100%) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{with_function_procedure_en.adoc => with_function_procedure.adoc} (100%) diff --git a/CN/modules/ROOT/nav.adoc b/CN/modules/ROOT/nav.adoc index 063bbdd3..aa3f8ac9 100644 --- a/CN/modules/ROOT/nav.adoc +++ b/CN/modules/ROOT/nav.adoc @@ -44,7 +44,6 @@ ** xref:v6.0/oracle_compatibility/to_number_scientific_notation.adoc[TO_NUMBER科学计数法] ** xref:v6.0/oracle_compatibility/compat_modify_column_compatibility.adoc[MODIFY列兼容] ** xref:v6.0/oracle_compatibility/compat_dynamic_performance_view.adoc[动态性能视图] -** xref:v6.0/oracle_compatibility/compat_xxx_cons_columns_view.adoc[约束列视图] ** xref:v6.0/oracle_compatibility/compat_all_tab_columns_view.adoc[表列信息视图] ** xref:v6.0/oracle_compatibility/compat_utl_raw.adoc[UTL_RAW包] ** xref:v6.0/oracle_compatibility/compat_utl_url.adoc[UTL_URL包] @@ -63,7 +62,6 @@ ** xref:v6.0/oracle_compatibility/nanvl.adoc[NAN替换函数] ** xref:v6.0/oracle_compatibility/compat_lnnvl_function.adoc[LNNVL条件函数] ** xref:v6.0/oracle_compatibility/compat_lengthc_function.adoc[字符长度函数] -** xref:v6.0/oracle_compatibility/compat_dbtimezone_function.adoc[数据库时区函数] ** xref:v6.0/oracle_compatibility/compat_to_binary_float_function.adoc[二进制浮点转换函数] ** xref:v6.0/oracle_compatibility/compat_to_binary_double_function.adoc[双精度浮点转换函数] ** xref:v6.0/oracle_compatibility/compat_create_type_as_object.adoc[类型对象] @@ -157,7 +155,6 @@ **** xref:v6.0/oracle_builtin_functions/to_number_scientific_notation.adoc[TO_NUMBER科学计数法] **** xref:v6.0/compatibility_features_design/modify_column_compatibility_impl.adoc[MODIFY列兼容] **** xref:v6.0/compatibility_features_design/dynamic_performance_view_impl.adoc[动态性能视图] -**** xref:v6.0/compatibility_features_design/xxx_cons_columns_view_impl.adoc[约束列视图] **** xref:v6.0/compatibility_features_design/all_tab_columns_view_impl.adoc[表列信息视图] **** xref:v6.0/compatibility_features_design/utl_raw_impl.adoc[UTL_RAW包] **** xref:v6.0/compatibility_features_design/utl_url_impl.adoc[UTL_URL包] diff --git a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc index 0b77fdf6..0122fd3d 100644 --- a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc +++ b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc @@ -51,6 +51,20 @@ ALTER INDEX idx_emp_email UNUSABLE; -- 装载前禁用索引维护 ALTER INDEX idx_emp_email UNUSABLE; +-- 创建暂存表 +CREATE TABLE staging_emp ( + id int, + email text +); + +-- 插入测试数据 +INSERT INTO staging_emp (id, email) VALUES + (1, 'alice@example.com'), + (2, 'bob@example.com'), + (3, 'carol@example.com'), + (4, 'david@example.com'), + (5, 'eva@example.com'); + -- 批量装载数据(跳过索引维护开销) INSERT INTO emp SELECT * FROM staging_emp; diff --git a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc index fb3ea4b6..ed30c8d8 100644 --- a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc +++ b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc @@ -86,9 +86,6 @@ JOIN pg_class c ON c.oid = i.indexrelid WHERE c.relname LIKE '%idx_part_online%' ORDER BY c.relname; -- 期望:idx_part_online(父)及两个分区子索引 indisvalid = t - --- 分区表 ONLINE + TABLESPACE -CREATE INDEX idx_part_online_tbs ON tbl_ci_part (region) ONLINE TABLESPACE pg_default; ---- === CONCURRENTLY 与 ONLINE 互斥 diff --git a/EN/modules/ROOT/nav.adoc b/EN/modules/ROOT/nav.adoc index 52fec218..b25c4031 100644 --- a/EN/modules/ROOT/nav.adoc +++ b/EN/modules/ROOT/nav.adoc @@ -27,11 +27,11 @@ ** xref:v6.0/oracle_compatibility/compat_empty_string_to_null.adoc[Empty String to NULL] ** xref:v6.0/oracle_compatibility/compat_call_into.adoc[CALL INTO] ** xref:v6.0/oracle_compatibility/compat_read_only_view.adoc[Read Only View] -** xref:v6.0/oracle_compatibility/with_function_procedure_en.adoc[WITH FUNCTION/PROCEDURE] +** xref:v6.0/oracle_compatibility/with_function_procedure.adoc[WITH FUNCTION/PROCEDURE] ** xref:v6.0/oracle_compatibility/compat_create_index_online.adoc[ONLINE Parameter for CREATE INDEX] ** xref:v6.0/oracle_compatibility/compat_stragg.adoc[STRAGG function] -** xref:v6.0/oracle_compatibility/compat_alter_index_unusable_en.adoc[Alter Index Unusable] -** xref:v6.0/oracle_compatibility/compat_dbtimezone_en.adoc[dbtimezone] +** xref:v6.0/oracle_compatibility/compat_alter_index_unusable.adoc[Alter Index Unusable] +** xref:v6.0/oracle_compatibility/compat_dbtimezone.adoc[dbtimezone] ** xref:v6.0/oracle_compatibility/compat_user_defined_exception.adoc[User-defined Exception] ** xref:v6.0/oracle_compatibility/compat_for_loop_implicit_record.adoc[FOR Loop Implicit Record Declaration] ** xref:v6.0/oracle_compatibility/compat_autonomous_transaction.adoc[Autonomous Transaction] @@ -44,7 +44,6 @@ ** xref:v6.0/oracle_compatibility/to_number_scientific_notation.adoc[TO_NUMBER Scientific Notation Support] ** xref:v6.0/oracle_compatibility/compat_modify_column_compatibility.adoc[MODIFY Column Compatibility] ** xref:v6.0/oracle_compatibility/compat_dynamic_performance_view.adoc[Dynamic Performance View] -** xref:v6.0/oracle_compatibility/compat_xxx_cons_columns_view.adoc[XXX_CONS_COLUMNS View] ** xref:v6.0/oracle_compatibility/compat_all_tab_columns_view.adoc[ALL_TAB_COLUMNS View] ** xref:v6.0/oracle_compatibility/compat_utl_raw.adoc[UTL_RAW Package] ** xref:v6.0/oracle_compatibility/compat_utl_url.adoc[UTL_URL Package] @@ -65,7 +64,7 @@ ** xref:v6.0/oracle_compatibility/compat_lengthc_function.adoc[LENGTHC Function] ** xref:v6.0/oracle_compatibility/compat_to_binary_float_function.adoc[TO_BINARY_FLOAT Function] ** xref:v6.0/oracle_compatibility/compat_to_binary_double_function.adoc[TO_BINARY_DOUBLE Function] -** xref:v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc[TYPE AS OBJECT] +** xref:v6.0/oracle_compatibility/compat_create_type_as_object.adoc[TYPE AS OBJECT] * Containerization and Cloud Service ** Containerization *** xref:v6.0/containerization/k8s_deployment.adoc[K8S deployment] @@ -103,13 +102,13 @@ *** xref:v6.0/ecosystem_components/pg_profile.adoc[pg_profile] *** xref:v6.0/ecosystem_components/pg_repack.adoc[pg_repack] *** xref:v6.0/ecosystem_components/pgdog.adoc[PgDog] -*** xref:v6.0/ecosystem_components/pg_readonly_en.adoc[pg_readonly] -*** xref:v6.0/ecosystem_components/zhparser_en.adoc[zhparser] +*** xref:v6.0/ecosystem_components/pg_readonly.adoc[pg_readonly] +*** xref:v6.0/ecosystem_components/zhparser.adoc[zhparser] *** xref:v6.0/ecosystem_components/pgbackrest.adoc[pgBackRest] *** xref:v6.0/ecosystem_components/set_user.adoc[set_user] *** xref:v6.0/ecosystem_components/pg_jieba.adoc[pg_jieba] *** xref:v6.0/ecosystem_components/pg_track_settings.adoc[pg_track_settings] -*** xref:v6.0/ecosystem_components/postgresql_anonymizer_en.adoc[postgresql_anonymizer] +*** xref:v6.0/ecosystem_components/postgresql_anonymizer.adoc[postgresql_anonymizer] * Monitor and O&M ** xref:v6.0/getting-started/daily_monitoring.adoc[Monitoring] ** xref:v6.0/getting-started/daily_maintenance.adoc[Maintenance] @@ -141,9 +140,9 @@ *** xref:v6.0/compatibility_features_design/empty_string_to_null.adoc[Empty String to NULL] *** xref:v6.0/compatibility_features_design/call_into.adoc[CALL INTO] *** xref:v6.0/compatibility_features_design/read_only_view.adoc[Read Only View] -*** xref:v6.0/compatibility_features_design/with_function_procedure_impl_en.adoc[WITH FUNCTION/PROCEDURE] +*** xref:v6.0/compatibility_features_design/with_function_procedure_impl.adoc[WITH FUNCTION/PROCEDURE] *** xref:v6.0/compatibility_features_design/create_index_online.adoc[ONLINE Parameter for CREATE INDEX] -*** xref:v6.0/compatibility_features_design/alter_index_unusable_impl_en.adoc[Alter Index Unusable] +*** xref:v6.0/compatibility_features_design/alter_index_unusable_impl.adoc[Alter Index Unusable] *** xref:v6.0/compatibility_features_design/user_defined_exception.adoc[User-defined Exception] *** xref:v6.0/compatibility_features_design/for_loop_implicit_record_impl.adoc[FOR Loop Implicit Record Declaration] *** xref:v6.0/compatibility_features_design/autonomous_transaction_impl.adoc[Autonomous Transaction] @@ -156,7 +155,6 @@ *** xref:v6.0/oracle_builtin_functions/to_number_scientific_notation.adoc[TO_NUMBER Scientific Notation Support] *** xref:v6.0/compatibility_features_design/modify_column_compatibility_impl.adoc[MODIFY Column Compatibility] *** xref:v6.0/compatibility_features_design/dynamic_performance_view_impl.adoc[Dynamic Performance View] -*** xref:v6.0/compatibility_features_design/xxx_cons_columns_view_impl.adoc[XXX_CONS_COLUMNS View] *** xref:v6.0/compatibility_features_design/all_tab_columns_view_impl.adoc[ALL_TAB_COLUMNS View] *** xref:v6.0/compatibility_features_design/utl_raw_impl.adoc[UTL_RAW Package] *** xref:v6.0/compatibility_features_design/utl_url_impl.adoc[UTL_URL Package] @@ -169,14 +167,14 @@ *** xref:v6.0/compatibility_features_design/dbms_utility_impl.adoc[DBMS_UTILITY Package] *** xref:v6.0/compatibility_features_design/dbms_scheduler_impl.adoc[DBMS_SCHEDULER Package] *** xref:v6.0/compatibility_features_design/dbms_transaction_impl.adoc[DBMS_TRANSACTION Package] -*** xref:v6.0/compatibility_features_design/create_type_as_object_en.adoc[TYPE AS OBJECT] +*** xref:v6.0/compatibility_features_design/create_type_as_object.adoc[TYPE AS OBJECT] ** Built-in Functions *** xref:v6.0/oracle_builtin_functions/sys_context.adoc[sys_context] *** xref:v6.0/oracle_builtin_functions/userenv.adoc[userenv] *** xref:v6.0/oracle_builtin_functions/rawtohex.adoc[rawtohex] *** xref:v6.0/oracle_builtin_functions/stragg.adoc[stragg] -*** xref:v6.0/oracle_builtin_functions/dbtimezone_impl_en.adoc[dbtimezone] -*** xref:v6.0/oracle_builtin_functions/vsize_en.adoc[vsize] +*** xref:v6.0/oracle_builtin_functions/dbtimezone_impl.adoc[dbtimezone] +*** xref:v6.0/oracle_builtin_functions/vsize.adoc[vsize] *** xref:v6.0/compatibility_features_design/ascii_function_impl.adoc[ASCII Function] *** xref:v6.0/compatibility_features_design/listagg_function_impl.adoc[LISTAGG Aggregate Function] *** xref:v6.0/compatibility_features_design/rawtohex_function_impl.adoc[RAWTOHEX Function] diff --git a/EN/modules/ROOT/pages/v6.0/compatibility_features_design/xxx_cons_columns_view_impl.adoc b/EN/modules/ROOT/pages/v6.0/compatibility_features_design/all_tab_columns_view_impl.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/compatibility_features_design/xxx_cons_columns_view_impl.adoc rename to EN/modules/ROOT/pages/v6.0/compatibility_features_design/all_tab_columns_view_impl.adoc diff --git a/EN/modules/ROOT/pages/v6.0/compatibility_features_design/alter_index_unusable_impl_en.adoc b/EN/modules/ROOT/pages/v6.0/compatibility_features_design/alter_index_unusable_impl.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/compatibility_features_design/alter_index_unusable_impl_en.adoc rename to EN/modules/ROOT/pages/v6.0/compatibility_features_design/alter_index_unusable_impl.adoc diff --git a/EN/modules/ROOT/pages/v6.0/compatibility_features_design/create_type_as_object_en.adoc b/EN/modules/ROOT/pages/v6.0/compatibility_features_design/create_type_as_object.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/compatibility_features_design/create_type_as_object_en.adoc rename to EN/modules/ROOT/pages/v6.0/compatibility_features_design/create_type_as_object.adoc diff --git a/EN/modules/ROOT/pages/v6.0/compatibility_features_design/with_function_procedure_impl_en.adoc b/EN/modules/ROOT/pages/v6.0/compatibility_features_design/with_function_procedure_impl.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/compatibility_features_design/with_function_procedure_impl_en.adoc rename to EN/modules/ROOT/pages/v6.0/compatibility_features_design/with_function_procedure_impl.adoc diff --git a/EN/modules/ROOT/pages/v6.0/ecosystem_components/pg_readonly_en.adoc b/EN/modules/ROOT/pages/v6.0/ecosystem_components/pg_readonly.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/ecosystem_components/pg_readonly_en.adoc rename to EN/modules/ROOT/pages/v6.0/ecosystem_components/pg_readonly.adoc diff --git a/EN/modules/ROOT/pages/v6.0/ecosystem_components/postgresql_anonymizer_en.adoc b/EN/modules/ROOT/pages/v6.0/ecosystem_components/postgresql_anonymizer.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/ecosystem_components/postgresql_anonymizer_en.adoc rename to EN/modules/ROOT/pages/v6.0/ecosystem_components/postgresql_anonymizer.adoc diff --git a/EN/modules/ROOT/pages/v6.0/ecosystem_components/zhparser_en.adoc b/EN/modules/ROOT/pages/v6.0/ecosystem_components/zhparser.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/ecosystem_components/zhparser_en.adoc rename to EN/modules/ROOT/pages/v6.0/ecosystem_components/zhparser.adoc diff --git a/EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/dbtimezone_impl_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/dbtimezone_impl.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/dbtimezone_impl_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/dbtimezone_impl.adoc diff --git a/EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/vsize_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/vsize.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/vsize_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_builtin_functions/vsize.adoc diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_xxx_cons_columns_view.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_all_tab_columns_view.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_xxx_cons_columns_view.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_all_tab_columns_view.adoc diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc similarity index 96% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc index ec6a0df6..51ff6c3b 100644 --- a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable_en.adoc +++ b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_alter_index_unusable.adoc @@ -51,6 +51,20 @@ ALTER INDEX idx_emp_email UNUSABLE; -- Disable index maintenance before loading ALTER INDEX idx_emp_email UNUSABLE; +-- Create test table +CREATE TABLE staging_emp ( + id int, + email text +); + +-- Insert test data +INSERT INTO staging_emp (id, email) VALUES + (1, 'alice@example.com'), + (2, 'bob@example.com'), + (3, 'carol@example.com'), + (4, 'david@example.com'), + (5, 'eva@example.com'); + -- Bulk load data (skips index maintenance overhead) INSERT INTO emp SELECT * FROM staging_emp; diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc index 86392c14..65b3fa86 100644 --- a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc +++ b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_index_online.adoc @@ -88,9 +88,6 @@ JOIN pg_class c ON c.oid = i.indexrelid WHERE c.relname LIKE '%idx_part_online%' ORDER BY c.relname; -- Expected: idx_part_online (parent) and both partition child indexes have indisvalid = t - --- Partitioned table ONLINE + TABLESPACE -CREATE INDEX idx_part_online_tbs ON tbl_ci_part (region) ONLINE TABLESPACE pg_default; ---- === CONCURRENTLY and ONLINE Are Mutually Exclusive diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object.adoc diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_dbtimezone_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_dbtimezone.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_dbtimezone_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_dbtimezone.adoc diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc From 797d5916f01920c77b14d02e6cfd1a9d8f26c621 Mon Sep 17 00:00:00 2001 From: Steven Niu Date: Thu, 3 Dec 2026 15:51:27 +0800 Subject: [PATCH 2/5] update utl_file doc and with_function_procedure --- .../utl_file_impl.adoc | 136 ++-- .../oracle_compatibility/compat_utl_file.adoc | 683 ++++++++++------- .../with_function_procedure.adoc | 25 + .../utl_file_impl.adoc | 154 ++-- .../oracle_compatibility/compat_utl_file.adoc | 685 +++++++++++------- .../with_function_procedure.adoc | 24 + 6 files changed, 1083 insertions(+), 624 deletions(-) diff --git a/CN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc b/CN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc index 5c0d8170..8f4944c2 100644 --- a/CN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc +++ b/CN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc @@ -5,121 +5,153 @@ == 目的 -IvorySQL 实现 Oracle 的 `UTL_FILE` 包,提供服务端文本文件 I/O 能力,支持文件的打开、关闭、读写、刷新、位置定位、属性查询以及复制、删除和重命名。其公开 API、打开模式、行长限制、最多 50 个同时打开文件的上限以及异常命名均与 Oracle 保持一致。用户示例见 xref:v6.0/oracle_compatibility/compat_utl_file.adoc[UTL_FILE 包]。 +IvorySQL 的 `UTL_FILE` 包提供服务端文件的打开、关闭、读写、刷新、定位、属性查询、复制、删除和重命名功能。它提供部分 Oracle 兼容接口,具体使用及兼容性边界见 link:compat_utl_file.adoc[UTL_FILE 包]。 -实现同时补齐了 PostgreSQL 内置文件函数不具备的两层安全机制: - -* `sys.utl_file_directory` 注册表,以白名单方式限定可访问目录,对应 Oracle 的目录对象; -* `utl_file.umask` GUC 参数,控制 `FOPEN` 创建文件的权限掩码。 +文件由数据库服务进程访问。`sys.utl_file_directory` 登记允许访问的目录,`utl_file.umask` 控制 `FOPEN` 新建文件的权限掩码。 == 实现说明 === 代码组织与调用关系 +下表路径均相对于 `contrib/ivorysql_ora/`。 + [cols="3,3",options="header"] |=== |源码路径 |职责 -|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql` |注册 C 入口 `sys.ora_utl_file_*`、复合类型(`ORA_UTL_FILE_FILE_TYPE`、`ora_utl_file_fgetattr_result`)、`sys.utl_file_directory` 表,以及 `UTL_FILE` 包说明与包体 -|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` |C 实现:路径安全检查、句柄槽位管理、基于 stdio 的 I/O、umask GUC 钩子 -|`contrib/ivorysql_ora/sql/utl_file.sql` |回归用例 -|`contrib/ivorysql_ora/expected/utl_file.out` |预期结果 -|`Makefile`、`meson.build`、`ivorysql_ora_merge_sqls` |新目录的构建集成与 SQL 合并 -|`src/ivorysql_ora.c` |在 `_PG_init` 中声明 `utl_file.umask` 自定义 GUC +|`src/builtin_packages/utl_file/utl_file--1.0.sql` |定义 `sys.ora_utl_file_*` 底层函数、`ora_utl_file_fgetattr_result` 复合类型、目录表和 `UTL_FILE` 包。 +|`src/builtin_packages/utl_file/utl_file.c` |实现路径检查、句柄槽位、stdio I/O、资源清理及 umask 钩子。 +|`sql/utl_file.sql`、`sql/utl_file_putf.sql` 及 `expected/` 下同名 `.out` 文件 |包接口、句柄生命周期和多字节格式化写入的回归用例及预期结果。 +|`Makefile`、`meson.build`、`ivorysql_ora_merge_sqls`、`gensql.pl` |编译共享库,并依据 SQL 路径清单和版本生成扩展安装脚本。 +|`src/ivorysql_ora.c` |在 `_PG_init()` 中注册 `utl_file.umask`。 |=== +主要调用关系如下(省略参数检查和错误分支): + [source,text] ---- -UTL_FILE.FOPEN(location, filename, open_mode, max_linesize) - → 包体: file.id := sys.ora_utl_file_fopen(location, filename, open_mode, max_linesize) - → ora_utl_file_fopen() → get_safe_path() → fopen() → reserve_slot() +UTL_FILE.FOPEN(...) + → sys.ora_utl_file_fopen(...) + → get_safe_path() → 临时切换 umask → fopen() → 恢复 umask → reserve_slot() UTL_FILE.PUT_LINE(file, buffer, autoflush) → sys.ora_utl_file_put_line(file.id, buffer, autoflush) - → ora_utl_file_put_line() → get_file_handle_from_slot() → fprintf()/fflush() + → do_put() → do_write() → 编码转换、长度检查、fwrite() + → put_lines() → fputc('\n') → 按 autoflush 决定是否 fflush() UTL_FILE.GET_LINE(file, buffer, len) → sys.ora_utl_file_get_line(file.id, len) - → ora_utl_file_get_line() → get_line()(文件末尾返回 NULL) + → get_line() → fgetc()/ungetc() → 编码校验和转换 + → 返回 TEXT;若因 EOF 未读到任何字符,则抛出 NO_DATA_FOUND ---- -包体中的 `UTL_FILE.*` 子程序只是薄封装:拆开复合文件句柄,把数字槽位 id 转发给 `sys.ora_utl_file_*` C 入口。`FOPEN_NCHAR`/`GET_LINE_NCHAR`/`PUT_LINE_NCHAR` 显式传入编码名 `UTF8`;不带编码参数的 `FOPEN` 使用数据库编码。 +公开句柄是包内记录 `UTL_FILE.FILE_TYPE`,包含 `id`、`datatype` 和 `byte_mode`;不存在 `sys.ora_utl_file_file_type` SQL 类型。包体将 `file.id` 转交底层函数,后者通过 C 入口或 SQL 包装重载完成操作。 + +`FOPEN` 使用数据库编码,`FOPEN_NCHAR` 在打开时显式传入 `'UTF8'`。实际编码保存在 C 槽位中,`GET_LINE_NCHAR`、`PUT_LINE_NCHAR` 不重新设置编码,也不检查记录的 `datatype`。`PUT_LINE_NCHAR` 固定启用刷新;当前没有实现字节打开模式。 === 安全模型 ==== 目录注册表 -访问被限制在注册于 `sys.utl_file_directory (dirname name PRIMARY KEY, dir TEXT)` 的目录内。先 `REVOKE ALL ... FROM PUBLIC` 再 `GRANT SELECT TO PUBLIC`,即只有超级用户能维护注册表,普通用户只读可见。 +安装脚本创建 `sys.utl_file_directory(dirname name PRIMARY KEY, dir TEXT)`,撤销 `PUBLIC` 的全部权限后授予 `SELECT`。表所有者、超级用户或获得相应表权限的角色可以维护登记。该表不提供按用户分别授予目录 `READ`/`WRITE` 的权限模型。 + +需要文件路径的操作均经过 `get_safe_path()`;复制和重命名分别检查源、目标路径: -所有把 `location` + `filename` 拼接为文件系统路径的操作都要经过 `get_safe_path()`: +. `safe_named_location()` 按 `dirname` 等值查找别名,命中非空路径时替换,否则将 `location` 当作路径。 +. 拼接目录、`/` 和 `filename`,调用 `canonicalize_path()` 规范化。 +. `check_secure_locality()` 执行 SPI 查询,检查完整路径是否位于某个登记目录之下。 -. `safe_named_location()` 按 `dirname` 精确等值查找(有意不用 `LIKE`,避免 `_`/`%` 的特殊语义),命中则替换为注册路径。 -. 拼出完整路径后先做 `canonicalize_path()` 规范化。 -. `check_secure_locality()` 通过缓存的 SPI 查询,用带显式 `/` 处理的前缀比较验证规范化后的路径位于某个已注册目录之内: +内部查询如下,`$1` 由 C 层绑定,不是可独立执行的无参数 SQL: [source,text] ---- SELECT 1 FROM sys.utl_file_directory - WHERE CASE WHEN substring(dir from '.$') = '/' THEN +WHERE CASE WHEN substring(dir from '.$') = '/' THEN substring($1, 1, length(dir)) = dir - ELSE +ELSE substring($1, 1, length(dir) + 1) = dir || '/' - END +END ---- -没有任何注册目录命中时报 `INVALID_PATH`(`errdetail: File location is invalid.`,`errhint: locality is not found in sys.utl_file_directory table`)。由于检查在规范化后的完整路径上进行,`..` 之类的路径穿越在匹配前已被解析成真实路径,无法把写入范围偷渡到注册目录之外。 +等值比较避免 `_`、`%` 的通配语义,分隔符检查避免误匹配同名前缀的同级目录。SPI 缓存查询计划,每次仍查询登记表;无匹配行时抛出 `INVALID_PATH`。 + +检查允许访问子目录,但只规范化路径字符串,不解析符号链接,不能视为文件系统沙箱。删除登记影响后续打开,已经打开的句柄不重新检查目录表。 ==== utl_file.umask -`FOPEN` 创建的文件权限为 `fopen()` 的默认模式套用 `utl_file.umask` 掩码(默认 `0077`)。实现上在 `fopen()` 调用前后用 `umask()` 保存/恢复进程级掩码,不影响进程中的其他操作。 +`utl_file.umask` 是默认值为 `'0077'` 的字符串 GUC,声明为 `PGC_USERSET`,修改权限由 check 钩子限制: -该 GUC 以字符串类型声明,并挂载 check/assign 钩子: +* check 钩子在正常处理模式且处于事务状态时要求超级用户;校验最多四位八进制数字,并将转换后的整数放入 `extra`。 +* assign 钩子从 `extra` 取整数,赋给内部掩码变量。 -* check 钩子拒绝非八进制数字;在正常处理模式下要求超级用户,否则报 `ERCODE_INSUFFICIENT_PRIVILEGE`; -* assign 钩子把字符串转成整数供 `FOPEN` 使用。 +`FOPEN`/`FOPEN_NCHAR` 在 `fopen()` 前保存并设置进程掩码,返回后恢复;已有文件权限不变。`FCOPY` 没有这段掩码切换,最终权限由后端原掩码及文件系统规则决定。 === 句柄管理 -句柄存放在 50 个固定槽位(`MAX_SLOTS`,与 Oracle 10g 一致)中,槽位记录 `FILE*`、`max_linesize` 和编码。`FOPEN` 分配槽位并把数字 id 存入复合文件句柄;超过上限时报 `ERRCODE_PROGRAM_LIMIT_EXCEEDED`。 +每个后端使用 50 个静态槽位,保存 `FILE *`、`max_linesize`、编码和 `uint32 id`。0 表示空闲槽位,id 由计数器生成,不能跨会话使用。 + +`FOPEN` 在 `fopen()` 之后分配槽位,耗尽时报 `54000 / program limit exceeded`,但文件可能已经创建或截断。`FCLOSE` 释放槽位并关闭流;`FCLOSE_ALL` 关闭全部槽位。关闭后旧句柄的 `IS_OPEN` 返回 `FALSE`。 -实现有意不使用 PostgreSQL 的 `AllocateFile`:它会在事务提交/中止时自动关闭文件,而 Oracle 兼容的句柄必须在 `COMMIT` 后继续存活。因此改用: +为使句柄在 `COMMIT` 后仍可使用,实现未采用事务结束时自动关闭流的 `AllocateFile`。首次成功打开后注册两类回调: -* `ResourceOwner` 释放回调,在事务中止或会话结束时关闭句柄; -* `before_shmem_exit` 钩子做最终兜底,即使后端异常退出也能刷缓冲并关闭文件。 +* 资源释放回调只在 `RESOURCE_RELEASE_AFTER_LOCKS`、`isTopLevel = TRUE` 且 `isCommit = FALSE` 时关闭当前会话全部槽位,包括此前已提交事务留下的句柄。提交和内部异常块的子事务回滚不会触发这一关闭。 +* `before_shmem_exit` 回调在正常退出流程中关闭文件,但不保证崩溃、立即退出或 `SIGKILL` 时也能运行。 -由此得到文档所述的生命周期:`IS_OPEN` 在 `COMMIT` 后仍为 `TRUE`,`ROLLBACK` 后变为 `FALSE`,会话退出后所有句柄消失。`FCLOSE_ALL` 关闭本会话持有的全部槽位。 +关闭流可能刷新缓冲数据。文件操作不参与数据库事务回滚,`ROLLBACK` 不会恢复被截断的文件,也不会撤销写入、删除或重命名。 === I/O 行为与异常 -* 全部文本 I/O 走 stdio,并在打开时记录编码,`GET_LINE`/`PUT_LINE` 由此在数据库编码与文件编码之间转换。 -* `GET_LINE` 的返回量取 `len`、到下一行终止符的距离、`max_linesize` 三者的最小值——即 Oracle Operational Notes 的规则;行终止符本身不存入缓冲区,读空行得到空字符串。 -* `GET_LINE` 每次最多读取 `max_linesize` 字节(`len` 参数可临时调低);读到文件末尾时以 `LOG` 级别记录 `no data found` 并返回 `NULL`,调用方可以直接用 `WHILE line IS NOT NULL` 循环。`NO_DATA_FOUND` 因此体现在服务器日志中,而不是作为错误抛出。 -* `PUTF` 实现 Oracle 的受限 `printf()` 格式:`\n` 替换为平台行终止符,`%s` 依次消耗参数(多余的格式符与 `NULL` 参数都渲染为空字符串),`%%` 为 IvorySQL 扩展、输出字面量 `%`。`CHECK_LENGTH` 守卫在累计输出超过 `max_linesize` 时立即抛出 `VALUE_ERROR`("buffer is too short")。 -* `FSEEK` 支持绝对偏移(`SEEK_SET`,先 `rewind`)与相对偏移(`SEEK_CUR`,可为负);两个参数都为 `NULL` 时位置重置为 0。非法组合报 `INVALID_OFFSET`。 -* `FFLUSH` 显式对流执行 `fflush()`,这是让缓冲写入对并发打开的读句柄可见的关键。 -* `FGETATTR` 通过复合类型返回 `(fexists, file_length, block_size)`;`file_length` 以 `numeric` 承载以对应 Oracle 的 `NUMBER`。 -* `FCOPY` 支持按行区间复制(`start_line` 必须为正);`FRENAME` 在 `overwrite = TRUE` 之前拒绝覆盖目标文件(`WRITE_ERROR: Destination file already exists`)。 +* `GET_LINE` 逐字节读取并识别 LF、CRLF、CR,校验编码后转换到数据库编码。单次上限为 `min(len, max_linesize)`;`len` 为空时使用 `max_linesize`,有效长度范围为 1~32767。 +* 空行返回零长度文本;因 EOF 没有读到任何字符时,入口抛出 `ERROR / P0002 / no data found`,应捕获 `NO_DATA_FOUND` 结束循环。达到字节上限时未消费的换行留待下次读取,可能得到空字符串;截断多字节字符则可能报编码错误。 +* `PUT`、`PUT_LINE` 按单次参数转换后的字节数检查长度,不跨调用累计;`PUT_LINE` 追加的换行不计入检查。`NEW_LINE` 不执行该长度检查,`PUT_RAW` 直接写 `BYTEA`,不转换编码,也不受 `max_linesize` 检查约束。 +* `PUTF` 按文件编码扫描完整字符,支持 `%s`、`%%` 和反斜杠加 `n`。单次输出按字节累计并包含换行,超限报 `VALUE_ERROR`,已写出的前缀可能保留;多字节扫描和边界由 `utl_file_putf` 回归覆盖。 +* `FSEEK` 要求至少一个偏移,绝对偏移优先。刷新并测量文件长度、恢复原位置后,检查目标在 `[0, 文件长度]` 内,再用 `SEEK_SET` 定位;参数越界报 `INVALID_OFFSET`。`FGETPOS` 返回 32 位 `INTEGER`。 +* `FFLUSH` 调用 `fflush()` 将 stdio 缓冲交给操作系统,不调用 `fsync()`,不能保证物理介质持久化。 +* `FGETATTR` 通过复合类型返回属性,长度由 `st_size` 转换为 numeric,块大小取 `st_blksize`。`stat()` 失败统一返回 `FALSE, NULL, NULL`,不只代表文件不存在。 +* `FCOPY` 用 `fgets()`、`strlen()` 和 `fwrite()` 按 LF 分行复制,目标先创建或截断,不适合含 NUL 的数据。`FREMOVE` 调用 `unlink()`;`FRENAME` 禁止覆盖时先检查目标,再调用 `rename()`,不提供并发下的原子“不覆盖”保证。 -Oracle 兼容异常(`INVALID_FILEHANDLE`、`INVALID_MAXLINESIZE`、`INVALID_MODE`、`INVALID_OFFSET`、`INVALID_OPERATION`、`INVALID_PATH`、`READ_ERROR`、`VALUE_ERROR`、`WRITE_ERROR`)以 `ERRCODE_RAISE_EXCEPTION` 抛出、以 Oracle 异常名作为 `SQLERRM`,因此 `WHEN OTHERS` + `SQLERRM` 可以复现 Oracle 的错误处理风格。Oracle 定义的异常集合更大(还包括 `ACCESS_DENIED`、`CHARSETMISMATCH`、`DELETE_FAILED`、`FILE_OPEN`、`INTERNAL_ERROR`、`INVALID_FILENAME`、`RENAME_FAILED`);实现未针对这些条件做专门识别,底层操作系统错误会以上表中最接近的名称抛出,`DETAIL` 字段中带 `strerror(errno)` 文本。 +`INVALID_FILEHANDLE`、`INVALID_MAXLINESIZE`、`INVALID_MODE`、`INVALID_OFFSET`、`INVALID_OPERATION`、`INVALID_PATH`、`READ_ERROR`、`VALUE_ERROR`、`WRITE_ERROR` 都是 `P0001` 错误消息,不是包异常声明。应在 `WHEN OTHERS` 中检查 `SQLSTATE`、`SQLERRM`,不能假定预定义 `WHEN VALUE_ERROR` 能捕获同名消息。 + +`IO_EXCEPTION()` 将 `EACCES`、`ENAMETOOLONG`、`ENOENT`、`ENOTDIR` 映射为 `INVALID_PATH`,其他 errno 映射为 `INVALID_OPERATION`,详情取 `strerror(errno)`。未专门实现 `ACCESS_DENIED`、`CHARSETMISMATCH` 等异常;还可能发生 NULL 参数、编码或权限错误。 == 错误处理示例 === 未注册的目录 +在 Oracle 兼容端口连接的 IvorySQL `psql` 中执行。示例假定以下绝对路径不在任何登记目录下,路径检查会在操作系统打开文件之前失败。 + [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; BEGIN - f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024); + f := UTL_FILE.FOPEN('/tmp/utl_file_impl_unregistered_20261203', + 'missing.txt', 'R'); END; / --- ERROR: INVALID_PATH --- DETAIL: File location is invalid. --- HINT: locality is not found in sys.utl_file_directory table ---- -目录未在 `sys.utl_file_directory` 中注册时,路径检查在打开文件之前报错。示例假设 `wrong_directory` 未注册,也不是已注册目录下的有效路径。 +预期错误如下(省略调用栈): + +[source,text] +---- +ERROR: INVALID_PATH +DETAIL: File location is invalid. +HINT: locality is not found in sys.utl_file_directory table +---- == 回归验证 -`utl_file` 回归组覆盖:对未注册目录执行 `FOPEN`(`INVALID_PATH`)、`PUT_LINE`/`PUT`/`NEW_LINE`/`PUTF`/`GET_LINE` 的写入读回闭环(含按 `len` 截短的读取)、`FGETATTR`/`FCOPY`/`FREMOVE`/`FRENAME`、`FFLUSH` 可见性屏障与 `FSEEK`/`FGETPOS` 的绝对/相对定位、配合 `FCLOSE_ALL` 的异常处理,以及 `COMMIT`/`ROLLBACK` 跨越下的句柄生命周期。 +`utl_file` 覆盖路径、读写、属性和文件管理、刷新、定位边界、EOF、NCHAR 及句柄生命周期;`utl_file_putf` 补充多字节编码、格式替换和长度边界。当前实例上的两组回归均已通过。 + +以下命令从包含 `IvorySQL/` 和 `inst/` 的目录执行。先通过 PG 端口创建独立数据库,再通过 Oracle 端口测试,避免建库与连接名称的大小写差异;测试数据库须具备匹配的扩展。数据库名需未被占用,端口和安装路径按环境调整。 + +[source,bash] +---- +./inst/bin/createdb -h 127.0.0.1 -p 5432 -U highgo \ + -T template0 -E UTF8 utl_file_impl_check_20261203 +mkdir -p /tmp/utl_file_impl_check_20261203 +LD_LIBRARY_PATH=/home/highgo/6.0/inst/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} \ +make -C IvorySQL/contrib/ivorysql_ora oracle-installcheck \ + ORA_REGRESS='utl_file utl_file_putf' TAP_TESTS= \ + ORACLE_REGRESS_OPTS='--host=127.0.0.1 --port=1521 --user=highgo --dbname=utl_file_impl_check_20261203 --use-existing --outputdir=/tmp/utl_file_impl_check_20261203' +---- -在已完成配置构建的 IvorySQL 源码树中执行 `make -C contrib/ivorysql_ora oracle-installcheck ORA_REGRESS=utl_file` 即可验证本测试组。目标实例需安装匹配版本的 `ivorysql_ora` 扩展。 +`ORACLE_REGRESS_OPTS` 传递 Oracle 回归选项,`TAP_TESTS=` 避免额外执行 TAP。原始用例使用数据目录中的固定文件名,应在专用测试实例运行或先确认文件名未占用;结束后只清理本次生成的文件和数据库。 diff --git a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc index 76a1ba31..2b5836b9 100644 --- a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc +++ b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc @@ -3,407 +3,580 @@ = UTL_FILE 包 -== 目的 +== 概述与适用范围 -`UTL_FILE` 包用于在 PL/iSQL 中读写服务器上的文本文件,也提供查询文件属性、复制、删除和重命名文件的过程。`FOPEN` 返回 `sys.ORA_UTL_FILE_FILE_TYPE` 类型的句柄,后续读写和关闭操作使用该句柄。 +`UTL_FILE` 用于在 PL/iSQL 中操作数据库服务器上的文件,提供文本读写、文件定位、属性查询、复制、删除和重命名等功能。文件由数据库服务进程访问,路径指向服务器文件系统,而不是客户端文件系统。 -== 功能说明 +示例使用 Linux、UTF8 数据库和 IvorySQL 自带的 `psql`,通过 Oracle 兼容端口执行。不能将 Oracle 的完整接口、异常集合或边界行为直接作为本实现的保证。 -=== 安全前提 +== 使用前提 -`UTL_FILE` 使用 `sys.utl_file_directory` 表限制可访问的目录。使用文件操作前,需要先在表中注册目录。 +=== 目录登记与权限 -[source,sql] ----- -CREATE TABLE sys.utl_file_directory( - dirname name PRIMARY KEY, - dir TEXT -); ----- +安装 `ivorysql_ora` 时已经创建 `sys.utl_file_directory`,应用不需要重新创建此表。表包含 `dirname name PRIMARY KEY` 和 `dir text` 两列,分别保存目录别名和服务器上的目录路径。 -* 普通用户对该表只有 `SELECT` 权限;新增、删除注册目录需要超级用户权限。对应 Oracle 中仅默认授予 `SYS`、`SYSTEM` 的 `CREATE DIRECTORY` 权限。 -* 使用前先注册目录,之后通过 `dirname` 名称引用: +默认向 `PUBLIC` 授予该表的 `SELECT` 权限,未授予写权限。目录登记由表所有者、超级用户或另行获得相应表权限的角色执行;并非只有超级用户才能修改目录登记。登记目录不会创建操作系统目录,也不会改变操作系统权限。 -[source,sql] ----- --- 将数据目录注册为名为 'data_directory' 的目录对象 -INSERT INTO sys.utl_file_directory(dirname, dir) -VALUES ('data_directory', current_setting('data_directory')); ----- +路径解析规则如下: -* `location` 参数既可以是已注册的 `dirname`,也可以是原始路径。原始路径会先做规范化,并且必须落在某个已注册目录之内(前缀匹配),否则报 `INVALID_PATH`。 -* 与 Oracle 一致,**已注册目录的子目录不会自动获得访问权**,必须以完整路径单独注册。 -* 文件权限掩码:`FOPEN` 创建的文件受 `utl_file.umask` 参数控制(默认 `0077`)。仅超级用户可以修改该参数,取值必须为 3–4 位八进制数字: +* `location` 首先按 `dirname` 查找目录别名;没有匹配别名时,按路径处理。别名按保存的字符串匹配,示例统一使用小写。 +* 将目录与 `filename` 拼接并执行路径规范化后,检查完整文件路径是否以某个已登记的 `dir` 加目录分隔符为前缀。建议将 `dir` 登记为规范化的绝对路径。 +* 此检查允许访问已登记目录下的子目录。子目录必须事先存在,不需要再次登记;`filename` 也可以包含子目录部分。相似名称的同级目录不因字符串前缀相同而获得访问权。 +* `..` 规范化后的最终路径仍须位于某个已登记目录内。实现使用路径字符串检查,没有通过 `realpath()` 解析符号链接,因此不能将登记表视为隔离符号链接目标的文件系统沙箱。 +* 不展开环境变量或 `~`。最终能否读写还受数据库运行用户的文件系统权限限制。 -[source,sql] ----- -SET utl_file.umask = '0022'; -SHOW utl_file.umask; ----- +登记表不是按数据库用户分别授予目录 `READ`/`WRITE` 权限的模型。不要将数据库数据目录登记为一般应用的文件工作目录;本文使用独立示例目录。 + +=== 文件句柄 + +在 PL/iSQL 中使用包内类型 `UTL_FILE.FILE_TYPE` 声明变量。`FOPEN` 和 `FOPEN_NCHAR` 返回该类型。不要自行创建或引用 `sys.ORA_UTL_FILE_FILE_TYPE`,当前安装没有这一 SQL 类型。 + +包内记录包含 `id INTEGER`、`datatype INTEGER`、`byte_mode BOOLEAN`。这些字段供实现使用,应用应将整个记录作为句柄传递,不应修改或保存其字段来重建句柄。句柄仅在创建它的数据库会话中有效,每个会话最多同时保留 50 个打开的文件句柄。 + +`IS_OPEN` 查询该句柄是否仍在当前会话的打开文件表中。`FCLOSE` 关闭单个句柄;`FCLOSE_ALL()` 关闭当前会话的全部文件句柄。两种关闭操作之后,`IS_OPEN` 都返回 `FALSE`。再次读写或关闭已经关闭的句柄会报 `INVALID_FILEHANDLE`。 + +=== 文件创建权限 + +`FOPEN` 和 `FOPEN_NCHAR` 创建新文件时临时使用 `utl_file.umask`,默认值为 `'0077'`。在普通 Linux 权限模型下,新文件通常为 `0600`,属主为数据库运行用户;最终权限还可能受文件系统 ACL 等因素影响。打开已有文件不改变其权限。 + +当前设置检查要求超级用户权限,支持 1~4 位八进制数字,例如 `'77'`、`'077'`、`'0077'`,不是只能使用 3~4 位。建议使用明确的四位形式。`FCOPY` 的目标文件由另一个 `fopen()` 路径创建,没有应用 `utl_file.umask` 的临时切换,不能假定其权限与 `FOPEN` 新建文件相同。 + +== 接口说明 + +以下为包的公开接口。除标明返回值的函数外,其余均为过程。字符串参数为 `VARCHAR2`,`GET_LINE`、`GET_LINE_NCHAR` 的输出缓冲区及 `PUT_LINE_NCHAR` 的输入缓冲区为 `TEXT`。文件参数均为 `UTL_FILE.FILE_TYPE`。 -=== 函数与过程一览 +=== 打开、关闭、刷新与定位 -[cols="4,2,4",options="header"] +[cols="5,7",options="header"] |=== -|调用 |返回类型 |说明 -|`FOPEN(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |打开文件用于输入或输出。`open_mode` 为单字符:`R`(读)、`W`(写,截断)、`A`(追加)。`max_linesize` 默认 1024,范围 1–32767 -|`FOPEN_NCHAR(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |以 Unicode 模式打开文件用于输入或输出,文件以 UTF-8 而非数据库字符集读写。参数同 `FOPEN` -|`IS_OPEN(file)` |`BOOLEAN` |测试句柄是否指向一个已打开但尚未关闭的文件 -|`FCLOSE(file)` |— |关闭文件句柄标识的已打开文件 -|`FCLOSE_ALL` |— |关闭当前会话打开的所有文件句柄;属应急清理过程,例如 PL/iSQL 程序因异常退出时使用 -|`FFLUSH(file)` |— |把所有待写入数据物理写入文件;适用于文件尚未关闭就需要读取的场景(如调试信息) -|`FGETPOS(file)` |`INTEGER` |返回文件内当前的相对偏移位置(字节);`0` 表示文件开头 -|`FSEEK(file [, absolute_offset [, relative_offset]])` |— |按指定字节数向前或向后调整文件指针。`absolute_offset` 为相对文件开头的字节位置;`relative_offset` 相对当前位置向前(正数)或向后(负数)移动;两者都省略时 IvorySQL 将位置重置为 0 -|`GET_LINE(file, buffer OUT, [len])` |— |读取文本到 `buffer`,遇到行终止符(不含终止符本身)、文件末尾或 `len` 字节三者中先到者即停止。`len` 默认取 `max_linesize`;两者都指定时以较小值为准。读到文件末尾返回 `NULL` -|`GET_LINE_NCHAR(file, buffer OUT, [len])` |— |从 `FOPEN_NCHAR` 打开的文件中按 Unicode 读取文本 -|`NEW_LINE(file [, lines])` |— |写入一个或多个操作系统相关的行终止符(默认 1)。与 `PUT` 分开的原因是行终止符是平台相关的字符序列 -|`PUT(file, buffer)` |— |把 `buffer` 中的字符串写入文件,不追加行终止符;需要用 `NEW_LINE` 或 `PUT_LINE` 结束一行 -|`PUTF(file, format [, arg1..arg5])` |— |带格式的 `PUT`,类似功能受限的 `printf()`。`format` 中的 `%s` 依次被 `arg1`–`arg5` 替换,`\n` 替换为平台行终止符,`%%` 表示字面量 `%`(IvorySQL 扩展)。`%s` 多于参数时以空字符串替换 -|`PUT_LINE(file, buffer [, autoflush])` |— |写入一行并追加平台相关的行终止符;`autoflush = TRUE` 时写完立即把缓冲区刷到磁盘 -|`PUT_LINE_NCHAR(file, buffer)` |— |向 `FOPEN_NCHAR` 打开的文件写入 Unicode 行;追加行终止符 -|`PUT_RAW(file, buffer [, autoflush])` |— |把 `BYTEA` 值(对应 Oracle 的 `RAW`)写入文件,不追加行终止符;`autoflush = TRUE` 时写完即刷新 -|`FCOPY(src_location, src_filename, dest_location, dest_file [, start_line [, end_line]])` |— |把文件的连续部分复制到新建文件。默认复制整个文件;`start_line`(默认 1)与 `end_line`(默认为文件末尾)可选地选取源文件中间的一段。源文件以读模式打开,目标文件以写模式打开 -|`FREMOVE(location, filename)` |— |删除磁盘文件(需具备足够权限);文件与目录权限由操作系统校验 -|`FRENAME(src_location, src_filename, dest_location, dest_filename [, overwrite])` |— |把文件重命名为新名称,类似 UNIX 的 `mv` 命令。`overwrite` 默认 `FALSE`;目标文件已存在且 `overwrite` 为 `FALSE` 时报 `WRITE_ERROR` -|`FGETATTR(location, filename, fexists OUT, file_length OUT, block_size OUT)` |— |读取并返回磁盘文件属性:是否存在、字节长度(文件不存在时为 `NULL`)、文件系统块大小(文件不存在时为 `NULL`) +|接口 |说明 +|`FOPEN(location, filename, open_mode, max_linesize DEFAULT 1024) RETURN UTL_FILE.FILE_TYPE` +|以数据库字符集读写文本。`max_linesize` 为 `INTEGER`,有效范围为 1~32767;省略时取 1024,显式传入 `NULL` 会报错。 +|`FOPEN_NCHAR(location, filename, open_mode, max_linesize DEFAULT 1024) RETURN UTL_FILE.FILE_TYPE` +|文件编码固定为 UTF8,读写时与数据库字符集转换。其余参数规则同 `FOPEN`。 +|`IS_OPEN(file) RETURN BOOLEAN` +|判断句柄是否仍处于打开状态。 +|`FCLOSE(file IN OUT)` +|关闭文件并释放句柄槽位。包体不清空调用方记录中的字段,但句柄已经失效。 +|`FCLOSE_ALL()` +|关闭当前会话全部打开文件,释放所有槽位。 +|`FFLUSH(file)` +|调用 C 标准库 `fflush()`,将用户态写缓冲提交给操作系统。不调用 `fsync()`,不保证数据已经持久化到物理介质。 +|`FGETPOS(file) RETURN INTEGER` +|返回从文件开头计算的当前字节偏移,文件开头为 0。接口返回 32 位 `INTEGER`,不适合作为大于其可表示范围的文件偏移接口。 +|`FSEEK(file IN OUT, absolute_offset DEFAULT NULL, relative_offset DEFAULT NULL)` +|偏移参数为 `INTEGER`。绝对偏移从文件开头计算,相对偏移从当前位置计算;两者均非空时使用绝对偏移,两者均为空时报 `INVALID_OFFSET`。 |=== -与 Oracle 相比尚未实现:`GET_RAW`、`PUT_NCHAR`、`PUTF_NCHAR`,以及字节模式(`rb`/`wb`/`ab`)打开。 +打开模式仅接受单个字符,且不区分大小写: -文件句柄类型与 Oracle 私有 `FILE_TYPE` 记录逐字段对应;用户不应引用或修改其内容: +[cols="1,5",options="header"] +|=== +|模式 |行为 +|`R` / `r` |只读,文件必须已存在。 +|`W` / `w` |只写;已有文件立即截断,不存在则创建。 +|`A` / `a` |追加写入;不存在则创建。即使先执行定位,后续追加写入仍由操作系统追加模式控制。 +|=== -[source,sql] ----- -CREATE TYPE sys.ORA_UTL_FILE_FILE_TYPE AS(id INTEGER, datatype INTEGER, byte_mode BOOLEAN); ----- +不支持 `rb`、`wb`、`ab` 或 `r+` 等模式。 -=== 调用方式 +`FSEEK` 的有效目标范围是 `[0, 文件长度]`,允许恰好定位到 EOF。负的绝对偏移、相对移动到文件开头之前、移动到 EOF 之后都会报 `INVALID_OFFSET`,不会将位置自动截断到文件边界。上述参数越界错误不改变当前位置。 -`UTL_FILE` 的子程序通常在 PL/iSQL 匿名块中调用: +定位前实现会刷新流并测量文件长度,因此可以定位到当前句柄尚未显式刷新但已写入的内容范围内。回到文件开头应调用 `FSEEK(f, 0)`,不能省略两个偏移。 -[source,sql] ----- -DECLARE - f sys.ora_utl_file_file_type; - line TEXT; -BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); +=== 文本读写与原始字节写入 - UTL_FILE.PUT_LINE(f, 'abc'); - UTL_FILE.PUT_LINE(f, '-----'); - UTL_FILE.FCLOSE(f); +[cols="5,7",options="header"] +|=== +|接口 |说明 +|`GET_LINE(file, buffer OUT TEXT, len DEFAULT NULL)` +|读取文本片段并移除所遇到的行终止符。`len` 为 `INTEGER`,非空时必须在 1~32767 范围内;省略或为 `NULL` 时使用打开文件时的 `max_linesize`。读到 EOF 且没有读取任何字符时抛出 `NO_DATA_FOUND`。 +|`GET_LINE_NCHAR(file, buffer OUT TEXT, len DEFAULT NULL)` +|与 `GET_LINE` 使用相同的读取实现;实际文件编码取自打开句柄时保存的编码。 +|`PUT(file, buffer)` +|写入文本,不追加换行。按转换到文件编码后的字节数检查本次输入长度。 +|`PUT_LINE(file, buffer, autoflush DEFAULT FALSE)` +|写入文本后追加一个行终止符。`autoflush` 为 `BOOLEAN`,为 `TRUE` 时调用刷新;显式 `NULL` 按 `FALSE` 处理。 +|`PUT_LINE_NCHAR(file, buffer TEXT)` +|写入文本、追加行终止符并刷新。包体固定将 `autoflush` 设为 `TRUE`,接口没有第三个参数。 +|`NEW_LINE(file, lines DEFAULT 1)` +|写入 `lines` 个行终止符。`lines` 为 `INTEGER`;省略或为 `NULL` 时写一个,0 或负数时不写入。 +|`PUTF(file, format, arg1 DEFAULT NULL, arg2 DEFAULT NULL, arg3 DEFAULT NULL, arg4 DEFAULT NULL, arg5 DEFAULT NULL)` +|格式化写入,不自动追加换行。支持 `%s`、`%%` 和格式串中的反斜杠加 `n` 两个字符,详见下文。 +|`PUT_RAW(file, buffer BYTEA, autoflush DEFAULT FALSE)` +|直接写入 `BYTEA` 数据,不进行字符集转换,也不追加换行。为 `TRUE` 时刷新。当前实现不按 `max_linesize` 检查这次写入长度。 +|=== - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); - UTL_FILE.GET_LINE(f, line); - WHILE line IS NOT NULL LOOP - RAISE NOTICE '>>%<<', line; - UTL_FILE.GET_LINE(f, line); - END LOOP; - UTL_FILE.FCLOSE(f); -END; -/ ----- +==== 读取边界 -在 Oracle 兼容模式(`ivorysql.compatible_mode = oracle`)下可直接使用。与 Oracle 相同,文件位置与文件名作为独立字符串传入,以便对位置做注册表校验;两者拼在一起必须在操作系统上是合法的文件名。 +每次 `GET_LINE` 最多读取 `min(len, max_linesize)` 个文件编码的字节;`len` 为空时上限为 `max_linesize`。遇到 LF、CRLF 或单独 CR 时结束本次读取,返回值不含该终止符。 -=== 打开模式 +* 读到空行会返回零长度 `TEXT`。本文实测环境中它不是 `NULL`;循环应通过捕获 `NO_DATA_FOUND` 判断结束,不应依靠 `line IS NULL`。 +* 文件最后一段没有换行时,先返回该段文本;下一次读取才抛出 `NO_DATA_FOUND`。空文件第一次读取就抛出该异常。 +* 长行不会仅因超过本次上限就报 `READ_ERROR`,而是分次返回。若达到字节上限时恰好尚未消费换行符,下一次调用会读取这个换行符并返回空字符串。下文提供此边界的实测示例。 +* 长度单位是字节,不是字符。若上限将 UTF8 等多字节字符截断,字符集校验可能报编码错误。不要用过小的 `len` 拆分多字节字符。 -遵循 Oracle `FOPEN` 的定义: +==== 写入长度与格式化 -[cols="2,4,4",options="header"] +`max_linesize` 在当前实现中不是跨调用累计的逻辑行长度限制: + +* `PUT`、`PUT_LINE` 和 `PUT_LINE_NCHAR` 分别检查单次文本参数编码后的字节数;`PUT_LINE` 和 `PUT_LINE_NCHAR` 自动追加的换行不计入该检查。 +* 连续多次 `PUT` 的长度不累计,刷新也不承担重置累计长度的功能。因此,多次合法调用可以写出长于 `max_linesize` 的一行。 +* `PUTF` 检查一次调用生成的总字节数,包含替换参数和生成的换行;遇到换行不会重新计数。超限报 `VALUE_ERROR`,此前已经写出的部分可能保留。 +* `NEW_LINE` 不进行上述长度检查,`PUT_RAW` 也不受该检查约束。 +* `PUT`、`PUT_LINE`、`PUT_LINE_NCHAR` 和 `PUT_RAW` 的缓冲区,以及 `PUTF` 的格式串,不能显式为 `NULL`。 + +`PUTF` 的 `%s` 按顺序使用最多五个参数,参数缺省或为 `NULL` 时写入空内容;第六个及以后的 `%s` 也不写入内容。`%%` 写入一个 `%`。格式串中的反斜杠加 `n` 会写入换行;替换参数中的这两个字符不会再次作为格式指令解释。它不是完整的 `printf()`:不支持 `%d`、宽度或精度等格式;当前实现会吞掉 `%d` 这样的未知 ASCII 百分号双字符组合,应用应只使用明确支持的指令。 + +文本输出通过 C 文本流写入 `\n`,本文 Linux 示例的文件换行为 LF。`PUT_RAW` 虽直接写字节,仍使用 `FOPEN` 的文本流,不能据此认为实现已经支持跨平台二进制打开模式。 + +`FOPEN_NCHAR` 选择 UTF8 文件编码,但 `GET_LINE_NCHAR` 和 `PUT_LINE_NCHAR` 本身不重新选择编码。包体没有检查句柄的 `datatype` 是否与 NCHAR/普通接口匹配,混用不会专门抛出 `CHARSETMISMATCH`;应用仍应按成套接口使用。 + +=== 文件管理 + +[cols="5,7",options="header"] |=== -|模式 |说明 |备注 -|`R` |读文本 |文件必须已存在 -|`W` |写文本并截断 |文件不存在则创建,已存在则清空 -|`A` |追加文本 |写入内容添加到文件末尾;文件不存在时会创建,与 Oracle「append 模式下文件不存在则以写模式创建」的说明一致 +|接口 |说明 +|`FCOPY(location, filename, dest_dir, dest_file, start_line DEFAULT 1, end_line DEFAULT 2147483647)` +|按文本行复制,行号为 `INTEGER`,从 1 开始,包含起止行。省略或显式 `NULL` 时使用各自默认值;非正数报错。目标文件以写模式打开,已有内容会被截断。 +|`FREMOVE(location, filename)` +|删除指定文件,底层调用 `unlink()`。删除不存在文件会报错。 +|`FRENAME(src_location, src_filename, dest_location, dest_filename, overwrite DEFAULT FALSE)` +|重命名或移动文件,底层调用 `rename()`。`overwrite` 为 `BOOLEAN`,省略或为 `NULL` 时按 `FALSE` 处理;此时目标已存在报 `WRITE_ERROR`。为 `TRUE` 时允许替换已有目标,仍受操作系统规则限制。 +|`FGETATTR(location, filename, fexists OUT BOOLEAN, file_length OUT NUMBER, block_size OUT INTEGER)` +|通过 `stat()` 获取属性,`file_length` 是字节数,`block_size` 是系统返回的 `st_blksize`。不能把块大小固定写成 4096。 |=== -模式参数不区分大小写(`'r'`、`'w'`、`'a'` 均可),其他取值报 `INVALID_MODE`。Oracle 还支持字节模式 `rb`、`wb`、`ab`,IvorySQL 暂不支持。 +`FCOPY` 按 LF 分行,保留所复制的文本内容,不进行字符集转换,不适合作为含 NUL 字节数据的二进制复制接口。`start_line` 超过文件行数或大于 `end_line` 时,目标文件仍会被创建或截断,复制结果为空;不要使用相同的源文件和目标文件。复制仍在写入的源文件之前,应先刷新或关闭写句柄。 + +`FGETATTR` 在路径登记检查通过后,如果 `stat()` 失败,会返回 `FALSE, NULL, NULL`。这既可能表示不存在,也可能表示权限等原因导致无法取得属性;不能仅凭 `fexists = FALSE` 断定文件不存在。未通过目录检查仍会抛出 `INVALID_PATH`。 + +== 可运行示例 + +=== 准备示例目录与连接 + +以下示例按本节顺序执行。以数据库服务的操作系统用户在服务器上创建独立目录,再用有目录表写权限的数据库用户连接。这里展示的 `1521` 是本次验证实例的 Oracle 兼容端口;其他环境应使用各自的端口、数据库名和用户。 -=== 操作规则 +[source,bash] +---- +mkdir -p /tmp/ivorysql_utl_file_demo +/home/highgo/6.0/inst/bin/psql -X -h 127.0.0.1 -p 1521 -U highgo -d postgres +---- + +后续代码在上述 `psql` 会话中执行。使用 `/` 单独一行结束 PL/iSQL 匿名块。若从 PostgreSQL 兼容端口连接,仅设置服务器的 `ivorysql.compatible_mode` 不足以保证客户端正确切分匿名块,还需同步 `psql` 的解析器;这里直接使用 Oracle 兼容端口。 + +[source,sql] +---- +\set ON_ERROR_STOP on +SET client_min_messages = notice; +SET standard_conforming_strings = on; +SHOW ivorysql.compatible_mode; +SHOW server_encoding; +SHOW utl_file.umask; -使用文件句柄时需要注意以下限制: +INSERT INTO sys.utl_file_directory(dirname, dir) +VALUES ('utl_file_demo', '/tmp/ivorysql_utl_file_demo'); +---- -* **GET_LINE 实际返回的字节数**取三者的最小值:`GET_LINE` 的 `len` 参数、到下一个行终止符之间的字节数、`FOPEN` 指定的 `max_linesize`。行终止符本身不会读入缓冲区,因此读空行得到空字符串。 -* **max_linesize** 取值范围 1–32767,未指定时默认 1024。`GET_LINE` 的 `len` 参数遵循相同范围;`max_linesize` 与 `len` 取值不同时以较小者为准。 -* **字符集**:`FOPEN` 打开的文件预期使用数据库字符集编码,`FOPEN_NCHAR` 打开的文件预期使用 UTF-8 编码。以非预期字符集读文件时结果不可预测。 -* **连续 PUT 的总写入量**在两次刷新之间不应超过行限制;超出 `max_linesize` 报 `VALUE_ERROR`("buffer is too short")。 -* **同时打开文件数上限**:每个会话最多同时打开 50 个文件(与 Oracle 相同),超过后 `FOPEN` 报 "program limit exceeded" 错误。 -* 文件位置与文件名参数中不能使用操作系统相关的参数(如 UNIX 环境变量)。 +本次验证的查询值依次为 `oracle`、`UTF8`、`0077`。若已存在同名登记,应先核实其用途,避免改写其他应用的目录。 -== 语法示例 +以下每个功能示例自行创建并删除其文件,依赖的共同准备只有上述目录登记。示例输出只列出 `NOTICE`,省略 `psql` 的行号前缀和命令完成标记。 -逐行写入并读回文件: +=== 文本写入、追加、格式化及逐行读取 [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; line TEXT; - i INTEGER; + n INTEGER := 0; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); - + f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'W'); UTL_FILE.PUT_LINE(f, 'abc'); - UTL_FILE.PUT_LINE(f, '123'::numeric); UTL_FILE.NEW_LINE(f, 2); UTL_FILE.PUT(f, 'a'); UTL_FILE.PUT(f, 'b'); UTL_FILE.NEW_LINE(f); - UTL_FILE.PUTF(f, '[1=%s, 2=%s]', 'one', 'two'); - UTL_FILE.NEW_LINE(f); + UTL_FILE.PUTF(f, 'name=%s; ratio=100%%\n', 'IvorySQL'); UTL_FILE.FCLOSE(f); - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); - i := 1; - UTL_FILE.GET_LINE(f, line); - WHILE line IS NOT NULL LOOP - RAISE NOTICE '[%] >>%<<', i, line; - UTL_FILE.GET_LINE(f, line); - i := i + 1; - END LOOP; + f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'A'); + UTL_FILE.PUT_LINE(f, 'tail'); UTL_FILE.FCLOSE(f); - EXCEPTION - WHEN OTHERS THEN - RAISE NOTICE 'exception: %', sqlerrm; - UTL_FILE.FCLOSE_ALL(); + f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'R'); + LOOP + BEGIN + UTL_FILE.GET_LINE(f, line); + EXCEPTION WHEN NO_DATA_FOUND THEN + EXIT; + END; + n := n + 1; + RAISE NOTICE '[%] >>%<<', n, line; + END LOOP; + UTL_FILE.FCLOSE(f); + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); + UTL_FILE.FREMOVE('utl_file_demo', 'text.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -输出: +输出中包含两个空行记录: [source,text] ---- NOTICE: [1] >>abc<< -NOTICE: [2] >>123<< +NOTICE: [2] >><< NOTICE: [3] >><< NOTICE: [4] >>ab<< -NOTICE: [5] >>[1=one, 2=two]<< +NOTICE: [5] >>name=IvorySQL; ratio=100%<< +NOTICE: [6] >>tail<< +NOTICE: is_open = f ---- -使用 `PUTF` 写入格式化文本: +=== 长度上限与换行符边界 + +本例连续写入两个三字节字符串,证明写入检查不跨 `PUT` 累计。读取时指定 `len = 32767`,但打开句柄的 `max_linesize = 3` 仍限制每次读取最多三个字节。 [source,sql] ---- DECLARE - my_world VARCHAR2 := 'Zork'; - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; + line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'zork.txt', 'W'); - UTL_FILE.PUTF(f, 'Hello, world!\nI come from %s with %s.\n', - my_world, - 'greetings for all earthlings'); + f := UTL_FILE.FOPEN('utl_file_demo', 'length.txt', 'W', 3); + UTL_FILE.PUT(f, 'abc'); + UTL_FILE.PUT(f, 'def'); + UTL_FILE.NEW_LINE(f); UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('utl_file_demo', 'length.txt', 'R', 3); + FOR i IN 1..3 LOOP + UTL_FILE.GET_LINE(f, line, 32767); + RAISE NOTICE '[%] text=[%], bytes=%, pos=%', + i, line, octet_length(line), UTL_FILE.FGETPOS(f); + END LOOP; + BEGIN + UTL_FILE.GET_LINE(f, line); + EXCEPTION WHEN NO_DATA_FOUND THEN + RAISE NOTICE 'EOF: SQLSTATE=%, SQLERRM=%', SQLSTATE, SQLERRM; + END; + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'length.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -文件属性、复制、删除与重命名: +Linux 上输出: + +[source,text] +---- +NOTICE: [1] text=[abc], bytes=3, pos=3 +NOTICE: [2] text=[def], bytes=3, pos=6 +NOTICE: [3] text=[], bytes=0, pos=7 +NOTICE: EOF: SQLSTATE=P0002, SQLERRM=no data found +---- + +=== 刷新、绝对定位和相对定位 [source,sql] ---- DECLARE - fexists BOOLEAN; - file_length NUMBER; - block_size INTEGER; + writer UTL_FILE.FILE_TYPE; + reader UTL_FILE.FILE_TYPE; + line TEXT; + second_pos INTEGER; BEGIN - UTL_FILE.FCOPY('data_directory', 'regress.txt', 'data_directory', 'regress2.txt'); - UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); - RAISE NOTICE 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + writer := UTL_FILE.FOPEN('utl_file_demo', 'seek.txt', 'W'); + reader := UTL_FILE.FOPEN('utl_file_demo', 'seek.txt', 'R'); + UTL_FILE.PUT_LINE(writer, 'one'); + UTL_FILE.PUT_LINE(writer, 'two'); + UTL_FILE.FFLUSH(writer); + + UTL_FILE.FSEEK(reader, 0); + UTL_FILE.GET_LINE(reader, line); + second_pos := UTL_FILE.FGETPOS(reader); + RAISE NOTICE 'first=%, second_pos=%', line, second_pos; - UTL_FILE.FREMOVE('data_directory', 'regress2.txt'); - UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); - RAISE NOTICE 'fexists = %', fexists; + UTL_FILE.FSEEK(reader, second_pos); + UTL_FILE.GET_LINE(reader, line); + RAISE NOTICE 'absolute=%', line; - UTL_FILE.FRENAME('data_directory', 'regress.txt', 'data_directory', 'regress2.txt', TRUE); + UTL_FILE.FSEEK(reader, NULL, -4); + UTL_FILE.GET_LINE(reader, line); + RAISE NOTICE 'relative=%', line; + + UTL_FILE.FCLOSE_ALL(); + RAISE NOTICE 'writer_open=%, reader_open=%', + UTL_FILE.IS_OPEN(writer), UTL_FILE.IS_OPEN(reader); + UTL_FILE.FREMOVE('utl_file_demo', 'seek.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -输出: +本例的 `-4` 对应 Linux 上 `two` 加一个 LF 的四字节长度;应用应按实际记录字节长度定位,不要使用字符数代替字节偏移。 [source,text] ---- -NOTICE: fexists = t, file_length = 24, block_size = 4096 -NOTICE: fexists = f +NOTICE: first=one, second_pos=4 +NOTICE: absolute=two +NOTICE: relative=two +NOTICE: writer_open=f, reader_open=f ---- -`max_linesize` 和 `len` 的用法:`GET_LINE` 请求的字节数超过 `FOPEN` 的 `max_linesize`,实际返回字节数以较小值为上限: +=== 属性查询、按行复制、重命名和删除 [source,sql] ---- DECLARE - v1 TEXT; - f1 sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; + ex BOOLEAN; + sz NUMBER; + bs INTEGER; BEGIN - -- MAX_LINESIZE(256)小于 GET_LINE 的长度请求(32767), - -- 因此返回字节数为 256 以内(若提前遇到行终止符则更少)。 - f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R', 256); - UTL_FILE.GET_LINE(f1, v1, 32767); - UTL_FILE.FCLOSE(f1); - - -- FOPEN 的 MAX_LINESIZE 为空时默认 1024, - -- 因此返回字节数为 1024 以内(若提前遇到行终止符则更少)。 - f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); - UTL_FILE.GET_LINE(f1, v1, 32767); - UTL_FILE.FCLOSE(f1); - - -- GET_LINE 未指定字节数时默认取 FOPEN 的 MAX_LINESIZE, - -- 后者为空时同样默认 1024。 - f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); - UTL_FILE.GET_LINE(f1, v1); - UTL_FILE.FCLOSE(f1); + f := UTL_FILE.FOPEN('utl_file_demo', 'source.txt', 'W'); + UTL_FILE.PUT_LINE(f, 'alpha'); + UTL_FILE.PUT_LINE(f, 'beta'); + UTL_FILE.PUT_LINE(f, 'gamma'); + UTL_FILE.FCLOSE(f); + + UTL_FILE.FCOPY('utl_file_demo', 'source.txt', + 'utl_file_demo', 'copy.txt', 2, 3); + UTL_FILE.FGETATTR('utl_file_demo', 'copy.txt', ex, sz, bs); + RAISE NOTICE 'copy: exists=%, bytes=%', ex, sz; + + UTL_FILE.FRENAME('utl_file_demo', 'copy.txt', + 'utl_file_demo', 'renamed.txt', TRUE); + UTL_FILE.FGETATTR('utl_file_demo', 'renamed.txt', ex, sz, bs); + RAISE NOTICE 'renamed: exists=%, bytes=%', ex, sz; + + UTL_FILE.FREMOVE('utl_file_demo', 'renamed.txt'); + UTL_FILE.FGETATTR('utl_file_demo', 'renamed.txt', ex, sz, bs); + RAISE NOTICE 'removed: exists=%, length_null=%, block_null=%', + ex, sz IS NULL, bs IS NULL; + UTL_FILE.FREMOVE('utl_file_demo', 'source.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -`FFLUSH`、`FSEEK` 与 `FGETPOS` 配合可实现「先写后读」:缓冲区中的数据只有经过 `FFLUSH` 后对其他句柄可见,`FSEEK` 可以跳转到记录下来的偏移位置: +Linux 上复制内容为 `beta`、`gamma` 两行,各自带 LF,总计 11 字节: + +[source,text] +---- +NOTICE: copy: exists=t, bytes=11 +NOTICE: renamed: exists=t, bytes=11 +NOTICE: removed: exists=f, length_null=t, block_null=t +---- + +=== UTF8 文件读写 [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; - f1 sys.ora_utl_file_file_type; - line TEXT; - line2_pos INTEGER; + f UTL_FILE.FILE_TYPE; + line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'W'); - f1 := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'R'); - - FOR i IN 1..5 LOOP - UTL_FILE.PUT_LINE(f, 'line ' || i::text); - END LOOP; - - UTL_FILE.FFLUSH(f); -- 使缓冲数据对读句柄可见 - - UTL_FILE.FSEEK(f1); -- 读位置重置到 0 - UTL_FILE.GET_LINE(f1, line); - line2_pos := UTL_FILE.FGETPOS(f1); -- 记下第 2 行的偏移 - - WHILE line IS NOT NULL LOOP - RAISE NOTICE '>>%<<', line; - UTL_FILE.GET_LINE(f1, line); - END LOOP; - - UTL_FILE.FSEEK(f1, line2_pos, NULL); -- 绝对定位回第 2 行 - UTL_FILE.GET_LINE(f1, line); - RAISE NOTICE '>>%<<', line; - - UTL_FILE.FSEEK(f1, NULL, -7); -- 相对定位回退一条记录 - UTL_FILE.GET_LINE(f1, line); - RAISE NOTICE '>>%<<', line; + f := UTL_FILE.FOPEN_NCHAR('utl_file_demo', 'utf8.txt', 'W'); + UTL_FILE.PUT_LINE_NCHAR(f, '你好,IvorySQL'); + UTL_FILE.FCLOSE(f); + f := UTL_FILE.FOPEN_NCHAR('utl_file_demo', 'utf8.txt', 'R'); + UTL_FILE.GET_LINE_NCHAR(f, line); + RAISE NOTICE 'text=%, bytes=%', line, octet_length(line); + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'utf8.txt'); +EXCEPTION WHEN OTHERS THEN UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -已知字节偏移时,可以用 `FSEEK` 回到之前的位置。在到达指定字节数之前先到达文件开头时,文件指针落在文件开头;先到达文件末尾时则报 `INVALID_OFFSET`。 +在 UTF8 数据库中输出: -== 异常 - -`UTL_FILE` 抛出 Oracle 风格的异常,可用 `WHEN OTHERS` 捕获并通过 `SQLERRM` 查看。异常集合遵循 Oracle 的 *UTL_FILE Exceptions* 表: - -[cols="3,5",options="header"] -|=== -|异常 |说明 -|`INVALID_PATH` |文件位置无效 -|`INVALID_MODE` |`FOPEN` 的 `open_mode` 参数无效 -|`INVALID_FILEHANDLE` |文件句柄无效 -|`INVALID_OPERATION` |文件无法按要求打开或操作,例如对以 `W`/`A` 模式打开的句柄执行读取 -|`READ_ERROR` |目标缓冲区过小,或读取过程中发生操作系统错误 -|`WRITE_ERROR` |写入过程中发生操作系统错误;`FRENAME` 发现目标文件已存在且 `overwrite` 为 `FALSE` 时同样报此异常 -|`INTERNAL_ERROR` |未指定的 PL/iSQL 错误 -|`CHARSETMISMATCH` |文件用 `FOPEN_NCHAR` 打开,但后续 I/O 使用了 `PUTF`、`GET_LINE` 等非 NCHAR 函数 -|`FILE_OPEN` |因文件处于打开状态导致请求的操作失败 -|`INVALID_MAXLINESIZE` |`FOPEN()` 的 `max_linesize` 取值无效,应在 1 到 32767 之间 -|`INVALID_FILENAME` |`filename` 参数无效 -|`ACCESS_DENIED` |访问文件位置的权限被拒绝 -|`INVALID_OFFSET` |触发原因:`absolute_offset < 0`,或偏移导致定位越过文件末尾 -|`DELETE_FAILED` |请求的文件删除操作失败 -|`RENAME_FAILED` |请求的文件重命名操作失败 -|`NO_DATA_FOUND` |预定义异常;见下文文件末尾行为说明 -|`VALUE_ERROR` |预定义异常;写入数据超过 `max_linesize` 时抛出 -|=== +[source,text] +---- +NOTICE: text=你好,IvorySQL, bytes=17 +---- -`UTL_FILE` 的过程也可能抛出其他预定义 PL/iSQL 异常。 +=== 写入 BYTEA -文件末尾行为:Oracle 中 `GET_LINE` 读过文件末尾时抛出 `NO_DATA_FOUND`;IvorySQL 改为以 `LOG` 级别记录(`no data found`)并返回 `NULL`,因此 `WHILE line IS NOT NULL` 循环写法可以直接使用: +本例写入的五个字节为 `41 42 0a 43 44`,即 `AB`、LF、`CD`,最后没有换行。因为内容是有效文本,所以可用 `GET_LINE` 验证;一般二进制内容不应通过文本接口读取。 [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + f := UTL_FILE.FOPEN('utl_file_demo', 'raw.dat', 'W'); + UTL_FILE.PUT_RAW(f, decode('41420a4344', 'hex'), TRUE); + UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('utl_file_demo', 'raw.dat', 'R'); + UTL_FILE.GET_LINE(f, line); + RAISE NOTICE 'first=%', line; UTL_FILE.GET_LINE(f, line); - WHILE line IS NOT NULL LOOP - RAISE NOTICE '>>%<<', line; + RAISE NOTICE 'last=%', line; + BEGIN UTL_FILE.GET_LINE(f, line); - END LOOP; + EXCEPTION WHEN NO_DATA_FOUND THEN + RAISE NOTICE 'EOF'; + END; UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'raw.dat'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -错误处理示例: +[source,text] +---- +NOTICE: first=AB +NOTICE: last=CD +NOTICE: EOF +---- + +=== 捕获定位参数错误 + +`INVALID_OFFSET` 是错误消息,不是包中声明的异常变量。用 `WHEN OTHERS` 捕获后,可检查 `SQLSTATE` 和 `SQLERRM`;不符合预期的错误应重新抛出。 [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; BEGIN - -- 'wrong_directory' 未注册,报 INVALID_PATH - f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024); + f := UTL_FILE.FOPEN('utl_file_demo', 'offset.txt', 'W'); + UTL_FILE.PUT(f, 'abc'); + UTL_FILE.FCLOSE(f); + f := UTL_FILE.FOPEN('utl_file_demo', 'offset.txt', 'R'); + BEGIN + UTL_FILE.FSEEK(f); + EXCEPTION WHEN OTHERS THEN + IF SQLSTATE <> 'P0001' OR SQLERRM <> 'INVALID_OFFSET' THEN + RAISE; + END IF; + RAISE NOTICE 'error=%, pos=%', SQLERRM, UTL_FILE.FGETPOS(f); + END; + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'offset.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- [source,text] ---- -ERROR: INVALID_PATH -DETAIL: File location is invalid. -HINT: locality is not found in sys.utl_file_directory table +NOTICE: error=INVALID_OFFSET, pos=0 ---- -== 与 Oracle 的差异 +=== 提交、回滚与文件内容 -与 Oracle 的主要差异如下: +句柄可以跨事务提交继续使用。顶层事务回滚或因未处理错误而中止时,资源清理回调会关闭当前会话全部打开的文件;在内部异常块捕获错误所引起的子事务回滚,不会触发这种全部关闭。正常后端退出也注册了文件清理回调,但不能将其视为进程崩溃时的持久化保证。 -[cols="2,4",options="header"] -|=== -|方面 |IvorySQL 行为 -|目录对象 |使用 `sys.utl_file_directory` 表替代 Oracle 的 `CREATE DIRECTORY`/`ALL_DIRECTORIES`;同时接受位于已注册目录之下的原始路径 -|文件末尾 |`GET_LINE` 读到 EOF 返回 `NULL`;Oracle 抛出 `NO_DATA_FOUND` -|字节模式 |不支持 `rb`/`wb`/`ab` 打开模式,传入报 `INVALID_MODE`。句柄类型中保留 `byte_mode` 字段供将来使用 -|缺失的子程序 |`GET_RAW`、`PUT_NCHAR`、`PUTF_NCHAR` 尚未实现 -|`FSEEK` 两个偏移均为 `NULL` |重置文件位置为 0;Oracle 抛出 `INVALID_OFFSET` -|`PUTF` 格式串 |支持 `%%` 表示字面量 `%`(IvorySQL 扩展);没有对应参数的 `%s` 替换为空字符串,与 Oracle 一致 -|`FCLOSE_ALL` 与 `IS_OPEN` |`FCLOSE_ALL` 之后 `IS_OPEN` 在 IvorySQL 中返回 `FALSE`;Oracle 对未改动的句柄仍返回 `TRUE` -|异常集合 |实现中未专门识别的异常(`ACCESS_DENIED`、`DELETE_FAILED`、`RENAME_FAILED`、`FILE_OPEN`、`CHARSETMISMATCH`、`INVALID_FILENAME`、`INTERNAL_ERROR`)会以最接近的 Oracle 异常抛出,通常是 `INVALID_PATH`/`INVALID_OPERATION`/`READ_ERROR`/`WRITE_ERROR`,`DETAIL` 中带操作系统错误文本 -|文件属主 |UNIX 上 `FOPEN` 创建的文件属主为数据库服务器运行用户,与 Oracle 一致;权限按 `utl_file.umask` 掩码设置 -|=== +文件操作不参与数据库事务回滚。关闭流可能将此前的缓冲写入提交给操作系统,因此 `ROLLBACK` 不会撤销已经写入的内容、恢复被截断的文件,或撤销删除及重命名。 -== 事务与会话生命周期 - -文件句柄在 `COMMIT` 后仍然有效;事务回滚或会话结束时自动关闭,避免缓冲数据静默丢失: +以下匿名块应直接在自动提交的顶层会话执行,不要用显式事务包裹,也不要给执行 `COMMIT`/`ROLLBACK` 的块加异常处理区。 [source,sql] ---- +DECLARE + f UTL_FILE.FILE_TYPE; + line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory','regress.txt','A',1024); - RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + f := UTL_FILE.FOPEN('utl_file_demo', 'transaction.txt', 'W'); + UTL_FILE.PUT_LINE(f, 'kept'); COMMIT; - RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + RAISE NOTICE 'after commit: open=%', UTL_FILE.IS_OPEN(f); ROLLBACK; - RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- f + RAISE NOTICE 'after rollback: open=%', UTL_FILE.IS_OPEN(f); + + f := UTL_FILE.FOPEN('utl_file_demo', 'transaction.txt', 'R'); + UTL_FILE.GET_LINE(f, line); + RAISE NOTICE 'content=%', line; + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'transaction.txt'); END; / ---- -== 实现说明 +[source,text] +---- +NOTICE: after commit: open=t +NOTICE: after rollback: open=f +NOTICE: content=kept +---- + +=== 清理目录登记 + +完成以上示例后,删除本节创建的登记。示例文件已由各自代码删除;若执行中断,先关闭文件,再检查独立示例目录中的残留文件。 + +[source,sql] +---- +DELETE FROM sys.utl_file_directory +WHERE dirname = 'utl_file_demo' + AND dir = '/tmp/ivorysql_utl_file_demo'; +---- + +确认目录为空后,可在服务器上移除目录: + +[source,bash] +---- +rmdir /tmp/ivorysql_utl_file_demo +---- + +== 错误与兼容性边界 + +当前 C 实现使用以下错误消息。除 `NO_DATA_FOUND` 外,下表中的大写名称均通过通用 `raise_exception` SQLSTATE `P0001` 报出,不代表存在同名的包异常声明。 + +[cols="3,2,7",options="header"] +|=== +|错误消息或条件 |SQLSTATE |典型触发原因 +|`INVALID_PATH` |`P0001` |完整路径不在登记目录范围内,或操作系统返回文件不存在、无访问权限、路径组件不是目录等错误。 +|`INVALID_MODE` |`P0001` |打开模式不是允许的单字符模式,例如 `rb`。 +|`INVALID_MAXLINESIZE` |`P0001` |`max_linesize` 或非空的 `GET_LINE.len` 不在 1~32767 范围内。 +|`INVALID_FILEHANDLE` |`P0001` |句柄不在当前会话的有效槽位中,例如关闭后再次读取。 +|`INVALID_OPERATION` |`P0001` |对只写句柄读取、对只读句柄写入,或其他未映射为路径错误的操作系统失败。 +|`INVALID_OFFSET` |`P0001` |两个定位偏移均为空,或目标偏移越界。 +|`READ_ERROR` |`P0001` |底层读取失败且未被映射为 `INVALID_OPERATION`;不能简单解释为文本行超过长度上限。 +|`WRITE_ERROR` |`P0001` |底层写入、刷新或关闭失败;或禁止覆盖时重命名目标已经存在。 +|`VALUE_ERROR` |`P0001` |单次受检查的文本写入超出长度预算,附带 `buffer is too short`。不要假定它能由预定义的 `WHEN VALUE_ERROR` 捕获。 +|`NO_DATA_FOUND` / `no data found` |`P0002` |读取时因 EOF 未获得任何字符;可以用 `WHEN NO_DATA_FOUND` 捕获。 +|`null value not allowed` |`22004` |必需参数为 `NULL`,例如显式传入空的 `max_linesize` 或写入缓冲区。 +|`program limit exceeded` |`54000` |尝试获得第 51 个同时打开的文件句柄。 +|=== + +还可能出现 `22023` 参数错误(例如 `FCOPY` 的非正行号)、字符集转换或校验错误,以及数据库对象权限错误。诊断时应同时查看 `SQLSTATE`、`SQLERRM` 和服务器返回的 `DETAIL`。 + +当前包没有声明 Oracle 文档中常见的 `ACCESS_DENIED`、`DELETE_FAILED`、`RENAME_FAILED`、`FILE_OPEN`、`CHARSETMISMATCH`、`INVALID_FILENAME`、`INTERNAL_ERROR` 等专用异常,不能将它们列为已实现的包异常集合。删除或重命名失败一般按底层错误映射为 `INVALID_PATH` 或 `INVALID_OPERATION`。 + +尚未提供的公开子程序包括 `GET_RAW`、`PUT_NCHAR`、`PUTF_NCHAR`;也未提供字节打开模式。迁移代码时,还应重点复核目录授权、单次与累计长度、NCHAR 混用、关闭后的句柄状态以及文件操作不随事务回滚等行为。 + +== 核验依据 + +本次核验日期为 2026-12-03。实际实例报告版本为 `PostgreSQL 19.0 (IvorySQL 6.0)`,安装的 `ivorysql_ora` 扩展版本为 `1.1`。以上全部可执行 SQL 示例均从本文提取,在该实例的 Oracle 兼容端口以 `ON_ERROR_STOP` 执行,并核对所列输出。 + +对应源码位于: + +* `contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql`:包类型、公开签名、默认值、包装过程及目录表初始权限。 +* `contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`:路径检查、文件槽位、读写与定位、错误映射和资源清理。 +* `contrib/ivorysql_ora/src/ivorysql_ora.c`:`utl_file.umask` 配置注册。 +* `contrib/ivorysql_ora/sql/utl_file.sql`、`contrib/ivorysql_ora/sql/utl_file_putf.sql`:现有回归用例,作为核对线索;本文示例另外在运行实例上执行验证。 -安全模型、句柄管理与内部实现见 xref:v6.0/compatibility_features_design/utl_file_impl.adoc[UTL_FILE 实现设计]。 +除正文示例外,还验证了子目录访问、同级目录与越界路径拒绝、空文件 EOF、无效模式、显式 `NULL` 参数、长度上下界、多字节字符截断、普通/NCHAR 接口混用、定位边界、只读/只写句柄误用、重复关闭、50 个句柄上限及 `PUT_RAW` 的长度行为。 diff --git a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc index 18999041..4a43cc4c 100644 --- a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc +++ b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc @@ -173,11 +173,36 @@ SELECT safe_div(1, 0) FROM dual; [source,sql] ---- -- 允许:INSERT INTO ... WITH FUNCTION ... SELECT ...(Oracle 兼容形式) + +-- 创建数据表 +CREATE TABLE emp ( + empno NUMBER(4) PRIMARY KEY, + sal NUMBER(10, 2), + deptno NUMBER(2) +); + +CREATE TABLE emp_bonus ( + empno NUMBER(4) PRIMARY KEY, + bonus NUMBER(12, 2) +); + +-- 插入测试数据 +INSERT INTO emp (empno, sal, deptno) VALUES (1001, 5000, 10); +INSERT INTO emp (empno, sal, deptno) VALUES (1002, 8000, 10); +INSERT INTO emp (empno, sal, deptno) VALUES (1003, 6000, 20); + +COMMIT; + WITH FUNCTION get_bonus(sal NUMBER) RETURN NUMBER AS BEGIN RETURN sal * 1.2; END; INSERT INTO emp_bonus (empno, bonus) SELECT empno, get_bonus(sal) FROM emp WHERE deptno = 10; + +-- 验证结果 +SELECT empno, bonus FROM emp_bonus ORDER BY empno; + +-- 预期得到 1001 6000 | 1002 9600 ---- NOTE: Oracle 不允许 WITH FUNCTION 位于 UPDATE、DELETE、MERGE 之前。 diff --git a/EN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc b/EN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc index 7f013279..d63be4af 100644 --- a/EN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc +++ b/EN/modules/ROOT/pages/v6.0/compatibility_features_design/utl_file_impl.adoc @@ -1,125 +1,157 @@ :sectnums: :sectnumlevels: 5 -= UTL_FILE package implementation += UTL_FILE Package Implementation == Purpose -IvorySQL implements Oracle's `UTL_FILE` package, providing server-side text file I/O including open, close, read, write, flush, position seeking, file attribute queries, and file copy/remove/rename. Its public API, open modes, line-length limits, 50-open-file limit, and exception names match Oracle. For user examples, see xref:v6.0/oracle_compatibility/compat_utl_file.adoc[UTL_FILE package]. +IvorySQL's `UTL_FILE` package provides server-side file operations for opening, closing, reading, writing, flushing, seeking, querying attributes, copying, deleting, and renaming. It provides a subset of Oracle-compatible interfaces. For usage and compatibility boundaries, see link:compat_utl_file_en.adoc[UTL_FILE Package]. -Two security mechanisms that PostgreSQL's built-in file functions do not provide are added alongside: - -* a `sys.utl_file_directory` registry table that whitelists accessible directories, mirroring Oracle's directory objects; -* a `utl_file.umask` GUC that controls the permission mask of files created by `FOPEN`. +Files are accessed by the database server process. `sys.utl_file_directory` registers the directories that may be accessed, and `utl_file.umask` controls the permission mask for files created by `FOPEN`. == Implementation -=== Code organization and call path +=== Code Organization and Call Flow + +All paths in the following table are relative to `contrib/ivorysql_ora/`. [cols="3,3",options="header"] |=== -|Source path |Responsibility -|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql` |Registers the C entry points `sys.ora_utl_file_*`, the composite types (`ORA_UTL_FILE_FILE_TYPE`, `ora_utl_file_fgetattr_result`), the `sys.utl_file_directory` table, and the `UTL_FILE` package specification and body -|`contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c` |C implementation: path security checks, handle slot management, stdio-based I/O, umask GUC hooks -|`contrib/ivorysql_ora/sql/utl_file.sql` |Regression cases -|`contrib/ivorysql_ora/expected/utl_file.out` |Expected results -|`Makefile`, `meson.build`, `ivorysql_ora_merge_sqls` |Build integration and SQL merge for the new directory -|`src/ivorysql_ora.c` |Declares the `utl_file.umask` custom GUC in `_PG_init` +|Source Path |Responsibility +|`src/builtin_packages/utl_file/utl_file--1.0.sql` |Defines the underlying `sys.ora_utl_file_*` functions, the `ora_utl_file_fgetattr_result` composite type, the directory table, and the `UTL_FILE` package. +|`src/builtin_packages/utl_file/utl_file.c` |Implements path checks, handle slots, stdio I/O, resource cleanup, and umask hooks. +|`sql/utl_file.sql`, `sql/utl_file_putf.sql`, and the corresponding `.out` files under `expected/` |Regression cases and expected results for package interfaces, handle lifetimes, and formatted output with multibyte encodings. +|`Makefile`, `meson.build`, `ivorysql_ora_merge_sqls`, `gensql.pl` |Build the shared library and generate extension installation scripts from the SQL path list and version information. +|`src/ivorysql_ora.c` |Registers `utl_file.umask` in `_PG_init()`. |=== +The main call flows are shown below, omitting argument checks and error branches: + [source,text] ---- -UTL_FILE.FOPEN(location, filename, open_mode, max_linesize) - → package body: file.id := sys.ora_utl_file_fopen(location, filename, open_mode, max_linesize) - → ora_utl_file_fopen() → get_safe_path() → fopen() → reserve_slot() +UTL_FILE.FOPEN(...) + → sys.ora_utl_file_fopen(...) + → get_safe_path() → temporarily set umask → fopen() → restore umask → reserve_slot() UTL_FILE.PUT_LINE(file, buffer, autoflush) → sys.ora_utl_file_put_line(file.id, buffer, autoflush) - → ora_utl_file_put_line() → get_file_handle_from_slot() → fprintf()/fflush() + → do_put() → do_write() → encoding conversion, length check, fwrite() + → put_lines() → fputc('\n') → fflush() if autoflush is enabled UTL_FILE.GET_LINE(file, buffer, len) → sys.ora_utl_file_get_line(file.id, len) - → ora_utl_file_get_line() → get_line() (returns NULL at EOF) + → get_line() → fgetc()/ungetc() → encoding validation and conversion + → return TEXT; raise NO_DATA_FOUND if no characters were read because of EOF ---- -The `UTL_FILE.*` subprograms in the package body are thin wrappers: they unpack the composite file handle and forward the numeric slot id to the `sys.ora_utl_file_*` C entry points. `FOPEN_NCHAR`/`GET_LINE_NCHAR`/`PUT_LINE_NCHAR` pass the encoding name `UTF8` explicitly; `FOPEN` without the encoding argument uses the database encoding. +The public handle is the package record `UTL_FILE.FILE_TYPE`, containing `id`, `datatype`, and `byte_mode`; there is no SQL type named `sys.ora_utl_file_file_type`. The package body passes `file.id` to the underlying functions, which perform the operation through C entry points or SQL wrapper overloads. + +`FOPEN` uses the database encoding, while `FOPEN_NCHAR` explicitly passes `'UTF8'` when opening the file. The actual encoding is stored in the C slot. `GET_LINE_NCHAR` and `PUT_LINE_NCHAR` neither reset the encoding nor check the record's `datatype`. `PUT_LINE_NCHAR` always enables flushing. Byte open modes are not currently implemented. + +=== Security Model -=== Security model +==== Directory Registration Table -==== Directory registry +The installation script creates `sys.utl_file_directory(dirname name PRIMARY KEY, dir TEXT)`, revokes all privileges from `PUBLIC`, and then grants `SELECT`. The table owner, superusers, and roles granted the necessary table privileges can maintain registrations. The table does not provide a model for granting directory `READ` and `WRITE` privileges separately to individual users. -Access is restricted to directories registered in `sys.utl_file_directory (dirname name PRIMARY KEY, dir TEXT)`. `REVOKE ALL ... FROM PUBLIC` followed by `GRANT SELECT TO PUBLIC` means only superusers can maintain the registry, while unprivileged users can see it. +Operations that require file paths pass through `get_safe_path()`. Copying and renaming check both source and destination paths: -Every operation that turns `location` + `filename` into a filesystem path goes through `get_safe_path()`: +. `safe_named_location()` looks up an alias by equality against `dirname`. If a non-null path is found, it substitutes that path; otherwise, it treats `location` as a path. +. The directory, `/`, and `filename` are joined, and `canonicalize_path()` normalizes the result. +. `check_secure_locality()` executes an SPI query to check whether the full path falls under a registered directory. -. `safe_named_location()` looks the location up by exact `dirname` equality (deliberately not `LIKE`, to avoid `_`/`%` special handling) and substitutes the registered path when found. -. The full path is assembled and passed through `canonicalize_path()`. -. `check_secure_locality()` runs a cached SPI query that verifies the canonicalized path lies within a registered directory using prefix comparison with explicit `/` handling: +The internal query is shown below. `$1` is bound by the C layer; this is not standalone SQL that can be executed without parameter binding: [source,text] ---- SELECT 1 FROM sys.utl_file_directory - WHERE CASE WHEN substring(dir from '.$') = '/' THEN +WHERE CASE WHEN substring(dir from '.$') = '/' THEN substring($1, 1, length(dir)) = dir - ELSE +ELSE substring($1, 1, length(dir) + 1) = dir || '/' - END +END ---- -If no registered directory matches, the operation fails with `INVALID_PATH` (`errdetail: File location is invalid.`, `errhint: locality is not found in sys.utl_file_directory table`). Because the check runs on the canonicalized full path, `..`-style escapes resolve to real paths before matching and cannot smuggle writes outside the registry. +Equality comparisons avoid wildcard interpretation of `_` and `%`, while the separator check prevents matching sibling directories that share a name prefix. SPI caches the query plan but still queries the registration table on each call. If no row matches, `INVALID_PATH` is raised. + +The check permits subdirectory access, but it only normalizes path strings and does not resolve symbolic links; it must not be regarded as a file system sandbox. Removing a registration affects subsequent opens. Handles that are already open do not recheck the directory table. ==== utl_file.umask -`FOPEN` creates files with the mode implied by `fopen()`, masked by `utl_file.umask` (default `0077`). The implementation brackets the `fopen()` call with `umask()` save/restore so no other operations in the process are affected. +`utl_file.umask` is a string GUC with a default value of `'0077'`, declared as `PGC_USERSET`. Permission to change it is restricted by the check hook: + +* During normal processing within a transaction, the check hook requires a superuser. It validates up to four octal digits and stores the converted integer in `extra`. +* The assign hook reads the integer from `extra` and assigns it to the internal mask variable. -The GUC is declared as a string with check/assign hooks: +`FOPEN` and `FOPEN_NCHAR` save and set the process mask before `fopen()`, then restore it after the call returns. Permissions on existing files remain unchanged. `FCOPY` does not perform this mask switch; its resulting permissions depend on the backend's original mask and file system rules. -* the check hook rejects non-octal digits, and inside normal processing requires superuser (`ERCODE_INSUFFICIENT_PRIVILEGE` otherwise); -* the assign hook converts the string to an integer used by `FOPEN`. +=== Handle Management -=== Handle management +Each backend uses 50 static slots containing `FILE *`, `max_linesize`, the encoding, and a `uint32 id`. An id of 0 indicates a free slot. IDs are generated by a counter and cannot be used across sessions. -Handles live in a fixed table of 50 slots (`MAX_SLOTS`, matching Oracle 10g) holding the `FILE*`, `max_linesize`, and encoding. `FOPEN` allocates a slot and stores its numeric id in the composite file handle; exceeding the limit fails with `ERRCODE_PROGRAM_LIMIT_EXCEEDED`. +`FOPEN` allocates a slot after calling `fopen()`. If no slot is available, it raises `54000 / program limit exceeded`, but the file may already have been created or truncated. `FCLOSE` releases the slot and closes the stream; `FCLOSE_ALL` closes all slots. After closure, `IS_OPEN` returns `FALSE` for the old handle. -PostgreSQL's `AllocateFile` is intentionally *not* used: it auto-closes files at transaction commit/abort, while Oracle-compatible handles must survive `COMMIT`. Instead: +To keep handles usable after `COMMIT`, the implementation does not use `AllocateFile`, which automatically closes streams at transaction end. Two types of callbacks are registered after the first successful open: -* a `ResourceOwner` release callback closes handles on transaction abort or session end; -* a `before_shmem_exit` hook does a final sweep so buffered data is flushed and files closed even on abnormal backend termination. +* The resource release callback closes all slots in the current session only during `RESOURCE_RELEASE_AFTER_LOCKS` when `isTopLevel = TRUE` and `isCommit = FALSE`. This includes handles left open by previously committed transactions. Commits and subtransaction rollbacks within inner exception blocks do not trigger this closure. +* The `before_shmem_exit` callback closes files during normal exit processing, but is not guaranteed to run after a crash, immediate exit, or `SIGKILL`. -This yields the documented lifecycle: `IS_OPEN` stays `TRUE` across `COMMIT`, becomes `FALSE` after `ROLLBACK`, and all handles are gone when the session exits. `FCLOSE_ALL` closes every slot owned by the session. +Closing a stream may flush buffered data. File operations do not participate in database transaction rollback: `ROLLBACK` does not restore truncated files or undo writes, deletions, or renames. -=== I/O behavior and exceptions +=== I/O Behavior and Errors -* All text I/O goes through stdio with the encoding recorded at open time, so `GET_LINE`/`PUT_LINE` perform conversion between the database encoding and the file encoding. -* `GET_LINE` returns at most the lesser of `len`, the distance to the next line terminator, and `max_linesize` — the Oracle *Operational Notes* rule; the terminator itself is not stored, and blank lines yield empty strings. -* `GET_LINE` reads up to `max_linesize` bytes per call (`len` temporarily lowers it); at EOF it logs `no data found` at `LOG` level and returns `NULL`, so callers can loop on `WHILE line IS NOT NULL`. The `NO_DATA_FOUND` condition is therefore observable in the server log rather than raised as an error. -* `PUTF` implements Oracle's limited-`printf()` format: `\n` becomes the platform line terminator, `%s` consumes the next argument (unmatched formatters render as an empty string, including `NULL` arguments), and `%%` is an IvorySQL extension producing a literal `%`. A `CHECK_LENGTH` guard raises `VALUE_ERROR` ("buffer is too short") as soon as the accumulated output exceeds `max_linesize`. -* `FSEEK` supports absolute (`SEEK_SET`, preceded by a `rewind`) and relative (`SEEK_CUR`, may be negative) offsets; both `NULL` resets the position to 0. Invalid combinations raise `INVALID_OFFSET`. -* `FFLUSH` explicitly `fflush()`es the stream, which is what makes buffered writes visible to a concurrently opened read handle. -* `FGETATTR` returns `(fexists, file_length, block_size)` via a composite type; `file_length` is carried as `numeric` to match Oracle's `NUMBER`. -* `FCOPY` copies line ranges (`start_line` must be positive); `FRENAME` refuses to clobber the destination unless `overwrite = TRUE` (`WRITE_ERROR: Destination file already exists`). +* `GET_LINE` reads byte by byte, recognizes LF, CRLF, and CR, validates the encoding, and converts the result to the database encoding. The limit per call is `min(len, max_linesize)`; when `len` is null, `max_linesize` is used. The valid length range is 1–32767. +* An empty line returns zero-length text. If no characters are read because of EOF, the entry point raises `ERROR / P0002 / no data found`; catch `NO_DATA_FOUND` to end a reading loop. A newline left unconsumed when the byte limit is reached remains for the next read, which may return an empty string. Splitting a multibyte character may raise an encoding error. +* `PUT` and `PUT_LINE` check the converted byte length of the argument for each call, without accumulating lengths across calls. The newline appended by `PUT_LINE` is excluded from the check. `NEW_LINE` does not perform this length check. `PUT_RAW` writes `BYTEA` directly, without encoding conversion or a `max_linesize` check. +* `PUTF` scans complete characters using the file encoding and supports `%s`, `%%`, and a backslash followed by `n`. It accumulates output bytes within a single call, including newlines. Exceeding the limit raises `VALUE_ERROR`, and a prefix already written may remain. Multibyte scanning and boundaries are covered by the `utl_file_putf` regression suite. +* `FSEEK` requires at least one offset, with the absolute offset taking precedence. After flushing, measuring the file length, and restoring the original position, it checks that the target is within `[0, file length]` and seeks using `SEEK_SET`. Out-of-range arguments raise `INVALID_OFFSET`. `FGETPOS` returns a 32-bit `INTEGER`. +* `FFLUSH` calls `fflush()` to submit the stdio buffer to the operating system. It does not call `fsync()` and cannot guarantee persistence to physical storage. +* `FGETATTR` returns attributes through a composite type: the length is converted from `st_size` to numeric, and the block size comes from `st_blksize`. Any `stat()` failure returns `FALSE, NULL, NULL`, which does not exclusively indicate a missing file. +* `FCOPY` uses `fgets()`, `strlen()`, and `fwrite()` to copy text by LF-delimited lines. The destination is created or truncated first, and the operation is unsuitable for data containing NUL bytes. `FREMOVE` calls `unlink()`. When overwriting is disabled, `FRENAME` checks the destination before calling `rename()`; this does not provide an atomic no-overwrite guarantee under concurrency. -Oracle-compatible exceptions (`INVALID_FILEHANDLE`, `INVALID_MAXLINESIZE`, `INVALID_MODE`, `INVALID_OFFSET`, `INVALID_OPERATION`, `INVALID_PATH`, `READ_ERROR`, `VALUE_ERROR`, `WRITE_ERROR`) are raised as `ERRCODE_RAISE_EXCEPTION` with the Oracle exception name as `SQLERRM`, so `WHEN OTHERS` plus `SQLERRM` reproduces Oracle's error handling style. Oracle defines a larger exception set (also `ACCESS_DENIED`, `CHARSETMISMATCH`, `DELETE_FAILED`, `FILE_OPEN`, `INTERNAL_ERROR`, `INVALID_FILENAME`, `RENAME_FAILED`); the implementation does not detect these conditions specifically, and the underlying operating system errors surface under the closest name above, with `strerror(errno)` text in the `DETAIL` field. +`INVALID_FILEHANDLE`, `INVALID_MAXLINESIZE`, `INVALID_MODE`, `INVALID_OFFSET`, `INVALID_OPERATION`, `INVALID_PATH`, `READ_ERROR`, `VALUE_ERROR`, and `WRITE_ERROR` are all `P0001` error messages, not package exception declarations. Check `SQLSTATE` and `SQLERRM` in a `WHEN OTHERS` handler; do not assume that the predefined `WHEN VALUE_ERROR` handler catches the message with the same name. + +`IO_EXCEPTION()` maps `EACCES`, `ENAMETOOLONG`, `ENOENT`, and `ENOTDIR` to `INVALID_PATH`, and other errno values to `INVALID_OPERATION`, with details from `strerror(errno)`. Dedicated exceptions such as `ACCESS_DENIED` and `CHARSETMISMATCH` are not implemented. NULL argument, encoding, and permission errors may also occur. == Error Handling Example -=== Unregistered directory +=== Unregistered Directory + +Run this example in IvorySQL `psql` connected through the Oracle compatibility port. It assumes that the absolute path below is outside all registered directories. The path check fails before the operating system attempts to open the file. [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; BEGIN - f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024); + f := UTL_FILE.FOPEN('/tmp/utl_file_impl_unregistered_20261203', + 'missing.txt', 'R'); END; / --- ERROR: INVALID_PATH --- DETAIL: File location is invalid. --- HINT: locality is not found in sys.utl_file_directory table ---- -The path check reports an error before opening the file. This example assumes `wrong_directory` is neither registered nor a valid path within a registered directory. +The expected error is shown below, with the call stack omitted: -== Regression verification +[source,text] +---- +ERROR: INVALID_PATH +DETAIL: File location is invalid. +HINT: locality is not found in sys.utl_file_directory table +---- + +== Regression Verification -The `utl_file` regression group covers: `FOPEN` against an unregistered directory (`INVALID_PATH`), the write/read round trip across `PUT_LINE`/`PUT`/`NEW_LINE`/`PUTF`/`GET_LINE` (including `len`-clipped reads), `FGETATTR`/`FCOPY`/`FREMOVE`/`FRENAME`, the `FFLUSH` visibility barrier and `FSEEK`/`FGETPOS` absolute/relative seeks, exception handling with `FCLOSE_ALL`, and handle lifecycle across `COMMIT`/`ROLLBACK`. +`utl_file` covers paths, reading and writing, attributes and file management, flushing, seek boundaries, EOF, NCHAR, and handle lifetimes. `utl_file_putf` adds multibyte encodings, format substitution, and length boundaries. Both regression suites passed on the current instance. + +Run the following commands from the directory containing `IvorySQL/` and `inst/`. Create a separate database through the PG port, then run the tests through the Oracle port to avoid case differences between the database name created and the connection name. The test database must contain the matching extension. The database name must be unused; adjust the ports and installation path for your environment. + +[source,bash] +---- +./inst/bin/createdb -h 127.0.0.1 -p 5432 -U highgo \ + -T template0 -E UTF8 utl_file_impl_check_20261203 +mkdir -p /tmp/utl_file_impl_check_20261203 +LD_LIBRARY_PATH=/home/highgo/6.0/inst/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} \ +make -C IvorySQL/contrib/ivorysql_ora oracle-installcheck \ + ORA_REGRESS='utl_file utl_file_putf' TAP_TESTS= \ + ORACLE_REGRESS_OPTS='--host=127.0.0.1 --port=1521 --user=highgo --dbname=utl_file_impl_check_20261203 --use-existing --outputdir=/tmp/utl_file_impl_check_20261203' +---- -From a configured and built IvorySQL source tree, run `make -C contrib/ivorysql_ora oracle-installcheck ORA_REGRESS=utl_file` to verify this test group. The target instance must have the matching version of the `ivorysql_ora` extension installed. +`ORACLE_REGRESS_OPTS` passes options to the Oracle regression runner, and `TAP_TESTS=` prevents additional TAP tests from running. The original cases use fixed file names in the data directory. Run them on a dedicated test instance or first confirm that those names are unused. Afterwards, clean up only the files and database created by this test run. diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc index 0e95a39a..34dbd47c 100644 --- a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc +++ b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_utl_file.adoc @@ -1,409 +1,582 @@ :sectnums: :sectnumlevels: 5 -= UTL_FILE package += UTL_FILE Package -== Purpose +== Overview and Scope -The `UTL_FILE` package reads and writes text files on the server from PL/iSQL. It also provides procedures to inspect, copy, remove, and rename files. `FOPEN` returns a `sys.ORA_UTL_FILE_FILE_TYPE` handle for subsequent read, write, and close operations. +`UTL_FILE` provides PL/iSQL operations on files on the database server, including text input and output, file positioning, attribute queries, copying, deletion, and renaming. Files are accessed by the database server process, and paths refer to the server's file system rather than the client's file system. -== Feature Description +The examples use Linux, a UTF8 database, and the `psql` client supplied with IvorySQL, connected through the Oracle compatibility port. Oracle's full set of interfaces, exceptions, and boundary behaviors must not be assumed to apply to this implementation. -=== Security prerequisites +== Prerequisites -`UTL_FILE` uses the `sys.utl_file_directory` table to restrict access to directories. Register a directory in this table before using file operations. +=== Directory Registration and Permissions -[source,sql] ----- -CREATE TABLE sys.utl_file_directory( - dirname name PRIMARY KEY, - dir TEXT -); ----- +The `sys.utl_file_directory` table is created when `ivorysql_ora` is installed; applications do not need to create it again. Its two columns, `dirname name PRIMARY KEY` and `dir text`, store a directory alias and the corresponding directory path on the server. -* Unprivileged users have `SELECT` on `sys.utl_file_directory` only; adding or deleting registered directories requires superuser privileges. This corresponds to Oracle's `CREATE DIRECTORY` privilege, which is granted only to `SYS` and `SYSTEM` by default. -* Register a directory before use, then reference it by its `dirname`: +By default, `PUBLIC` has `SELECT` permission on this table but no write permissions. Directories can be registered by the table owner, a superuser, or a role explicitly granted the necessary table permissions; modifying directory registrations is not restricted to superusers. Registering a directory neither creates the operating system directory nor changes its permissions. -[source,sql] ----- --- register the data directory as a directory object named 'data_directory' -INSERT INTO sys.utl_file_directory(dirname, dir) -VALUES ('data_directory', current_setting('data_directory')); ----- +Paths are resolved as follows: -* The `location` parameter may be either a registered `dirname` or a raw path. Raw paths are canonicalized and must fall under one of the registered directories (prefix match); otherwise the operation fails with `INVALID_PATH`. -* As in Oracle, **a subdirectory of an accessible directory is not automatically accessible**; it must be registered with a complete path of its own. -* File permission mask: files created by `FOPEN` are subject to the `utl_file.umask` parameter (default `0077`). Only superusers can change it, and the value must be 3–4 octal digits: +* `location` is first looked up as a directory alias in `dirname`. If no alias matches, it is treated as a path. Aliases are matched against their stored strings; all examples use lowercase aliases. +* After the directory and `filename` are joined and the resulting path is normalized, the full file path is checked for a prefix consisting of a registered `dir` followed by a directory separator. Registering `dir` as a normalized absolute path is recommended. +* This check permits access to subdirectories of a registered directory. Subdirectories must already exist but do not need separate registration; `filename` can also include subdirectory components. A sibling directory with a similar name does not gain access merely because its name shares a prefix. +* After `..` components are normalized, the final path must still fall within a registered directory. The implementation checks path strings without resolving symbolic links through `realpath()`, so the registration table must not be regarded as a file system sandbox that isolates symbolic link targets. +* Environment variables and `~` are not expanded. Actual read and write access also depends on the file system permissions of the operating system user running the database. -[source,sql] ----- -SET utl_file.umask = '0022'; -SHOW utl_file.umask; ----- +The registration table does not provide a model for granting directory `READ` and `WRITE` permissions separately to each database user. Do not register the database data directory as a general application working directory; this document uses a separate example directory. + +=== File Handles + +In PL/iSQL, declare variables using the package type `UTL_FILE.FILE_TYPE`. Both `FOPEN` and `FOPEN_NCHAR` return this type. Do not create or reference `sys.ORA_UTL_FILE_FILE_TYPE`; that SQL type does not exist in the current installation. + +The package record contains `id INTEGER`, `datatype INTEGER`, and `byte_mode BOOLEAN`. These fields are for internal use. Applications should pass the entire record as a handle and should not modify or persist its fields to reconstruct a handle. A handle is valid only in the database session that created it. Each session can hold at most 50 open file handles at a time. + +`IS_OPEN` checks whether a handle is still present in the current session's open file table. `FCLOSE` closes a single handle; `FCLOSE_ALL()` closes all file handles in the current session. After either operation, `IS_OPEN` returns `FALSE`. Reading, writing, or closing an already closed handle raises `INVALID_FILEHANDLE`. + +=== Permissions for Newly Created Files + +When creating a new file, `FOPEN` and `FOPEN_NCHAR` temporarily apply `utl_file.umask`, whose default value is `'0077'`. Under the ordinary Linux permission model, new files typically have mode `0600` and are owned by the operating system user running the database. File system ACLs and other factors can also affect the final permissions. Opening an existing file does not change its permissions. + +The current setting validation requires superuser privileges and accepts one to four octal digits, such as `'77'`, `'077'`, and `'0077'`; values are not restricted to three or four digits. An explicit four-digit form is recommended. `FCOPY` creates its destination through a separate `fopen()` code path that does not temporarily apply `utl_file.umask`, so its file permissions must not be assumed to match those of a file created by `FOPEN`. + +== Interface Reference + +The following are the package's public interfaces. Entries with an explicit return type are functions; all other entries are procedures. String parameters use `VARCHAR2`, except that the output buffers of `GET_LINE` and `GET_LINE_NCHAR` and the input buffer of `PUT_LINE_NCHAR` use `TEXT`. All file handle parameters use `UTL_FILE.FILE_TYPE`. -=== Functions and procedures +=== Opening, Closing, Flushing, and Positioning -[cols="4,2,4",options="header"] +[cols="5,7",options="header"] |=== -|Call |Return type |Description -|`FOPEN(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |Open a file for input or output. `open_mode` is one character: `R` (read), `W` (write, truncate), `A` (append). `max_linesize` defaults to 1024, range 1–32767 -|`FOPEN_NCHAR(location, filename, open_mode [, max_linesize])` |`ORA_UTL_FILE_FILE_TYPE` |Open a file in Unicode mode for input or output; the file is read and written in UTF-8 instead of the database character set. Same parameters as `FOPEN` -|`IS_OPEN(file)` |`BOOLEAN` |Determine whether the file handle refers to a file that has been opened but not yet closed -|`FCLOSE(file)` |— |Close an open file identified by a file handle -|`FCLOSE_ALL` |— |Close all open file handles for the session; an emergency cleanup procedure, e.g. when a PL/iSQL program exits on an exception -|`FFLUSH(file)` |— |Physically write all pending output to the file; useful when the file must be read while it is still open (e.g. debug messages) -|`FGETPOS(file)` |`INTEGER` |Return the current relative offset position within the file, in bytes; `0` means the beginning of the file -|`FSEEK(file [, absolute_offset [, relative_offset]])` |— |Adjust the file pointer forward or backward within the file by the number of bytes specified. `absolute_offset` is a byte position counted from the beginning of the file; `relative_offset` seeks forward (positive) or backward (negative) from the current position; with both omitted IvorySQL resets the position to 0 -|`GET_LINE(file, buffer OUT, [len])` |— |Read text up to, but not including, the line terminator, the end of file, or `len` bytes — whichever comes first — into `buffer`. `len` defaults to `max_linesize`; if both are given the lesser value takes precedence. Returns `NULL` at end of file -|`GET_LINE_NCHAR(file, buffer OUT, [len])` |— |Read text in Unicode from a file opened by `FOPEN_NCHAR` -|`NEW_LINE(file [, lines])` |— |Write one or more operating system-specific line terminators (default 1). Separate from `PUT` because the line terminator is a platform-specific character sequence -|`PUT(file, buffer)` |— |Write the string in `buffer` to the file without appending a line terminator; use `NEW_LINE` or `PUT_LINE` to terminate the line -|`PUTF(file, format [, arg1..arg5])` |— |A `PUT` with formatting, like a limited `printf()`. `%s` in `format` is replaced by `arg1`–`arg5` in order, `\n` by the platform line terminator, `%%` by a literal `%` (IvorySQL extension). If there are more `%s` formatters than arguments, an empty string is substituted -|`PUT_LINE(file, buffer [, autoflush])` |— |Write the line to the file and append the platform-specific line terminator; `autoflush = TRUE` flushes the buffer to disk after the write -|`PUT_LINE_NCHAR(file, buffer)` |— |Write a Unicode line to a file opened by `FOPEN_NCHAR`; appends the line terminator -|`PUT_RAW(file, buffer [, autoflush])` |— |Write a `BYTEA` value (the counterpart of Oracle `RAW`) to the file without appending a line terminator; `autoflush = TRUE` flushes after writing -|`FCOPY(src_location, src_filename, dest_location, dest_file [, start_line [, end_line]])` |— |Copy a contiguous portion of a file to a newly created file. By default the whole file is copied; `start_line` (default 1) and `end_line` (default: end of file) select a portion from the source file. The source is opened in read mode, the destination in write mode -|`FREMOVE(location, filename)` |— |Delete a disk file, assuming sufficient privileges; the operating system verifies file and directory permissions -|`FRENAME(src_location, src_filename, dest_location, dest_filename [, overwrite])` |— |Rename a file to a new name, similar to the UNIX `mv` function. `overwrite` defaults to `FALSE`; if the destination exists and `overwrite` is `FALSE`, `WRITE_ERROR` is raised -|`FGETATTR(location, filename, fexists OUT, file_length OUT, block_size OUT)` |— |Read and return the attributes of a disk file: existence, length in bytes (`NULL` if the file does not exist), and file system block size (`NULL` if the file does not exist) +|Interface |Description +|`FOPEN(location, filename, open_mode, max_linesize DEFAULT 1024) RETURN UTL_FILE.FILE_TYPE` +|Reads and writes text in the database character set. `max_linesize` is an `INTEGER` in the range 1–32767. Omitting it uses 1024; explicitly passing `NULL` raises an error. +|`FOPEN_NCHAR(location, filename, open_mode, max_linesize DEFAULT 1024) RETURN UTL_FILE.FILE_TYPE` +|Uses UTF8 as the file encoding, converting to and from the database character set during input and output. All other parameter rules are the same as for `FOPEN`. +|`IS_OPEN(file) RETURN BOOLEAN` +|Checks whether the handle is still open. +|`FCLOSE(file IN OUT)` +|Closes the file and releases the handle slot. The package body does not clear the fields in the caller's record, but the handle is no longer valid. +|`FCLOSE_ALL()` +|Closes all open files in the current session and releases all slots. +|`FFLUSH(file)` +|Calls the C standard library function `fflush()` to submit buffered writes from user space to the operating system. It does not call `fsync()` and does not guarantee that data has been persisted to physical storage. +|`FGETPOS(file) RETURN INTEGER` +|Returns the current byte offset from the beginning of the file, where the initial position is 0. The return type is a 32-bit `INTEGER`, so this interface is unsuitable for file offsets beyond its representable range. +|`FSEEK(file IN OUT, absolute_offset DEFAULT NULL, relative_offset DEFAULT NULL)` +|Both offset parameters are `INTEGER`. Absolute offsets are measured from the beginning of the file; relative offsets are measured from the current position. If both are non-null, the absolute offset takes precedence. If both are null, `INVALID_OFFSET` is raised. |=== -Not yet implemented compared with Oracle: `GET_RAW`, `PUT_NCHAR`, `PUTF_NCHAR`, and the byte (`rb`/`wb`/`ab`) open modes. +Open modes accept a single character and are case-insensitive: -The file handle type corresponds field-by-field to Oracle's private `FILE_TYPE` record; its contents should not be referenced or changed by the user: +[cols="1,5",options="header"] +|=== +|Mode |Behavior +|`R` / `r` |Read only; the file must already exist. +|`W` / `w` |Write only; an existing file is immediately truncated, and a missing file is created. +|`A` / `a` |Append; a missing file is created. Even after a seek, subsequent writes remain subject to the operating system's append mode. +|=== -[source,sql] ----- -CREATE TYPE sys.ORA_UTL_FILE_FILE_TYPE AS(id INTEGER, datatype INTEGER, byte_mode BOOLEAN); ----- +Modes such as `rb`, `wb`, `ab`, and `r+` are not supported. -=== Syntax +The valid target range for `FSEEK` is `[0, file length]`, including the exact EOF position. A negative absolute offset, a relative move before the beginning of the file, or a move beyond EOF raises `INVALID_OFFSET`; the position is not automatically clamped to a file boundary. These out-of-range parameter errors leave the current position unchanged. -`UTL_FILE` subprograms are typically called from PL/iSQL anonymous blocks: +Before seeking, the implementation flushes the stream and measures the file length. A seek can therefore target content already written through the current handle even if it has not been explicitly flushed. To return to the beginning of the file, call `FSEEK(f, 0)`; do not omit both offsets. -[source,sql] ----- -DECLARE - f sys.ora_utl_file_file_type; - line TEXT; -BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); +=== Text Input and Output and Raw Byte Output - UTL_FILE.PUT_LINE(f, 'abc'); - UTL_FILE.PUT_LINE(f, '-----'); - UTL_FILE.FCLOSE(f); +[cols="5,7",options="header"] +|=== +|Interface |Description +|`GET_LINE(file, buffer OUT TEXT, len DEFAULT NULL)` +|Reads a text fragment and removes any line terminator encountered. `len` is an `INTEGER` and, when non-null, must be in the range 1–32767. If omitted or `NULL`, it uses the `max_linesize` specified when the file was opened. Raises `NO_DATA_FOUND` when EOF is reached without reading any characters. +|`GET_LINE_NCHAR(file, buffer OUT TEXT, len DEFAULT NULL)` +|Uses the same reading implementation as `GET_LINE`; the actual file encoding is taken from the encoding saved when the handle was opened. +|`PUT(file, buffer)` +|Writes text without appending a newline. The input length for this call is checked in bytes after conversion to the file encoding. +|`PUT_LINE(file, buffer, autoflush DEFAULT FALSE)` +|Writes text and appends one line terminator. `autoflush` is a `BOOLEAN`; `TRUE` triggers a flush, and an explicit `NULL` is treated as `FALSE`. +|`PUT_LINE_NCHAR(file, buffer TEXT)` +|Writes text, appends a line terminator, and flushes the stream. The package body always passes `TRUE` for `autoflush`; this interface has no third parameter. +|`NEW_LINE(file, lines DEFAULT 1)` +|Writes `lines` line terminators. `lines` is an `INTEGER`; omitting it or passing `NULL` writes one terminator, while zero or a negative value writes nothing. +|`PUTF(file, format, arg1 DEFAULT NULL, arg2 DEFAULT NULL, arg3 DEFAULT NULL, arg4 DEFAULT NULL, arg5 DEFAULT NULL)` +|Writes formatted text without automatically appending a newline. Supports `%s`, `%%`, and the two-character sequence consisting of a backslash followed by `n` in the format string, as described below. +|`PUT_RAW(file, buffer BYTEA, autoflush DEFAULT FALSE)` +|Writes `BYTEA` data directly, without character set conversion or an appended newline. Flushes when `autoflush` is `TRUE`. The current implementation does not check the length of this write against `max_linesize`. +|=== - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); - UTL_FILE.GET_LINE(f, line); - WHILE line IS NOT NULL LOOP - RAISE NOTICE '>>%<<', line; - UTL_FILE.GET_LINE(f, line); - END LOOP; - UTL_FILE.FCLOSE(f); -END; -/ ----- +==== Read Boundaries -In Oracle compatibility mode (`ivorysql.compatible_mode = oracle`) the package can be used directly. As in Oracle, the file location and file name are supplied as separate strings so the location can be checked against the registry; together they must represent a legal filename on the system. +Each `GET_LINE` call reads at most `min(len, max_linesize)` bytes in the file encoding. If `len` is null, the limit is `max_linesize`. Encountering LF, CRLF, or a standalone CR ends the read, and the terminator is excluded from the returned value. -=== Open modes +* Reading an empty line returns a zero-length `TEXT` value. In the environment verified for this document, that value is not `NULL`. End a reading loop by catching `NO_DATA_FOUND`, rather than relying on `line IS NULL`. +* If the final text fragment has no terminating newline, that fragment is returned first; the next read raises `NO_DATA_FOUND`. An empty file raises this exception on the first read. +* A long line does not raise `READ_ERROR` merely because it exceeds the current read limit; it is returned across multiple calls. If the byte limit is reached just before the newline is consumed, the next call consumes that newline and returns an empty string. A verified example of this boundary appears below. +* Lengths are measured in bytes, not characters. If the limit splits a multibyte character, such as a UTF8 character, character set validation can raise an encoding error. Avoid choosing a `len` so small that it splits multibyte characters. -Following Oracle's `FOPEN` definition: +==== Write Lengths and Formatting -[cols="2,4,4",options="header"] +In the current implementation, `max_linesize` is not a limit on the cumulative length of a logical line across calls: + +* `PUT`, `PUT_LINE`, and `PUT_LINE_NCHAR` each check the encoded byte length of the text argument for that call. The newline automatically appended by `PUT_LINE` or `PUT_LINE_NCHAR` is excluded from this check. +* Lengths are not accumulated across consecutive `PUT` calls, and flushing does not reset any accumulated length. Multiple valid calls can therefore produce a line longer than `max_linesize`. +* `PUTF` checks the total number of bytes produced by one call, including substituted arguments and generated newlines. A newline does not reset the count. Exceeding the limit raises `VALUE_ERROR`, and any portion already written may remain in the file. +* `NEW_LINE` does not perform this length check, and `PUT_RAW` is also exempt from it. +* The buffer arguments of `PUT`, `PUT_LINE`, `PUT_LINE_NCHAR`, and `PUT_RAW`, and the format string of `PUTF`, must not be explicitly `NULL`. + +Each `%s` in `PUTF` consumes the next of up to five arguments. An omitted or `NULL` argument produces no content; the sixth and subsequent `%s` directives also produce no content. `%%` writes one `%`. A backslash followed by `n` in the format string writes a newline; the same two characters inside a substituted argument are not interpreted again as a format directive. This is not a complete `printf()` implementation: `%d`, width, precision, and similar formats are not supported. The current implementation discards unknown two-character ASCII percent sequences such as `%d`, so applications should use only the explicitly supported directives. + +Text output writes `\n` through a C text stream. Files in the Linux examples in this document use LF line endings. Although `PUT_RAW` writes bytes directly, it still uses the text stream opened by `FOPEN`; this does not imply support for portable binary open modes. + +`FOPEN_NCHAR` selects UTF8 as the file encoding, but `GET_LINE_NCHAR` and `PUT_LINE_NCHAR` do not independently select an encoding. The package body does not check whether the handle's `datatype` matches the NCHAR or ordinary interface, so mixing them does not specifically raise `CHARSETMISMATCH`. Applications should nevertheless use the corresponding interfaces consistently. + +=== File Management + +[cols="5,7",options="header"] |=== -|Mode |Description |Notes -|`R` |Read text |The file must exist -|`W` |Write text, truncating |Creates the file if it does not exist, otherwise empties it -|`A` |Append text |Writes are added at the end of the file; a missing file is created, which matches Oracle's note that append mode creates the file in write mode +|Interface |Description +|`FCOPY(location, filename, dest_dir, dest_file, start_line DEFAULT 1, end_line DEFAULT 2147483647)` +|Copies text lines. Line numbers are `INTEGER`, start at 1, and include both endpoints. Omitted or explicitly `NULL` arguments use their respective defaults; nonpositive values raise an error. The destination is opened for writing, truncating any existing contents. +|`FREMOVE(location, filename)` +|Deletes the specified file using `unlink()`. Deleting a nonexistent file raises an error. +|`FRENAME(src_location, src_filename, dest_location, dest_filename, overwrite DEFAULT FALSE)` +|Renames or moves a file using `rename()`. `overwrite` is a `BOOLEAN`; an omitted or `NULL` value is treated as `FALSE`, in which case an existing destination raises `WRITE_ERROR`. `TRUE` permits replacing an existing destination, subject to operating system rules. +|`FGETATTR(location, filename, fexists OUT BOOLEAN, file_length OUT NUMBER, block_size OUT INTEGER)` +|Retrieves attributes using `stat()`. `file_length` is measured in bytes, and `block_size` is the `st_blksize` value returned by the system. Do not assume a fixed block size of 4096. |=== -The mode is case-insensitive (`'r'`, `'w'`, `'a'` are accepted); any other value raises `INVALID_MODE`. Oracle additionally supports the byte modes `rb`, `wb`, and `ab`; these are not yet supported by IvorySQL. +`FCOPY` recognizes LF as the line separator, preserves the copied text, and performs no character set conversion. It is not suitable for copying binary data containing NUL bytes. If `start_line` exceeds the number of lines in the file or is greater than `end_line`, the destination is still created or truncated, and the result is empty. Do not use the same file as both source and destination. Before copying a source that is still being written, flush or close its write handle. + +Once the directory registration check passes, `FGETATTR` returns `FALSE, NULL, NULL` if `stat()` fails. This can mean either that the file does not exist or that its attributes cannot be retrieved because of permissions or another cause. Therefore, `fexists = FALSE` alone does not prove that the file is absent. Failure of the directory check still raises `INVALID_PATH`. + +== Runnable Examples + +=== Preparing the Example Directory and Connection + +Run the following examples in the order shown. On the server, create a separate directory as the operating system user running the database, then connect as a database user with write permission on the directory registration table. Port `1521` below is the Oracle compatibility port of the instance used for verification; adjust the port, database name, and user for other environments. -=== Operational notes +[source,bash] +---- +mkdir -p /tmp/ivorysql_utl_file_demo +/home/highgo/6.0/inst/bin/psql -X -h 127.0.0.1 -p 1521 -U highgo -d postgres +---- + +Run the subsequent code in this `psql` session. Use `/` on a line by itself to terminate a PL/iSQL anonymous block. When connecting through the PostgreSQL compatibility port, setting only the server's `ivorysql.compatible_mode` does not ensure that the client correctly splits anonymous blocks; the `psql` parser must also be synchronized. These examples connect directly through the Oracle compatibility port. + +[source,sql] +---- +\set ON_ERROR_STOP on +SET client_min_messages = notice; +SET standard_conforming_strings = on; +SHOW ivorysql.compatible_mode; +SHOW server_encoding; +SHOW utl_file.umask; -The following rules are inherited from Oracle's *Operational Notes* and *Rules and Limits* for `UTL_FILE`: +INSERT INTO sys.utl_file_directory(dirname, dir) +VALUES ('utl_file_demo', '/tmp/ivorysql_utl_file_demo'); +---- -* **Bytes returned by GET_LINE** are the lesser of: the `GET_LINE` `len` parameter, the number of bytes until the next line terminator, and the `max_linesize` specified by `FOPEN`. The line terminator itself is not read into the buffer, so reading blank lines returns empty strings. -* **max_linesize** must be in the range 1–32767; if unspecified, a default value of 1024 is supplied. The `GET_LINE` `len` parameter follows the same range; when `max_linesize` and `len` differ, the lesser value takes precedence. -* **Character sets**: files opened by `FOPEN` are expected to be encoded in the database character set, files opened by `FOPEN_NCHAR` in UTF-8. Reading a file in an unexpected character set gives indeterminate results. -* **Sequential `PUT` output** should not exceed the line limit between flushes; exceeding `max_linesize` raises `VALUE_ERROR` ("buffer is too short"). -* **Open-file limit**: a session can have at most 50 files open simultaneously (same as Oracle). Beyond that, `FOPEN` fails with a "program limit exceeded" error. -* Operating system-specific parameters (e.g. environment variables) cannot be used in the file location or file name parameters. +The queried values in the verification environment were `oracle`, `UTF8`, and `0077`, respectively. If a registration with the same name already exists, check its purpose first to avoid changing a directory used by another application. -== Syntax Examples +Each functional example below creates and deletes its own files; the only shared prerequisite is the directory registration above. Expected output lists only `NOTICE` messages, omitting the `psql` line-number prefixes and command completion tags. -Writing and reading a file line by line: +=== Writing, Appending, Formatting, and Reading Text Line by Line [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; line TEXT; - i INTEGER; + n INTEGER := 0; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'W'); - + f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'W'); UTL_FILE.PUT_LINE(f, 'abc'); - UTL_FILE.PUT_LINE(f, '123'::numeric); UTL_FILE.NEW_LINE(f, 2); UTL_FILE.PUT(f, 'a'); UTL_FILE.PUT(f, 'b'); UTL_FILE.NEW_LINE(f); - UTL_FILE.PUTF(f, '[1=%s, 2=%s]', 'one', 'two'); - UTL_FILE.NEW_LINE(f); + UTL_FILE.PUTF(f, 'name=%s; ratio=100%%\n', 'IvorySQL'); UTL_FILE.FCLOSE(f); - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); - i := 1; - UTL_FILE.GET_LINE(f, line); - WHILE line IS NOT NULL LOOP - RAISE NOTICE '[%] >>%<<', i, line; - UTL_FILE.GET_LINE(f, line); - i := i + 1; - END LOOP; + f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'A'); + UTL_FILE.PUT_LINE(f, 'tail'); UTL_FILE.FCLOSE(f); - EXCEPTION - WHEN OTHERS THEN - RAISE NOTICE 'exception: %', sqlerrm; - UTL_FILE.FCLOSE_ALL(); + f := UTL_FILE.FOPEN('utl_file_demo', 'text.txt', 'R'); + LOOP + BEGIN + UTL_FILE.GET_LINE(f, line); + EXCEPTION WHEN NO_DATA_FOUND THEN + EXIT; + END; + n := n + 1; + RAISE NOTICE '[%] >>%<<', n, line; + END LOOP; + UTL_FILE.FCLOSE(f); + RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); + UTL_FILE.FREMOVE('utl_file_demo', 'text.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -Output: +The output includes two empty-line records: [source,text] ---- NOTICE: [1] >>abc<< -NOTICE: [2] >>123<< +NOTICE: [2] >><< NOTICE: [3] >><< NOTICE: [4] >>ab<< -NOTICE: [5] >>[1=one, 2=two]<< +NOTICE: [5] >>name=IvorySQL; ratio=100%<< +NOTICE: [6] >>tail<< +NOTICE: is_open = f ---- -The classic `PUTF` example from the Oracle documentation writes `Hello, world!\nI come from Zork with greetings for all earthlings.`: +=== Length Limits and the Newline Boundary + +This example writes two consecutive three-byte strings, demonstrating that write lengths are not accumulated across `PUT` calls. Although the read specifies `len = 32767`, the handle's `max_linesize = 3` still limits each read to three bytes. [source,sql] ---- DECLARE - my_world VARCHAR2 := 'Zork'; - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; + line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'zork.txt', 'W'); - UTL_FILE.PUTF(f, 'Hello, world!\nI come from %s with %s.\n', - my_world, - 'greetings for all earthlings'); + f := UTL_FILE.FOPEN('utl_file_demo', 'length.txt', 'W', 3); + UTL_FILE.PUT(f, 'abc'); + UTL_FILE.PUT(f, 'def'); + UTL_FILE.NEW_LINE(f); UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('utl_file_demo', 'length.txt', 'R', 3); + FOR i IN 1..3 LOOP + UTL_FILE.GET_LINE(f, line, 32767); + RAISE NOTICE '[%] text=[%], bytes=%, pos=%', + i, line, octet_length(line), UTL_FILE.FGETPOS(f); + END LOOP; + BEGIN + UTL_FILE.GET_LINE(f, line); + EXCEPTION WHEN NO_DATA_FOUND THEN + RAISE NOTICE 'EOF: SQLSTATE=%, SQLERRM=%', SQLSTATE, SQLERRM; + END; + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'length.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -File attributes, copy, remove, and rename: +Output on Linux: + +[source,text] +---- +NOTICE: [1] text=[abc], bytes=3, pos=3 +NOTICE: [2] text=[def], bytes=3, pos=6 +NOTICE: [3] text=[], bytes=0, pos=7 +NOTICE: EOF: SQLSTATE=P0002, SQLERRM=no data found +---- + +=== Flushing and Seeking with Absolute and Relative Offsets [source,sql] ---- DECLARE - fexists BOOLEAN; - file_length NUMBER; - block_size INTEGER; + writer UTL_FILE.FILE_TYPE; + reader UTL_FILE.FILE_TYPE; + line TEXT; + second_pos INTEGER; BEGIN - UTL_FILE.FCOPY('data_directory', 'regress.txt', 'data_directory', 'regress2.txt'); - UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); - RAISE NOTICE 'fexists = %, file_length = %, block_size = %', fexists, file_length, block_size; + writer := UTL_FILE.FOPEN('utl_file_demo', 'seek.txt', 'W'); + reader := UTL_FILE.FOPEN('utl_file_demo', 'seek.txt', 'R'); + UTL_FILE.PUT_LINE(writer, 'one'); + UTL_FILE.PUT_LINE(writer, 'two'); + UTL_FILE.FFLUSH(writer); + + UTL_FILE.FSEEK(reader, 0); + UTL_FILE.GET_LINE(reader, line); + second_pos := UTL_FILE.FGETPOS(reader); + RAISE NOTICE 'first=%, second_pos=%', line, second_pos; - UTL_FILE.FREMOVE('data_directory', 'regress2.txt'); - UTL_FILE.FGETATTR('data_directory', 'regress2.txt', fexists, file_length, block_size); - RAISE NOTICE 'fexists = %', fexists; + UTL_FILE.FSEEK(reader, second_pos); + UTL_FILE.GET_LINE(reader, line); + RAISE NOTICE 'absolute=%', line; - UTL_FILE.FRENAME('data_directory', 'regress.txt', 'data_directory', 'regress2.txt', TRUE); + UTL_FILE.FSEEK(reader, NULL, -4); + UTL_FILE.GET_LINE(reader, line); + RAISE NOTICE 'relative=%', line; + + UTL_FILE.FCLOSE_ALL(); + RAISE NOTICE 'writer_open=%, reader_open=%', + UTL_FILE.IS_OPEN(writer), UTL_FILE.IS_OPEN(reader); + UTL_FILE.FREMOVE('utl_file_demo', 'seek.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -Output: +Here, `-4` corresponds to the four bytes occupied by `two` followed by one LF on Linux. Applications should seek using the actual byte length of a record, not its character count. [source,text] ---- -NOTICE: fexists = t, file_length = 24, block_size = 4096 -NOTICE: fexists = f +NOTICE: first=one, second_pos=4 +NOTICE: absolute=two +NOTICE: relative=two +NOTICE: writer_open=f, reader_open=f ---- -The max_linesize/len precedence example from the Oracle documentation — `GET_LINE`'s `len` request exceeds `FOPEN`'s `max_linesize`, so the number of bytes returned is bounded by the smaller value: +=== Querying Attributes, Copying Lines, Renaming, and Deleting [source,sql] ---- DECLARE - v1 TEXT; - f1 sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; + ex BOOLEAN; + sz NUMBER; + bs INTEGER; BEGIN - -- MAX_LINESIZE (256) is less than GET_LINE's length request (32767), - -- so the number of bytes returned will be 256 or less if a line terminator is seen. - f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R', 256); - UTL_FILE.GET_LINE(f1, v1, 32767); - UTL_FILE.FCLOSE(f1); - - -- FOPEN's MAX_LINESIZE defaults to 1024, - -- so the number of bytes returned will be 1024 or less if a line terminator is seen. - f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); - UTL_FILE.GET_LINE(f1, v1, 32767); - UTL_FILE.FCLOSE(f1); - - -- GET_LINE doesn't specify a number of bytes, so it defaults to - -- FOPEN's MAX_LINESIZE, which in turn defaults to 1024. - f1 := UTL_FILE.FOPEN('data_directory', 'u12345.tmp', 'R'); - UTL_FILE.GET_LINE(f1, v1); - UTL_FILE.FCLOSE(f1); + f := UTL_FILE.FOPEN('utl_file_demo', 'source.txt', 'W'); + UTL_FILE.PUT_LINE(f, 'alpha'); + UTL_FILE.PUT_LINE(f, 'beta'); + UTL_FILE.PUT_LINE(f, 'gamma'); + UTL_FILE.FCLOSE(f); + + UTL_FILE.FCOPY('utl_file_demo', 'source.txt', + 'utl_file_demo', 'copy.txt', 2, 3); + UTL_FILE.FGETATTR('utl_file_demo', 'copy.txt', ex, sz, bs); + RAISE NOTICE 'copy: exists=%, bytes=%', ex, sz; + + UTL_FILE.FRENAME('utl_file_demo', 'copy.txt', + 'utl_file_demo', 'renamed.txt', TRUE); + UTL_FILE.FGETATTR('utl_file_demo', 'renamed.txt', ex, sz, bs); + RAISE NOTICE 'renamed: exists=%, bytes=%', ex, sz; + + UTL_FILE.FREMOVE('utl_file_demo', 'renamed.txt'); + UTL_FILE.FGETATTR('utl_file_demo', 'renamed.txt', ex, sz, bs); + RAISE NOTICE 'removed: exists=%, length_null=%, block_null=%', + ex, sz IS NULL, bs IS NULL; + UTL_FILE.FREMOVE('utl_file_demo', 'source.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -`FFLUSH`, `FSEEK`, and `FGETPOS` work together for write-then-reread scenarios: writes become visible to other handles only after `FFLUSH`, and `FSEEK` can jump to a saved offset: +On Linux, the copied content consists of the lines `beta` and `gamma`, each followed by LF, for a total of 11 bytes: + +[source,text] +---- +NOTICE: copy: exists=t, bytes=11 +NOTICE: renamed: exists=t, bytes=11 +NOTICE: removed: exists=f, length_null=t, block_null=t +---- + +=== Reading and Writing UTF8 Files [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; - f1 sys.ora_utl_file_file_type; - line TEXT; - line2_pos INTEGER; + f UTL_FILE.FILE_TYPE; + line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'W'); - f1 := UTL_FILE.FOPEN('data_directory', 'regressflush.txt', 'R'); - - FOR i IN 1..5 LOOP - UTL_FILE.PUT_LINE(f, 'line ' || i::text); - END LOOP; - - UTL_FILE.FFLUSH(f); -- make buffered writes visible - - UTL_FILE.FSEEK(f1); -- reset read position to 0 - UTL_FILE.GET_LINE(f1, line); - line2_pos := UTL_FILE.FGETPOS(f1); -- remember the offset of line 2 - - WHILE line IS NOT NULL LOOP - RAISE NOTICE '>>%<<', line; - UTL_FILE.GET_LINE(f1, line); - END LOOP; - - UTL_FILE.FSEEK(f1, line2_pos, NULL); -- jump back to line 2 (absolute) - UTL_FILE.GET_LINE(f1, line); - RAISE NOTICE '>>%<<', line; - - UTL_FILE.FSEEK(f1, NULL, -7); -- move back one record (relative) - UTL_FILE.GET_LINE(f1, line); - RAISE NOTICE '>>%<<', line; + f := UTL_FILE.FOPEN_NCHAR('utl_file_demo', 'utf8.txt', 'W'); + UTL_FILE.PUT_LINE_NCHAR(f, '你好,IvorySQL'); + UTL_FILE.FCLOSE(f); + f := UTL_FILE.FOPEN_NCHAR('utl_file_demo', 'utf8.txt', 'R'); + UTL_FILE.GET_LINE_NCHAR(f, line); + RAISE NOTICE 'text=%, bytes=%', line, octet_length(line); + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'utf8.txt'); +EXCEPTION WHEN OTHERS THEN UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -`FSEEK` makes it possible to read previous lines without first closing and reopening the file — you must know the number of bytes by which to navigate. If the beginning of the file is reached before the requested number of bytes, the file pointer is placed at the beginning of the file; if the end of the file is reached first, `INVALID_OFFSET` is raised. +Output in a UTF8 database: -== Exceptions - -`UTL_FILE` raises Oracle-style exceptions, which can be caught with `WHEN OTHERS` and inspected via `SQLERRM`. The exception set follows Oracle's *UTL_FILE Exceptions* table: - -[cols="3,5",options="header"] -|=== -|Exception |Description -|`INVALID_PATH` |File location is invalid -|`INVALID_MODE` |The `open_mode` parameter in `FOPEN` is invalid -|`INVALID_FILEHANDLE` |File handle is invalid -|`INVALID_OPERATION` |File could not be opened or operated on as requested, e.g. reading from a handle opened in `W`/`A` mode -|`READ_ERROR` |Destination buffer too small, or an operating system error occurred during the read operation -|`WRITE_ERROR` |An operating system error occurred during the write operation; also raised when `FRENAME` finds the destination file exists and `overwrite` is `FALSE` -|`INTERNAL_ERROR` |Unspecified PL/iSQL error -|`CHARSETMISMATCH` |A file is opened using `FOPEN_NCHAR`, but later I/O operations use nonchar functions such as `PUTF` or `GET_LINE` -|`FILE_OPEN` |The requested operation failed because the file is open -|`INVALID_MAXLINESIZE` |The `max_linesize` value for `FOPEN()` is invalid; it should be within the range 1 to 32767 -|`INVALID_FILENAME` |The `filename` parameter is invalid -|`ACCESS_DENIED` |Permission to access the file location is denied -|`INVALID_OFFSET` |`absolute_offset < 0`, or an offset causes a seek past the end of the file -|`DELETE_FAILED` |The requested file delete operation failed -|`RENAME_FAILED` |The requested file rename operation failed -|`NO_DATA_FOUND` |Predefined exception; see the note on end-of-file behavior below -|`VALUE_ERROR` |Predefined exception; raised when written data exceeds `max_linesize` -|=== +[source,text] +---- +NOTICE: text=你好,IvorySQL, bytes=17 +---- -Procedures in `UTL_FILE` can also raise other predefined PL/iSQL exceptions. +=== Writing BYTEA Data -End-of-file behavior: when `GET_LINE` reads past the end of the file, Oracle raises `NO_DATA_FOUND`. IvorySQL instead logs the condition at `LOG` level (`no data found`) and returns `NULL`, so the `WHILE line IS NOT NULL` loop pattern works naturally: +This example writes five bytes, `41 42 0a 43 44`, representing `AB`, LF, and `CD`, with no final newline. Since the content is valid text, it can be verified using `GET_LINE`; arbitrary binary content should not be read through a text interface. [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory', 'regress.txt', 'R'); + f := UTL_FILE.FOPEN('utl_file_demo', 'raw.dat', 'W'); + UTL_FILE.PUT_RAW(f, decode('41420a4344', 'hex'), TRUE); + UTL_FILE.FCLOSE(f); + + f := UTL_FILE.FOPEN('utl_file_demo', 'raw.dat', 'R'); + UTL_FILE.GET_LINE(f, line); + RAISE NOTICE 'first=%', line; UTL_FILE.GET_LINE(f, line); - WHILE line IS NOT NULL LOOP - RAISE NOTICE '>>%<<', line; + RAISE NOTICE 'last=%', line; + BEGIN UTL_FILE.GET_LINE(f, line); - END LOOP; + EXCEPTION WHEN NO_DATA_FOUND THEN + RAISE NOTICE 'EOF'; + END; UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'raw.dat'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- -Error handling example: +[source,text] +---- +NOTICE: first=AB +NOTICE: last=CD +NOTICE: EOF +---- + +=== Catching Invalid Seek Parameters + +`INVALID_OFFSET` is an error message, not an exception variable declared in the package. After catching an error with `WHEN OTHERS`, inspect `SQLSTATE` and `SQLERRM` and rethrow any unexpected error. [source,sql] ---- DECLARE - f sys.ora_utl_file_file_type; + f UTL_FILE.FILE_TYPE; BEGIN - -- 'wrong_directory' is not registered, raises INVALID_PATH - f := UTL_FILE.FOPEN('wrong_directory', 'regress.txt', 'A', 1024); + f := UTL_FILE.FOPEN('utl_file_demo', 'offset.txt', 'W'); + UTL_FILE.PUT(f, 'abc'); + UTL_FILE.FCLOSE(f); + f := UTL_FILE.FOPEN('utl_file_demo', 'offset.txt', 'R'); + BEGIN + UTL_FILE.FSEEK(f); + EXCEPTION WHEN OTHERS THEN + IF SQLSTATE <> 'P0001' OR SQLERRM <> 'INVALID_OFFSET' THEN + RAISE; + END IF; + RAISE NOTICE 'error=%, pos=%', SQLERRM, UTL_FILE.FGETPOS(f); + END; + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'offset.txt'); +EXCEPTION WHEN OTHERS THEN + UTL_FILE.FCLOSE_ALL(); + RAISE; END; / ---- [source,text] ---- -ERROR: INVALID_PATH -DETAIL: File location is invalid. -HINT: locality is not found in sys.utl_file_directory table +NOTICE: error=INVALID_OFFSET, pos=0 ---- -== Differences from Oracle +=== Commit, Rollback, and File Contents -The API is aligned with Oracle, with the following known differences: +Handles remain usable across transaction commits. When a top-level transaction rolls back or aborts because of an unhandled error, the resource cleanup callback closes all open files in the current session. A subtransaction rollback caused by catching an error in an inner exception block does not trigger this session-wide closure. A file cleanup callback is also registered for normal backend exit, but it must not be treated as a durability guarantee in the event of a process crash. -[cols="2,4",options="header"] -|=== -|Area |IvorySQL behavior -|Directory objects |Uses the `sys.utl_file_directory` table instead of Oracle's `CREATE DIRECTORY`/`ALL_DIRECTORIES`. A raw path under a registered directory is also accepted -|End of file |`GET_LINE` returns `NULL` at EOF; Oracle raises `NO_DATA_FOUND` -|Byte modes |`rb`/`wb`/`ab` open modes are not supported; `INVALID_MODE` is raised. The `byte_mode` field exists in the handle type for future use -|Missing subprograms |`GET_RAW`, `PUT_NCHAR`, `PUTF_NCHAR` are not yet implemented -|`FSEEK` with both offsets `NULL` |Resets the file position to 0; Oracle raises `INVALID_OFFSET` -|`PUTF` format strings |`%%` is supported as a literal `%` (an IvorySQL extension); unmatched `%s` formatters are replaced by an empty string, same as Oracle -|`FCLOSE_ALL` and `IS_OPEN` |After `FCLOSE_ALL`, `IS_OPEN` returns `FALSE` in IvorySQL; Oracle keeps reporting `TRUE` for the untouched handle -|Exception set |Exceptions not specifically detected by the implementation (`ACCESS_DENIED`, `DELETE_FAILED`, `RENAME_FAILED`, `FILE_OPEN`, `CHARSETMISMATCH`, `INVALID_FILENAME`, `INTERNAL_ERROR`) surface as the closest Oracle exception, typically `INVALID_PATH`/`INVALID_OPERATION`/`READ_ERROR`/`WRITE_ERROR` with the operating system error text as `DETAIL` -|File ownership |On UNIX, files created by `FOPEN` are owned by the user running the database server, as in Oracle; their permissions are masked by `utl_file.umask` -|=== +File operations do not participate in database transaction rollback. Closing a stream may submit previously buffered writes to the operating system, so `ROLLBACK` does not undo written content, restore truncated files, or reverse deletion and renaming. -== Transaction and session lifecycle - -File handles survive `COMMIT` but are automatically closed when the transaction rolls back or the session terminates, so buffered data is not silently lost: +Run the following anonymous block directly at the top level in a session with autocommit enabled. Do not wrap it in an explicit transaction or add an exception handler to the block that executes `COMMIT` and `ROLLBACK`. [source,sql] ---- +DECLARE + f UTL_FILE.FILE_TYPE; + line TEXT; BEGIN - f := UTL_FILE.FOPEN('data_directory','regress.txt','A',1024); - RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + f := UTL_FILE.FOPEN('utl_file_demo', 'transaction.txt', 'W'); + UTL_FILE.PUT_LINE(f, 'kept'); COMMIT; - RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- t + RAISE NOTICE 'after commit: open=%', UTL_FILE.IS_OPEN(f); ROLLBACK; - RAISE NOTICE 'is_open = %', UTL_FILE.IS_OPEN(f); -- f + RAISE NOTICE 'after rollback: open=%', UTL_FILE.IS_OPEN(f); + + f := UTL_FILE.FOPEN('utl_file_demo', 'transaction.txt', 'R'); + UTL_FILE.GET_LINE(f, line); + RAISE NOTICE 'content=%', line; + UTL_FILE.FCLOSE(f); + UTL_FILE.FREMOVE('utl_file_demo', 'transaction.txt'); END; / ---- -== Implementation notes +[source,text] +---- +NOTICE: after commit: open=t +NOTICE: after rollback: open=f +NOTICE: content=kept +---- + +=== Removing the Directory Registration + +After completing the examples, remove the registration created in this section. Each example has already deleted its own files. If execution was interrupted, close the files first, then inspect the separate example directory for any remaining files. + +[source,sql] +---- +DELETE FROM sys.utl_file_directory +WHERE dirname = 'utl_file_demo' + AND dir = '/tmp/ivorysql_utl_file_demo'; +---- + +Once the directory is empty, remove it on the server: + +[source,bash] +---- +rmdir /tmp/ivorysql_utl_file_demo +---- + +== Errors and Compatibility Boundaries + +The current C implementation uses the following error messages. Except for `NO_DATA_FOUND`, the uppercase names in this table are reported using the generic `raise_exception` SQLSTATE `P0001`; they do not imply that the package declares an exception with the same name. + +[cols="3,2,7",options="header"] +|=== +|Error Message or Condition |SQLSTATE |Typical Cause +|`INVALID_PATH` |`P0001` |The full path is outside the registered directories, or the operating system reports a missing file, denied access, a path component that is not a directory, or a similar error. +|`INVALID_MODE` |`P0001` |The open mode is not an allowed single-character mode, for example `rb`. +|`INVALID_MAXLINESIZE` |`P0001` |`max_linesize` or a non-null `GET_LINE.len` is outside the range 1–32767. +|`INVALID_FILEHANDLE` |`P0001` |The handle has no valid slot in the current session, for example when reading after closing it. +|`INVALID_OPERATION` |`P0001` |Reading from a write-only handle, writing to a read-only handle, or another operating system failure not mapped to a path error. +|`INVALID_OFFSET` |`P0001` |Both seek offsets are null, or the target offset is outside the valid range. +|`READ_ERROR` |`P0001` |An underlying read failure not mapped to `INVALID_OPERATION`; this should not simply be interpreted as a text line exceeding the length limit. +|`WRITE_ERROR` |`P0001` |An underlying write, flush, or close failure; or a rename destination that already exists when overwriting is disabled. +|`VALUE_ERROR` |`P0001` |A single text write subject to length checking exceeds its byte budget, with the detail `buffer is too short`. Do not assume that the predefined `WHEN VALUE_ERROR` handler catches it. +|`NO_DATA_FOUND` / `no data found` |`P0002` |A read obtains no characters because of EOF. This can be caught with `WHEN NO_DATA_FOUND`. +|`null value not allowed` |`22004` |A required argument is `NULL`, such as an explicitly null `max_linesize` or write buffer. +|`program limit exceeded` |`54000` |An attempt to obtain a 51st simultaneously open file handle. +|=== + +Other possible errors include `22023` parameter errors, such as nonpositive line numbers in `FCOPY`, character set conversion or validation errors, and database object permission errors. When diagnosing a failure, examine `SQLSTATE`, `SQLERRM`, and the `DETAIL` returned by the server together. + +The current package does not declare dedicated exceptions such as `ACCESS_DENIED`, `DELETE_FAILED`, `RENAME_FAILED`, `FILE_OPEN`, `CHARSETMISMATCH`, `INVALID_FILENAME`, and `INTERNAL_ERROR`, which appear in Oracle documentation. They must not be listed as implemented package exceptions. Deletion and renaming failures are generally mapped to `INVALID_PATH` or `INVALID_OPERATION` according to the underlying error. + +Public subprograms not yet provided include `GET_RAW`, `PUT_NCHAR`, and `PUTF_NCHAR`. Byte open modes are also unavailable. When migrating code, pay particular attention to directory authorization, per-call versus cumulative lengths, mixing NCHAR and ordinary interfaces, handle state after closing, and the fact that file operations are not undone by transaction rollback. + +== Verification Basis + +Verification was performed on 2026-12-03. The instance reported its version as `PostgreSQL 19.0 (IvorySQL 6.0)`, and the installed `ivorysql_ora` extension version was `1.1`. All executable SQL examples above were extracted from the document and run through the instance's Oracle compatibility port with `ON_ERROR_STOP` enabled, and the listed output was checked. + +The corresponding source files are: + +* `contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file--1.0.sql`: package types, public signatures, defaults, wrapper procedures, and initial directory table permissions. +* `contrib/ivorysql_ora/src/builtin_packages/utl_file/utl_file.c`: path checks, file slots, input and output, positioning, error mapping, and resource cleanup. +* `contrib/ivorysql_ora/src/ivorysql_ora.c`: registration of the `utl_file.umask` setting. +* `contrib/ivorysql_ora/sql/utl_file.sql` and `contrib/ivorysql_ora/sql/utl_file_putf.sql`: existing regression cases used as verification references; the examples in this document were also run separately against the running instance. -For the security model, handle management, and internal design, see xref:v6.0/compatibility_features_design/utl_file_impl.adoc[UTL_FILE implementation design]. +Additional checks covered subdirectory access; rejection of sibling directories and paths outside registered directories; EOF on an empty file; invalid modes; explicit `NULL` arguments; lower and upper length limits; truncated multibyte characters; mixing ordinary and NCHAR interfaces; seek boundaries; misuse of read-only and write-only handles; repeated closing; the 50-handle limit; and the length behavior of `PUT_RAW`. diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc index 3e5ad534..be935c5f 100644 --- a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc +++ b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/with_function_procedure.adoc @@ -186,11 +186,35 @@ SELECT safe_div(1, 0) FROM dual; [source,sql] ---- -- Allowed: INSERT INTO ... WITH FUNCTION ... SELECT ... (Oracle-compatible form) +-- Create data table +CREATE TABLE emp ( + empno NUMBER(4) PRIMARY KEY, + sal NUMBER(10, 2), + deptno NUMBER(2) +); + +CREATE TABLE emp_bonus ( + empno NUMBER(4) PRIMARY KEY, + bonus NUMBER(12, 2) +); + +-- Insert test data +INSERT INTO emp (empno, sal, deptno) VALUES (1001, 5000, 10); +INSERT INTO emp (empno, sal, deptno) VALUES (1002, 8000, 10); +INSERT INTO emp (empno, sal, deptno) VALUES (1003, 6000, 20); + +COMMIT; + WITH FUNCTION get_bonus(sal NUMBER) RETURN NUMBER AS BEGIN RETURN sal * 1.2; END; INSERT INTO emp_bonus (empno, bonus) SELECT empno, get_bonus(sal) FROM emp WHERE deptno = 10; + +-- Verify result +SELECT empno, bonus FROM emp_bonus ORDER BY empno; + +-- Expect 1001 6000 | 1002 9600 ---- NOTE: Oracle does not allow WITH FUNCTION to precede UPDATE, DELETE, or MERGE. From fb20ab474b6637f58067c26fa12e3716f627fedc Mon Sep 17 00:00:00 2001 From: Steven Niu Date: Thu, 3 Dec 2026 16:16:00 +0800 Subject: [PATCH 3/5] fix the wrong desciption in lnnvl_function --- .../pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc | 2 +- .../pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc index 88a815ba..8ac61686 100644 --- a/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc +++ b/CN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc @@ -99,7 +99,7 @@ SELECT count(*) FROM lnnvl_test; -- 期望:5 -- 2 + 3 = 5,条件与其 LNNVL 覆盖全表,无行丢失 -- 若改用 NOT,两者之和会小于总行数 -SELECT count(*) FROM lnnvl_test WHERE NOT (v >= 0.2); -- 期望:2,合计仅 4 +SELECT count(*) FROM lnnvl_test WHERE NOT (v >= 0.2); -- 期望:1 ---- === NOT IN 遇含 NULL 的子查询 diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc index e762a337..297c10af 100644 --- a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc +++ b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_lnnvl_function.adoc @@ -102,7 +102,7 @@ SELECT count(*) FROM lnnvl_test; -- expected: 5 -- 2 + 3 = 5: the condition and its LNNVL cover the whole table, no row is lost -- With NOT, the two counts add up to less than the total -SELECT count(*) FROM lnnvl_test WHERE NOT (v >= 0.2); -- expected: 2, total only 4 +SELECT count(*) FROM lnnvl_test WHERE NOT (v >= 0.2); -- expected: 1 ---- === NOT IN over a Subquery Containing NULL From c0ab900ac96d591247b41340c91df2a9212df951 Mon Sep 17 00:00:00 2001 From: Steven Niu Date: Thu, 3 Dec 2026 16:41:19 +0800 Subject: [PATCH 4/5] bypass the conflict --- ...e_type_as_object.adoc => compat_create_type_as_object_en.adoc} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{compat_create_type_as_object.adoc => compat_create_type_as_object_en.adoc} (100%) diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc From 21bfe3c96c0f69c61ff25c916ba02c9a2984b1cd Mon Sep 17 00:00:00 2001 From: Steven Niu Date: Thu, 3 Dec 2026 16:54:29 +0800 Subject: [PATCH 5/5] remove the en postfix from compat_create_type_as_object_en.adoc --- ...e_type_as_object_en.adoc => compat_create_type_as_object.adoc} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename EN/modules/ROOT/pages/v6.0/oracle_compatibility/{compat_create_type_as_object_en.adoc => compat_create_type_as_object.adoc} (100%) diff --git a/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc b/EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object.adoc similarity index 100% rename from EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object_en.adoc rename to EN/modules/ROOT/pages/v6.0/oracle_compatibility/compat_create_type_as_object.adoc