mulesoftmule4dynamicquery

Mule 4 dynamic queries in the Database Connector


In my flow in Mule 4 I am trying to query a database for specific data. For example I want to run a query like this:

SELECT * FROM mulesoft WHERE plant = CCCNNB;

The thing is both plant and CCNNB need to be dynamic. They will come through an API request. I can handle the value to be dynamic, but I get empty results whenever I try to make the field dynamic. I first create a variable which stores the json from the request:

set-variable value="#[payload]" doc:name="Set Variable" doc:id="8ed26865-d722-4fdb-9407-1f629b45d318" variableName="SORT_KEY"/>

Request looks like this:

{
 "FILTER_KEY": "plant",
 "FILTER_VALS": "CCNNB"
}

Afterwards in the db connector I configure the following:

<db:select doc:name="Select" doc:id="13a66f51-2a4e-4949-b383-86c43056f7a3" config-ref="Database_Config">
        <db:sql><![CDATA[SELECT * FROM mulesoft WHERE :filter_key = :filter_val;]]></db:sql>
        <db:input-parameters ><![CDATA[#[{
        "filter_val": vars.SORT_KEY.FILTER_VALS,
        "filter_key": vars.SORT_KEY.FILTER_KEY
    }]]]></db:input-parameters>

Replacing :filter_key with plant works but as soon as I try to make it dynamic I get nothing in the response. It does not fail though, response code is 200 but I get nothing inside it. How can I make this work?


Solution

  • You can directly use the stored variables in the query itself.

    Query Should be an expression in DataWeave.

    #["SELECT * FROM $(vars.table) WHERE $(vars.SORT_KEY.FILTER_KEY) = :filter_val"]
    
    <db:select config-ref="Database_Config">
      <db:sql><![CDATA[#["SELECT * FROM $(vars.table) WHERE $(vars.SORT_KEY.FILTER_KEY) = :filter_val"]]]></db:sql>
        <db:input-parameters ><![CDATA[#[{
                                     "filter_val": vars.SORT_KEY.FILTER_VALS
                              }]]]>
        </db:input-parameters>          
    </db:select>