I am building a PostgreSQL query through a script that returns formatted LaTeX formulas surrounded by double dollar signs, such as the following one:
$$6 x^{14} + \frac{7 x^{13}}{5} + \frac{13 x^{8}}{7} + \frac{5 x^{5}}{6}$$
Moreover, these formulas belong to an array, so that the complete INSERT
query would be something like this:
INSERT INTO table("array")
VALUES (
'{"$$6 x^{14} + \frac{7 x^{13}}{5} + \frac{13 x^{8}}{7} + \frac{5 x^{5}}{6}$$",
"$$\frac{9 x^{11}}{13} + \frac{13 x^{9}}{7} + x^{8} + \frac{x^{6}}{3}$$",
"$$2 x^{13} + \frac{52 x^{12}}{3} + \frac{65 x^{4}}{9} + \frac{3}{2}$$"}'
)
However, following the INSERT, the backslash (\
) that precedes frac
disappears in the database (I get frac
instead of \frac
. Consequently my formulas do not render well in my application.
Here's the content of the cell:
{"$$6 x^{14} + frac{7 x^{13}}{5} + frac{13 x^{8}}{7} + frac{5 x^{5}}{6}$$",
"$$frac{9 x^{11}}{13} + frac{13 x^{9}}{7} + x^{8} + frac{x^{6}}{3}$$",
"$$2 x^{13} + frac{52 x^{12}}{3} + frac{65 x^{4}}{9} + frac{3}{2}$$"}
I use the sympy module in Python to automatically generate the formulas, so to manually double the backslashes before each frac
is not an option.
What should I do to prevent this behavior from happening?
Backslash is an escape character in strings that represent an array of strings:
SELECT ('{a,"b\"c\\d"}'::text[])[2];
text
-------
b"c\d
(1 row)
If the backslash does not precede a character with a special meaning, it is ignored.
Double all the backslashes inside the string representation of a string array in PostgreSQL to get what you want.
If such backslashes are the only ones occurring in your string constant, you could proceed as follows:
SELECT replace(
'{"$$6 x^{14} + \frac{7 x^{13}}{5} + \frac{13 x^{8}}{7} + \frac{5 x^{5}}{6}$$",
"$$\frac{9 x^{11}}{13} + \frac{13 x^{9}}{7} + x^{8} + \frac{x^{6}}{3}$$",
"$$2 x^{13} + \frac{52 x^{12}}{3} + \frac{65 x^{4}}{9} + \frac{3}{2}$$"}',
'\',
'\\'
)::text[];