✅ What does "persistent" mean?
In the context of SQLAlchemy (and databases):
A persistent object is one that is saved to the database and tracked by the database session.
So before calling .refresh()
or accessing certain data (like auto-generated IDs), SQLAlchemy must first know that the object actually exists in the database — that's when we say it's persistent.
🧠 Example in Simple Terms
Imagine this:
- You're writing a new report on paper (creating a
Report()
object). - You put it in the "send-to-database" tray with
db.add(report)
. ✅ Now the system knows you want to save it. - You hit "flush" with
await db.flush()
. This actually sends it to the database, but doesn't finalize/save it permanently yet. - Now that it's in the database (persistent), you can look up its ID or auto-generated fields — that's where
await db.refresh(report)
comes in. - Then finally,
await db.commit()
saves everything permanently.
✅ What does db.flush()
do?
- Sends pending data (like the new
Report
) to the database temporarily. - Makes sure the object exists in the database (so things like
report.id
get generated). - Does not commit/lock it yet.
Think of it like pressing "save" in a Word doc — but not clicking "submit."
✅ What does db.refresh(report)
do?
- Re-reads the data from the database, just in case something was updated (like
created_at
,id
, or a trigger). - Makes sure the object in memory has the latest database version.
It's like refreshing a web page to see the latest content.
🔁 In short:
Step | Description |
---|---|
db.add() |
Tells SQLAlchemy: "I want to save this." |
await db.flush() |
Actually sends it to the DB (now it's persistent) |
await db.refresh() |
Pulls the latest data for that object from DB |
await db.commit() |
Saves it permanently |