uriyyo / fastapi-pagination

FastAPI pagination 📖
https://uriyyo-fastapi-pagination.netlify.app/
MIT License
1.1k stars 126 forks source link

`count_query` seems to be not usable with `ext.sqlmodel.paginate` and `ext.sqlalchemy.paginate` #1193

Open moumoutte opened 2 weeks ago

moumoutte commented 2 weeks ago

I'm actually working on splitting query to get the total into the pagination with nested objects into the main query


query = select(Entity).join(Entity.retalated_entity)
return paginate(session, query, count_query=select(func.count()).select_from(Entity)

First, the fastapi_pagination.ext.sqlmodel.paginate do not expose the count_query parameters properly.

I suggest to complete the signutare function with


105 @no_type_check
106 def paginate(
107     session: Session,
108     query: Any,
109     params: Optional[AbstractParams] = None,
110     *,
111     count_query: Optional[Select] = None,  # adding the count_query kwargs to the signature
112     subquery_count: bool = True,
113     transformer: Optional[ItemsTransformer] = None,
114     additional_data: Optional[AdditionalData] = None,
115     unique: bool = True, 
116 ) -> Any:

Second, the fastapi_pagination.ext.sqlalchemy.paginate has an issue when using the count_query parameter.

When I'm trying to use it , I've got an error while interpreting the count_query.__bool__ cause of this line

https://github.com/uriyyo/fastapi-pagination/blob/main/fastapi_pagination/ext/sqlalchemy.py#L151

The following error is raised


    return exec_pagination(
../../../../.pyenv/versions/3.11.8/envs/app-core-3.11/lib/python3.11/site-packages/fastapi_pagination/ext/sqlalchemy.py:158: in exec_pagination
    count_query = count_query or create_count_query(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <sqlmodel.sql.expression.SelectOfScalar object at 0x7acc5a5f4910>

    def __bool__(self):
>       raise TypeError("Boolean value of this clause is not defined")
E       TypeError: Boolean value of this clause is not defined

By modifying it with something like that, it works fine.


157     if raw_params.include_total:
158         if count_query is None:
159             count_query = create_count_query(query, use_subquery=subquery_count)

Did I miss something ?

Thank you for your help.

uriyyo commented 2 weeks ago

Totally makes sense to me, we need to fix this issue. PR welcomed!

uriyyo commented 1 week ago

Fix will be include in next release