Skip to content

Commit

Permalink
database.table_view - add docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
MatteoCampinoti94 committed Nov 27, 2024
1 parent d4662bb commit ec1fa86
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions acacore/database/table_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@


class View(Generic[_M]):
"""
A class that represents a view in an SQLite database and allows accessing rows as Pydantic models.
:ivar database: The connection to the database.
:ivar model: The model the view is based on.
:ivar name: The name of the view.
:ivar select_stmt: The select statement used to create the view.
"""

def __init__(
self,
database: Connection,
Expand All @@ -20,6 +29,12 @@ def __init__(
select: str,
ignore: list[str] | None = None,
) -> None:
"""
:param model: The Pydantic model to create the view for.
:param name: The name of the view.
:param select: The select SQL expression to use to populate the view.
:param ignore: A list of field names to ignore from the model.
""" # noqa: D205
self.database: Connection = database
self.model: Type[_M] = model
self.name: str = name
Expand All @@ -42,9 +57,15 @@ def __contains__(self, where: _M) -> bool:
return self._table.select(where, limit=1).cursor.fetchone() is not None

def create_sql(self, *, exist_ok: bool = False) -> str:
"""Generate the SQL statement to create the view."""
return f"create view {'if not exists' if exist_ok else ''} {self.name} as {self.select_stmt}"

def create(self, *, exist_ok: bool = False) -> Self:
"""
Create the view in the connected database.
:param exist_ok: Whether to ignore any existing view with the same name.
"""
self.database.execute(self.create_sql(exist_ok=exist_ok))
return self

Expand All @@ -56,4 +77,16 @@ def select(
limit: int | None = None,
offset: int | None = None,
) -> Cursor[_M]:
"""
Select entries from the view.
:param where: The where statement to use. This can be a string, a dictionary containing column names and
values, or an instance of the model used by the table if primary keys have been defined.
:param params: The parameters to use for the query, they are ignored if the ``where`` argument is anything but
a string.
:param order_by: A list of column names and direction ("asc", "desc") tuples to sort the results.
:param limit: The maximum number of results to return.
:param offset: The offset to start the results from.
:return: A ``Cursor`` instance.
"""
return self._table.select(where, params, order_by, limit, offset)

0 comments on commit ec1fa86

Please sign in to comment.