Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
IndexerTableSwapper.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
11 
16 {
22  private $temporaryTables = [];
23 
27  private $resourceConnection;
28 
33  {
34  $this->resourceConnection = $resource;
35  }
36 
44  private function createTemporaryTable(string $originalTableName): string
45  {
46  $temporaryTableName = $this->resourceConnection->getTableName(
47  $originalTableName . '__temp' . $this->generateRandomSuffix()
48  );
49 
50  $this->resourceConnection->getConnection()->query(
51  sprintf(
52  'create table %s like %s',
53  $temporaryTableName,
54  $this->resourceConnection->getTableName($originalTableName)
55  )
56  );
57 
58  return $temporaryTableName;
59  }
60 
66  private function generateRandomSuffix(): string
67  {
68  return bin2hex(random_bytes(4));
69  }
70 
74  public function getWorkingTableName(string $originalTable): string
75  {
76  $originalTable = $this->resourceConnection->getTableName($originalTable);
77  if (!array_key_exists($originalTable, $this->temporaryTables)) {
78  $this->temporaryTables[$originalTable] = $this->createTemporaryTable($originalTable);
79  }
80 
81  return $this->temporaryTables[$originalTable];
82  }
83 
87  public function swapIndexTables(array $originalTablesNames)
88  {
89  $toRename = [];
91  $toDrop = [];
93  $temporaryTablesRenamed = [];
94  //Renaming temporary tables to original tables' names, dropping old
95  //tables.
96  foreach ($originalTablesNames as $tableName) {
97  $tableName = $this->resourceConnection->getTableName($tableName);
98  $temporaryOriginalName = $this->resourceConnection->getTableName(
99  $tableName . $this->generateRandomSuffix()
100  );
101  $temporaryTableName = $this->getWorkingTableName($tableName);
102  $toRename[] = [
103  'oldName' => $tableName,
104  'newName' => $temporaryOriginalName,
105  ];
106  $toRename[] = [
107  'oldName' => $temporaryTableName,
108  'newName' => $tableName,
109  ];
110  $toDrop[] = $temporaryOriginalName;
111  $temporaryTablesRenamed[] = $tableName;
112  }
113 
114  //Swapping tables.
115  $this->resourceConnection->getConnection()->renameTablesBatch($toRename);
116  //Cleaning up.
117  foreach ($temporaryTablesRenamed as $tableName) {
118  unset($this->temporaryTables[$tableName]);
119  }
120  //Removing old ones.
121  foreach ($toDrop as $tableName) {
122  $this->resourceConnection->getConnection()->dropTable($tableName);
123  }
124  }
125 }
$tableName
Definition: trigger.php:13
$resource
Definition: bulk.php:12