Example #1
0
 /**
  * Test node migration from Drupal 6 to 8.
  */
 public function testNode()
 {
     $node = node_load(1);
     $this->assertEqual($node->id(), 1, 'Node 1 loaded.');
     $this->assertEqual($node->body->value, 'test');
     $this->assertEqual($node->body->format, 'filtered_html');
     $this->assertEqual($node->getType(), 'story', 'Node has the correct bundle.');
     $this->assertEqual($node->getTitle(), 'Test title', 'Node has the correct title.');
     $this->assertEqual($node->getCreatedTime(), 1388271197, 'Node has the correct created time.');
     $this->assertEqual($node->isSticky(), FALSE);
     $this->assertEqual($node->getOwnerId(), 1);
     //$this->assertEqual($node->getRevisionCreationTime(), 1390095701, 'Node has the correct revision timestamp.');
     // It is pointless to run the second half from MigrateDrupal6Test.
     if (empty($this->standalone)) {
         return;
     }
     // Test that we can re-import using the EntityContentBase destination.
     $connection = Database::getConnection('default', 'migrate');
     $connection->update('node_revisions')->fields(array('title' => 'New node title', 'format' => 2))->condition('vid', 1)->execute();
     $connection->delete('content_field_test_two')->condition('delta', 1)->execute();
     /** @var \Drupal\migrate\entity\Migration $migration */
     $migration = entity_load('migration', 'd6_node');
     $executable = new MigrateExecutable($migration, $this);
     $executable->import();
     $node = node_load(1);
     $this->assertEqual($node->getTitle(), 'New node title');
     // Test a multi-column fields are correctly upgraded.
     $this->assertEqual($node->body->value, 'test');
     $this->assertEqual($node->body->format, 'full_html');
 }
 public static function deleteAllUsers($roles = NULL)
 {
     $count = 0;
     $db_connection = Database::getConnection();
     if (!$roles) {
         $result = $db_connection->query('SELECT uid FROM {users} WHERE uid > 1')->fetchAllAssoc('uid');
         foreach ($result as $data) {
             $user = User::load($data->uid);
             $user->delete();
             $count++;
         }
         // Delete the URL aliases
         $db_connection->query("DELETE FROM {url_alias} WHERE source LIKE 'user/%%'");
     } else {
         if (is_array($roles)) {
             $result = array();
             foreach ($roles as $role) {
                 $result = array_merge($result, db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $role, '=')->execute()->fetchCol('entity_id'));
             }
         } else {
             $result = db_select('user__roles', 'roles_target_id')->fields('roles_target_id', array('entity_id'))->condition('roles_target_id', $roles, '=')->execute()->fetchCol('entity_id');
         }
         foreach ($result as $data) {
             $user = User::load($data);
             $user->delete();
             $count++;
         }
         // @TODO Delete individual aliases
     }
     return $count;
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     foreach (Database::getAllConnectionInfo() as $key => $info) {
         Database::startLog('webprofiler', $key);
     }
     return $this->httpKernel->handle($request, $type, $catch);
 }
  /**
   * Sets up the configuration and schema of views and views_test_data modules.
   *
   * Because the schema of views_test_data.module is dependent on the test
   * using it, it cannot be enabled normally.
   */
  protected function setUpFixtures() {
    // First install the system module. Many Views have Page displays have menu
    // links, and for those to work, the system menus must already be present.
    $this->installConfig(['system']);

    /** @var \Drupal\Core\State\StateInterface $state */
    $state = $this->container->get('state');
    // Define the schema and views data variable before enabling the test module.
    $state->set('views_test_data_schema', $this->schemaDefinition());
    $state->set('views_test_data_views_data', $this->viewsData());

    $this->installConfig(['views', 'views_test_config', 'views_test_data']);
    foreach ($this->schemaDefinition() as $table => $schema) {
      $this->installSchema('views_test_data', $table);
    }

    $this->container->get('router.builder')->rebuild();

    // Load the test dataset.
    $data_set = $this->dataSet();
    $query = Database::getConnection()->insert('views_test_data')
      ->fields(array_keys($data_set[0]));
    foreach ($data_set as $record) {
      $query->values($record);
    }
    $query->execute();
  }
