Skip to content

Conversation

@charlie-pecora
Copy link

#75 Implemented a basic sessionmaker class that returns an instance of the sqlmodel.Session by default (can be overridden by passing the class_ keyword argument to the sessionmaker)

A basic test showing the functionality:

from typing import Optional
from sqlmodel import SQLModel, Field, create_engine
from sqlmodel import Session, sessionmaker


class Test(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    a: str
    b: Optional[str] = None
    c: str = Field(default="Hey")
    d: str = "hey"

# tested both with local postgres & in-memory sqlite:
# sqlite_url = "postgresql://test:test@localhost:5432/test"
sqlite_url = "sqlite:///:memory:"
engine = create_engine(sqlite_url, echo=True)
SQLModel.metadata.drop_all(engine)
SQLModel.metadata.create_all(engine)

session = sessionmaker(engine)

with session() as _session:
    assert isinstance(_session, Session), "calling sessionmaker in a context manager did not produce a sqlmodel.Session instance"
    with session.begin():
        _session.add(Test(id=1, a="abc"))
        _session.commit()
    with _session.begin():
        test_results = _session.query(Test)
        test_result = test_results.first()
        assert test_result.a == "abc"
        assert isinstance(test_result.id, int)
        print(test_result)
        _session.commit()

I am not sure where it makes sense to test and show that sessionmaker is available in the docs.

@Zaffer
Copy link

Zaffer commented Mar 22, 2022

why closed? we need sessionmaker...

@msftcangoblowm
Copy link

For anyone in the future who comes here and also wants sqlmodel to have a sessionmaker implementation. Wondering why this PR was not merged. Be very thankful it wasn't!

The author simply really really wanted to wrap sessionmaker, but then didn't address the underlying issue. Now you have a wrapped sessionmaker that still won't work.

Look back at #75 for a temporary workaround and how to actually resolve the underlying issue. Then can come back and will realize [async_]sessionmaker are perfect as-is.

@msftcangoblowm msftcangoblowm mentioned this pull request Dec 24, 2025
8 tasks
This pull request was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants