PHPackages                             sad\_spirit/pg\_wrapper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. sad\_spirit/pg\_wrapper

ActiveLibrary[Database &amp; ORM](/categories/database)

sad\_spirit/pg\_wrapper
=======================

Converter of complex PostgreSQL types and an OO wrapper for PHP's pgsql extension

v3.3.1(6mo ago)2211.2k↓37.9%22BSD-2-ClausePHPPHP ^8.2CI passing

Since Sep 27Pushed 6mo ago2 watchersCompare

[ Source](https://github.com/sad-spirit/pg-wrapper)[ Packagist](https://packagist.org/packages/sad_spirit/pg_wrapper)[ RSS](/packages/sad-spirit-pg-wrapper/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (29)Used By (2)

sad\_spirit/pg\_wrapper
=======================

[](#sad_spiritpg_wrapper)

[![Build Status](https://github.com/sad-spirit/pg-wrapper/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/sad-spirit/pg-wrapper/actions/workflows/ci.yml)[![Static Analysis](https://github.com/sad-spirit/pg-wrapper/actions/workflows/static-analysis.yml/badge.svg?branch=master)](https://github.com/sad-spirit/pg-wrapper/actions/workflows/static-analysis.yml)

This package has two parts and purposes

- Converter of [PostgreSQL data types](https://www.postgresql.org/docs/current/datatype.html) to their PHP equivalents and back and
- An object-oriented wrapper around PHP's native [pgsql extension](https://php.net/manual/en/book.pgsql.php).

While the converter part can be used separately e.g. with [PDO](https://www.php.net/manual/en/book.pdo.php), features like transparent conversion of query results work only with the wrapper.

Why type conversion?
--------------------

[](#why-type-conversion)

PostgreSQL supports a large (and extensible) set of complex database types: arrays, ranges, geometric and date/time types, composite (row) types, JSON...

```
create table test (
    strings  text[],
    coords   point,
    occupied daterange,
    age      interval,
    document json
);

insert into test values (
    array['Mary had', 'a little lamb'], point(55.75, 37.61),
    daterange('2014-01-13', '2014-09-19'), age('2014-09-19', '2014-01-13'),
    '{"title":"pg_wrapper","text":"pg_wrapper is cool"}'
);
```

Unfortunately neither of PHP extensions for talking to PostgreSQL (pgsql and PDO\_pgsql) can map these complex types to their PHP equivalents. They return string representations instead: both

```
var_dump(pg_fetch_assoc(pg_query($conn, 'select * from test')));
```

and

```
var_dump($pdo->query('select * from test')->fetch(\PDO::FETCH_ASSOC));
```

yield

```
array(5) {
  ["strings"]=>
  string(28) "{"Mary had","a little lamb"}"
  ["coords"]=>
  string(13) "(55.75,37.61)"
  ["occupied"]=>
  string(23) "[2014-01-13,2014-09-19)"
  ["age"]=>
  string(13) "8 mons 6 days"
  ["document"]=>
  string(50) "{"title":"pg_wrapper","text":"pg_wrapper is cool"}"
}

```

And that is where this library kicks in:

```
$result = $connection->execute('select * from test');
var_dump($result[0]);
```

yields

```
array(5) {
  ["strings"]=>
  array(2) {
    [0]=>
    string(8) "Mary had"
    [1]=>
    string(13) "a little lamb"
  }
  ["coords"]=>
  object(sad_spirit\pg_wrapper\types\Point)#28 (2) {
    ["x"]=>
    float(55.75)
    ["y"]=>
    float(37.61)
  }
  ["occupied"]=>
  object(sad_spirit\pg_wrapper\types\DateTimeRange)#29 (5) {
    ["lower"]=>
    object(DateTimeImmutable)#30 (3) {
      ["date"]=>
      string(26) "2014-01-13 00:00:00.000000"
      ...
    }
    ["upper"]=>
    object(DateTimeImmutable)#31 (3) {
      ["date"]=>
      string(26) "2014-09-19 00:00:00.000000"
      ...
    }
  }
  ["age"]=>
  object(DateInterval)#32 (10) {
    ...
    ["m"]=>
    int(8)
    ["d"]=>
    int(6)
    ...
  }
  ["document"]=>
  array(2) {
    ["title"]=>
    string(10) "pg_wrapper"
    ["text"]=>
    string(18) "pg_wrapper is cool"
  }
}

```

Note that no configuration is needed here: proper types are deduced from metadata returned with the result.

Why another wrapper when we have PDO, Doctrine DBAL, etc?
---------------------------------------------------------

[](#why-another-wrapper-when-we-have-pdo-doctrine-dbal-etc)

The goal of an abstraction layer is to target the Lowest Common Denominator, and thus it intentionally hides some low-level APIs that we can use with the native extension and / or adds another level of complexity.

- PDO does not expose [`pg_query_params()`](http://php.net/manual/en/function.pg-query-params.php), so you have to `prepare()` / `execute()` each query even if you `execute()` it only once. Doctrine DBAL has `Connection::executeQuery()`but it uses `prepare()` / `execute()` under the hood.
- Postgres only supports `$1` positional parameters natively, while PDO has positional `?` and named `:foo` parameters. PDO rewrites the query to convert the latter to the former, shortcomings in that rewrite logic prevented using [Postgres operators containing `?`](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) with PDO [until PHP 7.4](https://wiki.php.net/rfc/pdo_escape_placeholders) and led to problems when using dollar quoting for strings [until PHP 8.4](https://www.php.net/manual/en/migration84.new-features.php#migration84.new-features.pdo-pgsql).
- PDO has an *extremely inefficient* way to work with result metadata in Postgres. Its [`PDOStatement::getColumnMeta()`](https://www.php.net/manual/en/pdostatement.getcolumnmeta.php)executes one to two database queries for each call.
- The default way [Doctrine handles date and time types in PostgreSQL](https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/known-vendor-issues.html#datetime-datetimetz-and-time-types)is prominently mentioned in [Don't Do This](https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_timestamp.280.29_or_timestamptz.280.29) list on PostgreSQL's official wiki.

### Parameter as array: native vs. abstraction

[](#parameter-as-array-native-vs-abstraction)

A very common problem for database abstraction is providing a list of parameters to a query with an `IN` clause

```
SELECT * FROM stuff WHERE id IN (?)
```

where `?` actually represents a variable number of parameters.

On the one hand, if you don't need the abstraction, then Postgres has native array types, and this can be easily achieved with the following query

```
-- in case of using PDO just replace $1 with a PDO-compatible placeholder
SELECT * FROM stuff WHERE id = ANY($1::INTEGER[])
```

passing an array literal as its parameter value

```
use sad_spirit\pg_wrapper\converters\DefaultTypeConverterFactory;

$arrayLiteral = (new DefaultTypeConverterFactory())
    ->getConverterForTypeSpecification('INTEGER[]')
    ->output([1, 2, 3]);
```

Obviously, the above query can be prepared as usual and executed with another array literal.

On the other hand, Doctrine DBAL [has its own solution for parameter lists](https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#list-of-parameters-conversion)which once again depends on rewriting SQL and does not work with `prepare()` / `execute()`. It also has ["support" for array types](https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#array-types), but that just (un)serializes PHP arrays rather than converts them from/to native DB representation. Serialized PHP arrays will obviously not work with the above query.

Installation
------------

[](#installation)

Require the package with composer:

```
composer require "sad_spirit/pg_wrapper:^3"

```

pg\_wrapper requires at least PHP 8.2. Native [pgsql extension](https://php.net/manual/en/book.pgsql.php)should be enabled to use classes that access the DB (the extension is not a hard requirement).

Minimum supported PostgreSQL version is 12

It is highly recommended to use [PSR-6 compatible](https://www.php-fig.org/psr/psr-6/) metadata cache in production to prevent possible metadata lookups from database on each page request.

Documentation
-------------

[](#documentation)

For in-depth description of package features, visit [pg\_wrapper manual](https://pg-wrapper.readthedocs.io/).

###  Health Score

55

—

FairBetter than 98% of packages

Maintenance68

Regular maintenance activity

Popularity35

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity86

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~156 days

Recently: every ~64 days

Total

27

Last Release

191d ago

Major Versions

v0.2.2 → v1.0.0-beta2020-07-17

v1.0.0 → v2.0.0-beta2021-11-18

v2.5.0 → v3.0.0-beta2024-12-21

PHP version history (3 changes)v0.1.0PHP &gt;=5.3.0

v1.0.0-betaPHP &gt;=7.2.0

v3.0.0-betaPHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b43550745afa89d33e4b93f8535fc31c93ac0a712d264c13cb8f8c62d9198c1?d=identicon)[sad-spirit](/maintainers/sad-spirit)

---

Top Contributors

[![sad-spirit](https://avatars.githubusercontent.com/u/4820288?v=4)](https://github.com/sad-spirit "sad-spirit (348 commits)")

---

Tags

arraycomplex-typescompositedatetimegeometrichstoreintervaljsonpdopgsqlphppostgrespostgresqlrangearraydatabasepostgresqlpostgresdatetimeconversioncompositerangegeometric

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sad-spirit-pg-wrapper/health.svg)

```
[![Health](https://phpackages.com/badges/sad-spirit-pg-wrapper/health.svg)](https://phpackages.com/packages/sad-spirit-pg-wrapper)
```

###  Alternatives

[scienta/doctrine-json-functions

A set of extensions to Doctrine that add support for json query functions.

58523.9M36](/packages/scienta-doctrine-json-functions)[martin-georgiev/postgresql-for-doctrine

Extends Doctrine with native PostgreSQL support for arrays, JSONB, ranges, PostGIS geometries, text search, ltree, uuid, and 100+ PostgreSQL-specific functions.

4485.3M4](/packages/martin-georgiev-postgresql-for-doctrine)[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4572.9M34](/packages/aura-sqlquery)[tigrov/yii2-pgsql

Improved PostgreSQL schemas for Yii2

3467.0k](/packages/tigrov-yii2-pgsql)[atlas/query

Object-oriented query builders and performers for MySQL, Postgres, SQLite, and SQLServer.

41249.0k7](/packages/atlas-query)[aura/sqlschema

Provides facilities to read table names and table columns from a database using PDO.

41234.1k4](/packages/aura-sqlschema)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
