You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. <?php
  2. namespace Illuminate\Database\Migrations;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Str;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Console\OutputStyle;
  7. use Illuminate\Filesystem\Filesystem;
  8. use Illuminate\Database\ConnectionResolverInterface as Resolver;
  9. class Migrator
  10. {
  11. /**
  12. * The migration repository implementation.
  13. *
  14. * @var \Illuminate\Database\Migrations\MigrationRepositoryInterface
  15. */
  16. protected $repository;
  17. /**
  18. * The filesystem instance.
  19. *
  20. * @var \Illuminate\Filesystem\Filesystem
  21. */
  22. protected $files;
  23. /**
  24. * The connection resolver instance.
  25. *
  26. * @var \Illuminate\Database\ConnectionResolverInterface
  27. */
  28. protected $resolver;
  29. /**
  30. * The name of the default connection.
  31. *
  32. * @var string
  33. */
  34. protected $connection;
  35. /**
  36. * The paths to all of the migration files.
  37. *
  38. * @var array
  39. */
  40. protected $paths = [];
  41. /**
  42. * The output interface implementation.
  43. *
  44. * @var \Illuminate\Console\OutputStyle
  45. */
  46. protected $output;
  47. /**
  48. * Create a new migrator instance.
  49. *
  50. * @param \Illuminate\Database\Migrations\MigrationRepositoryInterface $repository
  51. * @param \Illuminate\Database\ConnectionResolverInterface $resolver
  52. * @param \Illuminate\Filesystem\Filesystem $files
  53. * @return void
  54. */
  55. public function __construct(MigrationRepositoryInterface $repository,
  56. Resolver $resolver,
  57. Filesystem $files)
  58. {
  59. $this->files = $files;
  60. $this->resolver = $resolver;
  61. $this->repository = $repository;
  62. }
  63. /**
  64. * Run the pending migrations at a given path.
  65. *
  66. * @param array|string $paths
  67. * @param array $options
  68. * @return array
  69. */
  70. public function run($paths = [], array $options = [])
  71. {
  72. $this->notes = [];
  73. // Once we grab all of the migration files for the path, we will compare them
  74. // against the migrations that have already been run for this package then
  75. // run each of the outstanding migrations against a database connection.
  76. $files = $this->getMigrationFiles($paths);
  77. $this->requireFiles($migrations = $this->pendingMigrations(
  78. $files, $this->repository->getRan()
  79. ));
  80. // Once we have all these migrations that are outstanding we are ready to run
  81. // we will go ahead and run them "up". This will execute each migration as
  82. // an operation against a database. Then we'll return this list of them.
  83. $this->runPending($migrations, $options);
  84. return $migrations;
  85. }
  86. /**
  87. * Get the migration files that have not yet run.
  88. *
  89. * @param array $files
  90. * @param array $ran
  91. * @return array
  92. */
  93. protected function pendingMigrations($files, $ran)
  94. {
  95. return Collection::make($files)
  96. ->reject(function ($file) use ($ran) {
  97. return in_array($this->getMigrationName($file), $ran);
  98. })->values()->all();
  99. }
  100. /**
  101. * Run an array of migrations.
  102. *
  103. * @param array $migrations
  104. * @param array $options
  105. * @return void
  106. */
  107. public function runPending(array $migrations, array $options = [])
  108. {
  109. // First we will just make sure that there are any migrations to run. If there
  110. // aren't, we will just make a note of it to the developer so they're aware
  111. // that all of the migrations have been run against this database system.
  112. if (count($migrations) === 0) {
  113. $this->note('<info>Nothing to migrate.</info>');
  114. return;
  115. }
  116. // Next, we will get the next batch number for the migrations so we can insert
  117. // correct batch number in the database migrations repository when we store
  118. // each migration's execution. We will also extract a few of the options.
  119. $batch = $this->repository->getNextBatchNumber();
  120. $pretend = $options['pretend'] ?? false;
  121. $step = $options['step'] ?? false;
  122. // Once we have the array of migrations, we will spin through them and run the
  123. // migrations "up" so the changes are made to the databases. We'll then log
  124. // that the migration was run so we don't repeat it next time we execute.
  125. foreach ($migrations as $file) {
  126. $this->runUp($file, $batch, $pretend);
  127. if ($step) {
  128. $batch++;
  129. }
  130. }
  131. }
  132. /**
  133. * Run "up" a migration instance.
  134. *
  135. * @param string $file
  136. * @param int $batch
  137. * @param bool $pretend
  138. * @return void
  139. */
  140. protected function runUp($file, $batch, $pretend)
  141. {
  142. // First we will resolve a "real" instance of the migration class from this
  143. // migration file name. Once we have the instances we can run the actual
  144. // command such as "up" or "down", or we can just simulate the action.
  145. $migration = $this->resolve(
  146. $name = $this->getMigrationName($file)
  147. );
  148. if ($pretend) {
  149. return $this->pretendToRun($migration, 'up');
  150. }
  151. $this->note("<comment>Migrating:</comment> {$name}");
  152. $this->runMigration($migration, 'up');
  153. // Once we have run a migrations class, we will log that it was run in this
  154. // repository so that we don't try to run it next time we do a migration
  155. // in the application. A migration repository keeps the migrate order.
  156. $this->repository->log($name, $batch);
  157. $this->note("<info>Migrated:</info> {$name}");
  158. }
  159. /**
  160. * Rollback the last migration operation.
  161. *
  162. * @param array|string $paths
  163. * @param array $options
  164. * @return array
  165. */
  166. public function rollback($paths = [], array $options = [])
  167. {
  168. $this->notes = [];
  169. // We want to pull in the last batch of migrations that ran on the previous
  170. // migration operation. We'll then reverse those migrations and run each
  171. // of them "down" to reverse the last migration "operation" which ran.
  172. $migrations = $this->getMigrationsForRollback($options);
  173. if (count($migrations) === 0) {
  174. $this->note('<info>Nothing to rollback.</info>');
  175. return [];
  176. }
  177. return $this->rollbackMigrations($migrations, $paths, $options);
  178. }
  179. /**
  180. * Get the migrations for a rollback operation.
  181. *
  182. * @param array $options
  183. * @return array
  184. */
  185. protected function getMigrationsForRollback(array $options)
  186. {
  187. if (($steps = $options['step'] ?? 0) > 0) {
  188. return $this->repository->getMigrations($steps);
  189. }
  190. return $this->repository->getLast();
  191. }
  192. /**
  193. * Rollback the given migrations.
  194. *
  195. * @param array $migrations
  196. * @param array|string $paths
  197. * @param array $options
  198. * @return array
  199. */
  200. protected function rollbackMigrations(array $migrations, $paths, array $options)
  201. {
  202. $rolledBack = [];
  203. $this->requireFiles($files = $this->getMigrationFiles($paths));
  204. // Next we will run through all of the migrations and call the "down" method
  205. // which will reverse each migration in order. This getLast method on the
  206. // repository already returns these migration's names in reverse order.
  207. foreach ($migrations as $migration) {
  208. $migration = (object) $migration;
  209. if (! $file = Arr::get($files, $migration->migration)) {
  210. $this->note("<fg=red>Migration not found:</> {$migration->migration}");
  211. continue;
  212. }
  213. $rolledBack[] = $file;
  214. $this->runDown(
  215. $file, $migration,
  216. $options['pretend'] ?? false
  217. );
  218. }
  219. return $rolledBack;
  220. }
  221. /**
  222. * Rolls all of the currently applied migrations back.
  223. *
  224. * @param array|string $paths
  225. * @param bool $pretend
  226. * @return array
  227. */
  228. public function reset($paths = [], $pretend = false)
  229. {
  230. $this->notes = [];
  231. // Next, we will reverse the migration list so we can run them back in the
  232. // correct order for resetting this database. This will allow us to get
  233. // the database back into its "empty" state ready for the migrations.
  234. $migrations = array_reverse($this->repository->getRan());
  235. if (count($migrations) === 0) {
  236. $this->note('<info>Nothing to rollback.</info>');
  237. return [];
  238. }
  239. return $this->resetMigrations($migrations, $paths, $pretend);
  240. }
  241. /**
  242. * Reset the given migrations.
  243. *
  244. * @param array $migrations
  245. * @param array $paths
  246. * @param bool $pretend
  247. * @return array
  248. */
  249. protected function resetMigrations(array $migrations, array $paths, $pretend = false)
  250. {
  251. // Since the getRan method that retrieves the migration name just gives us the
  252. // migration name, we will format the names into objects with the name as a
  253. // property on the objects so that we can pass it to the rollback method.
  254. $migrations = collect($migrations)->map(function ($m) {
  255. return (object) ['migration' => $m];
  256. })->all();
  257. return $this->rollbackMigrations(
  258. $migrations, $paths, compact('pretend')
  259. );
  260. }
  261. /**
  262. * Run "down" a migration instance.
  263. *
  264. * @param string $file
  265. * @param object $migration
  266. * @param bool $pretend
  267. * @return void
  268. */
  269. protected function runDown($file, $migration, $pretend)
  270. {
  271. // First we will get the file name of the migration so we can resolve out an
  272. // instance of the migration. Once we get an instance we can either run a
  273. // pretend execution of the migration or we can run the real migration.
  274. $instance = $this->resolve(
  275. $name = $this->getMigrationName($file)
  276. );
  277. $this->note("<comment>Rolling back:</comment> {$name}");
  278. if ($pretend) {
  279. return $this->pretendToRun($instance, 'down');
  280. }
  281. $this->runMigration($instance, 'down');
  282. // Once we have successfully run the migration "down" we will remove it from
  283. // the migration repository so it will be considered to have not been run
  284. // by the application then will be able to fire by any later operation.
  285. $this->repository->delete($migration);
  286. $this->note("<info>Rolled back:</info> {$name}");
  287. }
  288. /**
  289. * Run a migration inside a transaction if the database supports it.
  290. *
  291. * @param object $migration
  292. * @param string $method
  293. * @return void
  294. */
  295. protected function runMigration($migration, $method)
  296. {
  297. $connection = $this->resolveConnection(
  298. $migration->getConnection()
  299. );
  300. $callback = function () use ($migration, $method) {
  301. if (method_exists($migration, $method)) {
  302. $migration->{$method}();
  303. }
  304. };
  305. $this->getSchemaGrammar($connection)->supportsSchemaTransactions()
  306. && $migration->withinTransaction
  307. ? $connection->transaction($callback)
  308. : $callback();
  309. }
  310. /**
  311. * Pretend to run the migrations.
  312. *
  313. * @param object $migration
  314. * @param string $method
  315. * @return void
  316. */
  317. protected function pretendToRun($migration, $method)
  318. {
  319. foreach ($this->getQueries($migration, $method) as $query) {
  320. $name = get_class($migration);
  321. $this->note("<info>{$name}:</info> {$query['query']}");
  322. }
  323. }
  324. /**
  325. * Get all of the queries that would be run for a migration.
  326. *
  327. * @param object $migration
  328. * @param string $method
  329. * @return array
  330. */
  331. protected function getQueries($migration, $method)
  332. {
  333. // Now that we have the connections we can resolve it and pretend to run the
  334. // queries against the database returning the array of raw SQL statements
  335. // that would get fired against the database system for this migration.
  336. $db = $this->resolveConnection(
  337. $migration->getConnection()
  338. );
  339. return $db->pretend(function () use ($migration, $method) {
  340. if (method_exists($migration, $method)) {
  341. $migration->{$method}();
  342. }
  343. });
  344. }
  345. /**
  346. * Resolve a migration instance from a file.
  347. *
  348. * @param string $file
  349. * @return object
  350. */
  351. public function resolve($file)
  352. {
  353. $class = Str::studly(implode('_', array_slice(explode('_', $file), 4)));
  354. return new $class;
  355. }
  356. /**
  357. * Get all of the migration files in a given path.
  358. *
  359. * @param string|array $paths
  360. * @return array
  361. */
  362. public function getMigrationFiles($paths)
  363. {
  364. return Collection::make($paths)->flatMap(function ($path) {
  365. return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');
  366. })->filter()->sortBy(function ($file) {
  367. return $this->getMigrationName($file);
  368. })->values()->keyBy(function ($file) {
  369. return $this->getMigrationName($file);
  370. })->all();
  371. }
  372. /**
  373. * Require in all the migration files in a given path.
  374. *
  375. * @param array $files
  376. * @return void
  377. */
  378. public function requireFiles(array $files)
  379. {
  380. foreach ($files as $file) {
  381. $this->files->requireOnce($file);
  382. }
  383. }
  384. /**
  385. * Get the name of the migration.
  386. *
  387. * @param string $path
  388. * @return string
  389. */
  390. public function getMigrationName($path)
  391. {
  392. return str_replace('.php', '', basename($path));
  393. }
  394. /**
  395. * Register a custom migration path.
  396. *
  397. * @param string $path
  398. * @return void
  399. */
  400. public function path($path)
  401. {
  402. $this->paths = array_unique(array_merge($this->paths, [$path]));
  403. }
  404. /**
  405. * Get all of the custom migration paths.
  406. *
  407. * @return array
  408. */
  409. public function paths()
  410. {
  411. return $this->paths;
  412. }
  413. /**
  414. * Get the default connection name.
  415. *
  416. * @return string
  417. */
  418. public function getConnection()
  419. {
  420. return $this->connection;
  421. }
  422. /**
  423. * Set the default connection name.
  424. *
  425. * @param string $name
  426. * @return void
  427. */
  428. public function setConnection($name)
  429. {
  430. if (! is_null($name)) {
  431. $this->resolver->setDefaultConnection($name);
  432. }
  433. $this->repository->setSource($name);
  434. $this->connection = $name;
  435. }
  436. /**
  437. * Resolve the database connection instance.
  438. *
  439. * @param string $connection
  440. * @return \Illuminate\Database\Connection
  441. */
  442. public function resolveConnection($connection)
  443. {
  444. return $this->resolver->connection($connection ?: $this->connection);
  445. }
  446. /**
  447. * Get the schema grammar out of a migration connection.
  448. *
  449. * @param \Illuminate\Database\Connection $connection
  450. * @return \Illuminate\Database\Schema\Grammars\Grammar
  451. */
  452. protected function getSchemaGrammar($connection)
  453. {
  454. if (is_null($grammar = $connection->getSchemaGrammar())) {
  455. $connection->useDefaultSchemaGrammar();
  456. $grammar = $connection->getSchemaGrammar();
  457. }
  458. return $grammar;
  459. }
  460. /**
  461. * Get the migration repository instance.
  462. *
  463. * @return \Illuminate\Database\Migrations\MigrationRepositoryInterface
  464. */
  465. public function getRepository()
  466. {
  467. return $this->repository;
  468. }
  469. /**
  470. * Determine if the migration repository exists.
  471. *
  472. * @return bool
  473. */
  474. public function repositoryExists()
  475. {
  476. return $this->repository->repositoryExists();
  477. }
  478. /**
  479. * Get the file system instance.
  480. *
  481. * @return \Illuminate\Filesystem\Filesystem
  482. */
  483. public function getFilesystem()
  484. {
  485. return $this->files;
  486. }
  487. /**
  488. * Set the output implementation that should be used by the console.
  489. *
  490. * @param \Illuminate\Console\OutputStyle $output
  491. * @return $this
  492. */
  493. public function setOutput(OutputStyle $output)
  494. {
  495. $this->output = $output;
  496. return $this;
  497. }
  498. /**
  499. * Write a note to the conosle's output.
  500. *
  501. * @param string $message
  502. * @return void
  503. */
  504. protected function note($message)
  505. {
  506. if ($this->output) {
  507. $this->output->writeln($message);
  508. }
  509. }
  510. }