orm: Add SELECT generation
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Val Lorentz 2022-09-20 21:28:34 +02:00
parent 8abf869c13
commit 826c6f73f1
3 changed files with 15 additions and 6 deletions

View File

@ -16,5 +16,4 @@
Database management
"""
from . import models, orm # noqa
from .db import Db # noqa

View File

@ -50,11 +50,10 @@ class Db:
"""
Returns the last snapshot of the given IRI.
"""
with self.conn.cursor(
row_factory=psycopg.rows.class_row(models.WebPageSnapshot)
) as cur:
cur.execute("SELECT * FROM web_page_snapshot WHERE url=%s", (url,))
return cur.fetchone()
snapshots = models.WebPageSnapshot.select(
self.conn, "WHERE url=%s ORDER BY snapshot_date DESC LIMIT 1", (url,)
)
return next(snapshots, None)
def add_web_page_snapshots(
self, snapshots: typing.Iterable[models.WebPageSnapshot]

View File

@ -137,6 +137,17 @@ class BaseModel:
)
copy.write_row(row)
@classmethod
def select(
cls: type[_TSelf], conn: psycopg.Connection, clauses: str, params: tuple
) -> typing.Iterator[_TSelf]:
"""
Selects objects from the corresponding table and yields instances of this class.
"""
with conn.cursor(row_factory=psycopg.rows.class_row(cls)) as cur:
cur.execute(f"SELECT * FROM {cls.TABLE} {clauses}", params)
yield from cur
@classmethod
def db_schema(cls) -> str:
"""