PHPackages                             k-kinzal/ztd-query-postgres - 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. k-kinzal/ztd-query-postgres

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

k-kinzal/ztd-query-postgres
===========================

PostgreSQL platform support for ZTD Query

v0.1.1(2mo ago)016↓100%1MITPHPPHP ^8.1

Since Mar 6Pushed 2mo agoCompare

[ Source](https://github.com/k-kinzal/ztd-query-postgres)[ Packagist](https://packagist.org/packages/k-kinzal/ztd-query-postgres)[ RSS](/packages/k-kinzal-ztd-query-postgres/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (11)Versions (3)Used By (1)

ZTD Query PostgreSQL
====================

[](#ztd-query-postgresql)

[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/7535257ca228724c93658bd52583d4e47a9bab02c356abf6e54c1d575f2151e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d626c75652e737667)](https://www.php.net/)

PostgreSQL platform support for [ZTD Query PHP](https://github.com/k-kinzal/ztd-query-core). Provides SQL parsing, classification, rewriting, and schema management for PostgreSQL.

Overview
--------

[](#overview)

This package implements the PostgreSQL-specific logic for ZTD (Zero Table Dependency) query transformation. It handles:

- **SQL Parsing** - Parse PostgreSQL statements using a built-in regex-based parser
- **Query Classification** - Classify queries as READ, WRITE\_SIMULATED, or DDL\_SIMULATED
- **CTE Rewriting** - Transform SELECT queries to use CTE-shadowed fixture data
- **Result Select Query** - Convert INSERT/UPDATE/DELETE into SELECT queries returning affected rows
- **Schema Management** - Reflect and track PostgreSQL table definitions via `information_schema` queries
- **Error Classification** - Identify PostgreSQL-specific error codes for unknown schema detection

This package is used internally by the [PDO adapter](https://github.com/k-kinzal/ztd-query-pdo-adapter), but can also be used directly for custom adapter implementations.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- [k-kinzal/ztd-query-php](https://github.com/k-kinzal/ztd-query-core) (core)

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

[](#installation)

```
composer require k-kinzal/ztd-query-postgres
```

Usage
-----

[](#usage)

### Creating a PostgreSQL Session

[](#creating-a-postgresql-session)

`PgSqlSessionFactory` is the main entry point. It creates a fully configured `Session` instance for PostgreSQL:

```
use ZtdQuery\Config\ZtdConfig;
use ZtdQuery\Platform\Postgres\PgSqlSessionFactory;

// $connection implements ZtdQuery\Connection\ConnectionInterface
$session = PgSqlSessionFactory::create($connection, ZtdConfig::default());
```

The factory automatically:

1. Reflects the database schema via `information_schema` queries
2. Sets up the SQL parser, query guard, and all transformers
3. Configures the shadow store for virtual write tracking

### Query Classification

[](#query-classification)

`PgSqlQueryGuard` classifies SQL statements into query kinds:

```
use ZtdQuery\Platform\Postgres\PgSqlQueryGuard;
use ZtdQuery\Platform\Postgres\PgSqlParser;
use ZtdQuery\Rewrite\QueryKind;

$parser = new PgSqlParser();
$guard = new PgSqlQueryGuard($parser);

$guard->classify('SELECT * FROM users');
// => QueryKind::READ

$guard->classify('INSERT INTO users (name) VALUES (\'Alice\')');
// => QueryKind::WRITE_SIMULATED

$guard->classify('CREATE TABLE logs (id INT)');
// => QueryKind::DDL_SIMULATED

$guard->classify('BEGIN');
// => null (unsupported)
```

### SQL Rewriting

[](#sql-rewriting)

`PgSqlRewriter` transforms SQL statements for ZTD execution:

```
use ZtdQuery\Platform\Postgres\PgSqlRewriter;

// Rewrite a single statement
$plan = $rewriter->rewrite('SELECT email FROM users WHERE id = 1');
// $plan->sql() returns the CTE-shadowed query
// $plan->kind() returns the QueryKind

// Rewrite multiple statements (e.g., multi-query)
$plans = $rewriter->rewriteMultiple('SELECT 1; SELECT 2');
```

### Error Classification

[](#error-classification)

`PgSqlErrorClassifier` identifies PostgreSQL error codes related to unknown schemas:

```
use ZtdQuery\Platform\Postgres\PgSqlErrorClassifier;

$classifier = new PgSqlErrorClassifier();

$classifier->isUnknownSchemaError('42P01'); // true (Undefined table)
$classifier->isUnknownSchemaError('42703'); // true (Undefined column)
$classifier->isUnknownSchemaError('42601'); // false (Syntax error)
```

Architecture
------------

[](#architecture)

```
PgSqlSessionFactory
    |
    +-- PgSqlParser (regex-based SQL parsing)
    +-- PgSqlQueryGuard (query classification)
    +-- PgSqlSchemaReflector (database schema reflection via information_schema)
    +-- PgSqlSchemaParser (CREATE TABLE parsing)
    +-- PgSqlRewriter (query rewriting orchestrator)
    |       +-- PgSqlTransformer
    |       |       +-- SelectTransformer (CTE injection)
    |       |       +-- InsertTransformer (INSERT -> SELECT)
    |       |       +-- UpdateTransformer (UPDATE -> SELECT)
    |       |       +-- DeleteTransformer (DELETE -> SELECT)
    |       +-- PgSqlMutationResolver (virtual DDL tracking)
    +-- PgSqlErrorClassifier (error code classification)

```

SQL Support
-----------

[](#sql-support)

### Fully Supported

[](#fully-supported)

- **SELECT**: All clauses including JOIN, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET, FETCH FIRST, UNION, INTERSECT, EXCEPT, subqueries, CTEs, window functions, DISTINCT ON, FOR UPDATE/SHARE
- **INSERT**: VALUES, SELECT, ON CONFLICT (upsert)
- **UPDATE**: Single-table with WHERE
- **DELETE**: Single-table with WHERE
- **TRUNCATE**
- **DDL**: CREATE TABLE, ALTER TABLE, DROP TABLE (virtual schema)
- **WITH**: CTE and recursive CTE

### Unsupported

[](#unsupported)

- MERGE
- Stored procedures, triggers, functions, views
- Database/schema operations
- User/permission management
- Server operations (VACUUM, ANALYZE, REINDEX, etc.)

Development
-----------

[](#development)

```
# Run tests
composer test

# Run unit tests
composer test:unit

# Run linter (PHP-CS-Fixer + PHPStan level max)
composer lint

# Run fuzz tests
composer fuzz:robustness
composer fuzz:robustness:classify
composer fuzz:robustness:rewrite

# Fix code style
composer format
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance87

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

 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 ~0 days

Total

2

Last Release

65d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4458a22db62c885006248e08715301bcb73e78c1057e2bbf686af001729165d5?d=identicon)[kinzal](/maintainers/kinzal)

---

Top Contributors

[![k-kinzal](https://avatars.githubusercontent.com/u/1281825?v=4)](https://github.com/k-kinzal "k-kinzal (5 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/k-kinzal-ztd-query-postgres/health.svg)

```
[![Health](https://phpackages.com/badges/k-kinzal-ztd-query-postgres/health.svg)](https://phpackages.com/packages/k-kinzal-ztd-query-postgres)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M545](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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