How to delete all rows where date is older than two weeks ago using Grails' Gorm - grails

I am new to Gorm, and currently have a requirement where I need to delete all records older than two weeks.
Right now I am querying my table like this:
String query = "select a from history a where successful = :successful"
List<History> histories = History.executeQuery(query, null, [max:null, offset:null])
for (History history: histories){
Date date1 = New Date()
Date date2 = New Date(history.date)
use(groovy.time.TimeCategory) {
def duration = date1 - date2
if (duration.days > 14){
// delete here
}
}
}
I am certain there is a better and more efficient way to delete all records older than 14 days using gorm, I was wondering if anyone had any knowledge on how to do this? Thank you!

The GORM documentation recommends a couple of options, how about something like:
def twoWeeksAgo = use(TimeCategory){ new Date() - 2.weeks }
History.where{
date < twoWeeksAgo
}.deleteAll()

Related

Get total count of sql records of matched date

I'm trying to return a count of records from a database with today's date, using entity framework. I think my query is ok, if you take a look at the screenshot record 2 is the only item out of the 3 with todays date, which is correct.
How can i return a count. Currently its returning a bool value
Thank you
Dim today = DateTime.Today.Date
Dim todaysBuild = retrieveOrders.[Select](Function(build) build.TimeAndDate >= today).ToList()
EDIT:
Dim todaysBuild = retrieveOrders.Where(Function(build) build.TimeAndDate >= today).ToList()
The variable todaysBuild is a list. You need the count (Integer) of that list so add the .Count at the end of your code.
Dim todaysBuild = retrieveOrders.[WHERE](Function(build) build.TimeAndDate >= today).ToList.Count

Querying between two date values in asp.net mvc5

I have a treatmentDate column in the database where dates to treated patients are submitted. If I need to generate report of Total Sum say between January 01 2015 and Jan 30 2015 for a particular company, how do I construct my query.
Below is what I have done and I'm having errors
var treatmentSum = (from s in db.Treatments
where (s.CompanyId == CompanyID)
s.TreatmentDate >= fromDate && s.TreatmentDate <= toDate
select s.Amount).Sum();
ViewBag.TreatmentSum = treatmentSum;
Here's the treatment date column I want to search through.
Your guidance will be highly appreciated.
You didn't post the error message. You are trying to compare strings using the <= and >= , instead try to handle all of your Date and Time variable as DateTime properties.
Here's a piece of code for the LINQ expression:
DateTime FromDate= Convert.ToDateTime("04/20/2015");
DateTime ToDate= Convert.ToDateTime("04/28/2015");
ViewBag.TreatmentSum = GetAllTreatments.
Where(c=>Convert.ToDateTime(c.TreatmentDate)>=FromDate &&
Convert.ToDateTime(c.TreatmentDate)<=ToDate).
Sum(c=>c.Amount);
Also Here's a link to a demo for your specific problem : https://dotnetfiddle.net/1a50HI
You've got some formatting issues:
var treatmentSum = (from s in db.Treatments
where s.CompanyId == CompanyID &&
s.TreatmentDate >= fromDate && s.TreatmentDate <= toDate
select s.Amount).Sum();
ViewBag.TreatmentSum = treatmentSum;
You had a where in the middle of the statement:
where (s.CompanyId == CompanyID) and you weren't separating it with &&
Edit
As stated the dates are in string, you could convert them inline, although be aware you may need to provide some CultureInfo so the formatter knows how to convert the date:
var treatmentSum = (from s in db.Treatments
where s.CompanyId == CompanyID &&
Convert.ToDateTime(s.TreatmentDate) >= fromDate && Convert.ToDateTime(s.TreatmentDate) <= toDate
select s.Amount).Sum();

Can I Compare the day name with the date Entity Framework 6

I am working on news function. News model contains publishing date....
Is there a way to filter my record from db on the base of Publishing Date's day name such as in controller action:
var data1 = db.News.Where(x => x.PublishingDate >= DateTime.Now
&& x.PublishingDate.Day == (int)DayOfWeek.Sunday);
ViewBag.SundayNews = data1;
Or if there is another way around or any reference.
Try this solution: http://c-sharp-snippets.blogspot.ru/2011/12/getting-dayofweek-in-linq-to-entities.html
var firstSunday = new DateTime(1753, 1, 7);
var filtered = from e in dbContext.Entities
where EntityFunctions.DiffDays(firstSunday, e.SomeDate) % 7 == (int)DayOfWeek.Monday
select e;
firstSunday stores the minimal value for MS SQL DATETIME type.

Grails - dynamic finders derived date query GORM

I have the following domain class
class Book {
String title
Date releaseDate
Integer daysOnShelf
Author author
}
How can I list all books where current date is greater than the releaseDate + daysOnShelf? For instance, don't list if 2015-02-10 + 5 (releaseDate + daysOnShelf) since date is less than now.
Can this be done using GORM dynamic finders or Criteria Builder ? e.g.,
def index(Integer max) {
def books = Book.findAll {
releaseDate.plus(daysOnShelf) < new Date()
}
respond books
}
This should acchieve what you want:
Date dateMinusDaysOnShelf = new Date() - daysOnShelf
Book.findAllByReleaseDateLessThan(dateMinusDaysOnShelf)

How do I find that March 2nd and March 3rd falls between March 1st and March 4th?

I need a way to find these in grails:
1) I have two dates say start and end.
2) User selects two dates in the browser say them userStartDate and userEndDate.
I have all these values, but I need to write a query that do find that both start and end falls between userStartDate and userEndDate.
For example, March 2nd and March 3rd falls between March 1st and March 4th. Given that :
March 2nd and March 3rd are userStartDate and userEndDate dates respectively
March 1st and March 4th are start and end respectively. (they are domain objects).
I have this code which works for between cases i.e start is in between userStartDate and userEndDate like so :
test = Holiday.createCriteria().list {
and {
user {
eq('username',username)
}
or {
between('start',userStartDate,userEndDate)
between('end',userStartDate,userEndDate)
}
}
}
As according to my question, how can attach that part into my code?
Thanks in advance.
Assuming that you already do a check that userStartDate is before userEndDate (validated when the user selects) and that start is before end in the database (validated when inserting), the criteria query should look something like this:
test = Holiday.createCriteria().list {
user { eq('username',username) }
lt('start', userStartDate)
gt('end', userEndDate)
}
This checks that start is less than (i.e. before) userStartDate and that end is greater than (i.e. after) userEndDate. There is also no need to wrap in an and block since all clauses are implicitly and-ed.
Date provides before and after methods (http://docs.oracle.com/javase/6/docs/api/)
if(start.after(userStartDate) && start.before(userEndDate))
{
//start is between userStartDate && userEndDate
}
The simplest way to figure out if one date is between two others is using a Range object
def start = new Date()
def end = new Date() + 10
// make a date range
def dateRange = start..end
// test if some dates are within the range
def inRange = new Date() + 5
def outsideRange = new Date() + 50
assert inRange in dateRange
assert !(outsideRange in dateRange)
However, you mentioned that you want to compare dates in a query, so a Groovy solution may not be optimal. Here's an example for checking if someone's birthday is between 2 dates using a criteria query
def start = new Date()
def end = new Date() + 10
def results = User.withCriteria {
between('birthday', start, end)
}

Resources