Migrations

Implementing a secondary Drupal migration to enrich existing data

In the previous article in this series, we implemented an end-to-end migration project: the Rick and Migraty experience. It populates a Drupal installation from several data sources. The Rick and Morty API supplies the primary catalogue, TVmaze contributes episode data, and the Fandom content hub adds editorial context. The result is a small content domain made up of characters, locations, episodes, and the relationships among them—a map of several facets of the animated series’ universe.

After completing that first migration, I considered a new feature: plotting the rating of every episode so that visitors could follow the evolution of the series, compare seasons, and spot the highest- and lowest-rated episodes at a glance. What initially looked like a visualisation task exposed two limitations in the migrated dataset: a) we retained only one rating source, and b) the Rick and Morty universe did not end with the regular series; it also included Rick and Morty: The Anime and The Non-Canonical Adventures.

The chart therefore changed the technical question. It was no longer just a matter of drawing existing data, but of extending and enriching a completed migration without restarting it, duplicating entities, or turning optional sources into dependencies of the primary catalogue. This seventh article explains the solution implemented in Rick and Migraty: a secondary migration that adds complementary works and episodes, locates episodes already stored in Drupal, and attaches new rating observations with their provenance. Once those data are in place, we can build the ratings-tracking chart.

Note: As of 30 November 2026, this article contains approximately 7,900 words and 65,000 characters, with an estimated reading time of 40–48 minutes.

Table of contents


0. TL;DR

The first Rick and Migraty migration had already created a stable catalogue for the main series. The requirement to compare episode ratings exposed two gaps: complementary franchise content was missing, and a single rating provider was not enough for meaningful comparison.

The solution was not to rerun the whole process or keep expanding the primary migration indefinitely. Instead, we implemented a secondary migration with two responsibilities:

  1. Create works and episodes that do not yet exist in Drupal.
  2. Locate previously migrated episodes and attach rating observations from additional providers.

We use migration_lookup to associate newly created episodes with work entities produced by an earlier migration. IMDb enrichment requires a dedicated migration: a source plugin prepares rating rows, while two process plugins resolve both the receiving episode and any observation imported before the new migration map existed. The work is divided into resumable steps and ultimately feeds a new ratings and charting area.

A secondary migration does not necessarily repeat the initial migration. It can depend on that migration’s result, create only what is missing, and enrich entities that already exist.

Updated menu with the new secondary-migration action. New primary-menu actions: secondary migration and ratings area.

Welcome, then, to the complementary process: The More Cowbell Migration! The new features are available on the project’s main branch and included in tag 2.0.0. Installation and build instructions are available in the project README and in the previous article.

After running both the primary and secondary processes, the ratings area contains the full set of data and comparisons:

The new episode-ratings area. Episode ratings generated from the integrated data.

The ratings area is available even before the secondary migration runs, but it will then show only the regular series and will not expose combined values from the additional sources: arithmetic mean, median, and vote-weighted mean.

Poster announcing the new migration in a deliberately dissonant way. More episodes, more data, more ratings… MORE COWBELL.

“I got a fever, and the only prescription is more cowbell!”

— Christopher Walken as Bruce Dickinson

And now, as in a Guy Ritchie film, let us freeze the frame, rewind, and say: You are probably wondering how I got here…

1. The starting point: Rick and Migraty

The first version of the project had a deliberately clear boundary: the Rick and Morty API defined the identity of the main series’ characters, locations, and episodes. TVmaze and Fandom could enrich selected fields, but they could not silently decide which entities belonged to the catalogue or replace their identity.

That division of responsibilities made the process predictable:

  1. Import the main work.
  2. Import characters, locations, and episodes.
  3. Build their relationships.
  4. Complete descriptions and provenance from secondary sources.
  5. Verify the result before considering the migration complete.

The previous article, Drupal Migrations (VI): Rick and Migraty, combining data from several sources, describes that design in detail. What matters here is that we already had persisted data and a stable identity for every entity. The secondary migration had to respect that state.

Changing the first pipeline to absorb every later requirement would mix two different moments: a) building the minimum catalogue that makes the site useful and b) extending it when new use cases appear. It would also turn optional or less reliable providers into requirements for a usable result. I chose a different direction.

2. When a chart reveals a data problem

The original idea was simple: create an episode-ratings chart. I wanted to represent the series as a trajectory, filter it by season or score, and open an episode profile from each point.

Before building the interface, I reviewed the data that could feed the chart. Two problems appeared.

2.1. First issue: more works than the regular series

The migrated catalogue described the main series but left out two related collections:

  • Rick and Morty: The Anime, with its own continuity and episode catalogue;
  • The Non-Canonical Adventures, a collection of shorts that should not be mixed with regular seasons.

These were not extra seasons of the same work. We needed to add them as independent works, retain their context, and connect every episode to the correct work.

2.2. Second issue: one observation is not enough for comparison

Episodes already had a TVmaze rating. That value was useful for display, but it could not support provider comparison or explain why sources might disagree. Overwriting it with another score would not solve the problem: we would lose provenance and turn the most recent import into an accidental truth.

The chart needed a richer model: several observations per episode, each with a provider, scale, vote count, external identifier, source URL, and retrieval date. The interface would come later; first we had to complete the domain model and the ETL process that supplied it.

3. What to require from the new sources

