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

Database.query: use DataClassRowFactory + AttrDict #6

Open
pydanny opened this issue Dec 19, 2024 · 0 comments
Open

Database.query: use DataClassRowFactory + AttrDict #6

pydanny opened this issue Dec 19, 2024 · 0 comments

Comments

@pydanny
Copy link
Contributor

pydanny commented Dec 19, 2024

https://rogerbinns.github.io/apsw/example.html#accessing-results-by-column-name

Right now we return a generator of dictionaries, we want to change to using AttrDict to improve the UI. In essence allowing this behavior:

for row in db.table.query(stmt):
    print(row['title']) # <-- Current
    print(row.title) # <-- What we want to add

Code implementation

As determined from discovery in #7, convert this:

class Database
    def query(
        self, sql: str, params: Optional[Union[Iterable, dict]] = None
    ) -> Generator[dict, None, None]:
        """
        Execute ``sql`` and return an iterable of dictionaries representing each row.

        :param sql: SQL query to execute
        :param params: Parameters to use in that query - an iterable for ``where id = ?``
          parameters, or a dictionary for ``where id = :id``
        """
        cursor = self.execute(sql, tuple(params or tuple()))
        try: columns = [c[0] for c in cursor.description]
        except apsw.ExecutionCompleteError: return []
        for row in cursor:
            yield dict(zip(columns, row))

to:

class Database:
    def query(
        self, sql: str, params: Optional[Union[Iterable, dict]] = None
    ) -> Generator[dict, None, None]:
        cursor = self.execute(sql, tuple(params or tuple()))
        # Row results will be dataclasses
        cursor.row_trace = apsw.ext.DataClassRowFactory(
            dataclass_kwargs={"frozen": True}
        )                
        # Yield attrdict so rows can be accessed as row.id or row['id']
        for row in cursor: yield AttrDict(row.__dict__)        
        # Cleanup the row_trace
        cursor.row_trace = None    
@pydanny pydanny changed the title Use DataClassRowFactory Database.query: use DataClassRowFactory + AttrDict Dec 23, 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