SQLite3 C++ Query near "CASE": syntax error - c++

Using SQLite3 C++ implementation though I believe this error is more general.
I'm simply trying to do a statement that says:
"If the column 'lastPlayed' does not exist in the table 'Players', ALTER the table and add it to said table"
Here's my query:
query = string("CASE WHEN COL_LENGTH('Players', 'lastPlayed') IS NULL ")
+ " BEGIN "
+ "ALTER TABLE Players "
+ "ADD lastPlayed DATETIME DEFAULT now"
+ " END "
;
The error:
near "CASE": syntax error
What am I doing wrong here?

Your CASE statement is fine. The error is in the fact that COL_LENGTH is not an inbuilt function in SQLite.
What you can do to achieve your result is remove the CASE statement and in your code, just attempt to alter the Players table to add a lastPlayed column. Then wrap your alter statement in a try-catch block. When the column already exists, the exception will be thrown, otherwise the table will be altered successfully and you can proceed.

Try this syntax
CASE
WHEN expr THEN expr
WHEN expr THEN expr
.
.
END
https://www.sqlite.org/lang_expr.html

Related

Is it possible to update a piece of data in a pre-existing table using the output of data from a CTE?

I need to correct a datapoint in a pre-existing table. I am using multiple CTEs to find the bad value and the corresponding good value. I am having trouble working out how to overwrite the value in the table using the output of the CTE. Here is what I am trying:
with [extra CTEs here]....
,CTE3 AS (
SELECT c1.FIELD_1, c1.FIELD_2 AS GOOD, c2.FIELD_3 AS BAD
FROM CTE1 c1
JOIN CTE2 c2 ON c1.FIELD_1 = c2.FIELD_1
)
update TABLE1
set TABLE1.FIELD_3 = CTE3.GOOD
from CTE3
INNER JOIN TABLE1 ON CTE3.BAD = TABLE1.FIELD_3
Is it even possible to achieve this?
If so, how should I change my logic to get it to work?
Trying the above logic is throwing the following error:
SQL Error [42601]: An unexpected token "WITH CTE1 AS ( SELECT
FIELD_1" was found following "BEGIN-OF-STATEMENT". Expected tokens
may include: "<update>".. SQLCODE=-104, SQLSTATE=42601,
DRIVER=4.27.25
Table designs and expected output:

"Where clause" is not working in AWS Athena