The search could not stop at finding a page that displayed the right value. The sources had to fit an open, reproducible project. I used criteria similar to those applied to the primary migration:

  • Open or free access, without requiring a closed commercial service to run the example.
  • Current data, obtained from a maintained API or dataset rather than copied manually into the repository.
  • Stable identifiers, so records can be joined without translated titles or ambiguous searches.
  • Verifiable provenance, including provider, URL, and usage conditions that can be stored with the value.
  • A processable format, whether remote JSON, downloadable files, or responses a source plugin can normalise.
  • Isolatable failures, because an unavailable secondary source must not make the primary catalogue unusable.

That last requirement proved decisive. A deprecated API or a large dataset can remain useful when its absence does not break the base process and the affected step can be retried independently.

4. The selected sources and their responsibilities

The research produced a small set of sources, each with a specific responsibility. Some were already present in the primary migration, but not all create entities or act on the same content.

SourceAccess methodResponsibility in the secondary migration
WikidataRecords identified by QIDIdentify and describe the two complementary works.
TVmazePublic episode APICreate the Anime and Non-Canonical Adventures catalogues with stable episode IDs.
FandomEditorial franchise catalogueIndependently verify the expected set of 36 non-canonical shorts.
MyShowsPublic read-only APIAdd rating observations to the non-canonical shorts.
IMDbDownloadable non-commercial datasetsAdd scores and vote counts to existing main-series episodes.

This split prevents any source from receiving more authority than it should have. Wikidata identifies works, TVmaze supplies episode catalogues, Fandom helps verify coverage, and rating providers contribute observations. The optional-enrichment documentation records the full contract and approved identifiers.

Operationally, the providers also differ. IMDb publishes compressed files that we download and stream. MyShows exposes a deprecated but still useful API, kept optional and isolated. TVmaze is queried through fixed IDs rather than title search. If a catalogue changes unexpectedly, the process fails for review instead of silently accepting different content.

5. Designing a secondary migration

Secondary migration is not an official Drupal plugin type or Migrate API category. In this project, it is the name of an optional operational contract that runs after the primary migration.

The contract has five properties. They are not five consecutive steps and do not all belong to one class; they are invariants distributed across input validation, YAML definitions, lookup plugins, and orchestration.

Contract propertyImplementation decisionPrimary mechanism
5.1 Startup: the primary migration must be complete.Treat persisted output as a precondition rather than an assumption.PrimaryMigrationReadiness and repeated endpoint validation.
5.2 Operation: the primary catalogue must not be destructively changed.Add separate works, episodes, and observations without reverting the first migration.OptionalEnrichmentOrchestrator and independent optional migrations.
5.3 Idempotency: retries must not duplicate content.Assign stable identities and retain source-to-destination mappings.Source keys, Migrate maps, --update, and deterministic lookups.
5.4 Isolation: one optional provider must not block the others.Make every external integration independently executable and configurable.Provider-specific steps and RICK_AND_MIGRATY_OPTIONAL_* variables.
5.5 Persistence: interruption must not require a full restart.Store step outcomes and retry only incomplete work.Drupal State, typed outcomes, and effect verification.

This table serves as both a compact requirements catalogue and a high-level design map. The components described below each implement a specific part of that contract.

5.1. The primary migration is a verifiable precondition

The first property establishes how we certify that the primary migration has actually run and finished. This is why the contract calls for a PHP class devoted to checking that precondition.

I therefore implemented PrimaryMigrationReadiness. Its responsibility is neither to execute the primary migration nor to order a YAML definition. It answers a domain question: does Drupal contain a sufficiently complete primary catalogue to accept extensions?

Knowing that a command completed at some point is not enough. The class checks the main entities, the relationships between episodes and characters, the relationships between locations and residents, and the completion of the Fandom enrichment batches. The secondary migration depends on the persisted result of the first migration, not merely its execution history.

The first check queries the entity storages directly. count() does not read a previous run status; it asks Drupal how many entities really exist at that moment:

private function count(string $entityTypeId): int {
  return (int) $this->entityTypeManager->getStorage($entityTypeId)
    ->getQuery()
    ->accessCheck(FALSE)
    ->count()
    ->execute();
}

isComplete() uses that method to count characters, locations, episodes, and works. It then compares the result with the minimum catalogue that the primary migration must have produced:

$counts = [
  'characters' => $this->count('rick_and_migraty_character'),
  'locations' => $this->count('rick_and_migraty_location'),
  'episodes' => $this->count('rick_and_migraty_episode'),
  'works' => $this->count('rick_and_migraty_work'),
];
$coreReady = $counts['characters'] >= 826
  && $counts['locations'] >= 126
  && $counts['episodes'] >= 51
  && $counts['works'] >= 1
  && $this->hasRelationship('rick_and_migraty_episode', 'characters')
  && $this->hasRelationship('rick_and_migraty_location', 'residents');

if (!$coreReady) {
  return FALSE;
}

Counts prove that entities exist, but not that the main relationships were populated. That is why the same block calls hasRelationship() twice. The method looks for at least one entity whose reference field contains data:

private function hasRelationship(string $entityTypeId, string $fieldName): bool {
  return $this->entityTypeManager->getStorage($entityTypeId)
    ->getQuery()
    ->accessCheck(FALSE)
    ->exists($fieldName)
    ->range(0, 1)
    ->execute() !== [];
}

More precisely, isComplete() requires at least one episode with associated characters and one location with residents. This is not an exhaustive validation of every relationship, but it prevents a catalogue containing only disconnected entities from being considered ready.

Finally, the class performs a different check for the Fandom enrichment. Those batches do leave an explicit list of completed steps in Drupal State. The class retrieves that value, rejects anything that is not a step identifier, and makes sure none of the steps returned by fandomStepIds() is missing:

$completed = $this->state->get(self::COMPLETED_STEPS_STATE_KEY, []);
$completed = is_array($completed)
  ? array_values(array_filter($completed, 'is_string'))
  : [];

return array_diff($this->fandomStepIds(), $completed) === [];

Here we do consult persisted execution history, but never in isolation. The class reaches this comparison only after verifying that the main entities and relationships still exist. The precondition therefore combines evidence from the current domain state with the record of the batches that completed the enrichment.

This validation runs when the flow is opened, when it starts, and before protected operations execute. Consequently, a direct request to an endpoint cannot bypass the precondition already displayed by the interface.

The dependency declared in Migrate YAML remains useful for ordering specific migrations, but it cannot express this complete functional state on its own. The two layers complement each other:

  • migration_dependencies orders related migrations inside Migrate API;
  • PrimaryMigrationReadiness verifies that the application as a whole is ready for optional enrichment.

5.2. The boundary is additive: extend, do not rebuild

The second property is enforced by restricting what the secondary plan may do. It never calls rollback, reset, or deletion commands. It imports optional works, complementary episodes, and rating observations without rebuilding the characters, locations, episodes, and relationships produced by the primary migration.

The data model expresses the same boundary. IMDb and MyShows scores become related observation entities; they do not overwrite TVmaze’s value. The Anime and The Non-Canonical Adventures have their own migrations rather than becoming extra source rows in the main-work definition.

Secondary describes both a temporal dependency and an ownership restriction: the process may read and relate to the base catalogue, but it does not own its lifecycle. A provider failure therefore leaves a usable primary site behind.

5.3. Idempotency starts with identity

The third property connects the contract with the implementation decisions developed in the next two sections. Flags and execution options such as --update cannot prevent duplicates on their own. First, every source row must present the same identity each time the migration runs:

Several kinds of identity appear in this workflow because not every operation creates the same kind of content:

  • optional works use a stable machine_id;
  • complementary episodes retain the TVmaze episode ID;
  • IMDb observations use tconst as their source ID and store the destination observation in a Migrate map;
  • observations created before that map can be adopted through episode + provider + external ID.

A visible title never becomes an accidental identity. Source keys allow Migrate to find previous destinations, while process plugins resolve existing entities when two systems do not share identifiers. Section 6 illustrates the first case by creating new works and episodes; Section 7 develops the second by enriching episodes that already exist in Drupal.

5.4. Isolating providers means isolating steps and failures

The fourth property takes shape in the plan defined by OptionalEnrichmentOrchestrator. Although the browser presents a single action, the orchestrator keeps separate steps for optional works, each episode catalogue, MyShows ratings, and IMDb ratings.

This separation has two consequences. First, each integration can be disabled through its own RICK_AND_MIGRATY_OPTIONAL_* variable without changing the meaning or usefulness of the primary catalogue. Second, a network failure, unexpected episode count, or unavailable provider remains attached to its own step; it does not require reverting completed steps or invalidate the base data.

This is not merely a matter of decomposing a large method into smaller functions. The isolation boundary matches the external risk boundary: every provider has its own availability, licence, format, and identity model. Each one therefore deserves a separate operational outcome that can be inspected and retried independently.

5.5. Resuming requires persisted progress and verified effects

After every step, the orchestrator stores an imported, updated, skipped, or failed outcome in Drupal State. A later run retains successful steps and retries failed ones, so reloading the browser does not force the whole process to start again.

Historical state, however, does not prove that data still exist. Before retaining a previous IMDb success, the orchestrator verifies that IMDb observations remain persisted. This distinction gives us two kinds of truth:

  1. Orchestration truth: which step ran and what outcome it reported.
  2. Domain truth: which works, episodes, and ratings currently exist in Drupal.

Drupal State retains the first; entities, source keys, and migration maps retain the second. Reliable resumption checks both wherever the risk requires it.

With this map in place, we can discuss the implementation without presenting one PHP class as though it were the entire secondary migration. The contract is fulfilled through composition: readiness verifies the precondition; separate migrations and observations protect the base catalogue; identities and lookups make repetition safe; provider-specific steps isolate failures; and persisted state makes the workflow resumable.

These properties are not five consecutive steps. The following sections deliberately change perspective and follow the data flow instead: first we create complementary content, then enrich existing entities, orchestrate a resumable run, and finally verify the result.

6. Creating the complementary works and episodes

Once the primary precondition is satisfied, the first ETL operation creates the two missing works. This small migration uses Drupal Core’s embedded_data source plugin because its approved identity records belong directly in the YAML definition.

This is the simplest useful Migrate API case: the source rows live directly inside the migration definition. If you need the background, the second article in this series develops a similar embedded-data example before moving on to CSV.

rick_and_migraty_work_optional contains the records:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
id: rick_and_migraty_work_optional
label: 'Optional Rick and Migraty franchise works'
migration_group: rick_and_migraty

source:
  plugin: embedded_data
  data_rows:
    -
      machine_id: rick-and-morty-the-anime
      name: 'Rick and Morty: The Anime'
      work_type: anime_series
      canonical_status: derivative_continuity
      source_provider: Wikidata
      source_id: Q116508000
      source_url: 'https://www.wikidata.org/wiki/Q116508000'
      wikidata_id: Q116508000
      tvmaze_id: '62220'
    -
      machine_id: non-canonical-adventures
      name: 'Rick and Morty: The Non-Canonical Adventures'
      work_type: short_collection
      canonical_status: non_canonical
      source_provider: Wikidata
      source_id: Q117358705
      source_url: 'https://www.wikidata.org/wiki/Q117358705'
      wikidata_id: Q117358705
      tvmaze_id: '55936'
  ids:
    machine_id:
      type: string

process:
  machine_id: machine_id
  name: name
  work_type: work_type
  canonical_status: canonical_status
  source_provider: source_provider
  source_id: source_id
  source_url: source_url
  wikidata_id: wikidata_id
  imdb_id: imdb_id
  tvmaze_id: tvmaze_id
  uid:
    plugin: default_value
    default_value: 1

destination:
  plugin: 'entity:rick_and_migraty_work'
  validate: true

migration_dependencies:
  required:
    - rick_and_migraty_work

Source: Source file on GitLab

machine_id matters more than the visible title: it is the stable identity that makes migrate:import --update update a previous destination instead of creating another work. The migration also depends on rick_and_migraty_work, establishing that the optional catalogue extends rather than replaces the main work.

Once the destination contains the two new work entities, the next operation can load the episode catalogue that belongs to each one. We keep those responsibilities in two migrations: one for The Anime and one for the non-canonical shorts.

6.1. Which plugins do we need?

Before implementing them, we should take stock of the tools: which resources already exist, and which piece genuinely needs to be custom? The decision should follow the migration contract rather than a preference for writing new code.

At source level, both migrations need the same reusable abstraction: the complete, approved episode catalogue for one specific TVmaze show. It must serve both The Anime and The Non-Canonical Adventures without hard-coding either one into the plugin.

Drupal Core provides the base for source plugins and covers sources such as the embedded data we just used. Migrate Plus could combine its generic url plugin with a JSON parser. That would be enough if the problem were merely to download a document and select a path, but our contract requires more: it must enforce a fixed show identity and an expected catalogue size.

Existing custom plugins do not fit either. rick_and_morty_api understands the canonical API’s pagination and schema; reusing it for TVmaze would mix two remote contracts. The Fandom plugin resolves MediaWiki pages rather than episode catalogues.

Forcing either plugin into this job merely to avoid creating one class would reduce the visible line count while increasing coupling. More importantly, it would hide the actual conditions of this source: the caller must select one known TVmaze show, receive its complete episode catalogue, and reject a response that no longer matches the approved scope.

That leads to the custom source plugin RickAndMigratyTvmazeEpisodes. It receives a show_id, requests /shows/{id}/episodes, normalises each row, exposes the TVmaze ID as a stable key, supports a test base URL, caches responses, and can enforce expected_count. A catalogue mismatch fails for review instead of being silently accepted.

The following simplified extract makes the core decision visible. HTTP and cache infrastructure are omitted so that the contract stands out: stable identity, mandatory configuration, and catalogue-size validation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php

#[MigrateSource('rick_and_migraty_tvmaze_episodes')]
final class RickAndMigratyTvmazeEpisodes extends SourcePluginBase {

  public function getIds(): array {
    return ['id' => ['type' => 'integer']];
  }

  protected function initializeIterator(): \Iterator {
    $showId = (int) ($this->configuration['show_id'] ?? 0);
    if ($showId < 1) {
      throw new MigrateException(
        'TVmaze requires a positive show_id.',
      );
    }

    $rows = $this->loadAndNormalizeEpisodes($showId);
    $expected = (int) (
      $this->configuration['expected_count'] ?? 0
    );

    if ($expected > 0 && count($rows) !== $expected) {
      throw new MigrateException(
        'The TVmaze catalog has an unexpected size.',
      );
    }

    return new \ArrayIterator($rows);
  }

}

Source: Complete plugin on GitLab

The full implementation injects http_client and cache.data, validates the URL and HTTP response, decodes JSON, and normalises fields such as episode_code, rating_average, and description. YAML remains responsible for the differences between the two migrations—the show, expected row count, and destination mapping—while the shared TVmaze contract lives in one reusable, unit-tested class.

The two migrations therefore draw on components from different parts of the Drupal ecosystem. Not every operation in their YAML files needs a custom plugin. We reserve project code for the TVmaze-specific contract and reuse Migrate API plugins for generic transformations. The resulting inventory is deliberately small:

  • Custom source — rick_and_migraty_tvmaze_episodes: this is the new RickAndMigratyTvmazeEpisodes. Although it extends Core’s SourcePluginBase, its implementation belongs to our rick_and_migraty_migrate module. It queries TVmaze, enforces the approved-catalogue contract, normalises rows, and exposes id as the stable source identity.
  • Core process — default_value: introduces known values that do not need to come from TVmaze. We use it for the receiving work key, rating and description providers, licence, and owner. Both migrations reuse the same plugin while supplying different values.
  • Core process — migration_lookup: translates the optional work’s stable source key into the destination entity ID created by rick_and_migraty_work_optional. Episodes are attached to their work without searching by title or duplicating query logic.
  • Core process — concat: needed only for non-canonical content. It combines the SHORT- constant with the episode number to build episode_code; the Anime migration can use the code already normalised by the source plugin.
  • Core destination — entity:rick_and_migraty_episode: this is Core’s generic entity destination derivative. The plugin is part of Core even though rick_and_migraty_episode is our custom entity type. With validate: true, every entity is validated before its row finishes importing.

As a contributed module, Migrate Plus still provides the migration_group: rick_and_migraty metadata used to organise these definitions. It also supplied the generic url plus JSON-parser alternative considered earlier, but that option was deliberately rejected. In other words, no contributed plugin remains in the final source/process/destination pipeline: the executable plugins are the Core components listed above plus our custom source.

With the toolbox established, we can define one episode migration for each catalogue:

Both use RickAndMigratyTvmazeEpisodes: the configured show_id changes, but the plugin still normalises fields, retains the TVmaze episode ID, and validates the expected number of rows. Both then attach episodes to their work through Core’s migration_lookup:

process:
  work_key:
    plugin: default_value
    default_value: rick-and-morty-the-anime
  work:
    plugin: migration_lookup
    migration: rick_and_migraty_work_optional
    source: '@work_key'
    no_stub: true

This is the natural use of migration_lookup: we know the original source key and the migration that created the destination. no_stub: true prevents an incomplete reference from being fabricated when the work is absent.

7. Locating existing entities to enrich them

The other half of the work—and the core of this article—is not creating episodes. It is accepting an external row, determining which stored entity represents the same object, and adding information without recreating it. The hard question is how to prove that records from different systems describe the same thing.

IMDb identifies an episode by its tconst. Drupal knows it through an internal entity ID, a work reference, season, and episode number. We need a shared identity that bridges both models.

Searching by episode title is tempting, but fragile. Titles can be translated, corrected, punctuated differently, or repeated across works. Even an exact match today can stop matching after a routine editorial change.

A useful lookup identity must satisfy three conditions:

  1. It must be stable: a presentation correction should not change it.
  2. It must be sufficiently specific: it should identify at most one local entity.
  3. It must be available on both sides: the external source and Drupal must express the same key or a verifiable equivalent.

For regular episodes, we use work + season + episode number:

rick-and-morty + season 3 + episode 7

The work prevents S03E07 from another series becoming a false positive. Season and episode locate the record within that work. IMDb’s tconst is retained as the identity of the new rating observation rather than used to locate an episode created before that identifier was needed.

Three kinds of lookup in a Drupal migration

  • migration_lookup queries an earlier migration’s map tables. It is the best option when the original source ID and the migration that created the destination are known.
  • entity_lookup, provided by contributed modules in the Migrate ecosystem, searches for an entity by property. It is useful when there is no reusable migration map and one unique property can express the identity.
  • A custom process plugin can combine several entity types and properties, validate cardinality, and explicitly decide what to do with zero or multiple matches.

No option is universally best. If we retained the original source ID and its map, migration_lookup gives us traceability almost for free. If the entity predates our migration, or the new source does not share that ID, we must locate it through its business identity. The IMDb → episode join requires work + season + episode, so Rick and Migraty uses a dedicated process plugin.

The source prepares the external half of the identity

Before looking at the plugin, we need to understand how IMDb distributes these data. Rather than exposing one request that returns every Rick and Morty episode with its rating, IMDb publishes a collection of datasets for non-commercial use. They are global snapshots of its catalogue, updated daily and divided by responsibility: title identity, series/episode relationships, ratings, cast, and other domains.

Every dataset is a UTF-8 TSV file compressed with Gzip. The first row contains headers, columns are separated by tabs, and \N represents a missing value. We are not downloading a small JSON document for our series; we are filtering and joining general-purpose files during ETL.

Two files are required:

  • title.episode.tsv.gz describes the episode’s structural identity. Each row contains the episode tconst, the series parentTconst, seasonNumber, and episodeNumber. It answers which episode is this, and to which series does it belong?, but contains no rating.
  • title.ratings.tsv.gz contains the rating observation. For each tconst, it provides averageRating—the weighted mean of user ratings—and numVotes. It knows how a title was rated, but not its season, episode number, or parent series.

The tconst is the join key between both files. The operation can be described in four steps:

  1. Read the series IMDb identifier from Drupal’s work entity; this is the parentTconst we need.
  2. Stream title.episode.tsv.gz and retain only episodes whose parentTconst matches that series.
  3. Find each selected episode’s score and vote count in title.ratings.tsv.gz through its tconst.
  4. Emit a migration row that combines tconst, season, episode, rating, and votes.

Neither dataset is sufficient on its own: the first provides the context required to locate the Drupal episode; the second provides the new information with which we want to enrich it. The files are streamed and never committed to the project.

rick_and_migraty_episode_rating_imdb implements this join through RickAndMigratyImdbEpisodeRatings.

The plugin first loads the work by machine_id and obtains its IMDb series identifier. This lets it filter a huge dataset and emit only rows that belong to the work being enriched:

$works = $this->entityTypeManager
  ->getStorage('rick_and_migraty_work')
  ->loadByProperties(['machine_id' => $machineId]);
$work = reset($works);

if ($work === FALSE) {
  throw new MigrateException(sprintf(
    'The work %s must be imported before IMDb ratings.',
    $machineId,
  ));
}

$seriesId = trim((string) $work->get('imdb_id')->value);

This illustrates a broader principle: an enrichment migration should declare and verify its precondition. If the main work does not exist or lacks an IMDb ID, continuing to download and transform rating files makes no sense. Failing early gives a much more useful diagnosis than ending with zero matches.

After joining both files, every row entering Migrate has a deterministic shape:

$rows[] = [
  'tconst' => $titleId,
  'series_tconst' => $seriesId,
  'season' => $identity['season'],
  'episode' => $identity['episode'],
  'episode_code' => sprintf(
    'S%02dE%02d',
    $identity['season'],
    $identity['episode'],
  ),
  'average_rating' => $ratings[$titleId]['value'],
  'num_votes' => $ratings[$titleId]['votes'],
  'retrieved_at' => $retrievedAt,
];

