Skip to content
Closed
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
30 changes: 30 additions & 0 deletions src/components/ui/FilterRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
getOperatorsForType,
getPickedValues,
isFilterComplete,
isMatchCaseEnabled,
isValuePickerSupported,
NO_VALUE_OPS,
} from "../../utils/filterBar";
Expand Down Expand Up @@ -40,6 +41,12 @@ export interface FilterRowProps {
onLoadValues?: (filter: StructuredFilter) => Promise<DistinctValue[]>;
/** Identifies the connection and query whose values the picker displays. */
valuePickerContextKey?: string;
/**
* Offers the match-case toggle for the literal text operators. Only a
* PostgreSQL dialect can emit `ILIKE`, so other connections hide the control
* instead of showing one that changes nothing.
*/
supportsMatchCase?: boolean;
}

export const FilterRow = ({
Expand All @@ -54,6 +61,7 @@ export const FilterRow = ({
onTriggerApplied,
onLoadValues,
valuePickerContextKey,
supportsMatchCase,
}: FilterRowProps) => {
const { t } = useTranslation();
const selectedCol = columns.find((c) => c.name === filter.column);
Expand All @@ -65,6 +73,12 @@ export const FilterRow = ({
const dataType = selectedCol?.data_type ?? "";
const showValuePicker =
!!onLoadValues && !!filter.column && !noValue && !isBetween && isValuePickerSupported(dataType);
const isTextMatch =
filter.operator === "contains" ||
filter.operator === "starts with" ||
filter.operator === "ends with";
const showMatchCase = !!supportsMatchCase && isTextMatch;
const matchCase = isMatchCaseEnabled(filter);

const handleColumnChange = (col: string) => {
const colMeta = columns.find((c) => c.name === col);
Expand Down Expand Up @@ -141,6 +155,22 @@ export const FilterRow = ({
placeholder={t("toolbar.valuePlaceholder")}
autoComplete="off"
/>
{showMatchCase && (
<button
type="button"
onClick={() => onChange({ ...filter, matchCase: !matchCase })}
aria-pressed={matchCase}
aria-label={t("toolbar.matchCase")}
title={t("toolbar.matchCaseHint")}
className={`shrink-0 h-6 px-1.5 rounded border font-mono text-[10px] leading-none transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus ${
matchCase
? "bg-accent-primary/15 border-accent-primary/40 text-accent hover:bg-accent-primary/25"
: "bg-transparent border-default/60 text-muted hover:text-secondary hover:border-default"
}`}
>
Aa
</button>
)}
{showValuePicker && (
<FilterValuePicker
key={JSON.stringify([valuePickerContextKey, filter, dataType])}
Expand Down
5 changes: 4 additions & 1 deletion src/components/ui/TableToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
parseDistinctValues,
} from "../../utils/filterBar";
import type { StructuredFilter, FilterCombinator, DistinctValue } from "../../utils/filterBar";
import { formatSqlIdentifier } from "../../utils/identifiers";
import { formatSqlIdentifier, isPostgresDialect } from "../../utils/identifiers";
import { formatSortClause } from "../../utils/tableToolbar";
import { FilterRow } from "./FilterRow";
import { StyledSelect } from "./StyledSelect";
Expand Down Expand Up @@ -222,6 +222,8 @@ const TableToolbarInternal = ({
[onRunQuery, tableName, queryForValues],
);
const canPickValues = !!onRunQuery && !!tableName;
// ILIKE is PostgreSQL syntax; every other dialect keeps its LIKE-only rows.
const supportsMatchCase = isPostgresDialect(quotingDriver);

// Applies only that single row's filter — resets Applied on all others
const handleApplySingle = useCallback(
Expand Down Expand Up @@ -744,6 +746,7 @@ const TableToolbarInternal = ({
onEscape={closePanel}
isApplied={appliedFilters[filter.id] === true}
onTriggerApplied={() => onTriggerApplied(filter.id)}
supportsMatchCase={supportsMatchCase}
onLoadValues={canPickValues ? loadValuesFor : undefined}
valuePickerContextKey={canPickValues
? JSON.stringify([activeConnectionId, queryForValues(filter)])
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "beginnt mit",
"opEndsWith": "endet mit",
"opIsEmpty": "ist leer",
"opIsNotEmpty": "ist nicht leer"
"opIsNotEmpty": "ist nicht leer",
"matchCase": "Groß-/Kleinschreibung beachten",
"matchCaseHint": "Groß-/Kleinschreibung beachten (LIKE). Aus: jede Schreibweise (ILIKE)."
},
"tags": {
"label": "Tags",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "starts with",
"opEndsWith": "ends with",
"opIsEmpty": "is empty",
"opIsNotEmpty": "is not empty"
"opIsNotEmpty": "is not empty",
"matchCase": "Match case",
"matchCaseHint": "Match case (LIKE). Off matches any case (ILIKE)."
},
"tags": {
"label": "Tags",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "empieza con",
"opEndsWith": "termina con",
"opIsEmpty": "está vacío",
"opIsNotEmpty": "no está vacío"
"opIsNotEmpty": "no está vacío",
"matchCase": "Distinguir mayúsculas",
"matchCaseHint": "Distinguir mayúsculas (LIKE). Desactivado coincide con cualquier combinación (ILIKE)."
},
"tags": {
"label": "Etiquetas",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,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": "Respecter la casse (LIKE). Désactivé : toutes les casses (ILIKE)."
},
"tags": {
"label": "Tags",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "inizia con",
"opEndsWith": "finisce con",
"opIsEmpty": "è vuoto",
"opIsNotEmpty": "non è vuoto"
"opIsNotEmpty": "non è vuoto",
"matchCase": "Distingui maiuscole",
"matchCaseHint": "Distingui maiuscole (LIKE). Disattivato: qualsiasi combinazione (ILIKE)."
},
"triggers":{
"originalRestored": "Il trigger originale è stato ripristinato.",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "で始まる",
"opEndsWith": "で終わる",
"opIsEmpty": "空である",
"opIsNotEmpty": "空でない"
"opIsNotEmpty": "空でない",
"matchCase": "大文字と小文字を区別",
"matchCaseHint": "大文字と小文字を区別します(LIKE)。オフにすると区別しません(ILIKE)。"
},
"tags": {
"label": "タグ",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "으로 시작",
"opEndsWith": "으로 끝남",
"opIsEmpty": "비어 있음",
"opIsNotEmpty": "비어 있지 않음"
"opIsNotEmpty": "비어 있지 않음",
"matchCase": "대소문자 구분",
"matchCaseHint": "대소문자를 구분합니다(LIKE). 끄면 구분하지 않습니다(ILIKE)."
},
"common": {
"save": "저장",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,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": "Diferenciar maiúsculas (LIKE). Desativado: qualquer capitalização (ILIKE)."
},
"common": {
"save": "Salvar",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "начинается с",
"opEndsWith": "заканчивается на",
"opIsEmpty": "пусто",
"opIsNotEmpty": "не пусто"
"opIsNotEmpty": "не пусто",
"matchCase": "Учитывать регистр",
"matchCaseHint": "Учитывать регистр (LIKE). Выключено — любой регистр (ILIKE)."
},
"tags": {
"label": "Теги",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/tl.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "nagsisimula sa",
"opEndsWith": "nagtatapos sa",
"opIsEmpty": "walang laman",
"opIsNotEmpty": "may laman"
"opIsNotEmpty": "may laman",
"matchCase": "Itugma ang case",
"matchCaseHint": "Itugma ang case (LIKE). Kapag patay, anumang case (ILIKE)."
},
"tags": {
"label": "Mga tag",
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@
"opStartsWith": "开头是",
"opEndsWith": "结尾是",
"opIsEmpty": "为空",
"opIsNotEmpty": "不为空"
"opIsNotEmpty": "不为空",
"matchCase": "区分大小写",
"matchCaseHint": "区分大小写(LIKE)。关闭后不区分大小写(ILIKE)。"
},
"tags": {
"label": "标签",
Expand Down
37 changes: 34 additions & 3 deletions 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";


Expand Down Expand Up @@ -35,6 +40,14 @@ export interface StructuredFilter {
value: string;
value2?: string; // for BETWEEN only
enabled?: boolean; // defaults to true when building clause
/**
* Case sensitivity for the literal text operators (`contains`,
* `starts with`, `ends with`). Defaults to `true`, which keeps emitting the
* `LIKE` every dialect has always produced; `false` emits `ILIKE`, which
* only a PostgreSQL dialect can run. Other dialects ignore the flag, so a
* row reused on another connection keeps its previous SQL.
*/
matchCase?: boolean;
}

const NUMERIC_TYPES = [
Expand Down Expand Up @@ -200,7 +213,7 @@ 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, isMatchCaseEnabled(filter));
}

if (op === "BETWEEN") {
Expand Down Expand Up @@ -236,17 +249,32 @@ export function buildSingleFilterClause(
/** Where a literal LIKE match may sit inside the column value. */
export type LikeMatchMode = "contains" | "starts with" | "ends with";

/**
* Whether a row's literal text match is case-sensitive. Only `contains`,
* `starts with` and `ends with` read it, and only a PostgreSQL dialect can act
* on it. `matchCase` is `true` unless the user turned it off, so filters saved
* before the setting existed keep generating `LIKE`.
*/
export function isMatchCaseEnabled(filter: StructuredFilter): boolean {
return filter.matchCase !== false;
}

/**
* 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.
*
* `matchCase` swaps `LIKE` for `ILIKE` on PostgreSQL dialects only. The
* pattern and its escaping are identical in both modes, so turning the setting
* off changes case sensitivity and nothing else.
*/
export function buildLiteralLikeClause(
col: string,
value: string,
mode: LikeMatchMode,
driver: string | PluginManifest | DriverCapabilities | null | undefined,
matchCase = true,
): string {
const escaped = escapeLikePattern(value);
let pattern: string;
Expand All @@ -262,7 +290,10 @@ export function buildLiteralLikeClause(
const literal = usesBackslashStringEscapes(driver)
? pattern.replace(/\\/g, "\\\\")
: pattern;
return `${col} LIKE ${quoteLiteral(literal)} ESCAPE '${LIKE_ESCAPE}'`;
// ILIKE exists only in PostgreSQL. Everywhere else the flag is ignored, so
// the toggle can never produce SQL the connection's dialect rejects.
const operator = matchCase || !isPostgresDialect(driver) ? "LIKE" : "ILIKE";
return `${col} ${operator} ${quoteLiteral(literal)} ESCAPE '${LIKE_ESCAPE}'`;
}

/**
Expand Down
44 changes: 44 additions & 0 deletions tests/components/ui/FilterRow.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,47 @@ describe("FilterRow value picker", () => {
});

});

describe("FilterRow match-case toggle", () => {
const textRow: StructuredFilter = {
id: "f1",
column: "status",
operator: "contains",
value: "act",
};
const toggle = () => screen.queryByRole("button", { name: "toolbar.matchCase" });

it("is offered for the literal text operators on a postgres connection", () => {
renderRow(textRow, { supportsMatchCase: true });
expect(toggle()).toBeInTheDocument();
expect(toggle()).toHaveAttribute("aria-pressed", "true");
expect(toggle()).toHaveAttribute("title", "toolbar.matchCaseHint");
});

it("reflects the setting stored on the row", () => {
renderRow({ ...textRow, matchCase: false }, { supportsMatchCase: true });
expect(toggle()).toHaveAttribute("aria-pressed", "false");
});

it("turns the setting off and leaves the value alone", () => {
const { onChange } = renderRow(textRow, { supportsMatchCase: true });
act(() => {
fireEvent.click(toggle()!);
});
expect(onChange).toHaveBeenCalledWith({ ...textRow, matchCase: false });
});

it("is hidden on connections whose dialect cannot run ILIKE", () => {
renderRow(textRow, { supportsMatchCase: false });
expect(toggle()).not.toBeInTheDocument();
renderRow(textRow);
expect(toggle()).not.toBeInTheDocument();
});

it("is hidden for operators that are not a literal text match", () => {
for (const operator of ["=", "LIKE", "IN", "IS NULL"] as const) {
renderRow({ ...textRow, operator }, { supportsMatchCase: true });
expect(toggle()).not.toBeInTheDocument();
}
});
});
15 changes: 15 additions & 0 deletions tests/i18n/filterMatchCase.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import en from "../../src/i18n/locales/en.json";

const locales = import.meta.glob<{ default: typeof en }>("../../src/i18n/locales/*.json", { eager: true });

describe("filter match-case translations", () => {
it.each(Object.entries(locales))("covers the toggle and its hint in %s", (_path, locale) => {
const { toolbar } = locale.default;
expect(toolbar.matchCase.trim()).not.toBe("");
expect(toolbar.matchCaseHint.trim()).not.toBe("");
// The hint names the SQL keyword the toggle switches to, so translators
// can't drop it without the tooltip becoming misleading.
expect(toolbar.matchCaseHint).toContain("ILIKE");
});
});
Loading