postgres.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php namespace Laravel\Database\Connectors; use PDO;
  2. class Postgres extends Connector {
  3. /**
  4. * Establish a PDO database connection for a given database configuration.
  5. *
  6. * @param array $config
  7. * @return PDO
  8. */
  9. public function connect($config)
  10. {
  11. $connection = new PDO($this->dsn($config), $config['username'], $config['password'], $this->options($config));
  12. if (isset($config['charset']))
  13. {
  14. $connection->prepare("SET NAMES '{$config['charset']}'")->execute();
  15. }
  16. return $connection;
  17. }
  18. /**
  19. * Format the DSN connection string for a Postgres connection.
  20. *
  21. * @param array $config
  22. * @return string
  23. */
  24. protected function dsn($config)
  25. {
  26. // Format the initial Postgres PDO connection string. These options are required
  27. // for every Postgres connection that is established. The connection strings
  28. // have the following convention: "pgsql:host=hostname;dbname=database"
  29. $dsn = sprintf('%s:host=%s;dbname=%s', $config['driver'], $config['host'], $config['database']);
  30. // Check for any optional Postgres PDO options. These options are not required
  31. // to establish a PDO connection; however, may be needed in certain server
  32. // or hosting environments used by the developer.
  33. foreach (array('port', 'unix_socket') as $key => $value)
  34. {
  35. if (isset($config[$key])) $dsn .= ";{$key}={$value}";
  36. }
  37. return $dsn;
  38. }
  39. }