Classes representing SQL statements
Subclasses of \sad_spirit\pg_builder\Statement represent the complete SQL statements.
Their instances are usually created by StatementFactory methods.
All relative class and interface names below assume \sad_spirit\pg_builder prefix, which is omitted for readability.
Class hierarchy
NodeCommon interface for all nodes in Abstract Syntax Tree.
nodes\GenericNodeCommon base class for all implementations of
Nodewithin package.StatementAbstract base class for statements. Loosely corresponds to
PreparableStmtproduction in PostgreSQL’s grammar.DeleteRepresents
DELETEstatement.InsertRepresents
INSERTstatement.MergeRepresents
Mergestatement.UpdateRepresents
UPDATEstatement.SelectCommonAbstract base class for
SELECT-type statements.SelectRepresents a simple
SELECTstatement.SetOpSelectRepresents a set operator (
UNION,INTERSECT,EXCEPT) applied to twoSELECTstatements.ValuesRepresents
VALUESstatement. Note that this can be an independent statement in PostgreSQL, not only a part ofINSERT.
Clauses of SQL statements, e.g. WHERE or FROM, are exposed as properties of the relevant objects.
Those properties can be writable if a corresponding setProperty() method is defined for $property and
read-only otherwise.
Warning
The setter methods for properties should be considered an implementation detail, which may change in the future. Assign new values directly to the properties, e.g.
$select->distinct = true;
rather than via setters
$select->setDistinct(true);
If the clause is a list of items, like FROM, then the corresponding property is usually read-only and
is an implementation of NodeList and consequently \ArrayAccess.
The items in the list may be modified as array offsets:
$select->from[0] = 'foo as bar';
unset($select->from[1]);
Statement methods and properties
$with: nodes\WithClauseA writable property that represents a
WITHclause containing Common Table Expressions attached to a primary statement.setParser(Parser $parser)Sets the parser instance to use. If you add a
Parserto theStatementthen you’ll be able to add parts of query as strings that will be parsed automatically.getParser(): ?ParserReturns the parser instance, if available.
It is always possible to add query parts by creating the relevant Node implementations, but this is very tedious:
$select->list[] = new nodes\TargetElement(new nodes\ColumnReference('foo', 'bar'), new nodes\Identifier('alias'));
vs
$select->list[] = 'foo.bar as alias';
the result of the above is the same, as the string will be parsed and an instance of TargetElement added.
Tip
Statement instances created by StatementFactory will have a Parser set.
nodes\WithClause
This is an implementation of NodeList so individual CTEs (instances of nodes\CommonTableExpression)
are accessible as array offsets. It also has a writable boolean $recursive property.
$select->with[] = 'foobar as (select foo.*, bar.* from foo natural join bar)';
echo "WITH clause is " . ($select->with->recursive ? 'recursive' : 'not recursive');
echo "Statement of first CTE is " . get_class($select->with[0]->statement);
Delete properties
$relation: nodes\range\UpdateOrDeleteTargetName of the table to delete from. Can be set only via constructor.
$using: nodes\lists\FromListList of tables whose columns may appear in
WHEREclause.FromListimplementsNodeListand behaves like an array containing only instances ofnodes\range\FromElement.$where: nodes\WhereOrHavingClauseWHEREclause ofDELETE.$whereproperty is read-only, but has helper methods for building theWHEREclause.$returning: nodes\ReturningClauseRETURNINGclause ofDELETE. If present,DELETEwill return values based on each deleted row.ReturningClauseis essentially an array containing only instances ofnodes\TargetElementwith additional properties representing aliases forOLDandNEWin Postgres 18+.
Insert properties
$relation: nodes\range\InsertTargetName of the table to insert into. Can be set only via constructor.
$cols: nodes\lists\SetTargetListList of table’s columns to use.
SetTargetListis essentially an array containing only instances ofnodes\SetTargetElement.$values: SelectCommonActual values to insert. This property is writable.
$overriding: enums\InsertOverriding|nullOVERRIDINGclause. The property is writable.$onConflict: nodes\OnConflictClauseON CONFLICTclause used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. The property is writable.$returning: nodes\ReturningClauseRETURNINGclause ofINSERT, if presentINSERTwill return values based on each inserted (or maybe updated in case ofON CONFLICT ... DO UPDATE) row.ReturningClauseis essentially an array containing only instances ofnodes\TargetElementwith additional properties representing aliases forOLDandNEWin Postgres 18+.
Merge properties
$relation: nodes\range\UpdateOrDeleteTargetName of the
MERGEtarget table. This property is writable.$using: nodes\range\FromElementData source for
MERGE. This property is writable.$on: nodes\ScalarExpressionCondition for joining data source to target table. This property is writable.
$when: nodes\merge\MergeWhenListList of
WHENconditions forMERGE.MergeWhenListbehaves like an array containing only instances ofnodes\merge\MergeWhenClause.$returning: nodes\ReturningClauseRETURNINGclause ofMERGE.ReturningClausebehaves like an array containing only instances ofnodes\TargetElement.
Update properties
$relation: nodes\range\UpdateOrDeleteTargetName of the table to update. Can be set only via constructor.
$set: nodes\lists\SetClauseListSETclause ofUPDATEstatement.SetClauseListis essentially an array containing only instances of eithernodes\SingleSetClauseornodes\MultipleSetClause.$from: nodes\lists\FromListList of tables whose columns may appear in
WHEREcondition and the update expressions.FromListis essentially an array containing only instances ofnodes\range\FromElement.$where: WhereOrHavingClauseWHEREclause ofUPDATE.$returning: nodes\ReturningClauseRETURNINGclause ofUPDATE, if presentUPDATEwill return values based on each updated row.ReturningClauseis essentially an array containing only instances ofnodes\TargetElement.
SelectCommon methods and properties
$order: nodes\lists\OrderByListORDER BYclause ofSELECTstatement.OrderByListis essentially an array containing only instances ofnodes\OrderByElement.$limit: nodes\ScalarExpressionLIMITclause ofSELECTstatement. This property is writable.$limitWithTies: boolIf
true, triggers generating SQL standardFETCH FIRST ... ROWS WITH TIESclause. This property is writable.$offset: nodes\ScalarExpressionOFFSETclause ofSELECTstatement. This property is writable.$locking: nodes\lists\LockListLocking clause of
SELECTstatement, consisting of e.g.FOR UPDATE ...clauses.LockListis essentially an array containing only instances ofnodes\LockingElement.
Methods for set operators
SelectCommon also defines methods for applying set operators:
public function union(string|self $select, bool $distinct = true): SetOpSelectCombines this
SELECTstatement with another one usingUNION [ALL]operator.public function intersect(string|self $select, bool $distinct = true): SetOpSelectCombines this
SELECTstatement with another one usingINTERSECT [ALL]operator.public function except(string|self $select, bool $distinct = true): SetOpSelectCombines this
SELECTstatement with another one usingEXCEPT [ALL]operator
If these methods are called on a SELECT statement that is a part of
some larger statement then result will replace the original statement:
use sad_spirit\pg_builder\{
StatementFactory,
Select
};
$factory = new StatementFactory();
/** @var Select $select */
$select = $factory->createFromString(
'select foo.*, bar.* from (select * from foosource) as foo, bar where foo.id = bar.id'
);
$select->from[0]->query->union('select * from othersource');
echo $factory->createFromAST($select)->getSql();
will output
select foo.*, bar.*
from (
select *
from foosource
union
select *
from othersource
) as foo, bar
where foo.id = bar.id
Select properties
$list: nodes\lists\TargetListList of columns returned by
SELECT.TargetListbehaves like an array containing only instances ofnodes\TargetElement, its subclass is also used forRETURNINGclauses of data-modifying statements.$distinct: bool|nodes\lists\ExpressionListtruehere representsDISTINCTclause, list of expressions -DISTINCT ON (...)clause. This property is writable.ExpressionListbehaves like an array containing only implementations ofnodes\ScalarExpression.$from: nodes\lists\FromListList of tables to select from.
FromListbehaves like an array containing only instances ofnodes\range\FromElement.$where: nodes\WhereOrHavingClauseWHEREclause ofSELECT.$group: nodes\group\GroupByClauseGROUP BYclause ofSELECT.GroupByClausehas array offsets containing implementations of eithernodes\ScalarExpressionornodes\group\GroupByElementinterfaces, additionally it has a writable bool$distinctproperty.$having: nodes\WhereOrHavingClauseHAVINGclause ofSELECT, the same class is used here as for$whereproperty.$window: nodes\lists\WindowListWINDOWclause ofSELECT.WindowListbehaves like an array containing only instances ofnodes\WindowDefinition.
SetOpSelect properties
$left: SelectCommonFirst operand of set operation. This property is writable.
$right: SelectCommonSecond operand of set operation. This property is writable.
$operator: enums\SetOperatorOperator, can be set only via constructor.
Values properties
$rows: nodes\lists\RowListList of rows in
VALUES.RowListbehaves like an array containing only instances ofnodes\expressions\RowExpression.