json formatting of timestamp - mysql

I got an AngularJS client, nodeJS server, and a MySQL DB.
I am trying to delete an entry of a table, when timestamp is a primery key with user Email.
The JSON giving me the this data from the DB:
[{"instanceTime":"2018-02-10T14:19:29.000Z","item":"write papter","email":"admin#gmail.com","ischeck":0},
{"instanceTime":"2018-02-10T14:19:33.000Z","item":"paint chair","email":"admin#gmail.com","ischeck":0},
{"instanceTime":"2018-02-10T15:07:34.000Z","item":"yes","email":"admin#gmail.com","ischeck":0}]
But the deletion with this "instanceTime" gives an error:
DELETE FROM tododb.taskstable WHERE (instanceTime like '2018-02-10T15:07:34.000Z' AND email like 'admin#gmail.com' );
errError: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '2018-02-10T15:07:34.000Z' for column 'instanceTime' at row 1
Why is the formating "2018-02-10T14:19:29.000Z" this way?
When I am using:
DELETE FROM taskstable
WHERE (instanceTime like "2018-02-10 14:19:29" AND email like "admin#gmail.com");
everything works just fine

I did 2 things to fix this problem.
Change DB time field to int(11) and inserted new value with the current UNIX timestamp instead-
insert into taskstable
values (UNIX_TIMESTAMP(NOW()),"to call mom","admin#gmail.com",false);
The UNIX timestamp is a lot easier to manage since it is just a countdown.
I changed the view formatting in the HTML page, to show UNIX time as the desired human-readable version, this way:
{{t.instanceTime * 1000 | date:'yyyy-MM-dd HH:mm:ss'}}
Not exactly what I asked, but I found this a lot easier.

Related

Grafana dashboard using MySQL: how should I deal with timestamp of "%Y%m%d%H%i%s" to use as time column of panel?

I want to visualize my MySQL DB table to an hourly basis graph using Grafana dashboard. The table that I'm working with has the attributes below, with unused ones including PK not mentioned:
SERVER_NAME varchar(250)
STAT_TYPE int(11)
STAT_DTM varchar(14)
CPU_MAX_USAGE int(11)
MEMORY_MAX_USAGE int(11)
What matters is STAT_DTM. Its format is "%Y%m%d%H%i%s", e.g. "20210621090000"; for 09:00:00 of June 21st 2021. I want this to be the X axis of the graph. Grafana guide says:
return column named time or time_sec (in UTC), as a unix time stamp or
any sql native date data type. You can use the macros below.
So I put unix_timestamp(date_format(str_to_date(substr(stat_dtm, 1, 10),'%Y%m%d%H'), '%Y-%m-%d %H:00:00')) but an error saying db query error: query failed - please inspect Grafana server log for details popped up.
select
unix_timestamp(date_format(str_to_date(substr(stat_dtm, 1, 10),'%Y%m%d%H'), '%Y-%m-%d %H:00:00')) as 'time',
CPU_MAX_USAGE,
MEMORY_MAX_USAGE
from lcop.tb_stat_os_day
where stat_type = 60 and server_name = 'LDFSWAS1'
The Panel I'm currently working on
The result of the query above
How can I set the timestamp correctly and show the graph? The table schema cannot be modified unfortunately and I can give any additional info if needed. Thanks in advance.
Let's simplify your type conversion there:
SELECT '20210621090000' as `src`,
UNIX_TIMESTAMP(STR_TO_DATE('20210621090000', '%Y%m%d%H%i%s')) as `dts`
The STR_TO_DATE() function can be given the full format, which can then be given to UNIX_TIMESTAMP. There is no need to make things more difficult with SUBSTR() or DATE_FORMAT() 👍🏻

Rails and MySql datetime behaviour

I just noticed something odd in my Rails application.
When I update a DateTime column with a random value like below code, it automatically generates a wrong DateTime and saves it instead of NULL.
user = AdminUser.last
data = {last_sign_in_at: "1234568!"}
user.update_attributes(data)
And it generates a query like below:
UPDATE `admin_users` SET `last_sign_in_at` = '1234-01-01 04:56:02', `updated_at` = '2018-01-24 21:27:50' WHERE `admin_users`.`id` = 3
Where is that odd DateTime value coming from ? And interestingly it works with that specific random value. Not with something like "invalid!" and "1234568!" .
So is this something to do with MySql or Rails query generation ?
Maybe I am not aware of such things in database, as it is not something I work with regularly .
It looks like rails use Time library to convert your 1234568! and if you try that in rails console like Time.zone.parse('1234568!') you get back a Time object Sun, 01 Jan 1234 00:00:00 UTC +00:00 but if you try to do a Date.parse(1234568!) it throws you an ArgumentError: invalid date error so maybe you can parse using date to avoid that.

