Skip to content
Alexey Borzov edited this page Nov 29, 2021 · 6 revisions

sad_spirit\pg_builder

This is a query builder for Postgres backed by a partial PHP reimplementation of PostgreSQL's own query parser. All syntax available for SELECT (and VALUES), INSERT, UPDATE, and DELETE queries in Postgres 14 is supported with minor omissions. Highlights:

  • Query is represented by an Abstract Syntax Tree consisting of Nodes. This is quite similar to what Postgres does internally.
  • When building a query, it is possible to start with manually written SQL and work from there.
  • Query parts (e.g. new columns for a SELECT or parts of a WHERE clause) can usually be added to the AST either as Nodes or as strings. Strings are processed by Parser, so query being built is automatically checked for correct syntax.
  • Nodes can be removed and replaced in AST (e.g. calling join() method of a node in FROM clause replaces it with a JoinExpression node having the original node as its left argument).
  • AST can be analyzed and transformed, the package takes advantage of this to allow named parameters like :foo instead of standard PostgreSQL's positional parameters $1 and to infer parameters' types from SQL typecasts.

The package can be used on its own but using it together with sad_spirit\pg_wrapper is highly recommended: that package provides transparent conversion from PHP types to PostgreSQL ones and back. StatementFactory, NativeStatement, and ParserAwareTypeConverterFactory classes are responsible for integration with pg_wrapper.

It is also possible to generate queries suitable for PDO, though converting types in that case will be less transparent.

User guide

Internals