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

Type Checking for Class Row Factory #60

Open
ms2892 opened this issue Feb 6, 2024 · 0 comments
Open

Type Checking for Class Row Factory #60

ms2892 opened this issue Feb 6, 2024 · 0 comments

Comments

@ms2892
Copy link

ms2892 commented Feb 6, 2024

As described in Issue #42 there was a proposed solution for having a Class Row Factory. Alongside the conversations happened there, there was a concern regarding type checking for the attributes of the class and output returned by the database. There doesn't seem to be a way to enforce type checking hence an extra __post_init__ method would be required within the class to enforce type checking. This can be overlooked by a lot of developers and can lead to a lot of type mismatches.

Solution

Define a Base class that our dataclasses can inherit. The Base class can have all the required methods for the validation etc.

The updated use of it can be described it here. The solution has been implemented on the PR #57

        >>> from dataclasses import dataclass
        >>> from comdb2.dataclasses.class_row_factory import BaseRowFactoryClass
        ...
        >>> @dataclass
        >>> class ABC(BaseRowFactoryClass):
        >>>     x: int
        >>>     y: int
        
        ...
        >>> conn.row_factory = ClassRowFactory(ABC)
        >>> row = conn.cursor().execute("select 1 as x, 2 as y").fetchone()
        >>> print(row)
        <>
        >>> print(row.x)
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