Quick start
name became price desc. The comment, the lowercase keywords, and the named CSV parameter are untouched, and the new desc follows the query’s lowercase style.
$printer->print($printer->original()) returns the original SQL byte for byte.
How the printer decides
AST nodes are immutable. An edit rebuilds only the path from the root to the changed node, so every untouched subtree is still the same object as inoriginal(). SourcePrinter relies on that identity:
1
Original nodes keep their text
A node from
original() is written as its original text, comments inside it included, wherever it appears in the edited tree. Moved fields keep their spelling.2
Changed nodes keep their layout
A changed node is written against the original node in the same place. Its keywords, punctuation, and gaps are copied from the original; only the changed parts are written fresh. Changing
price>100 to price>200 gives price>200, not price > 200. A changed LEFT OUTER JOIN source keeps LEFT OUTER JOIN.3
Lists keep their separators
In SELECT fields, conditions, function arguments,
IN values, ORDER BY / GROUP BY items, CTEs, joins, and clauses:- The separator between two former neighbours stays verbatim.
- A removed item takes its separator along (
, field,AND condition, the line of a removed clause). - An inserted item copies the layout of the nearest existing separator, without its comments. A new condition in a multi-line
WHEREgoes on its own line with the same indentation. - A comment after an item on its line (
price, -- money) moves and disappears with that item. Comments on the lines before an item stay in front of it.
4
New clauses go to their canonical place
WITH, SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, INTO, UNION — relative to the clauses the query already has. Existing clauses keep their order.5
New keywords follow the query's case
New keywords, function names, and
TRUE / FALSE / NULL use the keyword case of the original query (the majority of its keywords, see keywordCase()).FqlPrinter. Text around the root statement, such as a leading comment or a trailing newline, is kept.
Building edited trees
Every node keeps its public constructor. Most nodes also havewith…() helpers that return a copy with one property replaced. Copies have no span, because they no longer match the source, but they share all other children with the original.
Setting a clause to
null (for example withWhere(null)) removes it. Nodes you create yourself use Position::synthetic(); their position is not used for printing.
Nodes parsed from another SQL string, such as a condition parsed from a snippet, are not part of
original(). They are printed fresh, not as the text of the snippet.Recipes
All examples assume this setup:Toggle a sort direction
ASC is written only when the original item spelled out a direction (name DESC becomes name ASC, name stays name).
Add a condition
AND / OR left to right without precedence. To add AND c to a OR b, wrap the original group. It is printed in parentheses:
Remove a condition or a clause
Change the source
raw text, the source is written from the FileQuery with every non-default parameter. Named parameters are used when the original source used them, or when a parameter has no position. Pass $raw (for example $fileQuery->toFql(true)) to choose the text yourself.
Hide a column
EXCLUDE applies to every field after it.
Group and count
Source spans
Every node produced by the parser carries its source range throughspan(): ?Span (interface FQL\Sql\Ast\HasSpan). FQL\Sql\Token\Span is a half-open byte range [start, end) of the SQL string:
Offsets are bytes, like
Position::$offset. Convert them for editors that count UTF-16 code units. Nodes built in code have no span. Custom parsers get the same information from TokenStream::spanFrom() and TokenStream::previous().Fresh printing
FQL\Sql\Printer\FqlPrinter writes any node as single-line FQL without a source:
- Identifiers are backticked when the tokenizer would not read them as one plain identifier (spaces, diacritics, keywords). Column paths are quoted segment by segment.
- Literals keep their
rawspelling when it still matches the value. Otherwise strings use double quotes (single quotes when the value contains"), numbers have no exponent, and booleans andNULLare keywords. - A column on the right side of a condition stays a column. Arithmetic uses operators (
price * 2).ORDER BYwrites onlyDESC. - File queries keep their raw text when it matches; otherwise they are written from their
FileQuery.
Sql\Provider::format() uses the same printing for expressions, so formatted queries also parse back unchanged. See Pretty-printing.
Writing file queries
FQL\Query\FileQuery writes every parameter that differs from the format default:
__toString() stays positional when every non-default parameter has a position (encoding, delimiter, useHeader for CSV; encoding for XML; format for LOG). It switches to named parameters otherwise (enclosure, bom, LOG pattern). Parameters the format does not know are not written. Format::getParamNames() and Format::getPositionalParamNames() list them per format.
Before 3.3.0, writing a FileQuery back dropped
enclosure, bom, and the LOG pattern. As a result, FROM log(./access.log, pattern: "…") ignored the custom pattern and parsed every line with the default nginx_combined profile. Both are fixed in 3.3.0.FQL\Exception\FileQueryException with a message that names the part:
- A parameter value containing
". - A file path containing both
"and'. - A path in file with characters outside letters, digits, and
_ - . *(for example@idor spaces). - A format without a file, or a format name that is not 2–8 letters.
Errors
FQL\Sql\Printer\UnprintableNodeException extends FQL\Exception\InvalidArgumentException and exposes the offending node in $node. It is thrown for trees FQL cannot express, for example:
- An identifier or alias containing a backtick, or a string containing both
'and". - Arithmetic that needs parentheses (
(a + b) * c,a - (b - c)) or a signed number right after*. - Arithmetic inside
IN ( … ),BETWEEN, orCAST. - An included SELECT field after an excluded one.
- An empty
GROUP BY/ORDER BY, aCASEwithoutWHEN, orCASTtoTRUE/FALSE. - A condition used as a value, or a function named like a keyword.
Guarantees and limitations
print(original())returns the original SQL byte for byte, for any valid input.print($edited)parses back to a tree equal to$edited, up to spellings the AST does not record: positions and spans, literal and file queryrawtext, backticks around column path segments, and the logical operator of the first condition of a group.- A changed
LIMITis written asLIMIT n OFFSET m(LIMIT 5, 10becomesLIMIT 5 OFFSET 10). - A repeated clause (two
WHEREs, where only the last one applies) keeps the overridden copy when the clause is changed and drops both when it is removed. - An item moved to another position keeps its text and trailing comments; comments on the lines before it may be dropped.
- Unions added with
withUnions()are written one after another (A UNION B UNION C), which the parser reads as nested (A UNION (B UNION C)). - A column named like a keyword (
desc) is backticked when its node is printed fresh.