Example #5
0
  /**
   * {@inheritdoc}
   */
  protected function validateEntityStrings(array &$form, array $values, FormStateInterface $form_state) {
    $uids = array();
    $missing = array();
    foreach ($values as $value) {
      if (Unicode::strtolower($value) === Unicode::strtolower(\Drupal::config('user.settings')->get('anonymous'))) {
        $uids[] = 0;
      }
      else {
        $missing[strtolower($value)] = $value;
      }
    }

    if (!$missing) {
      return $uids;
    }

    $result = Database::getConnection()->query("SELECT * FROM {users} WHERE name IN (:names)", array(':names' => array_values($missing)));
    foreach ($result as $account) {
      unset($missing[strtolower($account->name)]);
      $uids[] = $account->uid;
    }

    if ($missing) {
      $form_state->setError($form, $this->formatPlural(count($missing), 'Unable to find user: @users', 'Unable to find users: @users', array('@users' => implode(', ', $missing))));
    }

    return $uids;
  }
 /**
  * Queries database for the order ids of the most recently modified billing
  * addresses. It assumes the billing address on the most recent order are 
  * the most current.
  */
 public function getOrderIds()
 {
     // This query wouldn't work so used the raw MySQL query below. Not sure
     // if the limitation is Drupal's database framework or my understanding
     // of it.
     //$query = $this->select('uc_orders', 'uo')
     //  ->fields('uo', ['order_id']);
     //$query->addExpression('MAX(uo.modified)', 'newest_entry');
     //$query->groupBy('uo.uid');
     //$query->execute();
     //drush_print($query->__toString());
     // Ugly and somewhat hackish. A neater, more Drupal 8 method would be
     // nice. If anyone knows of a better way to do it as I attempted above,
     // I'd love to see it.
     $connection = Database::getConnectionInfo('migrate');
     $mysql_connection = mysqli_connect($connection['default']['host'], $connection['default']['username'], $connection['default']['password'], $connection['default']['database']);
     // Only imports the most recently modified orders for each shopper.
     $result = mysqli_query($mysql_connection, 'SELECT uo.order_id AS order_id, MAX(uo.modified) AS newest_entry 
    FROM uc_orders uo 
    GROUP BY uo.uid');
     $order_ids = array();
     foreach ($result as $row) {
         $order_ids[] = $row['order_id'];
     }
     return $order_ids;
 }
Example #7
0
 /**
  * {@inheritdoc}
  */
 public function log($level, $message, array $context = array())
 {
     // Remove any backtraces since they may contain an unserializable variable.
     unset($context['backtrace']);
     // Convert PSR3-style messages to SafeMarkup::format() style, so they can be
     // translated too in runtime.
     $message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
     try {
         $this->connection->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => Unicode::substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => $context['link'], 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => Unicode::substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute();
     } catch (\Exception $e) {
         // When running Drupal on MySQL or MariaDB you can run into several errors
         // that corrupt the database connection. Some examples for these kind of
         // errors on the database layer are "1100 - Table 'xyz' was not locked
         // with LOCK TABLES" and "1153 - Got a packet bigger than
         // 'max_allowed_packet' bytes". If such an error happens, the MySQL server
         // invalidates the connection and answers all further requests in this
         // connection with "2006 - MySQL server had gone away". In that case the
         // insert statement above results in a database exception. To ensure that
         // the causal error is written to the log we try once to open a dedicated
         // connection and write again.
         if (($e instanceof DatabaseException || $e instanceof \PDOException) && $this->connection->getTarget() != self::DEDICATED_DBLOG_CONNECTION_TARGET) {
             // Open a dedicated connection for logging.
             $key = $this->connection->getKey();
             $info = Database::getConnectionInfo($key);
             Database::addConnectionInfo($key, self::DEDICATED_DBLOG_CONNECTION_TARGET, $info['default']);
             $this->connection = Database::getConnection(self::DEDICATED_DBLOG_CONNECTION_TARGET, $key);
             // Now try once to log the error again.
             $this->log($level, $message, $context);
         } else {
             throw $e;
         }
     }
 }
Example #8
0
 /**
  * Get the database connection object.
  *
  * @return \Drupal\Core\Database\Connection
  *   The database connection.
  */
 public function getDatabase()
 {
     if (!isset($this->database)) {
         $this->database = Database::getConnection('default', 'migrate');
     }
     return $this->database;
 }
Example #9
0
 /**
  * Parse input options decide on a database.
  *
  * @param \Symfony\Component\Console\Input\InputInterface $input
  *   Input object.
  * @return \Drupal\Core\Database\Connection
  */
 protected function getDatabaseConnection(InputInterface $input)
 {
     // Load connection from a url.
     if ($input->getOption('database-url')) {
         // @todo this could probably be refactored to not use a global connection.
         // Ensure database connection isn't set.
         if (Database::getConnectionInfo('db-tools')) {
             throw new \RuntimeException('Database "db-tools" is already defined. Cannot define database provided.');
         }
         $info = Database::convertDbUrlToConnectionInfo($input->getOption('database-url'), \Drupal::root());
         Database::addConnectionInfo('db-tools', 'default', $info);
         $key = 'db-tools';
     } else {
         $key = $input->getOption('database');
     }
     // If they supplied a prefix, replace it in the connection information.
     $prefix = $input->getOption('prefix');
     if ($prefix) {
         $info = Database::getConnectionInfo($key)['default'];
         $info['prefix']['default'] = $prefix;
         Database::removeConnection($key);
         Database::addConnectionInfo($key, 'default', $info);
     }
     return Database::getConnection('default', $key);
 }
 /**
  * Test that missing action's causes failures.
  */
 public function testInvalidCropValues()
 {
     Database::getConnection('default', 'migrate')->insert("imagecache_action")->fields(['presetid', 'weight', 'module', 'action', 'data'])->values(['presetid' => '1', 'weight' => '0', 'module' => 'imagecache', 'action' => 'imagecache_crop', 'data' => serialize(['xoffset' => '10', 'yoffset' => '10'])])->execute();
     $this->startCollectingMessages();
     $this->executeMigration('d6_imagecache_presets');
     $this->assertEqual(['error' => ['The Drupal 8 image crop effect does not support numeric values for x and y offsets. Use keywords to set crop effect offsets instead.']], $this->migrateMessages);
 }
 /**
  * Checks and disables the replica database server if appropriate.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The Event to process.
  */
 public function checkReplicaServer(GetResponseEvent $event)
 {
     // Ignore replica database servers for this request.
     //
     // In Drupal's distributed database structure, new data is written to the
     // master and then propagated to the replica servers.  This means there is a
     // lag between when data is written to the master and when it is available
     // on the replica. At these times, we will want to avoid using a replica server
     // temporarily. For example, if a user posts a new node then we want to
     // disable the replica server for that user temporarily to allow the replica
     // server to catch up.
     // That way, that user will see their changes immediately while for other
     // users we still get the benefits of having a replica server, just with
     // slightly stale data.  Code that wants to disable the replica server should
     // use the db_set_ignore_replica() function to set
     // $_SESSION['ignore_replica_server'] to the timestamp after which the replica
     // can be re-enabled.
     if (isset($_SESSION['ignore_replica_server'])) {
         if ($_SESSION['ignore_replica_server'] >= REQUEST_TIME) {
             Database::ignoreTarget('default', 'replica');
         } else {
             unset($_SESSION['ignore_replica_server']);
         }
     }
 }
 /**
  * Tests the Drupal 6 files to Drupal 8 migration.
  */
 public function testFiles()
 {
     /** @var \Drupal\file\FileInterface $file */
     $file = entity_load('file', 1);
     $this->assertIdentical('Image1.png', $file->getFilename());
     $this->assertIdentical('39325', $file->getSize());
     $this->assertIdentical('public://image-1.png', $file->getFileUri());
     $this->assertIdentical('image/png', $file->getMimeType());
     // It is pointless to run the second half from MigrateDrupal6Test.
     if (empty($this->standalone)) {
         return;
     }
     // Test that we can re-import and also test with file_directory_path set.
     db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute();
     $migration = entity_load_unchanged('migration', 'd6_file');
     $dumps = array($this->getDumpDirectory() . '/Variable.php');
     $this->prepare($migration, $dumps);
     // Update the file_directory_path.
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute();
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('/tmp')))->condition('name', 'file_directory_temp')->execute();
     $executable = new MigrateExecutable($migration, $this);
     $executable->import();
     $file = entity_load('file', 2);
     $this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
     // Ensure that a temporary file has been migrated.
     $file = entity_load('file', 6);
     $this->assertIdentical('temporary://some-temp-file.jpg', $file->getFileUri());
 }
