I have a concatenation of string replacements in this way:
CREATE OR REPLACE FUNCTION norm(t text) RETURNS text AS $$
declare t1 text;
declare t2 text;
...
declare t10 text;
BEGIN
select replace (lower(t), ',', ' ') into t1;
select regexp_replace (t1, '[^0-9a-z\s-]', '', 'g') into t2;
...
select regexp_replace (t10, 'n?oise?.*', '', 'g') into t10;
RETURN trim(t10);
END;
$$ LANGUAGE plpgsql;
At the moment it has 10 different operations and the number keeps on grow. Also it has the inconvenient that changing position to transformations forces to rename variables.
Is there a better way to manage this situation?
Best Answer
You can help yourself by having a
replacements
table:That you would populate with as many replacements you need to perform:
And then change your function to use it:
And check the results:
This won't be as fast as hard-coding all the changes in your function, but will allow for highest flexibility.
As an alternative, you can just change the code structure of your function, and reuse the same variable more than once1:
This is faster, and the best alternative if the number of substitutions is moderate.
You can check it at dbfiddle here
1) PLPGSQL is not a functional language that forces you to assign only once to
val
s, variables can be overwritten as many times as necessary. If you think in Scala terms, they'revar
s, notval
s. In Java terms, they aren'timmutable
.