Giter Site home page Giter Site logo

ancestry's Introduction

Ancestry

Build Status Coverage Status

The tree structure implementations for Ecto.

Table of contents

Getting started

If available in Hex, the package can be installed by adding ancestry to your list of dependencies in mix.exs:

def deps do
  [
    {:ancestry, "~> 0.1.3"}
  ]
end

Gen migration file to add string field in your model.

mix ecto.gen.migration add_ancestry_to_<model>

Add ancestry field and index to migration file.

def change do
  alter table(:my_models) do
    add :ancestry, :string
  end
  create index(:my_models, [:ancestry])
end
mix ecto.migration

Add use Ancestry, repo: MyApp.repo to you model.ex

defmodule MyModel do
  use Ecto.Schema
  use Ancestry, repo: MyApp.repo

  import Ecto.Changeset

  schema "my_models" do
    field :ancestry, :string
  end

  def changeset(struct, params) do
    struct
    |> cast(params, [:ancestry])
  end
end

Navigation

method return value usage example finished?
roots all root node MyModel.roots true
parent parent of the record, nil for a root node MyModel.parent(record) true
parent_id parent id of the record, nil for a root node MyModel.parent_id(record) true
has_parent? true if the record has a parent, false otherwise MyModel.has_parent?(record) true
root root of the record's tree, self for a root node MyModel.root(record) true
root_id root id of the record's tree, self for a root node MyModel.root_id(record) true
is_root? true if the record is a root node, false otherwise MyModel.is_root?(record) true
ancestors ancestors of the record, starting with the root and ending with the parent MyModel.ancestors(record) true
ancestor_ids ancestor ids of the record MyModel.ancestor_ids(record) true
children direct children of the record MyModel.children(record) true
child_ids direct children's ids MyModel.child_ids(record) true
has_children? true if the record has any children, false otherwise MyModel.has_children?(record) true
is_childless? true is the record has no children, false otherwise MyModel.is_childless?(record) true
siblings siblings of the record, the record itself is included* MyModel.siblings(record) true
sibling_ids sibling ids MyModel.sibling_ids(record) true
has_siblings? true if the record's parent has more than one child MyModel.has_siblings?(record) true
is_only_child? true if the record is the only child of its parent MyModel.is_only_child?(record) true
descendants direct and indirect children of the record MyModel.descendants(record) true
descendant_ids direct and indirect children's ids of the record MyModel.descendant_ids(record) true
subtree the model on descendants and itself MyModel.subtree(record) true
subtree_ids a list of all ids in the record's subtree MyModel.subtree_ids(record) true
path path of the record, starting with the root and ending with self MyModel.path(record) true
path_ids a list the path ids, starting with the root id and ending with the node's own id MyModel.path_ids(record) true
depth the depth of the node, root nodes are at depth 0 MyModel.depth(record) true

Options for use Ancestry

The use Ancestry method supports the following options:

:repo                  The current app repo
:ancestry_column       Pass in a symbol to store ancestry in a different column
:orphan_strategy       Instruct Ancestry what to do with children of a node that is destroyed:
                       :destroy   All children are destroyed as well (default)
                       :rootify   The children of the destroyed node become root nodes
                       :restrict  An AncestryException is raised if any children exist
                       :adopt     The orphan subtree is added to the parent of the deleted node.
                                  If the deleted node is Root, then rootify the orphan subtree.

Arrangement

Ancestry can arrange an entire subtree into nested hashes for easy navigation after retrieval from the database.

MyModel.arrange(record) =>
%{
  id: 1,
  name: "root",
  ancestry: nil,
  children: [
    %{
      id: "2",
      name: "childA",
      ancestry: "1",
      children: [
        %{
          id: 3,
          name: "childA1",
          ancestry: "1/2",
          children: []
        }
      ]
    }
  ],
}

Examples

# use `MyModel.delete` deal with orphan strategy.
iex> MyModel.delete(record)

# use `MyModel.get_ancestry_value(record, "children|siblings")` gen `ancestry` value
iex> MyModel.get_ancestry_value(record, "children")

# use `MyModel.arrange`
iex> MyModel.arrange(record)

TODO's

  • Establish data relationships
  • Parent create child
  • Create child with parent

Contributing

Bug report or pull request are welcome.

Make a pull request

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Please write unit test with your code if necessary.

License

The mix is available as open source under the terms of the MIT License.

Credits

  • ancestry - Organise ActiveRecord model into a tree structure(Ruby classes).

ancestry's People

Contributors

dependabot-preview[bot] avatar rafaeliga avatar zven21 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ancestry's Issues

Descendants query

The like statement is not accurate, example if id of the record is 1 it will find all subrecord having an ancestry of 10.., 100...

# https://github.com/zven21/ancestry/blob/master/lib/ancestry.ex#L265
query =
  from(
    u in unquote(module),
    where:
      fragment(
        unquote("#{opts[:ancestry_column]} LIKE ?"),
        ^"#{query_string}%"
      )
  )

A quick fix could be something like

query =
  from(
    u in unquote(module),
    where: fragment("#{opts[:ancestry_column]} = ?", "#{query_string}") or
      fragment(
        unquote("#{opts[:ancestry_column]} LIKE ?"),
        ^"#{query_string}/%"
      )
  )

`arrange` n + 1 problem

  def arrange(record, _opts, module) do
    case module.has_children?(record) do
      true ->
        Map.merge(record, %{children: do_build_children(record, module)})

      false ->
        record
    end
  end

  defp do_build_children(record, module) do
    record
    |> module.children()
    |> Enum.map(fn x ->
      case module.has_children?(x) do
        true ->
          Map.merge(x, %{children: do_build_children(x, module)})

        false ->
          x
      end
    end)
  end

If a record has 100 children but no grandchildren, We will hit the database 101 times, if every child has 100 children, we will hit the database more than 10000 times, the cost is huge.

Provide safe version of Module.delete/1 function

Right now, Ancestry.Repo.delete/3 breaks convention by using the unsafe Repo.delete!/2.

Please, provide an alternate version of the function that uses Repo.delete/2 instead. Also, rename the current function to reflect the convention.

This "safe" version of this function, should probably accept and pass on the optional opts keyword list which allows us to treat exceptional cases like :stale_error_field.

category = Repo.get!(Category, id)

# This could be replaced with an exclusion happening in another process or request
Repo.delete!(category) 

# throws unexpected "** (Ecto.StaleEntryError) attempted to delete a stale struct:"
Category.delete(category)

If the struct has been removed from db prior to call, Ecto.StaleEntryError will be raised.

Since by the documentation, this is the default behavior. Ancestry.Repo.delete/3, should either treat the exclusion process completely (and safely) or provide an API that allows it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.