Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions documentation/components/bridges/symfony-postgresql-bundle.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,9 +476,17 @@ These commands are always available, with or without a migration configuration.
| `flow:database:create` | Create the configured database |
| `flow:database:drop` | Drop the configured database (requires `--force`) |
| `flow:sql:run` | Execute SQL directly on the database |
| `flow:sql:format` | Format SQL with the flow-php/postgresql parser |

The commands above accept `--connection` (`-c`) to target a specific connection. Migration commands do not accept
it. They always run against the configured migrations connection.
`flow:database:create`, `flow:database:drop` and `flow:sql:run` accept `--connection` (`-c`) to target a specific
connection. Migration commands do not accept it. They always run against the configured migrations connection.

```bash
bin/console flow:sql:format "select id,name from users -- active only"
bin/console flow:sql:format --path="sql/*.sql" --write
bin/console flow:sql:format --path=sql --check
bin/console flow:sql:format --path=sql --write --preserve-comments
```

### Migration Commands

Expand Down
28 changes: 27 additions & 1 deletion documentation/components/extensions/pg-query-ext.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,36 @@ pg_query_deparse_opts(
int $indent_size = 4, // Spaces per indentation level
int $max_line_length = 80, // Maximum line length before wrapping
bool $trailing_newline = false, // Add trailing newline
bool $commas_start_of_line = false // Place commas at line start
bool $commas_start_of_line = false, // Place commas at line start
?string $comments_from = null // Source SQL whose comments the output keeps
): string
```

```php
<?php

$sql = "SELECT a, -- the a column
b
/* block comment
two lines */
FROM t
WHERE x = $1 -- trailing
AND y IN (1, 2);";

echo pg_query_deparse_opts(pg_query_parse_protobuf($sql), true, 2, 80, false, false, $sql);
// SELECT
// a,
// -- the a column
// b
// FROM t
// WHERE
// /* block comment
// two lines */
// x = $1
// AND -- trailing
// y IN (1, 2)
```

## Error Handling

On a parse error, the extension throws `RuntimeException`:
Expand Down
17 changes: 15 additions & 2 deletions documentation/components/libs/postgresql.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ $sql = sql_deparse($query, sql_deparse_options()

// Shorthand: parse and format in one step
$formatted = sql_format('SELECT id,name FROM users WHERE active=true');

// Comments are removed by default
$formatted = sql_format("SELECT id, -- primary key\n name FROM users");

// Keep the comments of the input
$formatted = sql_format("SELECT id, -- primary key\n name FROM users", sql_deparse_options()->preserveComments());
```

#### DeparseOptions
Expand All @@ -176,6 +182,7 @@ $formatted = sql_format('SELECT id,name FROM users WHERE active=true');
| `maxLineLength(int)` | Maximum line length before wrapping | `80` |
| `trailingNewline(bool)` | Add trailing newline at end | `false` |
| `commasStartOfLine(bool)` | Place commas at start of lines | `false` |
| `preserveComments(bool)` | Keep the comments of the parsed SQL | `false` |

---

Expand Down Expand Up @@ -839,9 +846,9 @@ catalog_comparator()->compare($current, $target, dropIfExists: true);
<?php

use Flow\PostgreSql\AST\Transformers\{OffsetPaginationConfig, OffsetPaginationModifier};
use Flow\PostgreSql\Exception\{ParserException, ExtensionNotLoadedException, PaginationException};
use Flow\PostgreSql\Exception\{ParserException, ExtensionNotLoadedException, ExtensionOutdatedException, PaginationException};

use function Flow\PostgreSql\DSL\sql_parse;
use function Flow\PostgreSql\DSL\{sql_deparse_options, sql_format, sql_parse};

