postgresqlcharacter-encodingturkish

Postgres upper function on turkish character does not return expected result


It looks like postgres upper/lower function does not handle select characters in Turkish character set.

select upper('Aaı'), lower('Aaİ') from mytable;

returns :

AAı, aaİ

instead of :

AAI, aai

Note that normal english characters are converted correctly, but not the Turkish I (lower or upper)

Postgres version: 9.2 32 bit

Database encoding (Same result in any of these): UTF-8, WIN1254, C

Client encoding:

 UTF-8, WIN1254, C

OS: Windows 7 enterprise edition 64bit

SQL functions lower and upper return the following same bytes for ı and İ on UTF-8 encoded database

\xc4b1    
\xc4b0   

And the following on WIN1254 (Turkish) encoded database

\xfd      
\xdd     

I hope my investigation is wrong, and there is something I missed.


Solution

  • Your problem is 100% Windows. (Or rather Microsoft Visual Studio, which PostgreSQL was built with, to be more precise.)

    For the record, SQL UPPER ends up calling Windows' LCMapStringW (via towupper via str_toupper) with almost all the right parameters (locale 1055 Turkish for a UTF-8-encoded, Turkish_Turkey database),

    but

    the Visual Studio Runtime (towupper) does not set the LCMAP_LINGUISTIC_CASING bit in LCMapStringW's dwMapFlags. (I can confirm that setting it does the trick.) This is not considered a bug at Microsoft; it is by design, and will probably not ever be "fixed" (oh the joys of legacy.)

    You have three ways out of this:


    For completeness (and nostalgic fun) ONLY, here is the procedure to patch a Windows system (but remember, unless you'll be managing this PostgreSQL instance from cradle to grave you may cause a lot of grief to your successor(s); whenever deploying a new test or backup system from scratch you or your successor(s) would have to remember to apply the patch again -- and if let's say you one day upgrade to PostgreSQL 10, which say uses MSVCR120.DLL instead of MSVCR100.DLL, then you'll have to try your luck with patching the new DLL, too.) On a test system

    BUT REMEMBER, the moment you move the data off the Ubuntu system or off the patched Windows system to an unpatched Windows system you will have the problem again, and you may be unable to import this data back on Ubuntu if the Windows instance introduced duplicates in a citext field or in a UPPER/LOWER-based function index.