string.PadLeft and string.PadRight wrong translation #3116
Open
Description
Npgsql EF Core provider automatically translates stringValue.PadLeft(length, char) -> lpad(stringValue, length, char).
However, these two functions do not produce exactly the same result and may cause problems.
C# example:
var stringValue = "1234";
Console.WriteLine(stringValue.PadLeft(2, '0'));
/* Output : 1234 */
SQL example:
SELECT lpad('1234', 2, '0')
/* Output : 12 */
If the string is already longer than length then it is truncated in lpad and rpad functions.
lpad and rpad functions need to be replaced with a new function that gives the correct result.
I tried a method like the one below, but strangely, in a different scenario, I still did not get the result I expected.
SQL example:
SELECT greatest('1234'::text, lpad('1234'::text, 6, '0')::text)
/* Output : 1234 */
After working on it a bit I found a method that works correctly as follows
/* lpad alternative */
SELECT repeat('0', 6 - length('1234')) || '1234' /* Output : 001234 */
SELECT repeat('0', 2 - length('1234')) || '1234' /* Output : 1234 */
/* rpad alternative */
SELECT '1234' || repeat('0', 6 - length('1234')) /* Output : 123400 */
SELECT '1234' || repeat('0', 2 - length('1234')) /* Output : 1234 */
Do you have any other ideas?