Skip to content

Database

hook_query_alter

/**
 * Perform alterations to a structured query.
 *
 * Structured (aka dynamic) queries that have tags associated may be altered by
 * any module before the query is executed.
 *
 * @param \Drupal\Core\Database\Query\AlterableInterface $query
 *   A Query object describing the composite parts of a SQL query.
 *
 * @see hook_query_TAG_alter()
 * @see node_query_node_access_alter()
 * @see AlterableInterface
 * @see SelectInterface
 */
function hook_query_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  if ($query->hasTag('micro_limit')) {
    $query->range(0, 2);
  }
}

hook_query_TAG_alter

/**
 * Perform alterations to a structured query for a given tag.
 *
 * Some common tags include:
 * - 'entity_reference': For queries that return entities that may be referenced
 *   by an entity reference field.
 * - ENTITY_TYPE . '_access': For queries of entities that will be displayed in
 *   a listing (e.g., from Views) and therefore require access control.
 *
 * @param \Drupal\Core\Database\Query\AlterableInterface $query
 *   A Query object describing the composite parts of a SQL query.
 *
 * @see hook_query_alter()
 * @see node_query_node_access_alter()
 * @see AlterableInterface
 * @see SelectInterface
 */
function hook_query_TAG_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  // This is an example of a possible hook_query_media_access_alter()
  // implementation. In other words, alter queries of media entities that
  // require access control (have the 'media_access' query tag).

  // Determine which media entities we want to remove from the query. In this
  // example, we hard-code some media IDs.
  $media_entities_to_hide = [1, 3];

  // In this example, we're only interested in applying our media access
  // restrictions to SELECT queries. hook_media_access() can be used to apply
  // access control to 'update' and 'delete' operations.
  if (!($query instanceof SelectInterface)) {
    return;
  }

  // The tables in the query. This can include media entity tables and other
  // tables. Tables might be joined more than once, with aliases.
  $query_tables = $query->getTables();

  // The tables belonging to media entity storage.
  $table_mapping = \Drupal::entityTypeManager()->getStorage('media')->getTableMapping();
  $media_tables = $table_mapping->getTableNames();

  // For each table in the query, if it's a media entity storage table, add a
  // condition to filter out records belonging to a media entity that we wish
  // to hide.
  foreach ($query_tables as $alias => $info) {
    // Skip over subqueries.
    if ($info['table'] instanceof SelectInterface) {
      continue;
    }
    $real_table_name = $info['table'];
    if (in_array($real_table_name, $media_tables)) {
      $query->condition("$alias.mid", $media_entities_to_hide, 'NOT IN');
    }
  }
}

hook_schema

/**
 * Define the current version of the database schema.
 *
 * Only procedural implementations are supported for this hook.
 *
 * A Drupal schema definition is a structure of value objects representing one
 * or more tables and their related keys and indexes. A schema is defined by
 * hook_schema() which must live in your module's .install file.
 *
 * The tables declared by this hook will be automatically created when the
 * module is installed, and removed when the module is uninstalled. This happens
 * before hook_install() is invoked, and after hook_uninstall() is invoked,
 * respectively.
 *
 * By declaring the tables used by your module via an implementation of
 * hook_schema(), these tables will be available on all supported database
 * engines. You don't have to deal with the different SQL dialects for table
 * creation and alteration of the supported database engines.
 *
 * See the Schema API documentation for details on schema definition
 * structures. Note that foreign key definitions are for documentation purposes
 * only; foreign keys are not created in the database, nor are they enforced by
 * Drupal.
 *
 * @return \Drupal\Core\Database\SchemaDefinition\Schema
 *   A schema definition.
 */
function hook_schema(): Schema {
  $tables[] = new Table(
    name: 'users_data',
    description: 'Stores module data as key/value pairs per user.',
    columns: [
      Column::int(
        name: 'uid',
        description: 'The {users}.uid this record affects.',
        unsigned: TRUE,
        notNull: TRUE,
        default: new IntValue(0),
      ),
      Column::varcharAscii(
        name: 'module',
        description: 'The name of the module declaring the variable.',
        length: DRUPAL_EXTENSION_NAME_MAX_LENGTH,
        notNull: TRUE,
        default: new StringValue(''),
      ),
      Column::varcharAscii(
        name: 'name',
        description: 'The identifier of the data.',
        length: 128,
        notNull: TRUE,
        default: new StringValue(''),
      ),
      Column::blob(
        name: 'value',
        description: 'The value.',
        size: ColumnSize::Big,
        notNull: FALSE,
      ),
      Column::int(
        name: 'serialized',
        description: 'Whether value is serialized.',
        size: ColumnSize::Tiny,
        unsigned: TRUE,
        default: new IntValue(0),
      ),
    ],
    primaryKey: new PrimaryKey(['uid', 'module', 'name']),
    indexes: [
      new Index(name: 'module', columns: ['module']),
      new Index(name: 'name', columns: ['name']),
    ],
    // For documentation purposes only; foreign keys are not created in the
    // database.
    foreignKeys: [
      new ForeignKey(
      name: 'data_user',
      foreignTable: 'users',
      columns: ['uid'],
      foreignColumns: ['uid'],
      ),
    ],
  );

  return new Schema(
    type: SchemaDefinitionType::Module,
    name: 'hook',
    tables: $tables,
  );
}