Skip to content

Commit

Permalink
enable search across beneficiary, note, reason, account in `/…
Browse files Browse the repository at this point in the history
…credits` endpoint (#120)
  • Loading branch information
andersy005 authored Sep 11, 2024
1 parent 11273dc commit b6efecb
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions offsets_db_api/routers/credits.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,16 @@ async def get_credits(
),
search: str | None = Query(
None,
description='Case insensitive search string. Currently searches on `project_id` and `name` fields only.',
description='Case insensitive search string. Currently searches in fields specified in `search_fileds` parameter',
),
search_fields: list[str] = Query(
default=[
'retirement_beneficiary',
'retirement_account',
'retirement_note',
'retirement_reason',
],
description='Fields to search in',
),
sort: list[str] = Query(
default=['project_id'],
Expand Down Expand Up @@ -76,19 +85,24 @@ async def get_credits(
operation=operation,
)

# Handle 'search' filter separately due to its unique logic
if search:
search_pattern = f'%{search}%'
statement = statement.where(
or_(
col(Project.project_id).ilike(search_pattern),
col(Project.name).ilike(search_pattern),
)
)
# Default to case-insensitive partial match
search_term = f'%{search}%'
search_conditions = []
for field in search_fields:
if field in Credit.__table__.columns:
search_conditions.append(getattr(Credit, field).ilike(search_term))
elif field in Project.__table__.columns:
search_conditions.append(getattr(Project, field).ilike(search_term))

if search_conditions:
statement = statement.where(or_(*search_conditions))

if sort:
statement = apply_sorting(statement=statement, sort=sort, model=Credit, primary_key='id')

logger.info(f"SQL Credits Query: {statement.compile(compile_kwargs={'literal_binds': True})}")

total_entries, current_page, total_pages, next_page, results = handle_pagination(
statement=statement,
primary_key=Credit.id,
Expand Down

0 comments on commit b6efecb

Please sign in to comment.