SqliteSchemaState.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Illuminate\Database\Schema;
  3. use Illuminate\Database\Connection;
  4. class SqliteSchemaState extends SchemaState
  5. {
  6. /**
  7. * Dump the database's schema into a file.
  8. *
  9. * @param \Illuminate\Database\Connection $connection
  10. * @param string $path
  11. * @return void
  12. */
  13. public function dump(Connection $connection, $path)
  14. {
  15. with($process = $this->makeProcess(
  16. $this->baseCommand().' .schema'
  17. ))->setTimeout(null)->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [
  18. //
  19. ]));
  20. $migrations = collect(preg_split("/\r\n|\n|\r/", $process->getOutput()))->filter(function ($line) {
  21. return stripos($line, 'sqlite_sequence') === false &&
  22. strlen($line) > 0;
  23. })->all();
  24. $this->files->put($path, implode(PHP_EOL, $migrations).PHP_EOL);
  25. if ($this->hasMigrationTable()) {
  26. $this->appendMigrationData($path);
  27. }
  28. }
  29. /**
  30. * Append the migration data to the schema dump.
  31. *
  32. * @param string $path
  33. * @return void
  34. */
  35. protected function appendMigrationData(string $path)
  36. {
  37. with($process = $this->makeProcess(
  38. $this->baseCommand().' ".dump \''.$this->migrationTable.'\'"'
  39. ))->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [
  40. //
  41. ]));
  42. $migrations = collect(preg_split("/\r\n|\n|\r/", $process->getOutput()))->filter(function ($line) {
  43. return preg_match('/^\s*(--|INSERT\s)/iu', $line) === 1 &&
  44. strlen($line) > 0;
  45. })->all();
  46. $this->files->append($path, implode(PHP_EOL, $migrations).PHP_EOL);
  47. }
  48. /**
  49. * Load the given schema file into the database.
  50. *
  51. * @param string $path
  52. * @return void
  53. */
  54. public function load($path)
  55. {
  56. if ($this->connection->getDatabaseName() === ':memory:') {
  57. $this->connection->getPdo()->exec($this->files->get($path));
  58. return;
  59. }
  60. $process = $this->makeProcess($this->baseCommand().' < "${:LARAVEL_LOAD_PATH}"');
  61. $process->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [
  62. 'LARAVEL_LOAD_PATH' => $path,
  63. ]));
  64. }
  65. /**
  66. * Get the base sqlite command arguments as a string.
  67. *
  68. * @return string
  69. */
  70. protected function baseCommand()
  71. {
  72. return 'sqlite3 "${:LARAVEL_LOAD_DATABASE}"';
  73. }
  74. /**
  75. * Get the base variables for a dump / load command.
  76. *
  77. * @param array $config
  78. * @return array
  79. */
  80. protected function baseVariables(array $config)
  81. {
  82. return [
  83. 'LARAVEL_LOAD_DATABASE' => $config['database'],
  84. ];
  85. }
  86. }