packages/sql-parser/src/PostgreSql/PostgreSqlParser.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlParser\PostgreSql;
6
7use RuntimeException;
8use SqlParser\Lexer\LexicalException;
9use SqlParser\Lexer\ParameterSyntax;
10use SqlParser\Lexer\TerminalIndex;
11use SqlParser\Lexer\Token;
12use SqlParser\Parser\LrParser;
13use SqlParser\Parser\Node;
14use SqlParser\Parser\SqlParser;
15use SqlParser\Parser\SyntaxException;
16use SqlParser\PostgreSql\Lexer\KeywordTable;
17use SqlParser\PostgreSql\Lexer\PostgreSqlLexer;
18use SqlParser\Resource\VersionRegistry;
19use SqlParser\Table\ParseTable;
20use SqlParser\Table\TableFile;
21
22/**
23 * Parses PostgreSQL statements with the grammar of a chosen server release.
24 *
25 * The parse table is built from the `gram.y` of that release and the lexer
26 * follows its `scan.l`, so the tree names the nonterminals of the official
27 * grammar. Several statements separated by semicolons parse as one tree.
28 *
29 * @visibility public
30 *
31 * @example Parsing with the default release
32 *     $parser = new \SqlParser\PostgreSql\PostgreSqlParser();
33 *     $tree = $parser->parse('SELECT id FROM users WHERE id = $1');
34 *     $tree->name // => 'parse_toplevel'
35 *     count($tree->find('relation_expr')) // => 1
36 * @example Writing a parsed statement back
37 *     $sql = "SELECT id FROM users -- everyone\n";
38 *     $parser = new \SqlParser\PostgreSql\PostgreSqlParser();
39 *     $parser->parse($sql)->toString() === $sql // => true
40 * @example Rejecting an unsupported release
41 *     new \SqlParser\PostgreSql\PostgreSqlParser('pg-9.6.0') // throws \RuntimeException: Unsupported
42 * @example Reading a named placeholder
43 *     $parser = new \SqlParser\PostgreSql\PostgreSqlParser(parameters: \SqlParser\Lexer\ParameterSyntax::Named);
44 *     $parser->tokenize('SELECT id FROM users WHERE id = :id')[7]->name // => 'PARAM'
45 */
46final class PostgreSqlParser implements SqlParser
47{
48    private readonly PostgreSqlVersion $version;
49
50    private readonly ParseTable $table;
51
52    private readonly PostgreSqlLexer $lexer;
53
54    /**
55     * Loads the parser of one release.
56     *
57     * @param string|null $version Release tag such as `pg-17.2`, or null for the newest shipped
58     * @param VersionRegistry $registry Record of shipped releases
59     * @param ParameterSyntax $parameters Which parameter markers are read; the server reads only `$1`
60     *
61     * @throws RuntimeException When the release is not shipped or its resources are missing
62     */
63    public function __construct(?string $version = null, VersionRegistry $registry = new VersionRegistry(), ParameterSyntax $parameters = ParameterSyntax::Native)
64    {
65        $this->version = PostgreSqlVersion::resolve($version, $registry);
66        $this->table = (new TableFile())->load($this->version->release->tablePath);
67        $this->lexer = new PostgreSqlLexer(KeywordTable::load($this->version->release->keywordPath), parameters: $parameters);
68    }
69
70    /**
71     * Answers the release the parser reads for.
72     *
73     * @return string Release tag such as `pg-17.2`
74     */
75    public function version(): string
76    {
77        return $this->version->name();
78    }
79
80    /**
81     * Reads SQL text into the terminals of the grammar, the end marker last.
82     *
83     * A token carries the whitespace and comments skipped before it and the
84     * end marker what follows the last of them, so the tokens hold every byte
85     * of the text.
86     *
87     * @param string $sql The SQL text
88     *
89     * @return list<Token> The tokens in text order
90     *
91     * @throws LexicalException When the text holds something no token starts with
92     */
93    public function tokenize(string $sql): array
94    {
95        return (new TerminalIndex($this->table->symbols))->tokens($this->lexer->scan($sql), $sql);
96    }
97
98    /**
99     * Parses one or more statements.
100     *
101     * @param string $sql The SQL text
102     *
103     * @return Node The tree, rooted at the grammar's start symbol, holding every byte of the text
104     *
105     * @throws LexicalException When the text holds something no token starts with
106     * @throws SyntaxException When the text is not in the grammar of the release
107     */
108    public function parse(string $sql): Node
109    {
110        return (new LrParser($this->table))->parse($this->tokenize($sql), $sql);
111    }
112
113    /**
114     * Answers every release tag the package ships a PostgreSQL grammar for, oldest first.
115     *
116     * @return list<string> Release tags
117     */
118    public static function versions(): array
119    {
120        return (new VersionRegistry())->names(PostgreSqlVersion::DIALECT);
121    }
122}
123