Skip to content

Connection

Alexey Borzov edited this page Sep 18, 2020 · 4 revisions

Connection class

This is the main class, wrapping around pgsql connection resource and providing methods to run queries on it.

Constructor __construct(string $connectionString, bool $lazy = true) accepts a string suitable for pg_connect(). The second parameter $lazy controls whether to open the connection immediately ($lazy = false) or postpone connecting until needed ($lazy = true, the default).

Connection methods

  • connect(): $this - Explicitly connects to the database. The method will be called implicitly if the connection is needed. Throws ConnectionException if connecting fails.
  • disconnect(): $this - Disconnects from the database.
  • isConnected(): bool - Checks whether the connection was made.
  • getResource(): resource - Returns database connection resource. Will call connect() if not connected yet.
  • getConnectionId(): string - Returns a unique identifier for connection. The identifier is based on connection string and is used by DefaultTypeConverterFactory as cache key prefix for connection-related data. May be used for cache invalidation as well.

Type conversion methods

  • getTypeConverterFactory(): TypeConverterFactory - Returns the factory object for converters to and from PostreSQL representation. If one was not set explicitly, creates and sets an instance of DefaultTypeConverterFactory.
  • setTypeConverterFactory(TypeConverterFactory $factory): $this - Sets the factory object for converters to and from PostgreSQL types.
  • getTypeConverter(mixed $type): TypeConverter - Returns type converter for the given database type. This is a shorthand for $this->getTypeConverterFactory()->getConverterForTypeSpecification($type) and accepts the same parameters as the latter.
  • quote(mixed $value, mixed $type = null): string - Quotes a value for inclusion in a query, taking connection encoding into account. This is only needed when building a query by hand, $sql .= 'WHERE foo = ' . $connection->quote($foo); That way of building queries is not recommended, use any of the methods that allow passing parameters separately from query.
  • quoteIdentifier(string $identifier): string - Quotes an identifier (e.g. table or column name) for inclusion in a query.

Query execution methods

An overview of query execution details the benefits/drawbacks of these methods. All of the methods throw a ServerException if execution fails or ConnectionException if connection is lost.

  • execute(string $sql, array $resultTypes = array()): ResultSet|int - Executes a given query. For queries that return rows this method returns a ResultSet object, for data modification queries it returns the number of affected rows. $resultTypes information is passed to ResultSet and overrides automatically determined types.
  • executeParams(string $sql, array $params, array $paramTypes = array(), array $resultTypes = array()): ResultSet|int - Executes a given query with the ability to pass parameters separately. The query should contain positional placeholders $1, $2, … that will be replaced by $params on execution. $paramTypes specify the types for query parameters, $resultTypes information will be passed to ResultSet.
  • prepare(string $query, array $paramTypes = array()): PreparedStatement - Prepares the given query for execution, returning a PreparedStatement object. As above, the query should contain positional placeholders, $paramTypes specify types for them.

Transaction methods

Using atomic() method described on a separate page is recommended.

  • atomic(callable $callback, bool $savepoint = false): mixed - Runs a given function atomically
  • beginTransaction(string $savepoint = null): $this - Begins a transaction. Throws a BadMethodCallException if called inside atomic().
  • commit(string $savepoint = null): $this - Commits a transaction. Throws a BadMethodCallException if called inside atomic().
  • rollback(string $savepoint = null): $this - Rolls back changes done during a transaction. Throws a BadMethodCallException if called inside atomic().
  • inTransaction(): bool - Checks whether a transaction is currently open.
  • createSavepoint(string $savepoint): $this - Creates a savepoint. Throws a RuntimeException if trying to create a savepoint outside the transaction block.
  • releaseSavepoint(string $savepoint): $this - releases a savepoint. Throws a RuntimeException if trying to release a savepoint outside the transaction block.
  • rollbackToSavepoint(string $savepoint): $this - Rolls back changes done since a specific savepoint. Throws a RuntimeException if trying to roll back to a savepoint outside the transaction block.

The following methods are related to atomic():

  • onCommit(callable $callback): $this - Registers a callback that will execute when the transaction is committed. Throws a BadMethodCallException if called outside atomic().
  • onRollback(callable $callback): $this - Registers a callback that will execute when the transaction is rolled back. Throws a BadMethodCallException if called outside atomic().
  • setNeedsRollback(bool $needsRollback): $this - Sets/resets the $needsRollback flag for the current transaction. If this flag is set, then the only possible outcome for the current transaction is rollback(), attempts to perform other queries will cause exceptions. atomic() uses this flag internally to signal to the outer call that the inner call failed. This method should only be used when doing some custom error handling in atomic() and will raise a BadMethodCallException if used outside.
  • needsRollback(): bool - Returns the $needsRollback flag
  • checkRollbackNotNeeded(): void - Throws an exception if $needsRollback flag is set

Cache related methods

  • setMetadataCache(CacheItemPoolInterface $cache): $this - Sets the DB metadata cache
  • getMetadataCache(): CacheItemPoolInterface - Returns the DB metadata cache

CacheItemPoolInterface is defined in PSR-6 so use any compatible implementation. Currently this cache is used by DefaultTypeConverterFactory to store type information loaded from database. It is higly recommended to use the cache in production to prevent database metadata lookups on each page request.