Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WITH statement in raw text query does nothing #5090

Closed
mmEissen opened this issue Jan 12, 2020 · 2 comments
Closed

WITH statement in raw text query does nothing #5090

mmEissen opened this issue Jan 12, 2020 · 2 comments
Labels
question issue where a "fix" on the SQLAlchemy side is unlikely, hence more of a usage question

Comments

@mmEissen
Copy link

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 returns successfully:

>>> 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)
@zzzeek
Copy link
Member

zzzeek commented Jan 12, 2020

hi there -

this statement will not autocommit automatically, you should use a transaction:

with engine.begin() as conn:
   conn.execute("whatever")

while the above documentation refers to using the autocommit=True option, long term the whole "autocommit" concept is going away as well as connectionless execution (e.g. engine.execute()) because of this confusion, so it's best to just use "with engine.begin() as conn": for all your operations as that will be the API going forward long term.

@zzzeek zzzeek added the question issue where a "fix" on the SQLAlchemy side is unlikely, hence more of a usage question label Jan 12, 2020
@mmEissen
Copy link
Author

Thank you so much! This has caused me so much headache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question issue where a "fix" on the SQLAlchemy side is unlikely, hence more of a usage question
Projects
None yet
Development

No branches or pull requests

2 participants