Convert DB rules to if-else conditions?

I want to convert a set of rows in SQL Server database (In the form of rules) to a single if-else condition without hardcoding any values in the code. The code will be written in Scala and I am trying to figure out the logic to do this but could not think of a good approach.

Sample SQL Server Rows:

TAG |  CONDITION | MIN VALUE | MAX VALUE | STATUS

ABC |     =      | 0         |  NULL     | GOOD

ABC |     =      | 1         |  NULL     | BAD

ABC |     =      | 2         |  NULL     | ERROR

ABC |     >=     | 3         |  NULL     | IGNORE

Similar to tag ABC, there could be any number of tags and the conditions will vary with the tag column and each tag will have conditions in multiple rows. If anyone has dealt with a similar problem and has any suggestions that would be appreciated.

1 answer

  • answered 2018-02-13 11:22 Rich

    The question doesn't seem clear to me as currently written. What do you mean by a "a single if-else condition without hardcoding any values in the code"?

    Would the following work?

    sealed trait Condition
    object Eq extends Condition // =
    object Ge extends Condition // >=
    
    sealed trait Status
    object Good extends Status
    object Bad extends Status
    object Error extends Status
    object Ignore extends Status
    
    case class Rule(tag: String,
                    condition: Condition,
                    min: Int,
                    max: Int,
                    status: Status)
    
    def handle(input: Int, rules: List[Rule]): Status =
      rules
          .view // lazily iterate the rules
          .filter { // find matching rules
            case Rule(_, Eq, x, _, _) if input == x => true
            case Rule(_, Ge, x, _, _) if input >= x => true
            case _ => false
          }
          .map { matchingRule => matchingRule.status } // return the status
          .head // find the status of the first matching rule, or throw
    
    
    // Tests
    
    val rules = List(
      Rule("abc", Eq, 0, 0, Good),
      Rule("abc", Eq, 1, 0, Bad),
      Rule("abc", Eq, 2, 0, Error),
      Rule("abc", Ge, 3, 0, Ignore))
    
    assert(handle(0, rules) == Good)
    assert(handle(1, rules) == Bad)
    assert(handle(2, rules) == Error)
    assert(handle(3, rules) == Ignore)
    assert(handle(4, rules) == Ignore)