try {
$query = sql_parse('INVALID SQL');
Expand All @@ -851,6 +858,12 @@ try {
echo "Parse error: " . $e->getMessage();
}

try {
$sql = sql_format("SELECT 1 -- one\n", sql_deparse_options()->preserveComments());
} catch (ExtensionOutdatedException $e) {
// pg_query extension is older than 0.49 and cannot keep comments
}

try {
// OFFSET without ORDER BY throws exception
$query = sql_parse('SELECT * FROM users');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,10 @@ private function deleteObjects(Path $listed, array $keys): void
'%d of %d paths were not removed, the first is %s: %s',
count($errors),
count($keys),
path($listed->protocol() . '://' . DIRECTORY_SEPARATOR . $errors[0]->getKey(), $listed->options())->uri(),
path(
$listed->protocol() . '://' . DIRECTORY_SEPARATOR . (string) $errors[0]->getKey(),
$listed->options(),
)->uri(),
$errors[0]->getCode(),
));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,32 @@ public function test_rm_of_a_non_empty_directory_without_recursion_sends_no_dele
static::assertSame(['HeadObject', 'ListObjectsV2'], $calls);
}

public function test_rm_of_a_refusal_without_a_key_throws_with_the_error_code(): void
{
$calls = [];

try {
aws_s3_filesystem('bucket', S3ClientMother::answering([
'ListObjectsV2' => [200, [], S3ClientMother::listing('dir/a.csv')],
'DeleteObjects' => [
200,
[],
'<?xml version="1.0" encoding="UTF-8"?><DeleteResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
. '<Error><Code>InternalError</Code><Message>InternalError</Message></Error></DeleteResult>',
],
], $calls))->rm(path('aws-s3://dir/*.csv'));

static::fail('rm() of a refusal without a key must throw');
} catch (RuntimeException $exception) {
static::assertSame(
'1 of 1 paths were not removed, the first is aws-s3://: InternalError',
$exception->getMessage(),
);
}

static::assertSame(['ListObjectsV2', 'DeleteObjects'], $calls);
}

public function test_rm_of_refused_keys_throws_before_the_next_delete_objects(): void
{
$calls = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ protected function configure(): void
InputOption::VALUE_NONE,
'Place commas at the start of the line instead of the end',
)
->addOption('trailing-newline', null, InputOption::VALUE_NONE, 'Append a trailing newline to formatted SQL')
->addOption(
'trailing-newline',
'preserve-comments',
null,
InputOption::VALUE_NONE,
'Append a trailing newline to formatted SQL',
'Keep SQL comments in the formatted output',
);
}

Expand Down Expand Up @@ -132,7 +133,8 @@ private function buildDeparseOptions(InputInterface $input): DeparseOptions
->maxLineLength(type_integer()->cast($input->getOption('max-line-length')))
->prettyPrint(!type_boolean()->cast($input->getOption('no-pretty-print')))
->commasStartOfLine(type_boolean()->cast($input->getOption('commas-start-of-line')))
->trailingNewline(type_boolean()->cast($input->getOption('trailing-newline')));
->trailingNewline(type_boolean()->cast($input->getOption('trailing-newline')))
->preserveComments(type_boolean()->cast($input->getOption('preserve-comments')));
}

private function formatPath(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,36 @@ public function test_reports_when_no_sql_files_found(): void
static::assertStringContainsString('No .sql files found', $tester->getDisplay());
}

public function test_preserve_comments_option_keeps_comments(): void
{
$tester = new CommandTester($this->context->command('flow.postgresql.command.sql_format'));
$tester->execute(['sql' => "select a, -- the a column\n b from t", '--preserve-comments' => true]);

static::assertSame(Command::SUCCESS, $tester->getStatusCode());
static::assertStringContainsString('-- the a column', $tester->getDisplay());
}

public function test_removes_comments_by_default(): void
{
$tester = new CommandTester($this->context->command('flow.postgresql.command.sql_format'));
$tester->execute(['sql' => "select a, -- the a column\n b from t"]);

static::assertSame(Command::SUCCESS, $tester->getStatusCode());
static::assertStringNotContainsString('-- the a column', $tester->getDisplay());
}

