【问题标题】:Convert DB rules to if-else conditions?将数据库规则转换为 if-else 条件?
【发布时间】:2018-02-13 03:05:20
【问题描述】:

我想将 SQL Server 数据库中的一组行(以规则的形式)转换为单个 if-else 条件,而不对代码中的任何值进行硬编码。代码将用 Scala 编写,我正在尝试找出执行此操作的逻辑,但想不出一个好的方法。

示例 SQL Server 行:

TAG |  CONDITION | MIN VALUE | MAX VALUE | STATUS

ABC |     =      | 0         |  NULL     | GOOD

ABC |     =      | 1         |  NULL     | BAD

ABC |     =      | 2         |  NULL     | ERROR

ABC |     >=     | 3         |  NULL     | IGNORE

与标记 ABC 类似,可以有任意数量的标记,并且条件会随着标记列的不同而不同,并且每个标记都会在多行中具有条件。如果有人处理过类似的问题并有任何建议,将不胜感激。

【问题讨论】:

    标签: sql-server database scala


    【解决方案1】:

    这个问题对我来说似乎并不清楚,就像目前写的那样。 “没有硬编码代码中任何值的单个 if-else 条件”是什么意思?

    以下是否可行?

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 2019-04-09
      • 2014-04-13
      • 2018-11-15
      • 2019-05-06
      • 2023-03-08
      相关资源
      最近更新 更多