Take. a particular string from a TEXT in postgres - postgresql

I have one question:
Below is an error message which is stored in a postgres table column, From this string i would like to extract only a part of the string, Is that possible to do in Postgres?
I would like to see odoo.exceptions.ValidationError: ('No MRP template was found for MO/10881!', None)' only this part.
In general all text starting with odoo.exceptions.ValidationError: until the end
How can i do it ? Any idea or suggestions?
'Traceback (most recent call last):
File "/opt/src/addons_OCA/queue/queue_job/controllers/main.py", line 101, in runjob
self._try_perform_job(env, job)
File "/opt/src/addons_OCA/queue/queue_job/controllers/main.py", line 61, in _try_perform_job
job.perform()
File "/opt/src/addons_OCA/queue/queue_job/job.py", line 466, in perform
self.result = self.func(*tuple(self.args), **self.kwargs)
File "/opt/src/addons/costs/models/mrp_production.py", line 163, in trigger_calculate_all_costs
self.calculate_all_costs()
File "/opt/src/addons/sucosts/models/costline_mixin.py", line 284, in calculate_all_costs
rec.generate_service_products()
File "/opt/src/addons/mrp_product_templates/models/mrp_production.py", line 660, in generate_service_products
MO=self.name)))
odoo.exceptions.ValidationError: ('No MRP template was found for MO/10881!', None)'

You can use regexp_replace function to search for particular text then select the text following.
The regexp_replace function provides substitution of new text for
substrings that match POSIX regular expression patterns. It has the
syntax regexp_replace(source, pattern, replacement [, flags ]). The
source string is returned unchanged if there is no match to the
pattern. ...
In this case it seems you want the text after ValidationError:. Something like: (see demo)
select regexp_replace (message, '.*ValidationError:(.*)','\1')
from test;

Related

How to properly insert from stdin in postgresql?

