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

Relationships Broken? #327

Closed
8 tasks done
brizzbuzz opened this issue May 4, 2022 · 8 comments
Closed
8 tasks done

Relationships Broken? #327

brizzbuzz opened this issue May 4, 2022 · 8 comments
Labels
question Further information is requested

Comments

@brizzbuzz
Copy link

brizzbuzz commented May 4, 2022

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

Hey, this is directly from the documentation here

from typing import List, Optional

from sqlmodel import Field, Relationship, Session, SQLModel, create_engine


class Team(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    headquarters: str

    heroes: List["Hero"] = Relationship(back_populates="team")


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    secret_name: str
    age: Optional[int] = Field(default=None, index=True)

    team_id: Optional[int] = Field(default=None, foreign_key="team.id")
    team: Optional[Team] = Relationship(back_populates="heroes")


sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"

engine = create_engine(sqlite_url, echo=True)


def create_db_and_tables():
    SQLModel.metadata.create_all(engine)


def create_heroes():
    with Session(engine) as session:
        team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
        team_z_force = Team(name="Z-Force", headquarters="Sister Margaret’s Bar")

        hero_deadpond = Hero(
            name="Deadpond", secret_name="Dive Wilson", team=team_z_force
        )
        hero_rusty_man = Hero(
            name="Rusty-Man", secret_name="Tommy Sharp", age=48, team=team_preventers
        )
        hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
        session.add(hero_deadpond)
        session.add(hero_rusty_man)
        session.add(hero_spider_boy)
        session.commit()

        session.refresh(hero_deadpond)
        session.refresh(hero_rusty_man)
        session.refresh(hero_spider_boy)

        print("Created hero:", hero_deadpond)
        print("Created hero:", hero_rusty_man)
        print("Created hero:", hero_spider_boy)

        hero_spider_boy.team = team_preventers
        session.add(hero_spider_boy)
        session.commit()
        session.refresh(hero_spider_boy)
        print("Updated hero:", hero_spider_boy)

        hero_black_lion = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
        hero_sure_e = Hero(name="Princess Sure-E", secret_name="Sure-E")
        team_wakaland = Team(
            name="Wakaland",
            headquarters="Wakaland Capital City",
            heroes=[hero_black_lion, hero_sure_e],
        )
        session.add(team_wakaland)
        session.commit()
        session.refresh(team_wakaland)
        print("Team Wakaland:", team_wakaland)

        hero_tarantula = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
        hero_dr_weird = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
        hero_cap = Hero(
            name="Captain North America", secret_name="Esteban Rogelios", age=93
        )

        team_preventers.heroes.append(hero_tarantula)
        team_preventers.heroes.append(hero_dr_weird)
        team_preventers.heroes.append(hero_cap)
        session.add(team_preventers)
        session.commit()
        session.refresh(hero_tarantula)
        session.refresh(hero_dr_weird)
        session.refresh(hero_cap)
        print("Preventers new hero:", hero_tarantula)
        print("Preventers new hero:", hero_dr_weird)
        print("Preventers new hero:", hero_cap)


def main():
    create_db_and_tables()
    create_heroes()


if __name__ == "__main__":
    main()

Description

When I run this (python 3.10.2, sqlmodel 0.0.6), I get the following error

Traceback (most recent call last):
  File "/Users/lappy/Workspace/unredundant/sourdough-py/src/heroes.py", line 102, in <module>
    main()
  File "/Users/lappy/Workspace/unredundant/sourdough-py/src/heroes.py", line 98, in main
    create_heroes()
  File "/Users/lappy/Workspace/unredundant/sourdough-py/src/heroes.py", line 83, in create_heroes
    team_preventers.heroes.append(hero_tarantula)
AttributeError: 'Team' object has no attribute 'heroes'

Operating System

macOS

Operating System Details

Apple Silicon, if that matters

SQLModel Version

0.0.6

Python Version

3.10.2

Additional Context

I'm a python n00b so hopefully this isn't just me doing something dumb 😅

@brizzbuzz brizzbuzz added the question Further information is requested label May 4, 2022
@brizzbuzz
Copy link
Author

I also tried pinning the SQLAlchemy version as mentioned in #315 and still face the same error :(

@belgianbluebear
Copy link

I encountered the same issue. Trying to downgrade SQLAlchemy to several previous versions did not fix, so I guess some 0.0.6 SQLmodel code relies on new SQLAlchemy code.

Is it planned to be fixed? I'm currently working on an implementation of our internal lib to migrate our FastAPI domain model from NOSQL Elasticsearch to SQL, using SQLModel to get the best of Pydantic and SQLAlchemy...

Thank you for your attention.

@byrman
Copy link
Contributor

byrman commented May 4, 2022

SQLModel 0.0.6 has SQLAlchemy = ">=1.4.17,<1.5.0" as a constraint, so you are bound to encounter #315. Are you sure downgrading was successful? Did you inspect pip list (or the poetry / etc equivalent)?

@synodriver
Copy link

Can confirm this with async mod.

@byrman
Copy link
Contributor

byrman commented May 4, 2022

I cannot reproduce this issue on macOS (Intel) with Python 3.9.10:

❯ pip install sqlmodel
Collecting sqlmodel
  Using cached sqlmodel-0.0.6-py3-none-any.whl (21 kB)
Collecting SQLAlchemy<1.5.0,>=1.4.17
  Using cached SQLAlchemy-1.4.36-cp39-cp39-macosx_10_15_x86_64.whl (1.5 MB)
Collecting sqlalchemy2-stubs
  Using cached sqlalchemy2_stubs-0.0.2a22-py3-none-any.whl (190 kB)
Collecting pydantic<2.0.0,>=1.8.2
  Using cached pydantic-1.9.0-cp39-cp39-macosx_10_9_x86_64.whl (2.9 MB)
Collecting typing-extensions>=3.7.4.3
  Using cached typing_extensions-4.2.0-py3-none-any.whl (24 kB)
Collecting greenlet!=0.4.17
  Using cached greenlet-1.1.2-cp39-cp39-macosx_10_14_x86_64.whl (92 kB)
Installing collected packages: typing-extensions, greenlet, sqlalchemy2-stubs, SQLAlchemy, pydantic, sqlmodel
Successfully installed SQLAlchemy-1.4.36 greenlet-1.1.2 pydantic-1.9.0 sqlalchemy2-stubs-0.0.2a22 sqlmodel-0.0.6 typing-extensions-4.2.0

~/Projects/issue327
❯ pip install -U SQLAlchemy==1.4.35
Collecting SQLAlchemy==1.4.35
  Using cached SQLAlchemy-1.4.35-cp39-cp39-macosx_10_15_x86_64.whl (1.5 MB)
Requirement already satisfied: greenlet!=0.4.17 in /Users/byrman/.virtualenvs/issue327/lib/python3.9/site-packages (from SQLAlchemy==1.4.35) (1.1.2)
Installing collected packages: SQLAlchemy
  Attempting uninstall: SQLAlchemy
    Found existing installation: SQLAlchemy 1.4.36
    Uninstalling SQLAlchemy-1.4.36:
      Successfully uninstalled SQLAlchemy-1.4.36
Successfully installed SQLAlchemy-1.4.35

~/Projects/issue327
❯ python3 --version
Python 3.9.10

~/Projects/issue327
❯ python3 main.py  # The code above runs fine!

But it fails on Apple silicon M1 and/or Python 3.10.2?

@brizzbuzz
Copy link
Author

Are you sure downgrading was successful? Did you inspect pip list (or the poetry / etc equivalent)?

Ah no, it looks like this was just me not knowing the steps required to downgrade. Once I explicitly removed sqlalchemy and then reinstalled it with the version explicitly set (I'm using poetry), it now works (tho I have not tried the async mod as someone else mentioned).

I'll leave it up to the maintainers if they want to close this issue and handle the async issue in a separate thread, or continue here :)

@byrman
Copy link
Contributor

byrman commented May 4, 2022

I have an async project myself that runs fine with 1.4.35 and fails with 1.4.36. I am pretty sure this issue is a duplicate of #315 and may be closed for that reason.

@bbeattie-phxlabs
Copy link

Broken again, it seems. See #315.

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

5 participants