All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.bingoohuang.sqltrigger.SqlParseUtil Maven / Gradle / Ivy

The newest version!
package com.github.bingoohuang.sqltrigger;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.*;
import com.github.bingoohuang.utils.lang.Str;
import com.google.common.collect.Maps;
import lombok.val;

import java.util.Map;

public class SqlParseUtil {

    public static Map clone(Map prototype) {
        Map map = Maps.newHashMap();

        for (val e : prototype.entrySet()) {
            map.put(e.getKey(), new TriggerColumnInfo(e.getValue().getName()));
        }

        return map;
    }

    public static void fulfilColumnInfo(TriggerColumnInfo col, SQLExpr value) {
        if (value instanceof SQLVariantRefExpr) {
            col.setValueType(ValueType.VariantRef);
        } else if (value instanceof SQLTextLiteralExpr) {
            col.setValueType(ValueType.Literal);
            col.setValue(((SQLTextLiteralExpr) value).getText());
        } else if (value instanceof SQLIntegerExpr) {
            col.setValueType(ValueType.Literal);
            col.setValue(((SQLIntegerExpr) value).getNumber());
        } else if (value instanceof SQLNullExpr) {
            col.setValueType(ValueType.Null);
            col.setValue(null);
        }
    }

    public static Map createWhereColumnInfo(SQLExpr where) {
        Map cols = Maps.newHashMap();
        processWhereItems(where, cols);

        return cols;
    }

    private static void processWhereItems(SQLExpr where, Map cols) {
        if (where instanceof SQLBinaryOpExpr) {
            val e = (SQLBinaryOpExpr) where;
            val l = e.getLeft();
            val r = e.getRight();
            val o = e.getOperator().getName();

            if (Str.anyOf(o, "=", "!=", "<>", ">", ">=", "<", "<=")) {
                if (l instanceof SQLIdentifierExpr) {
                    val simpleName = ((SQLIdentifierExpr) l).getSimpleName();
                    createWhereTriggerColumn(cols, r, simpleName);
                } else if (l instanceof SQLPropertyExpr) {
                    val simpleName = ((SQLPropertyExpr) l).getSimpleName();
                    createWhereTriggerColumn(cols, r, simpleName);
                }
            } else if (Str.anyOf(o, "AND", "OR")) {
                processWhereItems(l, cols);
                processWhereItems(r, cols);
            }
        }
    }

    private static void createWhereTriggerColumn(Map cols, SQLExpr r, String simpleName) {
        int colIndex = cols.size() + 1;

        val columnInfo = new TriggerColumnInfo(simpleName.toUpperCase());
        cols.put(colIndex, columnInfo);
        fulfilColumnInfo(columnInfo, r);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy