{"id":15065854,"url":"https://github.com/strawberry-graphql/strawberry-sqlalchemy","last_synced_at":"2025-05-16T12:03:23.288Z","repository":{"id":37562747,"uuid":"464031545","full_name":"strawberry-graphql/strawberry-sqlalchemy","owner":"strawberry-graphql","description":"A SQLAlchemy Integration for strawberry-graphql","archived":false,"fork":false,"pushed_at":"2024-10-29T17:58:58.000Z","size":367,"stargazers_count":92,"open_issues_count":20,"forks_count":27,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-10-29T22:32:08.356Z","etag":null,"topics":["database","graphql","hacktoberfest","strawberry","strawberry-graphql"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/strawberry-graphql.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.rst","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.rst","dei":null,"publiccode":null,"codemeta":null},"funding":{"polar":"strawberry-graphql","open_collective":"strawberry-graphql","github":"strawberry-graphql"}},"created_at":"2022-02-27T03:55:38.000Z","updated_at":"2024-10-25T19:31:24.000Z","dependencies_parsed_at":"2023-09-22T00:53:02.092Z","dependency_job_id":"b260d21a-910c-4829-b872-6ff8d485d751","html_url":"https://github.com/strawberry-graphql/strawberry-sqlalchemy","commit_stats":{"total_commits":75,"total_committers":19,"mean_commits":"3.9473684210526314","dds":0.8266666666666667,"last_synced_commit":"d1fc06978ce23ff134188dd4e9f0c8b48a390096"},"previous_names":["expedock/strawberry-sqlalchemy-mapper"],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/strawberry-graphql%2Fstrawberry-sqlalchemy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/strawberry-graphql%2Fstrawberry-sqlalchemy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/strawberry-graphql%2Fstrawberry-sqlalchemy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/strawberry-graphql%2Fstrawberry-sqlalchemy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/strawberry-graphql","download_url":"https://codeload.github.com/strawberry-graphql/strawberry-sqlalchemy/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247980836,"owners_count":21027808,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","graphql","hacktoberfest","strawberry","strawberry-graphql"],"created_at":"2024-09-25T00:55:41.057Z","updated_at":"2025-04-09T05:07:12.038Z","avatar_url":"https://github.com/strawberry-graphql.png","language":"Python","funding_links":["https://polar.sh/strawberry-graphql","https://opencollective.com/strawberry-graphql","https://github.com/sponsors/strawberry-graphql"],"categories":[],"sub_categories":[],"readme":"# strawberry-sqlalchemy-mapper\n\n\nStrawberry-sqlalchemy-mapper is the simplest way to implement autogenerated strawberry types for columns and relationships in SQLAlchemy models.\n\n\n- Instead of manually listing every column and relationship in a SQLAlchemy model, strawberry-sqlalchemy-mapper\nlets you decorate a class declaration and it will automatically generate the necessary strawberry fields\nfor all columns and relationships (subject to the limitations below) in the given model.\n\n- Native support for most of SQLAlchemy's most common types.\n- Extensible to arbitrary custom SQLAlchemy types.\n- Automatic batching of queries, avoiding N+1 queries when getting relationships\n- Support for SQLAlchemy \u003e=1.4.x\n- Lightweight and fast.\n\n## Getting Started\n\nstrawberry-sqlalchemy-mapper is available on [PyPi](https://pypi.org/project/strawberry-sqlalchemy-mapper/)\n\n```\npip install strawberry-sqlalchemy-mapper\n```\n\n\nFirst, define your sqlalchemy model:\n\n```python\n# models.py\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\nclass Employee(Base):\n    __tablename__ = \"employee\"\n    id = Column(UUID, primary_key=True)\n    name = Column(String, nullable=False)\n    password_hash = Column(String, nullable=False)\n    department_id = Column(UUID, ForeignKey(\"department.id\"))\n    department = relationship(\"Department\", back_populates=\"employees\")\n\n\nclass Department(Base):\n    __tablename__ = \"department\"\n    id = Column(UUID, primary_key=True)\n    name = Column(String, nullable=False)\n    employees = relationship(\"Employee\", back_populates=\"department\")\n```\n\nNext, decorate a type with `strawberry_sqlalchemy_mapper.type()`\nto register it as a strawberry type for the given SQLAlchemy model.\nThis will automatically add fields for the model's columns, relationships, association proxies,\nand hybrid properties. For example:\n\n```python\n# elsewhere\n# ...\nfrom strawberry_sqlalchemy_mapper import StrawberrySQLAlchemyMapper\n\nstrawberry_sqlalchemy_mapper = StrawberrySQLAlchemyMapper()\n\n\n@strawberry_sqlalchemy_mapper.type(models.Employee)\nclass Employee:\n    __exclude__ = [\"password_hash\"]\n\n\n@strawberry_sqlalchemy_mapper.type(models.Department)\nclass Department:\n    pass\n\n\n@strawberry.type\nclass Query:\n    @strawberry.field\n    def departments(self):\n        return db.session.scalars(select(models.Department)).all()\n\n\n# context is expected to have an instance of StrawberrySQLAlchemyLoader\nclass CustomGraphQLView(GraphQLView):\n    def get_context(self):\n        return {\n            \"sqlalchemy_loader\": StrawberrySQLAlchemyLoader(bind=YOUR_SESSION),\n        }\n\n\n# call finalize() before using the schema:\n# (note that models that are related to models that are in the schema\n# are automatically mapped at this stage -- e.g., Department is mapped\n# because employee.department is a relationshp to Department)\nstrawberry_sqlalchemy_mapper.finalize()\n# only needed if you have polymorphic types\nadditional_types = list(strawberry_sqlalchemy_mapper.mapped_types.values())\nschema = strawberry.Schema(\n    query=Query,\n    mutation=Mutation,\n    extensions=extensions,\n    types=additional_types,\n)\n\n# You can now query, e.g.:\n\"\"\"\nquery {\n    departments {\n        id\n        name\n        employees {\n            edge {\n                node {\n                    id\n                    name\n                    department {\n                        # Just an example of nested relationships\n                        id\n                        name\n                    }\n                }\n            }\n        }\n    }\n}\n\"\"\"\n```\n\n## Limitations\n\nSQLAlchemy Models -\u003e Strawberry Types and Interfaces are expected to have a consistent\n(customizable) naming convention. These can be configured by passing `model_to_type_name`\nand `model_to_interface_name` when constructing the mapper.\n\nNatively supports the following SQLAlchemy types:\n\n```python\nInteger: int,\nFloat: float,\nBigInteger: BigInt,\nNumeric: Decimal,\nDateTime: datetime,\nDate: date,\nTime: time,\nString: str,\nText: str,\nBoolean: bool,\nUnicode: str,\nUnicodeText: str,\nSmallInteger: int,\nSQLAlchemyUUID: uuid.UUID,\nVARCHAR: str,\nARRAY[T]: List[T] # PostgreSQL array\nJSON: JSON # SQLAlchemy JSON\nEnum: (the Python enum it is mapped to, which should be @strawberry.enum-decorated)\n```\n\nAdditional types can be supported by passing `extra_sqlalchemy_type_to_strawberry_type_map`,\nalthough support for `TypeDecorator` types is untested.\n\nAssociation proxies are expected to be of the form `association_proxy('relationship1', 'relationship2')`,\ni.e., both properties are expected to be relationships.\n\nRoots of polymorphic hierarchies **are supported**, but are also expected to be registered via\n`strawberry_sqlalchemy_mapper.interface()`, and its concrete type and\nits descendants are expected to inherit from the interface:\n\n```python\nclass Book(Model):\n    id = Column(UUID, primary_key=True)\n\n\nclass Novel(Book):\n    pass\n\n\nclass ShortStory(Book):\n    pass\n\n\n# in another file\nstrawberry_sqlalchemy_mapper = StrawberrySQLAlchemyMapper()\n\n\n@strawberry_sqlalchemy_mapper.interface(models.Book)\nclass BookInterface:\n    pass\n\n\n@strawberry_sqlalchemy_mapper.type(models.Book)\nclass Book:\n    pass\n\n\n@strawberry_sqlalchemy_mapper.type(models.Novel)\nclass Novel:\n    pass\n\n\n@strawberry_sqlalchemy_mapper.type(models.ShortStory)\nclass ShortStory:\n    pass\n```\n\n## Contributing\n\nWe encourage you to contribute to strawberry-sqlalchemy-mapper! Any contributions you make are greatly appreciated.\n\nIf you have a suggestion that would make this better, please fork the repo and create a pull request. Don't forget to give the project a star! Thanks again!\n\n1. Fork the Project\n2. Create your Feature Branch (git checkout -b feature)\n3. Commit your Changes (git commit -m 'Add some feature')\n4. Push to the Branch (git push origin feature)\n5. Open a Pull Request\n\nFor more details on how to contribute, as well as how to setup the project on your local machine, please refer to [the docs](CONTRIBUTING.rst)\n\n\n### Prerequisites\n\nThis project uses `pre-commit`_, please make sure to install it before making any\nchanges::\n\n    pip install pre-commit\n    cd strawberry-sqlalchemy-mapper\n    pre-commit install\n\nIt is a good idea to update the hooks to the latest version::\n\n    pre-commit autoupdate\n\nDon't forget to tell your contributors to also install and use pre-commit.\n\n### Installation\n\n```bash\npip install -r requirements.txt\n```\n\nInstall [PostgreSQL 14+](https://www.postgresql.org/download/)\n\n### Test\n\n```bash\npytest\n```\n\n## ⚖️ LICENSE\n\nMIT © [strawberry-sqlalchemy-mapper](LICENSE.txt)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstrawberry-graphql%2Fstrawberry-sqlalchemy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstrawberry-graphql%2Fstrawberry-sqlalchemy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstrawberry-graphql%2Fstrawberry-sqlalchemy/lists"}