Example #13
0
 /**
  * Tests aborting of traditional SQL database systems with invalid data.
  */
 function testInsertDuplicateData()
 {
     // Try to insert multiple records where at least one has bad data.
     try {
         db_insert('test')->fields(array('name', 'age', 'job'))->values(array('name' => 'Elvis', 'age' => 63, 'job' => 'Singer'))->values(array('name' => 'John', 'age' => 17, 'job' => 'Consultant'))->values(array('name' => 'Frank', 'age' => 75, 'job' => 'Singer'))->execute();
         $this->fail('Insert succeeded when it should not have.');
     } catch (IntegrityConstraintViolationException $e) {
         // Check if the first record was inserted.
         $name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 63))->fetchField();
         if ($name == 'Elvis') {
             if (!Database::getConnection()->supportsTransactions()) {
                 // This is an expected fail.
                 // Database engines that don't support transactions can leave partial
                 // inserts in place when an error occurs. This is the case for MySQL
                 // when running on a MyISAM table.
                 $this->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
             } else {
                 $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
             }
         } else {
             $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
         }
         // Ensure the other values were not inserted.
         $record = db_select('test')->fields('test', array('name', 'age'))->condition('age', array(17, 75), 'IN')->execute()->fetchObject();
         $this->assertFalse($record, 'The rest of the insert aborted as expected.');
     }
 }
 /**
  * Gets the database connection for the source Drupal database.
  *
  * @param array $database
  *   Database array representing the source Drupal database.
  *
  * @return \Drupal\Core\Database\Connection
  *   The database connection for the source Drupal database.
  */
 protected function getConnection(array $database)
 {
     // Set up the connection.
     Database::addConnectionInfo('upgrade', 'default', $database);
     $connection = Database::getConnection('default', 'upgrade');
     return $connection;
 }
 /**
  * Cont how many nodes we have of each type.
  */
 protected function countNodesPerType()
 {
     $result = Database::getConnection()->query("SELECT type, COUNT(*) AS num FROM {node} GROUP BY type")->fetchAllAssoc('type');
     foreach ($result as $data) {
         $this->count[$data->type] = $data->num;
     }
 }
 /**
  * Verifies that a transaction rolls back the failed creation.
  */
 function testFailedPageCreation()
 {
     // Create a node.
     $edit = array('uid' => $this->loggedInUser->id(), 'name' => $this->loggedInUser->name, 'type' => 'page', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'title' => 'testing_transaction_exception');
     try {
         // An exception is generated by node_test_exception_node_insert() if the
         // title is 'testing_transaction_exception'.
         entity_create('node', $edit)->save();
         $this->fail(t('Expected exception has not been thrown.'));
     } catch (\Exception $e) {
         $this->pass(t('Expected exception has been thrown.'));
     }
     if (Database::getConnection()->supportsTransactions()) {
         // Check that the node does not exist in the database.
         $node = $this->drupalGetNodeByTitle($edit['title']);
         $this->assertFalse($node, 'Transactions supported, and node not found in database.');
     } else {
         // Check that the node exists in the database.
         $node = $this->drupalGetNodeByTitle($edit['title']);
         $this->assertTrue($node, 'Transactions not supported, and node found in database.');
         // Check that the failed rollback was logged.
         $records = db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
         $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
     }
     // Check that the rollback error was logged.
     $records = db_query("SELECT wid FROM {watchdog} WHERE variables LIKE '%Test exception for rollback.%'")->fetchAll();
     $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.');
 }
