Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
:sectnums:
:sectnumlevels: 5

= 字符长度函数实现说明

== 目的

`ivorysql_ora` 提供 Oracle 兼容的 `LENGTHC`,在 `UTF8` 下统计 Unicode NFC 规范化后的码点数。调用示例见 xref:master/oracle_compatibility/compat_lengthc_function.adoc[字符长度函数]。

== 实现说明

=== 字符输入与编码路径

`sys.lengthc(text)` 和 Oracle 兼容的 `CHAR`、`VARCHAR2` 字节及字符长度重载都直接调用 `ora_lengthc()`。C 函数读取字符串的变长数据,保留定长类型的尾随空格。先转为 `text` 会丢掉 `CHAR` 的补齐空格,因此这些重载直接处理原值。

核心入口是 `contrib/ivorysql_ora/src/builtin_functions/character_datatype_functions.c` 中的 `ora_lengthc(PG_FUNCTION_ARGS)`。UTF8 路径复用 PostgreSQL 的 `src/common/unicode_norm.c`,按 Unicode NFC 规则进行规范分解、排序和组合,再统计结果码点。非 UTF8 路径直接按数据库编码计数。

. 单字节数据库编码直接返回字节数。
. 多字节的非 `UTF8` 编码调用 `pg_mbstrlen_with_len()` 统计字符。
. `UTF8` 的纯 ASCII 输入直接返回字节数。对其他 `UTF8` 输入,先统计码点并检查分配上限,再解码为 `char32_t` 数组。
. 调用 `unicode_is_normalized_quickcheck(UNICODE_NFC, ...)`。已确定为 NFC 时直接返回原码点数。
. 其余情况调用 `unicode_normalize(UNICODE_NFC, ...)`,返回规范化后的码点数。

NFC 也可能增加码点数。例如 `U+0958` 规范化后为 `U+0915` 和 `U+093C`,此时 `LENGTHC` 返回 2。

=== 重载、类型转换与索引

安装脚本声明了 18 个精确重载,其中 15 个参与计数,3 个用于拒绝大对象。对于支持的非字符串类型,SQL 重载先将输入显式转为 `sys.oravarcharchar`,再复用字符计数入口。

[cols="1,3,3", options="header"]
|===
|输入 |SQL 重载参数类型 |实现

|字符
|`text`、`sys.oracharchar`、`sys.oracharbyte`、`sys.oravarcharchar`、`sys.oravarcharbyte`
|直接绑定 `ora_lengthc()` 的字符重载声明为 `STRICT`、`IMMUTABLE` 和 `PARALLEL SAFE`,支持字符列上的表达式索引。`LONG` 通过其基础类型 `text` 查找重载。

|数值
|`integer`(`int4`)、`numeric`、`sys.number`、`sys.binary_double`
|按数值转换后的文本计数。

|日期时间
|`sys.oradate`、`sys.oratimestamp`、`sys.oratimestamptz`
|文本格式取决于会话的 NLS 设置,因此这些重载声明为 `STABLE`。表达式索引会拒绝这些重载。

|二进制
|`bytea`、`sys.raw`、`sys.long_raw`
|单独声明重载以免与 `BLOB` 产生歧义。按 `bytea_output` 转成文本后计数。

|大对象
|`sys.clob`、`sys.nclob`、`sys.blob`
|精确匹配时调用 `ora_lengthc_unsupported()` 报类型错误。传入这些类型的 `NULL` 同样报错。
|===

== 相关文件与验证

以下路径相对于 `contrib/ivorysql_ora/`。

[cols="2,3", options="header"]
|===
|文件 |职责

|`src/builtin_functions/character_datatype_functions.c`
|字符计数、NFC 规范化和大对象类型错误。

|`src/builtin_functions/builtin_functions--1.0.sql`
|SQL 重载、类型转换和易变性声明。

|`sql/ora_character_datatype_functions.sql`、`expected/ora_character_datatype_functions.out`
|覆盖规范化、补齐空格、空值、类型转换、大对象拒绝和表达式索引。字符计数用例还与 `length(normalize(value, 'NFC'))` 的结果比对。
|===
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
:sectnums:
:sectnumlevels: 5
:note-caption: 注意