The tconst is the migration’s source ID. Season and episode are the coordinates used to locate the corresponding Drupal entity. Score, votes, and retrieval time are the new information. Keeping those roles separate prevents a presentation value from becoming an accidental identity.

Resolving the receiving entity in the process pipeline

The YAML definition passes season and episode to the custom rick_and_migraty_episode_lookup process plugin:

process:
  episode:
    plugin: rick_and_migraty_episode_lookup
    source:
      - season
      - episode
    work_machine_id: rick-and-morty

RickAndMigratyEpisodeLookup receives those two coordinates and adds the configured third component: the work identity. First, it requires exactly one work with that machine_id:

$works = $this->entityTypeManager
  ->getStorage('rick_and_migraty_work')
  ->loadByProperties(['machine_id' => $machineId]);

if (count($works) !== 1) {
  throw new MigrateException(sprintf(
    'Expected exactly one work with machine_id %s; found %d.',
    $machineId,
    count($works),
  ));
}

It then uses that work ID to constrain the episode query:

$work = reset($works);
$episodes = $this->entityTypeManager
  ->getStorage('rick_and_migraty_episode')
  ->loadByProperties([
    'work' => $work->id(),
    'season' => $season,
    'episode_number' => $episodeNumber,
  ]);

The result is not treated as a boolean. Its cardinality has meaning:

  • Zero episodes: the IMDb row has no local receiver and is skipped with MigrateSkipRowException.
  • One episode: the match is unambiguous, so the plugin returns its ID.
  • More than one episode: the local catalogue violates the assumed uniqueness and the migration fails with MigrateException.

This distinction matters. “We do not have this episode yet” can be a tolerable difference between catalogues. “We have two indistinguishable candidates” signals corruption or ambiguity that should not be hidden by selecting the first result. A safe lookup does more than find an entity: it protects the system from uncertain matches.

The migration pipeline then maps that resolved entity ID into the observation’s episode reference while preserving tconst as the observation’s external identity.

Enrichment does not mean modifying the episode directly

The IMDb score is not written into a single episode field and does not replace TVmaze’s rating. Doing that would destroy provenance. Instead, the model stores a separate rick_and_migraty_episode_rating observation entity linked to the resolved episode, so providers can coexist and every value retains its scale, votes, URL, licence, and retrieval date.

The central part of the migration looks like this:

process:
  episode:
    plugin: rick_and_migraty_episode_lookup
    source:
      - season
      - episode
    work_machine_id: rick-and-morty
  id:
    plugin: rick_and_migraty_episode_rating_lookup
    source:
      - '@episode'
      - tconst
    provider: IMDb
  provider: constants/provider
  external_id: tconst
  raw_value: average_rating
  normalized_value: average_rating
  vote_count: num_votes
  retrieved_at: retrieved_at

destination:
  plugin: 'entity:rick_and_migraty_episode_rating'
  validate: true
  overwrite_properties:
    - episode
    - raw_value
    - normalized_value
    - vote_count
    - retrieved_at

The first lookup answers “which episode should receive this datum?” The second answers “did this IMDb observation already exist before this migration started managing it?” They are two different identities and two different problems.

Adopting data that predates the migration map

Migrate API maintains a map table between each row’s tconst and the rating entity created at the destination. That map allows later --update runs to refresh the same observation. There is, however, an edge case: an earlier importer may already have created an IMDb observation before the Migrate-based implementation existed. The new map does not know its destination even though the domain entity is present.

RickAndMigratyEpisodeRatingLookup can adopt those entities. It searches through a compound identity made of episode, provider, and external ID:

$ratings = $this->entityTypeManager
  ->getStorage('rick_and_migraty_episode_rating')
  ->loadByProperties([
    'episode' => $episodeId,
    'provider' => $provider,
    'external_id' => $externalId,
  ]);

if (count($ratings) > 1) {
  throw new MigrateException(sprintf(
    'Multiple %s observations exist for episode %d and external ID %s.',
    $provider,
    $episodeId,
    $externalId,
  ));
}

return $ratings === [] ? NULL : (int) reset($ratings)->id();

If none exists, the plugin returns NULL and the destination creates an observation. If one exists, it returns the ID and the destination updates it. If several exist, the process stops: creating a third or updating an arbitrary one would only conceal the problem.

This layer makes the migration idempotent in two distinct scenarios:

  1. After its first run, through the standard Migrate API map.
  2. When replacing an older importer, by adopting observations that existed before that map.

Idempotency is not merely the ability to run a command twice. It means that repetition—or a transition between implementations—preserves identity, updates the correct datum, and does not accidentally increase the entity count. This is an important migration pattern: a new implementation can adopt older, correctly identified data into its tracking model.

The complete journey of an IMDb row

For one episode, the flow is now explicit:

  1. title.episode.tsv.gz supplies tconst, parent series, season, and episode.
  2. title.ratings.tsv.gz supplies score and vote count for the same tconst.
  3. The source plugin joins and normalises both records.
  4. RickAndMigratyEpisodeLookup resolves one local episode through work + season + episode.
  5. RickAndMigratyEpisodeRatingLookup adopts any matching pre-map observation.
  6. The entity destination validates and writes the rating observation.
  7. The Migrate map records tconst → rating entity ID for future updates.

