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

Nullable relationships require Optional #276

Open
2 tasks done
amacfie opened this issue Aug 4, 2023 · 0 comments
Open
2 tasks done

Nullable relationships require Optional #276

amacfie opened this issue Aug 4, 2023 · 0 comments
Labels

Comments

@amacfie
Copy link

amacfie commented Aug 4, 2023

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

Sqlacodegen version

master (66a88dc)

SQLAlchemy version

2.0.19

RDBMS vendor

PostgreSQL

What happened?

Using --generator declarative I get

from typing import List, Optional

from sqlalchemy import ForeignKeyConstraint, Integer, PrimaryKeyConstraint
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

class Base(DeclarativeBase):
    pass


class Refers(Base):
    __tablename__ = 'refers'
    __table_args__ = (
        ForeignKeyConstraint(['parent_id'], ['refers.id'], name='refers_parent_id_fkey'),
        PrimaryKeyConstraint('id', name='refers_pkey')
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    parent_id: Mapped[Optional[int]] = mapped_column(Integer)

    parent: Mapped['Refers'] = relationship('Refers', remote_side=[id], back_populates='parent_reverse')
    parent_reverse: Mapped[List['Refers']] = relationship('Refers', remote_side=[parent_id], back_populates='parent')

I believe the type of parent should be Mapped[Optional['Refers']]. SQLAlchemy docs reference.

Database schema for reproducing the bug

CREATE TABLE refers (
    id        SERIAL  PRIMARY KEY,
    parent_id INTEGER,
    FOREIGN KEY (parent_id) REFERENCES refers(id)
);
@amacfie amacfie added the bug label Aug 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant