Ruby on Rails Active Record Query - counting records - ruby-on-rails

Hi I'm new to rails and developing an application to pull results from database in preparation for charting. I have the following code in my controller:
#statistic = OutstandingWorkIndex.find_by_sql ["SELECT Result_Set.Set_Code, Request.Specimen_Number ,
DATEDIFF('hh',Result_Set.Date_Time_Booked_In,current_timestamp) as HrsIn FROM iLabTP.Outstanding_Work_Index, iLabTP.Result_Set Result_Set, iLabTP.Request
WHERE Outstanding_Work_Index.Request_Row_ID = Result_Set.Request_Row_ID and Outstanding_Work_Index.Request_Row_ID = Request.Request_Row_ID and Result_Set.Set_code=?
order by Result_Set.Date_Time_Booked_In DESC", params[:set_code].upcase]
What I'd like to do is count the number of records returned in addition to the object from above which I then use to create and XML stream of paired values or use the google charts java script api in the view.
Do I need to issue commands like:
#statistic = OutstandingWorkIndex.find_by_sql ["SELECT Result_Set.Set_Code, Request.Specimen_Number ,
DATEDIFF('hh',Result_Set.Date_Time_Booked_In,current_timestamp) as HrsIn
FROM iLabTP.Outstanding_Work_Index, iLabTP.Result_Set Result_Set, iLabTP.Request
WHERE Outstanding_Work_Index.Request_Row_ID = Result_Set.Request_Row_ID and Outstanding_Work_Index.Request_Row_ID = Request.Request_Row_ID and Result_Set.Set_code=?
order by Result_Set.Date_Time_Booked_In DESC", params[:set_code].upcase].**count**
And if so does this result in the query being reissued?
Thanks

You should do:
#size = #statistic.size
It's well explained here.

Related

Denodo Json Source and Base View: how to make VQL more traditional SQL syntax

I have a web service api
In Denodo, I have virtualized the following api:
https://delphi.cmu.edu/epidata/fluview/?regions=nat&epiweeks=201501,201601,201701
as
https://delphi.cmu.edu/epidata/fluview/?regions=#{regions}&epiweeks=#{epiweeks}
This allows us, in Denodo, to write the following:
Select * from bv_fluview where epiweeks = '201501,201601,201701' and regions = 'nat'
Is there any way where the query could be written in a more traditional way such as:
Select * from bv_fluview where epiweeks in ('201501','201601','201701') and regions = 'nat'
I am relatively new to Denodo.
Thanks,
Dan
In Denodo, you can use the IN clause to check if a value is present in a list
SELECT *
FROM bv_fluview
WHERE epiweeks IN ('201501','201601','201701')
AND regions = 'nat'
This would return the same result as your original query but with a more conventional syntax for the IN operator.

How do I use join and indexBy in Yii2?

I have this, but it loads each and every ebay row individually, generating thousands of SQL statements:
$products = \app\models\Product::find()
->joinWith('ebay', false, 'inner join')
->indexBy(function($row){return $row->ebay->epid;})
->all();
I tried this, but it gave an error: 'Getting unknown property: app\models\Product::ebay.epid'
$products = \app\models\Product::find()
->joinWith('ebay', false, 'inner join')
->indexBy('ebay.epid')
->all();
Setting eager loading = true doesn't help either. It still loads each row individually then loads them again at the end.
How can I efficiently join a table in Yii and index by a value in the joined table?
You won't be able to do it with indexBy. However, ArrayHelper::index can index an array on a related model field. So here's how it can be done:
$products = \app\models\Product::find()
->with('ebay')
->all();
ArrayHelper::index($products, 'ebay.epid');
The code will run two queries, one to get all products, one to get all related ebay products. Then the array will be indexed with no DB queries at all.
I ended up doing it manually for a subset of the ids and it only uses 2 queries. I'd still be interested in the indexBy though.
$products = Product::find()->joinWith('ebay', true, 'inner join')->where(['ebay.epid' => $productIds])->all();
$ebayProducts = array();
foreach ($products as $p) {
$ebayProducts[$p->ebay->epid] = $p;
}
If you want index by relation recods via joinWith() or with() results you can use following:
->with(['relationName' => function($q) {
$q->indexBy('field_name');
}])

Searching HP-Trim / Records-Manager using SDK

Using the HP-Trim SDK, how do you search for a document by its reference number?
The alleged documentation refers to methods for straightforward searches:
SelectByPrefix
SelectFavorites
SelectByUserLabel
SelectNone
SelectAll
SelectByUris
SelectTopLevels
SelectThoseWithin
and a generic search:
records.SetSearchString(“createdOn:this week and assignee:me”);
but all I want to do is find a document by its index.
These don't work:
records.SetSearchString("recordNum: <RecordNumber>");
records.SetSearchString("recordNumber: <RecordNumber>");
records.SetSearchString("reference: <RecordNumber>");
Any suggestions?
Are you using the .NET SDK? If so you can grab a record by its record number like so (C# example):
using (Database db = new Database()) {
db.Connect();
Record record = new Record(db, "123456"); // Replace with record number
// Do stuff with record
Console.WriteLine(record.Title);
}
You aren't required to construct a 'formal search' as such.
In case you're curious about the correct string search syntax, this would have worked:
records.SetSearchString("number: <RecordNumber>");
Using the COM SDK;
using (Database db = new Database()) {
db.Connect();
Records records = db.MakeRecords();
records.SelectAll();
records.FilterString = "number:<RecordNumber>";
if (records == null || records.Count.Equals(0))
return;
Record existing = records.Item(0);
}

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 make LIMIT work in Grails HQL executeUpdate()?

I'm running grails 1.3.6 and I have this code:
String hql = '''
UPDATE
ApiResponse a
SET
a.lockId = :lockId
WHERE
a.lockId = 0
ORDER BY
a.dateAdded asc
LIMIT 5
'''
ApiResponse.executeUpdate(hql, [lockId : workerId])
It seems that this code updates all rows in DB instead of the 5 oldest entries. Does this mean LIMIT is not working in HQL? Please help me how to achieve the same SQL logic in GORM or HQL. Basically, I need to do a bulk update using LIMIT.
what i do (grails 1.3.7):
ExAus.executeQuery( "select distinct <field> from <controller>", [max: 20, offset: 0] )
While waiting for someone to reply, I think I found a workaround. Here it is:
def c = ApiResponse.createCriteria()
def targetList = c.list {
eq('lockId', 0)
maxResults(5)
order("dateAdded", 'asc')
}
String hql = '''
UPDATE
ApiResponse
SET
lockId = :lockId
WHERE
id in (:ids)
'''
ApiResponse.executeUpdate(hql, [lockId : workerId, ids: targetList.collect {it.id}])
I believe this approach can still be considered same logic with the original. However, this has to make 2 queries.
Feel free to suggest other approaches. Thanks!
I know the post is quite old but the question is still relevant since I had the same problem.
I fell back to using Groovy sql (jdbc) instead.
You will need to inject the dataSource object within your service/controller first by using:
def dataSource
Then you may do this in your method:
String sqlQuery = '''
UPDATE
API_RESPONSE a
SET
a.LOCK_ID = :lockId
WHERE
a.LOCK_ID = 0
ORDER BY
a.DATE_ADDED asc
LIMIT 5
'''
def sql = new Sql(dataSource)
sql.executeUpdate(sqlQuery, [lockId : workerId])
Note that you will need to use the database native table and column names in the sql query.

Resources