How to insert a value to postgres database column which contains double quotes and triple quotes - postgresql

I want to insert a query string into a Postgres database column in the following format
{"enrolled_time":'''SELECT DISTINCT enrolled_time AT TIME ZONE %s FROM alluser'''}
I try this:
UPDATE reports SET raw_query = {"enrolled_time":'''SELECT DISTINCT enrolled_time AT TIME ZONE %s FROM alluser'''} WHERE id=37;
It gives error like
ERROR: syntax error at or near "{"
LINE 1: UPDATE base_reports SET extra_query = {"enrolled_time":'''SE...
When I try using single quotes it throws error like following:
ERROR: syntax error at or near "SELECT"
LINE 1: ...DATE reports SET raw_query = '{"enrolled_time":'''SELECT DIS...
How can I overcome this situation

Use dollar quoting:
UPDATE reports
SET raw_query = $${"enrolled_time":'''SELECT DISTINCT enrolled_time AT TIME ZONE %s FROM alluser'''}$$
WHERE id = 37;

Related

Tableau Prep: How can I refer to a parameter in the Custom SQL query?

Using Tableau Prep Builder version 2021.4.4 I connected to Postgresql database (version 12) and created a Custom Query as the only input in the Flow.
Then I created a parameter (my_date).
In the custom query I have:
select my_field
from my_table
where date = -- How can I refer to my_date?
I have already tried the following but all failed:
where date = ${my_date}-- syntax error at or near "$"
where date = $my_date -- syntax error at or near "$"
where date = :my_date -- syntax error at or near ":"
where date = (my_date) -- "my_date" does not exist
where date = my_date -- "my_date" does not exist
where date = $1 -- Index 0 out of bounds for length 0
Use < > , for example:
where date = <my_date>
OR
where date = '<my_date>'

Escaping column with dot in UPDATE in PostgreSQL 9.3.9

I need to fix few lines in Jira configuration in PostgreSQL. Unfortunatelly it uses dot notation in columns and I cannot fine a way how to escape it.
select * from "cwd_directory_attribute";
directory_id | attribute_name | attribute_value
1 | user_encryption_method | atlassian-security
10000 | ldap.user.filter | (objectclass=person)
No escaping:
psql:fix_directory.sql:1: ERROR: column "ldap" of relation "cwd_directory_attribute" does not exist
LINE 1: update cwd_directory_attribute set ldap.basedn='ou=sandbox,d...
Single quote:
psql:fix_directory.sql:1: ERROR: syntax error at or near "'ldap.basedn'"
LINE 1: update cwd_directory_attribute set 'ldap.basedn'='ou=sandbox...
Double quote:
psql:fix_directory.sql:1: ERROR: column "ldap.basedn" of relation "cwd_directory_attribute" does not exist
LINE 1: update cwd_directory_attribute set "ldap.basedn" ='ou=sandb...
Square bracket:
psql:fix_directory.sql:1: ERROR: syntax error at or near "["
LINE 1: update cwd_directory_attribute set [ldap.basedn] ='ou=sandb...
E.g.
update cwd_directory_attribute set "ldap.basedn" ='ou=sandbox,dc=eu' where directory_id=10100;
I found answers that double quotes shall work but they do not. I could modify the columns manually in some SQL editor, but I want to set up a script:
psql -f fix_directory.sql jiradb7
What is the proper escaping for columns in UPDATE procedure?
Update:
select "ldap.secure" from "cwd_directory_attribute";
ERROR: syntax error at or near "select"
LINE 2: select "ldap.secure" from "cwd_directory_attribute";
You are confusing column values and column names.
Your table has a column named attribute_name which contains the value 'ldap.user.filter' (and supposedly 'ldap.basedn' in a different row).
So what you want is:
update cwd_directory_attribute
set attribute_value = 'ou=sandbox,dc=eu'
where directory_id = 10100
and attribute_name = 'ldap.basedn';

intersystem cache C# query with datetime

When I use cache sql query in C# I'm getting an error:
SQLtext1 = "SELECT top 10 * FROM dbo.DAPPLICATIONSTAT where TIMESTAMP = '2015-02-01 00:00:00'"
I would like to use a where clause with a datetime filter.
I am using InterSystems.Data.CacheClient.dll to execute the query.
Error Messge :
[SQLCODE: <-4>:<A term expected, beginning with one of the following: identifier, constant, aggregate, %ALPHAUP, %EXACT, %MVR, %SQLSTRING, %SQLUPPER, %STRING, %UPPER, $$, :, +, -, (, NOT, EXISTS, or FOR>]
[Cache Error: <<SYNTAX>errdone+2^%qaqqt>] [Details: <Prepare>]
[%msg: < SQL ERROR #4: A term expected, beginning with either of: (, NOT, EXISTS, or FOR^SELECT top :%qpar(1) * FROM dbo . DAPPLICATIONSTAT where TIMESTAMP>
I think that you have reserved word TIMESTAMP and so, you have that error
Try this SQL query, where filedname TIMESTAMP in dobled quotas
SELECT top 10 * FROM dbo.DAPPLICATIONSTAT where "TIMESTAMP" = '2015-02-01 00:00:00'

Using date in ref cusor with pl/sql

I have a var: acc_date with type date.
It takes its value from a cursor and when I insert its value to logger table as:
insert into logger values(1,acc_date);
the out put when a select it from logger is
1 01-JAN-10
but when i use it to compare with another Date value in another cursor as
OPEN c_get_date_id
for 'SELECT Date_D.DATEKEY from Date_D where Date_D.DATEVALUE='||acc_date;
EXIT WHEN c_get_date_id%NOTFOUND;
FETCH c_get_date_id
INTO date_id;
insert into logger values (1,'Now with date_id'||date_id);
CLOSE c_get_date_id;
an error occurs:
Error report:
ORA-00904: "JAN": invalid identifier
ORA-06512: at "HW.FILLFACT", line 82
ORA-06512: at line 1
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
strong text
You need at least add some quotes around the date:
....' where Date_D.DATEVALUE='''||acc_date||'''';
Double apostrophes within a string will be concatenated to a single apostrophe, so that the expression becomes
where Date_D.DATEVALUE='....';
In order to make the thing more foolprof, I'd also add a specific to_date:
.... ' where Date_D.DATEVALUE=to_date(''' || acc_date || ', ''dd-mon-yy'')';
At the moment your dynamic query is being interpreted as:
SELECT Date_D.DATEKEY from Date_D where Date_D.DATEVALUE=01-JAN-10
The error is because string representation of the date isn't being quoted, so it's seeing JAN as an identifier - and nothing matches that name. You could enclose the date value in quotes:
open c_get_date_id
for 'SELECT Date_D.DATEKEY from Date_D where Date_D.DATEVALUE='''||acc_date||'''';
But you're treating the date as a string, and forcing conversion of all your table values to strings to be compared, using your session's NLS_DATE_FORMAT. It would be better to compare it as a date (although this somewhat assumes all your values have the time portion set to midnight):
open c_get_date_id
for select date_d.datekey from date_d where date_d.datevalue = acc_date;
Your exit is in the wrong place though, and you aren't looping, so maybe you want:
open c_get_date_id
for select date_d.datekey from date_d where date_d.datevalue = acc_date;
loop
fetch c_get_date_id into date_id;
exit when c_get_date_id%notfound;
insert into logger values (1, 'Now with date_id'||date_id);
end loop;
close c_get_date_id;
If you only have one value in the first place though, you probably don't want a loop or cursor at all, and could do a simple select ... into instead:
select date_d.datekey into date_id from date_d
where date_d.datevalue = acc_date;
insert into logger values (1, 'Now with date_id'||date_id);
Though of course that would error if you had no matching date in your table, or more than one, and you'd need to deal with that - but then I guess you'd want to anyway.

Convert a string representing a timestamp to an actual timestamp in PostgreSQL?

In PostgreSQL: I convert string to timestamp with to_timestamp():
select * from ms_secondaryhealthcarearea
where to_timestamp((COALESCE(update_datetime, '19900101010101'),'YYYYMMDDHH24MISS')
> to_timestamp('20121128191843','YYYYMMDDHH24MISS')
But I get this error:
ERROR: syntax error at end of input
LINE 1: ...H24MISS') >to_timestamp('20121128191843','YYYYMMDDHH24MISS')
^
********** Error **********
ERROR: syntax error at end of input
SQL state: 42601
Character: 176
Why? How to convert a string to timestamp?
One too many opening brackets. Try this:
select *
from ms_secondaryhealthcarearea
where to_timestamp(COALESCE(update_datetime, '19900101010101'),'YYYYMMDDHH24MISS') >to_timestamp('20121128191843','YYYYMMDDHH24MISS')
You had two opening brackets at to_timestamp:
where to_timestamp((COA.. -- <-- the second one is not needed!
#ppeterka has pointed out the syntax error.
The more pressing question is: Why store timestamp data as string to begin with? If your circumstances allow, consider converting the column to its proper type:
ALTER TABLE ms_secondaryhealthcarearea
ALTER COLUMN update_datetime TYPE timestamp
USING to_timestamp(update_datetime,'YYYYMMDDHH24MISS');
Or use timestamptz - depending on your requirements.
Another way to convert a string to a timestamp type of PostgreSql is the above,
SELECT to_timestamp('23-11-1986 06:30:00', 'DD-MM-YYYY hh24:mi:ss')::timestamp without time zone;
I had the same requirement as how I read the title. How to convert an epoch timestamp as text to a real timestamp. In my case I extracted one from a json object. So I ended up with a timestamp as text with milliseconds
'1528446110978' (GMT: Friday, June 8, 2018 8:21:50.978 AM)
This is what I tried. Just the latter (ts_ok_with_ms) is exactly right.
SELECT
data->>'expiration' AS expiration,
pg_typeof(data->>'expiration'),
-- to_timestamp(data->>'expiration'), < ERROR: function to_timestamp(text) does not exist
to_timestamp(
(data->>'expiration')::int8
) AS ts_wrong,
to_timestamp(
LEFT(
data->>'expiration',
10
)::int8
) AS ts_ok,
to_timestamp(
LEFT(
data->>'expiration',
10
)::int8
) + (
CASE
WHEN LENGTH(data->>'expiration') = 13
THEN RIGHT(data->>'expiration', 3) ELSE '0'
END||' ms')::interval AS ts_ok_with_ms
FROM (
SELECT '{"expiration": 1528446110978}'::json AS data
) dummy
This is the (transposed) record that is returned:
expiration 1528446110978
pg_typeof text
ts_wrong 50404-07-12 12:09:37.999872+00
ts_ok 2018-06-08 08:21:50+00
ts_ok_with_ms 2018-06-08 08:21:50.978+00
I'm sure I overlooked a simpler version of how to get from a timestamp string in a json object to a real timestamp with ms (ts_ok_with_ms), but I hope this helps nonetheless.
Update: Here's a function for your convenience.
CREATE OR REPLACE FUNCTION data.timestamp_from_text(ts text)
RETURNS timestamptz
LANGUAGE SQL AS
$$
SELECT to_timestamp(LEFT(ts, 10)::int8) +
(
CASE
WHEN LENGTH(ts) = 13
THEN RIGHT(ts, 3) ELSE '0'
END||' ms'
)::interval
$$;