= 字符长度函数

== 目的

`LENGTHC` 是 Oracle 字符串长度函数之一,计数单位是 Unicode 完整字符。IvorySQL 在 `UTF8` 数据库中统计 NFC 规范化后的码点数,因此同一个字符的预组合形式和规范等价的分解形式计数相同。

== 功能说明

需要按规范化后的字符数比较文本长度时,可以使用 `LENGTHC`。例如,同一个带重音的字母可能由一个码点表示,也可能由字母与组合重音两个码点表示。

`LENGTHC` 由 `ivorysql_ora` 扩展提供。以下示例通过 Oracle 兼容端口(默认 1521)连接 `UTF8` 数据库。

=== 接口

`LENGTHC(value)` 返回 `integer`,也可以写成 `sys.lengthc(value)`。

这是一个 SQL 函数。参数可以是字面量、表字段、函数返回值或返回单值的标量子查询。表达式的类型需要直接匹配可用重载,或通过已有类型转换匹配。

字符输入为 `NULL` 时返回 `NULL`。空字符串在默认的 `ivorysql.enable_emptystring_to_NULL = on` 下返回 `NULL`,设为 `off` 时返回 0。`CHAR` 补齐的尾随空格也计入长度。

=== Oracle 长度函数的计数单位

[cols="1,3", options="header"]
|===
|函数 |计数单位

|`LENGTH` |输入字符集中的字符
|`LENGTHB` |字节
|`LENGTHC` |Unicode 完整字符
|`LENGTH2` |UCS-2 代码单元
|`LENGTH4` |UCS-4 代码单元
|===

IvorySQL 在 `UTF8` 数据库中按 NFC 规范化后的码点计数。在其他数据库编码下,`LENGTHC` 仍可使用,按该编码直接统计字符数。

=== 兼容范围

IvorySQL 支持 `CHAR`、`NCHAR`、`VARCHAR2` 和 `text` 等字符输入。Oracle 还在文档中列出 `NVARCHAR2`,当前 IvorySQL 不识别该类型名。直接传入 `CLOB`、`NCLOB` 或 `BLOB` 会报类型错误,即使值为这些类型的 `NULL`。 https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/LENGTH.html[Oracle LENGTH 系列函数参考]

数值、日期时间以及 `RAW`、`bytea` 等输入会先转成文本再计数。日期时间结果取决于会话格式。二进制值在默认十六进制格式下会将 `\x` 前缀计入长度。

== 使用示例

=== 比较字符数、字节数和规范化后的长度

[source,sql]
----
SELECT sample_name,
pg_catalog.encode(pg_catalog.convert_to(sample_text, 'UTF8'), 'hex') AS utf8_hex,
LENGTH(sample_text) AS char_count,
LENGTHB(sample_text) AS byte_count,
LENGTHC(sample_text) AS normalized_count
FROM (VALUES (1, 'precomposed', CHR(233)),
(2, 'decomposed', 'e' || CHR(769)),
(3, 'q_with_accent', 'q' || CHR(769))) samples(sample_no, sample_name, sample_text)
ORDER BY sample_no;
----

[listing]
----
sample_name | utf8_hex | char_count | byte_count | normalized_count
---------------+----------+------------+------------+------------------
precomposed | c3a9 | 1 | 2 | 1
decomposed | 65cc81 | 2 | 3 | 1
q_with_accent | 71cc81 | 2 | 3 | 2
(3 rows)
----

预组合的 `é` 使用一个码点 `U+00E9`。分解形式使用 `e`(`U+0065`)和组合尖音符(`U+0301`)。NFC 将这两种形式规范为同一个码点。 https://www.unicode.org/reports/tr15/[Unicode 规范化形式]

[NOTE]
====
NFC 只会合并 Unicode 规定可组合的码点。`q` 加组合尖音符在 NFC 后仍是两个码点,即使显示时看起来像一个字符。
====

=== 统计定长字符值

