Skip to content

Commit

Permalink
repos use query builder
Browse files Browse the repository at this point in the history
  • Loading branch information
TrueRou authored and arily committed Dec 5, 2023
1 parent 854f39a commit ba2b1c1
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 195 deletions.
28 changes: 13 additions & 15 deletions app/repositories/achievements.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import app.state.services
from app._typing import _UnsetSentinel
from app._typing import UNSET
from app.query_builder import build as bq

if TYPE_CHECKING:
from app.objects.score import Score
Expand Down Expand Up @@ -88,17 +89,13 @@ async def fetch_one(
"""Fetch a single achievement."""
if id is None and name is None:
raise ValueError("Must provide at least one parameter.")

query, params = bq(
f"SELECT {READ_PARAMS} FROM achievements WHERE 1 = 1",
(id, "id = :id"),
(name, "name = :name"),
)

query = f"""\
SELECT {READ_PARAMS}
FROM achievements
WHERE id = COALESCE(:id, id)
OR name = COALESCE(:name, name)
"""
params: dict[str, Any] = {
"id": id,
"name": name,
}
rec = await app.state.services.database.fetch_one(query, params)

if rec is None:
Expand Down Expand Up @@ -170,12 +167,13 @@ async def update(
update_fields["desc"] = desc
if not isinstance(cond, _UnsetSentinel):
update_fields["cond"] = cond

query = (
"UPDATE achievements SET",
",".join(f"{k} = :{k}" for k in update_fields),
"WHERE id = :id",
)

query = f"""\
UPDATE achievements
SET {",".join(f"{k} = COALESCE(:{k}, {k})" for k in update_fields)}
WHERE id = :id
"""
values = {"id": id} | update_fields
await app.state.services.database.execute(query, values)

Expand Down
82 changes: 34 additions & 48 deletions app/repositories/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import app.state.services
from app._typing import _UnsetSentinel
from app._typing import UNSET
from app.query_builder import build as bq

# +------------+--------------+------+-----+---------+----------------+
# | Field | Type | Null | Key | Default | Extra |
Expand Down Expand Up @@ -88,16 +89,13 @@ async def fetch_one(
"""Fetch a single channel."""
if id is None and name is None:
raise ValueError("Must provide at least one parameter.")
query = f"""\
SELECT {READ_PARAMS}
FROM channels
WHERE id = COALESCE(:id, id)
AND name = COALESCE(:name, name)
"""
params: dict[str, Any] = {
"id": id,
"name": name,
}

query, params = bq(
f"SELECT {READ_PARAMS} FROM channels WHERE 1 = 1",
(id, "id = :id"),
(name, "name = :name"),
)

channel = await app.state.services.database.fetch_one(query, params)

return cast(Channel, dict(channel._mapping)) if channel is not None else None
Expand All @@ -110,19 +108,13 @@ async def fetch_count(
) -> int:
if read_priv is None and write_priv is None and auto_join is None:
raise ValueError("Must provide at least one parameter.")

query = """\
SELECT COUNT(*) AS count
FROM channels
WHERE read_priv = COALESCE(:read_priv, read_priv)
AND write_priv = COALESCE(:write_priv, write_priv)
AND auto_join = COALESCE(:auto_join, auto_join)
"""
params: dict[str, Any] = {
"read_priv": read_priv,
"write_priv": write_priv,
"auto_join": auto_join,
}

query, params = bq(
"SELECT COUNT(*) count FROM channels WHERE 1 = 1",
(read_priv, "read_priv = :read_priv"),
(write_priv, "write_priv = :write_priv"),
(auto_join, "auto_join = :auto_join"),
)

rec = await app.state.services.database.fetch_one(query, params)
assert rec is not None
Expand All @@ -137,26 +129,19 @@ async def fetch_many(
page_size: int | None = None,
) -> list[Channel]:
"""Fetch multiple channels from the database."""
query = f"""\
SELECT {READ_PARAMS}
FROM channels
WHERE read_priv = COALESCE(:read_priv, read_priv)
AND write_priv = COALESCE(:write_priv, write_priv)
AND auto_join = COALESCE(:auto_join, auto_join)
"""
params: dict[str, Any] = {
"read_priv": read_priv,
"write_priv": write_priv,
"auto_join": auto_join,
}

if page is not None and page_size is not None:
query += """\
LIMIT :limit
OFFSET :offset
"""
params["limit"] = page_size
params["offset"] = (page - 1) * page_size
query, params = bq(
f"SELECT {READ_PARAMS} FROM channels WHERE 1 = 1",
(read_priv, "read_priv = :read_priv"),
(write_priv, "write_priv = :write_priv"),
(auto_join, "auto_join = :auto_join"),
(
(page_size, "LIMIT :page_size"),
lambda: (
(page - 1) * page_size if page is not None else None,
"OFFSET :offset",
),
),
)

channels = await app.state.services.database.fetch_all(query, params)
return cast(list[Channel], [dict(c._mapping) for c in channels])
Expand All @@ -179,12 +164,13 @@ async def update(
update_fields["write_priv"] = write_priv
if not isinstance(auto_join, _UnsetSentinel):
update_fields["auto_join"] = auto_join

query = (
"UPDATE channels SET",
",".join(f"{k} = :{k}" for k in update_fields),
"WHERE name = :name",
)

query = f"""\
UPDATE channels
SET {",".join(f"{k} = COALESCE(:{k}, {k})" for k in update_fields)}
WHERE name = :name
"""
values = {"name": name} | update_fields
await app.state.services.database.execute(query, values)

Expand Down
29 changes: 15 additions & 14 deletions app/repositories/clans.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import app.state.services
from app._typing import _UnsetSentinel
from app._typing import UNSET
from app.query_builder import build as bq

# +------------+-------------+------+-----+---------+----------------+
# | Field | Type | Null | Key | Default | Extra |
Expand Down Expand Up @@ -81,16 +82,15 @@ async def fetch_one(
"""Fetch a single clan from the database."""
if id is None and name is None and tag is None and owner is None:
raise ValueError("Must provide at least one parameter.")

query, params = bq(
f"SELECT {READ_PARAMS} FROM clans WHERE 1 = 1",
(id, "id = :id"),
(name, "name = :name"),
(tag, "tag = :tag"),
(owner, "owner = :owner"),
)

query = f"""\
SELECT {READ_PARAMS}
FROM clans
WHERE id = COALESCE(:id, id)
AND name = COALESCE(:name, name)
AND tag = COALESCE(:tag, tag)
AND owner = COALESCE(:owner, owner)
"""
params: dict[str, Any] = {"id": id, "name": name, "tag": tag, "owner": owner}
clan = await app.state.services.database.fetch_one(query, params)

return cast(Clan, dict(clan._mapping)) if clan is not None else None
Expand Down Expand Up @@ -144,12 +144,13 @@ async def update(
update_fields["tag"] = tag
if not isinstance(owner, _UnsetSentinel):
update_fields["owner"] = owner

query = (
"UPDATE clans SET",
",".join(f"{k} = :{k}" for k in update_fields),
"WHERE id = :id",
)

query = f"""\
UPDATE clans
SET {",".join(f"{k} = :{k}" for k in update_fields)}
WHERE id = :id
"""
values = {"id": id} | update_fields
await app.state.services.database.execute(query, values)

Expand Down
53 changes: 21 additions & 32 deletions app/repositories/ingame_logins.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing import Any
from typing import cast
from typing import TypedDict
from app.query_builder import build as bq

import app.state.services

Expand Down Expand Up @@ -96,16 +97,12 @@ async def fetch_count(
ip: str | None = None,
) -> int:
"""Fetch the number of logins in the database."""
query = """\
SELECT COUNT(*) AS count
FROM ingame_logins
WHERE userid = COALESCE(:userid, userid)
AND ip = COALESCE(:ip, ip)
"""
params: dict[str, Any] = {
"userid": user_id,
"ip": ip,
}
query, params = bq(
"SELECT COUNT(*) count FROM ingame_logins WHERE 1 = 1",
(user_id, "userid = :userid"),
(ip, "ip = :ip"),
)

rec = await app.state.services.database.fetch_one(query, params)
assert rec is not None
return cast(int, rec._mapping["count"])
Expand All @@ -120,28 +117,20 @@ async def fetch_many(
page_size: int | None = None,
) -> list[IngameLogin]:
"""Fetch a list of logins from the database."""
query = f"""\
SELECT {READ_PARAMS}
FROM ingame_logins
WHERE userid = COALESCE(:userid, userid)
AND ip = COALESCE(:ip, ip)
AND osu_ver = COALESCE(:osu_ver, osu_ver)
AND osu_stream = COALESCE(:osu_stream, osu_stream)
"""
params: dict[str, Any] = {
"userid": user_id,
"ip": ip,
"osu_ver": osu_ver,
"osu_stream": osu_stream,
}

if page is not None and page_size is not None:
query += """\
LIMIT :limit
OFFSET :offset
"""
params["limit"] = page_size
params["offset"] = (page - 1) * page_size
query, params = bq(
f"SELECT {READ_PARAMS} FROM ingame_logins WHERE 1 = 1",
(user_id, "userid = :userid"),
(ip, "ip = :ip"),
(osu_ver, "osu_ver = :osu_ver"),
(osu_stream, "osu_stream = :osu_stream"),
(
(page_size, "LIMIT :page_size"),
lambda: (
(page - 1) * page_size if page is not None else None,
"OFFSET :offset",
),
),
)

ingame_logins = await app.state.services.database.fetch_all(query, params)
return cast(list[IngameLogin], ingame_logins)
Loading

0 comments on commit ba2b1c1

Please sign in to comment.