Re: Localizing stored functions by replacing placeholders in their body

From: Alvaro Herrera <alvherre(at)alvh(dot)no-ip(dot)org>
To: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Localizing stored functions by replacing placeholders in their body
Date: 2021-03-02 20:19:00
Message-ID: 20210302201900.GA14417@alvherre.pgsql
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 2021-Mar-02, Alexander Farber wrote:

> CREATE OR REPLACE FUNCTION localize_hello()
> RETURNS text AS
> $func$
> SELECT '$(hello)';
> $func$ LANGUAGE sql IMMUTABLE;

I'm not sure this is a great approach to in-database translations: you
have one function per string, which is cumbersome, bloated and probably
slow. I would suggest having a function that takes a string and returns
its translation, which is obtained from a couple of tables: one where
the original strings are stored and another which stores the
translations for each string into each language.

(You can have the target language be a property of the database, or a
custom GUC setting that the application sets at the start, or just
passed as an argument to the translate() function from somewhere. Or
maybe each database always has exactly one language. Whatever suits you
best.)

So the functions that your application calls return strings by doing
stuff like
SELECT translate('one UFO came and stole one bike');
and they'll get whatever is right for them. The functions only need to
worry about calling translate() in all the right places; they don't need
to individually worry about fetching the translation etc.

Note that in that design, the original string appears in two places: the
function source code, and the original-strings table. You could go one
step further and have the function store a code (UUID?) for the string;
then if a message has a typo, you're just one UPDATE away from fixing it
instead of an ALTER FUNCTION. And also, it's easy to change all
translations together if your UFOs are actually ordinary burglars.

Exercise for the reader: what if your strings have format specifiers?
"%d UFOs came and stole %d bikes"

--
Álvaro Herrera 39°49'30"S 73°17'W

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Karsten Hilbert 2021-03-02 20:23:51 Aw: Re: Localizing stored functions by replacing placeholders in their body
Previous Message Asaf Flescher 2021-03-02 20:18:35 Locks in creating a partition in CREATE TABLE vs ALTER TABLE