normal insert:
insert into tfreeze(id,s) values(1,'foo');
I tried the following ways, both not working:
copy tfreeze(id,s ) from stdin;
1 foo
\.
copy tfreeze(id,s ) from stdin;
1 'foo'
\.
Only a few questions related from stdin in stackoverflow. https://stackoverflow.com/search?q=Postgres+Insert+statements+from+stdin
--
error code:
ERROR: 22P02: invalid input syntax for type integer: "1 foo"
CONTEXT: COPY tfreeze, line 1, column id: "1 foo"
LOCATION: pg_strtoint32, numutils.c:320
I get code from this(https://postgrespro.ru/education/books/internals) book.
code source: https://prnt.sc/eEsRZ5AK-tjQ
So far I tried:
1, foo, 1\t'foo', 1\tfoo
First, you have to use psql for that (you are already doing that).
You get that error because you use the default text format, which requires that the values are separated by tabulator characters (ASCII 9).
I recommend that you use the CSV format and separate the values with commas:
COPY tfreeze (id, s) FROM STDIN (FORMAT 'csv', FREEZE);
1,foo
\.

PSQL add line breaks to a string

I have a function in PSQL that sends an email to a particular user. The function takes an email text argument and adds this to some constant text before and after in the email body:
In this function, I have a json_build_object call which deals with the recipient, body and title of the email:
jsonb_build_object(
'recipient',recipient,
'title',title,
'message_text', 'some text before.
some text on new line ' || body ||
' some text after.
some text on new line.'
)
My problem is, in the text before and after body, I can't format this on to separate lines. I have tried the following but it did not work:
jsonb_build_object(
'recipient',recipient,
'title',title,
'message_text', E'some text before.\n
some text on new line \n' || body ||
E'\nsome text after.\n
some text on new line.'
)
Can anyone advise what I am doing wrong?
You do it correctly, and the result has line breaks in the form \n. That's how line breaks in text look in JSON.
RFC 8259 describes this:
A string begins and ends with
quotation marks. All Unicode characters may be placed within the
quotation marks, except for the characters that MUST be escaped:
quotation mark, reverse solidus, and the control characters (U+0000
through U+001F).
Line feed is character U+000A, so it must be escaped.
If you want unescaped line breaks, use something else than JSON.
Laurenz Albe pointed out the issue from the JSON end. My answer is about the other end.
What are you doing with the JSON to get it into an email?
It might be possible to do what you want from there. An example in Python:
select * from json_build_object(
'recipient', 'aklaver',
'title', 'head bottlewasher',
'message_text', 'some text before.\nsome text on new line ' || ' The body'||' some text after.\nsome text on new line.'
);
json_build_object
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{"recipient" : "aklaver", "title" : "head bottlewasher", "message_text" : "some text before.\\nsome text on new line The body some text after.\\nsome text on new line."}
email_str = "some text before.\\nsome text on new line The body some text after.\\nsome text on new line."
print(email_str.replace("\\n", "\n"))
some text before.
some text on new line The body some text after.
some text on new line.

Ambiguous column error using orange3 - POSTGRES

When executing the query inside Orange 3, I got an ambiguous column error
QUERY
SELECT CAST(REPLACE(memoria_em_uso, 'G','') AS FLOAT),
CAST(REPLACE(memoria_total, 'G','') as FLOAT),
CAST(REPLACE(memoria_livre, 'M','') as FLOAT)
FROM tbl_memoria_hosts
OUTPUT
Error encountered in widget SQL Table:
Traceback (most recent call last):
File "/home/luis/anaconda3/lib/python3.7/site-packages/Orange/data/sql/backend/postgres.py", line 81, in execute_sql_query
cur.execute(query, params)
psycopg2.errors.AmbiguousColumn: column reference "replace" is ambiguous
LINHA 1: SELECT (("replace")::double precision) AS "replace", (("repl...
Note:
All columns in the table are VARCHAR, where the information is written as follows 7.7G

pyspark DataFrame selectExpr is not working for more than one column

We are trying Spark DataFrame selectExpr and its working for one column, when i add more than one column it throws error.
First one is working, the second one throws error.
Code sample:
df1.selectExpr("coalesce(gtr_pd_am,0 )").show(2)
df1.selectExpr("coalesce(gtr_pd_am,0),coalesce(prev_gtr_pd_am,0)").show()
Error log:
>>> df1.selectExpr("coalesce(gtr_pd_am,0),coalesce(prev_gtr_pd_am,0)").show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/hdp/2.6.5.0-292/spark2/python/pyspark/sql/dataframe.py", line 1216, in selectExpr
jdf = self._jdf.selectExpr(self._jseq(expr))
File "/usr/hdp/2.6.5.0-292/spark2/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py", line 1160, in __call__
File "/usr/hdp/2.6.5.0-292/spark2/python/pyspark/sql/utils.py", line 73, in deco
raise ParseException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.ParseException: u"\nmismatched input ',' expecting <EOF>(line 1, pos 21)\n\n== SQL ==\ncoalesce(gtr_pd_am,0),coalesce(prev_gtr_pd_am,0)\n---------------------^^^\n"
check this
df1.selectExpr("coalesce(gtr_pd_am,0)”,”coalesce(prev_gtr_pd_am,0)").show()
You need specify the columns individually

replace string with split_part function

I want to replace the first word before delimeter ' ,' with ' 0, the first word ')
select replace('tab,graph,map', split_part('tab,graph', ',', 1) like 'tab','0, tab')
ERROR: function replace(unknown, boolean, unknown) does not exist
LINE 1: select replace('tab,graph,map', split_part('tab,graph', ',',...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
The replace function replaces all occurrences of the string so you have to make sure the string to replace is unique or use something else. However, regexp_replace only replaces the first occurrence by default so you can use that; your question is a little unclear about what the expected output is but maybe this is is what you're looking for:
=> select regexp_replace('tab,graph,map', ',', '0,');
regexp_replace
----------------
tab0,graph,map
Or this one:
=> select regexp_replace('tab,graph,map', 'tab,', '0,');
regexp_replace
----------------
0,graph,map
Or maybe even this:
=> select regexp_replace('tab,graph,map', 'tab,', '0,,');
regexp_replace
----------------
0,,graph,map
you need to cast, since the function expects replace(text, text, text) and does not know how to handle your literal strings calling them unknown...
cast('tab,graph,map' AS text)
also the 2nd param is a LIKE comparison ? which returns boolean, but the function replace expects it to be the delimiter.
CAST(split_part('tab,graph', ',', 1) AS text)
finally the last param (same problem as the first)
cast('0, tab' AS text)
of course if you really just want to prepend '0, ' to your string, 'tab,graph,map' you could just do that...
SELECT '0, ' || 'tab,graph,map' ;