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
26 changes: 26 additions & 0 deletions packages/web-ui/src/components/ui/FilterRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ const OPERATOR_LABEL_KEYS: Partial<Record<FilterOperator, string>> = {
'is not empty': 'toolbar.opIsNotEmpty',
};

/** Operators that build a literal LIKE and so can switch to ILIKE. */
const MATCH_CASE_OPS: FilterOperator[] = ['contains', 'starts with', 'ends with'];

export interface FilterRowProps {
filter: StructuredFilter;
columns: TableColumn[];
Expand All @@ -40,6 +43,11 @@ export interface FilterRowProps {
onLoadValues?: (filter: StructuredFilter) => Promise<DistinctValue[]>;
/** Identifies the connection and query whose values the picker displays. */
valuePickerContextKey?: string;
/**
* Shows the "Match case" toggle for contains / starts with / ends with.
* Set only on PostgreSQL-dialect connections.
*/
supportsMatchCase?: boolean;
}

export const FilterRow = ({
Expand All @@ -54,6 +62,7 @@ export const FilterRow = ({
onTriggerApplied,
onLoadValues,
valuePickerContextKey,
supportsMatchCase = false,
}: FilterRowProps) => {
const {t} = useTranslation();
const selectedCol = columns.find((c) => c.name === filter.column);
Expand All @@ -70,6 +79,9 @@ export const FilterRow = ({
!isBetween &&
isValuePickerSupported(dataType);

const showMatchCase = supportsMatchCase && MATCH_CASE_OPS.includes(filter.operator);
const matchCase = filter.matchCase !== false;

const handleColumnChange = (col: string) => {
const colMeta = columns.find((c) => c.name === col);
const ops = getOperatorsForType(colMeta?.data_type ?? '');
Expand Down Expand Up @@ -157,6 +169,20 @@ export const FilterRow = ({
)}
</div>
)}
{showMatchCase && (
<label
className="shrink-0 flex items-center gap-1 text-xs text-muted cursor-pointer select-none"
title={t('toolbar.matchCaseHint')}
>
<input
type="checkbox"
checked={matchCase}
onChange={(e) => onChange({...filter, matchCase: e.target.checked})}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Toggling "Match case" does not reset the filter's applied state

TableToolbar.handleFilterChange (src/components/ui/TableToolbar.tsx, ~line 316) decides whether to call onResetApplied by comparing only column, operator, value and value2. Since matchCase is not part of that comparison, flipping this checkbox is treated as an "only enabled changed" update: the row keeps its "applied" indicator even though the clause it would generate has changed (LIKE <-> ILIKE) and the displayed data no longer matches the filter. Add prev.matchCase === updated.matchCase to the onlyEnabledChanged check, and cover it with a test.

className="accent-accent-primary cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-focus/60 rounded"
/>
{t('toolbar.matchCase')}
</label>
)}
{noValue && <div className="flex-1" />}
{isBetween && (
<div className="flex items-center gap-1.5 flex-1 min-w-0">
Expand Down
6 changes: 5 additions & 1 deletion packages/web-ui/src/components/ui/TableToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
replaceCurrentWord,
buildStructuredFilterClause,
buildSingleFilterClause,
supportsMatchCaseToggle,
isFilterComplete,
createEmptyFilter,
buildDistinctValuesQuery,
Expand Down Expand Up @@ -316,7 +317,9 @@ const TableToolbarInternal = ({
prev.column === updated.column &&
prev.operator === updated.operator &&
prev.value === updated.value &&
prev.value2 === updated.value2;
prev.value2 === updated.value2 &&
// undefined and true both mean "match case"
(prev.matchCase !== false) === (updated.matchCase !== false);
if (!onlyEnabledChanged) {
onResetApplied(updated.id);
}
Expand Down Expand Up @@ -895,6 +898,7 @@ const TableToolbarInternal = ({
onEscape={closePanel}
isApplied={appliedFilters[filter.id] === true}
onTriggerApplied={() => onTriggerApplied(filter.id)}
supportsMatchCase={supportsMatchCaseToggle(quotingDriver)}
onLoadValues={canPickValues ? loadValuesFor : undefined}
valuePickerContextKey={
canPickValues
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "beginnt mit",
"opEndsWith": "endet mit",
"opIsEmpty": "ist leer",
"opIsNotEmpty": "ist nicht leer"
"opIsNotEmpty": "ist nicht leer",
"matchCase": "Groß-/Kleinschreibung",
"matchCaseHint": "Groß-/Kleinschreibung beachten (LIKE). Abwählen für eine Suche ohne Beachtung (ILIKE)."
},
"tags": {
"label": "Tags",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "starts with",
"opEndsWith": "ends with",
"opIsEmpty": "is empty",
"opIsNotEmpty": "is not empty"
"opIsNotEmpty": "is not empty",
"matchCase": "Match case",
"matchCaseHint": "Case-sensitive match (LIKE). Untick for a case-insensitive match (ILIKE)."
},
"tags": {
"label": "Tags",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "empieza con",
"opEndsWith": "termina con",
"opIsEmpty": "está vacío",
"opIsNotEmpty": "no está vacío"
"opIsNotEmpty": "no está vacío",
"matchCase": "Coincidir mayúsculas",
"matchCaseHint": "Distingue mayúsculas y minúsculas (LIKE). Desmarca para ignorarlas (ILIKE)."
},
"tags": {
"label": "Etiquetas",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "commence par",
"opEndsWith": "se termine par",
"opIsEmpty": "est vide",
"opIsNotEmpty": "n'est pas vide"
"opIsNotEmpty": "n'est pas vide",
"matchCase": "Respecter la casse",
"matchCaseHint": "Respecte la casse (LIKE). Décochez pour ignorer la casse (ILIKE)."
},
"tags": {
"label": "Tags",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "inizia con",
"opEndsWith": "finisce con",
"opIsEmpty": "è vuoto",
"opIsNotEmpty": "non è vuoto"
"opIsNotEmpty": "non è vuoto",
"matchCase": "Maiuscole/minuscole",
"matchCaseHint": "Distingue maiuscole e minuscole (LIKE). Deseleziona per ignorarle (ILIKE)."
},
"triggers":{
"originalRestored": "Il trigger originale è stato ripristinato.",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "で始まる",
"opEndsWith": "で終わる",
"opIsEmpty": "空である",
"opIsNotEmpty": "空でない"
"opIsNotEmpty": "空でない",
"matchCase": "大文字小文字を区別",
"matchCaseHint": "大文字と小文字を区別します (LIKE)。オフにすると区別しません (ILIKE)。"
},
"tags": {
"label": "タグ",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "으로 시작",
"opEndsWith": "으로 끝남",
"opIsEmpty": "비어 있음",
"opIsNotEmpty": "비어 있지 않음"
"opIsNotEmpty": "비어 있지 않음",
"matchCase": "대소문자 구분",
"matchCaseHint": "대소문자를 구분합니다 (LIKE). 해제하면 구분하지 않습니다 (ILIKE)."
},
"common": {
"save": "저장",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "começa com",
"opEndsWith": "termina com",
"opIsEmpty": "está vazio",
"opIsNotEmpty": "não está vazio"
"opIsNotEmpty": "não está vazio",
"matchCase": "Diferenciar maiúsculas",
"matchCaseHint": "Diferencia maiúsculas de minúsculas (LIKE). Desmarque para ignorar (ILIKE)."
},
"common": {
"save": "Salvar",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "начинается с",
"opEndsWith": "заканчивается на",
"opIsEmpty": "пусто",
"opIsNotEmpty": "не пусто"
"opIsNotEmpty": "не пусто",
"matchCase": "Учитывать регистр",
"matchCaseHint": "Учитывать регистр (LIKE). Снимите флажок, чтобы не учитывать (ILIKE)."
},
"tags": {
"label": "Теги",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/tl.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "nagsisimula sa",
"opEndsWith": "nagtatapos sa",
"opIsEmpty": "walang laman",
"opIsNotEmpty": "may laman"
"opIsNotEmpty": "may laman",
"matchCase": "Itugma ang case",
"matchCaseHint": "Sensitibo sa laki ng titik (LIKE). I-untick para hindi maging sensitibo (ILIKE)."
},
"tags": {
"label": "Mga tag",
Expand Down
4 changes: 3 additions & 1 deletion packages/web-ui/src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@
"opStartsWith": "开头是",
"opEndsWith": "结尾是",
"opIsEmpty": "为空",
"opIsNotEmpty": "不为空"
"opIsNotEmpty": "不为空",
"matchCase": "区分大小写",
"matchCaseHint": "区分大小写 (LIKE)。取消勾选则不区分 (ILIKE)。"
},
"tags": {
"label": "标签",
Expand Down
37 changes: 33 additions & 4 deletions packages/web-ui/src/utils/filterBar.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import type {TableColumn} from '@/types/editor';
import type {DriverCapabilities, PluginManifest} from '@/types/plugins';
import {formatSqlIdentifier, quoteIdentifier, quoteTableRef} from './identifiers';
import {
formatSqlIdentifier,
isPostgresDialect,
quoteIdentifier,
quoteTableRef,
} from './identifiers';
import {formatSqlValueForColumnComparison, isMysqlFloatColumn} from './foreignKeys';
import {
booleanLiteralWithStyle,
Expand Down Expand Up @@ -41,6 +46,12 @@ export interface StructuredFilter {
value: string;
value2?: string; // for BETWEEN only
enabled?: boolean; // defaults to true when building clause
/**
* Case sensitivity of contains / starts with / ends with. Defaults to true
* (`LIKE`). `false` generates `ILIKE`, and only on PostgreSQL-dialect
* connections (see `supportsMatchCaseToggle`); other dialects ignore it.
*/
matchCase?: boolean;
}

const NUMERIC_TYPES = [
Expand Down Expand Up @@ -194,7 +205,9 @@ export function buildSingleFilterClause(
}

if (op === 'contains' || op === 'starts with' || op === 'ends with') {
return buildLiteralLikeClause(col, filter.value, op, driver);
return buildLiteralLikeClause(col, filter.value, op, driver, {
matchCase: filter.matchCase !== false,
});
}

if (op === 'BETWEEN') {
Expand Down Expand Up @@ -233,18 +246,34 @@ export function buildSingleFilterClause(
/** Where a literal LIKE match may sit inside the column value. */
export type LikeMatchMode = 'contains' | 'starts with' | 'ends with';

/**
* True when the match-case setting applies: PostgreSQL-dialect connections,
* decided from the declared `sql_dialect` (so plugins count) rather than the
* driver id. Other dialects have no `ILIKE` and keep their existing filters.
*/
export function supportsMatchCaseToggle(
driver: string | PluginManifest | DriverCapabilities | null | undefined,
): boolean {
return isPostgresDialect(driver);
}

/**
* Builds `col LIKE '<pattern>' ESCAPE '!'` that matches `value` literally:
* `%`, `_` and the escape character in the value are escaped, so they don't
* act as wildcards, and the pattern is wrapped with `%` according to `mode`.
* `col` must already be a quoted/formatted identifier.
* With `options.matchCase === false` on a PostgreSQL-dialect driver the
* operator is `ILIKE` instead of `LIKE`; the escaping is identical.
*/
export function buildLiteralLikeClause(
col: string,
value: string,
mode: LikeMatchMode,
driver: string | PluginManifest | DriverCapabilities | null | undefined,
options?: {matchCase?: boolean},
): string {
const likeOp =
options?.matchCase === false && supportsMatchCaseToggle(driver) ? 'ILIKE' : 'LIKE';
// A syntax without `LIKE … ESCAPE` (declared `like_escape: false`, e.g.
// GoogleSQL) escapes `%`, `_` and backslash itself with a backslash, its
// default LIKE escape; the literal then gets the syntax's own escaping.
Expand All @@ -260,11 +289,11 @@ export function buildLiteralLikeClause(
} else {
pattern = `%${escaped}`;
}
if (noEscapeClause) return `${col} LIKE ${quoteSqlString(pattern, driver)}`;
if (noEscapeClause) return `${col} ${likeOp} ${quoteSqlString(pattern, driver)}`;
// MySQL/MariaDB (default sql_mode) treat backslash as an escape inside
// string literals, so a literal backslash must be doubled to survive.
const literal = usesBackslashStringEscapes(driver) ? pattern.replace(/\\/g, '\\\\') : pattern;
return `${col} LIKE ${quoteLiteral(literal, driver)} ESCAPE '${LIKE_ESCAPE}'`;
return `${col} ${likeOp} ${quoteLiteral(literal, driver)} ESCAPE '${LIKE_ESCAPE}'`;
}

/**
Expand Down
36 changes: 36 additions & 0 deletions packages/web-ui/tests/components/ui/FilterRow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,39 @@ describe('FilterRow value picker', () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});

describe('FilterRow match case toggle', () => {
const textFilter: StructuredFilter = {
id: 'f1',
column: 'status',
operator: 'contains',
value: 'a',
};
const toggle = () => screen.queryByRole('checkbox', {name: 'toolbar.matchCase'});

it('is hidden unless the connection supports it', () => {
renderRow(textFilter);
expect(toggle()).not.toBeInTheDocument();
});

it('is shown, checked by default, for text operators when supported', () => {
renderRow(textFilter, {supportsMatchCase: true});
expect(toggle()).toBeChecked();
});

it('is hidden for operators it does not affect', () => {
renderRow({...textFilter, operator: '='}, {supportsMatchCase: true});
expect(toggle()).not.toBeInTheDocument();
});

it('stores matchCase false when unticked', () => {
const {onChange} = renderRow(textFilter, {supportsMatchCase: true});
fireEvent.click(toggle()!);
expect(onChange).toHaveBeenCalledWith({...textFilter, matchCase: false});
});

it('reflects an unticked filter', () => {
renderRow({...textFilter, matchCase: false}, {supportsMatchCase: true});
expect(toggle()).not.toBeChecked();
});
});
35 changes: 35 additions & 0 deletions packages/web-ui/tests/components/ui/TableToolbar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,41 @@ describe('TableToolbar', () => {
expect(screen.queryByText('toolbar.applied')).not.toBeInTheDocument();
});

it('resets the applied state when Match case is toggled, but not when only enabled changes', () => {
vi.mocked(useDatabase).mockReturnValue({
activeDriver: 'postgres',
} as ReturnType<typeof useDatabase>);
render(
<TableToolbar
{...defaultProps}
columnMetadata={[
{
name: 'name',
data_type: 'varchar(20)',
is_pk: false,
is_nullable: true,
is_auto_increment: false,
},
]}
/>,
);
openPanel();
fireEvent.change(screen.getByDisplayValue('='), {target: {value: 'contains'}});
fireEvent.change(screen.getByPlaceholderText('toolbar.valuePlaceholder'), {
target: {value: 'ab'},
});
fireEvent.click(screen.getByText('toolbar.apply'));
expect(screen.getByText('toolbar.applied')).toBeInTheDocument();

// Selecting/deselecting for Apply All keeps the applied feedback.
fireEvent.click(screen.getByTitle('toolbar.deselectFromApplyAll'));
expect(screen.getByText('toolbar.applied')).toBeInTheDocument();

fireEvent.click(screen.getByRole('checkbox', {name: 'toolbar.matchCase'}));
expect(screen.queryByText('toolbar.applied')).not.toBeInTheDocument();
expect(screen.getByText('toolbar.apply')).toBeInTheDocument();
});

it('applies a complete filter from its own Apply button', () => {
render(<TableToolbar {...panelProps} />);
openPanel();
Expand Down
Loading