PostgresSchemaState.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Illuminate\Database\Schema;
  3. use Illuminate\Database\Connection;
  4. class PostgresSchemaState 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. $commands = collect([
  16. $this->baseDumpCommand().' --schema-only > '.$path,
  17. ]);
  18. if ($this->hasMigrationTable()) {
  19. $commands->push($this->baseDumpCommand().' -t '.$this->migrationTable.' --data-only >> '.$path);
  20. }
  21. $commands->map(function ($command, $path) {
  22. $this->makeProcess($command)->mustRun($this->output, array_merge($this->baseVariables($this->connection->getConfig()), [
  23. 'LARAVEL_LOAD_PATH' => $path,
  24. ]));
  25. });
  26. }
  27. /**
  28. * Load the given schema file into the database.
  29. *
  30. * @param string $path
  31. * @return void
  32. */
  33. public function load($path)
  34. {
  35. $command = 'pg_restore --no-owner --no-acl --clean --if-exists --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}" "${:LARAVEL_LOAD_PATH}"';
  36. if (str_ends_with($path, '.sql')) {
  37. $command = 'psql --file="${:LARAVEL_LOAD_PATH}" --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}"';
  38. }
  39. $process = $this->makeProcess($command);
  40. $process->mustRun(null, array_merge($this->baseVariables($this->connection->getConfig()), [
  41. 'LARAVEL_LOAD_PATH' => $path,
  42. ]));
  43. }
  44. /**
  45. * Get the base dump command arguments for PostgreSQL as a string.
  46. *
  47. * @return string
  48. */
  49. protected function baseDumpCommand()
  50. {
  51. return 'pg_dump --no-owner --no-acl --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}"';
  52. }
  53. /**
  54. * Get the base variables for a dump / load command.
  55. *
  56. * @param array $config
  57. * @return array
  58. */
  59. protected function baseVariables(array $config)
  60. {
  61. $config['host'] ??= '';
  62. return [
  63. 'LARAVEL_LOAD_HOST' => is_array($config['host']) ? $config['host'][0] : $config['host'],
  64. 'LARAVEL_LOAD_PORT' => $config['port'] ?? '',
  65. 'LARAVEL_LOAD_USER' => $config['username'],
  66. 'PGPASSWORD' => $config['password'],
  67. 'LARAVEL_LOAD_DATABASE' => $config['database'],
  68. ];
  69. }
  70. }