Example #17
0
 /**
  * Test different connection types.
  */
 public function testConnectionTypes()
 {
     $sql_base = new TestSqlBase();
     // Check the default values.
     $this->assertIdentical($sql_base->getDatabase()->getTarget(), 'default');
     $this->assertIdentical($sql_base->getDatabase()->getKey(), 'migrate');
     $target = 'test_db_target';
     $key = 'test_migrate_connection';
     $config = array('target' => $target, 'key' => $key);
     $sql_base->setConfiguration($config);
     Database::addConnectionInfo($key, $target, Database::getConnectionInfo('default')['default']);
     // Validate we've injected our custom key and target.
     $this->assertIdentical($sql_base->getDatabase()->getTarget(), $target);
     $this->assertIdentical($sql_base->getDatabase()->getKey(), $key);
     // Now test we can have SqlBase create the connection from an info array.
     $sql_base = new TestSqlBase();
     $target = 'test_db_target2';
     $key = 'test_migrate_connection2';
     $database = Database::getConnectionInfo('default')['default'];
     $config = array('target' => $target, 'key' => $key, 'database' => $database);
     $sql_base->setConfiguration($config);
     // Call getDatabase() to get the connection defined.
     $sql_base->getDatabase();
     // Validate the connection has been created with the right values.
     $this->assertIdentical(Database::getConnectionInfo($key)[$target], $database);
 }
 /**
  * Verifies that a transaction rolls back the failed creation.
  */
 function testFailedTicketCreation()
 {
     // Create a support_ticket.
     $edit = array('uid' => $this->loggedInUser->id(), 'name' => $this->loggedInUser->name, 'support_ticket_type' => 'ticket', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'title' => 'testing_transaction_exception');
     try {
         // An exception is generated by support_ticket_test_exception_support_ticket_insert() if the
         // title is 'testing_transaction_exception'.
         entity_create('support_ticket', $edit)->save();
         $this->fail(t('Expected exception has not been thrown.'));
     } catch (\Exception $e) {
         $this->pass(t('Expected exception has been thrown.'));
     }
     if (Database::getConnection()->supportsTransactions()) {
         // Check that the support_ticket does not exist in the database.
         $support_ticket = $this->supportTicketGetTicketByTitle($edit['title']);
         $this->assertFalse($support_ticket, 'Transactions supported, and support_ticket not found in database.');
     } else {
         // Check that the support_ticket exists in the database.
         $support_ticket = $this->supportTicketGetTicketByTitle($edit['title']);
         $this->assertTrue($support_ticket, 'Transactions not supported, and support_ticket found in database.');
         // Check that the failed rollback was logged.
         $records = static::getWatchdogIdsForFailedExplicitRollback();
         $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
     }
     // Check that the rollback error was logged.
     $records = static::getWatchdogIdsForTestExceptionRollback();
     $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.');
 }
 public function __construct()
 {
     $this->connection = \Drupal\Core\Database\Database::getConnection();
     $this->module_config = \Drupal::config('sociallogin.settings');
     $this->apiSecret = trim($this->module_config->get('api_secret'));
     $this->apiKey = trim($this->module_config->get('api_key'));
 }
 public function __construct($database)
 {
     global $ss_client;
     $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
     require_once DRUPAL_ROOT . '/core/includes/database.inc';
     Database::setMultipleConnectionInfo($database);
     $this->connection = Database::getConnection();
     $this->ss_client =& $ss_client;
     $this->database = $database;
     $query = db_select('config', 'n')->fields('n')->condition('name', $this->options, 'IN');
     $result = $query->execute();
     if ($result && is_object($result)) {
         foreach ($result as $key => $row) {
             $values = unserialize($row->data);
             foreach ($values[key($values)] as $value_key => $value) {
                 $this->data_options[$value_key] = $value;
             }
         }
     }
     if (defined('STACKSIGHT_SETTINGS_IN_DB') && STACKSIGHT_SETTINGS_IN_DB === true) {
         if (isset($this->data_options['token'])) {
             $this->ready = true;
         }
     } else {
         $this->ready = true;
     }
     define('STACKSIGHT_PHP_SDK_INCLUDE', TRUE);
 }
Example #21
0
 /**
  * Test node migration from Drupal 6 to 8.
  */
 public function testNode()
 {
     $node = Node::load(1);
     $this->assertIdentical('1', $node->id(), 'Node 1 loaded.');
     $this->assertIdentical('und', $node->langcode->value);
     $this->assertIdentical('test', $node->body->value);
     $this->assertIdentical('test', $node->body->summary);
     $this->assertIdentical('filtered_html', $node->body->format);
     $this->assertIdentical('story', $node->getType(), 'Node has the correct bundle.');
     $this->assertIdentical('Test title', $node->getTitle(), 'Node has the correct title.');
     $this->assertIdentical('1388271197', $node->getCreatedTime(), 'Node has the correct created time.');
     $this->assertIdentical(FALSE, $node->isSticky());
     $this->assertIdentical('1', $node->getOwnerId());
     $this->assertIdentical('1420861423', $node->getRevisionCreationTime());
     /** @var \Drupal\node\NodeInterface $node_revision */
     $node_revision = \Drupal::entityManager()->getStorage('node')->loadRevision(1);
     $this->assertIdentical('Test title', $node_revision->getTitle());
     $this->assertIdentical('1', $node_revision->getRevisionAuthor()->id(), 'Node revision has the correct user');
     // This is empty on the first revision.
     $this->assertIdentical(NULL, $node_revision->revision_log->value);
     // Test that we can re-import using the EntityContentBase destination.
     $connection = Database::getConnection('default', 'migrate');
     $connection->update('node_revisions')->fields(array('title' => 'New node title', 'format' => 2))->condition('vid', 1)->execute();
     $connection->delete('content_field_test_two')->condition('delta', 1)->execute();
     $migration = Migration::load('d6_node__story');
     $this->executeMigration($migration);
     $node = Node::load(1);
     $this->assertIdentical('New node title', $node->getTitle());
     // Test a multi-column fields are correctly upgraded.
     $this->assertIdentical('test', $node->body->value);
     $this->assertIdentical('full_html', $node->body->format);
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Create some fields so the data gets stored.
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_color', 'type' => 'text'))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_biography', 'type' => 'text_long'))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_sell_address', 'type' => 'boolean'))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_sold_to', 'type' => 'list_string', 'settings' => array('allowed_values' => array('Pill spammers' => 'Pill spammers', 'Fitness spammers' => 'Fitness spammers'))))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_bands', 'type' => 'text', 'cardinality' => -1))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_blog', 'type' => 'link'))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_birthdate', 'type' => 'datetime'))->save();
     entity_create('field_storage_config', array('entity_type' => 'user', 'field_name' => 'profile_love_migrations', 'type' => 'boolean'))->save();
     // Add some id mappings for the dependant migrations.
     $id_mappings = array('d6_user_profile_field_instance' => array(array(array(1), array('user', 'user', 'fieldname'))), 'd6_user_profile_entity_display' => array(array(array(1), array('user', 'user', 'default', 'fieldname'))), 'd6_user_profile_entity_form_display' => array(array(array(1), array('user', 'user', 'default', 'fieldname'))), 'd6_user' => array(array(array(2), array(2)), array(array(8), array(8)), array(array(15), array(15))));
     $this->prepareMigrations($id_mappings);
     // Load database dumps to provide source data.
     $dumps = array($this->getDumpDirectory() . '/ProfileFields.php', $this->getDumpDirectory() . '/Users.php', $this->getDumpDirectory() . '/ProfileValues.php', $this->getDumpDirectory() . '/UsersRoles.php', $this->getDumpDirectory() . '/EventTimezones.php');
     $this->loadDumps($dumps);
     $field_data = Database::getConnection('default', 'migrate')->select('profile_fields', 'u')->fields('u')->execute()->fetchAll();
     // Create the field instances.
     foreach ($field_data as $field) {
         entity_create('field_config', array('label' => $field->title, 'description' => '', 'field_name' => $field->name, 'entity_type' => 'user', 'bundle' => 'user', 'required' => 0))->save();
     }
     // Create our users for the node authors.
     $query = Database::getConnection('default', 'migrate')->query('SELECT * FROM {users} WHERE uid NOT IN (0, 1)');
     while (($row = $query->fetchAssoc()) !== FALSE) {
         $user = entity_create('user', $row);
         $user->enforceIsNew();
         $user->save();
     }
     // Migrate profile fields.
     $migration_format = entity_load('migration', 'd6_profile_values:user');
     $executable = new MigrateExecutable($migration_format, $this);
     $executable->import();
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('node');
     $this->installEntitySchema('comment');
     $this->installEntitySchema('taxonomy_term');
     CommentType::create(['id' => 'comment_node_page', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_article', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_blog', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_book', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_forum', 'label' => $this->randomMachineName()])->save();
     CommentType::create(['id' => 'comment_node_test_content_type', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'page', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'article', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'blog', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'book', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'forum', 'label' => $this->randomMachineName()])->save();
     NodeType::create(['type' => 'test_content_type', 'label' => $this->randomMachineName()])->save();
     Vocabulary::create(['vid' => 'test_vocabulary'])->save();
     // Give one unfortunate field instance invalid display settings to ensure
     // that the migration provides an empty array as a default (thus avoiding
     // an "unsupported operand types" fatal).
     Database::getConnection('default', 'migrate')->update('field_config_instance')->fields(array('data' => serialize(array('label' => 'Body', 'widget' => array('type' => 'text_textarea_with_summary', 'settings' => array('rows' => 20, 'summary_rows' => 5), 'weight' => -4, 'module' => 'text'), 'settings' => array('display_summary' => TRUE, 'text_processing' => 1, 'user_register_form' => FALSE), 'display' => array('default' => array('label' => 'hidden', 'type' => 'text_default', 'settings' => array(), 'module' => 'text', 'weight' => 0), 'teaser' => array('label' => 'hidden', 'type' => 'text_summary_or_trimmed', 'settings' => NULL, 'module' => 'text', 'weight' => 0)), 'required' => FALSE, 'description' => ''))))->condition('entity_type', 'node')->condition('bundle', 'article')->condition('field_name', 'body')->execute();
     $this->executeMigrations(['d7_field', 'd7_field_instance', 'd7_view_modes', 'd7_field_formatter_settings']);
 }
Example #24
0
 /**
  * Tests truncation of messages when max_allowed_packet exception occurs.
  */
 function testMaxAllowedPacketQueryTruncating()
 {
     // This test only makes sense if we are running on a MySQL database.
     // Test if we are.
     $database = Database::getConnectionInfo('default');
     if ($database['default']['driver'] == 'mysql') {
         // The max_allowed_packet value is configured per database instance.
         // Retrieve the max_allowed_packet value from the current instance and
         // check if PHP is configured with sufficient allowed memory to be able
         // to generate a query larger than max_allowed_packet.
         $max_allowed_packet = db_query('SELECT @@global.max_allowed_packet')->fetchField();
         if (Environment::checkMemoryLimit($max_allowed_packet + 16 * 1024 * 1024)) {
             $long_name = str_repeat('a', $max_allowed_packet + 1);
             try {
                 db_query('SELECT name FROM {test} WHERE name = :name', array(':name' => $long_name));
                 $this->fail("An exception should be thrown for queries larger than 'max_allowed_packet'");
             } catch (DatabaseException $e) {
                 // Close and re-open the connection. Otherwise we will run into error
                 // 2006 "MySQL server had gone away" afterwards.
                 Database::closeConnection();
                 Database::getConnection();
                 $this->assertEqual($e->getPrevious()->errorInfo[1], 1153, "Got a packet bigger than 'max_allowed_packet' bytes exception thrown.");
                 // Use strlen() to count the bytes exactly, not the unicode chars.
                 $this->assertTrue(strlen($e->getMessage()) <= $max_allowed_packet, "'max_allowed_packet' exception message truncated.");
             }
         } else {
             $this->verbose('The configured max_allowed_packet exceeds the php memory limit. Therefore the test is skipped.');
         }
     } else {
         $this->verbose('The test requires MySQL. Therefore the test is skipped.');
     }
 }
  /**
   * Tests the Drupal 6 menu to Drupal 8 migration.
   */
  public function testMenu() {
    $navigation_menu = Menu::load('navigation');
    $this->assertSame('navigation', $navigation_menu->id());
    $this->assertSame('Navigation', $navigation_menu->label());
    $expected = <<<EOT
The navigation menu is provided by Drupal and is the main interactive menu for any site. It is usually the only menu that contains personalized links for authenticated users, and is often not even visible to anonymous users.
EOT;
    $this->assertSame($expected, $navigation_menu->getDescription());

    // Test that we can re-import using the ConfigEntityBase destination.
    Database::getConnection('default', 'migrate')
      ->update('menu_custom')
      ->fields(array('title' => 'Home Navigation'))
      ->condition('menu_name', 'navigation')
      ->execute();

    $migration = $this->getMigration('d6_menu');
    \Drupal::database()
        ->truncate($migration->getIdMap()->mapTableName())
        ->execute();
    $this->executeMigration($migration);

    $navigation_menu = Menu::load('navigation');
    $this->assertSame('Home Navigation', $navigation_menu->label());
  }
 /**
  * @covers ::convertDbUrlToConnectionInfo
  *
  * @dataProvider providerGetConnectionInfoAsUrl
  */
 public function testGetConnectionInfoAsUrl(array $info, $expected_url)
 {
     Database::addConnectionInfo('default', 'default', $info);
     $url = Database::getConnectionInfoAsUrl();
     // Remove the connection to not pollute subsequent datasets being tested.
     Database::removeConnection('default');
     $this->assertEquals($expected_url, $url);
 }
