You are here

public function Table::create in Data 8

Create a table.

Do not call directly but use data_create_table() instead.

File

src/Table.php, line 64

Class

Table
Manages data access and manipulation for a single data table. Use data_create_table() or data_get_table() to instantiate an object from this class.

Namespace

Drupal\data

Code

public function create($table_schema) {

  // Only create the table if it is not defined as data table AND it does not
  // physically exist.
  if (!_data_load_table($this->name, TRUE) && !\Drupal::database()
    ->schema()
    ->tableExists($this->name)) {

    // Create table.
    try {
      \Drupal::database()
        ->createTable($this->name, $table_schema);
    } catch (DatabaseSchemaObjectExistsException $e) {
      \Drupal::messenger()
        ->addError(t('Error creating table.'), 'error');
      return FALSE;
    }

    // If schema module is enabled, inspect and read back to make
    // sure our schema information is up to date.
    // @todo: this is slow, maybe we need to make this an explicit method
    // on DataTable.
    if (module_exists('schema')) {
      $schema = schema_dbobject()
        ->inspect();
      if (isset($schema[$this->name])) {
        $table_schema = $schema[$this->name];
      }
    }

    // Set table_schema and export_type.
    // @todo: rather user _data_table_load() ?
    $this->table_schema = $table_schema;
    $this->export_type = EXPORT_IN_DATABASE;

    // Save table information.
    // Set export_type - needs to be defined so that schema information is being passed on
    // to Drupal by data_schema_alter().
    // @todo: refactor ->update() to ->save() and use ->save().
    $table = array(
      'name' => $this->name,
      'table_schema' => $this->table_schema,
    );
    drupal_write_record('data_tables', $table);

    // Clear caches.
    drupal_get_schema($this->name, TRUE);

    // Have views read new views information about table.
    if (module_exists('views')) {
      views_invalidate_cache();
    }

    // data ui exposes path to a new default view.
    if (module_exists('data_ui')) {
      menu_rebuild();
    }
    return TRUE;
  }
  return FALSE;
}