-
Notifications
You must be signed in to change notification settings - Fork 518
/
Copy pathDatabaseCommand.php
375 lines (321 loc) · 12.4 KB
/
DatabaseCommand.php
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
namespace Akeneo\Platform\Bundle\InstallerBundle\Command;
use Akeneo\Platform\Bundle\InstallerBundle\CommandExecutor;
use Akeneo\Platform\Bundle\InstallerBundle\Event\InstallerEvent;
use Akeneo\Platform\Bundle\InstallerBundle\Event\InstallerEvents;
use Akeneo\Platform\Bundle\InstallerBundle\FixtureLoader\FixtureJobLoader;
use Akeneo\Tool\Bundle\ElasticsearchBundle\ClientRegistry;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Exception\ConnectionException;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Process\Process;
/**
* Database preparing command
* - creates database
* - updates schema
* - loads fixtures
* - launches other command for database calculations (completeness calculation)
*
* @author Romain Monceau <romain@akeneo.com>
* @copyright 2013 Akeneo SAS (http://www.akeneo.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class DatabaseCommand extends Command
{
protected static $defaultName = 'pim:installer:db';
const LOAD_ALL = 'all';
const LOAD_BASE = 'base';
/** @var CommandExecutor */
protected $commandExecutor;
/** @var EntityManagerInterface */
private $entityManager;
/** @var ClientRegistry */
private $clientRegistry;
/** @var Connection */
protected $connection;
/** @var FixtureJobLoader */
private $fixtureJobLoader;
/** @var EventDispatcherInterface */
private $eventDispatcher;
/** @var string */
private $env;
public function __construct(
EntityManagerInterface $entityManager,
ClientRegistry $clientRegistry,
Connection $connection,
FixtureJobLoader $fixtureJobLoader,
EventDispatcherInterface $eventDispatcher,
string $env
) {
parent::__construct();
$this->entityManager = $entityManager;
$this->clientRegistry = $clientRegistry;
$this->connection = $connection;
$this->fixtureJobLoader = $fixtureJobLoader;
$this->eventDispatcher = $eventDispatcher;
$this->env = $env;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('pim:installer:db')
->setDescription('Prepare database and load fixtures')
->addOption(
'fixtures',
null,
InputOption::VALUE_REQUIRED,
'Determines fixtures to load (can be just OroPlatform or all)',
self::LOAD_ALL
)
->addOption(
'withoutIndexes',
null,
InputOption::VALUE_OPTIONAL,
'Should the command setup the elastic search indexes',
false
)
->addOption(
'withoutFixtures',
null,
InputOption::VALUE_OPTIONAL,
'Should the command install any fixtures',
false
)
->addOption(
'catalog',
null,
InputOption::VALUE_OPTIONAL,
'Directory of the fixtures to install',
'src/Akeneo/Platform/Bundle/InstallerBundle/Resources/fixtures/minimal'
)
->addOption(
'doNotDropDatabase',
null,
InputOption::VALUE_NONE,
'Try to use an existing database if it already exists. Beware, the database data will still be deleted'
)
;
}
/**
* {@inheritdoc}
*/
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->commandExecutor = new CommandExecutor(
$input,
$output,
$this->getApplication()
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Prepare database schema</info>');
// Needs to try if database already exists or not
try {
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
if ($input->getOption('doNotDropDatabase')) {
$this->commandExecutor->runCommand('doctrine:schema:drop', ['--force' => true, '--full-database' => true]);
} else {
$this->commandExecutor->runCommand('doctrine:database:drop', ['--force' => true]);
}
} catch (ConnectionException $e) {
$output->writeln('<error>Database does not exist yet</error>');
}
$this->commandExecutor->runCommand('doctrine:database:create', ['--if-not-exists' => true]);
// Needs to close connection if always open
if ($this->connection->isConnected()) {
$this->connection->close();
}
$this->commandExecutor
->runCommand('doctrine:schema:create')
->runCommand(
'doctrine:schema:update',
['--force' => true, '--no-interaction' => true]
);
if (false === $input->getOption('withoutIndexes')) {
$this->resetElasticsearchIndex($output);
}
$entityManager = $this->entityManager;
$entityManager->clear();
$this->eventDispatcher->dispatch(
InstallerEvents::POST_DB_CREATE,
new InstallerEvent($this->commandExecutor)
);
// TODO: Should be in an event subscriber
if (!$input->getOption('doNotDropDatabase')) {
$this->createNotMappedTables($output);
}
if (false === $input->getOption('withoutFixtures')) {
$this->eventDispatcher->dispatch(
InstallerEvents::PRE_LOAD_FIXTURES,
new InstallerEvent($this->commandExecutor)
);
$this->loadFixturesStep($input, $output);
$this->eventDispatcher->dispatch(
InstallerEvents::POST_LOAD_FIXTURES,
new InstallerEvent($this->commandExecutor, null, [
'catalog' => $input->getOption('catalog')
])
);
}
// TODO: Should be in an event subscriber
$this->launchCommands();
$this->setLatestKnownMigration($input);
return $this;
}
/**
* TODO: TIP-613: This should be done with a command.
* TODO: TIP-613: This command should be able to drop/create indexes, and/or re-index products.
*
* @param OutputInterface $output
*/
protected function resetElasticsearchIndex(OutputInterface $output)
{
$output->writeln('<info>Reset elasticsearch indexes</info>');
$clients = $this->clientRegistry->getClients();
foreach ($clients as $client) {
$client->resetIndex();
}
}
/**
* Create tables not mapped to Doctrine entities
*
* @param OutputInterface $output
*
* @throws \Doctrine\DBAL\DBALException
*/
protected function createNotMappedTables(OutputInterface $output)
{
$output->writeln('<info>Create session table</info>');
$sessionTableSql = "CREATE TABLE pim_session (
`sess_id` VARBINARY(128) NOT NULL PRIMARY KEY,
`sess_data` BLOB NOT NULL,
`sess_time` INTEGER UNSIGNED NOT NULL,
`sess_lifetime` INTEGER UNSIGNED NOT NULL
) COLLATE utf8mb4_bin, ENGINE = InnoDB;";
$this->connection->exec($sessionTableSql);
$output->writeln('<info>Create configuration table</info>');
$configTableSql = "CREATE TABLE pim_configuration (
`code` VARCHAR(128) NOT NULL PRIMARY KEY,
`values` JSON NOT NULL
) COLLATE utf8mb4_unicode_ci, ENGINE = InnoDB;";
$this->connection->exec($configTableSql);
$output->writeln('<info>Create messenger table</info>');
$messengerTableSql = "CREATE TABLE messenger_messages (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`body` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`headers` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`queue_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` datetime NOT NULL COMMENT '(DC2Type:datetime)',
`available_at` datetime NOT NULL COMMENT '(DC2Type:datetime)',
`delivered_at` datetime DEFAULT NULL COMMENT '(DC2Type:datetime)',
PRIMARY KEY (`id`),
KEY `IDX_75EA56E0FB7336F0` (`queue_name`),
KEY `IDX_75EA56E0E3BD61CE` (`available_at`),
KEY `IDX_75EA56E016BA31DB` (`delivered_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
$this->connection->exec($messengerTableSql);
}
/**
* Step where fixtures are loaded
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @return DatabaseCommand
*/
protected function loadFixturesStep(InputInterface $input, OutputInterface $output)
{
$catalog = $input->getOption('catalog');
if ($input->getOption('env') === 'behat') {
$input->setOption('fixtures', self::LOAD_BASE);
}
$output->writeln(
sprintf(
'<info>Load jobs for fixtures. (data set: %s)</info>',
$catalog
)
);
$this->fixtureJobLoader->loadJobInstances($input->getOption('catalog'));
$jobInstances = $this->fixtureJobLoader->getLoadedJobInstances();
foreach ($jobInstances as $jobInstance) {
$params = [
'code' => $jobInstance->getCode(),
'--no-debug' => true,
'--no-log' => true,
'-v' => true,
];
$this->eventDispatcher->dispatch(
InstallerEvents::PRE_LOAD_FIXTURE,
new InstallerEvent($this->commandExecutor, $jobInstance->getCode(), [
'catalog' => $catalog
])
);
if ($input->getOption('verbose')) {
$output->writeln(
sprintf(
'Please wait, the <comment>%s</comment> are processing...',
$jobInstance->getCode()
)
);
}
$this->commandExecutor->runCommand('akeneo:batch:job', $params);
$this->eventDispatcher->dispatch(
InstallerEvents::POST_LOAD_FIXTURE,
new InstallerEvent($this->commandExecutor, $jobInstance->getCode())
);
}
$output->writeln('');
$output->writeln('<info>Delete jobs for fixtures.</info>');
$this->fixtureJobLoader->deleteJobInstances();
return $this;
}
private function setLatestKnownMigration(InputInterface $input): void
{
$latestMigration = $this->getLatestMigration($input);
$this->commandExecutor->runCommand(
'doctrine:migrations:version',
['version' => $latestMigration, '--add' => true, '--all' => true, '-q' => true]
);
}
private function getLatestMigration(InputInterface $input): string
{
$params = ['bin/console', 'doctrine:migrations:latest'];
$params[] = '--no-debug';
if ($input->hasOption('env')) {
$params[] = '--env';
$params[] = $input->getOption('env');
}
if ($input->hasOption('verbose') && $input->getOption('verbose') === true) {
$params[] = '--verbose';
}
$latestMigrationProcess = new Process($params);
$latestMigrationProcess->run();
if ($latestMigrationProcess->getExitCode() !== 0) {
throw new \RuntimeException("Impossible to get the latest migration {$latestMigrationProcess->getErrorOutput()}");
}
return $latestMigrationProcess->getOutput();
}
/**
* Launches all commands needed after fixtures loading
*/
protected function launchCommands()
{
$this->commandExecutor->runCommand('pim:versioning:refresh');
return $this;
}
}