[source,sql]
----
SELECT LENGTHC(CAST('ab' AS CHAR(5 CHAR))) AS fixed_length,
LENGTHC(CAST('ab' AS VARCHAR2(5 CHAR))) AS variable_length
FROM dual;
----

[listing]
----
fixed_length | variable_length
--------------+-----------------
5 | 2
(1 row)
----

`fixed_length` 为 5,包含 3 个补齐空格。`variable_length` 为 2。
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
:sectnums:
:sectnumlevels: 5

= LENGTHC Implementation

== Purpose

`ivorysql_ora` provides Oracle-compatible `LENGTHC` to count Unicode code points after NFC normalization in `UTF8` databases. For examples, see xref:master/oracle_compatibility/compat_lengthc_function.adoc[LENGTHC Function].

== Implementation

=== Character Inputs and Encoding Paths

`sys.lengthc(text)` and the byte- and character-length variants of Oracle-compatible `CHAR` and `VARCHAR2` call `ora_lengthc()` directly. The C function reads the variable-length string data and preserves fixed-length padding. Casting a `CHAR` value to `text` would trim that padding, so these overloads operate on the original value.

The entry point is `ora_lengthc(PG_FUNCTION_ARGS)` in `contrib/ivorysql_ora/src/builtin_functions/character_datatype_functions.c`. For UTF8 input it uses PostgreSQL's `src/common/unicode_norm.c` to apply Unicode NFC rules for canonical decomposition, ordering, and composition. Other database encodings use direct character counting.

. For single-byte database encodings, return the byte count.
. For multibyte encodings other than `UTF8`, count characters with `pg_mbstrlen_with_len()`.
. For ASCII-only `UTF8` input, return the byte count. For other `UTF8` input, count code points, check the allocation limit, and decode into a `char32_t` array.
. Call `unicode_is_normalized_quickcheck(UNICODE_NFC, ...)` and return the existing count when the check confirms NFC.
. Otherwise, call `unicode_normalize(UNICODE_NFC, ...)` and return the normalized code point count.

NFC can also increase the code point count. For example, `U+0958` normalizes to `U+0915` followed by `U+093C`, so `LENGTHC` returns 2.

=== Overloads, Type Conversion, and Indexes

The installation script declares 18 exact overloads. Fifteen count characters and three reject large-object types. For supported non-string inputs, the SQL overloads explicitly cast the value to `sys.oravarcharchar` before calling the character-counting function.

[cols="1,3,3", options="header"]
|===
|Input |SQL overload argument types |Implementation

|Character
|`text`, `sys.oracharchar`, `sys.oracharbyte`, `sys.oravarcharchar`, `sys.oravarcharbyte`
|Character overloads bound to `ora_lengthc()` are `STRICT`, `IMMUTABLE`, and `PARALLEL SAFE`. They support expression indexes on character columns. `LONG` resolves through its base type, `text`.

|Numeric
|`integer` (`int4`), `numeric`, `sys.number`, `sys.binary_double`
|Count the characters of the converted numeric text.

|Datetime
|`sys.oradate`, `sys.oratimestamp`, `sys.oratimestamptz`
|Text formatting depends on session NLS settings, so these overloads are `STABLE`. Expression indexes reject them.

|Binary
|`bytea`, `sys.raw`, `sys.long_raw`
|Separate overloads avoid ambiguity with `BLOB`. The count uses the text generated with `bytea_output`.

|Large objects
|`sys.clob`, `sys.nclob`, `sys.blob`
|Call `ora_lengthc_unsupported()` to raise a type error on an exact match, including a `NULL` of one of these types.
|===

== Related Files and Tests

Paths are relative to `contrib/ivorysql_ora/`.

[cols="2,3", options="header"]
|===
|File |Role

|`src/builtin_functions/character_datatype_functions.c`
|Character counting, NFC normalization, and large-object type errors.

|`src/builtin_functions/builtin_functions--1.0.sql`
|SQL overloads, type conversions, and volatility declarations.

|`sql/ora_character_datatype_functions.sql`, `expected/ora_character_datatype_functions.out`
|Regression coverage for normalization, padding, null handling, type conversion, large-object rejection, and expression indexes. The counting cases also compare against `length(normalize(value, 'NFC'))`.
|===
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
:sectnums:
:sectnumlevels: 5

