I want to create a dynamic insert query in mulesoft as part of the system API that is can be used to interact with DB for multiple tables as per the calling processing API.
I want to below outout
"Ronaldo","GOAT"
But I'm getting below output
"Ronaldo, GOAT"
Can someone please help me, I'm trying to create a dynamic insert but values needs to be in double quotes.
Below is my current logic,
PAYLOAD
{
"table": "std",
"Payload": {
"studentName" : "Ronaldo" ,
"course" : "GOAT"
}
}
CODE
%dw 2.0
output application/json
var table = "insert into " ++ payload.table
var value = valuesOf(payload.Payload) reduce ((item, accumulator) -> item ++"," ++ accumulator)
var key = keysOf(payload.Payload) reduce ((item, accumulator) -> item ++ "," ++ accumulator)
---
table ++ key ++ "(VALUES " ++ value ++");"
OUTPUT
"Ronadlo","GOAT"
The script can be simpler and there are some possible improvements:
keysOf()
. The former returns keys as an Array of Strings while the later returns an Array of Keys, a different type that has to be converted and could case issues with comparisons.map()
to transform the values to add double quotes before and after each String in the array. Example: if a
is an array the a map ("\""++$++"\"")
will concatenate a double quote before and after each string of a
.%dw 2.0
output application/java
fun listOfString(a)=a map ("\""++$++"\"") joinBy ","
var values = listOfString(valuesOf(payload.Payload))
var columns = listOfString(namesOf(payload.Payload))
---
"insert into " ++ payload.table ++ " (" ++ columns ++ ") VALUES (" ++ values ++");"
Output:
insert into std ("studentName","course") VALUES ("Ronaldo","GOAT");