{"id":13561173,"url":"https://github.com/florinpatrascu/closure_table","last_synced_at":"2025-09-12T10:34:09.911Z","repository":{"id":47145916,"uuid":"200294084","full_name":"florinpatrascu/closure_table","owner":"florinpatrascu","description":"Closure Table for Elixir - a simple solution for storing and manipulating complex hierarchies.","archived":false,"fork":false,"pushed_at":"2024-08-15T12:46:19.000Z","size":370,"stargazers_count":33,"open_issues_count":0,"forks_count":9,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-02-04T21:43:44.756Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Elixir","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/florinpatrascu.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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":"2019-08-02T20:28:55.000Z","updated_at":"2025-01-18T15:22:32.000Z","dependencies_parsed_at":"2024-05-01T15:27:31.456Z","dependency_job_id":"060bbc62-b5fc-4172-a3f7-5e650fdff60a","html_url":"https://github.com/florinpatrascu/closure_table","commit_stats":{"total_commits":57,"total_committers":6,"mean_commits":9.5,"dds":0.5789473684210527,"last_synced_commit":"a50214410beac39f284a7fd4c96e581c11440535"},"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinpatrascu%2Fclosure_table","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinpatrascu%2Fclosure_table/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinpatrascu%2Fclosure_table/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinpatrascu%2Fclosure_table/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/florinpatrascu","download_url":"https://codeload.github.com/florinpatrascu/closure_table/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238563735,"owners_count":19492975,"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":"2024-08-01T13:00:53.278Z","updated_at":"2025-02-12T23:16:55.010Z","avatar_url":"https://github.com/florinpatrascu.png","language":"Elixir","funding_links":[],"categories":["Algorithms and Data structures"],"sub_categories":[],"readme":"# Closure Table\n\n[![Hex.pm](https://img.shields.io/hexpm/dt/closure_table.svg?maxAge=2592000)](https://hex.pm/packages/closure_table)\n[![Hexdocs.pm](https://img.shields.io/badge/api-hexdocs-brightgreen.svg)](https://hexdocs.pm/closure_table)\n\nThe Closure Table solution is a simple and elegant way of storing hierarchies. It involves storing all paths through a tree, not just those with a direct parent-child relationship. You may want to chose this model, over the [Nested Sets model](https://en.wikipedia.org/wiki/Nested_set_model), should you need referential integrity and to assign nodes to multiple trees.\n\nThroughout the various examples and tests, we will refer to the hierarchies depicted below, where we are modeling a hypothetical forum-like discussion between [Rolie, Olie and Polie](https://www.youtube.com/watch?v=LTkmaE_QWMQ), and their debate around the usefulness of this implementation :)\n\n![Closure Table](assets/closure_table.png)\n\nWarning:\n\n\u003e This version introduces significant changes. We are removing the concept of a CT Adapter and focusing on using Ecto for the core functions. The (in-memory) adapter has been eliminated.\n\n\n## Quick start\n\nThe current implementation is depending on Ecto \u003e= 3.1; using [Ecto.SubQuery](https://hexdocs.pm/ecto/Ecto.SubQuery.html)!\n\nFor this implementation to work you'll have to provide two tables, and the name of the Repo used by your application:\n\n1. a table containing the nodes, with `id` as the primary key. With this new version, you are no longer required to name your primary keys `id`. Although `id` remains the default, you now have the option to use your own keys and data types. Example:\n\n    ```elixir\n    # For more details and an example of designing and implementing simple\n    # hierarchical structures of tags, see test/custom_node_id_test.exs (excerpt below)\n    use CTE,\n      repo: Repo,\n      nodes: Tag,\n      paths: TagTreePath,\n      options: %{\n        node: %{primary_key: :name, type: :string},\n        paths: %{\n          ancestor: [type: :string],\n          descendant: [type: :string]\n        }\n      }\n    ```\n\n2. a table name for storing the tree paths.\n3. the name of the Ecto.Repo, defined by your app\n\nUsing a structure like the one above and just a few functions from this library, you will be able to create highly efficient hierarchies such as these. Their management will be quick, accurate, and straightforward:\n\n    food\n    ├── vegetable\n    ├── fruit\n    │  ├── apple\n    │  ├── orange\n    │  └── berry\n    │     └── tomato\n    └── meat\n      └── burger\n\nIn a future version we will provide you with a convenient migration template to help you starting, but for now you must supply these tables.\n\nFor example, given you have the following Schemas for comments:\n\n```elixir\n      defmodule CT.Comment do\n        use Ecto.Schema\n        import Ecto.Changeset\n\n        @timestamps_opts [type: :utc_datetime]\n\n        schema \"comments\" do\n          field :text, :string\n          belongs_to :author, CT.Author\n\n          timestamps()\n        end\n      end\n```\n\nand a table used for storing the parent-child relationships\n\n```elixir\n\n      defmodule CT.TreePath do\n        use Ecto.Schema\n        import Ecto.Changeset\n        alias CT.Comment\n\n        @primary_key false\n\n        schema \"tree_paths\" do\n          belongs_to :parent_comment, Comment, foreign_key: :ancestor\n          belongs_to :comment, Comment, foreign_key: :descendant\n          field :depth, :integer, default: 0\n        end\n      end\n```\n\nwe can define the following module:\n\n```elixir\n\n      defmodule CT.MyCTE do\n        use CTE,\n        repo: CT.Repo,\n        nodes: CT.Comment,\n        paths: CT.TreePath\n      end\n```\n\nWe add our CTE Repo to the app's main supervision tree, like this:\n\n```elixir\n      defmodule CT.Application do\n        use Application\n\n        def start(_type, _args) do\n          children = [\n            CT.Repo,\n          ]\n\n          opts = [strategy: :one_for_one, name: CT.Supervisor]\n          Supervisor.start_link(children, opts)\n        end\n      end\n```\n\nrestart your application.\n\nThen using `iex -S mix`, we can start experimenting. Examples:\n\n```elixir\n      iex» CT.MyCTE.ancestors(9)\n      {:ok, [1, 4, 6]}\n\n      iex» {:ok, tree} = CT.MyCTE.tree(1)\n      {:ok,\n      %{\n      nodes: %{\n        6 =\u003e %CT.Comment{\n          __meta__: #Ecto.Schema.Metadata\u003c:loaded, \"comments\"\u003e,\n          author: #Ecto.Association.NotLoaded\u003cassociation :author is not loaded\u003e,\n          author_id: 2,\n          id: 6,\n          inserted_at: ~U[2019-07-21 01:10:35Z],\n          text: \"Everything is easier, than with the Nested Sets.\",\n          updated_at: ~U[2019-07-21 01:10:35Z]\n        },\n        8 =\u003e %CT.Comment{\n          __meta__: #Ecto.Schema.Metadata\u003c:loaded, \"comments\"\u003e,\n          author: #Ecto.Association.NotLoaded\u003cassociation :author is not loaded\u003e,\n          author_id: 1,\n          id: 8,\n          inserted_at: ~U[2019-07-21 01:10:35Z],\n          text: \"I’m sold! And I’ll use its Elixir implementation! \u003c3\",\n          updated_at: ~U[2019-07-21 01:10:35Z]\n        },\n        ...\n\n      },\n      paths: [\n          [1, 1, 0],\n          [1, 2, 1],\n          [2, 2, 0],\n          [1, 3, 2],\n          [2, 3, 1],\n          [3, 3, 0],\n          [1, 7, 3],\n          [2, 7, 2],\n     ...\n            ]\n      }}\n```\n\nif you want to visualize a tree, you can do that too:\n\n```elixir\niex» CTE.Utils.print_tree(tree, 1, callback: \u0026({\u00262[\u00261], \u00262[\u00261].text}))\n```\n\nand you may see this:\n\n```txt\nIs Closure Table better than the Nested Sets?\n├── It depends. Do you need referential integrity?\n│  └── Yeah\n│     └── Closure Table *has* referential integrity?\n└── Querying the data it's easier.\n   ├── What about inserting nodes?\n   └── Everything is easier, than with the Nested Sets.\n      ├── I'm sold! And I'll use its Elixir implementation! \u003c3\n      └── w⦿‿⦿t!\n```\n\nPlease check the docs for more details and return from more updates!\n\nOh and there is a simple utility for helping you drawing your paths, using graphviz! From Rolie's comments, excerpt:\n\n![dot](assets/dot.dot.dot.png)\n\nMaybe useful?! If yes, then we'll let you find this function by yourself ;)\n\nhint: _check the tests \u003c3_\n\n## Installation\n\nIf available on [Hex](https://hex.pm/packages/closure_table), you can install the package by adding `closure_table` to your list of dependencies in `mix.exs`:\n\n```elixir\ndef deps do\n  [\n    {:closure_table, \"~\u003e 2.0\"}\n  ]\nend\n```\n\n## Contributing\n\n- [Fork this project](https://github.com/florinpatrascu/closure_table/fork)\n- Create your feature branch (git checkout -b my-new-feature)\n- Setup database and test (`mix test`)\n- Commit your changes (`git commit -am 'Add some feature'`)\n- Push to the branch (`git push origin my-new-feature`)\n- Create new Pull Request\n\n## License\n\n```txt\nCopyright 2024 Florin T.PATRASCU \u0026 the Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n  http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflorinpatrascu%2Fclosure_table","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fflorinpatrascu%2Fclosure_table","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflorinpatrascu%2Fclosure_table/lists"}