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

results.dict() method for SQL query results #2414

Closed
simonw opened this issue Sep 2, 2024 · 2 comments
Closed

results.dict() method for SQL query results #2414

simonw opened this issue Sep 2, 2024 · 2 comments

Comments

@simonw
Copy link
Owner

simonw commented Sep 2, 2024

I find myself using this pattern all the time:

rows = [dict(r) for r in (await db.execute("select * from t"))]

I'm going to add a utility method like this:

rows = (await db.execute("select * from t")).dicts()

Relevant code:

class Results:
def __init__(self, rows, truncated, description):
self.rows = rows
self.truncated = truncated
self.description = description
@property
def columns(self):
return [d[0] for d in self.description]
def first(self):
if self.rows:
return self.rows[0]
else:
return None
def single_value(self):
if self.rows and 1 == len(self.rows) and 1 == len(self.rows[0]):
return self.rows[0][0]
else:
raise MultipleValues
def __iter__(self):
return iter(self.rows)
def __len__(self):
return len(self.rows)

@simonw
Copy link
Owner Author

simonw commented Sep 2, 2024

Could I get it to work like this instead?

rows = await db.execute("select * from t").dicts()

Bounced the idea through Claude: https://gist.github.com/simonw/c6b7d46da9e145676f6f1c0785e518c3 - but I don't think I'm going to do it. It's just a little bit complicated to explain to end users, especially if they don't use it quite right and have to untangle what happened.

@simonw simonw closed this as completed in 92c4d41 Sep 2, 2024
simonw added a commit that referenced this issue Sep 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants
@simonw and others