Seen this way, enrichment is not a second import of the content. It is a controlled join between two identity spaces. The episode remains the entity created by the primary migration; the secondary migration only proves which episode it is, creates or adopts a related observation, and adds information that was not previously available.

MyShows applies the same principle with a different identity

IMDb forced us to join two global datasets through tconst. MyShows poses the same underlying problem—associating an external observation with an episode already stored—but exposes a different source and identity space. We use its public read-only API to complete the ratings for the 36 Non-Canonical Adventures shorts.

The API does not return everything in one response. MyShowsClient makes two kinds of request:

  • shows/74303 returns the remote Non-Canonical Adventures catalogue and its episode identifiers;
  • episodes/{episode_id} returns one episode’s details, including its aggregate rating and vote count.

This access pattern explains why we keep a dedicated importer rather than modelling the operation as another declarative migration. We must validate the complete catalogue first and make an additional request for every accepted episode. The MyShows API is also deprecated and optional: isolating it behind a small client prevents its contract from leaking into the rest of the Migrate API pipeline.

Identity is again the difficult part. The MyShows episode ID identifies the rating request and is retained as the observation’s external ID, but the Drupal episodes were not created with it. The catalogue response does, however, contain a tvrageLink whose URL embeds the same episode’s TVmaze ID. Drupal already knows that value because the preceding migration stored it as tvmaze_id.

MyShowsEpisodeRatingImporter builds the bridge in five steps:

  1. Loads non-canonical-adventures and its episodes.
  2. Indexes local episodes by tvmaze_id.
  3. Loads the MyShows record for show 74303 and extracts TVmaze IDs from tvrageLink.
  4. Resolves the matching local episode.
  5. Loads the MyShows detail and stores the observation.

Here again we prefer to fail when the contract drifts. Before writing, the importer requires exactly 36 local episodes and 36 remote episodes. A partial response is not interpreted as a successful import: a change in either catalogue must be reviewed before accepting new associations.

For every match, the remote detail must contain a score between 1 and 5 and a positive vote count. EpisodeRatingManager retains the provider, original value and scale, votes, external ID and URL, and retrieval time. It writes by the compound identity episode + provider + external ID, so a retry updates the existing observation instead of duplicating it.

Finally, persistence and trust are not the same decision. MyShows observations with fewer than five votes remain visible and traceable, but do not participate in the episode’s aggregate calculations. Importing a value does not require us to give it the same statistical weight as an observation backed by a larger sample.

The concrete mechanism differs from IMDb, but the mental model remains the same: choose a stable shared key, require an unambiguous match, separate the receiving entity from the new observation, and make the write repeatable. That is what turns an additional data load into reliable enrichment.

8. Orchestrating a resumable run

The browser presents one secondary-migration action, but OptionalEnrichmentOrchestrator coordinates seven steps:

  1. Prepare the system.
  2. Import the complementary works.
  3. Import The Anime episodes.
  4. Import The Non-Canonical Adventures shorts.
  5. Add MyShows ratings.
  6. Add IMDb ratings to existing episodes.
  7. Finalise and rebuild caches.

Works, episodes, and IMDb ratings run through migrate:import --update; MyShows keeps its dedicated Drush importer. Each step records an imported, updated, skipped, or failed outcome in Drupal State. A new run retains successful steps and retries failed ones. The IMDb step additionally checks that persisted observations still exist before trusting historical success.

That extra check preserves an important distinction: “the command completed” is not the same as “the expected effect still exists”. A resumable ETL workflow needs both pieces of evidence before it decides that a step can safely be skipped.

Providers can be disabled independently for testing or local operation:

RICK_AND_MIGRATY_OPTIONAL_WIKIDATA=0
RICK_AND_MIGRATY_OPTIONAL_TVMAZE=0
RICK_AND_MIGRATY_OPTIONAL_MYSHOWS=0
RICK_AND_MIGRATY_OPTIONAL_IMDB=0

The web UI invokes each step separately and displays progress, but it is not the source of truth. Progress lives in Drupal State; identity lives in entities and Migrate maps. Reloading the browser does not force a restart.

9. Testing the integration and building the ratings area

A secondary migration does not finish when the last command returns zero. We must prove that works exist, episodes reference the right work, ratings belong to real episodes, and the interface can consume the resulting model.

The project distributes that evidence across several tests:

For the interactive visualisation, we use Chart.js. Version 4.6.1 renders a line chart whose horizontal axis represents an episode’s position within a work and whose vertical axis shows its rating on a normalised ten-point scale. Each work is a separate series, so their trajectories can be compared without merging catalogues.

Chart.js is responsible only for client-side presentation: it draws the chart, adapts its scales, displays episode details, providers, vote counts, and confidence levels in tooltips, updates the result after filtering, and turns each point into a link. It neither queries Drupal entities nor decides how ratings are calculated; those responsibilities remain in the backend.

RatingInsightsController loads works, episodes, and observations. It applies aggregate-eligibility rules and marks episodes whose only samples have low confidence. It sends that structure to the template and drupalSettings; rating-insights.js converts it into Chart.js datasets.

The public ratings area lets visitors:

  • compare the main series, The Anime, and The Non-Canonical Adventures;
  • filter by work, season segment, and rating threshold;
  • follow rating trajectories on a chart;
  • inspect provider, vote count, and confidence;
  • open an episode profile from a point or card.

The ratings-dashboard guide documents the filters and visualisation. The interface is not an isolated extra: it is visible proof that the secondary migration created and enriched the required relationships.

Rick and Migraty ratings dashboard with work, season, and score filters and a comparative episode chart. Interactive Rick and Migraty ratings dashboard

The screenshot shows the integrated result: three works as independent filters and their episode trajectories on one common scale. The controls narrow the comparison by work, season segment, and rating threshold; each point links to its episode. This verifies the complete chain: run enrichment, persist new observations, and turn them into a navigable interface.

10. Patterns worth keeping

At this point, we can separate Rick and Migraty’s concrete details from the architectural decisions that sustained the whole process. TVmaze, IMDb, and MyShows are this example’s providers; works, episodes, and ratings are its specific model. The broader problem is how to extend an already migrated catalogue without breaking its original contract, how to recognise existing entities, and how to incorporate multiple sources repeatably and verifiably.

The conclusion is not that every secondary migration needs this exact collection of plugins and services. It is that dependencies must be explicit: required prior state, destination identity, ownership of each datum, and the evidence that proves enrichment completed successfully.

When those decisions remain separate, we can replace one provider, add another catalogue, or resume a failed import without turning the entire process into a special case that is difficult to understand and maintain.

From that perspective, several decisions are reusable:

  • Start from the use case. The chart revealed which data and model were missing.
  • Separate the base catalogue from extensions. The primary migration remains small, stable, and independently useful.
  • Assign one responsibility to each source. Identification, content creation, enrichment, and verification are different jobs.
  • Choose the lookup from the identity. A migration map, entity property, or custom service solves a different problem.
  • Keep deterministic keys. machine_id, season + episode, and tvmaze_id turn retries into updates.
  • Store observations with provenance. Providers can coexist without the latest one overwriting earlier values.
  • Validate persistent effects. A successful command is insufficient if it left no usable entity or rating.
  • Design for resumption. External providers fail; isolate the damage and continue safely.
  • Test the complete integration. Model, migrations, importers, and visualisation form one chain.

A well-designed secondary migration is not an improvised appendix. It is a new ETL contract that understands the state created by the previous migration and knows exactly what it may create, locate, and enrich.

11. Running the secondary migration from the terminal

The same process can be run from a terminal. This is especially useful during development because we can invoke providers separately, inspect Drush output, and repeat only a failed step. The contract remains unchanged: the primary migration must be complete, and the secondary flow must not begin by deleting the existing catalogue.

The project currently has no single shell wrapper for the complete secondary process. scripts/rick-and-migraty-migrate.sh handles the primary catalogue. The complementary sequence is declared by OptionalEnrichmentOrchestrator, which also powers the browser’s More cowbell action. Manual execution reproduces that same order with Drush.

11.1. Preparing the primary migration

From the repository root, start DDEV and run the primary runner when a complete base catalogue is not already present. --fixtures uses local API copies when available:

ddev start
scripts/rick-and-migraty-migrate.sh --fixtures

The script rebuilds caches, optionally resets previous imported data, imports primary entities and relationships, generates aliases, and runs Fandom enrichment. Do not run it with its default reset behaviour after starting secondary enrichment, because ramt:migrate:reset removes both primary and complementary entities, observations, and maps.

When the primary migration already exists, inspect its status instead of rebuilding it:

ddev drush migrate:status --group=rick_and_migraty

11.2. Running the secondary steps with Drush

Rebuild caches so Drupal discovers current definitions and plugins, then create optional works, import both TVmaze catalogues, and add MyShows and IMDb observations:

ddev drush cr

ddev drush migrate:import rick_and_migraty_work_optional \
  --update --feedback=10

ddev drush migrate:import rick_and_migraty_episode_anime \
  --update --feedback=10

ddev drush migrate:import rick_and_migraty_episode_noncanonical \
  --update --feedback=10

ddev drush ramt:migrate:myshows-ratings

ddev drush migrate:import rick_and_migraty_episode_rating_imdb \
  --update --feedback=10

ddev drush cr

Order matters. rick_and_migraty_work_optional persists work identities first; episode migrations can then resolve them through migration_lookup; MyShows finds non-canonical shorts by TVmaze identity; IMDb joins its datasets to main-series episodes. --update makes already imported sources processable without creating another copy.

MyShows uses a different command because it is not a YAML Migrate definition: ramt:migrate:myshows-ratings invokes the dedicated API importer and upserts every observation. IMDb retains Migrate maps and messages, so it uses the standard migrate:import command.

11.3. Verifying the result and resuming after a failure

Inspect group status and IMDb messages after the run:

ddev drush migrate:status --group=rick_and_migraty
ddev drush migrate:messages rick_and_migraty_episode_rating_imdb

Do not stop at a zero exit code. Open /ratings, confirm that all three works are present, and verify that episode observations show provider, votes, and provenance links. This validates the persistent effect consumed by the interface rather than only command execution.

If a provider fails, repeat only its command. Stable keys, --update, and upserts make the sequence resumable. When a migration remains administratively stuck in Importing, release that specific migration before retrying:

ddev drush migrate:reset-status MIGRATION_ID

Replace MIGRATION_ID with the migration that is actually stuck. Do not use ramt:migrate:reset as an ordinary resume mechanism: it is a destructive cleanup of the complete local environment, not an isolated rollback of secondary enrichment.

12. :wq!

The first migration built the world of Rick and Migraty. The second appeared when we looked at that world from another angle and discovered that territories and data were still missing.

TRL · AUDIO / VISUAL ARCHIVE

Join the Newsletter

Subscribe to receive new articles about Drupal and web development directly in your inbox.

No spam. Unsubscribe at any time.