Groovy name queried - grails

I got a domain like this:
ZZPartAndTeam
String parts
String team
Parts may have many team.
For ex: part:part1 team:10
part:part1 team:20
part:part2 team:30
How can I query in the domain that get all parts which have multi team?
result:part:part1 team:10
part:part1 team:20
Thanks.

The HAVING clause is not supported by Hibernate Criteria. A way around is to use DetachedCriteria.
import org.hibernate.criterion.DetachedCriteria as HDetachedCriteria
query: { builder, params ->
// This query counts the number of teams per part
HDetachedCriteria innerQry = HDetachedCriteria.forClass(ZZPartAndTeam.class)
innerQry.setProjection(Projections.projectionList()
.add(Projections.count('team').as('teamCount'))
)
innerQry.add(HRestrictions.eqProperty('part', 'outer.part')
// Using innerQuery, this criteria returns the parts having more than one team.
HDetachedCriteria outerQry = HDetachedCriteria.forClass(ZZPartAndTeam.class, 'outer')
outerQry.setProjection(Projections.projectionList()
.add(Projections.distinct(Projections.property('part').as('part')))
)
outerQry.add(Subqueries.gt(1, innerQry))
builder.addToCriteria(Property.forName('part').in(outerQry))
}

Related

Yii2: How to do a inner join of three tables?

I have a many-to-many relationship so I have three tables (administrators, offices and the intermediate table):
I need to do a very simple innerjoin of the three tables to show lastnames and their offices with Active Record. I tried but I couldn't.
This is what I tried:
$admins = Admins::find()
->joinWith(Oficinas::tableName())
->all();
echo '<pre>';
print_r($admins);
echo '</pre>';
die();
Also I would like to know how to show the SQL query so it can help me to find a solution.
You need to specify the relation name for joinWith() rather than table names. Since there isn't any info on the relation names I will use simple innerJoin using table names as per your requirements to display the last name and the office name for the admins.
Admins::find()
->alias('a')
->select('a.lastnameadm, o.nombreofi')
->innerJoin('admin_oficinas ao','ao.idadm = a.idadm')
->innerJoin('oficinas o','o.idofi = ao.idofi')
->all();
Try this:
TABLE_NAME_1::find()
->join('inner join',
'table_name_2',
'table_name_2.column = table_name_1.column'
);
->join('inner join',
'table_name_3',
'table_name_3.column = table_name_2.column'
)->all();
but if you can also use Via like the following example:
public function getClassschedule()
{
return $this->hasOne(TABLE_NAME_2::className(), ['table_name_1.column' => 'table_name_2.column'])
->via('tableName3');
}
when excuded, the results should be obtained like the previous example. so there's no need to repeated relations. full documentation can be seen here :
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record

Neo4j+PopotoJS: filter graph based-on predefined constraints

I have a question about the query based on the predefined constraints in PopotoJs. In this example, the graph can be filtered based on the constraints defined in the search boxes. The sample file in this example visualizations folder, constraint is only defined for "Person" node. It is specified in the sample html file like the following:
"Person": {
"returnAttributes": ["name", "born"],
"constraintAttribute": "name",
// Return a predefined constraint that can be edited in the page.
"getPredefinedConstraints": function (node) {
return personPredefinedConstraints;
},
....
In my graph I would like to apply that query function for more than one node. For example I have 2 nodes: Contact (has "name" attribute) and Delivery (has "address" attribute)
I succeeded it by defining two functions for each nodes. However, I also had to put two search box forms with different input id (like constraint1 and constraint2). And I had to make the queries in the associated search boxes.
Is there a way to make queries which are defined for multiple nodes in one search box? For example searching Contact-name and/or Delivery-adress in the same search box?
Thanks
First I’d like to specify that the predefined constraints feature is still experimental (but fully functional) and doesn’t have any documentation yet.
It is intended to be used in configuration to filter data displayed in nodes and in the example the use of search boxes is just to show dynamically how it works.
A common use of this feature would be to add the list of predefined constraint you want in the configuration for every node types.
Let's take an example:
With the following configuration example the graph will be filtered to show only Person nodes having "born" attribute and only Movie nodes with title in the provided list:
"Person": {
"getPredefinedConstraints": function (node) {
return ["has($identifier.born)"];
},
...
}
"Movie": {
"getPredefinedConstraints": function (node) {
return ["$identifier.title IN [\"The Matrix\", \"The Matrix Reloaded\", \"The Matrix Revolutions\"]"];
},
...
}
The $identifier variable is then replaced during query generation with the corresponding node identifier. In this case the generated query would look like this:
MATCH (person:`Person`) WHERE has(person.born) RETURN person
In your case if I understood your question correctly you are trying to use this feature to implement a search box to filter the data. I'm still working on that feature but it won't be available soon :(
This is a workaround but maybe it could work in your use case, you could keep the search box value in a variable:
var value = d3.select("#constraint")[0][0].value;
inputValue = value;
Then use it in the predefined constraint of all the nodes type you want.
In this example Person will be filtered based on the name attribute and Movie on title:
"Person": {
"getPredefinedConstraints": function (node) {
if (inputValue) {
return ["$identifier.name =~ '(?i).*" + inputValue + ".*'"];
} else {
return [];
}
},
...
}
"Movie": {
"getPredefinedConstraints": function (node) {
if (inputValue) {
return ["$identifier.title =~ '(?i).*" + inputValue + ".*'"];
} else {
return [];
}
},
...
}
Everything is in the HTML page of this example so you can view the full source directly on the page.
#Popoto, thanks for the descriptive reply. I tried your suggestion and it worked pretty much well. With the actual codes, when I make a query it was showing only the queried node and make the other node amount zero. I wanted to make a query which queries only the related node while the number of other nodes are still same.
I tried a temporary solution for my problem. What I did is:
Export the all the node data to JSON file, search my query constraint in the exported JSONs, if the file is existing in JSON, then run the query in the related node; and if not, do nothing.
With that way, of course I needed to define many functions with different variable names (as much as the node amount). Anyhow, it is not a propoer way, bu it worked for now.

grails gorm mongodb `like` functionality in criteria

Is like or rlike supported for searching a string in a collection's property value?
Does the collection need to define text type index for this to work? Unfortunately I can not create a text index for the property. There are 100 million documents and text index killed the performance (MongoDB is on single node). If this is not do-able without text index, its fine with me. I will look for alternatives.
Given below collection:
Message {
'payload' : 'XML or JSON string'
//few other properties
}
In grails, I created a Criteria to return me a list of documents which contain a specific string in the payload
Message.list {
projections {
like('payload' : searchString)
}
}
I tried using rlike('payload' : ".*${searchString}.*") as well. It did not result in any doc to me.
Note: I was able to get the document when I fired the native query on Mongo shell.
db.Message.find({payload : { $regex : ".*My search string.*" }}).pretty()
I got it working in a round about way. I believe there is a much better grails solution. Criteria approach did not work. So used the low level API converted the DBObjects to Domain objects.
def query = ['payload' : [ '$regex' : /${searchString}/ ] ]
def dbObjects = Message.collection.find(query).skip(offset).limit(defaultPageSize).toArray()
dbObjects?.collect { new Message(new JsonSlurper().parseText(it.toString()))}

How to use was clause with Jql

i am developing report plugin for jira where i need to get assignee for given duration.it could be diffrent than current assignee in given duration.
now i am building my query in report like below.
JqlQueryBuilder queryBuilder = JqlQueryBuilder.newBuilder();
query = queryBuilder.where().updatedBetween(stdate,endDate).and().assignee() in(status_val).buildQuery();
return searchProvider.searchCount(query, remoteUser);
i want to get the count for prior assigned issues for given duration.
please let me know how i can use Was clause with assignee and updatedbetween dates.
regards,
tousif shaikh.
Try reading this answer. In short, you'll need to define a new clause and use it in your query, like this:
JqlQueryBuilder builder = JqlQueryBuilder.newBuilder();
WasClauseImpl wasClause = new WasClauseImpl("status", Operator.WAS, new SingleValueOperand("Resolved"), new TerminalHistoryPredicate(Operator.AFTER, new SingleValueOperand(3500000L)));
JqlClauseBuilder clauseBuilder = JqlQueryBuilder.newClauseBuilder(wasClause);
Query query = clauseBuilder.buildQuery();

How to querying across databases with grails?

Is there a way to querying across 2 databases in grails ?
Example (I made a select on two databases - works and test) :
select
c.crf_name,
c.crf_id,
ig.group_id,
ig.group_name,
from
works.crfs c,
test.item_groups ig;
1) I would like to query against two databases, and attach results to a domain.
Or :
2) Is it possible to mixing one query part with data from database and other part with domain class ?
Edit : I need to do a single query mixing tables from 2 databases (one db is PostgreSQL and other db is Mysql). So, in grails is it possible to mix to dataSources beans in one query ?
Edit 2 : Here a better example :
select
igm.item_id,
igm.item_group_id as group_id,
igm.crf_version_id,
ig.name as group_name
from
works.item_group_metadata igm,
test.item_group ig
where
igm.item_group_id=ig.item_group_id
;
If you are planning to do your own sql (like it seems to be the case) over 2 datasources, I suggest that you define your 2 datasources as Spring beans in grails-app/conf/spring.
e.g. (drop your db drivers in /lib and replace the values to match your RDBMS drivers and connection string) :
import org.apache.commons.dbcp.BasicDataSource
import oracle.jdbc.driver.OracleDriver
beans = {
worksDataSource(BasicDataSource) {
driverClassName = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:#someserver:someport:works"
username = "works"
password = "workspassword"
}
testDataSource(BasicDataSource) {
driverClassName = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:#someserver:someport:test"
username = "test"
password = "testpassword"
}
}
Then create a service to handle your queries, like :
import groovy.sql.Sql
class SomeService {
def worksDataSource
def testDataSource
def query1 = """
SELECT crf_name, crf_id
FROM works.crfs
"""
def query2 = """
SELECT group_id, group_name
FROM test.item_groups
"""
def sqlWorks = Sql.newInstance(query1)
def sqlTest = Sql.newInstance(query2)
// Then do whatever you like with the results of the 2 queries
// e.g.
sqlWorks.eachRow{ row ->
def someDomainObject = new SomeDomainObject(prop1 : row.crf_name, prop2 : crf_id)
someDomainObject.otherProp = whateverYouLike()
someDomainObject.save()
}
}
Your query doesn't have a where clause so I don't know how you want to relate the data coming from your 2 tables...
If you want to do a single query mixing tables from 2 databases, (ask your DBA to) establish a DBLink between databases test and works and perform the query on the datasource containing the DBLink.
I hope this helps.
You should use a "UNION SELECT" which is supported by most databases. Make sure that both select statements have the same number of columns.
select
crf_name,
crf_id
from
ig
UNION SELECT
group_id,
group_name
from
id
A union select concatenates the results for 2 queries, for example:
select 1 union select 2
Have you looked at the Datasources plugin? It sounds like it will do what you require, but I think you'd need to use HQL or finders on the domain objects directly, rather than SQL, for it to work.
I haven't used the plugin myself but I'd be interested to hear how it goes it you try it.
HTH

Resources