{"id":24016462,"url":"https://github.com/zechcodes/ommi","last_synced_at":"2025-04-15T14:14:26.961Z","repository":{"id":218806732,"uuid":"739786582","full_name":"ZechCodes/Ommi","owner":"ZechCodes","description":"A portable object model mapper for Python that can work with any database and model library (dataclasses, Attrs, Pydantic, etc.). It is designed for the general case to support the largest possible number of databases.","archived":false,"fork":false,"pushed_at":"2024-12-13T19:31:05.000Z","size":542,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T21:03:36.677Z","etag":null,"topics":[],"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/ZechCodes.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-06T14:42:25.000Z","updated_at":"2024-12-30T22:28:57.000Z","dependencies_parsed_at":"2024-05-22T18:25:10.370Z","dependency_job_id":"19f12497-f5a1-4a07-ad66-eb486ac7be37","html_url":"https://github.com/ZechCodes/Ommi","commit_stats":null,"previous_names":["zechcodes/ommi"],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZechCodes%2FOmmi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZechCodes%2FOmmi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZechCodes%2FOmmi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZechCodes%2FOmmi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ZechCodes","download_url":"https://codeload.github.com/ZechCodes/Ommi/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248933348,"owners_count":21185461,"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":[],"created_at":"2025-01-08T08:51:28.760Z","updated_at":"2025-04-15T14:14:26.940Z","avatar_url":"https://github.com/ZechCodes.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Ommi\n\n\u003e [!CAUTION]\n\u003e Ommi is under construction and much of the functionality is undergoing frequent revision. There is no guarantee future\n\u003e versions will be backwards compatible.\n\nHave you ever needed to use a database for a simple project but didn't want to worry about which database you were going\nto use? Or maybe you wanted to create a package that needed to store data but didn't want to force your users to use a\nspecific database? Meet Ommi, a simple object model mapper that allows you to use whatever models you want to interface\nwith whatever database you like.\n\nOmmi doesn't provide its own model types, it allows you to use whatever models you are already using. Compatibility with\nthe most popular model implementations are ensured through a comprehensive unit test suite.\n\n### Compatible Model Implementations\n\nOmmi's test suite checks for compatibility with the following model implementations:\n\n- [Dataclasses](https://docs.python.org/3/library/dataclasses.html)\n- [Attrs](https://www.attrs.org/en/stable/)\n- [Pydantic](https://docs.pydantic.dev/latest/)\n\n### Included Database Support\n\n#### SQLite3\n\n- Table creation from models\n- Select, Insert, Update, Delete, Count\n- One-to-one \u0026 one-to-many relationships\n- Joins to filter queries for a single model type (cannot query for multiple model types in a single query)\n\n#### PostgreSQL\n\n- Table creation from models\n- Select, Insert, Update, Delete, Count\n- One-to-one \u0026 one-to-many relationships\n- Joins to filter queries for a single model type (cannot query for multiple model types in a single query)\n\n#### MongoDB\n\n- Collection creation from models\n- Fetch, Insert, Update, Delete, Count\n- One-to-one \u0026 one-to-many relationships\n- Joins to filter queries for a single model type (cannot query for multiple model types in a single query)\n\n## Usage\n\n### Defining Models\n\nAll models that support Ommi database drivers need to use the `ommi_model` class decorator.\n\n```python\nfrom ommi import ommi_model, Key\nfrom dataclasses import dataclass\nfrom typing import Annotated\n\n@ommi_model\n@dataclass\nclass User:\n    name: str\n    age: int\n    id: Annotated[int, Key] = None  # Optional primary key\n```\n\nModels can be assigned to model collections. Any model not assigned a collection will be assigned to a global\ncollection which can be accessed by calling `ommi.models.get_global_collection()`.\n\n```python\nfrom ommi.models.collections import ModelCollection\n\ncollection = ModelCollection()\n\n\n@ommi_model(collection=collection)\n@dataclass\nclass User:\n    name: str\n    age: int\n```\n\n### Connecting\n\n```python\nfrom ommi.ext.drivers.sqlite import SQLiteDriver, SQLiteConfig\n\n\nasync def example():\n    async with SQLiteDriver.from_config(SQLiteConfig(filename=\":memory:\")) as db:\n        ...\n```\n\n### Database Actions\n\nThe database drivers provide `add`, `count`, `delete`, `fetch`, `sync_schema`, and `update` methods. These methods should\nbe wrapped in an `ommi.drivers.DatabaseAction`. The database action will capture the return and wrap it in a\n`DatabaseStatus` result that is either a `Success` or `Exception`. The database action provides an `or_raise` method\nthat will force the exception to be raised immediately or return a `Success` result. The `DatabaseStatus` types are\nsub-types of `tramp.results.Result` types.\n\n#### Add\n\nAdd takes any number of model instances and adds them to the database.\n\n```python\nuser_1 = User(name=\"Alice\", age=25)\nuser_2 = User(name=\"Alice\", age=25)\nawait db.add(user_1, user_2).raise_on_errors()\n```\n\n#### Find\n\nFind returns a `FindAction`. This action is used to count, delete, fetch, or set fields on models in the database. It\ntakes any number of predicates that are AND'd together. It doesn't return any models or make any changes to the database\non its own.\n\n#### Count\n\nCount is an action of `find` that returns the number of models that match the predicates passed to `find`. It returns an\n`AsyncResultWrapper` which allows you to access the returned `int` value through chaining, you can read more about it\nbelow.\n\n```python\ncount = await db.find(User.name == \"Alice\").count().value\n```\n\n#### Delete\n\nDelete is an action of `find` that deletes all models that match the predicates passed to `find`. It also returns\nan `AsyncResultWrapper`.\n\n```python\nawait db.find(User.id == user.id).delete().raise_on_errors()\n```\n\n#### Fetch\n\nFetch is an action of `find` that returns all models that match the predicates passed to `find`. It provides `all` and\n`one` helper methods to help with value unpacking, they both raise on errors. Calling `fetch` directly will  return an\n`AsyncResultWrapper` that contains the list of models.\n\n```python\nusers = await db.find(User.name == \"Alice\").fetch().value\n```\n\n```python\nusers = await db.find(User.name == \"Alice\").fetch.all()\n```\n\n```python\nuser = await db.find(User.name == \"Alice\").fetch.one()\n```\n\nModels provide a `reload` method that will pull the latest data from the database. It returns an `AsyncResultWrapper`.\n\n```python\nawait user.reload().raise_on_errors()\n```\n\n#### Set\n\nSet is an action of `find` that updates all models that match the predicates passed to `find`. It takes a any number of\nkeyword arguments that are used to update the models fields. It returns an `AsyncResultWrapper`.\n\n```python\nawait db.find(name=\"bob\").set(name = \"Bob\").raise_on_errors()\n```\n\nModels provide a `save` method that will push changed fields to the database. It returns an\n`AsyncResultWrapper`.\n\n```python\nuser.name = \"Bob\"\nawait user.save().raise_on_errors()\n```\n\n#### Schema\n\nSchema is an action object that provides methods to manipulate the database itself. It can optionally be passed an\noptional `ModelCollection` or nothing to default to the global collection.\n\nIts `create_models` action returns an `AsyncResultWrapper` that contains a list of the models that were created.\n\n```python\nawait db.schema().create_models().raise_on_errors()\n```\n\n```python\nawait db.schema(some_model_collection).create_models().raise_on_errors()\n```\n\nIt also provides a `delete_models` action that deletes all models in the collection from the database.\n\n```python\nawait db.schema(some_model_collection).delete_models().raise_on_errors()\n```\n\n### AsyncResultWrapper\n\n`AsyncResultWrapper` is a wrapper around the result of an async database action. It provides various awaitable\nproperties and methods that allow you to access the result of the action. Awaiting the `AsyncResultWrapper` itself will\nreturn a `DatabaseResult.Success` object if the action succeeded or a `DatabaseResult.Failure` object if there was an\nexception.\n\n```python\nmatch await db.find(User.name == \"Alice\").count():\n    case DatabaseResult.Success(value):\n        print(value)\n\n    case DatabaseResult.Failure(error):\n        print(error)\n```\n\n#### Value\n\nValue is an awaitable property that returns the value of the action. It will raise an exception if the action failed.\n\n```python\nawait db.find(User.name == \"Alice\").count().value\n```\n\n#### Value Or\n\nValue or is a method that takes a default value and returns the value of the action or the default value if the action\nfailed.\n\n```python\ncount = await db.find(User.name == \"Alice\").count().value_or(0)\n```\n\n#### Raise on Errors\n\nRaise on errors is a method that will raise an exception if the action failed. If the action succeeds it'll return\nnothing. It's a convenience method that allows you to raise errors and discard the result on success.\n\n```python\nawait db.find(User.name == \"Alice\").delete().raise_on_errors()\n```\n\n### Database Results\n\n`DatabaseResult` is a result type that is used to wrap the values of database actions. It provides a `Success` and\n`Failure` type that can be used to match on the result of an action.\n\n```python\nmatch await db.find(User.name == \"Alice\").count():\n    case DatabaseResult.Success(value):\n        print(value)\n\n    case DatabaseResult.Failure(error):\n        print(error)\n```\n\n#### Value and Value Or\n\n`DatabaseResult` objects provide a `value` property that returns the value of the action or raises an exception if the\naction failed. It also provides a `value_or` that takes a default value that is returned if the action failed.\n\nUnlike `AsyncResultWrapper`, `DatabaseResult` objects do not need to be awaited.\n\n```python\nresult = await db.find(User.name == \"Alice\").count()\nprint(result.value)  # Raises an exception if the action failed\n```\n\n```python\nresult = await db.find(User.name == \"Alice\").count()\nprint(result.value_or(0))  # Prints 0 if the action failed\n```\n\n#### Error\n\n`DatabaseResult` objects provide an `error` property that returns the exception that caused the action to fail or `None`\nif the action succeeded.\n\n```python\nresult = await db.find(User.name == \"Alice\").count()\nprint(result.error)  # Prints None if the action succeeded\n```\n\n### Lazy Loaded Relationships\n\nOmmi provides support for lazy loading relationships between models. It fully supports forward references as string\nannotations. There are two supported relationship types using the `ommi.query_fields.LazyLoadTheRelated` and\n`ommi.query_fields.LazyLoadEveryRelated` generic types as annotations. It relies on models using the\n`ommi.field_metadata.ReferenceTo` annotation to define which field references which field on another model.\n\n```python\n@ommi_model\n@dataclass\nclass User:\n    id: int\n\n    posts: \"LazyLoadEveryRelated[Post]\"\n\n@ommi_model\n@dataclass\nclass Post:\n    id: int\n    author_id: Annotated[int, ReferenceTo(User)]\n\n    author: LazyLoadTheRelated[User]\n```\n\n`LazyLoadTheRelated` and `LazyLoadEveryRelated` are awaitable to fetch the related models. They also provide an\nawaitable `value` property that returns the same value as well as a `get` method that takes a default value in case of a\nfailure. `LazyLoadTheRelated` will return a single model while `LazyLoadEveryRelated` will return a `list` of models.\n\n```python\nuser = User(id=1)\nposts = await user.posts\n```\n\nLazy fields will only fetch once and then cache the result.\n\nAdditionally, `LazyLoadTheRelated` and `LazyLoadEveryRelated` can associate with models using an association model that\nhas references to model being defined and the model being lazily queried. To do this annotate the referenced model with\n`ommi.query_fields.AssociateUsing` which is passed the model that is to be used to associate the models.\n\n```python\n@ommi_model\n@dataclass\nclass User:\n    id: int\n\n    permissions: \"LazyLoadEveryRelated[Annotated[Permission, AssociateUsing(UserPermission)]]\"\n\n@ommi_model\n@dataclass\nclass Permission:\n    id: int\n    \n@ommi_model\n@dataclass\nclass UserPermission:\n    user_id: Annotated[int, ReferenceTo(User.id)]\n    permission_id: Annotated[int, ReferenceTo(Permission.id)]\n```\n\n#### Get\n\n'LazyQueryFields` provide a `get` method that takes a default value and returns the value of the relationship or the\ndefault value if there is an error.\n\n```python\nuser = User(id=1)\nposts = await user.posts.get([])\n```\n\n### Value\n\n`LazyQueryFields` provide a `value` property that returns the value of the relationship or raises an exception if there\nis an error.\n\n```python\nuser = User(id=1)\nposts = await user.posts.value\n```\n\n### Refresh\n\n`LazyQueryFields` provide a `refresh` method that will fetch the related models again and update the cache.\n\n```python\nuser = User(id=1)\nawait user.posts.refresh()\n```\n\n### Refresh if needed\n\nThe `refresh_if_needed` method will only fetch the related models if they haven't been fetched yet.\n\n```python\nuser = User(id=1)\nawait user.posts.refresh_if_needed()\n```\n\n### Result\n\n`LazyQueryFields` provide a `result` property that returns the `tramp.results.Result` object directly. This can be\nhelpful for handling errors more explicitly.\n\n```python\nuser = User(id=1)\nmatch await user.posts.result:\n    case Value(posts):\n        ...\n\n    case Error(error):\n        ...\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzechcodes%2Fommi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzechcodes%2Fommi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzechcodes%2Fommi/lists"}