Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does it work with Textual Statements #1349

Open
sombathoudom opened this issue Nov 1, 2024 · 1 comment
Open

Does it work with Textual Statements #1349

sombathoudom opened this issue Nov 1, 2024 · 1 comment
Assignees
Labels
question Further information is requested

Comments

@sombathoudom
Copy link

Does it work with Textual Statements?

Ex:
stmt = text("select * from users")
 return paginate(db, stmt)

@uriyyo uriyyo self-assigned this Nov 2, 2024
@uriyyo uriyyo added the question Further information is requested label Nov 2, 2024
@uriyyo
Copy link
Owner

uriyyo commented Nov 2, 2024

Hi @sombathoudom,

Yes, here is an example:

from faker import Faker
from pydantic import BaseModel
from sqlalchemy import create_engine, text
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, Session, mapped_column

from fastapi_pagination import Page, set_page, set_params, Params
from fastapi_pagination.ext.sqlalchemy import paginate

faker = Faker()

engine = create_engine("sqlite:///:memory:")


class Base(MappedAsDataclass, DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"

    name: Mapped[str]
    email: Mapped[str]

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, default=None)


class UserSchema(BaseModel):
    id: int
    name: str
    email: str


Base.metadata.create_all(bind=engine)

session = Session(engine)

with session.begin():
    session.add_all([User(name=faker.name(), email=faker.email()) for _ in range(100)])

set_page(Page[UserSchema])
set_params(Params(size=5, page=2))

with session.begin():
    page = paginate(session, text("SELECT * FROM users"))

print(page.model_dump_json(indent=2))
{
  "items": [
    {
      "id": 6,
      "name": "Mark Snyder",
      "email": "[email protected]"
    },
    {
      "id": 7,
      "name": "Scott Moreno",
      "email": "[email protected]"
    },
    {
      "id": 8,
      "name": "Melissa Parker",
      "email": "[email protected]"
    },
    {
      "id": 9,
      "name": "David Walker",
      "email": "[email protected]"
    },
    {
      "id": 10,
      "name": "Timothy Patton",
      "email": "[email protected]"
    }
  ],
  "total": 100,
  "page": 2,
  "size": 5,
  "pages": 20
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants