Ruby format DateTimeParameter in where query - ruby

I want to do a query like this:
bookings = Booking.where(user_id: #current_user.id, start_at: date.to_datetime)
The problem in this case is, that I just get results in bookings which match a timestamp 00:00:00 which is quite logical.
Is there a possibility to format the start_at parameter in the query to date, so that I just compare two dates and not datetimes?

Try convert your datetime field to date via SQL:
bookings = Booking.where(user_id: #current_user.id)
.where("DATE(start_at) = ?", date)
DATE() extracts the date part of a datetime expression.
Note: it does not works in PotsgreSQL
Or:
bookings = Booking.where(user_id: #current_user.id,
created_at: date.beginning_of_day..date.end_of_day)

How about this?
bookings = Booking.where(user_id: #current_user.id, start_at: start_date..end_date)
or
bookings = Booking.where(user_id: #current_user.id)
.where('start_at > ? AND start_at < ?', start_date, end_date)
where start_date and end_date are the two dates you wish to check between.

Related

JPQL query to get last 10 days of data

I have a simple sql query
SELECT * FROM survey t WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -10 DAY);
or
SELECT * FROM survey t WHERE t.date >= ( CURDATE() - INTERVAL 10 DAY )
What is the equaivalent of getting the data using JPQL query for the where condition
Incase if it is useful to anyone
BETWEEN is the word
Call like this in service
repository.getData(new java.util.Date(System.currentTimeMillis() - 10*24*60*60*1000L), new java.util.Date());
in the repositary
#Query(SELECT * FROM survey t WHERE t.date BETWEEN :startDate
AND :endDate)
List<Object[]> data(#Param("startDate") Date startDate,#Param("endDate") Date endDate);

Laravel eloquent possible bug?

I want to join two tables and filter on a field in the joined table. I don't think the actual tables matter in this question, but it's a table with dates joined with a table with the event info, so there are more dates possible for 1 event.
I made this eloquent line:
Event_date::whereRaw('startdate >= curdate() OR enddate >= curdate()')->whereHas('Event', function($q){$q->where("approved",true );})->orderBy('startdate', 'asc')->orderBy('enddate', 'asc')->toSql());
the filter doesn't work though. So thats why i added the ->toSql() to the line.
I get the following back:
select * from `event_dates` where startdate >= curdate() OR enddate >= curdate() and exists (select * from `events` where `event_dates`.`event_id` = `events`.`id` and `approved` = ?) order by `startdate` asc, `enddate` asc
You see that the 'where("approved",true )' results in 'where ..... and and approved = ?)' Where does the questionmark come from??? I tried diferent things, like '1', 1, 'True', True, true, 'true'...everything comes back as a questionmark.
Any suggestions??
Thanks!
Erwin
This is expected behaviour. Laravel uses prepared statements. To get parameters that are put into placeholders, you can use
$query->getBindings();
so for example in your case you can use:
$query = Event_date::whereRaw('startdate >= curdate() OR enddate >= curdate()')->whereHas('Event', function($q){$q->where("approved",true );})->orderBy('startdate', 'asc')->orderBy('enddate', 'asc'));
and now
echo $query->toSql();
var_dump($query->getBindings());
to get both query with placeholders and values that will be put in place of placeholders.

Issue in date conversion in ruby

In my #query I am putting the date in MM-DD-YYYY format. e.g., 01-22-2016. Now I want to search the dates from messages table with that date how can I do. I had added the query:
Message.includes(:user)
.select('messages.*, users.name')
.where(
"users.name ilike ? OR messages.to ilike ? OR messages.created_at.srtftime(\"%Y-%m-%d\") = ?",
"%#{#query}%",
"%#{#query}%",
Date.strptime(#query, "%m-%d-%Y")
)
But I am getting the issue for that:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "%Y-%m-%d" does not exist
I had also added the query as:
Message.includes(:user)
.select('messages.*, users.name')
.where(
"users.name ilike ? OR messages.to ilike ? OR messages.created_at.srtftime("%Y-%m-%d") = ?",
"%#{#query}%",
"%#{#query}%",
Date.strptime(#query, "%m-%d-%Y")
)
But in that the error is coming as: unknown type of %string
From your comment on #Amadan's answer:
If I don't convert my message.created_at then I am getting blank result.
Message.includes(:user)
.select('messages.*, users.name')
.where(
"users.name ilike ? OR messages.to ilike ? OR messages.created_at = ?",
"%#{#query}%",
"%#{#query}%",
Date.strptime(#query, "%m-%d-%Y")
)
This will produce a query with (among others) a condition like this:
messages.created_at = '2016-01-29 00:00:00'
It should be apparent why this won't work.
messages.created_at is a timestamp, and unless the record just happens to have been created at midnight, that equality comparison is going to fail.
What you need to do is compare the date part of messages.created_at to the date from the query. To get the date part of a timestamp in PostgreSQL, you can use either the date() function or the ::date suffix:
Message.includes(:user)
.select('messages.*, users.name')
.where(
"messages.created_at::date = ?",
Date.strptime(#query, "%m-%d-%Y")
)
Hopefully, you don't have dates stored in the database in VARCHAR columns, but DATETIME or equivalent. Don't convert to String, let ActiveRecord handle dates for you: messages.created_at = ?.

Orderby month and year using linq

I'm fetching distinct months from database but the month values are in the form of month and year. ie, Jan-15,Feb-15. How do I get it in Ascending order of both month and year?
Right now I'm getting result as: Apr-15 Feb-15 Jan-15 Mar-15. But I want the result like this: Jan-15 Feb-15 Mar-15 Apr-15.
var months = ((from mnths in context.Table
orderby mnths.Month
select mnths.Month).Distinct()).ToList();
return months;
Thanks.
You can use DateTime.TryParseExact like this:
var months = ((from mnths in context.Table
orderby mnths.Month
select mnths.Month).Distinct()).ToList().OrderBy(m =>
{
DateTime month;
return DateTime.TryParseExact(m, new[] {"MMM-yy"}, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out month)
? month
: DateTime.MinValue;
}).ToList();
You need to call ToList before OrderBy so the original query is executed and you get an IEnumerable<string> instead of an IQueryable.
Just use .NET Sort Method.
First Get All dates from DB
var dates = ((from dts in context.Table
select dts).Distinct().ToList();
return dates;
And then Do
dates.Sort();
dates.Reverse();
And you'll get the result as yo want. (And Store Datetime in Db with type datetime not nvarchar or other).

Delete using active record

How to achieve below query in ActiveRecord ?
"delete from model where date(created_at)=#{some_date}"
where created_at is sql datetime field.
One option I can think is calculate
start_date = starting time of the day
end_date = end time of the day
and
Model.delete_all('created_at' >= start_date, 'created_at' < end_date)
Any other clean option ?
Assuming database you are using is MySql and start_date is a date object.
Use mysql DATE_FORMAT function
Model.delete_all("DATE_FORMAT(created_at, '%Y-%m-%d') >= ?",
start_date.strftime("%Y-%m-%d"))

Resources