简体   繁体   English

如何在数据库中存储依赖树?

[英]How to store dependency tree in a database?

I am trying to store a dependency tree in a PostgreSQL database. 我试图在PostgreSQL数据库中存储一个依赖树。 There are about 20,000 software items, each item can depend on several other items. 大约有20,000个软件项目,每个项目可以依赖于其他几个项目。

There are several types of dependencies (some are run-time dependencies, some are build-time dependencies and some are test-dependencies). 有几种类型的依赖项(一些是运行时依赖项,一些是构建时依赖项,一些是测试依赖项)。

The dependency is recursive and each item only knows about the things it immediately depends on. 依赖是递归的,每个项只知道它立即依赖的东西。

I'll need to list all the dependencies of an item and display them both as a tree and as a flattened list. 我需要列出项目的所有依赖项,并将它们显示为树和展平列表。 I'll also need to answer "what depends on this item?" 我还需要回答“这取决于什么项目?”

What would be a recommended way to store this information to make fetching relatively easy? 什么是建议的方式来存储这些信息,以使获取相对容易?

It might be worth picking up a copy of Joe Celko's "Trees and Hierarchies in SQL for Smarties". 可能值得拿起Joe Celko的“树中的树和层次结构用于聪明人”的副本。 It has a explanations and examples of the different options available for this sort of thing. 它有一个解释和示例,可用于此类事情的不同选项。

I'd store the data in something like 我将数据存储在类似的东西中

CREATE TABLE software (
   id SERIAL PRIMARY KEY,
   ...
);

CREATE TABLE software_dependency (
   dependent int NOT NULL REFERENCES software(id),
   dependee int NOT NULL REFERENCES software(id),
   deptype int, -- or whatever you want
   CONSTRAINT pk_software_dependency PRIMARY KEY  (dependent, dependee)
);

You'll be able to get a list of all the dependencies with something like: 您将能够获得所有依赖项的列表,例如:

WITH RECURSIVE t(id,type) AS (
 SELECT dependee,deptype FROM software_dependency WHERE dependent=3
UNION ALL
 SELECT d.dependee,deptype FROM software_dependency d INNER JOIN t ON t.id=d.dependent
)
SELECT * FROM t;

Edit: to get a tree, a good way is to accumulate the dependencies in ARRAY format. 编辑:获取树,一个好方法是以ARRAY格式累积依赖项。 For each step in the recursion use the array append operator (||) to add the new ID to an array, and get it out at the end. 对于递归中的每个步骤,使用数组追加运算符(||)将新ID添加到数组中,并在结尾处将其取出。

I'd implement a simple many-to-many auto relationship. 我实现了一个简单的多对多自动关系。

Something like this: 像这样的东西:

 Software                Dependency
+------------+          +-----------------------+
| SoftwareId |          | SoftwareId            |
+------------+         /| DependsUponSoftwareId |
| Name       |--------|-+-----------------------+
| ...        |         \| ...                   |
+------------+          +-----------------------+ 

我会使用ORM,在内存中构造对象图,然后让ORM持久化它:P。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM