Подскажите, плз, как настроить сабж. (какие environments etc.)
То есть стоит задача хранить информацию введенную в любой кодировке (данные
вводятся с пользователями www), ессно данные необходимо сортировать и т.п.
Как я понимаю подобное решается использованием unicode.
В Informix Guide to GLS об этом ни слова (или я чего проглядел), кроме фразы
в глоссарии "Informix supports UNICODE..."
Используются IDS 7.30 UC5 for Solaris 2.6 SPARC + IfxJDBC driver 1.22
Заранее спасибо.
--
Regards,
Dmitry Krivosheyenko
E-mail: uli...@ukraina.net
ICQ UIN:17396761
Вообще то достаточно двух переменных.
DB_LOCALE нужна при создании базы (и на клиенте указывает кодировку в базе.)
CLIENT_LOCALE нужна, чтобы указать , в какой кодировке получать из базы.
Если клиенты разные, то нужно чтобы были соответствующие таблицы перекодировки (но для всех поставляемых основных
локалей они есть - должны быть :)
Можно вообще работать без локалей (по умолчанию американская).
>То есть стоит задача хранить информацию введенную в любой кодировке (данные
>вводятся с пользователями www), ессно данные необходимо сортировать и т.п.
Храниться то они будут, но сортировки будут возможны только в кодовой последовательности, а не в локализованной.
И использовать для этого NCHAR и NVARCHAR не нужно.
>Как я понимаю подобное решается использованием unicode.
>В Informix Guide to GLS об этом ни слова (или я чего проглядел), кроме фразы
>в глоссарии "Informix supports UNICODE..."
Если я правильно понимаю, имеется в виду возможность поддержки кодовых таблиц больше 256 символов.
А это возможно с GLS, даже мультибайтные кодировки (китайские иероглифы :).
Василий.
Все классно, но только какое значение необходимо поставить в DB_LOCALE для
_UNICODE_
>>То есть стоит задача хранить информацию введенную в любой кодировке
(данные
>>вводятся с пользователями www), ессно данные необходимо сортировать и т.п.
>
>Храниться то они будут, но сортировки будут возможны только в кодовой
последовательности, а не в локализованной.
>И использовать для этого NCHAR и NVARCHAR не нужно.
>
>>Как я понимаю подобное решается использованием unicode.
>>В Informix Guide to GLS об этом ни слова (или я чего проглядел), кроме
фразы
>>в глоссарии "Informix supports UNICODE..."
>
>Если я правильно понимаю, имеется в виду возможность поддержки кодовых
таблиц больше 256 символов.
>А это возможно с GLS, даже мультибайтные кодировки (китайские иероглифы :).
Да, когда у ты китаец, ты с чувством гордости за свою страну и Ifx выбираешь
соответствующую китайскую локаль и все ok.
HO стоит задача хранения в одной базе данных в _ЛЮБОЙ_ кодировке (и ru1251 и
en819 и китайские иероглифы, и всякую другую чушь).
В настоящее время для этого принято использовать unicode character sets (ISO
10646).
То есть в теории при создании базы надо указать DB_LOCALE= ?unicode? (как?)
В $INFORMIXDIR/gls/cv3/registry codeset-name 'unicode' присутствует
(codeset-number 57349).
То есть в теории где-то должны быть файлы локали: e005.* Их у меня нет ни на
NT, ни на Solaris
В %INFORMIXDIR%\gls\lc11\en_us\0333dict.lc (NT) в дескрипшине говорится "GLS
locale for 8859-1, Unicode or UTF8"
Так ISO8859-1 или Unicode (ISO10646)?
Есть идеи?
>
>Василий.
Боюсь, что это в прямом виде невозможно. Т.е. хранить то их можно, но все символы с кодом 248 (например) будут
равнозначны и при сортировке будут собраны в одно место. Может быть, можно "вручную" сохранять в базе инф-ю о кодовой
таблице и при выдаче производить правильную перекодировку.
А что, нельзя сразу же перекодировать при записи в базу в единую кодировку ? Ведь клиент при коннекте должен указать
свою кодовую таблицу (или определить это за него, если доступ через броузер и WWW-сервер).
>В настоящее время для этого принято использовать unicode character sets (ISO
>10646).
>То есть в теории при создании базы надо указать DB_LOCALE= ?unicode? (как?)
>В $INFORMIXDIR/gls/cv3/registry codeset-name 'unicode' присутствует
>(codeset-number 57349).
>То есть в теории где-то должны быть файлы локали: e005.* Их у меня нет ни на
>NT, ни на Solaris
>В %INFORMIXDIR%\gls\lc11\en_us\0333dict.lc (NT) в дескрипшине говорится "GLS
>locale for 8859-1, Unicode or UTF8"
>Так ISO8859-1 или Unicode (ISO10646)?
Локаль ведь специфицирует не только кодовый набор, в котором определено соответствие символов их двоичному
представлению, но и еще много вещей - формат даты, времени, преобразования и т.д. Ну как ты себе представляешь названия
таблиц в БД на различных языках ?
Мне кажется, что у тебя изначально неверен подход.
Василий.
>>>>То есть стоит задача хранить информацию введенную в любой кодировке
>>(данные
>>>>вводятся пользователями www), ессно данные необходимо сортировать и т.п.
>>>>Как я понимаю подобное решается использованием unicode.
>>>Если я правильно понимаю, имеется в виду возможность поддержки кодовых
>>таблиц больше 256 символов.
>>>А это возможно с GLS, даже мультибайтные кодировки (китайские иероглифы
:).
>>Да, когда у ты китаец, ты с чувством гордости за свою страну и Ifx
выбираешь
>>соответствующую китайскую локаль и все ok.
>>HO стоит задача хранения в одной базе данных в _ЛЮБОЙ_ кодировке (и ru1251
и
>>en819 и китайские иероглифы, и всякую другую чушь).
>Боюсь, что это в прямом виде невозможно. Т.е. хранить то их можно, но все
символы с кодом 248 (например) будут
>равнозначны и при сортировке будут собраны в одно место. Может быть, можно
"вручную" сохранять в базе инф-ю о кодовой
>таблице и при выдаче производить правильную перекодировку.
>А что, нельзя сразу же перекодировать при записи в базу в единую кодировку
?
Ведь клиент при коннекте должен указать
>свою кодовую таблицу (или определить это за него, если доступ через броузер
и WWW-сервер).
Так это и будет производится! Я конвертирую введенную информацию в "Единую
Кодировку" - unicode!
А на клиенте - в соответствии с учетной записью о его "родной" кодировке
произвожу перекодировку.
Более того, если из базы я получаю unicode я могу устроить ему и его родную
сортировку.
>>В настоящее время для этого принято использовать unicode character sets
(ISO
>>10646).
>>То есть в теории при создании базы надо указать DB_LOCALE= ?unicode?
(как?)
В oracle например для сабжа есть специальная локаль (с тоски заглянул в
мануал)
>Локаль ведь специфицирует не только кодовый набор, в котором определено
соответствие символов их двоичному
>представлению, но и еще много вещей - формат даты, времени, преобразования
и т.д.
Специфика инструмента (java) как раз и предполагает что исходные данные -
unicode. Не откажу себе в удовольствии процитировать (2moderator - сорри за
офтопик) :
"Version 1.1 of the JDK (Java Development Kit) provides a rich set of APIs
for _developing_ _global_ _applications_. These internationalization APIs
are based on the Unicode 2.0 character encoding and include the ability to
adapt text, numbers, dates, currency, and user-defined objects to any
country's conventions."
Ну как ты себе представляешь названия
>таблиц в БД на различных языках ?
:) В этом нет необходимости
>Мне кажется, что у тебя изначально неверен подход.
>
>Василий.
>
--
После установки 7.30 TCX в подкаталоге GLS оседают файлы
для UNICODE & UTF8. Кроме того все возможные комбинации
перекодировок. То есть e01c для UTF8 и e005 для unicode.
Они есть и в подкаталоге локалей для ru_ru. e005 использовать у меня не
получилось. e01c отработал справно как в виде
ru_ru.utf8 так и в виде ru_ru.53372. Отработал, в смысле база создалась.
Дальше нужно пробовать джаву.
Под SUN их нужно просто переписать, поскольку они все равно
в UNIX формате. Для UNIVERSAL есть unicode blade (see ниже).
****************************************************************************
**********
1.0 Overview
1.1 Product Positioning
The Informix Unicode DataBlade Module enables users of Informix Dynamic
Server with Universal Data Option (IDS/UD) to store data in native Unicode
format in a database and to access and manipulate that data.
Previously, distributed queries could only be made among databases with the
same GLS locales, and customers were unable to store data from more than
one language in a single database. To resolve this, Informix created a
locale and code set conversion files for a Universal Code Set (UCS) called
UTF-8. However, many customers use a UCS called Unicode which has some
advantages and some disadvantages over UTF-8. For the first time, the
Unicode DataBlade gives customers a choice as to which Universal Code Set
they can use.
1.2 Product Overview
The Unicode DataBlade module takes advantage of extensibility of IDS/UD to
create a data type and supporting routines that can be used in SQL
statements to store, retrieve, and manipulate data encoded in the Unicode
character set. This new data type is UNIvarchar.
1.3 Target Customers
The target customers for the Unicode DataBlade module are:
--any customer who wants to store data in many different languages
in a database. (The current Informix GLS implementation of the
UTF-8 code set also allows you to do this, but there is performance
degradation and other downsides associated with this.)
--customers who have Unicode data from other sources which they would
like to migrate to Informix.
--customers who specifically want to use the Unicode code set.
--customers who want performance enhancement for Asian code sets that
currently use multi-byte code sets. (Performance is increased due to
the fixed-width nature of the Unicode code set, since each Unicode
character occupies only two bytes. Some Asian databases would
decrease in size compared to using a current non-Unicode multibyte
code set.)
2.0 Product Features and Benefits
Unicode is a Universal Code Set (UCS). This is a generic term used to
describe a code set which tries to encode all known characters. The three
currently existing UCS's are Unicode, Universal Transformation Format-8
bits (UTF-8), and ISO 10646. Unicode was the first UCS to be created; it
was followed by UTF-8 and ISO 10646, which were created to make up for
Unicode's perceived shortcomings. A UCS makes multi-lingual strings
feasible, and gives you the ability to store characters from many different
alphabets in one string. Without a UCS, you would have to tag each
substring with the code set used to encode the characters. Very few software
programs have ever done this, and those that have, have rarely done it
efficiently. Unicode is unique from the code sets that came before it
because it is the first published standard which encoded characters from
dozens of European, Asian and Middle Eastern alphabets around the world.
Most code sets only encode characters for a few alphabets.
UTF-8 is also a UCS and is currently supported in all GLS-enabled Informix
products. Our main competitors claim to support Unicode natively in their
products, but they actually mean that their products support UTF-8.
ISO 10646 is a superset of the Unicode character set, containing some
additional characters from rare code sets, but which otherwise is identical
to the Unicode code set.
The Unicode DataBlade module provides an alternative to using UTF-8 for
users who want to use a UCS code set.
The Unicode DataBlade module allows users to use existing SQL statements to
store, access and manipulate native Unicode data in the same way character
data from other code sets can be manipulated. A user using ESQL/C can
retrieve the actual Unicode data. When viewed through tools such as
DB-Access or other dynamic SQL tools, the data will be returned as LVARCHAR
in a hexadecimal ASCII representation of Unicode.
Unicode data in different columns may originate in different languages.
With the Unicode DataBlade module, each column's data can remain in its
original language if the database uses the generic Unicode GLS locale that
accompanies the Unicode DataBlade module. Unicode data is stored in columns
that have a UNIvarchar data type. If the user so desires it is possible to
store multiple languages in the same column, although in practice users are
unlikely to want to do this.
3.0 Product Requirements
3.1 Hardware Requirements
The hardware requirements are the same as those for Informix Dynamic Server
with Universal Data Option 9.12 and 9.13.
3.2 Software Requirements
The Unicode DataBlade module requires the Informix Dynamic Server with
Universal Data Option, versions 9.12.UCx, 9.13.UC1, 9.13.UC2, or 9.13.UC3.
4.2 Language Support - Internationalization & Localization
The Informix Unicode DataBlade module supports GLS and requires users to
use the GLS locale for the Unicode code set. A generic Unicode GLS locale
with the appropriate code map and conversion files is distributed with this
DataBlade module. The generic Unicode locale contains classifications for
the following character sets :
- ISO8859 character sets from 8859-1 to 8859-9 inclusive
- Microsoft Windows character sets CP1250 to CP1258 inclusive
- Chinese GB2312-1980
- Japanese JIS\EUC 0201-1976, JIS\EUC 0208-1990, JIS\EUC 0212-1990
- Korean KSC5601-1990
The generic Unicode locale is based on en_us language and territory
conventions. Users who want to have NUMERIC, MONETARY, DATE, and TIME
settings other than en_us defaults will need to set these manually using
the appropriate GLS environment variables.
The sort order within the locale is based on codepoint order.
PDF versions of the documentation for Informix DataBlade modules are
included at no additional charge on the same media with the DataBlade
modules themselves. Hard copy documentation is also included.
Additional hard copy documentation can be purchased.
Answers OnLine gives you access to on-line documentation for all Informix
products. All documents are in Adobe Portable Document Format (PDF), HTML,
or both. The PDF documents can be viewed with the free Acrobat Reader,
version 3.0 or later, available for download from Adobe Systems, Inc.
Check the Informix external Web site (http://www.informix.com/answers) for
more details.
7.0 Frequently Asked Questions
Q. What is Unicode?
A. Unicode is a Universal Code Set (UCS). What makes Unicode unique from
other code sets is that it was the first published standard which encoded
characters from dozens of European, Asian and Middle Eastern alphabets
around the world. Most code sets only encode characters for a few
alphabets. For example, ISO 8859-1 encodes characters from the English,
French, Spanish, German and Italian alphabets; Shift-JIS encodes characters
from the English, Japanese, Greek and Cyrillic alphabets. Unicode is a
two-byte code set, and is natively supported by Microsoft Windows NT. No
other operating system natively supports Unicode. Using the UNIX version of
the Unicode DataBlade module, customers can store Unicode data in a UNIX
IDS/UD server and display it on a Windows NT client, a properly configured
Windows 95 client, or a properly configured X-terminal UNIX client. The NT
version of the DataBlade module will be available in May of 1998.
Q. How does the Unicode DataBlade module work?
A. Informix Dynamic Server DataBlade modules and other customer
applications can create their own data types. The Unicode DataBlade module
takes advantage of this facility to create a data type and supporting
routines that can be used in SQL statements to store, retrieve and
manipulate data encoded in the Unicode character set. The new data type is
UNIvarchar. The Unicode DataBlade module allows users to store, access, and
manipulate native Unicode data in the same way as any variable character
data is manipulated. The native Unicode data can be retrieved using
DB-Access, for example, or another dynamic SQL tool. The data will be the
hexadecimal ASCII representation of Unicode, returned as LVARCHAR. Unicode
data is stored in columns so a column can have a UNIvarchar data type.
Q. Why a Unicode DataBlade module?
A. None of Informix's Servers can natively store data encoded in the
Unicode code set. The Unicode DataBlade module solves this problem by
allowing
such data to be stored in IDS/UD.
Q. What are the disadvantages of Unicode?
A. Two bytes are required to store English and European characters. Both
application software and operating system software must be re-written to
support Unicode.
Q. What is UTF-8?
A. Universal Transformation Format-8 bits (UTF-8) is a multi-byte Universal
code set. Software vendors who support large applications and who support
customers with large amounts of English data immediately recognized the
disadvantages of Unicode. They encouraged X/Open to devise an alternative
encoding for each Unicode character in which English characters only occupy
one byte (for space compression) and a string's NULL terminator is only one
byte
long (for compatibility with existing software). This alternative encoding
is the multi-byte code set called UTF-8. All Informix GLS-enabled products
currently support UTF-8 natively by using a UTF-8 GLS locale. UTF-8
contains all the characters contained in Unicode; the ASCII characters
occupy one byte and the remaining characters occupy either two or three
bytes.
Q. What are the advantages of UTF-8?
A. One byte is required to store English characters, rather than the two
bytes required by Unicode.
Q. What are the disadvantages of UTF-8?
A. Two bytes are required to store European characters; Asian and Japanese
characters require two or three bytes. Variable character size can slow
down processing in some cases.
>>>>Подскажите, плз, как настроить сабж. (какие environments etc.)
>>>>То есть стоит задача хранить информацию введенную в любой кодировке
>>>(данные вводятся пользователями www), ессно данные необходимо
сортировать и
>>То есть в теории при создании базы надо указать DB_LOCALE= ?unicode?
(как?)
>>В $INFORMIXDIR/gls/cv3/registry codeset-name 'unicode' присутствует
>>(codeset-number 57349).
>>То есть в теории где-то должны быть файлы локали: e005.* Их у меня нет ни
>>на NT, ни на Solaris
>После установки 7.30 TCX в подкаталоге GLS оседают файлы
>для UNICODE & UTF8. Кроме того все возможные комбинации
>перекодировок. То есть e01c для UTF8 и e005 для unicode.
>Они есть и в подкаталоге локалей для ru_ru. e005 использовать у меня не
>получилось. e01c отработал справно как в виде
>ru_ru.utf8 так и в виде ru_ru.53372. Отработал, в смысле база создалась.
>Дальше нужно пробовать джаву.
>Под SUN их нужно просто переписать, поскольку они все равно
>в UNIX формате. Для UNIVERSAL есть unicode blade (see ниже).
Что такое 7.30 TCX? точнее TCX?
Подскажи пожалуста: может где-то есть эти локали отдельно, и их можно
откуда-то вынуть (www e.g.).
(ну не просить же мне в самом деле на время 7.30 TCX, дескать я только
посмотрю и сразу же отдам :))
>К сожалению я не виже на открытом WEB этой информации.
>Есть бесплатный продукт, International Language Supplement. Содержит самые
>последние локали под
>все что угодно. На диске есть инсталляция под WIN и UNIX.
А какие еще вспомогательные продукты информикса являются свободно
распространяемыми? И как такие диски можно получать?
Я имею в виду не зайти в представительство и переписать, а
получить подписку на это удовольствие, чтобы диски приходили
по мере их выхода.
=============================================================
SY Petro Petin p...@antec.carrier.kiev.ua //Software Developer
ANTEC (Advanced Network TEChnologies), Kiev, Ukraine
Fax: (380-44) 234-35-50 Phone:(380-44) 221-21-64
Ну ты и нахал :))
Мало того, что первым все переписываешь, так ему еще и СД подавай.
Ты что, солить их будешь (как один из твоих начальников :)) ?
[.....]
>>Мне кажется, что у тебя изначально неверен подход.
Прошу прощения за ошибку. Это у меня был неверен подход :))
Теперь немного прояснилось, но не до конца.
Напомню цитату из присланного Володей Притуленко:
Вопрос. Поддерживает ли Informix GLS кодировку Unicode?
Ответ. Библиотека GLS, используемая всеми продуктами Informix GLS,
поддерживает кодировку Unicode, а также все другие однобайтовые и
многобайтовые кодировки. Применение библиотеки GLS не мешает разработчикам
продуктов на Informix использовать Unicode. Однако для поддержки Unicode
разработчики продуктов на Informix должны в своих программах переделать
всю обработку данных типов CHAR, VARCHAR и TEXT, а также вызовы библиотечных
функций GLS. Эта повторная реализация не была сделана ни на сервере БД ODS
версии 7.2, ни на сервере БД Universal Server.
Кто может прокоментировать последние две фразы ?
В отношении 7.30 похоже все уже сделано и "переделать
всю обработку данных типов CHAR, VARCHAR и TEXT" не нужно ?
И что это обозначает для 7.2х ?
Василий.
INFORMIX Client SDK,
INFORMIX документация,
INFORMIX International Language Supplement
INFORMIX JDBC Driver
INFORMIX SE for Linux
Этот список не есть статика. Еще вчера нужно было покупать
клиентскую часть. После нового года тоже может быть что-то изменено.
!!! Наличие free продуктов не означает free поддержку.
> И как такие диски можно получать?
> Я имею в виду не зайти в представительство и переписать, а
>получить подписку на это удовольствие, чтобы диски приходили
>по мере их выхода.
Никто ничего не рассылает по мере выхода. Или снять с сети или
заказать. Или переписать в представительстве.
Regards,
Vladimir
Нет, как раз не сделано. Просто READ.ME, который был с диска ILS
писался до 7.30. А вот в 9.X как раз скорее сделано, но только с применением
UNICODE BLADE.
Я не UNICODE GURU, но из всего, что написано я понимаю 2 момента
(поправьте если не прав):
1. Хотя в локалях UNICODE и UTF8 стоит один комментарий в 2 разных
файлах
Unicdoe or UTF-8 - это все таки разные вещи.
2. В чистом виде поддерживается UTF, хотя приложения,
которые хотят работать реально с UNICDOE все таки могут быть
удовлетворены. Опять же либо blade либо прослойка (пристегнута в
файле маленькая программка), скорей всего о которой идет речь.
На правоту не претендую. Думаю, реально и полно сможет
ответить на вопрос тот, кто это попытается ипользовать. Я так понимаю
реально сейчас это интересует одну команду, которая хорошо
оперирует понятием JAVA (в том числе и INFORMIX JDBC) и INFORMIX.
Может скоро мы увидим что-то типа tips или рекомендаций (безусловно если оно
сработает :)
А по сему пока - пока.
Владимир
Unicode
What is Unicode?
What is a Universal Code Set (UCS)?
What is UTF-8?
What is ISO 10646?
What problem does a UCS solve?
What problems UCS's cannot solve?
What are the advantages of Unicode?
What are the disadvantages of Unicode?
What are the advantages of UTF-8?
What are the disadvantages of UTF-8?
What is character subsetting in a UCS?
What are composite characters?
Do Informix products support a UCS?
How to decide when to use UTF-8?
How to convert between Unicode and UTF-8?
----------------------------------------------------------------------------
----
What is Unicode?
Unicode is a codeset (see the definition of a codeset). What makes Unicode
unique from other code sets is that it was the first published standard
which encoded characters from dozens of European, Asian and Middle Eastern
alphabets around the world. Most code sets only encode characters for a few
alphabets. For example, ISO 8859-1 encodes characters from the English,
French, Spanish, German and Italian alphabets; Shift-JIS encodes characters
from the English, Japanese, Greek and Cyrillic alphabets, etc.
Unicode defines 65536 characters, each occupying 2 bytes.
Unicode is supported by Microsoft Windows NT and Windows95; however, both of
these operating systems still support all the code sets that Windows 3.1
supports. At the time of this writing, no other operating system supports
Unicode.
----------------------------------------------------------------------------
----
What is a Universal Code Set (UCS)?
A Universal Code Set (UCS) is a generic term used to describe a codeset
which tries to encode all known characters. The three current UCS's are
Unicode, UTF-8 and ISO 10646.
Unicode was created first then UTF-8 and ISO 10646 were created to make up
for Unicode's perceived shortcomings.
----------------------------------------------------------------------------
----
What is UTF-8?
The X/Open standards committee did not feel that Unicode could be feasibly
used by existing applications and existing operating systems. Therefore,
they created a codeset called Universal Transformation Format-8 bits
(UTF-8). UTF-8 is a multi-byte codeset that contains all the same 65536
Unicode characters, where the ASCII characters occupy 1 byte and the
remaining characters occupy either 2 or 3 bytes.
As of this writing, there are a few UNIX operating systems which support
UTF-8.
----------------------------------------------------------------------------
----
What is ISO 10646?
The ISO standards committee did not feel that Unicode could contain all
known characters using only two bytes. Therefore, as part of ISO 10646, they
created two code sets: UCS-2 which is identical to Unicode and UCS-4 which
is extensible enough to encode the many characters they felt Unicode could
not.
As of this writing, the author does not know of any operating systems which
support UCS-4.
----------------------------------------------------------------------------
----
What problem does a UCS solve?
A UCS makes multi-lingual strings feasible
A UCS makes it feasible to store characters from many different alphabets in
one string. Without a UCS, you have to tag each substring with the codeset
used to encode the characters in the substring. Very few software programs
have ever done this, and those who have have rarely done it efficiently.
----------------------------------------------------------------------------
----
What problems UCS's cannot solve?
Any codeset simply defines a set of characters and their computer encoding.
Therefore, for even a UCS, there is still internationalized data processing
required to give semantic meaning to a character or string of characters.
A UCS does not obviate the need for codeset conversion
Codeset conversion is still required if any nodes in your network use
different code sets. If all nodes use the same codeset then, no codeset
conversion is required; however, the decision to support the same codeset on
all nodes is not based on whether the codeset is a UCS or not.
A UCS does not define a comparison order.
A codeset cannot necessarily define the sort order for the alphabet(s)
encoded by the codeset.
(1) There are languages that commonly order their characters in multiple
ways, depending on the context. For example, German as two common sort
orders.
(2) There are languages which share some of the same characters. For
example, if German sorts one character before another, but French sorts the
same two characters in the opposite order, the codeset can only specify one
of these orders.
The best a codeset can do is, by virtue of the order of the characters in
the codeset, (a) define an order between different alphabets and/or (b)
define the correct order for those languages which do not share characters
with other languages. For example, in Unicode (a) all the Hebrew characters
come before all the Devanagari characters and (b) all Hebrew characters are
in the correct order because the Hebrew characters are used only by the
Hebrew language.
A UCS does not define date, time, currency and numeric formats
No codeset defines these formats. For all code sets, including UCS's, these
formats need to be defined separately.
A UCS does not define which characters are alphabetic, punctuation, symbols,
etc.
No codeset defines these rules. For all code sets, including UCS's, these
rules need to be defined separately.
----------------------------------------------------------------------------
----
What are the advantages of Unicode?
In some cases, normalized character size (2 bytes) can speed-up processing
----------------------------------------------------------------------------
----
What are the disadvantages of Unicode?
Two bytes required to store English and European characters
Application software must be re-written to support Unicode
Operating system software must be re-written to support Unicode
Software vendors who support large applications and who support customers
with large amounts of English data immediately recognized these
disadvantages of Unicode. They encouraged X/Open to devise an alternative
encoding for each Unicode character in which English characters only occupy
one byte (for space compression) and a string's NULL terminator is only one
byte long (for compatibility with existing software). This alternative
encoding is the multi-byte codeset called UTF-8.
----------------------------------------------------------------------------
----
What are the advantages of UTF-8?
One byte required to store English characters
Multi-byte-enabled application software supports UTF-8 without change
Multi-byte-enabled operating system software supports UTF-8 without change
----------------------------------------------------------------------------
----
What are the disadvantages of UTF-8?
Two bytes required to store European characters
Variable character size can slow-down processing in some cases
----------------------------------------------------------------------------
----
What is character subsetting in a UCS?
Because UCS's contain so many characters, it is not always feasible for
someone like a font provider to create a glyph for all characters. This is
sometimes the case for even non-UCS code sets which define glyphs for only
the English, but not the European characters. Therefore, you usually see a
font for a UCS which does not define glyphs for all characters, but rather
defines common subsets; like Western European alphabets or English and
Japanese, etc.
----------------------------------------------------------------------------
----
What are composite characters?
Because Unicode tries to encode all known characters in 16 bits, it had to
make compromises as to what it defined as a character. Originally instead of
encoding 6 distinct characters for a, e, i, a, e, i, and '; Unicode encoded
only 4: a, e, i and '. The character was formed by following the a character
with the ' character. Unicode then decided to encode common accented
characters like the ones in the example above in a pre-composed form; that
is, a is now encoded as character by itself. However, there are still many
Unicode characters which can only be represented in this composite manner.
The algorithm to process these composite characters is virtually impossible
to implement efficiently. This has been admitted as much by the ISO 10646
committee when they defined the basic Unicode support to not include support
for composite characters. This inefficiency has been further born out by the
fact that there is no software vendor claiming both Unicode and composite
character support.
----------------------------------------------------------------------------
----
Do Informix products support a UCS?
The Application Programmer Interfaces (APIs) of the Informix 7.2
Connectivity products can read and write UTF-8 characters.
UTF-8 is just one of the many code sets that Informix GLS products support.
The character data in an Informix database can be encoded in any one of the
currently 30 code sets that Informix supports.
There are currently no new APIs which can read or write Unicode characters.
Until Informix products provide these APIs, if an application wants to
support Unicode, that application must convert characters from Unicode to
UTF-8 before passing them to Informix APIs and convert characters from UTF-8
to Unicode upon receiving them from Informix APIs. See below for details on
"How to convert between Unicode and UTF-8?".
Each UTF-8 locale that Informix provides defines all the characters in UTF-8
but defines the character classification, comparison order and data formats
for one language and territory; for example, the French language in Canada,
the German language in Germany, etc.
Informix products only support pre-composed characters and do not support
composite characters.
----------------------------------------------------------------------------
----
How to decide when to use UTF-8?
The character data in an Informix database can be encoded in any codeset
that Informix supports. The choice of which codeset to create a database in
does not depend on the capabilities of the operating system upon which the
database resides. This is because Informix GLS products do not rely on
operating system facilities to process character data. The choice of what
codeset to create a database in should be based on the code sets used by the
GUIs and/or terminal emulators of the clients accessing the data.
If all the clients that will ever access a database use the same codeset,
for example Japanese Shift-JIS, then the database should use Shift-JIS to
avoid codeset conversion.
If some of the clients accessing a database use Shift-JIS, but most of the
clients use UJIS (a codeset for which there is a codeset conversion between
it and Shift-JIS), then the database should use UJIS to avoid codeset
conversion most of the time.
If some clients use Shift-JIS and some clients use ISO 8859-1 (a codeset for
which there is no sensible codeset conversion between it and Shift-JIS),
then the database should use UTF-8 since both Shift-JIS and ISO 8859-1 can
be converted into UTF-8.
If any of the clients use UTF-8, then the database should use UTF-8.
If any of the clients use Unicode, then the clients need to convert between
Unicode and UTF-8 (which acts as a compression step) and the database should
use UTF-8.
----------------------------------------------------------------------------
----
How to convert between Unicode and UTF-8?
Below is the C language source code for the two functions which convert
between characters encoded in the Unicode codeset and the UTF-8 codeset.
This source is derived from the X/Open Preliminary Specification: "File
System Safe UCS Transformation Format (FFS-UTF)"; X/Open Document Number:
P316; ISBN: 1-872630-96-0; Published by X/Open Company Ltd., U.K.
/***************************************************************************
*
This structure is used by both functions below
****************************************************************************
/
typedef struct {
int cmask;
int cval;
int shift;
long lmask;
long lval;
} Tab;
static
Tab tab [] =
{
0x80, 0x00, 0*6, 0x7F, 0,
0xE0, 0xC0, 1*6, 0x7FF, 0x80,
0xF0, 0xE0, 2*6, 0xFFFF, 0x800,
0xF8, 0xF0, 3*6, 0x1FFFFF, 0x10000,
0xFC, 0xF8, 4*6, 0x3FFFFFF, 0x200000,
0xFE, 0xFC, 5*6, 0x7FFFFFFF, 0x4000000,
0,
};
/***************************************************************************
*
This function converts a two-byte Unicode character, unicode_char,
into its multi-byte UTF-8 representation and writes the result into
the buffer pointed to by utf8_char. Either 1, 2 or 3 bytes will be
written to utf8_char, but no more than 3 bytes will be written.
Return values: Upon success this function returns the number of bytes
written to the buffer pointed to by utf8_char. If an internal error
has occurred, the function will return -1 and the results written to
utf8_char, if any, will be undefined.
****************************************************************************
/
int
unicode_to_utf8(unsigned char *utf8_char, unsigned short unicode_char)
{
unsigned long long_unicode_char;
int utf8_bytes;
Tab *t;
long_unicode_char = (unsigned long) unicode_char;
utf8_bytes = 0;
for ( t = tab; t->cmask; t++ )
{
utf8_bytes++;
if ( long_unicode_char <= t->lmask )
{
int c = t->shift;
*utf8_char = t->cval | (long_unicode_char >> c);
while ( c > 0 )
{
c -= 6;
utf8_char++;
*utf8_char = 0x80 | ((long_unicode_char >> c) & 0x3F);
}
return utf8_bytes;
}
}
return -1;
}
/***************************************************************************
*
This function converts a multi-byte UTF-8 character, utf8_char, into
its two-byte Unicode character representation and writes the result
into the buffer pointed to by unicode_char. Either 1, 2 or 3 bytes
will be read from utf8_char, but no more than 3 bytes will be read.
Return values: Upon success this function returns the number of
bytes read from utf8_char. If utf8_char does not point to a valid
UTF-8 character or an internal error has occurred, the function will
return -1 and the results written to unicode_char, if any, will be
undefined.
****************************************************************************
/
int
utf8_to_unicode(unsigned short *unicode_char, unsigned char *utf8_char)
{
unsigned long long_unicode_char;
int c0, utf8_bytes;
Tab *t;
utf8_bytes = 0;
c0 = *utf8_char & 0xff;
long_unicode_char = c0;
for ( t = tab; t->cmask; t++ )
{
int c;
utf8_bytes++;
if ( (c0 & t->cmask) == t->cval )
{
long_unicode_char &= t->lmask;
if ( long_unicode_char < t->lval )
return -1;
*unicode_char = (unsigned short) long_unicode_char;
return utf8_bytes;
}
utf8_char++;
c = (*utf8_char ^ 0x80) & 0xff;
if ( c & 0xc0 )
return -1;
long_unicode_char = (long_unicode_char << 6) | c;
}
return -1;
}
END
----------------------------------------------------------------------------
----
Unicode - 27 JUN 96