Saturday, September 12, 2015

MySQL under the hood hurts

Recently I've been poking around MySQL, i've forgot how it's when someone makes a lot of decisions for you, e.g. that a column of type TIMESTAMP should have a default value set to CURRENT_TIMESTAMP or that on each row write it should be automatically updated to CURRENT_TIMESTAMP, and btw did you know, that NOW() and CURRENT_TIMESTAMP are not equal (check this)?

The simplest way to discover what MySQL have done for you is to either read the documentation (which is kind of long) or:

SHOW CREATE TABLE table;
This will print you the full command necessary to recreate the table in the same state as it's currently:
CREATE TABLE `table` (
  `user_id` int(11) DEFAULT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `tags` text,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `state` int(11) DEFAULT '0',
  `date_of_publication` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `auth_fb_share` tinyint(1) DEFAULT NULL,
  CONSTRAINT `table_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`),
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8

But why is it a problem?
Because by default CURRENT_TIMESTAMP inserts the value with timezone shift, but without the information about time zone. Let's say it's 2015-09-09 21:23 +02:00. The TIMESTAMP keeps the data as UTC (+00:00). The proper value should be: 2015-09-09 19:23.
But the CURRENT_TIMESTAMP will insert the data as: 2015-09-09 21:23 skipping time zone information.
This causes a shift of X hours depending what's a server timezone is.

No comments:

Post a Comment