Drupal 7: Create a datetime field in a schema with db_create_table

To create a table in Drupal 7, you can use the “my_module_update_7000” hook in the “my_module.install” file.

The datetime type is unfortunately not mapped, which is why you have to use the “mysql_type” key

const MY_MODULE_TABLE_NAME = 'my_module_table';

function get_my_module_schema(): array {
   return [
      'description' => 'description',
      'fields' => [
         'id' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
         'log' => ['type' => 'blob', 'not null' => TRUE],
         'created_at' => ['type' => 'datetime', 'mysql_type' => 'datetime', 'not null' => TRUE],
      ],
      'primary key' => ['id'],
   ];
}

function my_module_schema() {
   $schema[MY_MODULE_TABLE_NAME] = get_my_module_schema();
   return $schema;
}

function my_module_update_7000() {
   if (!db_table_exists(MY_MODULE_TABLE_NAME)) {
      $schema = get_my_module_schema();
      db_create_table(MY_MODULE_TABLE_NAME, $schema);
   }
}