[Drupal] Base hook schema example to put in .install

Introduction

Delighted

hook_schema is one of those methods where you are happy to have a usable documentation on the api website. It is pretty much self-explanatory and you don’t have to look for hours on third parties websites to get some usable information. 🙂

  • hook_schema on api.drupal.org and don’t forget to select your Drupal version!
  • $DRUPAL_ROOT\core\lib\Drupal\Core\Database\database.api.php: another file which describes the Database API array structure!
  • Schema Reference on drupal.org for D7. Yeah, there is no D8 version of the docs… Hopefully, nothing has changed between D7 and D8.

After some research, I found the files which are responsible for schema to SQL statement conversion:

File location Method name
$DRUPAL_ROOT\core\includes\schema.inc drupal_install_schema (8.2.x)
$DRUPAL_ROOT\core\includes\database.inc (deprecated) db_create_table (8.2.x) (deprecated)
$DRUPAL_ROOT\core\lib\Drupal\Core\Database\Schema.php protected createTable (8.2.x)
$DRUPAL_ROOT\core\lib\Drupal\Core\Database\Driver\{mysql,sqlite,pgsql}\Schema.php
$DRUPAL_ROOT\core\lib\Drupal\Core\Database\Driver\{mysql,sqlite,pgsql}\Schema.php

The code

 'Stores the history of content views blablabla.',
    'fields' => [
      'uid' => [
        'description' => 'User id.',
        'type' => 'int',
        'length' => 10,
        'unsigned' => true,
        'not null' => true
      ],
      'content_id'=> [
        'description' => 'Id of the content.',
        'type' => 'int',
        'length' => 11,
        'not null' => true
      ],
      'access_time'=> [
        'description' => 'Access timestamp.',
        'type' => 'int',
        'length' => 10,
        'unsigned' => true,
        'not null' => true
      ]
    ]
  ];
  
  return $schema;
}

Published by Dakwamine

Dakwamine, alias Quang-Minh Dang, né en 1987 en région parisienne. Un type sympa, pas bavard et pragmatique.