I have this column_property which checks how many credits a user is allowed:
select(
[func.ifnull( func.sum( orders_table.c.quantity ), 0 )],
orders_table.c.user_id == users_table.c.id
).where( and_(
orders_table.c.date_added < now_unix(),
orders_table.c.date_expires > now_unix(),
orders_table.c.status == STATUS_COMPLETED
) ).label( 'userAllowedCredits' ),
deferred = True
The now_unix() method returns the current unix timestamp but the problem is that this method is loaded only once and every time I call this userAllowedCredits property the query searches based on the same initial value that was saved when my app was started. I need this now_unix() method to return the actual current timestamp at every call.
Do I make any sense?
You probably store this expression at startup, so now_unix() is only executed at that time. From the SqlAlchemys point of view, it's just a value. How to solve this, depends a bit on your use case. You could use now(), which would use the database build in now() function. If you have to use your own now_unix(), you can still pass it as a parameter.
Related
In my application, a user can specify a date in a form, via a datepicker. Doing so, the date has this format : "2018-05-16T12:45:30Z".
Then, I want to store it in a MySql database, in a TIMESTAMP column.
Later, the user can edit his data. Consequently, the datepicker has to be initialized with the date coming from the server, previously saved.
To manage this, I created an accessor and a mutator :
public function setDateNameInputAttribute($value)
{
$this->attributes['date_name_input'] = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $value);
}
public function getDateNameInputAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d\TH:i:s\Z');
}
This code works fine : my front-end reads UTC (Zulu) dates and I can insert timestamps in my database.
However, it's not perfect.
Let's say I need for whatever reason to add one hour to a stored date
$myObject = MyClass::find(1);
$theDate = $myObject->dateNameInput;
Now $theDate is a "T Z format" string, because of the accessor. I could recreate a Carbon object to do my addition, but I think this Carbon -> string -> Carbon transition would be ugly. How can I make a nice operation ?
If my applications contains a lot of input dates, with many different model names, is there a way to generalize my accessor and my mutator ?
Actually, is my first approach good ?
Thanks for reading !
I have an external service that allows me to log users into my website.
To avoid getting kicked out of it for overuse I use a MySQL table on the following form that caches user accesses:
username (STRING) | last access (TIMESTAMP) | has access? (TINYINT(1) - BOOLEAN)
If the user had access on a given time I trust he has access and don't query the service during a day, that is
query_again = !user["last access"].between?(Time.now, 1.day.ago)
This always returns true for some reason, any help with this logic?
In ranges (which you effectively use here), it is generally expected that the lower number is the start and the higher number is the end. Thus, it should work for you if you just switch the condition in your between? call
query_again = !user["last access"].between?(1.day.ago, Time.now)
You can test this yourself easily in IRB:
1.hour.ago.between?(Time.now, 1.day.ago)
# => false
1.hour.ago.between?(1.day.ago, Time.now)
# => true
I have a document in CB which has two dates, a start date and an end date. Let's say, a product's price discount. 10% off starting from today and ends next Friday. How can I get all the documents from CB which have a valid discount today?
I made a view and have the following in it:
var dt = new Date();
Which gets today's date. Then I can do a simple
if(doc.FromDate < dt && doc.ToDate > dt){ emit([ ..... ]);
This filters the documents how I want. But...
Question
Is this a good approach re view and index updating? Will the index update every day because the date changed? Just trying to understand the working of CB in this respect
What is the best approach for this type of searching? If not possible please tell me!
Cheers
Robin
Note: Please note, the question is NOT like this here or this here
Let's me clarify something here:
the map() function is used to create/update the index on disk, and this occurs just "after" the document is saved on disk. This is why using date.now() in the map reduce does not really makes sense.
So what you will do is to emit the date for example emit( dateToArray(doc.startDate) );
then when you query the view(index) you can use the startkey & endkey to do a range query.
&startkey=[2013,4,16]&endkey=[2013,4,24]
the index won't be updated just because system date changed, you have to update the document. also view indexer doesn't allow you to pass any arguments defined by user. in this case you should emit the data and use date as a part of the key to filter on view query. I guess the same behaviour for SQL indexes too. you cannot predict when exactly this document will indexed, in your example you are freezing timestamp when the doc has been indexed, it isn't even the time when it was changed
I created a service and callResponder (Via Generate Service Call and Generate Form in Flash Builder 4) that query a MySQL database for a name and a birth date.
My problem is so simple I guess but I haven't been able to find the solution...
When I have an empty date in MySQL (0000-00-00), my binded DateField indicates 1899-11-30
I tried almost everything possible... A custom labelFunction, a custom function called straight after the call to my service to try to handle my data like this.. :
protected function parseDate(date:Date):void
{
if (date.getFullYear() == -1) {
friendbirthdate.selectedDate = null;
} else {
var df:DateFormatter = new DateFormatter;
df.formatString = 'YYYY-MM-DD';
friendbirthdate.selectedDate = date;
}
}
Unfortunately, this works only partially. When I try to update this same form in the database I get disconnected. I'm missing something here and would greatly appreciate a tip or two :-)
THANKS!
I recommend that you store NULL for unknown dates, as opposed to '0000-00-00'. NULL is a more accurate value in this case.
If you want to store it as NULL and display it as a different value you can do something like this:
SELECT COALESCE(date_column,'0000-00-00') as formatted_date
FROM your_table
Don't know if it will help somebody but I had trouble to insert values from a form, containing a DateField. That Form has been generated through the Flash Builder Generate Form tool.
The problem is that the service generated by Flash Builder expect a Date Object, no matter what... If you submit the form without selecting a date in the DateField, the service call crashes.
Let's have a look at a part of the generated sample service (Create and Update functions), we can see that PHP is expecting to transform a Date Object to a String like this :
mysqli_stmt_bind_param($stmt, 'sss', $item->friendname, $item->friendlastname, $item->friendbirth->toString('YYYY-MM-dd HH:mm:ss'));
First of all, be sure that your Date field in MySQL has as NULL default value.
Then alter the create and update functions like this :
if ($item->friendbirth == null)
$friendbirth = null;
else
$friendbirth = $item->friendbirth->toString('yyyy-MM-dd HH:mm:ss');
mysqli_stmt_bind_param($stmt, 'sss', $item->friendname, $item->friendnickname, $friendbirth);
This way, the service call script won't try to do kinda null->toString('...')
I have a Linq2Sql query that looks like this:
var data = from d in dc.GAMEs
where (d.GAMEDATE + d.GAMETIME.Value.TimeOfDay) >= DateTime.Now
&& d.GAMESTAT == 'O' && d.GAMETYPE == 0 select d;
Resharper is underlining the "d.GAMETIME.Value.TimeOfDay" in blue and telling me it's a possible System.InvalidOperationException. While I get that if it were C# code, referencing Value without checking if it has a value would be such, i'm not sure if that is true of a Linq query.
The actual SQL generated looks horrendous, and makes me want to burn my eyes out, but I see nothing that looks like it could be a null reference. Can I safely ignore this?
(ignore for the moment the other issues, such as if it returns the expected results)
EDIT:
Upon further thought, I can see how the above might cause an exception in a LinqToObjects query, and possibly other kinds (XML?). So yeah, I suppose Resharper is just being safe.
When dealing with expression trees (as this LINQ to SQL query) it totally depends on the LINQ provider used (in your case LINQ to SQL). Therefore, it is (almost) impossible for Resharper to say anything useful about your query. I think it just interprets this code as normal C# delegates. I would say it is safe to ignore, but perhaps add a comment for the next developer.
Without seeing the data schema my guess is that GAMETIME is Nullable<DateTime> - i.e. maps to datetime/time field in the DB that can be null. Resharper is simply giving you a static analysis warning that you are referencing Nullable<T>.Value without checking that it has a value.
You can rewrite the query in this way:
var data = from d in dc.GAMEs
where (d.GAMEDATE + (d.GAMETIME.HasValue ? d.GAMETIME.TimeOfDay : new TimeSpan())) >= DateTime.Now
&& d.GAMESTAT == 'O' && d.GAMETYPE == 0 select d;
The above query will just use a TimeSpan of 0 when GAMETIME is NULL.
Considering that GAMEDATE is a non-nullable database field and GAMETIME is a nullable one, I recommend that you make GAMETIME non-nullable too. This way the two fields are consistent and do not need extra logic to handle NULL values.
EDIT I have just confirmed that trying to call Nullable<T>.Value does indeed throw InvalidOperationException, not NullReferenceException.
From the horse's mouth (bolding is mine):
The two fundamental members of the
Nullable structure are the HasValue
and Value properties. If the HasValue
property for a Nullable object is
true, the value of the object can be
accessed with the Value property. If
the HasValue property is false, the
value of the object is undefined and
an attempt to access the Value
property throws an
InvalidOperationException.