1

I'm trying to insert values into a Postgres11 database with raw sqlalchemy text() queries. The following SQL query works correctly when I run it through psql-client:

WITH a AS (
  INSERT INTO person (id) 
       VALUES ('a')
    RETURNING id
) 
INSERT INTO person_info (person_id) 
     SELECT id 
       FROM a;

All rows are correctly inserted:

# select id from person;
 id 
----
 a
(1 row)

However, if I create an engine in sqlalchemy and call execute on it with an identical query, it runs successfully but no rows are inserted:

>>> engine.execute("WITH a AS (INSERT INTO person (id) VALUES ('b') RETURNING id) INSERT INTO person_info (person_id) SELECT id from a")
<sqlalchemy.engine.result.ResultProxy object at 0x7f25e6c2a090>

But no new row was inserted:

# select id from person;
 id 
----
 a
(1 row)

In what way is running the query through the psql-client different from executing it through sqlalchemy?

1

2 Answers 2

3

My question got answered on github.

The solution is to wrap the execute in a transaction context:

with engine.begin() as conn:
   conn.execute("whatever")
Sign up to request clarification or add additional context in comments.

1 Comment

Consider closing the question as answered :-) Thanks for reporting.
1

I had a similar issue and the following code helped me. Without the conn.execute("COMMIT;") part, I was not able to see all my changes reflected in my database.

with self.engine.begin() as conn:
    conn.execute(sql_query)
    conn.execute("COMMIT;")

Comments

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.