Example #27
0
 /**
  * Assert there are tables that begin with the specified base table name.
  *
  * @param $base_table
  *   Beginning of table name to look for.
  * @param $count
  *   (optional) Whether or not to assert that there are tables that match the
  *   specified base table. Defaults to TRUE.
  */
 function assertTableCount($base_table, $count = TRUE)
 {
     $tables = db_find_tables(Database::getConnection()->prefixTables('{' . $base_table . '}') . '%');
     if ($count) {
         return $this->assertTrue($tables, format_string('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
     }
     return $this->assertFalse($tables, format_string('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $database = Database::getConnection('default', 'migrate');
     $database->update('system')->fields(array('status' => 0))->condition('name', 'content')->condition('type', 'module')->execute();
     $database->schema()->dropTable('content_node_field');
     $database->schema()->dropTable('content_node_field_instance');
 }
 /**
  * Check table exist int database and get scheme of that table and create table.
  *
  * @param string $table_name Database table name
  */
 function socialprofiledata_check_table_exists_and_create($table_name)
 {
     if (!\Drupal\Core\Database\Database::getConnection()->schema()->tableExists($table_name)) {
         $function_table_name = 'socialprofiledata_' . $table_name;
         $schema = $function_table_name();
         \Drupal\Core\Database\Database::getConnection()->schema()->createTable($table_name, $schema);
     }
 }
 public function __construct()
 {
     // Starts timers and logs.
     Timer::start(self::class);
     if (!isset(self::$logger)) {
         self::$logger = Database::startLog(self::class);
     }
 }