packages/sql-semantics-sqlite/bench/SemanticsBench.php

1<?php
2
3declare(strict_types=1);
4
5namespace Bench;
6
7use PhpBench\Attributes as Benchmark;
8use SqlSemantics\Platform\Sqlite\Model\Contract\AnalysisContext;
9use SqlSemantics\Platform\Sqlite\Semantics;
10
11/**
12 * Measures the public SQL-to-operation pipeline: analysis, resolution against declarations, and script splitting.
13 */
14final class SemanticsBench
15{
16    private Semantics $semantics;
17
18    private AnalysisContext $context;
19
20    /**
21     * Loads the parser and the grammar artifacts before measurement.
22     */
23    public function setUp(): void
24    {
25        $this->semantics = new Semantics();
26        $this->context = $this->semantics->context([
27            $this->semantics->analyze('CREATE TABLE users (id INTEGER PRIMARY KEY, parent_id INTEGER, score INTEGER NOT NULL)'),
28        ]);
29    }
30
31    /**
32     * Analyzes a self join against an open context on each iteration.
33     */
34    #[Benchmark\BeforeMethods('setUp')]
35    #[Benchmark\Revs(100)]
36    #[Benchmark\Iterations(5)]
37    public function benchAnalyze(): void
38    {
39        $this->semantics->analyze('SELECT child.id, parent.score, coalesce(parent.score, 0) AS effective_score FROM users AS child LEFT JOIN users AS parent ON child.parent_id = parent.id WHERE child.score > 0 ORDER BY child.id LIMIT 10');
40    }
41
42    /**
43     * Resolves a self join against a complete declaration context on each iteration.
44     */
45    #[Benchmark\BeforeMethods('setUp')]
46    #[Benchmark\Revs(100)]
47    #[Benchmark\Iterations(5)]
48    public function benchResolve(): void
49    {
50        $this->semantics->analyze('SELECT child.id, parent.score FROM users AS child LEFT JOIN users AS parent ON child.parent_id = parent.id WHERE child.score > 0', $this->context);
51    }
52
53    /**
54     * Reads a declaration with constraints on each iteration.
55     */
56    #[Benchmark\BeforeMethods('setUp')]
57    #[Benchmark\Revs(100)]
58    #[Benchmark\Iterations(5)]
59    public function benchDeclaration(): void
60    {
61        $this->semantics->analyze('CREATE TABLE items (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parent(id), amount NUMERIC(7) DEFAULT 1.25)', []);
62    }
63
64    /**
65     * Finds the boundaries of a three-statement script on each iteration.
66     */
67    #[Benchmark\BeforeMethods('setUp')]
68    #[Benchmark\Revs(100)]
69    #[Benchmark\Iterations(5)]
70    public function benchSplit(): void
71    {
72        $this->semantics->split('SELECT 1; UPDATE users SET score = 0 WHERE id = 1; DELETE FROM users WHERE id = 2');
73    }
74}
75