November 3, 2010

Dynamic runtime named bind variables

public void search(String param1, String param2) {
    String sql_1 = " AND SOMETHING = :P_PARAM_1)";
    String sql_2 = " AND SOMETHING_ELSE = :P_PARAM_2";

    setWhereClause(null);
    clearWhereState();
    setWhereClause("1=1");

    if (param1 != null && param1.length() > 0) {
        addWhereClause(sql_1);
        defineNamedWhereClauseParam("P_PARAM_1", null, null);
        setNamedWhereClauseParam("P_PARAM_1", param1);
    }

    if (param2 != null && param2.length() > 0) {
        addWhereClause(sql_2);
        defineNamedWhereClauseParam("P_PARAM_2", null, null);
        setNamedWhereClauseParam("P_PARAM_2", param2);
    }

    executeQuery();
}

protected void clearWhereState() {
    ViewDefImpl viewDef = getViewDef();
    Variable[] viewInstanceVars = null;
    VariableManager viewInstanceVarMgr = ensureVariableManager();
    if (viewInstanceVarMgr != null) {
        viewInstanceVars = viewInstanceVarMgr.getVariablesOfKind(Variable.VAR_KIND_WHERE_CLAUSE_PARAM);
        if (viewInstanceVars != null) {
            for (Variable v : viewInstanceVars) {
                // only remove the variable if its not on the view def.
                if (!hasViewDefVariableNamed(v.getName())) {
                    removeNamedWhereClauseParam(v.getName());
                }
            }
        }
    }
    getDefaultRowSet().setExecuteParameters(null, null, true);
    setWhereClause(null);
    getDefaultRowSet().setWhereClauseParams(null);
}

private boolean hasViewDefVariableNamed(String name) {
    boolean ret = false;
    VariableManager viewDefVarMgr = getViewDef().ensureVariableManager();
    if (viewDefVarMgr != null) {
        try {
            ret = viewDefVarMgr.findVariable(name) != null;
        } catch (NoDefException ex) {
            // ignore
        }
    }
    return ret;
}

No comments: