How to design a database for query builder project

database-design

I have this project in which user can create queries using web based UI in which there will be list of columns and applicable operators. Later users can edit these queries, too. So I need to store this in database.

I can store query in table as simple string but then editing will be not possible so I need to store it some other way. So I somehow managed to design it following way.

Proposed DB Schema

So let's say I have to store this query:

C1 > 8 AND (C2 <= 7 OR (C4 LIKE '%all%' AND (C1 > 15 OR C2 <= 3)))

where: C denotes some column

If I have to store it in DB as shown in image,

  • I would group each condition and store it in sub_operand table
  • then there will be recursive mapping entry in op_master table for each entry in sub_operand table
  • finally there will be master entry in op_master

But it seems too much complicated to handle insert and update. Can someone help me with this? I am very much stuck here.

UPDATE: I think I am missing something here in schema. It won't work as I have thought. I will update question as soon as I can correct it.

Best Answer

One approach you could take is to design a table that implements a stack into which can be placed the components of the logical expression in reverse-polish (postfix) notation. In such a design, the components of the predicate are each inserted into the table with an order number to specify the reverse evaluation order. To evaluate them a query is written to read them out by order number, apply the operators when encounter, and store the intermediate result to be applied the next. The use of the reverse-polish notation eliminates the need for parenthesis and can support nesting of expressions to any level.

Here is an article specific to SQL Server that shows such a solution. Now in this article the author is developing a more complex example of implementing business rules to determine whether an employee is authorized to execute a particular operation. It can easily be adapted to your use case as in both cases what is being implemented is a logical expression storage and evaluation engine.

I hope this can point you in a direction that will enable you to more easily handle the complexity that parsing nested logical expressions bring!