I used AWS Glue Console to create a table from S3 bucket in Athena. You can see a relevant part on the screenshot above. I obfuscated column name, so assume the column name is "a test column". I would like to select the records with value D in that column. The query I tried to run is:
SELECT
*
FROM
table
WHERE
"a test column" = "D"
Nothing is returned. I also tried to use IS instead of =, as well as to surround D with single quotes instead of double quotes within the WHERE clause:
-- Tried this
WHERE
"a test column" = 'D'
-- Tried this
WHERE
"a test column" IS "D"
-- Tried this
WHERE
"a test column" IS 'D'
Nothing works. Can someone help? Thank you.
The error message I got is
Mismatched input 'where' expecting (service: amazon athena; status code: 400; error code: invalid request exception; request id: 8f2f7c17-8832-4e34-8fb2-a78855e3c17d)
Problem with the query syntax. Use single quotes (') when you refer to a string values, because double quotes refer to a column name in your table.
SELECT
*
FROM
table
WHERE
"column_name" = 'D'
The unexpected answer (also apologize if I did not say it clearly in the original post) is that, I cannot add "limit 200" in front of the where clause. I have to add it in the end. Hope it helps others.

How do you insert variables into a database table using PostgreSQL via C++?

I have a C++ program that inserts values into a database table. I can't directly hardcode the values in because the data is constantly being updated, but I'm really confused about the syntax.
When I try to do this:
l.exec("INSERT INTO course VALUES(cid, term, 'subj',crse, sec, 'units', 'instructors');");
l.exec("INSERT INTO meeting VALUES(cid, term, 'type', 'days', 'time', 'build', room);");
l.exec("INSERT INTO enrolledin VALUES(cid, term, sid, 'major', 'classlevel', 'level', 'status', seat, numunits, 'grade');");
l.exec("INSERT INTO student VALUES(sid, 'surname', 'prefname', 'email');");
I get this error:
terminate called after throwing an instance of 'pqxx::undefined_column'
what(): ERROR: column "cid" does not exist
LINE 1: INSERT INTO course VALUES(cid, term, 'subj',crse, se...
^
HINT: There is a column named "cid" in table "course", but it cannot be referenced from this part of the query.
--
I was told that it's because I was inserting the literal string name instead of the values inside the string, and I'm confused as to how to insert the values inside the string via C++ while still using variable names.
Syntax of the used SQL INSERT query is incorrect. It should be:
INSERT INTO course (cid, subj) VALUES(1, 'subj');
You should specify table name together with columns to insert into and values after that. I reduced number of columns for simplicity. For a complete syntax of INSERT query check the PostgreSQL documentation.
To insert values from your variables you can do the following:
int cidValue = 1;
std::string subjValue = "subj";
l.exec("INSERT INTO course (cid, subj) VALUES(" + std::to_string(cidValue) + ", '" + l.esc(subjValue) + "')");
esc() function helps to prevent SQL injection attack.

SOCI Cannot prepare statement

I have a function like this:
CREATE OR REPLACE FUNCTION get_path_set_1(IN pathset_id_in character varying, OUT id character varying, OUT pathset_id character varying, OUT utility double precision)
RETURNS SETOF record AS
$BODY$
begin
if exists(SELECT 1 FROM "PathSet_Scaled_HITS_distinctODs" WHERE "ID" = $1) then
return query SELECT "ID", "PATHSET_ID", "UTILITY"
FROM "SinglePath_Scaled_HITS_distinctODs"
where "PATHSET_ID" = $1;
end if;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION get_path_set_1(character varying)
OWNER TO postgres;
when I call it in my program using this:
std::string testStr("43046,75502");// or std::string testStr("'43046,75502'");
soci::rowset<sim_mob::SinglePath> rs = (sql.prepare << "get_path_set_1(:pathset_id_in)",soci::use(testStr));
I get the following exception:
terminate called after throwing an instance of 'soci::postgresql_soci_error'
what(): Cannot prepare statement. ERROR: syntax error at or near "get_path_set_1"
LINE 1: get_path_set_1($1)
I will appreciate if you help me detect missing part
thank you
This does not solve the error you report. But simplify your function:
CREATE OR REPLACE FUNCTION get_path_set_1(pathset_id_in varchar)
RETURNS TABLE(id varchar, pathset_id varchar, utility double precision) AS
$func$
BEGIN
RETURN QUERY
SELECT "ID", "PATHSET_ID", "UTILITY"
FROM "SinglePath_Scaled_HITS_distinctODs"
WHERE "PATHSET_ID" = $1;
END
$func$ LANGUAGE plpgsql;
RETURNS TABLE is the modern, more elegant, equivalent form of the combination RETURNS SETOF record and OUT parameters.
IF exists ... is buying you nothing here. Run the query; if nothing is found, nothing is returned. Same result for half the cost.
From this piece of code:
soci::rowset<sim_mob::SinglePath> rs =
(sql.prepare << "get_path_set_1(:pathset_id_in)",soci::use(testStr));
it appears you're trying to prepare a query that just contains the function call without even a SELECT.
That's not valid in SQL. You want to prepare this query instead:
SELECT * FROM get_path_set_1(:pathset_id_in)
This form (select * from function(...)) is also necessary because the function returns a resultset with multiple columns, as opposed to just a scalar value.
Also as Erwin mentions, the OUT and SETOF RECORD are weird in this case, I'll second his advice on using RETURNS TABLE.

Why do I get an error when I try to execute a query with parameters in postgreSQL?

The db is PostgreSQL. When I try to execute a query with parameters, such as this one
cursor.execute("""
SELECT u.username, up.description,
ts_rank_cd(to_tsvector(coalesce(username,'')|| coalesce(description,'')) , to_tsquery('%s')) as rank
FROM auth_user u INNER JOIN pm_core_userprofile up on u.id = up.user_id
WHERE to_tsvector(coalesce(username,'')|| coalesce(description,'')) ## to_tsquery('%s')
ORDER BY rank DESC;
""", ["hello","hello"])
Django complains of a ProgrammingError, adding syntax error at or near the parameter (in this example, "hello"). Here's the part of the Django generated SQL statement that the error comes from:
to_tsquery('E'hello'')
Even if I copy-paste it to a postgreSQL shell, I get the syntax error. If I omit the 'E' part, it works. What should I make of it?
ozgur,
Try
to_tsquery(%s)
instead of
to_tsquery('%s')
I believe you are missing a ' after the E.