dongying6896 2014-12-02 04:42
浏览 84
已采纳

如何使用Math.js解析器测试MySQL语法

I allow a user to specify a MySQL calculated field in a web form field that might read something like:

(bldgFuelCostElectricity * assetMotorSize) * if(bldgField1>bldgField2,bldgField1-bldgField2,0) * 24

At run time I will substitute other table columns for the camelcase parameters, but before I let the user save this expression as part of a report template, I would like to test the function for validity using Math.js but it doesn't like the IF() construct. Math.js does allow function name overrides, but I cannot make it work with the particular case of IF because that's a reserved word.

How can I test that a MySQL function is valid using Math.js when MySQL has certain functions that already have JavaScript equivalents?

  • 写回答

1条回答 默认 最新

  • donglin9717 2014-12-02 09:21
    关注

    You need to be careful testing MySQL syntax with the parser of math.js, as their syntaxes differ. You will have to define carefully which syntax you support and explicitely test this.

    What you can do with math.js is parse expressions into an expression tree and anaylise them. By traversing over the tree, you can validate the syntax. For example:

    var node = math.parse('3 * x + 2');
    node.traverse(function (node, path, parent) {
      switch (node.type) {
        case 'OperatorNode': console.log(node.type, node.op);    break;
        case 'ConstantNode': console.log(node.type, node.value); break;
        case 'SymbolNode':   console.log(node.type, node.name);  break;
        default:             console.log(node.type);
      }
    });
    // outputs:
    //   OperatorNode +
    //   OperatorNode *
    //   ConstantNode 3
    //   SymbolNode x
    //   ConstantNode 2
    

    So in your case, you can just parse your expression and then analyze the returned tree:

    var node = math.parse('(bldgFuelCostElectricity * assetMotorSize) * if(bldgField1>bldgField2,bldgField1-bldgField2,0) * 24');
    // node.traverse(...)
    

    See docs for more information: http://mathjs.org/docs/expressions/expression_trees.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