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

Populate primary key value for the row just inserted into DBAPI's lastrowid and SQLAlchemy's inserted_primary_key attributes #94

Open
amotl opened this issue Oct 6, 2022 · 0 comments

Comments

@amotl
Copy link
Member

amotl commented Oct 6, 2022

Problem

In SQLAlchemy (ORM) land, the standard is that the cursor object provides inserted_primary_key and lastrowid attributes. However, currently, both of them do not return anything sensible.

insert_stmt = table.insert(dict(name="John Doe", age=37))
cursor = engine.execute(insert_stmt)
print(cursor.inserted_primary_key)
print(cursor.lastrowid)
()
None

Motivation

dataset uses SQLAlchemy's inserted_primary_key attribute for returning the pk value from its insert method, see https://github.com/pudo/dataset/blob/1.5.2/dataset/table.py#L120-L121. It is important to make this work in order to be able to reference records just inserted, for manipulating them later, or for referencing them elsewhere.

Other statements

.inserted_primary_key returns a tuple of the primary key of the single inserted row using the connection.execute() command. A good reason to use .inserted_primary_key instead of .lastrowid: .lastrowid is database specific, it may work for some databases while not for others. But .inserted_primary_key will always work regardless of the underlying database.

-- https://stackoverflow.com/a/51258633

@amotl amotl changed the title Provide autogenerated primary key value for the row just inserted via DBAPI's lastrowid and SQLAlchemy's inserted_primary_key attributes Populate primary key value for the row just inserted into DBAPI's lastrowid and SQLAlchemy's inserted_primary_key attributes Mar 6, 2023
@amotl amotl transferred this issue from crate/crate-python Jun 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant