> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fiquela.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Editing queries

> Change a parsed FQL query and print it back with SourcePrinter, keeping the user's whitespace, comments, quotes, and keyword case. Covers AST copy helpers, source spans, and FqlPrinter.

FiQueLa can change a parsed FQL query and write it back while keeping the user's own text. Whitespace, line breaks, comments, backticks, quotes, and keyword case stay exactly as written everywhere except in the parts that changed.

Use this when you build an editor or GUI on top of FQL: sort by a column header, add a filter, change the source, or hide a column in a query the user also writes by hand.

Added in **3.3.0**.

## Quick start

```php theme={null}
use FQL\Enum\Sort;
use FQL\Sql\Ast\Expression\ColumnReferenceNode;
use FQL\Sql\Ast\Node\OrderByClauseNode;
use FQL\Sql\Ast\Node\OrderByItemNode;
use FQL\Sql\Printer\SourcePrinter;
use FQL\Sql\Token\Position;

$sql = <<<FQL
select name, price -- the price
from csv(./products.csv, delimiter: ";")
where price > 100
order by name
FQL;

$printer = new SourcePrinter($sql);   // parses $sql
$ast = $printer->original();          // FQL\Sql\Ast\Node\SelectStatementNode

$p = Position::synthetic();
$edited = $ast->withOrderBy(new OrderByClauseNode(
    [new OrderByItemNode(new ColumnReferenceNode('price', $p), Sort::DESC, $p)],
    $p
));

echo $printer->print($edited);
// select name, price -- the price
// from csv(./products.csv, delimiter: ";")
// where price > 100
// order by price desc
```

Only `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 in `original()`. `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 `WHERE` goes 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()`).

Anything with no original counterpart is written fresh by [`FqlPrinter`](#fresh-printing). 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 have `with…()` helpers that return a copy with one property replaced. Copies have no [span](#source-spans), because they no longer match the source, but they share all other children with the original.

| Node | Helpers |
| - | - |
| `SelectStatementNode` | `withFrom()`, `withFields()`, `withDistinct()`, `withJoins()`, `withWhere()`, `withGroupBy()`, `withHaving()`, `withOrderBy()`, `withLimit()`, `withUnions()`, `withInto()`, `withExplain()`, `withCommonTables()` |
| `SelectFieldNode` | `withExpression()`, `withAlias()`, `withExcluded()` |
| `FromClauseNode` | `withSource()`, `withAlias()` |
| `JoinClauseNode` | `withType()`, `withSource()`, `withAlias()`, `withOn()` |
| `WhereClauseNode`, `HavingClauseNode` | `withConditions()` |
| `GroupByClauseNode` | `withFields()` |
| `OrderByClauseNode` | `withItems()` |
| `OrderByItemNode` | `withExpression()`, `withDirection()` |
| `LimitClauseNode` | `withLimit()`, `withOffset()` |
| `ConditionGroupNode` | `withEntries()`, `withAppended(LogicalOperator, condition)`, `withoutEntry(int)` |
| `ConditionExpressionNode` | `withLeft()`, `withOperator()`, `withRight()` |
| `FunctionCallNode` | `withArguments()` |
| `FileQueryNode` | `withFileQuery(FileQuery, string $raw = '')` |

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.

> [!NOTE]
>
> 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:

```php theme={null}
$printer = new SourcePrinter($sql);
$ast = $printer->original();
$p = Position::synthetic();
```

### Toggle a sort direction

```php theme={null}
$item = $ast->orderBy->items[0];
$printer->print($ast->withOrderBy($ast->orderBy->withItems([$item->withDirection(Sort::DESC)])));
// ORDER BY name  →  ORDER BY name DESC
```

`ASC` is written only when the original item spelled out a direction (`name DESC` becomes `name ASC`, `name` stays `name`).

### Add a condition

```php theme={null}
use FQL\Enum\LogicalOperator;
use FQL\Enum\Operator;
use FQL\Enum\Type;
use FQL\Sql\Ast\Expression\ConditionExpressionNode;
use FQL\Sql\Ast\Expression\ConditionGroupNode;
use FQL\Sql\Ast\Expression\LiteralNode;
use FQL\Sql\Ast\Node\WhereClauseNode;

$condition = new ConditionExpressionNode(
    new ColumnReferenceNode('stock', $p),
    Operator::GREATER_THAN,
    new LiteralNode(0, Type::INTEGER, '', $p),
    $p
);

$where = $ast->where === null
    ? new WhereClauseNode(new ConditionGroupNode([['logical' => LogicalOperator::AND, 'condition' => $condition]], $p), $p)
    : $ast->where->withConditions($ast->where->conditions->withAppended(LogicalOperator::AND, $condition));

$printer->print($ast->withWhere($where));
// where price > 100  →  where price > 100 and stock > 0
```

FQL evaluates `AND` / `OR` left to right without precedence. To add `AND c` to `a OR b`, wrap the original group. It is printed in parentheses:

```php theme={null}
$group = new ConditionGroupNode([
    ['logical' => LogicalOperator::AND, 'condition' => $ast->where->conditions],
    ['logical' => LogicalOperator::AND, 'condition' => $condition],
], $p);
// WHERE a = 1 OR b = 2  →  WHERE (a = 1 OR b = 2) AND stock > 0
```

### Remove a condition or a clause

```php theme={null}
// Remove the second condition
$printer->print($ast->withWhere($ast->where->withConditions($ast->where->conditions->withoutEntry(1))));

// Remove the whole WHERE clause
$printer->print($ast->withWhere(null));
```

### Change the source

```php theme={null}
$source = $ast->from->source; // FileQueryNode
$fileQuery = $source->fileQuery->withQuery('SHOP.ITEM')->withParam('enclosure', "'");

$printer->print($ast->withFrom($ast->from->withSource($source->withFileQuery($fileQuery))));
// FROM csv(./a.csv, delimiter: ";").SHOP  →  FROM csv(./a.csv, delimiter: ";", enclosure: "'").SHOP.ITEM
```

Without a `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

```php theme={null}
use FQL\Sql\Ast\Node\SelectFieldNode;

// An explicit field: remove it
$printer->print($ast->withFields([$ast->fields[0], $ast->fields[2]]));

// A column coming from *: exclude it
$hidden = new SelectFieldNode(new ColumnReferenceNode('secret', $p), null, true, $p);
$printer->print($ast->withFields([...$ast->fields, $hidden]));
// SELECT * FROM …  →  SELECT * EXCLUDE secret FROM …
```

Excluded fields must come after all selected ones, because `EXCLUDE` applies to every field after it.

### Group and count

```php theme={null}
use FQL\Sql\Ast\Expression\FunctionCallNode;
use FQL\Sql\Ast\Expression\StarNode;
use FQL\Sql\Ast\Node\GroupByClauseNode;

$count = new SelectFieldNode(new FunctionCallNode('COUNT', [new StarNode($p)], false, $p), 'count', false, $p);

$printer->print($ast
    ->withFields([new SelectFieldNode(new ColumnReferenceNode('brand', $p), null, false, $p), $count])
    ->withGroupBy(new GroupByClauseNode([new ColumnReferenceNode('brand', $p)], $p))
    ->withOrderBy(new OrderByClauseNode([new OrderByItemNode(new ColumnReferenceNode('count', $p), Sort::DESC, $p)], $p)));
```

## Source spans

Every node produced by the parser carries its source range through `span(): ?Span` (interface `FQL\Sql\Ast\HasSpan`). `FQL\Sql\Token\Span` is a half-open byte range `[start, end)` of the SQL string:

```php theme={null}
$span = $ast->where->span();
$span->start;          // byte offset of WHERE
$span->end;            // byte offset after the last condition
$span->slice($sql);    // "where price > 100"
$span->length();       // number of bytes
$span->contains($ast->where->conditions->span()); // true
```

A span starts at the node's first token and ends after its last token, so it never includes surrounding whitespace or comments.

| Node | Span |
| - | - |
| Clause nodes | From the clause keyword (`FROM`, `LEFT OUTER JOIN`, `WHERE`, `UNION ALL`, …) to the end of the clause |
| `FromClauseNode` of `DESCRIBE` | From `DESCRIBE` |
| `SelectStatementNode` | From `EXPLAIN` / `WITH` / `SELECT` / `DESCRIBE` to the end, unions included |
| `BinaryOpNode`, `ConditionExpressionNode` | From the start of the left operand |
| `ConditionGroupNode` | The conditions; a nested group includes its parentheses |
| `CommonTableExpressionNode` | `name AS ( … )` |
| `CollectObjectExpressionNode` | The items inside `COLLECT_OBJECT( … )` |
| `LimitClauseNode` | `LIMIT n OFFSET m` when written together; otherwise only the part written last |

> [!NOTE]
>
> 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()`.

Spans also appear in errors and lint issues. See [Structured errors](https://docs.fiquela.io/api/exceptions.md#structured-errors-sourceawareexception) and [Linting](https://docs.fiquela.io/advanced/sql-provider.md#linting).

## Fresh printing

`FQL\Sql\Printer\FqlPrinter` writes any node as single-line FQL without a source:

```php theme={null}
use FQL\Sql\Printer\FqlPrinter;
use FQL\Sql\Printer\KeywordCase;

(new FqlPrinter())->print($ast);                     // SELECT name, price FROM … WHERE price > 100 ORDER BY name
(new FqlPrinter(KeywordCase::LOWER))->print($condition);

FqlPrinter::identifier('Kód objednávky');            // `Kód objednávky`
FqlPrinter::columnReference('Kód.items[].name');     // `Kód`.items[].name
FqlPrinter::stringLiteral('say "hi"');               // 'say "hi"'
```

The output always parses back to the same tree:

* 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 `raw` spelling when it still matches the value. Otherwise strings use double quotes (single quotes when the value contains `"`), numbers have no exponent, and booleans and `NULL` are keywords.
* A column on the right side of a condition stays a column. Arithmetic uses operators (`price * 2`). `ORDER BY` writes only `DESC`.
* 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](https://docs.fiquela.io/advanced/sql-provider.md#pretty-printing-and-highlighting).

## Writing file queries

`FQL\Query\FileQuery` writes every parameter that differs from the format default:

```php theme={null}
use FQL\Query\FileQuery;

$fq = new FileQuery('csv(./a.csv)');

(string) $fq->withParam('delimiter', ';');                    // csv(./a.csv, "utf-8", ";")
(string) $fq->withParam('enclosure', "'");                    // csv(./a.csv, enclosure: "'")
$fq->withParam('delimiter', ';')->toFql(true);                // csv(./a.csv, delimiter: ";")
(string) $fq->withParams(['delimiter' => '|', 'bom' => '1']); // csv(./a.csv, delimiter: "|", bom: "1")

(string) FileQuery::fromParts('xml', './feed.xml', ['encoding' => 'windows-1250'], 'SHOP.ITEM');
// xml(./feed.xml, "windows-1250").SHOP.ITEM
```

| Method | Description |
| - | - |
| `withParams(array $params)` | Replaces the parameter set. Missing keys fall back to the format defaults. |
| `fromParts(?string $format, ?string $file, array $params = [], ?string $query = null, bool $namedParams = false)` | Builds a `FileQuery` from its parts. |
| `toFql(bool $namedParams = false)` | Writes the FileQuery; `true` forces named parameters. |
| `pathToFql(string $file)` | Returns the file path as written in a FileQuery, quoted when needed. See [Quoted file paths](https://docs.fiquela.io/querying/opening-files.md#quoted-file-paths). |

`__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.

> [!NOTE]
>
> 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.

Parts FQL cannot express throw `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 `@id` or 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`, or `CAST`.
* An included SELECT field after an excluded one.
* An empty `GROUP BY` / `ORDER BY`, a `CASE` without `WHEN`, or `CAST` to `TRUE` / `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 query `raw` text, backticks around column path segments, and the logical operator of the first condition of a group.
* A changed `LIMIT` is written as `LIMIT n OFFSET m` (`LIMIT 5, 10` becomes `LIMIT 5 OFFSET 10`).
* A repeated clause (two `WHERE`s, 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.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.