How to get value of nested Map using parameter - sql

I'm trying to get value of nested Map using parameter of SQL component expression but it failed.
I have this json (unmarshal to java.util.Map):
{ "username" : "john",
"company" : { "companycode" : "stackoverflow.inc",
"address" : "Street 12" }
}
And I have this SQL expression with parameters on my Route builder:
...
.unmarshal().json(JsonLibrary.Jackson)
.to("sql:INSERT INTO user_tab VALUES (:#username, :#company.companycode)")
...
I was able to get the value of username but I can not get the value of companycode. What is the right way to do it? Thank you.

according: http://camel.apache.org/sql-component.html
From Camel 2.14 onward you can use Simple expressions as parameters as shown:
sql:select * from table where id=:#${property.myId} order by name[?options]
this work fine for me:
{guid=67, properties={last_seen=1472034553348, _type=business_service, name=Anna, created_at=1472033602648, status=USUNIĘTY}}
<to uri="dbSQL:insert into table_name (
guid,name,description,type,status,changedate,transid,transseq
) values (
:#${body[guid]}::integer, :#${body[properties][name]}, :#${body[properties][name]}, :#${body[properties][_type]}, :#${body[properties][staus]}, now(), 0, 0
)"/>

Related

How to change key part of query string dynamically in karate

I have the below requirement where I need to dynamically change the key-value pair of the query string, but I am able to dynamically change the value of the query parameter but not the key part. It is taking the text value like 'paramName' in the request.
string reqBody = version == 'v2' ? 'ABC' : 'DEF'
string paramName = version == 'v2' ? 'json_body' : 'proto_body'
param paramName = reqBody
GET https://test.apis.com/sample?paramName=ABC
or
GET https://test.apis.com/sample?paramName=DEF
If you need dynamic param names, use params: https://github.com/karatelabs/karate#params
* def temp = version == 'v2' ? { json_body: 'ABC' } : { proto_body: 'DEF' }
* params temp
If you still have questions, read this: https://stackoverflow.com/a/50350442/143475

Fix "dynamic" query without throwing me the given error?

UPDATE dbo.Einkauf_Web_Upload
SET
${
updatedUpload.Menge !== null
? `Anzahl = ${`${updatedUpload.Menge}`},`
: null
},
${
updatedUpload.ENummer !== null
? `ENummer = ${`'${updatedUpload.ENummer}'`}`
: null
}
WHERE ...
This query is supposed to differentiate between updated values of the object updatedUpload which, initially, has all of its values set to null. If the value is not altered therefor not updated, the query must not affect the particular column. In its current state, the query throws this error:
Incorrect syntax near the keyword 'null'
And I know why; if you do not alter the Menge attribute, the query looks like this:
UPDATE dbo.Einkauf_Web_Upload
SET null, ENummer = "abc"
WHERE ..
Is there a workaround to this? I am using NodeJs as my backend and thought of trying to make the column references dynamic via a mapped array which contains only the altered columns of updatedUpload.
Will appreciate any help!
SET null, ... is invalid SQL syntax, you should skip the null at all. Furthermore, remember not to do the query if there is nothing to update as SET WHERE ... is also invalid syntax.
I would suggest something like:
let updates = [
updatedUpload.Menge !== null ? `Anzahl = ${`${updatedUpload.Menge}`}` : null,
updatedUpload.ENummer !== null ? `ENummer = ${`'${updatedUpload.ENummer}'`}` : null,
// ... add here
]
// Filter out null updates
updates = updates.filter(u => !!u);
// Do query only if updates are avaliable
if (updates.length > 0) {
const sql = `UPDATE dbo.Einkauf_Web_Upload SET ${updates.join(', ')} WHERE ...`;
// ... execute
}

Criterion based on boolean TSQL function

I'm calling the sql server function Contains like this :
ftquery = _OrElse(ftquery,Restrictions.Eq(Projections.SqlFunction("contains",NHibernateUtil.Boolean, Projections.Property<Document>(d => d.SearchContent), Projections.Constant(query.Query)),true));
OrElse will juste do an or using Restrictions.Or(ICriterion, ICriterion). The problem is that it generates invalid sql :
... and contains(this_.SearchContent, ?) = ? ORDER BY ...
I don't want to have the right part ( = ? ), I only need the Projection without the Restrictions.Eq, but without Restrictions.Eq I can't find any solution to convert a Projection to a Criterion.
How can we using NHibernate generate an sql like :
Select Name from Users where Contains(Name,'toto') or Contains(Job,'tata')
Register the function in your dialect:
RegisterFunction("FullTextContains", new StandardSQLFunction("contains", NHibernateUtil.Boolean));
Create a projection using Projections.SqlFunction then use this ProjectionAsCriterion class on your query:
var projection = Projections.SqlFunction("FullTextContains",
NHibernateUtil.Boolean,
Projections.Property<Document>(x => x.SearchContent),
Projections.Constant(query.Query));
var result = Session.QueryOver<Document>()
.Where(new ProjectionAsCriterion(projection))
.List();

Grails: "where" query with optional associations

I'm trying to run a "where" query to find a domain model object that has no association with another domain model object or if it does, that domain model object has a specific property value. Here's my code:
query = Model.where({
other == null || other.something == value
})
def list = query.list()
However, the resulting list only contains objects that match the second part of the OR statement. It contains no results that match the "other == null" part. My guess is that since it's checking a value in the associated object its forcing it to only check entries that actually have this associated object. If that is the case, how do I go about creating this query and actually having it work correctly?
You have to use a LEFT JOIN in order to look for null associations. By default Grails uses inner join which will not be joined for null results. Using withCriteria as below you should get the expected results:
import org.hibernate.criterion.CriteriaSpecification
def results = Model.withCriteria {
other(CriteriaSpecification.LEFT_JOIN){
or{
isNull 'id'
eq 'something', value
}
}
}
UPDATE
I know aliasing is not possible in DetachedCritieria where one would try to specify the join as in createCriteria/withCriteria. There is an existing defect regarding adding the functionality to DetachedCriteria. Just adding the work around for where query as mentioned in defect.
Model.where {
other {
id == null || something == value
}
}.withPopulatedQuery(null, null){ query ->
query.#criteria.subcriteriaList[0].joinType = CriteriaSpecification.LEFT_JOIN
query.list()
}
I would rather use withCriteria instead of the above hack.
this might work:
query = Model.where({
isNull( other ) || other.something == value
})
If that wouldn't work, try something like:
other.id == null || other.something == value
UPDATE:
or with good'ol criteria query:
list = Pack.withCriteria{
or{
isNull 'other'
other{ eq 'something', value }
}
}

How to sort result by field?

I have a simple example:
result = db.command({
'findandmodify' : 'Task',
'remove' : True
})
print result
How to get first inserted element ? ( order by _id )
The find_one method in pymongo should return the first document in the collection: http://api.mongodb.org/python/current/tutorial.html#getting-a-single-document-with-find-one