{"id":23044767,"url":"https://github.com/danishabdullah/algen","last_synced_at":"2025-08-14T23:31:27.479Z","repository":{"id":57409619,"uuid":"59009493","full_name":"danishabdullah/algen","owner":"danishabdullah","description":"Generate opnionated python ORM classes from yaml schema for sqlalchemy","archived":false,"fork":false,"pushed_at":"2019-03-28T05:34:35.000Z","size":25,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-08-08T20:14:27.711Z","etag":null,"topics":["cli","models","postgres","python","schema","sqlalchemy"],"latest_commit_sha":null,"homepage":null,"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/danishabdullah.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-05-17T09:36:46.000Z","updated_at":"2020-09-22T11:59:56.000Z","dependencies_parsed_at":"2022-08-24T18:50:59.703Z","dependency_job_id":null,"html_url":"https://github.com/danishabdullah/algen","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danishabdullah%2Falgen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danishabdullah%2Falgen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danishabdullah%2Falgen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danishabdullah%2Falgen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danishabdullah","download_url":"https://codeload.github.com/danishabdullah/algen/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229875318,"owners_count":18137801,"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":["cli","models","postgres","python","schema","sqlalchemy"],"created_at":"2024-12-15T21:15:11.249Z","updated_at":"2024-12-15T21:15:11.692Z","avatar_url":"https://github.com/danishabdullah.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Algen\n\nAlgen generates opionated ORM classes for sqlalchemy given a simple schema\neither as a commandline string or as a yaml file. It is designed to have\nminimal dependencies and is trivially extensible. A command line tool\nis bundled along to help generate the models. For DB specific types,\nonly postgres is currently supported. The tool currently assumes that\nsqlalchemy's declarative base object is to be imported like\n    ```from .alchemy_base import Base```\nThe library prefers making the code verbose rather than concise for the\nsake of having better auto-completion and help from your editor/IDE\ne.g. first style is preferred to the second one:\n```python\ndef update(self, a=None, b=None):\n    if a is not None:\n        self.a = a\n    if b is not None:\n        self.b = b\n```\n```python\ndef update(self, **kwargs):\n    for k,v in kwargs.items():\n        if hasattr(self, k) and v is not None:\n            setattr(self, k, v)\n```\n\n\n### CLI\n```bash\n$ algen --help\nUsage: algen [OPTIONS]\n\nOptions:\n  -n, --name TEXT         Name of model\n  -c, --columns TEXT      Column definition. e.g. col_name:col_type Can be\n                          used multiple times hence named columns. e.g. -c\n                          foo:Int -c bar:Unicode(20)\n  -d, --destination PATH  Destination directory. Default will assume 'models'\n                          directory inside the current working directory\n  -y, --yaml PATH         Yaml file describing the Model. This supersedes the\n                          column definition provided through --columns option.\n  --help                  Show this message and exit.\n```\n\nGiven a file as follows:\n```yaml\nPerson:\n  columns:\n    - name: id\n      type: BigInteger\n      primary_key: True\n      auto_increment: True\n    - name: name\n      type: Unicode(255)\n    - name: is_vip\n      type: Boolean\n    - name: created_at\n      type: DateTime(timezone=True)\n      server_default: now() at time zone 'utc'\n    - name: updated_at\n      type: DateTime(timezone=True)\n      server_default: now() at time zone 'utc'\n  relationships:\n    - name: addresses\n      class: Address\n      back_populates: 'person'\n\nAddress:\n  columns:\n    - name: id\n      type: BigInteger\n      primary_key: True\n      auto_increment: True\n    - name: line1\n      type: Unicode()\n    - name: line2\n      type: Unicode()\n    - name: line3\n      type: Unicode()\n    - name: postcode\n      type: Unicode(10)\n      index: True\n    - name: created_at\n      type: DateTime(timezone=True)\n      server_default: now() at time zone 'utc'\n    - name: updated_at\n      type: DateTime(timezone=True)\n      server_default: now() at time zone 'utc'\n  foreign_keys:\n    - name: person_id\n      type: BigInteger\n      reference:\n        table: persons\n        column: id\n      nullable: False\n  relationships:\n    - name: person\n      class: Person\n      back_populates: 'addresses'\n\n```\n\nThe cli tool will create two the following two files ```person.py```  and  ```address.py```.\n\n```python\nfrom __future__ import unicode_literals, absolute_import, print_function\n\nfrom collections import namedtuple\n\nfrom sqlalchemy import Column, Unicode, BigInteger, DateTime, ForeignKey\nfrom sqlalchemy.orm import relationship\n\n\nfrom .alchemy_base import Base\n\n__author__ = 'danishabdullah'\n\n\nclass Address(Base):\n    __tablename__ = 'addresses'\n\n    id = Column(BigInteger, auto_increment=True, primary_key=True)\n    line1 = Column(Unicode(), )\n    line2 = Column(Unicode(), )\n    line3 = Column(Unicode(), )\n    postcode = Column(Unicode(10), index=True)\n    created_at = Column(DateTime(timezone=True), server_default=\"now() at time zone 'utc'\")\n    updated_at = Column(DateTime(timezone=True), server_default=\"now() at time zone 'utc'\")\n\n    # --- Foreign Keys ---\n    person_id = Column(BigInteger, ForeignKey('persons.id'), nullable=False)\n\n    # --- Relationships ---\n    person = relationship('Person', back_populates='addresses')\n\n    def __init__(self, id=None, line1=None, line2=None, line3=None, postcode=None, created_at=None, updated_at=None, person_id=None):\n        self.id = id\n        self.line1 = line1\n        self.line2 = line2\n        self.line3 = line3\n        self.postcode = postcode\n        self.created_at = created_at\n        self.updated_at = updated_at\n        self.person_id = person_id\n\n    def add(self, session):\n        session.add(self)\n\n    def update(self, line1=None, line2=None, line3=None, postcode=None, created_at=None, updated_at=None, person_id=None):\n        # This function only updates a value if it is not None.\n        # Falsy values go through in the normal way.\n        # To set things to None use the usual syntax:\n        #    Address.column_name = None\n\n        if line1 is not None:\n            self.line1 = line1\n\n        if line2 is not None:\n            self.line2 = line2\n\n        if line3 is not None:\n            self.line3 = line3\n\n        if postcode is not None:\n            self.postcode = postcode\n\n        if created_at is not None:\n            self.created_at = created_at\n\n        if updated_at is not None:\n            self.updated_at = updated_at\n\n        if person_id is not None:\n            self.person_id = person_id\n\n    def delete(self, session):\n        session.delete(self)\n\n    def to_dict(self):\n        return {x: y for x, y in self.__dict__.items() if not x.startswith(\"_sa\")}\n\n    def get_proxy_cls(self):\n        # AddressProxy is useful when you want to persist data\n        # independent of the sqlalchemy session. It's just a namedtuple\n        # that has very low memory/cpu footprint compared the regular\n        # orm class instances.\n        keys = self.to_dict().keys()\n        name = \"AddressProxy\"\n        return namedtuple(name, keys)\n\n    def to_proxy(self):\n        # Proxy-ing is useful when you want to persist data\n        # independent of the sqlalchemy session. It's just a namedtuple\n        # that has very low memory/cpu footprint compared the regular\n        # orm class instances.\n        cls = self._get_proxy_cls()\n        return cls(**self.to_dict())\n\n    @classmethod\n    def from_proxy(cls, proxy):\n        return cls(**proxy._asdict())\n\n    def __hash__(self):\n        return hash(str(self.id))\n\n    def __eq__(self, other):\n        return (self.id == other.id)\n\n    def __neq__(self, other):\n        return not (self.id == other.id)\n\n    def __str__(self):\n        return \"\u003cAddress: {id}\u003e\".format(id=self.id)\n\n    def __unicode__(self):\n        return \"\u003cAddress: {id}\u003e\".format(id=self.id)\n\n    def __repr__(self):\n        return \"\u003cAddress: {id}\u003e\".format(id=self.id)\n\n```\n\n```python\nfrom __future__ import unicode_literals, absolute_import, print_function\n\nfrom collections import namedtuple\n\nfrom sqlalchemy import Column, Unicode, BigInteger, Boolean, DateTime\nfrom sqlalchemy.orm import relationship\n\n\nfrom .alchemy_base import Base\n\n__author__ = 'danishabdullah'\n\n\nclass Person(Base):\n    __tablename__ = 'persons'\n\n    id = Column(BigInteger, auto_increment=True, primary_key=True)\n    name = Column(Unicode(255), )\n    is_vip = Column(Boolean, )\n    created_at = Column(DateTime(timezone=True), server_default=\"now() at time zone 'utc'\")\n    updated_at = Column(DateTime(timezone=True), server_default=\"now() at time zone 'utc'\")\n\n    # --- Foreign Keys ---\n\n\n    # --- Relationships ---\n    addresses = relationship('Address', back_populates='person')\n\n    def __init__(self, id=None, name=None, is_vip=None, created_at=None, updated_at=None):\n        self.id = id\n        self.name = name\n        self.is_vip = is_vip\n        self.created_at = created_at\n        self.updated_at = updated_at\n\n    def add(self, session):\n        session.add(self)\n\n    def update(self, name=None, is_vip=None, created_at=None, updated_at=None):\n        # This function only updates a value if it is not None.\n        # Falsy values go through in the normal way.\n        # To set things to None use the usual syntax:\n        #    Person.column_name = None\n\n        if name is not None:\n            self.name = name\n\n        if is_vip is not None:\n            self.is_vip = is_vip\n\n        if created_at is not None:\n            self.created_at = created_at\n\n        if updated_at is not None:\n            self.updated_at = updated_at\n\n    def delete(self, session):\n        session.delete(self)\n\n    def to_dict(self):\n        return {x: y for x, y in self.__dict__.items() if not x.startswith(\"_sa\")}\n\n    def get_proxy_cls(self):\n        # PersonProxy is useful when you want to persist data\n        # independent of the sqlalchemy session. It's just a namedtuple\n        # that has very low memory/cpu footprint compared the regular\n        # orm class instances.\n        keys = self.to_dict().keys()\n        name = \"PersonProxy\"\n        return namedtuple(name, keys)\n\n    def to_proxy(self):\n        # Proxy-ing is useful when you want to persist data\n        # independent of the sqlalchemy session. It's just a namedtuple\n        # that has very low memory/cpu footprint compared the regular\n        # orm class instances.\n        cls = self._get_proxy_cls()\n        return cls(**self.to_dict())\n\n    @classmethod\n    def from_proxy(cls, proxy):\n        return cls(**proxy._asdict())\n\n    def __hash__(self):\n        return hash(str(self.id))\n\n    def __eq__(self, other):\n        return (self.id == other.id)\n\n    def __neq__(self, other):\n        return not (self.id == other.id)\n\n    def __str__(self):\n        return \"\u003cPerson: {id}\u003e\".format(id=self.id)\n\n    def __unicode__(self):\n        return \"\u003cPerson: {id}\u003e\".format(id=self.id)\n\n    def __repr__(self):\n        return \"\u003cPerson: {id}\u003e\".format(id=self.id)\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanishabdullah%2Falgen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanishabdullah%2Falgen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanishabdullah%2Falgen/lists"}