LENGTHC Implementation
1. Purpose
ivorysql_ora provides Oracle-compatible LENGTHC to count Unicode code points after NFC normalization in UTF8 databases. For examples, see LENGTHC Function.
2. Implementation
2.1. 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 withpg_mbstrlen_with_len(). -
For ASCII-only
UTF8input, return the byte count. For otherUTF8input, count code points, check the allocation limit, and decode into achar32_tarray. -
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.
2.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.
| Input | SQL overload argument types | Implementation |
|---|---|---|
Character |
|
Character overloads bound to |
Numeric |
|
Count the characters of the converted numeric text. |
Datetime |
|
Text formatting depends on session NLS settings, so these overloads are |
Binary |
|
Separate overloads avoid ambiguity with |
Large objects |
|
Call |
3. Related Files and Tests
Paths are relative to contrib/ivorysql_ora/.
| File | Role |
|---|---|
|
Character counting, NFC normalization, and large-object type errors. |
|
SQL overloads, type conversions, and volatility declarations. |
|
Regression coverage for normalization, padding, null handling, type conversion, large-object rejection, and expression indexes. The counting cases also compare against |