email = User.find(id=1).email
OK, that was easy. I just needed to get the
User object by
id then retrieve its email.
Now, try answering these questions:
- Was a database connection open when executing that line of code or was it open at a previous time?
- Are we using a connection from a database connection pool?
- How much data did we retrieve from the database?
- Do we need all the data retrieved from the database?
- Is that line of code fetching data from the database or is it accessing an internal cache?
- If there is a cache, when is it going to be refreshed?
- Does that line of code automatically commit to the database?
From reading that single line of code, I am unable to answer any of those questions.
Now, let’s try answering the previous questions with this code:
1 2 3 4 5
| conn = psycopg2.connect('postrges://...')
with conn.cursor() as cur:
conn.execute('SELECT email FROM users WHERE id=1')
email = conn.fetchall()
conn.commit() |
This snippet of code is more challenging to create because it requires understanding what we are doing. But, it is a lot simpler than the previous “one-liner”.
From the new code, we can answer all of the questions.
Partager