packages/sql-semantics-mysql/src/Statement/Routine/DollarQuotedText.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Routine;
6
7use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Node;
10use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
11
12/**
13 * A dollar-quoted string: `$tag$ text $tag$` (MySQL 8.1 and later).
14 *
15 * The text between the delimiters is taken as it is, without escapes; the
16 * server treats it as the opaque code of an external language. The tag is
17 * part of the spelling the text needs: the text cannot hold its own closing
18 * delimiter.
19 * Source: https://dev.mysql.com/doc/refman/9.1/en/create-procedure.html.
20 *
21 * @visibility public
22 * @example Holding dollar-quoted code
23 * $quoted = new \SqlSemantics\Platform\MySql\Statement\Routine\DollarQuotedText('return 1', 'js');
24 * [$quoted->tag, $quoted->text] // => ['js', 'return 1']
25 */
26final class DollarQuotedText implements Node
27{
28 use Snapshot;
29
30 /**
31 * @param string $text The text between the delimiters
32 * @param string $tag The tag between the dollar signs of each delimiter; may be empty
33 */
34 public function __construct(public readonly string $text, public readonly string $tag = '')
35 {
36 Check::input(preg_match('/\A[^$\s]*\z/', $tag) === 1, 'The tag of a dollar-quoted string holds no dollar sign and no space.');
37 Check::input(!str_contains($text, '$' . $tag . '$'), 'The text of a dollar-quoted string cannot hold its closing delimiter.');
38 }
39
40 /**
41 * Writes the delimiters around the text.
42 */
43 public function render(Output $out): void
44 {
45 $out->spelled('$' . $this->tag . '$' . $this->text . '$' . $this->tag . '$');
46 }
47}
48