{"id":17151932,"url":"https://github.com/dancardin/sqlalchemy-declarative-extensions","last_synced_at":"2025-04-05T22:10:49.557Z","repository":{"id":45462537,"uuid":"213905338","full_name":"DanCardin/sqlalchemy-declarative-extensions","owner":"DanCardin","description":"Library to declare additional kinds of objects not natively supported by SqlAlchemy/Alembic.","archived":false,"fork":false,"pushed_at":"2024-11-12T14:41:04.000Z","size":918,"stargazers_count":40,"open_issues_count":1,"forks_count":9,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-03-29T19:06:57.605Z","etag":null,"topics":["alembic","autogenerate","database","declarative","grant","postgresql","role","sqlalchemy","trigger"],"latest_commit_sha":null,"homepage":"https://sqlalchemy-declarative-extensions.readthedocs.io/en/latest/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DanCardin.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"DanCardin"}},"created_at":"2019-10-09T11:54:25.000Z","updated_at":"2025-03-27T14:01:38.000Z","dependencies_parsed_at":"2023-02-19T11:01:10.698Z","dependency_job_id":"72efe72f-cfca-4cda-94e8-8f92d7ca4db1","html_url":"https://github.com/DanCardin/sqlalchemy-declarative-extensions","commit_stats":{"total_commits":127,"total_committers":6,"mean_commits":"21.166666666666668","dds":0.09448818897637801,"last_synced_commit":"9ca07141eaae48e667a08422c8b742c4498ce094"},"previous_names":[],"tags_count":57,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fsqlalchemy-declarative-extensions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fsqlalchemy-declarative-extensions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fsqlalchemy-declarative-extensions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DanCardin%2Fsqlalchemy-declarative-extensions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DanCardin","download_url":"https://codeload.github.com/DanCardin/sqlalchemy-declarative-extensions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247406111,"owners_count":20933806,"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":["alembic","autogenerate","database","declarative","grant","postgresql","role","sqlalchemy","trigger"],"created_at":"2024-10-14T21:42:25.235Z","updated_at":"2025-04-05T22:10:49.522Z","avatar_url":"https://github.com/DanCardin.png","language":"Python","readme":"# SQLAlchemy Declarative Extensions\n\n[![Actions Status](https://github.com/DanCardin/sqlalchemy-declarative-extensions/actions/workflows/test.yml/badge.svg)](https://github.com/dancardin/sqlalchemy-declarative-extensions/actions)\n[![codecov](https://codecov.io/gh/DanCardin/sqlalchemy-declarative-extensions/graph/badge.svg?token=DyS4xtntRo)](https://codecov.io/gh/DanCardin/sqlalchemy-declarative-extensions)\n[![Documentation Status](https://readthedocs.org/projects/sqlalchemy-declarative-extensions/badge/?version=latest)](https://sqlalchemy-declarative-extensions.readthedocs.io/en/latest/?badge=latest)\n\nSee the full documentation\n[here](https://sqlalchemy-declarative-extensions.readthedocs.io/en/latest/).\n\nAdds extensions to SQLAlchemy (and/or Alembic) which allows declaratively\nstating the existence of additional kinds of objects about your database not\nnatively supported by SQLAlchemy/Alembic.\n\nThe primary function(s) of this library include:\n\n- Registering onto the SQLAlchemy event system such that `metadata.create_all`\n  creates these objects.\n- (Optionally) Registers into Alembic such that\n  `alembic revision --autogenerate` automatically creates/updates/deletes\n  declared objects.\n\nObject support includes:\n\n|                | Postgres | MySQL | SQLite | Snowflake |\n| -------------- | -------- | ----- | ------ | --------- |\n| Schemas        | ✓        | N/A   | ✓      | ✓         |\n| Views          | ✓        | ✓     | ✓      | ✓         |\n| Roles          | ✓        |       | N/A    | ✓         |\n| Grants         | ✓        |       | N/A    |           |\n| Default Grants | ✓        |       | N/A    |           |\n| Functions      | ✓        | ✓     |        |           |\n| Procedures     | ✓        | ✓     |        |           |\n| Triggers       | ✓        | ✓     |        |           |\n| Databases      | ✓        |       | N/A    | ✓         |\n| Rows (data)    | ✓        | ✓     | ✓      | ✓         |\n| \"Audit Tables\" | ✓        |       |        |           |\n\nNotes:\n\n- \"Row\" is implemented with pure SQLAlchemy concepts, so should work for any\n  dialect that you can use SQLAlchemy to connect to.\n- \"Audit Tables\" are a higher-level set of functions/triggers which record data\n  changes against some source table.\n\nIn principle, this library **can** absolutely support any database supported by\nSQLAlchemy, and capable of being introspected enough to support detection of\ndifferent kinds of objects. In reality, the existence of implementations are going to\nbe purely driven by actual usage/contributions/requests.\n\nSee [docs on dialect support](https://sqlalchemy-declarative-extensions.readthedocs.io/en/latest/contributing/dialect-support.html)\nfor information on how to improve support for a given dialect. Also feel free to submit an issue!\n\n## Kitchen Sink Example (using all available features)\n\n```python\nfrom sqlalchemy import Column, types, select\nfrom sqlalchemy.orm import as_declarative\nfrom sqlalchemy_declarative_extensions import (\n    declarative_database, Schemas, Roles, Row, View, view,\n)\nfrom sqlalchemy_declarative_extensions.dialects.postgresql import (\n    DefaultGrant, Function, Trigger, Role\n)\nfrom sqlalchemy_declarative_extensions.audit import audit\n\n\n@declarative_database\n@as_declarative\nclass Base:\n    # Note: each object type also has a plural version (i.e. Schemas/Roles/etc) where you can specify\n    # collection-level options like `ignore_unspecified`).\n    #\n    # If you dont set any collection-level options, you can instead use raw list/iterable as the collection.\n    schemas = Schemas().are(\"example\")\n    roles = Roles(ignore_unspecified=True).are(\n        Role(\"read\", login=False),\n        Role(\n            \"app\",\n            in_roles=['read']\n        ),\n    )\n    grants = [\n        DefaultGrant.on_tables_in_schema(\"public\", 'example').grant(\"select\", to=\"read\"),\n        DefaultGrant.on_sequences_in_schema(\"public\").grant(\"usage\", to=\"read\"),\n        Grant.new(\"usage\", to=\"read\").on_schemas(\"example\")\n    ]\n    rows = [\n        Row('foo', id=1),\n    ]\n    views = [\n        View(\"low_foo\", \"select * from foo where i \u003c 10\"),\n    ]\n    functions = [\n        Function(\n            \"fancy_function\",\n            \"\"\"\n            BEGIN\n            INSERT INTO foo (id) select NEW.id + 1;\n            RETURN NULL;\n            END\n            \"\"\",\n            language=\"plpgsql\",\n            returns=\"trigger\",\n        ),\n    ]\n    triggers = [\n        Trigger.after(\"insert\", on=\"foo\", execute=\"fancy_function\")\n        .named(\"on_insert_foo\")\n        .when(\"pg_trigger_depth() \u003c 1\")\n        .for_each_row(),\n    ]\n\n\n@audit()\nclass Foo(Base):\n    __tablename__ = 'foo'\n\n    id = Column(types.Integer(), primary_key=True)\n\n\naudit_table = Foo.__audit_table__\n\n\n@view(Base)\nclass HighFoo:\n    __tablename__ = \"high_foo\"\n    __view__ = select(Foo.__table__).where(Foo.__table__.c.id \u003e= 10)\n```\n\nNote, there is also support for declaring objects directly through the\n`MetaData` for users not using sqlalchemy's declarative API.\n\n## Event Registration\n\nBy default, the above example does not automatically do anything. Depending on\nthe context, you can use one of two registration hooks:\n`register_sqlalchemy_events` or `register_alembic_events`.\n\n### `register_sqlalchemy_events`\n\nThis registers events in SQLAlchemy's event system such that a\n`metadata.create_all(...)` call will create the declared database objects.\n\n```python\nfrom sqlalchemy_declarative_extensions import register_sqlalchemy_events\n\nmetadata = Base.metadata  # Given the example above.\nregister_sqlalchemy_events(metadata)\n# Which is equivalent to...\nregister_sqlalchemy_events(metadata, schemas=False, roles=False, grants=False, rows=False)\n```\n\nAll object types are opt in, and should be explicitly included in order to get\nregistered.\n\nPractically, this is to avoid issues with testing. In **most** cases the\n`metadata.create_all` call will be run in tests, a context where it's more\nlikely that you dont **need** grants or grants, and where parallel test\nexecution could lead to issues with role or schema creation, depending on your\nsetup.\n\n### `register_alembic_events`\n\nThis registers comparators in Alembic's registration system such that an\n`alembic revision --autogenerate` command will diff the existing database state\nagainst the declared database objects, and issue statements to\ncreate/update/delete objects in order to match the declared state.\n\n```python\n# alembic's `env.py`\nfrom sqlalchemy_declarative_extensions import register_alembic_events\n\nregister_alembic_events()\n# Which is equivalent to...\nregister_sqlalchemy_events(schemas=True, roles=True, grants=True, rows=True)\n```\n\nAll object types are opt out but can be excluded.\n\nIn contrast to `register_sqlalchemy_events`, it's much more likely that you're\ndeclaring most of these object types in order to have alembic track them\n\n## Alembic-utils\n\n[Alembic Utils](https://github.com/olirice/alembic_utils) is the primary library\nagainst which this library can be compared. At time of writing, **most** (but\nnot all) object types supported by alembic-utils are supported by this library.\nOne might begin to question when to use which library.\n\nBelow is a list of points on which the two libraries diverge. But note that you\n**can** certainly use both in tandem! It doesn't need to be one or the other,\nand certainly for any object types which do not overlap, you might **need** to\nuse both.\n\n- Database Support\n\n  - Alembic Utils seems to explicitly only support PostgreSQL.\n\n  - This library is designed to support any dialect (in theory). Certainly\n    PostgreSQL is **best** supported, but there does exist support for specific\n    kinds of objects to varying levels of support for Snowflake, SQLite, and MySQL,\n    so far.\n\n- Architecture\n\n  - Alembic Utils is directly tied to Alembic and does not support SQLAlchemy's\n    `MetaData.create_all`. It's also the responsibility of the user to\n    discover/register objects in alembic.\n\n  - This library **depends** only on SQLAlchemy, although it also supports\n    alembic. Support for `MetaData.create_all` can be important for creating all\n    object types in tests. It also is designed such that objects are registered\n    on the `MetaData` itself, so there is no need for any specific discovery\n    phase.\n\n- Scope\n\n  - Alembic Utils declares specific, individual objects. I.e. you instantiate\n    one specific `PGGrantTable` or `PGView` instance and Alembic know knows you\n    want that object to be created. It cannot drop objects it is not already\n    aware of.\n\n  - This library declares the objects the system as a whole expects to exist.\n    Similar to Alembic's behavior on tables, it will (by default) detect any\n    **undeclared** objects that should not exist and drop them. That means, you\n    can rely on this object to ensure the state of your migrations matches the\n    state of your database exactly.\n\n- Migration history\n\n  - Alembic Utils imports and references its own objects in your migrations\n    history. This can be unfortunate, in that it deeply ties your migrations\n    history to alembic-utils.\n\n    (In fact, this can be a sticking point, trying to convert **away** from\n    `alembic_utils`, because it will attempt to drop all the (e.g `PGView`)\n    instances previously created when we replaced it with this library.)\n\n  - This library, by contrast, prefers to emit the raw SQL of the operation into\n    your migration. That means you know the exact commands that will execute in\n    your migration, which can be helpful in debugging failure. It also means, if\n    at any point you decide to stop use of the library (or pause a given type of\n    object, due to a bug), you can! This library's behaviors are primarily very\n    much `--autogenerate`-time only.\n\n- Abstraction Level\n\n  - Alembic Utils appears to define a very \"literal\" interface (for example,\n    `PGView` accepts the whole view definition as a raw literal string).\n\n  - This library tries to, as much as possible, provide a more abstracted\n    interface that enables more compatibility with SQLAlchemy (For example\n    `View` accepts SQLAlchemy objects which can be coerced into a `SELECT`). It\n    also tends towards \"builder\" interfaces which progressively produce a object\n    (Take a look at the `DefaultGrant` above, for an example of where that's\n    helpful).\n\nA separate note on conversion/compatibility. Where possible, this library tries\nto support alembic-utils native objects as stand-ins for the objects defined in\nthis library. For example, `alembic_utils.pg_view.PGView` can be declared\ninstead of a `sqlalchemy_declarative_extensions.View`, and we will internally\ncoerce it into the appropriate type. Hopefully this eases any transitional\ncosts, or issues using one or the other library.\n","funding_links":["https://github.com/sponsors/DanCardin"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdancardin%2Fsqlalchemy-declarative-extensions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdancardin%2Fsqlalchemy-declarative-extensions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdancardin%2Fsqlalchemy-declarative-extensions/lists"}