2

I am creating a transaction where I want to update a user in one table and delete some data in another that belongs to that user. But only the first query is executed, not the second one. In the delete statement in the second query code is a comma-separated std::string.

pqxx::connection c(connectionString);

try {
    pqxx::work w(c);
    pqxx::result r;

    c.prepare("user", "update user set started = null, finished = null, task = $1 where id = $2");
    r = w.prepared("user")(task)(email).exec();

    c.prepare("belongings", "delete from belongings where id in " \
        "(select id from info where code in ($1) and id = $2)");
    r = w.prepared("belongings")(code)(id).exec();

    w.commit();
}

I read this SO-thread that explain how to run multiple queries before commit(). So I must be making a mistake in the second delete statement but can't find the reason.

3
  • What's the type of belongings.code? Also show assignment to code variable. Commented Nov 17, 2017 at 11:40
  • This doesn't answer your question, but you could wrap all of that in a function and execute the function. This would have the added benefit that if the first statement failed it wouldn't execute the second (although a transaction could accomplish the same thing). Commented Nov 17, 2017 at 11:42
  • @klin belongings.code is varchar in the table. And code is a std::string like 'abc','def','ghi'. I first thought there was a limit to the IN clause but that appears not to be the case. Commented Nov 17, 2017 at 11:50

1 Answer 1

1

The code parameter is interpreted as a single literal. You can try to use the alternative syntax of any(array expression), e.g.:

code = "{abc,def}";     // instead of code = "'abc','def'"
...

c.prepare("belongings", "delete from belongings where id in " \
    "(select id from info where code = any ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();      
Sign up to request clarification or add additional context in comments.

1 Comment

Works. That was very helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.