From b9d3ca90eb8c2955dd1a544147897e328e45f7ee Mon Sep 17 00:00:00 2001 From: Richard BAYET Date: Thu, 8 Feb 2024 11:38:46 +0100 Subject: [PATCH] Allow expressions in filter columns --- app/config/example.yaml | 5 +++++ src/Dumper/Mysql/TableFilterExtension.php | 14 +++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/config/example.yaml b/app/config/example.yaml index e252b5a4..4fd30695 100644 --- a/app/config/example.yaml +++ b/app/config/example.yaml @@ -27,6 +27,11 @@ tables: filters: - ['created_at', 'gt', 'expr: date_sub(now(), interval 60 day)'] + # Dump only CMS pages without "FAQ" in their meta title + cms_page: + filters: + - ["expr: COALESCE(meta_title, '')", 'notLike', '%FAQ%'] + # Anonymize a table named "my_custom_table" my_custom_table: converters: diff --git a/src/Dumper/Mysql/TableFilterExtension.php b/src/Dumper/Mysql/TableFilterExtension.php index 4d3f8a9e..707aff38 100644 --- a/src/Dumper/Mysql/TableFilterExtension.php +++ b/src/Dumper/Mysql/TableFilterExtension.php @@ -205,7 +205,7 @@ private function applyTableConfigToQueryBuilder(QueryBuilder $queryBuilder, Tabl $whereExpr = call_user_func_array( $callable, - [$this->connection->quoteIdentifier($filter->getColumn()), $value] + [$this->getFilterColumn($filter), $value] ); $queryBuilder->andWhere($whereExpr); @@ -303,4 +303,16 @@ private function quoteValue(mixed $value): mixed return $value; } + + /** + * Get a filter column so it can be safely injected in SQL query + * Extracts a possible expression to use instead of a real column name. + */ + private function getFilterColumn(Filter $filter): mixed + { + $column = $filter->getColumn(); + + return str_starts_with($column, 'expr:') ? + ltrim(substr($column, 5)) : $this->connection->quoteIdentifier($column); + } }