Ruby active record inserting datetime instead of time in mysql

Rails Active Record save uses datetime in insert query although the datatype is time in mysql and time is set in model before saving
mysql schema:
rtime time DEFAULT NULL
ActiveRecord model: Abc
abc = Abc.new {'rtime'=> '18:23 PM'}
abc.save!
corresponding mysql query generated by active record:
insert into abces (rtime) values('2000-01-01 18:23:00');
Later in mysql only the time is stored and date is sliced off, and a warning is also generated.
+-----------------------+
| rtime |
+-----------------------+
| 18:23:00 |
+-----------------------+`
Why is the date appended with time while mysql insertion?
Rails version: 3.2.16
Looks like ActiveRecord often falls back to a DateTime object when assigning a Time in Rails 3+: https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/attribute_assignment.rb#L130
There's some documentation on the conversion method here: http://apidock.com/rails/Time/time_with_datetime_fallback/class. Also, there's a comment that hints at this on line 180 of the same file: # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
Thus it seems Rails 3 often treats Time objects as though they were DateTimes, which explains the odd insert query you're seeing. The behavior seems to be changed in Rails 4 so upgrading may resolve the issue.
In any case the date values seem to simply get truncated by MySQL hence the warning, but the stored time seems correct to me.
Finally, do you need a timezone for this time?

How can I retrieve data from the database when the date > now()

My purpose is since the time I login my page, I want my web to show how many updated data in the database. My code is like this
$current = $_SESSION['date'];
$query2 = "SELECT * FROM gmaptracker1 WHERE datetime >= '$current'";
When I echo the $current, it showed 27/09/14 : 06:53:24, so the $current is correct, however, when I request the number of database where date>='$current', I get zero, although I have inserted to the database the data with datetime 28/09/14 : 06:53:24 and 29/09/14 : 06:53:24.
Can anyone help me to get out of this, please?
Few things,
It seems like your code is vulnerable to SQL Injection. Just because you retrieve the content of the date from a session, it doesn't mean that it's safe.
Also, why do you need it to be in a session variable? If you always want to retrieve dates bigger than NOW() you can just write your query this way:
SELECT * FROM gmaptracker1 WHERE datetime >= NOW()
The part that caught my attention was the format you're storing the dates.
You said that when you echo'ed $_SESSION['date'] the value was: 27/09/14 : 06:53:24
Now, that does not look like the date format at all. Is your column actually a datetime or timestampcolumn?
If it's a VARCHAR or any other type other than datetime or timestamp, then there's no way for MySQL to know that you're trying to retrieve dates that occur in the future.
If you already have data stored, then it isn't going to be as easy as changing the data type because you already have data, and your data is in the wrong format. The format that MySQL stores datetime information is as follows:
YYYY-MM-DD HH:MM:SS
Based on the comments you left, you don't need the time > NOW(), you need the time when you log in. Now it makes sense why you're storing that time in a variable.
The problem is the format you're storing it.
Since you're using PHP, then you have to store the time this way:
$time = new DateTime();
$_SESSION['date'] = $time->format("Y-m-d H:i:s");

Mysql "Time" type gives an "ArgumentError: argument out of range" in Rails if over 24 hours

I'm writing a rails application on top of a legacy mysql db which also feeds a PHP production tool. Because of this setup so its not possible for me to change the databases structure.
The problem I'm having is that two table have a "time" attribute (duration) as long as the time is under 24:00:00 rails handles this, but as soon as rails comes across something like 39:00:34 I get this "ArgumentError: argument out of range".
I've looked into this problem and seen how rails handle the time type, and from my understanding it treats it like a datetime, so a value of 39:00:34 would throw this error.
I need some way of mapping / or changing the type cast so I don't get this error. Reading the value as a string would also be fine.
Any ideas would be most appreciated.
Cheers
I'm not familiar with Rails so there can be a clean, native solution to this, but if all else fails, one workaround might be writing into a VARCHAR field, then running a 2nd query to copy it over into a TIME field within mySQL:
INSERT INTO tablename (name, stringfield)
VALUES ("My Record", "999:02:02");
UPDATE tablename SET datefield = CAST(stringfield as TIME)
WHERE id = LAST_INSERT_ID();