public function test_write_with_preserve_comments_leaves_comment_only_file_unchanged(): void
{
$file = $this->fs->writeFile('comments.sql', "-- only a comment\n/* and a block */");

$tester = new CommandTester($this->context->command('flow.postgresql.command.sql_format'));
$tester->execute(['--path' => $file->path(), '--write' => true, '--preserve-comments' => true]);

static::assertSame(Command::SUCCESS, $tester->getStatusCode());
static::assertStringContainsString('0 file(s) reformatted, 1 unchanged.', $tester->getDisplay());
static::assertSame("-- only a comment\n/* and a block */", $this->fs->readFile('comments.sql'));
}

public function test_writes_formatted_file_back_with_write_option(): void
{
$file = $this->fs->writeFile('query.sql', 'select id,name from users');
Expand Down
43 changes: 40 additions & 3 deletions src/extension/pg-query-ext/ext/pg_query.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@

#include "pg_query_arginfo.h"

// exported by libpg_query.a, declared only in its internal header; pg_query_free_deparse_comments_result() skips the error
void pg_query_free_error(PgQueryError *error);

zend_module_entry pg_query_module_entry = {
STANDARD_MODULE_HEADER,
PHP_PG_QUERY_EXTNAME,
Expand Down Expand Up @@ -446,31 +449,65 @@ PHP_FUNCTION(pg_query_deparse_opts)
zend_long max_line_length = 80;
bool trailing_newline = false;
bool commas_start_of_line = false;
char *comments_from = NULL;
size_t comments_from_len = 0;

ZEND_PARSE_PARAMETERS_START(1, 6)
ZEND_PARSE_PARAMETERS_START(1, 7)
Z_PARAM_STRING(protobuf, protobuf_len)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(pretty_print)
Z_PARAM_LONG(indent_size)
Z_PARAM_LONG(max_line_length)
Z_PARAM_BOOL(trailing_newline)
Z_PARAM_BOOL(commas_start_of_line)
Z_PARAM_STRING_OR_NULL(comments_from, comments_from_len)
ZEND_PARSE_PARAMETERS_END();

PgQueryDeparseCommentsResult comments = {0};

if (comments_from != NULL) {
comments = pg_query_deparse_comments_for_query(comments_from);

if (comments.error) {
char error_msg[1024];

if (comments.error->message) {
strncpy(error_msg, comments.error->message, sizeof(error_msg) - 1);
error_msg[sizeof(error_msg) - 1] = '\0';
} else {
strcpy(error_msg, "Comment scan error");
}

pg_query_free_error(comments.error);
pg_query_free_deparse_comments_result(comments);

zend_throw_exception(spl_ce_RuntimeException, error_msg, 0);
RETURN_THROWS();
}

for (size_t i = 0; i < comments.comment_count; i++) {
// a `--` comment ends at the newline, so a node placed after it on the same line becomes comment text
if (strncmp(comments.comments[i]->str, "--", 2) == 0 && comments.comments[i]->newlines_after_comment < 1) {
comments.comments[i]->newlines_after_comment = 1;
}
}
}

PgQueryProtobuf pbuf;
pbuf.data = protobuf;
pbuf.len = protobuf_len;

struct PostgresDeparseOpts opts = {0};
opts.comments = NULL;
opts.comment_count = 0;
opts.comments = comments.comments;
opts.comment_count = comments.comment_count;
opts.pretty_print = pretty_print;
opts.indent_size = (int)indent_size;
opts.max_line_length = (int)max_line_length;
opts.trailing_newline = trailing_newline;
opts.commas_start_of_line = commas_start_of_line;

PgQueryDeparseResult result = pg_query_deparse_protobuf_opts(pbuf, opts);
pg_query_free_deparse_comments_result(comments);

if (result.error) {
char error_msg[1024];
Expand Down
2 changes: 2 additions & 0 deletions src/extension/pg-query-ext/ext/pg_query.stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ function pg_query_deparse(string $protobuf): string { return ''; }
* @param int $max_line_length Maximum line length before wrapping (default: 80)
* @param bool $trailing_newline Add a trailing newline at the end (default: false)
* @param bool $commas_start_of_line Place commas at the start of lines (default: false)
* @param null|string $comments_from Source SQL whose comments the output keeps (default: null, no comments)
*
* @throws RuntimeException on deparse error
*
Expand All @@ -108,6 +109,7 @@ function pg_query_deparse_opts(
int $max_line_length = 80,
bool $trailing_newline = false,
bool $commas_start_of_line = false,
?string $comments_from = null,
): string { return ''; }

/**
Expand Down
1 change: 1 addition & 0 deletions src/extension/pg-query-ext/ext/pg_query_arginfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pg_query_deparse_opts, 0, 1, IS_
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, max_line_length, IS_LONG, 0, "80")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, trailing_newline, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, commas_start_of_line, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, comments_from, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_pg_query_summary, 0, 1, IS_STRING, 0)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
--TEST--
pg_query_deparse_opts() keeps the comments of the comments_from source
--SKIPIF--
<?php if (!extension_loaded("pg_query")) die("skip pg_query extension not loaded"); ?>
<?php if (!function_exists("pg_query_deparse_opts")) die("skip pg_query_deparse_opts function not available"); ?>
--FILE--
<?php
$sample = "SELECT a, -- the a column\n b\n/* block comment\n two lines */\nFROM t\nWHERE x = $1 -- trailing\n AND y IN (1, 2);";
$tree = pg_query_parse_protobuf($sample);

var_dump(pg_query_deparse_opts($tree, true, 2, 80, false, false, $sample));
var_dump(pg_query_deparse_opts($tree, false, 2, 80, false, false, $sample));
var_dump(pg_query_deparse_opts($tree, true, 2, 80, false, false, null) === pg_query_deparse_opts($tree, true, 2));

$multi = "SELECT 1; -- a\nSELECT 2; /* b */";
var_dump(pg_query_deparse_opts(pg_query_parse_protobuf($multi), true, 2, 80, false, false, $multi));
var_dump(pg_query_deparse_opts(pg_query_parse_protobuf($multi), false, 2, 80, false, false, $multi));

try {
pg_query_deparse_opts($tree, true, 2, 80, false, false, 'SELECT 1 /* open');
} catch (RuntimeException $e) {
var_dump($e->getMessage());
}

foreach (['SELECT 1, 2, 3 FROM t WHERE a = 1', 'SELECT 1 LIMIT 5'] as $grown) {
$grownTree = pg_query_parse_protobuf($grown);

foreach ([true, false] as $pretty) {
$out = pg_query_deparse_opts($grownTree, $pretty, 2, 80, false, false, 'SELECT 1 -- x');
var_dump($out);
var_dump(pg_query_deparse(pg_query_parse_protobuf($out)) === pg_query_deparse($grownTree));
}
}
?>
--EXPECT--
string(122) "SELECT
a,
-- the a column
b
FROM t
WHERE
/* block comment
two lines */
x = $1
AND -- trailing
y IN (1, 2)"
string(109) "SELECT a, -- the a column
b FROM t WHERE
/* block comment
two lines */
x = $1 AND -- trailing
y IN (1, 2)"
bool(true)
string(31) "SELECT 1; -- a
SELECT 2
/* b */"
string(32) "SELECT 1; -- a
SELECT 2 /* b */"
string(44) "unterminated /* comment at or near "/* open""
string(44) "SELECT
1,
-- x
2, 3
FROM t
WHERE a = 1"
bool(true)
string(38) "SELECT 1, -- x
2, 3 FROM t WHERE a = 1"
bool(true)
string(25) "SELECT 1
LIMIT
-- x
5"
bool(true)
string(21) "SELECT 1 LIMIT -- x
5"
bool(true)
Loading
Loading