Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store expression trees in database

I need to store logic conditions in database. for example: (condition1 || condition2) && condition3 should be stored in database.

I plan to design a table [ExpressionTree] to handle the structure:

Id
condition
combinationId
nextId(FK->[Condition2Combination.Id])
operator (AND, OR, null)

If (condition1 || condition2) && condition3 in the table [ExpressionTree], the records should be:

Id  conditionId combinationId nextId  operator
1  condition1   combination1  2       OR
2  condition2   combination1  3       AND
3  condition3   combination1  null    null

But the solution is not good, what’s your suggestion? Thanks!

like image 868
卢声远 Shengyuan Lu Avatar asked Feb 17 '11 07:02

卢声远 Shengyuan Lu


2 Answers

Unless you were actually going to perform database queries over the expression trees, I'd be inclined to store the expressions as a text column ... and parse them on the client side as required.

like image 131
Stephen C Avatar answered Sep 22 '22 12:09

Stephen C


I don't see the tree structure in your solution. In particular, I don't think your nextId column is capable of dealing with expressions that have parentheses in them. But I could be missing something.

I suggest that you look into a way of expressing tree structures that's known as the nested set technique. In this technique, the "next id" column gets replaced by two columns, called "left id" and "right id" that is capable of expressing which subreets are inside of other subtrees. This is an over simplified summary of what you're going to find.

Using nested sets, it's easy to come up with a query that reveals the subtree under any given node, or the path from any given node back to the root.

Why is this data in a database?

like image 25
Walter Mitty Avatar answered Sep 20 '22 12:09

Walter Mitty