= LENGTHC Function

== Purpose

`LENGTHC` is an Oracle string-length function that counts Unicode complete characters. In a `UTF8` database, IvorySQL counts code points after NFC normalization, so a precomposed character and its canonically equivalent decomposed form have the same length.

== Functionality

Use `LENGTHC` to compare text lengths after normalization. An accented letter, for example, can be represented by one code point or by a letter followed by a combining accent.

The `ivorysql_ora` extension provides `LENGTHC`. The examples connect to a `UTF8` database through the Oracle compatibility port, which defaults to 1521.

=== Interface

`LENGTHC(value)` returns an `integer`. You can also call it as `sys.lengthc(value)`.

The argument can be a SQL expression such as a literal, table column, function result, or scalar subquery. Its type must match a supported overload directly or through an available type conversion.

A character input of `NULL` returns `NULL`. An empty string returns `NULL` with the default `ivorysql.enable_emptystring_to_NULL = on`, or zero with `off`. Trailing padding spaces in `CHAR` values count toward the length.

=== Counting Units in Oracle Length Functions

[cols="1,3", options="header"]
|===
|Function |Unit

|`LENGTH` |Characters in the input character set
|`LENGTHB` |Bytes
|`LENGTHC` |Unicode complete characters
|`LENGTH2` |UCS-2 code units
|`LENGTH4` |UCS-4 code units
|===

IvorySQL counts code points after NFC normalization in `UTF8` databases. In other database encodings, `LENGTHC` remains available and counts characters directly in that encoding.

=== Oracle Compatibility Scope

IvorySQL accepts character inputs such as `CHAR`, `NCHAR`, `VARCHAR2`, and `text`. Oracle also lists `NVARCHAR2`, a type name that IvorySQL currently does not recognize. Direct `CLOB`, `NCLOB`, and `BLOB` inputs raise a type error, including `NULL` of those types. https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/LENGTH.html[Oracle LENGTH Function Reference]

Numeric and datetime values and binary inputs such as `RAW` and `bytea` are converted to text before counting. Datetime results depend on the session format. For binary inputs, the default hexadecimal format includes the `\x` prefix in the count.

== Examples

=== Compare Character, Byte, and Normalized Lengths

[source,sql]
----
SELECT sample_name,
pg_catalog.encode(pg_catalog.convert_to(sample_text, 'UTF8'), 'hex') AS utf8_hex,
LENGTH(sample_text) AS char_count,
LENGTHB(sample_text) AS byte_count,
LENGTHC(sample_text) AS normalized_count
FROM (VALUES (1, 'precomposed', CHR(233)),
(2, 'decomposed', 'e' || CHR(769)),
(3, 'q_with_accent', 'q' || CHR(769))) samples(sample_no, sample_name, sample_text)
ORDER BY sample_no;
----

[listing]
----
sample_name | utf8_hex | char_count | byte_count | normalized_count
---------------+----------+------------+------------+------------------
precomposed | c3a9 | 1 | 2 | 1
decomposed | 65cc81 | 2 | 3 | 1
q_with_accent | 71cc81 | 2 | 3 | 2
(3 rows)
----

Precomposed `é` uses one code point, `U+00E9`. The decomposed form uses `e` (`U+0065`) and a combining acute accent (`U+0301`). NFC normalizes both forms to the same code point. https://www.unicode.org/reports/tr15/[Unicode Normalization Forms]

[NOTE]
====
NFC applies the composition rules defined by Unicode. A `q` with a combining acute accent remains two code points after normalization, even when it looks like one character.
====

=== Count a Fixed-Length Character Value

[source,sql]
----
SELECT LENGTHC(CAST('ab' AS CHAR(5 CHAR))) AS fixed_length,
LENGTHC(CAST('ab' AS VARCHAR2(5 CHAR))) AS variable_length
FROM dual;
----

[listing]
----
fixed_length | variable_length
--------------+-----------------
5 | 2
(1 row)
----

`fixed_length` is 5, including three padding spaces. `variable_length` is 2.
Loading